Fix bug with updating parent statistics when children are hidden.
[org-mode.git] / lisp / org.el
blob2d27a9b849cd49ad3994379d8df161b4888c6942
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" . "gv %s")
1119 ("ps.gz" . "gv %s")
1120 ("eps" . "gv %s")
1121 ("eps.gz" . "gv %s")
1122 ("dvi" . "xdvi %s")
1123 ("fig" . "xfig %s"))
1124 "Default file applications on a MacOS X system.
1125 The system \"open\" is known as a default, but we use X11 applications
1126 for some files for which the OS does not have a good default.
1127 See `org-file-apps'.")
1129 (defconst org-file-apps-defaults-windowsnt
1130 (list
1131 '(remote . emacs)
1132 (cons t
1133 (list (if (featurep 'xemacs)
1134 'mswindows-shell-execute
1135 'w32-shell-execute)
1136 "open" 'file)))
1137 "Default file applications on a Windows NT system.
1138 The system \"open\" is used for most files.
1139 See `org-file-apps'.")
1141 (defcustom org-file-apps
1143 ("txt" . emacs)
1144 ("tex" . emacs)
1145 ("ltx" . emacs)
1146 ("org" . emacs)
1147 ("el" . emacs)
1148 ("bib" . emacs)
1150 "External applications for opening `file:path' items in a document.
1151 Org-mode uses system defaults for different file types, but
1152 you can use this variable to set the application for a given file
1153 extension. The entries in this list are cons cells where the car identifies
1154 files and the cdr the corresponding command. Possible values for the
1155 file identifier are
1156 \"ext\" A string identifying an extension
1157 `directory' Matches a directory
1158 `remote' Matches a remote file, accessible through tramp or efs.
1159 Remote files most likely should be visited through Emacs
1160 because external applications cannot handle such paths.
1161 t Default for all remaining files
1163 Possible values for the command are:
1164 `emacs' The file will be visited by the current Emacs process.
1165 `default' Use the default application for this file type.
1166 string A command to be executed by a shell; %s will be replaced
1167 by the path to the file.
1168 sexp A Lisp form which will be evaluated. The file path will
1169 be available in the Lisp variable `file'.
1170 For more examples, see the system specific constants
1171 `org-file-apps-defaults-macosx'
1172 `org-file-apps-defaults-windowsnt'
1173 `org-file-apps-defaults-gnu'."
1174 :group 'org-link-follow
1175 :type '(repeat
1176 (cons (choice :value ""
1177 (string :tag "Extension")
1178 (const :tag "Default for unrecognized files" t)
1179 (const :tag "Remote file" remote)
1180 (const :tag "Links to a directory" directory))
1181 (choice :value ""
1182 (const :tag "Visit with Emacs" emacs)
1183 (const :tag "Use system default" default)
1184 (string :tag "Command")
1185 (sexp :tag "Lisp form")))))
1187 (defgroup org-refile nil
1188 "Options concerning refiling entries in Org-mode."
1189 :tag "Org Remember"
1190 :group 'org)
1192 (defcustom org-directory "~/org"
1193 "Directory with org files.
1194 This directory will be used as default to prompt for org files.
1195 Used by the hooks for remember.el."
1196 :group 'org-refile
1197 :group 'org-remember
1198 :type 'directory)
1200 (defcustom org-default-notes-file "~/.notes"
1201 "Default target for storing notes.
1202 Used by the hooks for remember.el. This can be a string, or nil to mean
1203 the value of `remember-data-file'.
1204 You can set this on a per-template basis with the variable
1205 `org-remember-templates'."
1206 :group 'org-refile
1207 :group 'org-remember
1208 :type '(choice
1209 (const :tag "Default from remember-data-file" nil)
1210 file))
1212 (defcustom org-goto-interface 'outline
1213 "The default interface to be used for `org-goto'.
1214 Allowed vaues are:
1215 outline The interface shows an outline of the relevant file
1216 and the correct heading is found by moving through
1217 the outline or by searching with incremental search.
1218 outline-path-completion Headlines in the current buffer are offered via
1219 completion."
1220 :group 'org-refile
1221 :type '(choice
1222 (const :tag "Outline" outline)
1223 (const :tag "Outline-path-completion" outline-path-completion)))
1225 (defcustom org-reverse-note-order nil
1226 "Non-nil means, store new notes at the beginning of a file or entry.
1227 When nil, new notes will be filed to the end of a file or entry.
1228 This can also be a list with cons cells of regular expressions that
1229 are matched against file names, and values."
1230 :group 'org-remember
1231 :type '(choice
1232 (const :tag "Reverse always" t)
1233 (const :tag "Reverse never" nil)
1234 (repeat :tag "By file name regexp"
1235 (cons regexp boolean))))
1237 (defcustom org-refile-targets nil
1238 "Targets for refiling entries with \\[org-refile].
1239 This is list of cons cells. Each cell contains:
1240 - a specification of the files to be considered, either a list of files,
1241 or a symbol whose function or variable value will be used to retrieve
1242 a file name or a list of file names. Nil means, refile to a different
1243 heading in the current buffer.
1244 - A specification of how to find candidate refile targets. This may be
1245 any of
1246 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1247 This tag has to be present in all target headlines, inheritance will
1248 not be considered.
1249 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1250 todo keyword.
1251 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1252 headlines that are refiling targets.
1253 - a cons cell (:level . N). Any headline of level N is considered a target.
1254 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1256 When this variable is nil, all top-level headlines in the current buffer
1257 are used, equivalent to the vlaue `((nil . (:level . 1))'."
1258 :group 'org-remember
1259 :type '(repeat
1260 (cons
1261 (choice :value org-agenda-files
1262 (const :tag "All agenda files" org-agenda-files)
1263 (const :tag "Current buffer" nil)
1264 (function) (variable) (file))
1265 (choice :tag "Identify target headline by"
1266 (cons :tag "Specific tag" (const :tag) (string))
1267 (cons :tag "TODO keyword" (const :todo) (string))
1268 (cons :tag "Regular expression" (const :regexp) (regexp))
1269 (cons :tag "Level number" (const :level) (integer))
1270 (cons :tag "Max Level number" (const :maxlevel) (integer))))))
1272 (defcustom org-refile-use-outline-path nil
1273 "Non-nil means, provide refile targets as paths.
1274 So a level 3 headline will be available as level1/level2/level3.
1275 When the value is `file', also include the file name (without directory)
1276 into the path. When `full-file-path', include the full file path."
1277 :group 'org-remember
1278 :type '(choice
1279 (const :tag "Not" nil)
1280 (const :tag "Yes" t)
1281 (const :tag "Start with file name" file)
1282 (const :tag "Start with full file path" full-file-path)))
1284 (defgroup org-todo nil
1285 "Options concerning TODO items in Org-mode."
1286 :tag "Org TODO"
1287 :group 'org)
1289 (defgroup org-progress nil
1290 "Options concerning Progress logging in Org-mode."
1291 :tag "Org Progress"
1292 :group 'org-time)
1294 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1295 "List of TODO entry keyword sequences and their interpretation.
1296 \\<org-mode-map>This is a list of sequences.
1298 Each sequence starts with a symbol, either `sequence' or `type',
1299 indicating if the keywords should be interpreted as a sequence of
1300 action steps, or as different types of TODO items. The first
1301 keywords are states requiring action - these states will select a headline
1302 for inclusion into the global TODO list Org-mode produces. If one of
1303 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1304 signify that no further action is necessary. If \"|\" is not found,
1305 the last keyword is treated as the only DONE state of the sequence.
1307 The command \\[org-todo] cycles an entry through these states, and one
1308 additional state where no keyword is present. For details about this
1309 cycling, see the manual.
1311 TODO keywords and interpretation can also be set on a per-file basis with
1312 the special #+SEQ_TODO and #+TYP_TODO lines.
1314 Each keyword can optionally specify a character for fast state selection
1315 \(in combination with the variable `org-use-fast-todo-selection')
1316 and specifiers for state change logging, using the same syntax
1317 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1318 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1319 indicates to record a time stamp each time this state is selected.
1321 Each keyword may also specify if a timestamp or a note should be
1322 recorded when entering or leaving the state, by adding additional
1323 characters in the parenthesis after the keyword. This looks like this:
1324 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1325 record only the time of the state change. With X and Y being either
1326 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1327 Y when leaving the state if and only if the *target* state does not
1328 define X. You may omit any of the fast-selection key or X or /Y,
1329 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1331 For backward compatibility, this variable may also be just a list
1332 of keywords - in this case the interptetation (sequence or type) will be
1333 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1334 :group 'org-todo
1335 :group 'org-keywords
1336 :type '(choice
1337 (repeat :tag "Old syntax, just keywords"
1338 (string :tag "Keyword"))
1339 (repeat :tag "New syntax"
1340 (cons
1341 (choice
1342 :tag "Interpretation"
1343 (const :tag "Sequence (cycling hits every state)" sequence)
1344 (const :tag "Type (cycling directly to DONE)" type))
1345 (repeat
1346 (string :tag "Keyword"))))))
1348 (defvar org-todo-keywords-1 nil
1349 "All TODO and DONE keywords active in a buffer.")
1350 (make-variable-buffer-local 'org-todo-keywords-1)
1351 (defvar org-todo-keywords-for-agenda nil)
1352 (defvar org-done-keywords-for-agenda nil)
1353 (defvar org-todo-keyword-alist-for-agenda nil)
1354 (defvar org-tag-alist-for-agenda nil)
1355 (defvar org-agenda-contributing-files nil)
1356 (defvar org-not-done-keywords nil)
1357 (make-variable-buffer-local 'org-not-done-keywords)
1358 (defvar org-done-keywords nil)
1359 (make-variable-buffer-local 'org-done-keywords)
1360 (defvar org-todo-heads nil)
1361 (make-variable-buffer-local 'org-todo-heads)
1362 (defvar org-todo-sets nil)
1363 (make-variable-buffer-local 'org-todo-sets)
1364 (defvar org-todo-log-states nil)
1365 (make-variable-buffer-local 'org-todo-log-states)
1366 (defvar org-todo-kwd-alist nil)
1367 (make-variable-buffer-local 'org-todo-kwd-alist)
1368 (defvar org-todo-key-alist nil)
1369 (make-variable-buffer-local 'org-todo-key-alist)
1370 (defvar org-todo-key-trigger nil)
1371 (make-variable-buffer-local 'org-todo-key-trigger)
1373 (defcustom org-todo-interpretation 'sequence
1374 "Controls how TODO keywords are interpreted.
1375 This variable is in principle obsolete and is only used for
1376 backward compatibility, if the interpretation of todo keywords is
1377 not given already in `org-todo-keywords'. See that variable for
1378 more information."
1379 :group 'org-todo
1380 :group 'org-keywords
1381 :type '(choice (const sequence)
1382 (const type)))
1384 (defcustom org-use-fast-todo-selection 'prefix
1385 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1386 This variable describes if and under what circumstances the cycling
1387 mechanism for TODO keywords will be replaced by a single-key, direct
1388 selection scheme.
1390 When nil, fast selection is never used.
1392 When the symbol `prefix', it will be used when `org-todo' is called with
1393 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1394 in an agenda buffer.
1396 When t, fast selection is used by default. In this case, the prefix
1397 argument forces cycling instead.
1399 In all cases, the special interface is only used if access keys have actually
1400 been assigned by the user, i.e. if keywords in the configuration are followed
1401 by a letter in parenthesis, like TODO(t)."
1402 :group 'org-todo
1403 :type '(choice
1404 (const :tag "Never" nil)
1405 (const :tag "By default" t)
1406 (const :tag "Only with C-u C-c C-t" prefix)))
1408 (defcustom org-provide-todo-statistics t
1409 "Non-nil means, update todo statistics after insert and toggle.
1410 When this is set, todo statistics is updated in the parent of the current
1411 entry each time a todo state is changed."
1412 :group 'org-todo
1413 :type 'boolean)
1415 (defcustom org-after-todo-state-change-hook nil
1416 "Hook which is run after the state of a TODO item was changed.
1417 The new state (a string with a TODO keyword, or nil) is available in the
1418 Lisp variable `state'."
1419 :group 'org-todo
1420 :type 'hook)
1422 (defcustom org-log-done nil
1423 "Non-nil means, record a CLOSED timestamp when moving an entry to DONE.
1424 When equal to the list (done), also prompt for a closing note.
1425 This can also be configured on a per-file basis by adding one of
1426 the following lines anywhere in the buffer:
1428 #+STARTUP: logdone
1429 #+STARTUP: lognotedone
1430 #+STARTUP: nologdone"
1431 :group 'org-todo
1432 :group 'org-progress
1433 :type '(choice
1434 (const :tag "No logging" nil)
1435 (const :tag "Record CLOSED timestamp" time)
1436 (const :tag "Record CLOSED timestamp with closing note." note)))
1438 ;; Normalize old uses of org-log-done.
1439 (cond
1440 ((eq org-log-done t) (setq org-log-done 'time))
1441 ((and (listp org-log-done) (memq 'done org-log-done))
1442 (setq org-log-done 'note)))
1444 (defcustom org-log-note-clock-out nil
1445 "Non-nil means, record a note when clocking out of an item.
1446 This can also be configured on a per-file basis by adding one of
1447 the following lines anywhere in the buffer:
1449 #+STARTUP: lognoteclock-out
1450 #+STARTUP: nolognoteclock-out"
1451 :group 'org-todo
1452 :group 'org-progress
1453 :type 'boolean)
1455 (defcustom org-log-done-with-time t
1456 "Non-nil means, the CLOSED time stamp will contain date and time.
1457 When nil, only the date will be recorded."
1458 :group 'org-progress
1459 :type 'boolean)
1461 (defcustom org-log-note-headings
1462 '((done . "CLOSING NOTE %t")
1463 (state . "State %-12s %t")
1464 (note . "Note taken on %t")
1465 (clock-out . ""))
1466 "Headings for notes added to entries.
1467 The value is an alist, with the car being a symbol indicating the note
1468 context, and the cdr is the heading to be used. The heading may also be the
1469 empty string.
1470 %t in the heading will be replaced by a time stamp.
1471 %s will be replaced by the new TODO state, in double quotes.
1472 %u will be replaced by the user name.
1473 %U will be replaced by the full user name."
1474 :group 'org-todo
1475 :group 'org-progress
1476 :type '(list :greedy t
1477 (cons (const :tag "Heading when closing an item" done) string)
1478 (cons (const :tag
1479 "Heading when changing todo state (todo sequence only)"
1480 state) string)
1481 (cons (const :tag "Heading when just taking a note" note) string)
1482 (cons (const :tag "Heading when clocking out" clock-out) string)))
1484 (unless (assq 'note org-log-note-headings)
1485 (push '(note . "%t") org-log-note-headings))
1487 (defcustom org-log-states-order-reversed t
1488 "Non-nil means, the latest state change note will be directly after heading.
1489 When nil, the notes will be orderer according to time."
1490 :group 'org-todo
1491 :group 'org-progress
1492 :type 'boolean)
1494 (defcustom org-log-repeat 'time
1495 "Non-nil means, record moving through the DONE state when triggering repeat.
1496 An auto-repeating tasks is immediately switched back to TODO when marked
1497 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1498 the TODO keyword definition, or recording a closing note by setting
1499 `org-log-done', there will be no record of the task moving through DONE.
1500 This variable forces taking a note anyway. Possible values are:
1502 nil Don't force a record
1503 time Record a time stamp
1504 note Record a note
1506 This option can also be set with on a per-file-basis with
1508 #+STARTUP: logrepeat
1509 #+STARTUP: lognoterepeat
1510 #+STARTUP: nologrepeat
1512 You can have local logging settings for a subtree by setting the LOGGING
1513 property to one or more of these keywords."
1514 :group 'org-todo
1515 :group 'org-progress
1516 :type '(choice
1517 (const :tag "Don't force a record" nil)
1518 (const :tag "Force recording the DONE state" time)
1519 (const :tag "Force recording a note with the DONE state" note)))
1522 (defgroup org-priorities nil
1523 "Priorities in Org-mode."
1524 :tag "Org Priorities"
1525 :group 'org-todo)
1527 (defcustom org-highest-priority ?A
1528 "The highest priority of TODO items. A character like ?A, ?B etc.
1529 Must have a smaller ASCII number than `org-lowest-priority'."
1530 :group 'org-priorities
1531 :type 'character)
1533 (defcustom org-lowest-priority ?C
1534 "The lowest priority of TODO items. A character like ?A, ?B etc.
1535 Must have a larger ASCII number than `org-highest-priority'."
1536 :group 'org-priorities
1537 :type 'character)
1539 (defcustom org-default-priority ?B
1540 "The default priority of TODO items.
1541 This is the priority an item get if no explicit priority is given."
1542 :group 'org-priorities
1543 :type 'character)
1545 (defcustom org-priority-start-cycle-with-default t
1546 "Non-nil means, start with default priority when starting to cycle.
1547 When this is nil, the first step in the cycle will be (depending on the
1548 command used) one higher or lower that the default priority."
1549 :group 'org-priorities
1550 :type 'boolean)
1552 (defgroup org-time nil
1553 "Options concerning time stamps and deadlines in Org-mode."
1554 :tag "Org Time"
1555 :group 'org)
1557 (defcustom org-insert-labeled-timestamps-at-point nil
1558 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1559 When nil, these labeled time stamps are forces into the second line of an
1560 entry, just after the headline. When scheduling from the global TODO list,
1561 the time stamp will always be forced into the second line."
1562 :group 'org-time
1563 :type 'boolean)
1565 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1566 "Formats for `format-time-string' which are used for time stamps.
1567 It is not recommended to change this constant.")
1569 (defcustom org-time-stamp-rounding-minutes '(0 5)
1570 "Number of minutes to round time stamps to.
1571 These are two values, the first applies when first creating a time stamp.
1572 The second applies when changing it with the commands `S-up' and `S-down'.
1573 When changing the time stamp, this means that it will change in steps
1574 of N minutes, as given by the second value.
1576 When a setting is 0 or 1, insert the time unmodified. Useful rounding
1577 numbers should be factors of 60, so for example 5, 10, 15.
1579 When this is larger than 1, you can still force an exact time-stamp by using
1580 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
1581 and by using a prefix arg to `S-up/down' to specify the exact number
1582 of minutes to shift."
1583 :group 'org-time
1584 :get '(lambda (var) ; Make sure all entries have 5 elements
1585 (if (integerp (default-value var))
1586 (list (default-value var) 5)
1587 (default-value var)))
1588 :type '(list
1589 (integer :tag "when inserting times")
1590 (integer :tag "when modifying times")))
1592 ;; Normalize old customizations of this variable.
1593 (when (integerp org-time-stamp-rounding-minutes)
1594 (setq org-time-stamp-rounding-minutes
1595 (list org-time-stamp-rounding-minutes
1596 org-time-stamp-rounding-minutes)))
1598 (defcustom org-display-custom-times nil
1599 "Non-nil means, overlay custom formats over all time stamps.
1600 The formats are defined through the variable `org-time-stamp-custom-formats'.
1601 To turn this on on a per-file basis, insert anywhere in the file:
1602 #+STARTUP: customtime"
1603 :group 'org-time
1604 :set 'set-default
1605 :type 'sexp)
1606 (make-variable-buffer-local 'org-display-custom-times)
1608 (defcustom org-time-stamp-custom-formats
1609 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1610 "Custom formats for time stamps. See `format-time-string' for the syntax.
1611 These are overlayed over the default ISO format if the variable
1612 `org-display-custom-times' is set. Time like %H:%M should be at the
1613 end of the second format."
1614 :group 'org-time
1615 :type 'sexp)
1617 (defun org-time-stamp-format (&optional long inactive)
1618 "Get the right format for a time string."
1619 (let ((f (if long (cdr org-time-stamp-formats)
1620 (car org-time-stamp-formats))))
1621 (if inactive
1622 (concat "[" (substring f 1 -1) "]")
1623 f)))
1625 (defcustom org-time-clocksum-format "%d:%02d"
1626 "The format string used when creating CLOCKSUM lines, or when
1627 org-mode generates a time duration."
1628 :group 'org-time
1629 :type 'string)
1631 (defcustom org-deadline-warning-days 14
1632 "No. of days before expiration during which a deadline becomes active.
1633 This variable governs the display in sparse trees and in the agenda.
1634 When 0 or negative, it means use this number (the absolute value of it)
1635 even if a deadline has a different individual lead time specified."
1636 :group 'org-time
1637 :group 'org-agenda-daily/weekly
1638 :type 'number)
1640 (defcustom org-read-date-prefer-future t
1641 "Non-nil means, assume future for incomplete date input from user.
1642 This affects the following situations:
1643 1. The user gives a day, but no month.
1644 For example, if today is the 15th, and you enter \"3\", Org-mode will
1645 read this as the third of *next* month. However, if you enter \"17\",
1646 it will be considered as *this* month.
1647 2. The user gives a month but not a year.
1648 For example, if it is april and you enter \"feb 2\", this will be read
1649 as feb 2, *next* year. \"May 5\", however, will be this year.
1651 Currently this does not work for ISO week specifications.
1653 When this option is nil, the current month and year will always be used
1654 as defaults."
1655 :group 'org-time
1656 :type 'boolean)
1658 (defcustom org-read-date-display-live t
1659 "Non-nil means, display current interpretation of date prompt live.
1660 This display will be in an overlay, in the minibuffer."
1661 :group 'org-time
1662 :type 'boolean)
1664 (defcustom org-read-date-popup-calendar t
1665 "Non-nil means, pop up a calendar when prompting for a date.
1666 In the calendar, the date can be selected with mouse-1. However, the
1667 minibuffer will also be active, and you can simply enter the date as well.
1668 When nil, only the minibuffer will be available."
1669 :group 'org-time
1670 :type 'boolean)
1671 (if (fboundp 'defvaralias)
1672 (defvaralias 'org-popup-calendar-for-date-prompt
1673 'org-read-date-popup-calendar))
1675 (defcustom org-extend-today-until 0
1676 "The hour when your day really ends. Must be an integer.
1677 This has influence for the following applications:
1678 - When switching the agenda to \"today\". It it is still earlier than
1679 the time given here, the day recognized as TODAY is actually yesterday.
1680 - When a date is read from the user and it is still before the time given
1681 here, the current date and time will be assumed to be yesterday, 23:59.
1682 Also, timestamps inserted in remember templates follow this rule.
1684 IMPORTANT: This is a feature whose implementation is and likely will
1685 remain incomplete. Really, it is only here because past midnight seems to
1686 ne the favorite working time of John Wiegley :-)"
1687 :group 'org-time
1688 :type 'number)
1690 (defcustom org-edit-timestamp-down-means-later nil
1691 "Non-nil means, S-down will increase the time in a time stamp.
1692 When nil, S-up will increase."
1693 :group 'org-time
1694 :type 'boolean)
1696 (defcustom org-calendar-follow-timestamp-change t
1697 "Non-nil means, make the calendar window follow timestamp changes.
1698 When a timestamp is modified and the calendar window is visible, it will be
1699 moved to the new date."
1700 :group 'org-time
1701 :type 'boolean)
1703 (defgroup org-tags nil
1704 "Options concerning tags in Org-mode."
1705 :tag "Org Tags"
1706 :group 'org)
1708 (defcustom org-tag-alist nil
1709 "List of tags allowed in Org-mode files.
1710 When this list is nil, Org-mode will base TAG input on what is already in the
1711 buffer.
1712 The value of this variable is an alist, the car of each entry must be a
1713 keyword as a string, the cdr may be a character that is used to select
1714 that tag through the fast-tag-selection interface.
1715 See the manual for details."
1716 :group 'org-tags
1717 :type '(repeat
1718 (choice
1719 (cons (string :tag "Tag name")
1720 (character :tag "Access char"))
1721 (const :tag "Start radio group" (:startgroup))
1722 (const :tag "End radio group" (:endgroup)))))
1724 (defvar org-file-tags nil
1725 "List of tags that can be inherited by all entries in the file.
1726 The tags will be inherited if the variable `org-use-tag-inheritance'
1727 says they should be.
1728 This variable is populated from #+TAG lines.")
1730 (defcustom org-use-fast-tag-selection 'auto
1731 "Non-nil means, use fast tag selection scheme.
1732 This is a special interface to select and deselect tags with single keys.
1733 When nil, fast selection is never used.
1734 When the symbol `auto', fast selection is used if and only if selection
1735 characters for tags have been configured, either through the variable
1736 `org-tag-alist' or through a #+TAGS line in the buffer.
1737 When t, fast selection is always used and selection keys are assigned
1738 automatically if necessary."
1739 :group 'org-tags
1740 :type '(choice
1741 (const :tag "Always" t)
1742 (const :tag "Never" nil)
1743 (const :tag "When selection characters are configured" 'auto)))
1745 (defcustom org-fast-tag-selection-single-key nil
1746 "Non-nil means, fast tag selection exits after first change.
1747 When nil, you have to press RET to exit it.
1748 During fast tag selection, you can toggle this flag with `C-c'.
1749 This variable can also have the value `expert'. In this case, the window
1750 displaying the tags menu is not even shown, until you press C-c again."
1751 :group 'org-tags
1752 :type '(choice
1753 (const :tag "No" nil)
1754 (const :tag "Yes" t)
1755 (const :tag "Expert" expert)))
1757 (defvar org-fast-tag-selection-include-todo nil
1758 "Non-nil means, fast tags selection interface will also offer TODO states.
1759 This is an undocumented feature, you should not rely on it.")
1761 (defcustom org-tags-column (if (featurep 'xemacs) -79 -80)
1762 "The column to which tags should be indented in a headline.
1763 If this number is positive, it specifies the column. If it is negative,
1764 it means that the tags should be flushright to that column. For example,
1765 -80 works well for a normal 80 character screen."
1766 :group 'org-tags
1767 :type 'integer)
1769 (defcustom org-auto-align-tags t
1770 "Non-nil means, realign tags after pro/demotion of TODO state change.
1771 These operations change the length of a headline and therefore shift
1772 the tags around. With this options turned on, after each such operation
1773 the tags are again aligned to `org-tags-column'."
1774 :group 'org-tags
1775 :type 'boolean)
1777 (defcustom org-use-tag-inheritance t
1778 "Non-nil means, tags in levels apply also for sublevels.
1779 When nil, only the tags directly given in a specific line apply there.
1780 If this option is t, a match early-on in a tree can lead to a large
1781 number of matches in the subtree. If you only want to see the first
1782 match in a tree during a search, check out the variable
1783 `org-tags-match-list-sublevels'.
1785 This may also be a list of tags that should be inherited, or a regexp that
1786 matches tags that should be inherited."
1787 :group 'org-tags
1788 :type '(choice
1789 (const :tag "Not" nil)
1790 (const :tag "Always" t)
1791 (repeat :tag "Specific tags" (string :tag "Tag"))
1792 (regexp :tag "Tags matched by regexp")))
1794 (defun org-tag-inherit-p (tag)
1795 "Check if TAG is one that should be inherited."
1796 (cond
1797 ((eq org-use-tag-inheritance t) t)
1798 ((not org-use-tag-inheritance) nil)
1799 ((stringp org-use-tag-inheritance)
1800 (string-match org-use-tag-inheritance tag))
1801 ((listp org-use-tag-inheritance)
1802 (member tag org-use-tag-inheritance))
1803 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
1805 (defcustom org-tags-match-list-sublevels t
1806 "Non-nil means list also sublevels of headlines matching tag search.
1807 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1808 the sublevels of a headline matching a tag search often also match
1809 the same search. Listing all of them can create very long lists.
1810 Setting this variable to nil causes subtrees of a match to be skipped.
1811 This option is off by default, because inheritance in on. If you turn
1812 inheritance off, you very likely want to turn this option on.
1814 As a special case, if the tag search is restricted to TODO items, the
1815 value of this variable is ignored and sublevels are always checked, to
1816 make sure all corresponding TODO items find their way into the list."
1817 :group 'org-tags
1818 :type 'boolean)
1820 (defvar org-tags-history nil
1821 "History of minibuffer reads for tags.")
1822 (defvar org-last-tags-completion-table nil
1823 "The last used completion table for tags.")
1824 (defvar org-after-tags-change-hook nil
1825 "Hook that is run after the tags in a line have changed.")
1827 (defgroup org-properties nil
1828 "Options concerning properties in Org-mode."
1829 :tag "Org Properties"
1830 :group 'org)
1832 (defcustom org-property-format "%-10s %s"
1833 "How property key/value pairs should be formatted by `indent-line'.
1834 When `indent-line' hits a property definition, it will format the line
1835 according to this format, mainly to make sure that the values are
1836 lined-up with respect to each other."
1837 :group 'org-properties
1838 :type 'string)
1840 (defcustom org-use-property-inheritance nil
1841 "Non-nil means, properties apply also for sublevels.
1843 This setting is chiefly used during property searches. Turning it on can
1844 cause significant overhead when doing a search, which is why it is not
1845 on by default.
1847 When nil, only the properties directly given in the current entry count.
1848 When t, every property is inherited. The value may also be a list of
1849 properties that should have inheritance, or a regular expression matching
1850 properties that should be inherited.
1852 However, note that some special properties use inheritance under special
1853 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
1854 and the properties ending in \"_ALL\" when they are used as descriptor
1855 for valid values of a property.
1857 Note for programmers:
1858 When querying an entry with `org-entry-get', you can control if inheritance
1859 should be used. By default, `org-entry-get' looks only at the local
1860 properties. You can request inheritance by setting the inherit argument
1861 to t (to force inheritance) or to `selective' (to respect the setting
1862 in this variable)."
1863 :group 'org-properties
1864 :type '(choice
1865 (const :tag "Not" nil)
1866 (const :tag "Always" t)
1867 (repeat :tag "Specific properties" (string :tag "Property"))
1868 (regexp :tag "Properties matched by regexp")))
1870 (defun org-property-inherit-p (property)
1871 "Check if PROPERTY is one that should be inherited."
1872 (cond
1873 ((eq org-use-property-inheritance t) t)
1874 ((not org-use-property-inheritance) nil)
1875 ((stringp org-use-property-inheritance)
1876 (string-match org-use-property-inheritance property))
1877 ((listp org-use-property-inheritance)
1878 (member property org-use-property-inheritance))
1879 (t (error "Invalid setting of `org-use-property-inheritance'"))))
1881 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
1882 "The default column format, if no other format has been defined.
1883 This variable can be set on the per-file basis by inserting a line
1885 #+COLUMNS: %25ITEM ....."
1886 :group 'org-properties
1887 :type 'string)
1889 (defcustom org-columns-ellipses ".."
1890 "The ellipses to be used when a field in column view is truncated.
1891 When this is the empty string, as many characters as possible are shown,
1892 but then there will be no visual indication that the field has been truncated.
1893 When this is a string of length N, the last N characters of a truncated
1894 field are replaced by this string. If the column is narrower than the
1895 ellipses string, only part of the ellipses string will be shown."
1896 :group 'org-properties
1897 :type 'string)
1899 (defcustom org-columns-modify-value-for-display-function nil
1900 "Function that modifies values for display in column view.
1901 For example, it can be used to cut out a certain part from a time stamp.
1902 The function must take 2 argments:
1904 column-title The tite of the column (*not* the property name)
1905 value The value that should be modified.
1907 The function should return the value that should be displayed,
1908 or nil if the normal value should be used."
1909 :group 'org-properties
1910 :type 'function)
1912 (defcustom org-effort-property "Effort"
1913 "The property that is being used to keep track of effort estimates.
1914 Effort estimates given in this property need to have the format H:MM."
1915 :group 'org-properties
1916 :group 'org-progress
1917 :type '(string :tag "Property"))
1919 (defconst org-global-properties-fixed
1920 '(("VISIBILITY_ALL" . "folded children content all"))
1921 "List of property/value pairs that can be inherited by any entry.
1922 These are fixed values, for the preset properties.")
1925 (defcustom org-global-properties nil
1926 "List of property/value pairs that can be inherited by any entry.
1927 You can set buffer-local values for this by adding lines like
1929 #+PROPERTY: NAME VALUE"
1930 :group 'org-properties
1931 :type '(repeat
1932 (cons (string :tag "Property")
1933 (string :tag "Value"))))
1935 (defvar org-file-properties nil
1936 "List of property/value pairs that can be inherited by any entry.
1937 Valid for the current buffer.
1938 This variable is populated from #+PROPERTY lines.")
1939 (make-variable-buffer-local 'org-file-properties)
1941 (defgroup org-agenda nil
1942 "Options concerning agenda views in Org-mode."
1943 :tag "Org Agenda"
1944 :group 'org)
1946 (defvar org-category nil
1947 "Variable used by org files to set a category for agenda display.
1948 Such files should use a file variable to set it, for example
1950 # -*- mode: org; org-category: \"ELisp\"
1952 or contain a special line
1954 #+CATEGORY: ELisp
1956 If the file does not specify a category, then file's base name
1957 is used instead.")
1958 (make-variable-buffer-local 'org-category)
1959 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
1961 (defcustom org-agenda-files nil
1962 "The files to be used for agenda display.
1963 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
1964 \\[org-remove-file]. You can also use customize to edit the list.
1966 If an entry is a directory, all files in that directory that are matched by
1967 `org-agenda-file-regexp' will be part of the file list.
1969 If the value of the variable is not a list but a single file name, then
1970 the list of agenda files is actually stored and maintained in that file, one
1971 agenda file per line."
1972 :group 'org-agenda
1973 :type '(choice
1974 (repeat :tag "List of files and directories" file)
1975 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
1977 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
1978 "Regular expression to match files for `org-agenda-files'.
1979 If any element in the list in that variable contains a directory instead
1980 of a normal file, all files in that directory that are matched by this
1981 regular expression will be included."
1982 :group 'org-agenda
1983 :type 'regexp)
1985 (defcustom org-agenda-text-search-extra-files nil
1986 "List of extra files to be searched by text search commands.
1987 These files will be search in addition to the agenda files by the
1988 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
1989 Note that these files will only be searched for text search commands,
1990 not for the other agenda views like todo lists, tag searches or the weekly
1991 agenda. This variable is intended to list notes and possibly archive files
1992 that should also be searched by these two commands.
1993 In fact, if the first element in the list is the symbol `agenda-archives',
1994 than all archive files of all agenda files will be added to the search
1995 scope."
1996 :group 'org-agenda
1997 :type '(set :greedy t
1998 (const :tag "Agenda Archives" agenda-archives)
1999 (repeat :inline t (file))))
2001 (if (fboundp 'defvaralias)
2002 (defvaralias 'org-agenda-multi-occur-extra-files
2003 'org-agenda-text-search-extra-files))
2005 (defcustom org-agenda-skip-unavailable-files nil
2006 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2007 A nil value means to remove them, after a query, from the list."
2008 :group 'org-agenda
2009 :type 'boolean)
2011 (defcustom org-calendar-to-agenda-key [?c]
2012 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2013 The command `org-calendar-goto-agenda' will be bound to this key. The
2014 default is the character `c' because then `c' can be used to switch back and
2015 forth between agenda and calendar."
2016 :group 'org-agenda
2017 :type 'sexp)
2019 (defcustom org-calendar-agenda-action-key [?k]
2020 "The key to be installed in `calendar-mode-map' for agenda-action.
2021 The command `org-agenda-action' will be bound to this key. The
2022 default is the character `k' because we use the same key in the agenda."
2023 :group 'org-agenda
2024 :type 'sexp)
2026 (eval-after-load "calendar"
2027 '(progn
2028 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2029 'org-calendar-goto-agenda)
2030 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2031 'org-agenda-action)))
2033 (defgroup org-latex nil
2034 "Options for embedding LaTeX code into Org-mode."
2035 :tag "Org LaTeX"
2036 :group 'org)
2038 (defcustom org-format-latex-options
2039 '(:foreground default :background default :scale 1.0
2040 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2041 :matchers ("begin" "$" "$$" "\\(" "\\["))
2042 "Options for creating images from LaTeX fragments.
2043 This is a property list with the following properties:
2044 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2045 `default' means use the foreground of the default face.
2046 :background the background color, or \"Transparent\".
2047 `default' means use the background of the default face.
2048 :scale a scaling factor for the size of the images.
2049 :html-foreground, :html-background, :html-scale
2050 the same numbers for HTML export.
2051 :matchers a list indicating which matchers should be used to
2052 find LaTeX fragments. Valid members of this list are:
2053 \"begin\" find environments
2054 \"$\" find math expressions surrounded by $...$
2055 \"$$\" find math expressions surrounded by $$....$$
2056 \"\\(\" find math expressions surrounded by \\(...\\)
2057 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2058 :group 'org-latex
2059 :type 'plist)
2061 (defcustom org-format-latex-header "\\documentclass{article}
2062 \\usepackage{fullpage} % do not remove
2063 \\usepackage{amssymb}
2064 \\usepackage[usenames]{color}
2065 \\usepackage{amsmath}
2066 \\usepackage{latexsym}
2067 \\usepackage[mathscr]{eucal}
2068 \\pagestyle{empty} % do not remove"
2069 "The document header used for processing LaTeX fragments."
2070 :group 'org-latex
2071 :type 'string)
2074 (defgroup org-font-lock nil
2075 "Font-lock settings for highlighting in Org-mode."
2076 :tag "Org Font Lock"
2077 :group 'org)
2079 (defcustom org-level-color-stars-only nil
2080 "Non-nil means fontify only the stars in each headline.
2081 When nil, the entire headline is fontified.
2082 Changing it requires restart of `font-lock-mode' to become effective
2083 also in regions already fontified."
2084 :group 'org-font-lock
2085 :type 'boolean)
2087 (defcustom org-hide-leading-stars nil
2088 "Non-nil means, hide the first N-1 stars in a headline.
2089 This works by using the face `org-hide' for these stars. This
2090 face is white for a light background, and black for a dark
2091 background. You may have to customize the face `org-hide' to
2092 make this work.
2093 Changing it requires restart of `font-lock-mode' to become effective
2094 also in regions already fontified.
2095 You may also set this on a per-file basis by adding one of the following
2096 lines to the buffer:
2098 #+STARTUP: hidestars
2099 #+STARTUP: showstars"
2100 :group 'org-font-lock
2101 :type 'boolean)
2103 (defcustom org-fontify-done-headline nil
2104 "Non-nil means, change the face of a headline if it is marked DONE.
2105 Normally, only the TODO/DONE keyword indicates the state of a headline.
2106 When this is non-nil, the headline after the keyword is set to the
2107 `org-headline-done' as an additional indication."
2108 :group 'org-font-lock
2109 :type 'boolean)
2111 (defcustom org-fontify-emphasized-text t
2112 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2113 Changing this variable requires a restart of Emacs to take effect."
2114 :group 'org-font-lock
2115 :type 'boolean)
2117 (defcustom org-highlight-latex-fragments-and-specials nil
2118 "Non-nil means, fontify what is treated specially by the exporters."
2119 :group 'org-font-lock
2120 :type 'boolean)
2122 (defcustom org-hide-emphasis-markers nil
2123 "Non-nil mean font-lock should hide the emphasis marker characters."
2124 :group 'org-font-lock
2125 :type 'boolean)
2127 (defvar org-emph-re nil
2128 "Regular expression for matching emphasis.")
2129 (defvar org-verbatim-re nil
2130 "Regular expression for matching verbatim text.")
2131 (defvar org-emphasis-regexp-components) ; defined just below
2132 (defvar org-emphasis-alist) ; defined just below
2133 (defun org-set-emph-re (var val)
2134 "Set variable and compute the emphasis regular expression."
2135 (set var val)
2136 (when (and (boundp 'org-emphasis-alist)
2137 (boundp 'org-emphasis-regexp-components)
2138 org-emphasis-alist org-emphasis-regexp-components)
2139 (let* ((e org-emphasis-regexp-components)
2140 (pre (car e))
2141 (post (nth 1 e))
2142 (border (nth 2 e))
2143 (body (nth 3 e))
2144 (nl (nth 4 e))
2145 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
2146 (body1 (concat body "*?"))
2147 (markers (mapconcat 'car org-emphasis-alist ""))
2148 (vmarkers (mapconcat
2149 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2150 org-emphasis-alist "")))
2151 ;; make sure special characters appear at the right position in the class
2152 (if (string-match "\\^" markers)
2153 (setq markers (concat (replace-match "" t t markers) "^")))
2154 (if (string-match "-" markers)
2155 (setq markers (concat (replace-match "" t t markers) "-")))
2156 (if (string-match "\\^" vmarkers)
2157 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2158 (if (string-match "-" vmarkers)
2159 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2160 (if (> nl 0)
2161 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2162 (int-to-string nl) "\\}")))
2163 ;; Make the regexp
2164 (setq org-emph-re
2165 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
2166 "\\("
2167 "\\([" markers "]\\)"
2168 "\\("
2169 "[^" border "]\\|"
2170 "[^" border (if (and nil stacked) markers) "]"
2171 body1
2172 "[^" border (if (and nil stacked) markers) "]"
2173 "\\)"
2174 "\\3\\)"
2175 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
2176 (setq org-verbatim-re
2177 (concat "\\([" pre "]\\|^\\)"
2178 "\\("
2179 "\\([" vmarkers "]\\)"
2180 "\\("
2181 "[^" border "]\\|"
2182 "[^" border "]"
2183 body1
2184 "[^" border "]"
2185 "\\)"
2186 "\\3\\)"
2187 "\\([" post "]\\|$\\)")))))
2189 (defcustom org-emphasis-regexp-components
2190 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
2191 "Components used to build the regular expression for emphasis.
2192 This is a list with 6 entries. Terminology: In an emphasis string
2193 like \" *strong word* \", we call the initial space PREMATCH, the final
2194 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2195 and \"trong wor\" is the body. The different components in this variable
2196 specify what is allowed/forbidden in each part:
2198 pre Chars allowed as prematch. Beginning of line will be allowed too.
2199 post Chars allowed as postmatch. End of line will be allowed too.
2200 border The chars *forbidden* as border characters.
2201 body-regexp A regexp like \".\" to match a body character. Don't use
2202 non-shy groups here, and don't allow newline here.
2203 newline The maximum number of newlines allowed in an emphasis exp.
2205 Use customize to modify this, or restart Emacs after changing it."
2206 :group 'org-font-lock
2207 :set 'org-set-emph-re
2208 :type '(list
2209 (sexp :tag "Allowed chars in pre ")
2210 (sexp :tag "Allowed chars in post ")
2211 (sexp :tag "Forbidden chars in border ")
2212 (sexp :tag "Regexp for body ")
2213 (integer :tag "number of newlines allowed")
2214 (option (boolean :tag "Please ignore this button"))))
2216 (defcustom org-emphasis-alist
2217 `(("*" bold "<b>" "</b>")
2218 ("/" italic "<i>" "</i>")
2219 ("_" underline "<u>" "</u>")
2220 ("=" org-code "<code>" "</code>" verbatim)
2221 ("~" org-verbatim "" "" verbatim)
2222 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2223 "<del>" "</del>")
2225 "Special syntax for emphasized text.
2226 Text starting and ending with a special character will be emphasized, for
2227 example *bold*, _underlined_ and /italic/. This variable sets the marker
2228 characters, the face to be used by font-lock for highlighting in Org-mode
2229 Emacs buffers, and the HTML tags to be used for this.
2230 Use customize to modify this, or restart Emacs after changing it."
2231 :group 'org-font-lock
2232 :set 'org-set-emph-re
2233 :type '(repeat
2234 (list
2235 (string :tag "Marker character")
2236 (choice
2237 (face :tag "Font-lock-face")
2238 (plist :tag "Face property list"))
2239 (string :tag "HTML start tag")
2240 (string :tag "HTML end tag")
2241 (option (const verbatim)))))
2243 ;;; Miscellaneous options
2245 (defgroup org-completion nil
2246 "Completion in Org-mode."
2247 :tag "Org Completion"
2248 :group 'org)
2250 (defcustom org-completion-fallback-command 'hippie-expand
2251 "The expansion command called by \\[org-complete] in normal context.
2252 Normal means, no org-mode-specific context."
2253 :group 'org-completion
2254 :type 'function)
2256 ;;; Functions and variables from ther packages
2257 ;; Declared here to avoid compiler warnings
2259 ;; XEmacs only
2260 (defvar outline-mode-menu-heading)
2261 (defvar outline-mode-menu-show)
2262 (defvar outline-mode-menu-hide)
2263 (defvar zmacs-regions) ; XEmacs regions
2265 ;; Emacs only
2266 (defvar mark-active)
2268 ;; Various packages
2269 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2270 (declare-function calendar-forward-day "cal-move" (arg))
2271 (declare-function calendar-goto-date "cal-move" (date))
2272 (declare-function calendar-goto-today "cal-move" ())
2273 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2274 (defvar calc-embedded-close-formula)
2275 (defvar calc-embedded-open-formula)
2276 (declare-function cdlatex-tab "ext:cdlatex" ())
2277 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2278 (defvar font-lock-unfontify-region-function)
2279 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2280 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2281 (defvar iswitchb-temp-buflist)
2282 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2283 (declare-function org-agenda-skip "org-agenda" ())
2284 (declare-function org-format-agenda-item "org-agenda"
2285 (extra txt &optional category tags dotime noprefix remove-re))
2286 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2287 (declare-function org-agenda-change-all-lines "org-agenda"
2288 (newhead hdmarker &optional fixface))
2289 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2290 (declare-function org-agenda-maybe-redo "org-agenda" ())
2291 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2292 (beg end))
2293 (declare-function parse-time-string "parse-time" (string))
2294 (declare-function remember "remember" (&optional initial))
2295 (declare-function remember-buffer-desc "remember" ())
2296 (declare-function remember-finalize "remember" ())
2297 (defvar remember-save-after-remembering)
2298 (defvar remember-data-file)
2299 (defvar remember-register)
2300 (defvar remember-buffer)
2301 (defvar remember-handler-functions)
2302 (defvar remember-annotation-functions)
2303 (defvar texmathp-why)
2304 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2305 (declare-function table--at-cell-p "table" (position &optional object at-column))
2307 (defvar w3m-current-url)
2308 (defvar w3m-current-title)
2310 (defvar org-latex-regexps)
2312 ;;; Autoload and prepare some org modules
2314 ;; Some table stuff that needs to be defined here, because it is used
2315 ;; by the functions setting up org-mode or checking for table context.
2317 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2318 "Detects an org-type or table-type table.")
2319 (defconst org-table-line-regexp "^[ \t]*|"
2320 "Detects an org-type table line.")
2321 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2322 "Detects an org-type table line.")
2323 (defconst org-table-hline-regexp "^[ \t]*|-"
2324 "Detects an org-type table hline.")
2325 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2326 "Detects a table-type table hline.")
2327 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2328 "Searching from within a table (any type) this finds the first line
2329 outside the table.")
2331 ;; Autoload the functions in org-table.el that are needed by functions here.
2333 (eval-and-compile
2334 (org-autoload "org-table"
2335 '(org-table-align org-table-begin org-table-blank-field
2336 org-table-convert org-table-convert-region org-table-copy-down
2337 org-table-copy-region org-table-create
2338 org-table-create-or-convert-from-region
2339 org-table-create-with-table.el org-table-current-dline
2340 org-table-cut-region org-table-delete-column org-table-edit-field
2341 org-table-edit-formulas org-table-end org-table-eval-formula
2342 org-table-export org-table-field-info
2343 org-table-get-stored-formulas org-table-goto-column
2344 org-table-hline-and-move org-table-import org-table-insert-column
2345 org-table-insert-hline org-table-insert-row org-table-iterate
2346 org-table-justify-field-maybe org-table-kill-row
2347 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2348 org-table-move-column org-table-move-column-left
2349 org-table-move-column-right org-table-move-row
2350 org-table-move-row-down org-table-move-row-up
2351 org-table-next-field org-table-next-row org-table-paste-rectangle
2352 org-table-previous-field org-table-recalculate
2353 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2354 org-table-toggle-coordinate-overlays
2355 org-table-toggle-formula-debugger org-table-wrap-region
2356 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
2358 (defun org-at-table-p (&optional table-type)
2359 "Return t if the cursor is inside an org-type table.
2360 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2361 (if org-enable-table-editor
2362 (save-excursion
2363 (beginning-of-line 1)
2364 (looking-at (if table-type org-table-any-line-regexp
2365 org-table-line-regexp)))
2366 nil))
2367 (defsubst org-table-p () (org-at-table-p))
2369 (defun org-at-table.el-p ()
2370 "Return t if and only if we are at a table.el table."
2371 (and (org-at-table-p 'any)
2372 (save-excursion
2373 (goto-char (org-table-begin 'any))
2374 (looking-at org-table1-hline-regexp))))
2375 (defun org-table-recognize-table.el ()
2376 "If there is a table.el table nearby, recognize it and move into it."
2377 (if org-table-tab-recognizes-table.el
2378 (if (org-at-table.el-p)
2379 (progn
2380 (beginning-of-line 1)
2381 (if (looking-at org-table-dataline-regexp)
2383 (if (looking-at org-table1-hline-regexp)
2384 (progn
2385 (beginning-of-line 2)
2386 (if (looking-at org-table-any-border-regexp)
2387 (beginning-of-line -1)))))
2388 (if (re-search-forward "|" (org-table-end t) t)
2389 (progn
2390 (require 'table)
2391 (if (table--at-cell-p (point))
2393 (message "recognizing table.el table...")
2394 (table-recognize-table)
2395 (message "recognizing table.el table...done")))
2396 (error "This should not happen..."))
2398 nil)
2399 nil))
2401 (defun org-at-table-hline-p ()
2402 "Return t if the cursor is inside a hline in a table."
2403 (if org-enable-table-editor
2404 (save-excursion
2405 (beginning-of-line 1)
2406 (looking-at org-table-hline-regexp))
2407 nil))
2409 (defvar org-table-clean-did-remove-column nil)
2411 (defun org-table-map-tables (function)
2412 "Apply FUNCTION to the start of all tables in the buffer."
2413 (save-excursion
2414 (save-restriction
2415 (widen)
2416 (goto-char (point-min))
2417 (while (re-search-forward org-table-any-line-regexp nil t)
2418 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2419 (beginning-of-line 1)
2420 (if (looking-at org-table-line-regexp)
2421 (save-excursion (funcall function)))
2422 (re-search-forward org-table-any-border-regexp nil 1))))
2423 (message "Mapping tables: done"))
2425 ;; Declare and autoload functions from org-exp.el
2427 (declare-function org-default-export-plist "org-exp")
2428 (declare-function org-infile-export-plist "org-exp")
2429 (declare-function org-get-current-options "org-exp")
2430 (eval-and-compile
2431 (org-autoload "org-exp"
2432 '(org-export org-export-as-ascii org-export-visible
2433 org-insert-export-options-template org-export-as-html-and-open
2434 org-export-as-html-batch org-export-as-html-to-buffer
2435 org-replace-region-by-html org-export-region-as-html
2436 org-export-as-html org-export-icalendar-this-file
2437 org-export-icalendar-all-agenda-files
2438 org-table-clean-before-export
2439 org-export-icalendar-combine-agenda-files org-export-as-xoxo)))
2441 ;; Declare and autoload functions from org-agenda.el
2443 (eval-and-compile
2444 (org-autoload "org-agenda"
2445 '(org-agenda org-agenda-list org-search-view
2446 org-todo-list org-tags-view org-agenda-list-stuck-projects
2447 org-diary org-agenda-to-appt)))
2449 ;; Autoload org-remember
2451 (eval-and-compile
2452 (org-autoload "org-remember"
2453 '(org-remember-insinuate org-remember-annotation
2454 org-remember-apply-template org-remember org-remember-handler)))
2456 ;; Autoload org-clock.el
2459 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
2460 (beg end))
2461 (declare-function org-update-mode-line "org-clock" ())
2462 (defvar org-clock-start-time)
2463 (defvar org-clock-marker (make-marker)
2464 "Marker recording the last clock-in.")
2466 (eval-and-compile
2467 (org-autoload
2468 "org-clock"
2469 '(org-clock-in org-clock-out org-clock-cancel
2470 org-clock-goto org-clock-sum org-clock-display
2471 org-remove-clock-overlays org-clock-report
2472 org-clocktable-shift org-dblock-write:clocktable
2473 org-get-clocktable)))
2475 (defun org-clock-update-time-maybe ()
2476 "If this is a CLOCK line, update it and return t.
2477 Otherwise, return nil."
2478 (interactive)
2479 (save-excursion
2480 (beginning-of-line 1)
2481 (skip-chars-forward " \t")
2482 (when (looking-at org-clock-string)
2483 (let ((re (concat "[ \t]*" org-clock-string
2484 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
2485 "\\([ \t]*=>.*\\)?\\)?"))
2486 ts te h m s)
2487 (cond
2488 ((not (looking-at re))
2489 nil)
2490 ((not (match-end 2))
2491 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2492 (> org-clock-marker (point))
2493 (<= org-clock-marker (point-at-eol)))
2494 ;; The clock is running here
2495 (setq org-clock-start-time
2496 (apply 'encode-time
2497 (org-parse-time-string (match-string 1))))
2498 (org-update-mode-line)))
2500 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
2501 (end-of-line 1)
2502 (setq ts (match-string 1)
2503 te (match-string 3))
2504 (setq s (- (time-to-seconds
2505 (apply 'encode-time (org-parse-time-string te)))
2506 (time-to-seconds
2507 (apply 'encode-time (org-parse-time-string ts))))
2508 h (floor (/ s 3600))
2509 s (- s (* 3600 h))
2510 m (floor (/ s 60))
2511 s (- s (* 60 s)))
2512 (insert " => " (format "%2d:%02d" h m))
2513 t))))))
2515 (defun org-check-running-clock ()
2516 "Check if the current buffer contains the running clock.
2517 If yes, offer to stop it and to save the buffer with the changes."
2518 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2519 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
2520 (buffer-name))))
2521 (org-clock-out)
2522 (when (y-or-n-p "Save changed buffer?")
2523 (save-buffer))))
2525 (defun org-clocktable-try-shift (dir n)
2526 "Check if this line starts a clock table, if yes, shift the time block."
2527 (when (org-match-line "#\\+BEGIN: clocktable\\>")
2528 (org-clocktable-shift dir n)))
2530 ;; Autoload archiving code
2531 ;; The stuff that is needed for cycling and tags has to be defined here.
2533 (defgroup org-archive nil
2534 "Options concerning archiving in Org-mode."
2535 :tag "Org Archive"
2536 :group 'org-structure)
2538 (defcustom org-archive-location "%s_archive::"
2539 "The location where subtrees should be archived.
2541 Otherwise, the value of this variable is a string, consisting of two
2542 parts, separated by a double-colon.
2544 The first part is a file name - when omitted, archiving happens in the same
2545 file. %s will be replaced by the current file name (without directory part).
2546 Archiving to a different file is useful to keep archived entries from
2547 contributing to the Org-mode Agenda.
2549 The part after the double colon is a headline. The archived entries will be
2550 filed under that headline. When omitted, the subtrees are simply filed away
2551 at the end of the file, as top-level entries.
2553 Here are a few examples:
2554 \"%s_archive::\"
2555 If the current file is Projects.org, archive in file
2556 Projects.org_archive, as top-level trees. This is the default.
2558 \"::* Archived Tasks\"
2559 Archive in the current file, under the top-level headline
2560 \"* Archived Tasks\".
2562 \"~/org/archive.org::\"
2563 Archive in file ~/org/archive.org (absolute path), as top-level trees.
2565 \"basement::** Finished Tasks\"
2566 Archive in file ./basement (relative path), as level 3 trees
2567 below the level 2 heading \"** Finished Tasks\".
2569 You may set this option on a per-file basis by adding to the buffer a
2570 line like
2572 #+ARCHIVE: basement::** Finished Tasks
2574 You may also define it locally for a subtree by setting an ARCHIVE property
2575 in the entry. If such a property is found in an entry, or anywhere up
2576 the hierarchy, it will be used."
2577 :group 'org-archive
2578 :type 'string)
2580 (defcustom org-archive-tag "ARCHIVE"
2581 "The tag that marks a subtree as archived.
2582 An archived subtree does not open during visibility cycling, and does
2583 not contribute to the agenda listings.
2584 After changing this, font-lock must be restarted in the relevant buffers to
2585 get the proper fontification."
2586 :group 'org-archive
2587 :group 'org-keywords
2588 :type 'string)
2590 (defcustom org-agenda-skip-archived-trees t
2591 "Non-nil means, the agenda will skip any items located in archived trees.
2592 An archived tree is a tree marked with the tag ARCHIVE. The use of this
2593 variable is no longer recommended, you should leave it at the value t.
2594 Instead, use the key `v' to cycle the archives-mode in the agenda."
2595 :group 'org-archive
2596 :group 'org-agenda-skip
2597 :type 'boolean)
2599 (defcustom org-cycle-open-archived-trees nil
2600 "Non-nil means, `org-cycle' will open archived trees.
2601 An archived tree is a tree marked with the tag ARCHIVE.
2602 When nil, archived trees will stay folded. You can still open them with
2603 normal outline commands like `show-all', but not with the cycling commands."
2604 :group 'org-archive
2605 :group 'org-cycle
2606 :type 'boolean)
2608 (defcustom org-sparse-tree-open-archived-trees nil
2609 "Non-nil means sparse tree construction shows matches in archived trees.
2610 When nil, matches in these trees are highlighted, but the trees are kept in
2611 collapsed state."
2612 :group 'org-archive
2613 :group 'org-sparse-trees
2614 :type 'boolean)
2616 (defun org-cycle-hide-archived-subtrees (state)
2617 "Re-hide all archived subtrees after a visibility state change."
2618 (when (and (not org-cycle-open-archived-trees)
2619 (not (memq state '(overview folded))))
2620 (save-excursion
2621 (let* ((globalp (memq state '(contents all)))
2622 (beg (if globalp (point-min) (point)))
2623 (end (if globalp (point-max) (org-end-of-subtree t))))
2624 (org-hide-archived-subtrees beg end)
2625 (goto-char beg)
2626 (if (looking-at (concat ".*:" org-archive-tag ":"))
2627 (message "%s" (substitute-command-keys
2628 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
2630 (defun org-force-cycle-archived ()
2631 "Cycle subtree even if it is archived."
2632 (interactive)
2633 (setq this-command 'org-cycle)
2634 (let ((org-cycle-open-archived-trees t))
2635 (call-interactively 'org-cycle)))
2637 (defun org-hide-archived-subtrees (beg end)
2638 "Re-hide all archived subtrees after a visibility state change."
2639 (save-excursion
2640 (let* ((re (concat ":" org-archive-tag ":")))
2641 (goto-char beg)
2642 (while (re-search-forward re end t)
2643 (and (org-on-heading-p) (hide-subtree))
2644 (org-end-of-subtree t)))))
2646 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
2648 (eval-and-compile
2649 (org-autoload "org-archive"
2650 '(org-add-archive-files org-archive-subtree
2651 org-archive-to-archive-sibling org-toggle-archive-tag)))
2653 ;; Autoload Column View Code
2655 (declare-function org-columns-number-to-string "org-colview")
2656 (declare-function org-columns-get-format-and-top-level "org-colview")
2657 (declare-function org-columns-compute "org-colview")
2659 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
2660 '(org-columns-number-to-string org-columns-get-format-and-top-level
2661 org-columns-compute org-agenda-columns org-columns-remove-overlays
2662 org-columns org-insert-columns-dblock org-dblock-write:columnview))
2664 ;; Autoload ID code
2666 (org-autoload "org-id"
2667 '(org-id-get-create org-id-new org-id-copy org-id-get
2668 org-id-get-with-outline-path-completion
2669 org-id-get-with-outline-drilling
2670 org-id-goto org-id-find))
2672 ;;; Variables for pre-computed regular expressions, all buffer local
2674 (defvar org-drawer-regexp nil
2675 "Matches first line of a hidden block.")
2676 (make-variable-buffer-local 'org-drawer-regexp)
2677 (defvar org-todo-regexp nil
2678 "Matches any of the TODO state keywords.")
2679 (make-variable-buffer-local 'org-todo-regexp)
2680 (defvar org-not-done-regexp nil
2681 "Matches any of the TODO state keywords except the last one.")
2682 (make-variable-buffer-local 'org-not-done-regexp)
2683 (defvar org-todo-line-regexp nil
2684 "Matches a headline and puts TODO state into group 2 if present.")
2685 (make-variable-buffer-local 'org-todo-line-regexp)
2686 (defvar org-complex-heading-regexp nil
2687 "Matches a headline and puts everything into groups:
2688 group 1: the stars
2689 group 2: The todo keyword, maybe
2690 group 3: Priority cookie
2691 group 4: True headline
2692 group 5: Tags")
2693 (make-variable-buffer-local 'org-complex-heading-regexp)
2694 (defvar org-todo-line-tags-regexp nil
2695 "Matches a headline and puts TODO state into group 2 if present.
2696 Also put tags into group 4 if tags are present.")
2697 (make-variable-buffer-local 'org-todo-line-tags-regexp)
2698 (defvar org-nl-done-regexp nil
2699 "Matches newline followed by a headline with the DONE keyword.")
2700 (make-variable-buffer-local 'org-nl-done-regexp)
2701 (defvar org-looking-at-done-regexp nil
2702 "Matches the DONE keyword a point.")
2703 (make-variable-buffer-local 'org-looking-at-done-regexp)
2704 (defvar org-ds-keyword-length 12
2705 "Maximum length of the Deadline and SCHEDULED keywords.")
2706 (make-variable-buffer-local 'org-ds-keyword-length)
2707 (defvar org-deadline-regexp nil
2708 "Matches the DEADLINE keyword.")
2709 (make-variable-buffer-local 'org-deadline-regexp)
2710 (defvar org-deadline-time-regexp nil
2711 "Matches the DEADLINE keyword together with a time stamp.")
2712 (make-variable-buffer-local 'org-deadline-time-regexp)
2713 (defvar org-deadline-line-regexp nil
2714 "Matches the DEADLINE keyword and the rest of the line.")
2715 (make-variable-buffer-local 'org-deadline-line-regexp)
2716 (defvar org-scheduled-regexp nil
2717 "Matches the SCHEDULED keyword.")
2718 (make-variable-buffer-local 'org-scheduled-regexp)
2719 (defvar org-scheduled-time-regexp nil
2720 "Matches the SCHEDULED keyword together with a time stamp.")
2721 (make-variable-buffer-local 'org-scheduled-time-regexp)
2722 (defvar org-closed-time-regexp nil
2723 "Matches the CLOSED keyword together with a time stamp.")
2724 (make-variable-buffer-local 'org-closed-time-regexp)
2726 (defvar org-keyword-time-regexp nil
2727 "Matches any of the 4 keywords, together with the time stamp.")
2728 (make-variable-buffer-local 'org-keyword-time-regexp)
2729 (defvar org-keyword-time-not-clock-regexp nil
2730 "Matches any of the 3 keywords, together with the time stamp.")
2731 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
2732 (defvar org-maybe-keyword-time-regexp nil
2733 "Matches a timestamp, possibly preceeded by a keyword.")
2734 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
2735 (defvar org-planning-or-clock-line-re nil
2736 "Matches a line with planning or clock info.")
2737 (make-variable-buffer-local 'org-planning-or-clock-line-re)
2739 (defconst org-plain-time-of-day-regexp
2740 (concat
2741 "\\(\\<[012]?[0-9]"
2742 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2743 "\\(--?"
2744 "\\(\\<[012]?[0-9]"
2745 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2746 "\\)?")
2747 "Regular expression to match a plain time or time range.
2748 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2749 groups carry important information:
2750 0 the full match
2751 1 the first time, range or not
2752 8 the second time, if it is a range.")
2754 (defconst org-plain-time-extension-regexp
2755 (concat
2756 "\\(\\<[012]?[0-9]"
2757 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2758 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
2759 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
2760 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2761 groups carry important information:
2762 0 the full match
2763 7 hours of duration
2764 9 minutes of duration")
2766 (defconst org-stamp-time-of-day-regexp
2767 (concat
2768 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
2769 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
2770 "\\(--?"
2771 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
2772 "Regular expression to match a timestamp time or time range.
2773 After a match, the following groups carry important information:
2774 0 the full match
2775 1 date plus weekday, for backreferencing to make sure both times on same day
2776 2 the first time, range or not
2777 4 the second time, if it is a range.")
2779 (defconst org-startup-options
2780 '(("fold" org-startup-folded t)
2781 ("overview" org-startup-folded t)
2782 ("nofold" org-startup-folded nil)
2783 ("showall" org-startup-folded nil)
2784 ("content" org-startup-folded content)
2785 ("hidestars" org-hide-leading-stars t)
2786 ("showstars" org-hide-leading-stars nil)
2787 ("odd" org-odd-levels-only t)
2788 ("oddeven" org-odd-levels-only nil)
2789 ("align" org-startup-align-all-tables t)
2790 ("noalign" org-startup-align-all-tables nil)
2791 ("customtime" org-display-custom-times t)
2792 ("logdone" org-log-done time)
2793 ("lognotedone" org-log-done note)
2794 ("nologdone" org-log-done nil)
2795 ("lognoteclock-out" org-log-note-clock-out t)
2796 ("nolognoteclock-out" org-log-note-clock-out nil)
2797 ("logrepeat" org-log-repeat state)
2798 ("lognoterepeat" org-log-repeat note)
2799 ("nologrepeat" org-log-repeat nil)
2800 ("constcgs" constants-unit-system cgs)
2801 ("constSI" constants-unit-system SI))
2802 "Variable associated with STARTUP options for org-mode.
2803 Each element is a list of three items: The startup options as written
2804 in the #+STARTUP line, the corresponding variable, and the value to
2805 set this variable to if the option is found. An optional forth element PUSH
2806 means to push this value onto the list in the variable.")
2808 (defun org-set-regexps-and-options ()
2809 "Precompute regular expressions for current buffer."
2810 (when (org-mode-p)
2811 (org-set-local 'org-todo-kwd-alist nil)
2812 (org-set-local 'org-todo-key-alist nil)
2813 (org-set-local 'org-todo-key-trigger nil)
2814 (org-set-local 'org-todo-keywords-1 nil)
2815 (org-set-local 'org-done-keywords nil)
2816 (org-set-local 'org-todo-heads nil)
2817 (org-set-local 'org-todo-sets nil)
2818 (org-set-local 'org-todo-log-states nil)
2819 (org-set-local 'org-file-properties nil)
2820 (org-set-local 'org-file-tags nil)
2821 (let ((re (org-make-options-regexp
2822 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
2823 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
2824 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")))
2825 (splitre "[ \t]+")
2826 kwds kws0 kwsa key log value cat arch tags const links hw dws
2827 tail sep kws1 prio props ftags drawers
2828 ext-setup-or-nil setup-contents (start 0))
2829 (save-excursion
2830 (save-restriction
2831 (widen)
2832 (goto-char (point-min))
2833 (while (or (and ext-setup-or-nil
2834 (string-match re ext-setup-or-nil start)
2835 (setq start (match-end 0)))
2836 (and (setq ext-setup-or-nil nil start 0)
2837 (re-search-forward re nil t)))
2838 (setq key (upcase (match-string 1 ext-setup-or-nil))
2839 value (org-match-string-no-properties 2 ext-setup-or-nil))
2840 (cond
2841 ((equal key "CATEGORY")
2842 (if (string-match "[ \t]+$" value)
2843 (setq value (replace-match "" t t value)))
2844 (setq cat value))
2845 ((member key '("SEQ_TODO" "TODO"))
2846 (push (cons 'sequence (org-split-string value splitre)) kwds))
2847 ((equal key "TYP_TODO")
2848 (push (cons 'type (org-split-string value splitre)) kwds))
2849 ((equal key "TAGS")
2850 (setq tags (append tags (org-split-string value splitre))))
2851 ((equal key "COLUMNS")
2852 (org-set-local 'org-columns-default-format value))
2853 ((equal key "LINK")
2854 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
2855 (push (cons (match-string 1 value)
2856 (org-trim (match-string 2 value)))
2857 links)))
2858 ((equal key "PRIORITIES")
2859 (setq prio (org-split-string value " +")))
2860 ((equal key "PROPERTY")
2861 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
2862 (push (cons (match-string 1 value) (match-string 2 value))
2863 props)))
2864 ((equal key "FILETAGS")
2865 (when (string-match "\\S-" value)
2866 (setq ftags
2867 (append
2868 ftags
2869 (apply 'append
2870 (mapcar (lambda (x) (org-split-string x ":"))
2871 (org-split-string value)))))))
2872 ((equal key "DRAWERS")
2873 (setq drawers (org-split-string value splitre)))
2874 ((equal key "CONSTANTS")
2875 (setq const (append const (org-split-string value splitre))))
2876 ((equal key "STARTUP")
2877 (let ((opts (org-split-string value splitre))
2878 l var val)
2879 (while (setq l (pop opts))
2880 (when (setq l (assoc l org-startup-options))
2881 (setq var (nth 1 l) val (nth 2 l))
2882 (if (not (nth 3 l))
2883 (set (make-local-variable var) val)
2884 (if (not (listp (symbol-value var)))
2885 (set (make-local-variable var) nil))
2886 (set (make-local-variable var) (symbol-value var))
2887 (add-to-list var val))))))
2888 ((equal key "ARCHIVE")
2889 (string-match " *$" value)
2890 (setq arch (replace-match "" t t value))
2891 (remove-text-properties 0 (length arch)
2892 '(face t fontified t) arch))
2893 ((equal key "SETUPFILE")
2894 (setq setup-contents (org-file-contents
2895 (expand-file-name
2896 (org-remove-double-quotes value))
2897 'noerror))
2898 (if (not ext-setup-or-nil)
2899 (setq ext-setup-or-nil setup-contents start 0)
2900 (setq ext-setup-or-nil
2901 (concat (substring ext-setup-or-nil 0 start)
2902 "\n" setup-contents "\n"
2903 (substring ext-setup-or-nil start)))))
2904 ))))
2905 (when cat
2906 (org-set-local 'org-category (intern cat))
2907 (push (cons "CATEGORY" cat) props))
2908 (when prio
2909 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
2910 (setq prio (mapcar 'string-to-char prio))
2911 (org-set-local 'org-highest-priority (nth 0 prio))
2912 (org-set-local 'org-lowest-priority (nth 1 prio))
2913 (org-set-local 'org-default-priority (nth 2 prio)))
2914 (and props (org-set-local 'org-file-properties (nreverse props)))
2915 (and ftags (org-set-local 'org-file-tags ftags))
2916 (and drawers (org-set-local 'org-drawers drawers))
2917 (and arch (org-set-local 'org-archive-location arch))
2918 (and links (setq org-link-abbrev-alist-local (nreverse links)))
2919 ;; Process the TODO keywords
2920 (unless kwds
2921 ;; Use the global values as if they had been given locally.
2922 (setq kwds (default-value 'org-todo-keywords))
2923 (if (stringp (car kwds))
2924 (setq kwds (list (cons org-todo-interpretation
2925 (default-value 'org-todo-keywords)))))
2926 (setq kwds (reverse kwds)))
2927 (setq kwds (nreverse kwds))
2928 (let (inter kws kw)
2929 (while (setq kws (pop kwds))
2930 (setq inter (pop kws) sep (member "|" kws)
2931 kws0 (delete "|" (copy-sequence kws))
2932 kwsa nil
2933 kws1 (mapcar
2934 (lambda (x)
2935 ;; 1 2
2936 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
2937 (progn
2938 (setq kw (match-string 1 x)
2939 key (and (match-end 2) (match-string 2 x))
2940 log (org-extract-log-state-settings x))
2941 (push (cons kw (and key (string-to-char key))) kwsa)
2942 (and log (push log org-todo-log-states))
2944 (error "Invalid TODO keyword %s" x)))
2945 kws0)
2946 kwsa (if kwsa (append '((:startgroup))
2947 (nreverse kwsa)
2948 '((:endgroup))))
2949 hw (car kws1)
2950 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
2951 tail (list inter hw (car dws) (org-last dws)))
2952 (add-to-list 'org-todo-heads hw 'append)
2953 (push kws1 org-todo-sets)
2954 (setq org-done-keywords (append org-done-keywords dws nil))
2955 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
2956 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
2957 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
2958 (setq org-todo-sets (nreverse org-todo-sets)
2959 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
2960 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
2961 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
2962 ;; Process the constants
2963 (when const
2964 (let (e cst)
2965 (while (setq e (pop const))
2966 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
2967 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
2968 (setq org-table-formula-constants-local cst)))
2970 ;; Process the tags.
2971 (when tags
2972 (let (e tgs)
2973 (while (setq e (pop tags))
2974 (cond
2975 ((equal e "{") (push '(:startgroup) tgs))
2976 ((equal e "}") (push '(:endgroup) tgs))
2977 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
2978 (push (cons (match-string 1 e)
2979 (string-to-char (match-string 2 e)))
2980 tgs))
2981 (t (push (list e) tgs))))
2982 (org-set-local 'org-tag-alist nil)
2983 (while (setq e (pop tgs))
2984 (or (and (stringp (car e))
2985 (assoc (car e) org-tag-alist))
2986 (push e org-tag-alist)))))
2988 ;; Compute the regular expressions and other local variables
2989 (if (not org-done-keywords)
2990 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
2991 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
2992 (length org-scheduled-string)
2993 (length org-clock-string)
2994 (length org-closed-string)))
2995 org-drawer-regexp
2996 (concat "^[ \t]*:\\("
2997 (mapconcat 'regexp-quote org-drawers "\\|")
2998 "\\):[ \t]*$")
2999 org-not-done-keywords
3000 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3001 org-todo-regexp
3002 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3003 "\\|") "\\)\\>")
3004 org-not-done-regexp
3005 (concat "\\<\\("
3006 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3007 "\\)\\>")
3008 org-todo-line-regexp
3009 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3010 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3011 "\\)\\>\\)?[ \t]*\\(.*\\)")
3012 org-complex-heading-regexp
3013 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
3014 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3015 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3016 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3017 org-nl-done-regexp
3018 (concat "\n\\*+[ \t]+"
3019 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3020 "\\)" "\\>")
3021 org-todo-line-tags-regexp
3022 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3023 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3024 (org-re
3025 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3026 org-looking-at-done-regexp
3027 (concat "^" "\\(?:"
3028 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3029 "\\>")
3030 org-deadline-regexp (concat "\\<" org-deadline-string)
3031 org-deadline-time-regexp
3032 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3033 org-deadline-line-regexp
3034 (concat "\\<\\(" org-deadline-string "\\).*")
3035 org-scheduled-regexp
3036 (concat "\\<" org-scheduled-string)
3037 org-scheduled-time-regexp
3038 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3039 org-closed-time-regexp
3040 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3041 org-keyword-time-regexp
3042 (concat "\\<\\(" org-scheduled-string
3043 "\\|" org-deadline-string
3044 "\\|" org-closed-string
3045 "\\|" org-clock-string "\\)"
3046 " *[[<]\\([^]>]+\\)[]>]")
3047 org-keyword-time-not-clock-regexp
3048 (concat "\\<\\(" org-scheduled-string
3049 "\\|" org-deadline-string
3050 "\\|" org-closed-string
3051 "\\)"
3052 " *[[<]\\([^]>]+\\)[]>]")
3053 org-maybe-keyword-time-regexp
3054 (concat "\\(\\<\\(" org-scheduled-string
3055 "\\|" org-deadline-string
3056 "\\|" org-closed-string
3057 "\\|" org-clock-string "\\)\\)?"
3058 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3059 org-planning-or-clock-line-re
3060 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3061 "\\|" org-deadline-string
3062 "\\|" org-closed-string "\\|" org-clock-string
3063 "\\)\\>\\)")
3065 (org-compute-latex-and-specials-regexp)
3066 (org-set-font-lock-defaults))))
3068 (defun org-file-contents (file &optional noerror)
3069 "Return the contents of FILE, as a string."
3070 (if (or (not file)
3071 (not (file-readable-p file)))
3072 (if noerror
3073 (progn
3074 (message "Cannot read file %s" file)
3075 (ding) (sit-for 2)
3077 (error "Cannot read file %s" file))
3078 (with-temp-buffer
3079 (insert-file-contents file)
3080 (buffer-string))))
3082 (defun org-extract-log-state-settings (x)
3083 "Extract the log state setting from a TODO keyword string.
3084 This will extract info from a string like \"WAIT(w@/!)\"."
3085 (let (kw key log1 log2)
3086 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3087 (setq kw (match-string 1 x)
3088 key (and (match-end 2) (match-string 2 x))
3089 log1 (and (match-end 3) (match-string 3 x))
3090 log2 (and (match-end 4) (match-string 4 x)))
3091 (and (or log1 log2)
3092 (list kw
3093 (and log1 (if (equal log1 "!") 'time 'note))
3094 (and log2 (if (equal log2 "!") 'time 'note)))))))
3096 (defun org-remove-keyword-keys (list)
3097 "Remove a pair of parenthesis at the end of each string in LIST."
3098 (mapcar (lambda (x)
3099 (if (string-match "(.*)$" x)
3100 (substring x 0 (match-beginning 0))
3102 list))
3104 ;; FIXME: this could be done much better, using second characters etc.
3105 (defun org-assign-fast-keys (alist)
3106 "Assign fast keys to a keyword-key alist.
3107 Respect keys that are already there."
3108 (let (new e k c c1 c2 (char ?a))
3109 (while (setq e (pop alist))
3110 (cond
3111 ((equal e '(:startgroup)) (push e new))
3112 ((equal e '(:endgroup)) (push e new))
3114 (setq k (car e) c2 nil)
3115 (if (cdr e)
3116 (setq c (cdr e))
3117 ;; automatically assign a character.
3118 (setq c1 (string-to-char
3119 (downcase (substring
3120 k (if (= (string-to-char k) ?@) 1 0)))))
3121 (if (or (rassoc c1 new) (rassoc c1 alist))
3122 (while (or (rassoc char new) (rassoc char alist))
3123 (setq char (1+ char)))
3124 (setq c2 c1))
3125 (setq c (or c2 char)))
3126 (push (cons k c) new))))
3127 (nreverse new)))
3129 ;;; Some variables used in various places
3131 (defvar org-window-configuration nil
3132 "Used in various places to store a window configuration.")
3133 (defvar org-finish-function nil
3134 "Function to be called when `C-c C-c' is used.
3135 This is for getting out of special buffers like remember.")
3138 ;; FIXME: Occasionally check by commenting these, to make sure
3139 ;; no other functions uses these, forgetting to let-bind them.
3140 (defvar entry)
3141 (defvar state)
3142 (defvar last-state)
3143 (defvar date)
3144 (defvar description)
3146 ;; Defined somewhere in this file, but used before definition.
3147 (defvar org-html-entities)
3148 (defvar org-struct-menu)
3149 (defvar org-org-menu)
3150 (defvar org-tbl-menu)
3151 (defvar org-agenda-keymap)
3153 ;;;; Define the Org-mode
3155 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3156 (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."))
3159 ;; We use a before-change function to check if a table might need
3160 ;; an update.
3161 (defvar org-table-may-need-update t
3162 "Indicates that a table might need an update.
3163 This variable is set by `org-before-change-function'.
3164 `org-table-align' sets it back to nil.")
3165 (defun org-before-change-function (beg end)
3166 "Every change indicates that a table might need an update."
3167 (setq org-table-may-need-update t))
3168 (defvar org-mode-map)
3169 (defvar org-mode-hook nil)
3170 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3171 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3172 (defvar org-table-buffer-is-an nil)
3173 (defconst org-outline-regexp "\\*+ ")
3175 ;;;###autoload
3176 (define-derived-mode org-mode outline-mode "Org"
3177 "Outline-based notes management and organizer, alias
3178 \"Carsten's outline-mode for keeping track of everything.\"
3180 Org-mode develops organizational tasks around a NOTES file which
3181 contains information about projects as plain text. Org-mode is
3182 implemented on top of outline-mode, which is ideal to keep the content
3183 of large files well structured. It supports ToDo items, deadlines and
3184 time stamps, which magically appear in the diary listing of the Emacs
3185 calendar. Tables are easily created with a built-in table editor.
3186 Plain text URL-like links connect to websites, emails (VM), Usenet
3187 messages (Gnus), BBDB entries, and any files related to the project.
3188 For printing and sharing of notes, an Org-mode file (or a part of it)
3189 can be exported as a structured ASCII or HTML file.
3191 The following commands are available:
3193 \\{org-mode-map}"
3195 ;; Get rid of Outline menus, they are not needed
3196 ;; Need to do this here because define-derived-mode sets up
3197 ;; the keymap so late. Still, it is a waste to call this each time
3198 ;; we switch another buffer into org-mode.
3199 (if (featurep 'xemacs)
3200 (when (boundp 'outline-mode-menu-heading)
3201 ;; Assume this is Greg's port, it used easymenu
3202 (easy-menu-remove outline-mode-menu-heading)
3203 (easy-menu-remove outline-mode-menu-show)
3204 (easy-menu-remove outline-mode-menu-hide))
3205 (define-key org-mode-map [menu-bar headings] 'undefined)
3206 (define-key org-mode-map [menu-bar hide] 'undefined)
3207 (define-key org-mode-map [menu-bar show] 'undefined))
3209 (org-load-modules-maybe)
3210 (easy-menu-add org-org-menu)
3211 (easy-menu-add org-tbl-menu)
3212 (org-install-agenda-files-menu)
3213 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3214 (org-add-to-invisibility-spec '(org-cwidth))
3215 (when (featurep 'xemacs)
3216 (org-set-local 'line-move-ignore-invisible t))
3217 (org-set-local 'outline-regexp org-outline-regexp)
3218 (org-set-local 'outline-level 'org-outline-level)
3219 (when (and org-ellipsis
3220 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3221 (fboundp 'make-glyph-code))
3222 (unless org-display-table
3223 (setq org-display-table (make-display-table)))
3224 (set-display-table-slot
3225 org-display-table 4
3226 (vconcat (mapcar
3227 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3228 org-ellipsis)))
3229 (if (stringp org-ellipsis) org-ellipsis "..."))))
3230 (setq buffer-display-table org-display-table))
3231 (org-set-regexps-and-options)
3232 ;; Calc embedded
3233 (org-set-local 'calc-embedded-open-mode "# ")
3234 (modify-syntax-entry ?# "<")
3235 (modify-syntax-entry ?@ "w")
3236 (if org-startup-truncated (setq truncate-lines t))
3237 (org-set-local 'font-lock-unfontify-region-function
3238 'org-unfontify-region)
3239 ;; Activate before-change-function
3240 (org-set-local 'org-table-may-need-update t)
3241 (org-add-hook 'before-change-functions 'org-before-change-function nil
3242 'local)
3243 ;; Check for running clock before killing a buffer
3244 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3245 ;; Paragraphs and auto-filling
3246 (org-set-autofill-regexps)
3247 (setq indent-line-function 'org-indent-line-function)
3248 (org-update-radio-target-regexp)
3250 ;; Comment characters
3251 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3252 (org-set-local 'comment-padding " ")
3254 ;; Align options lines
3255 (org-set-local
3256 'align-mode-rules-list
3257 '((org-in-buffer-settings
3258 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3259 (modes . '(org-mode)))))
3261 ;; Imenu
3262 (org-set-local 'imenu-create-index-function
3263 'org-imenu-get-tree)
3265 ;; Make isearch reveal context
3266 (if (or (featurep 'xemacs)
3267 (not (boundp 'outline-isearch-open-invisible-function)))
3268 ;; Emacs 21 and XEmacs make use of the hook
3269 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3270 ;; Emacs 22 deals with this through a special variable
3271 (org-set-local 'outline-isearch-open-invisible-function
3272 (lambda (&rest ignore) (org-show-context 'isearch))))
3274 ;; If empty file that did not turn on org-mode automatically, make it to.
3275 (if (and org-insert-mode-line-in-empty-file
3276 (interactive-p)
3277 (= (point-min) (point-max)))
3278 (insert "# -*- mode: org -*-\n\n"))
3280 (unless org-inhibit-startup
3281 (when org-startup-align-all-tables
3282 (let ((bmp (buffer-modified-p)))
3283 (org-table-map-tables 'org-table-align)
3284 (set-buffer-modified-p bmp)))
3285 (org-set-startup-visibility)))
3287 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3289 (defun org-current-time ()
3290 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3291 (if (> (car org-time-stamp-rounding-minutes) 1)
3292 (let ((r (car org-time-stamp-rounding-minutes))
3293 (time (decode-time)))
3294 (apply 'encode-time
3295 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3296 (nthcdr 2 time))))
3297 (current-time)))
3299 ;;;; Font-Lock stuff, including the activators
3301 (defvar org-mouse-map (make-sparse-keymap))
3302 (org-defkey org-mouse-map
3303 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3304 (org-defkey org-mouse-map
3305 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3306 (when org-mouse-1-follows-link
3307 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3308 (when org-tab-follows-link
3309 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3310 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3311 (when org-return-follows-link
3312 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
3313 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
3315 (require 'font-lock)
3317 (defconst org-non-link-chars "]\t\n\r<>")
3318 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3319 "shell" "elisp"))
3320 (defvar org-link-types-re nil
3321 "Matches a link that has a url-like prefix like \"http:\"")
3322 (defvar org-link-re-with-space nil
3323 "Matches a link with spaces, optional angular brackets around it.")
3324 (defvar org-link-re-with-space2 nil
3325 "Matches a link with spaces, optional angular brackets around it.")
3326 (defvar org-angle-link-re nil
3327 "Matches link with angular brackets, spaces are allowed.")
3328 (defvar org-plain-link-re nil
3329 "Matches plain link, without spaces.")
3330 (defvar org-bracket-link-regexp nil
3331 "Matches a link in double brackets.")
3332 (defvar org-bracket-link-analytic-regexp nil
3333 "Regular expression used to analyze links.
3334 Here is what the match groups contain after a match:
3335 1: http:
3336 2: http
3337 3: path
3338 4: [desc]
3339 5: desc")
3340 (defvar org-any-link-re nil
3341 "Regular expression matching any link.")
3343 (defun org-make-link-regexps ()
3344 "Update the link regular expressions.
3345 This should be called after the variable `org-link-types' has changed."
3346 (setq org-link-types-re
3347 (concat
3348 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3349 org-link-re-with-space
3350 (concat
3351 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3352 "\\([^" org-non-link-chars " ]"
3353 "[^" org-non-link-chars "]*"
3354 "[^" org-non-link-chars " ]\\)>?")
3355 org-link-re-with-space2
3356 (concat
3357 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3358 "\\([^" org-non-link-chars " ]"
3359 "[^]\t\n\r]*"
3360 "[^" org-non-link-chars " ]\\)>?")
3361 org-angle-link-re
3362 (concat
3363 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3364 "\\([^" org-non-link-chars " ]"
3365 "[^" org-non-link-chars "]*"
3366 "\\)>")
3367 org-plain-link-re
3368 (concat
3369 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3370 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3371 org-bracket-link-regexp
3372 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3373 org-bracket-link-analytic-regexp
3374 (concat
3375 "\\[\\["
3376 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3377 "\\([^]]+\\)"
3378 "\\]"
3379 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3380 "\\]")
3381 org-any-link-re
3382 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3383 org-angle-link-re "\\)\\|\\("
3384 org-plain-link-re "\\)")))
3386 (org-make-link-regexps)
3388 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
3389 "Regular expression for fast time stamp matching.")
3390 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
3391 "Regular expression for fast time stamp matching.")
3392 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3393 "Regular expression matching time strings for analysis.
3394 This one does not require the space after the date, so it can be used
3395 on a string that terminates immediately after the date.")
3396 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3397 "Regular expression matching time strings for analysis.")
3398 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
3399 "Regular expression matching time stamps, with groups.")
3400 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
3401 "Regular expression matching time stamps (also [..]), with groups.")
3402 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3403 "Regular expression matching a time stamp range.")
3404 (defconst org-tr-regexp-both
3405 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3406 "Regular expression matching a time stamp range.")
3407 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3408 org-ts-regexp "\\)?")
3409 "Regular expression matching a time stamp or time stamp range.")
3410 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3411 org-ts-regexp-both "\\)?")
3412 "Regular expression matching a time stamp or time stamp range.
3413 The time stamps may be either active or inactive.")
3415 (defvar org-emph-face nil)
3417 (defun org-do-emphasis-faces (limit)
3418 "Run through the buffer and add overlays to links."
3419 (let (rtn)
3420 (while (and (not rtn) (re-search-forward org-emph-re limit t))
3421 (if (not (= (char-after (match-beginning 3))
3422 (char-after (match-beginning 4))))
3423 (progn
3424 (setq rtn t)
3425 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3426 'face
3427 (nth 1 (assoc (match-string 3)
3428 org-emphasis-alist)))
3429 (add-text-properties (match-beginning 2) (match-end 2)
3430 '(font-lock-multiline t))
3431 (when org-hide-emphasis-markers
3432 (add-text-properties (match-end 4) (match-beginning 5)
3433 '(invisible org-link))
3434 (add-text-properties (match-beginning 3) (match-end 3)
3435 '(invisible org-link)))))
3436 (backward-char 1))
3437 rtn))
3439 (defun org-emphasize (&optional char)
3440 "Insert or change an emphasis, i.e. a font like bold or italic.
3441 If there is an active region, change that region to a new emphasis.
3442 If there is no region, just insert the marker characters and position
3443 the cursor between them.
3444 CHAR should be either the marker character, or the first character of the
3445 HTML tag associated with that emphasis. If CHAR is a space, the means
3446 to remove the emphasis of the selected region.
3447 If char is not given (for example in an interactive call) it
3448 will be prompted for."
3449 (interactive)
3450 (let ((eal org-emphasis-alist) e det
3451 (erc org-emphasis-regexp-components)
3452 (prompt "")
3453 (string "") beg end move tag c s)
3454 (if (org-region-active-p)
3455 (setq beg (region-beginning) end (region-end)
3456 string (buffer-substring beg end))
3457 (setq move t))
3459 (while (setq e (pop eal))
3460 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
3461 c (aref tag 0))
3462 (push (cons c (string-to-char (car e))) det)
3463 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
3464 (substring tag 1)))))
3465 (unless char
3466 (message "%s" (concat "Emphasis marker or tag:" prompt))
3467 (setq char (read-char-exclusive)))
3468 (setq char (or (cdr (assoc char det)) char))
3469 (if (equal char ?\ )
3470 (setq s "" move nil)
3471 (unless (assoc (char-to-string char) org-emphasis-alist)
3472 (error "No such emphasis marker: \"%c\"" char))
3473 (setq s (char-to-string char)))
3474 (while (and (> (length string) 1)
3475 (equal (substring string 0 1) (substring string -1))
3476 (assoc (substring string 0 1) org-emphasis-alist))
3477 (setq string (substring string 1 -1)))
3478 (setq string (concat s string s))
3479 (if beg (delete-region beg end))
3480 (unless (or (bolp)
3481 (string-match (concat "[" (nth 0 erc) "\n]")
3482 (char-to-string (char-before (point)))))
3483 (insert " "))
3484 (unless (string-match (concat "[" (nth 1 erc) "\n]")
3485 (char-to-string (char-after (point))))
3486 (insert " ") (backward-char 1))
3487 (insert string)
3488 (and move (backward-char 1))))
3490 (defconst org-nonsticky-props
3491 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
3494 (defun org-activate-plain-links (limit)
3495 "Run through the buffer and add overlays to links."
3496 (catch 'exit
3497 (let (f)
3498 (while (re-search-forward org-plain-link-re limit t)
3499 (setq f (get-text-property (match-beginning 0) 'face))
3500 (if (or (eq f 'org-tag)
3501 (and (listp f) (memq 'org-tag f)))
3503 (add-text-properties (match-beginning 0) (match-end 0)
3504 (list 'mouse-face 'highlight
3505 'rear-nonsticky org-nonsticky-props
3506 'keymap org-mouse-map
3508 (throw 'exit t))))))
3510 (defun org-activate-code (limit)
3511 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
3512 (progn
3513 (remove-text-properties (match-beginning 0) (match-end 0)
3514 '(display t invisible t intangible t))
3515 t)))
3517 (defun org-activate-angle-links (limit)
3518 "Run through the buffer and add overlays to links."
3519 (if (re-search-forward org-angle-link-re limit t)
3520 (progn
3521 (add-text-properties (match-beginning 0) (match-end 0)
3522 (list 'mouse-face 'highlight
3523 'rear-nonsticky org-nonsticky-props
3524 'keymap org-mouse-map
3526 t)))
3528 (defun org-activate-bracket-links (limit)
3529 "Run through the buffer and add overlays to bracketed links."
3530 (if (re-search-forward org-bracket-link-regexp limit t)
3531 (let* ((help (concat "LINK: "
3532 (org-match-string-no-properties 1)))
3533 ;; FIXME: above we should remove the escapes.
3534 ;; but that requires another match, protecting match data,
3535 ;; a lot of overhead for font-lock.
3536 (ip (org-maybe-intangible
3537 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
3538 'keymap org-mouse-map 'mouse-face 'highlight
3539 'font-lock-multiline t 'help-echo help)))
3540 (vp (list 'rear-nonsticky org-nonsticky-props
3541 'keymap org-mouse-map 'mouse-face 'highlight
3542 ' font-lock-multiline t 'help-echo help)))
3543 ;; We need to remove the invisible property here. Table narrowing
3544 ;; may have made some of this invisible.
3545 (remove-text-properties (match-beginning 0) (match-end 0)
3546 '(invisible nil))
3547 (if (match-end 3)
3548 (progn
3549 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3550 (add-text-properties (match-beginning 3) (match-end 3) vp)
3551 (add-text-properties (match-end 3) (match-end 0) ip))
3552 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3553 (add-text-properties (match-beginning 1) (match-end 1) vp)
3554 (add-text-properties (match-end 1) (match-end 0) ip))
3555 t)))
3557 (defun org-activate-dates (limit)
3558 "Run through the buffer and add overlays to dates."
3559 (if (re-search-forward org-tsr-regexp-both limit t)
3560 (progn
3561 (add-text-properties (match-beginning 0) (match-end 0)
3562 (list 'mouse-face 'highlight
3563 'rear-nonsticky org-nonsticky-props
3564 'keymap org-mouse-map))
3565 (when org-display-custom-times
3566 (if (match-end 3)
3567 (org-display-custom-time (match-beginning 3) (match-end 3)))
3568 (org-display-custom-time (match-beginning 1) (match-end 1)))
3569 t)))
3571 (defvar org-target-link-regexp nil
3572 "Regular expression matching radio targets in plain text.")
3573 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3574 "Regular expression matching a link target.")
3575 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3576 "Regular expression matching a radio target.")
3577 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
3578 "Regular expression matching any target.")
3580 (defun org-activate-target-links (limit)
3581 "Run through the buffer and add overlays to target matches."
3582 (when org-target-link-regexp
3583 (let ((case-fold-search t))
3584 (if (re-search-forward org-target-link-regexp limit t)
3585 (progn
3586 (add-text-properties (match-beginning 0) (match-end 0)
3587 (list 'mouse-face 'highlight
3588 'rear-nonsticky org-nonsticky-props
3589 'keymap org-mouse-map
3590 'help-echo "Radio target link"
3591 'org-linked-text t))
3592 t)))))
3594 (defun org-update-radio-target-regexp ()
3595 "Find all radio targets in this file and update the regular expression."
3596 (interactive)
3597 (when (memq 'radio org-activate-links)
3598 (setq org-target-link-regexp
3599 (org-make-target-link-regexp (org-all-targets 'radio)))
3600 (org-restart-font-lock)))
3602 (defun org-hide-wide-columns (limit)
3603 (let (s e)
3604 (setq s (text-property-any (point) (or limit (point-max))
3605 'org-cwidth t))
3606 (when s
3607 (setq e (next-single-property-change s 'org-cwidth))
3608 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
3609 (goto-char e)
3610 t)))
3612 (defvar org-latex-and-specials-regexp nil
3613 "Regular expression for highlighting export special stuff.")
3614 (defvar org-match-substring-regexp)
3615 (defvar org-match-substring-with-braces-regexp)
3616 (defvar org-export-html-special-string-regexps)
3618 (defun org-compute-latex-and-specials-regexp ()
3619 "Compute regular expression for stuff treated specially by exporters."
3620 (if (not org-highlight-latex-fragments-and-specials)
3621 (org-set-local 'org-latex-and-specials-regexp nil)
3622 (require 'org-exp)
3623 (let*
3624 ((matchers (plist-get org-format-latex-options :matchers))
3625 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
3626 org-latex-regexps)))
3627 (options (org-combine-plists (org-default-export-plist)
3628 (org-infile-export-plist)))
3629 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
3630 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
3631 (org-export-with-TeX-macros (plist-get options :TeX-macros))
3632 (org-export-html-expand (plist-get options :expand-quoted-html))
3633 (org-export-with-special-strings (plist-get options :special-strings))
3634 (re-sub
3635 (cond
3636 ((equal org-export-with-sub-superscripts '{})
3637 (list org-match-substring-with-braces-regexp))
3638 (org-export-with-sub-superscripts
3639 (list org-match-substring-regexp))
3640 (t nil)))
3641 (re-latex
3642 (if org-export-with-LaTeX-fragments
3643 (mapcar (lambda (x) (nth 1 x)) latexs)))
3644 (re-macros
3645 (if org-export-with-TeX-macros
3646 (list (concat "\\\\"
3647 (regexp-opt
3648 (append (mapcar 'car org-html-entities)
3649 (if (boundp 'org-latex-entities)
3650 org-latex-entities nil))
3651 'words))) ; FIXME
3653 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
3654 (re-special (if org-export-with-special-strings
3655 (mapcar (lambda (x) (car x))
3656 org-export-html-special-string-regexps)))
3657 (re-rest
3658 (delq nil
3659 (list
3660 (if org-export-html-expand "@<[^>\n]+>")
3661 ))))
3662 (org-set-local
3663 'org-latex-and-specials-regexp
3664 (mapconcat 'identity (append re-latex re-sub re-macros re-special
3665 re-rest) "\\|")))))
3667 (defun org-do-latex-and-special-faces (limit)
3668 "Run through the buffer and add overlays to links."
3669 (when org-latex-and-specials-regexp
3670 (let (rtn d)
3671 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
3672 limit t))
3673 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
3674 'face))
3675 '(org-code org-verbatim underline)))
3676 (progn
3677 (setq rtn t
3678 d (cond ((member (char-after (1+ (match-beginning 0)))
3679 '(?_ ?^)) 1)
3680 (t 0)))
3681 (font-lock-prepend-text-property
3682 (+ d (match-beginning 0)) (match-end 0)
3683 'face 'org-latex-and-export-specials)
3684 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
3685 '(font-lock-multiline t)))))
3686 rtn)))
3688 (defun org-restart-font-lock ()
3689 "Restart font-lock-mode, to force refontification."
3690 (when (and (boundp 'font-lock-mode) font-lock-mode)
3691 (font-lock-mode -1)
3692 (font-lock-mode 1)))
3694 (defun org-all-targets (&optional radio)
3695 "Return a list of all targets in this file.
3696 With optional argument RADIO, only find radio targets."
3697 (let ((re (if radio org-radio-target-regexp org-target-regexp))
3698 rtn)
3699 (save-excursion
3700 (goto-char (point-min))
3701 (while (re-search-forward re nil t)
3702 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
3703 rtn)))
3705 (defun org-make-target-link-regexp (targets)
3706 "Make regular expression matching all strings in TARGETS.
3707 The regular expression finds the targets also if there is a line break
3708 between words."
3709 (and targets
3710 (concat
3711 "\\<\\("
3712 (mapconcat
3713 (lambda (x)
3714 (while (string-match " +" x)
3715 (setq x (replace-match "\\s-+" t t x)))
3717 targets
3718 "\\|")
3719 "\\)\\>")))
3721 (defun org-activate-tags (limit)
3722 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
3723 (progn
3724 (add-text-properties (match-beginning 1) (match-end 1)
3725 (list 'mouse-face 'highlight
3726 'rear-nonsticky org-nonsticky-props
3727 'keymap org-mouse-map))
3728 t)))
3730 (defun org-outline-level ()
3731 (save-excursion
3732 (looking-at outline-regexp)
3733 (if (match-beginning 1)
3734 (+ (org-get-string-indentation (match-string 1)) 1000)
3735 (1- (- (match-end 0) (match-beginning 0))))))
3737 (defvar org-font-lock-keywords nil)
3739 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
3740 "Regular expression matching a property line.")
3742 (defvar org-font-lock-hook nil
3743 "Functions to be called for special font lock stuff.")
3745 (defun org-font-lock-hook (limit)
3746 (run-hook-with-args 'org-font-lock-hook limit))
3748 (defun org-set-font-lock-defaults ()
3749 (let* ((em org-fontify-emphasized-text)
3750 (lk org-activate-links)
3751 (org-font-lock-extra-keywords
3752 (list
3753 ;; Call the hook
3754 '(org-font-lock-hook)
3755 ;; Headlines
3756 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
3757 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
3758 ;; Table lines
3759 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
3760 (1 'org-table t))
3761 ;; Table internals
3762 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
3763 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
3764 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
3765 ;; Drawers
3766 (list org-drawer-regexp '(0 'org-special-keyword t))
3767 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
3768 ;; Properties
3769 (list org-property-re
3770 '(1 'org-special-keyword t)
3771 '(3 'org-property-value t))
3772 (if org-format-transports-properties-p
3773 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
3774 ;; Links
3775 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
3776 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
3777 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
3778 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
3779 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
3780 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
3781 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
3782 '(org-hide-wide-columns (0 nil append))
3783 ;; TODO lines
3784 (list (concat "^\\*+[ \t]+" org-todo-regexp)
3785 '(1 (org-get-todo-face 1) t))
3786 ;; DONE
3787 (if org-fontify-done-headline
3788 (list (concat "^[*]+ +\\<\\("
3789 (mapconcat 'regexp-quote org-done-keywords "\\|")
3790 "\\)\\(.*\\)")
3791 '(2 'org-headline-done t))
3792 nil)
3793 ;; Priorities
3794 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
3795 ;; Special keywords
3796 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
3797 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
3798 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
3799 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
3800 ;; Emphasis
3801 (if em
3802 (if (featurep 'xemacs)
3803 '(org-do-emphasis-faces (0 nil append))
3804 '(org-do-emphasis-faces)))
3805 ;; Checkboxes
3806 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
3807 2 'bold prepend)
3808 (if org-provide-checkbox-statistics
3809 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
3810 (0 (org-get-checkbox-statistics-face) t)))
3811 ;; Description list items
3812 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
3813 2 'bold prepend)
3814 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
3815 '(1 'org-archived prepend))
3816 ;; Specials
3817 '(org-do-latex-and-special-faces)
3818 ;; Code
3819 '(org-activate-code (1 'org-code t))
3820 ;; COMMENT
3821 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
3822 "\\|" org-quote-string "\\)\\>")
3823 '(1 'org-special-keyword t))
3824 '("^#.*" (0 'font-lock-comment-face t))
3826 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
3827 ;; Now set the full font-lock-keywords
3828 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
3829 (org-set-local 'font-lock-defaults
3830 '(org-font-lock-keywords t nil nil backward-paragraph))
3831 (kill-local-variable 'font-lock-keywords) nil))
3833 (defvar org-m nil)
3834 (defvar org-l nil)
3835 (defvar org-f nil)
3836 (defun org-get-level-face (n)
3837 "Get the right face for match N in font-lock matching of healdines."
3838 (setq org-l (- (match-end 2) (match-beginning 1) 1))
3839 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
3840 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
3841 (cond
3842 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
3843 ((eq n 2) org-f)
3844 (t (if org-level-color-stars-only nil org-f))))
3846 (defun org-get-todo-face (kwd)
3847 "Get the right face for a TODO keyword KWD.
3848 If KWD is a number, get the corresponding match group."
3849 (if (numberp kwd) (setq kwd (match-string kwd)))
3850 (or (cdr (assoc kwd org-todo-keyword-faces))
3851 (and (member kwd org-done-keywords) 'org-done)
3852 'org-todo))
3854 (defun org-unfontify-region (beg end &optional maybe_loudly)
3855 "Remove fontification and activation overlays from links."
3856 (font-lock-default-unfontify-region beg end)
3857 (let* ((buffer-undo-list t)
3858 (inhibit-read-only t) (inhibit-point-motion-hooks t)
3859 (inhibit-modification-hooks t)
3860 deactivate-mark buffer-file-name buffer-file-truename)
3861 (remove-text-properties beg end
3862 '(mouse-face t keymap t org-linked-text t
3863 invisible t intangible t))))
3865 ;;;; Visibility cycling, including org-goto and indirect buffer
3867 ;;; Cycling
3869 (defvar org-cycle-global-status nil)
3870 (make-variable-buffer-local 'org-cycle-global-status)
3871 (defvar org-cycle-subtree-status nil)
3872 (make-variable-buffer-local 'org-cycle-subtree-status)
3874 ;;;###autoload
3875 (defun org-cycle (&optional arg)
3876 "Visibility cycling for Org-mode.
3878 - When this function is called with a prefix argument, rotate the entire
3879 buffer through 3 states (global cycling)
3880 1. OVERVIEW: Show only top-level headlines.
3881 2. CONTENTS: Show all headlines of all levels, but no body text.
3882 3. SHOW ALL: Show everything.
3883 When called with two C-c C-u prefixes, switch to the startup visibility,
3884 determined by the variable `org-startup-folded', and by any VISIBILITY
3885 properties in the buffer.
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 ((org-at-table-p 'any)
3932 ;; Enter the table or move to the next field in the table
3933 (or (org-table-recognize-table.el)
3934 (progn
3935 (if arg (org-table-edit-field t)
3936 (org-table-justify-field-maybe)
3937 (call-interactively 'org-table-next-field)))))
3939 ((eq arg t) ;; Global cycling
3941 (cond
3942 ((and (eq last-command this-command)
3943 (eq org-cycle-global-status 'overview))
3944 ;; We just created the overview - now do table of contents
3945 ;; This can be slow in very large buffers, so indicate action
3946 (message "CONTENTS...")
3947 (org-content)
3948 (message "CONTENTS...done")
3949 (setq org-cycle-global-status 'contents)
3950 (run-hook-with-args 'org-cycle-hook 'contents))
3952 ((and (eq last-command this-command)
3953 (eq org-cycle-global-status 'contents))
3954 ;; We just showed the table of contents - now show everything
3955 (show-all)
3956 (message "SHOW ALL")
3957 (setq org-cycle-global-status 'all)
3958 (run-hook-with-args 'org-cycle-hook 'all))
3961 ;; Default action: go to overview
3962 (org-overview)
3963 (message "OVERVIEW")
3964 (setq org-cycle-global-status 'overview)
3965 (run-hook-with-args 'org-cycle-hook 'overview))))
3967 ((and org-drawers org-drawer-regexp
3968 (save-excursion
3969 (beginning-of-line 1)
3970 (looking-at org-drawer-regexp)))
3971 ;; Toggle block visibility
3972 (org-flag-drawer
3973 (not (get-char-property (match-end 0) 'invisible))))
3975 ((integerp arg)
3976 ;; Show-subtree, ARG levels up from here.
3977 (save-excursion
3978 (org-back-to-heading)
3979 (outline-up-heading (if (< arg 0) (- arg)
3980 (- (funcall outline-level) arg)))
3981 (org-show-subtree)))
3983 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
3984 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
3985 ;; At a heading: rotate between three different views
3986 (org-back-to-heading)
3987 (let ((goal-column 0) eoh eol eos)
3988 ;; First, some boundaries
3989 (save-excursion
3990 (org-back-to-heading)
3991 (save-excursion
3992 (beginning-of-line 2)
3993 (while (and (not (eobp)) ;; this is like `next-line'
3994 (get-char-property (1- (point)) 'invisible))
3995 (beginning-of-line 2)) (setq eol (point)))
3996 (outline-end-of-heading) (setq eoh (point))
3997 (org-end-of-subtree t)
3998 (unless (eobp)
3999 (skip-chars-forward " \t\n")
4000 (beginning-of-line 1) ; in case this is an item
4002 (setq eos (1- (point))))
4003 ;; Find out what to do next and set `this-command'
4004 (cond
4005 ((= eos eoh)
4006 ;; Nothing is hidden behind this heading
4007 (message "EMPTY ENTRY")
4008 (setq org-cycle-subtree-status nil)
4009 (save-excursion
4010 (goto-char eos)
4011 (outline-next-heading)
4012 (if (org-invisible-p) (org-flag-heading nil))))
4013 ((or (>= eol eos)
4014 (not (string-match "\\S-" (buffer-substring eol eos))))
4015 ;; Entire subtree is hidden in one line: open it
4016 (org-show-entry)
4017 (show-children)
4018 (message "CHILDREN")
4019 (save-excursion
4020 (goto-char eos)
4021 (outline-next-heading)
4022 (if (org-invisible-p) (org-flag-heading nil)))
4023 (setq org-cycle-subtree-status 'children)
4024 (run-hook-with-args 'org-cycle-hook 'children))
4025 ((and (eq last-command this-command)
4026 (eq org-cycle-subtree-status 'children))
4027 ;; We just showed the children, now show everything.
4028 (org-show-subtree)
4029 (message "SUBTREE")
4030 (setq org-cycle-subtree-status 'subtree)
4031 (run-hook-with-args 'org-cycle-hook 'subtree))
4033 ;; Default action: hide the subtree.
4034 (hide-subtree)
4035 (message "FOLDED")
4036 (setq org-cycle-subtree-status 'folded)
4037 (run-hook-with-args 'org-cycle-hook 'folded)))))
4039 ;; TAB emulation and template completion
4040 (buffer-read-only (org-back-to-heading))
4042 ((org-try-structure-completion))
4044 ((org-try-cdlatex-tab))
4046 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4047 (or (not (bolp))
4048 (not (looking-at outline-regexp))))
4049 (call-interactively (global-key-binding "\t")))
4051 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4052 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4053 (or (and (eq org-cycle-emulate-tab 'white)
4054 (= (match-end 0) (point-at-eol)))
4055 (and (eq org-cycle-emulate-tab 'whitestart)
4056 (>= (match-end 0) pos))))
4058 (eq org-cycle-emulate-tab t))
4059 (call-interactively (global-key-binding "\t")))
4061 (t (save-excursion
4062 (org-back-to-heading)
4063 (org-cycle))))))
4065 ;;;###autoload
4066 (defun org-global-cycle (&optional arg)
4067 "Cycle the global visibility. For details see `org-cycle'.
4068 With C-u prefix arg, switch to startup visibility.
4069 With a numeric prefix, show all headlines up to that level."
4070 (interactive "P")
4071 (let ((org-cycle-include-plain-lists
4072 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4073 (cond
4074 ((integerp arg)
4075 (show-all)
4076 (hide-sublevels arg)
4077 (setq org-cycle-global-status 'contents))
4078 ((equal arg '(4))
4079 (org-set-startup-visibility)
4080 (message "Startup visibility, plus VISIBILITY properties."))
4082 (org-cycle '(4))))))
4084 (defun org-set-startup-visibility ()
4085 "Set the visibility required by startup options and properties."
4086 (cond
4087 ((eq org-startup-folded t)
4088 (org-cycle '(4)))
4089 ((eq org-startup-folded 'content)
4090 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4091 (org-cycle '(4)) (org-cycle '(4)))))
4092 (org-set-visibility-according-to-property 'no-cleanup)
4093 (org-cycle-hide-archived-subtrees 'all)
4094 (org-cycle-hide-drawers 'all)
4095 (org-cycle-show-empty-lines 'all))
4097 (defun org-set-visibility-according-to-property (&optional no-cleanup)
4098 "Switch subtree visibilities according to :VISIBILITY: property."
4099 (interactive)
4100 (let (state)
4101 (save-excursion
4102 (goto-char (point-min))
4103 (while (re-search-forward
4104 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
4105 nil t)
4106 (setq state (match-string 1))
4107 (save-excursion
4108 (org-back-to-heading t)
4109 (hide-subtree)
4110 (org-reveal)
4111 (cond
4112 ((equal state '("fold" "folded"))
4113 (hide-subtree))
4114 ((equal state "children")
4115 (org-show-hidden-entry)
4116 (show-children))
4117 ((equal state "content")
4118 (save-excursion
4119 (save-restriction
4120 (org-narrow-to-subtree)
4121 (org-content))))
4122 ((member state '("all" "showall"))
4123 (show-subtree)))))
4124 (unless no-cleanup
4125 (org-cycle-hide-archived-subtrees 'all)
4126 (org-cycle-hide-drawers 'all)
4127 (org-cycle-show-empty-lines 'all)))))
4129 (defun org-overview ()
4130 "Switch to overview mode, shoing only top-level headlines.
4131 Really, this shows all headlines with level equal or greater than the level
4132 of the first headline in the buffer. This is important, because if the
4133 first headline is not level one, then (hide-sublevels 1) gives confusing
4134 results."
4135 (interactive)
4136 (let ((level (save-excursion
4137 (goto-char (point-min))
4138 (if (re-search-forward (concat "^" outline-regexp) nil t)
4139 (progn
4140 (goto-char (match-beginning 0))
4141 (funcall outline-level))))))
4142 (and level (hide-sublevels level))))
4144 (defun org-content (&optional arg)
4145 "Show all headlines in the buffer, like a table of contents.
4146 With numerical argument N, show content up to level N."
4147 (interactive "P")
4148 (save-excursion
4149 ;; Visit all headings and show their offspring
4150 (and (integerp arg) (org-overview))
4151 (goto-char (point-max))
4152 (catch 'exit
4153 (while (and (progn (condition-case nil
4154 (outline-previous-visible-heading 1)
4155 (error (goto-char (point-min))))
4157 (looking-at outline-regexp))
4158 (if (integerp arg)
4159 (show-children (1- arg))
4160 (show-branches))
4161 (if (bobp) (throw 'exit nil))))))
4164 (defun org-optimize-window-after-visibility-change (state)
4165 "Adjust the window after a change in outline visibility.
4166 This function is the default value of the hook `org-cycle-hook'."
4167 (when (get-buffer-window (current-buffer))
4168 (cond
4169 ; ((eq state 'overview) (org-first-headline-recenter 1))
4170 ; ((eq state 'overview) (org-beginning-of-line))
4171 ((eq state 'content) nil)
4172 ((eq state 'all) nil)
4173 ((eq state 'folded) nil)
4174 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4175 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4177 (defun org-compact-display-after-subtree-move ()
4178 (let (beg end)
4179 (save-excursion
4180 (if (org-up-heading-safe)
4181 (progn
4182 (hide-subtree)
4183 (show-entry)
4184 (show-children)
4185 (org-cycle-show-empty-lines 'children)
4186 (org-cycle-hide-drawers 'children))
4187 (org-overview)))))
4189 (defun org-cycle-show-empty-lines (state)
4190 "Show empty lines above all visible headlines.
4191 The region to be covered depends on STATE when called through
4192 `org-cycle-hook'. Lisp program can use t for STATE to get the
4193 entire buffer covered. Note that an empty line is only shown if there
4194 are at least `org-cycle-separator-lines' empty lines before the headeline."
4195 (when (> org-cycle-separator-lines 0)
4196 (save-excursion
4197 (let* ((n org-cycle-separator-lines)
4198 (re (cond
4199 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
4200 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
4201 (t (let ((ns (number-to-string (- n 2))))
4202 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
4203 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
4204 beg end)
4205 (cond
4206 ((memq state '(overview contents t))
4207 (setq beg (point-min) end (point-max)))
4208 ((memq state '(children folded))
4209 (setq beg (point) end (progn (org-end-of-subtree t t)
4210 (beginning-of-line 2)
4211 (point)))))
4212 (when beg
4213 (goto-char beg)
4214 (while (re-search-forward re end t)
4215 (if (not (get-char-property (match-end 1) 'invisible))
4216 (outline-flag-region
4217 (match-beginning 1) (match-end 1) nil)))))))
4218 ;; Never hide empty lines at the end of the file.
4219 (save-excursion
4220 (goto-char (point-max))
4221 (outline-previous-heading)
4222 (outline-end-of-heading)
4223 (if (and (looking-at "[ \t\n]+")
4224 (= (match-end 0) (point-max)))
4225 (outline-flag-region (point) (match-end 0) nil))))
4227 (defun org-show-empty-lines-in-parent ()
4228 "Move to the parent and re-show empty lines before visible headlines."
4229 (save-excursion
4230 (let ((context (if (org-up-heading-safe) 'children 'overview)))
4231 (org-cycle-show-empty-lines context))))
4233 (defun org-cycle-hide-drawers (state)
4234 "Re-hide all drawers after a visibility state change."
4235 (when (and (org-mode-p)
4236 (not (memq state '(overview folded))))
4237 (save-excursion
4238 (let* ((globalp (memq state '(contents all)))
4239 (beg (if globalp (point-min) (point)))
4240 (end (if globalp (point-max) (org-end-of-subtree t))))
4241 (goto-char beg)
4242 (while (re-search-forward org-drawer-regexp end t)
4243 (org-flag-drawer t))))))
4245 (defun org-flag-drawer (flag)
4246 (save-excursion
4247 (beginning-of-line 1)
4248 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
4249 (let ((b (match-end 0))
4250 (outline-regexp org-outline-regexp))
4251 (if (re-search-forward
4252 "^[ \t]*:END:"
4253 (save-excursion (outline-next-heading) (point)) t)
4254 (outline-flag-region b (point-at-eol) flag)
4255 (error ":END: line missing"))))))
4257 (defun org-subtree-end-visible-p ()
4258 "Is the end of the current subtree visible?"
4259 (pos-visible-in-window-p
4260 (save-excursion (org-end-of-subtree t) (point))))
4262 (defun org-first-headline-recenter (&optional N)
4263 "Move cursor to the first headline and recenter the headline.
4264 Optional argument N means, put the headline into the Nth line of the window."
4265 (goto-char (point-min))
4266 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4267 (beginning-of-line)
4268 (recenter (prefix-numeric-value N))))
4270 ;;; Org-goto
4272 (defvar org-goto-window-configuration nil)
4273 (defvar org-goto-marker nil)
4274 (defvar org-goto-map
4275 (let ((map (make-sparse-keymap)))
4276 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
4277 (while (setq cmd (pop cmds))
4278 (substitute-key-definition cmd cmd map global-map)))
4279 (suppress-keymap map)
4280 (org-defkey map "\C-m" 'org-goto-ret)
4281 (org-defkey map [(return)] 'org-goto-ret)
4282 (org-defkey map [(left)] 'org-goto-left)
4283 (org-defkey map [(right)] 'org-goto-right)
4284 (org-defkey map [(control ?g)] 'org-goto-quit)
4285 (org-defkey map "\C-i" 'org-cycle)
4286 (org-defkey map [(tab)] 'org-cycle)
4287 (org-defkey map [(down)] 'outline-next-visible-heading)
4288 (org-defkey map [(up)] 'outline-previous-visible-heading)
4289 (if org-goto-auto-isearch
4290 (if (fboundp 'define-key-after)
4291 (define-key-after map [t] 'org-goto-local-auto-isearch)
4292 nil)
4293 (org-defkey map "q" 'org-goto-quit)
4294 (org-defkey map "n" 'outline-next-visible-heading)
4295 (org-defkey map "p" 'outline-previous-visible-heading)
4296 (org-defkey map "f" 'outline-forward-same-level)
4297 (org-defkey map "b" 'outline-backward-same-level)
4298 (org-defkey map "u" 'outline-up-heading))
4299 (org-defkey map "/" 'org-occur)
4300 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4301 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4302 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
4303 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
4304 (org-defkey map "\C-c\C-u" 'outline-up-heading)
4305 map))
4307 (defconst org-goto-help
4308 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4309 RET=jump to location [Q]uit and return to previous location
4310 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4312 (defvar org-goto-start-pos) ; dynamically scoped parameter
4314 ;; FIXME: Docstring doe not mention both interfaces
4315 (defun org-goto (&optional alternative-interface)
4316 "Look up a different location in the current file, keeping current visibility.
4318 When you want look-up or go to a different location in a document, the
4319 fastest way is often to fold the entire buffer and then dive into the tree.
4320 This method has the disadvantage, that the previous location will be folded,
4321 which may not be what you want.
4323 This command works around this by showing a copy of the current buffer
4324 in an indirect buffer, in overview mode. You can dive into the tree in
4325 that copy, use org-occur and incremental search to find a location.
4326 When pressing RET or `Q', the command returns to the original buffer in
4327 which the visibility is still unchanged. After RET is will also jump to
4328 the location selected in the indirect buffer and expose the
4329 the headline hierarchy above."
4330 (interactive "P")
4331 (let* ((org-refile-targets '((nil . (:maxlevel . 10))))
4332 (org-refile-use-outline-path t)
4333 (interface
4334 (if (not alternative-interface)
4335 org-goto-interface
4336 (if (eq org-goto-interface 'outline)
4337 'outline-path-completion
4338 'outline)))
4339 (org-goto-start-pos (point))
4340 (selected-point
4341 (if (eq interface 'outline)
4342 (car (org-get-location (current-buffer) org-goto-help))
4343 (nth 3 (org-refile-get-location "Goto: ")))))
4344 (if selected-point
4345 (progn
4346 (org-mark-ring-push org-goto-start-pos)
4347 (goto-char selected-point)
4348 (if (or (org-invisible-p) (org-invisible-p2))
4349 (org-show-context 'org-goto)))
4350 (message "Quit"))))
4352 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
4353 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
4354 (defvar org-goto-local-auto-isearch-map) ; defined below
4356 (defun org-get-location (buf help)
4357 "Let the user select a location in the Org-mode buffer BUF.
4358 This function uses a recursive edit. It returns the selected position
4359 or nil."
4360 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
4361 (isearch-hide-immediately nil)
4362 (isearch-search-fun-function
4363 (lambda () 'org-goto-local-search-headings))
4364 (org-goto-selected-point org-goto-exit-command))
4365 (save-excursion
4366 (save-window-excursion
4367 (delete-other-windows)
4368 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
4369 (switch-to-buffer
4370 (condition-case nil
4371 (make-indirect-buffer (current-buffer) "*org-goto*")
4372 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
4373 (with-output-to-temp-buffer "*Help*"
4374 (princ help))
4375 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
4376 (setq buffer-read-only nil)
4377 (let ((org-startup-truncated t)
4378 (org-startup-folded nil)
4379 (org-startup-align-all-tables nil))
4380 (org-mode)
4381 (org-overview))
4382 (setq buffer-read-only t)
4383 (if (and (boundp 'org-goto-start-pos)
4384 (integer-or-marker-p org-goto-start-pos))
4385 (let ((org-show-hierarchy-above t)
4386 (org-show-siblings t)
4387 (org-show-following-heading t))
4388 (goto-char org-goto-start-pos)
4389 (and (org-invisible-p) (org-show-context)))
4390 (goto-char (point-min)))
4391 (org-beginning-of-line)
4392 (message "Select location and press RET")
4393 (use-local-map org-goto-map)
4394 (recursive-edit)
4396 (kill-buffer "*org-goto*")
4397 (cons org-goto-selected-point org-goto-exit-command)))
4399 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
4400 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
4401 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
4402 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
4404 (defun org-goto-local-search-headings (string bound noerror)
4405 "Search and make sure that any matches are in headlines."
4406 (catch 'return
4407 (while (if isearch-forward
4408 (search-forward string bound noerror)
4409 (search-backward string bound noerror))
4410 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
4411 (and (member :headline context)
4412 (not (member :tags context))))
4413 (throw 'return (point))))))
4415 (defun org-goto-local-auto-isearch ()
4416 "Start isearch."
4417 (interactive)
4418 (goto-char (point-min))
4419 (let ((keys (this-command-keys)))
4420 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
4421 (isearch-mode t)
4422 (isearch-process-search-char (string-to-char keys)))))
4424 (defun org-goto-ret (&optional arg)
4425 "Finish `org-goto' by going to the new location."
4426 (interactive "P")
4427 (setq org-goto-selected-point (point)
4428 org-goto-exit-command 'return)
4429 (throw 'exit nil))
4431 (defun org-goto-left ()
4432 "Finish `org-goto' by going to the new location."
4433 (interactive)
4434 (if (org-on-heading-p)
4435 (progn
4436 (beginning-of-line 1)
4437 (setq org-goto-selected-point (point)
4438 org-goto-exit-command 'left)
4439 (throw 'exit nil))
4440 (error "Not on a heading")))
4442 (defun org-goto-right ()
4443 "Finish `org-goto' by going to the new location."
4444 (interactive)
4445 (if (org-on-heading-p)
4446 (progn
4447 (setq org-goto-selected-point (point)
4448 org-goto-exit-command 'right)
4449 (throw 'exit nil))
4450 (error "Not on a heading")))
4452 (defun org-goto-quit ()
4453 "Finish `org-goto' without cursor motion."
4454 (interactive)
4455 (setq org-goto-selected-point nil)
4456 (setq org-goto-exit-command 'quit)
4457 (throw 'exit nil))
4459 ;;; Indirect buffer display of subtrees
4461 (defvar org-indirect-dedicated-frame nil
4462 "This is the frame being used for indirect tree display.")
4463 (defvar org-last-indirect-buffer nil)
4465 (defun org-tree-to-indirect-buffer (&optional arg)
4466 "Create indirect buffer and narrow it to current subtree.
4467 With numerical prefix ARG, go up to this level and then take that tree.
4468 If ARG is negative, go up that many levels.
4469 If `org-indirect-buffer-display' is not `new-frame', the command removes the
4470 indirect buffer previously made with this command, to avoid proliferation of
4471 indirect buffers. However, when you call the command with a `C-u' prefix, or
4472 when `org-indirect-buffer-display' is `new-frame', the last buffer
4473 is kept so that you can work with several indirect buffers at the same time.
4474 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
4475 requests that a new frame be made for the new buffer, so that the dedicated
4476 frame is not changed."
4477 (interactive "P")
4478 (let ((cbuf (current-buffer))
4479 (cwin (selected-window))
4480 (pos (point))
4481 beg end level heading ibuf)
4482 (save-excursion
4483 (org-back-to-heading t)
4484 (when (numberp arg)
4485 (setq level (org-outline-level))
4486 (if (< arg 0) (setq arg (+ level arg)))
4487 (while (> (setq level (org-outline-level)) arg)
4488 (outline-up-heading 1 t)))
4489 (setq beg (point)
4490 heading (org-get-heading))
4491 (org-end-of-subtree t) (setq end (point)))
4492 (if (and (buffer-live-p org-last-indirect-buffer)
4493 (not (eq org-indirect-buffer-display 'new-frame))
4494 (not arg))
4495 (kill-buffer org-last-indirect-buffer))
4496 (setq ibuf (org-get-indirect-buffer cbuf)
4497 org-last-indirect-buffer ibuf)
4498 (cond
4499 ((or (eq org-indirect-buffer-display 'new-frame)
4500 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
4501 (select-frame (make-frame))
4502 (delete-other-windows)
4503 (switch-to-buffer ibuf)
4504 (org-set-frame-title heading))
4505 ((eq org-indirect-buffer-display 'dedicated-frame)
4506 (raise-frame
4507 (select-frame (or (and org-indirect-dedicated-frame
4508 (frame-live-p org-indirect-dedicated-frame)
4509 org-indirect-dedicated-frame)
4510 (setq org-indirect-dedicated-frame (make-frame)))))
4511 (delete-other-windows)
4512 (switch-to-buffer ibuf)
4513 (org-set-frame-title (concat "Indirect: " heading)))
4514 ((eq org-indirect-buffer-display 'current-window)
4515 (switch-to-buffer ibuf))
4516 ((eq org-indirect-buffer-display 'other-window)
4517 (pop-to-buffer ibuf))
4518 (t (error "Invalid value.")))
4519 (if (featurep 'xemacs)
4520 (save-excursion (org-mode) (turn-on-font-lock)))
4521 (narrow-to-region beg end)
4522 (show-all)
4523 (goto-char pos)
4524 (and (window-live-p cwin) (select-window cwin))))
4526 (defun org-get-indirect-buffer (&optional buffer)
4527 (setq buffer (or buffer (current-buffer)))
4528 (let ((n 1) (base (buffer-name buffer)) bname)
4529 (while (buffer-live-p
4530 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
4531 (setq n (1+ n)))
4532 (condition-case nil
4533 (make-indirect-buffer buffer bname 'clone)
4534 (error (make-indirect-buffer buffer bname)))))
4536 (defun org-set-frame-title (title)
4537 "Set the title of the current frame to the string TITLE."
4538 ;; FIXME: how to name a single frame in XEmacs???
4539 (unless (featurep 'xemacs)
4540 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
4542 ;;;; Structure editing
4544 ;;; Inserting headlines
4546 (defun org-insert-heading (&optional force-heading)
4547 "Insert a new heading or item with same depth at point.
4548 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
4549 If point is at the beginning of a headline, insert a sibling before the
4550 current headline. If point is not at the beginning, do not split the line,
4551 but create the new hedline after the current line."
4552 (interactive "P")
4553 (if (= (buffer-size) 0)
4554 (insert "\n* ")
4555 (when (or force-heading (not (org-insert-item)))
4556 (let* ((head (save-excursion
4557 (condition-case nil
4558 (progn
4559 (org-back-to-heading)
4560 (match-string 0))
4561 (error "*"))))
4562 (blank (cdr (assq 'heading org-blank-before-new-entry)))
4563 pos)
4564 (cond
4565 ((and (org-on-heading-p) (bolp)
4566 (or (bobp)
4567 (save-excursion (backward-char 1) (not (org-invisible-p)))))
4568 ;; insert before the current line
4569 (open-line (if blank 2 1)))
4570 ((and (bolp)
4571 (or (bobp)
4572 (save-excursion
4573 (backward-char 1) (not (org-invisible-p)))))
4574 ;; insert right here
4575 nil)
4577 ;; in the middle of the line
4578 (org-show-entry)
4579 (let ((split
4580 (org-get-alist-option org-M-RET-may-split-line 'headline))
4581 tags pos)
4582 (cond
4583 (org-insert-heading-respect-content
4584 (org-end-of-subtree nil t)
4585 (open-line 1))
4586 ((org-on-heading-p)
4587 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4588 (setq tags (and (match-end 2) (match-string 2)))
4589 (and (match-end 1)
4590 (delete-region (match-beginning 1) (match-end 1)))
4591 (setq pos (point-at-bol))
4592 (or split (end-of-line 1))
4593 (delete-horizontal-space)
4594 (newline (if blank 2 1))
4595 (when tags
4596 (save-excursion
4597 (goto-char pos)
4598 (end-of-line 1)
4599 (insert " " tags)
4600 (org-set-tags nil 'align))))
4602 (or split (end-of-line 1))
4603 (newline (if blank 2 1)))))))
4604 (insert head) (just-one-space)
4605 (setq pos (point))
4606 (end-of-line 1)
4607 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
4608 (run-hooks 'org-insert-heading-hook)))))
4610 (defun org-get-heading (&optional no-tags)
4611 "Return the heading of the current entry, without the stars."
4612 (save-excursion
4613 (org-back-to-heading t)
4614 (if (looking-at
4615 (if no-tags
4616 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
4617 "\\*+[ \t]+\\([^\r\n]*\\)"))
4618 (match-string 1) "")))
4620 (defun org-insert-heading-after-current ()
4621 "Insert a new heading with same level as current, after current subtree."
4622 (interactive)
4623 (org-back-to-heading)
4624 (org-insert-heading)
4625 (org-move-subtree-down)
4626 (end-of-line 1))
4628 (defun org-insert-heading-respect-content ()
4629 (interactive)
4630 (let ((org-insert-heading-respect-content t))
4631 (call-interactively 'org-insert-heading)))
4633 (defun org-insert-todo-heading-respect-content ()
4634 (interactive)
4635 (let ((org-insert-heading-respect-content t))
4636 (call-interactively 'org-insert-todo-todo-heading)))
4638 (defun org-insert-todo-heading (arg)
4639 "Insert a new heading with the same level and TODO state as current heading.
4640 If the heading has no TODO state, or if the state is DONE, use the first
4641 state (TODO by default). Also with prefix arg, force first state."
4642 (interactive "P")
4643 (when (not (org-insert-item 'checkbox))
4644 (org-insert-heading)
4645 (save-excursion
4646 (org-back-to-heading)
4647 (outline-previous-heading)
4648 (looking-at org-todo-line-regexp))
4649 (if (or arg
4650 (not (match-beginning 2))
4651 (member (match-string 2) org-done-keywords))
4652 (insert (car org-todo-keywords-1) " ")
4653 (insert (match-string 2) " "))
4654 (when org-provide-todo-statistics
4655 (org-update-parent-todo-statistics))))
4657 (defun org-insert-subheading (arg)
4658 "Insert a new subheading and demote it.
4659 Works for outline headings and for plain lists alike."
4660 (interactive "P")
4661 (org-insert-heading arg)
4662 (cond
4663 ((org-on-heading-p) (org-do-demote))
4664 ((org-at-item-p) (org-indent-item 1))))
4666 (defun org-insert-todo-subheading (arg)
4667 "Insert a new subheading with TODO keyword or checkbox and demote it.
4668 Works for outline headings and for plain lists alike."
4669 (interactive "P")
4670 (org-insert-todo-heading arg)
4671 (cond
4672 ((org-on-heading-p) (org-do-demote))
4673 ((org-at-item-p) (org-indent-item 1))))
4675 ;;; Promotion and Demotion
4677 (defun org-promote-subtree ()
4678 "Promote the entire subtree.
4679 See also `org-promote'."
4680 (interactive)
4681 (save-excursion
4682 (org-map-tree 'org-promote))
4683 (org-fix-position-after-promote))
4685 (defun org-demote-subtree ()
4686 "Demote the entire subtree. See `org-demote'.
4687 See also `org-promote'."
4688 (interactive)
4689 (save-excursion
4690 (org-map-tree 'org-demote))
4691 (org-fix-position-after-promote))
4694 (defun org-do-promote ()
4695 "Promote the current heading higher up the tree.
4696 If the region is active in `transient-mark-mode', promote all headings
4697 in the region."
4698 (interactive)
4699 (save-excursion
4700 (if (org-region-active-p)
4701 (org-map-region 'org-promote (region-beginning) (region-end))
4702 (org-promote)))
4703 (org-fix-position-after-promote))
4705 (defun org-do-demote ()
4706 "Demote the current heading lower down the tree.
4707 If the region is active in `transient-mark-mode', demote all headings
4708 in the region."
4709 (interactive)
4710 (save-excursion
4711 (if (org-region-active-p)
4712 (org-map-region 'org-demote (region-beginning) (region-end))
4713 (org-demote)))
4714 (org-fix-position-after-promote))
4716 (defun org-fix-position-after-promote ()
4717 "Make sure that after pro/demotion cursor position is right."
4718 (let ((pos (point)))
4719 (when (save-excursion
4720 (beginning-of-line 1)
4721 (looking-at org-todo-line-regexp)
4722 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
4723 (cond ((eobp) (insert " "))
4724 ((eolp) (insert " "))
4725 ((equal (char-after) ?\ ) (forward-char 1))))))
4727 (defun org-reduced-level (l)
4728 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
4730 (defun org-get-valid-level (level &optional change)
4731 "Rectify a level change under the influence of `org-odd-levels-only'
4732 LEVEL is a current level, CHANGE is by how much the level should be
4733 modified. Even if CHANGE is nil, LEVEL may be returned modified because
4734 even level numbers will become the next higher odd number."
4735 (if org-odd-levels-only
4736 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
4737 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
4738 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
4739 (max 1 (+ level change))))
4741 (if (boundp 'define-obsolete-function-alias)
4742 (if (or (featurep 'xemacs) (< emacs-major-version 23))
4743 (define-obsolete-function-alias 'org-get-legal-level
4744 'org-get-valid-level)
4745 (define-obsolete-function-alias 'org-get-legal-level
4746 'org-get-valid-level "23.1")))
4748 (defun org-promote ()
4749 "Promote the current heading higher up the tree.
4750 If the region is active in `transient-mark-mode', promote all headings
4751 in the region."
4752 (org-back-to-heading t)
4753 (let* ((level (save-match-data (funcall outline-level)))
4754 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
4755 (diff (abs (- level (length up-head) -1))))
4756 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
4757 (replace-match up-head nil t)
4758 ;; Fixup tag positioning
4759 (and org-auto-align-tags (org-set-tags nil t))
4760 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
4762 (defun org-demote ()
4763 "Demote the current heading lower down the tree.
4764 If the region is active in `transient-mark-mode', demote all headings
4765 in the region."
4766 (org-back-to-heading t)
4767 (let* ((level (save-match-data (funcall outline-level)))
4768 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
4769 (diff (abs (- level (length down-head) -1))))
4770 (replace-match down-head nil t)
4771 ;; Fixup tag positioning
4772 (and org-auto-align-tags (org-set-tags nil t))
4773 (if org-adapt-indentation (org-fixup-indentation diff))))
4775 (defun org-map-tree (fun)
4776 "Call FUN for every heading underneath the current one."
4777 (org-back-to-heading)
4778 (let ((level (funcall outline-level)))
4779 (save-excursion
4780 (funcall fun)
4781 (while (and (progn
4782 (outline-next-heading)
4783 (> (funcall outline-level) level))
4784 (not (eobp)))
4785 (funcall fun)))))
4787 (defun org-map-region (fun beg end)
4788 "Call FUN for every heading between BEG and END."
4789 (let ((org-ignore-region t))
4790 (save-excursion
4791 (setq end (copy-marker end))
4792 (goto-char beg)
4793 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
4794 (< (point) end))
4795 (funcall fun))
4796 (while (and (progn
4797 (outline-next-heading)
4798 (< (point) end))
4799 (not (eobp)))
4800 (funcall fun)))))
4802 (defun org-fixup-indentation (diff)
4803 "Change the indentation in the current entry by DIFF
4804 However, if any line in the current entry has no indentation, or if it
4805 would end up with no indentation after the change, nothing at all is done."
4806 (save-excursion
4807 (let ((end (save-excursion (outline-next-heading)
4808 (point-marker)))
4809 (prohibit (if (> diff 0)
4810 "^\\S-"
4811 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
4812 col)
4813 (unless (save-excursion (end-of-line 1)
4814 (re-search-forward prohibit end t))
4815 (while (and (< (point) end)
4816 (re-search-forward "^[ \t]+" end t))
4817 (goto-char (match-end 0))
4818 (setq col (current-column))
4819 (if (< diff 0) (replace-match ""))
4820 (indent-to (+ diff col))))
4821 (move-marker end nil))))
4823 (defun org-convert-to-odd-levels ()
4824 "Convert an org-mode file with all levels allowed to one with odd levels.
4825 This will leave level 1 alone, convert level 2 to level 3, level 3 to
4826 level 5 etc."
4827 (interactive)
4828 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
4829 (let ((org-odd-levels-only nil) n)
4830 (save-excursion
4831 (goto-char (point-min))
4832 (while (re-search-forward "^\\*\\*+ " nil t)
4833 (setq n (- (length (match-string 0)) 2))
4834 (while (>= (setq n (1- n)) 0)
4835 (org-demote))
4836 (end-of-line 1))))))
4839 (defun org-convert-to-oddeven-levels ()
4840 "Convert an org-mode file with only odd levels to one with odd and even levels.
4841 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
4842 section with an even level, conversion would destroy the structure of the file. An error
4843 is signaled in this case."
4844 (interactive)
4845 (goto-char (point-min))
4846 ;; First check if there are no even levels
4847 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
4848 (org-show-context t)
4849 (error "Not all levels are odd in this file. Conversion not possible."))
4850 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
4851 (let ((org-odd-levels-only nil) n)
4852 (save-excursion
4853 (goto-char (point-min))
4854 (while (re-search-forward "^\\*\\*+ " nil t)
4855 (setq n (/ (1- (length (match-string 0))) 2))
4856 (while (>= (setq n (1- n)) 0)
4857 (org-promote))
4858 (end-of-line 1))))))
4860 (defun org-tr-level (n)
4861 "Make N odd if required."
4862 (if org-odd-levels-only (1+ (/ n 2)) n))
4864 ;;; Vertical tree motion, cutting and pasting of subtrees
4866 (defun org-move-subtree-up (&optional arg)
4867 "Move the current subtree up past ARG headlines of the same level."
4868 (interactive "p")
4869 (org-move-subtree-down (- (prefix-numeric-value arg))))
4871 (defun org-move-subtree-down (&optional arg)
4872 "Move the current subtree down past ARG headlines of the same level."
4873 (interactive "p")
4874 (setq arg (prefix-numeric-value arg))
4875 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
4876 'outline-get-last-sibling))
4877 (ins-point (make-marker))
4878 (cnt (abs arg))
4879 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
4880 ;; Select the tree
4881 (org-back-to-heading)
4882 (setq beg0 (point))
4883 (save-excursion
4884 (setq ne-beg (org-back-over-empty-lines))
4885 (setq beg (point)))
4886 (save-match-data
4887 (save-excursion (outline-end-of-heading)
4888 (setq folded (org-invisible-p)))
4889 (outline-end-of-subtree))
4890 (outline-next-heading)
4891 (setq ne-end (org-back-over-empty-lines))
4892 (setq end (point))
4893 (goto-char beg0)
4894 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
4895 ;; include less whitespace
4896 (save-excursion
4897 (goto-char beg)
4898 (forward-line (- ne-beg ne-end))
4899 (setq beg (point))))
4900 ;; Find insertion point, with error handling
4901 (while (> cnt 0)
4902 (or (and (funcall movfunc) (looking-at outline-regexp))
4903 (progn (goto-char beg0)
4904 (error "Cannot move past superior level or buffer limit")))
4905 (setq cnt (1- cnt)))
4906 (if (> arg 0)
4907 ;; Moving forward - still need to move over subtree
4908 (progn (org-end-of-subtree t t)
4909 (save-excursion
4910 (org-back-over-empty-lines)
4911 (or (bolp) (newline)))))
4912 (setq ne-ins (org-back-over-empty-lines))
4913 (move-marker ins-point (point))
4914 (setq txt (buffer-substring beg end))
4915 (org-save-markers-in-region beg end)
4916 (delete-region beg end)
4917 (outline-flag-region (1- beg) beg nil)
4918 (outline-flag-region (1- (point)) (point) nil)
4919 (let ((bbb (point)))
4920 (insert-before-markers txt)
4921 (org-reinstall-markers-in-region bbb)
4922 (move-marker ins-point bbb))
4923 (or (bolp) (insert "\n"))
4924 (setq ins-end (point))
4925 (goto-char ins-point)
4926 (org-skip-whitespace)
4927 (when (and (< arg 0)
4928 (org-first-sibling-p)
4929 (> ne-ins ne-beg))
4930 ;; Move whitespace back to beginning
4931 (save-excursion
4932 (goto-char ins-end)
4933 (let ((kill-whole-line t))
4934 (kill-line (- ne-ins ne-beg)) (point)))
4935 (insert (make-string (- ne-ins ne-beg) ?\n)))
4936 (move-marker ins-point nil)
4937 (org-compact-display-after-subtree-move)
4938 (org-show-empty-lines-in-parent)
4939 (unless folded
4940 (org-show-entry)
4941 (show-children)
4942 (org-cycle-hide-drawers 'children))))
4944 (defvar org-subtree-clip ""
4945 "Clipboard for cut and paste of subtrees.
4946 This is actually only a copy of the kill, because we use the normal kill
4947 ring. We need it to check if the kill was created by `org-copy-subtree'.")
4949 (defvar org-subtree-clip-folded nil
4950 "Was the last copied subtree folded?
4951 This is used to fold the tree back after pasting.")
4953 (defun org-cut-subtree (&optional n)
4954 "Cut the current subtree into the clipboard.
4955 With prefix arg N, cut this many sequential subtrees.
4956 This is a short-hand for marking the subtree and then cutting it."
4957 (interactive "p")
4958 (org-copy-subtree n 'cut))
4960 (defun org-copy-subtree (&optional n cut force-store-markers)
4961 "Cut the current subtree into the clipboard.
4962 With prefix arg N, cut this many sequential subtrees.
4963 This is a short-hand for marking the subtree and then copying it.
4964 If CUT is non-nil, actually cut the subtree.
4965 If FORCE-STORE-MARKERS is non-nil, store the relative locations
4966 of some markers in the region, even if CUT is non-nil. This is
4967 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
4968 (interactive "p")
4969 (let (beg end folded (beg0 (point)))
4970 (if (interactive-p)
4971 (org-back-to-heading nil) ; take what looks like a subtree
4972 (org-back-to-heading t)) ; take what is really there
4973 (org-back-over-empty-lines)
4974 (setq beg (point))
4975 (skip-chars-forward " \t\r\n")
4976 (save-match-data
4977 (save-excursion (outline-end-of-heading)
4978 (setq folded (org-invisible-p)))
4979 (condition-case nil
4980 (outline-forward-same-level (1- n))
4981 (error nil))
4982 (org-end-of-subtree t t))
4983 (org-back-over-empty-lines)
4984 (setq end (point))
4985 (goto-char beg0)
4986 (when (> end beg)
4987 (setq org-subtree-clip-folded folded)
4988 (when (or cut force-store-markers)
4989 (org-save-markers-in-region beg end))
4990 (if cut (kill-region beg end) (copy-region-as-kill beg end))
4991 (setq org-subtree-clip (current-kill 0))
4992 (message "%s: Subtree(s) with %d characters"
4993 (if cut "Cut" "Copied")
4994 (length org-subtree-clip)))))
4996 (defun org-paste-subtree (&optional level tree)
4997 "Paste the clipboard as a subtree, with modification of headline level.
4998 The entire subtree is promoted or demoted in order to match a new headline
4999 level. By default, the new level is derived from the visible headings
5000 before and after the insertion point, and taken to be the inferior headline
5001 level of the two. So if the previous visible heading is level 3 and the
5002 next is level 4 (or vice versa), level 4 will be used for insertion.
5003 This makes sure that the subtree remains an independent subtree and does
5004 not swallow low level entries.
5006 You can also force a different level, either by using a numeric prefix
5007 argument, or by inserting the heading marker by hand. For example, if the
5008 cursor is after \"*****\", then the tree will be shifted to level 5.
5010 If you want to insert the tree as is, just use \\[yank].
5012 If optional TREE is given, use this text instead of the kill ring."
5013 (interactive "P")
5014 (unless (org-kill-is-subtree-p tree)
5015 (error "%s"
5016 (substitute-command-keys
5017 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
5018 (let* ((visp (not (org-invisible-p)))
5019 (txt (or tree (and kill-ring (current-kill 0))))
5020 (^re (concat "^\\(" outline-regexp "\\)"))
5021 (re (concat "\\(" outline-regexp "\\)"))
5022 (^re_ (concat "\\(\\*+\\)[ \t]*"))
5024 (old-level (if (string-match ^re txt)
5025 (- (match-end 0) (match-beginning 0) 1)
5026 -1))
5027 (force-level (cond (level (prefix-numeric-value level))
5028 ((string-match
5029 ^re_ (buffer-substring (point-at-bol) (point)))
5030 (- (match-end 1) (match-beginning 1)))
5031 (t nil)))
5032 (previous-level (save-excursion
5033 (condition-case nil
5034 (progn
5035 (outline-previous-visible-heading 1)
5036 (if (looking-at re)
5037 (- (match-end 0) (match-beginning 0) 1)
5039 (error 1))))
5040 (next-level (save-excursion
5041 (condition-case nil
5042 (progn
5043 (or (looking-at outline-regexp)
5044 (outline-next-visible-heading 1))
5045 (if (looking-at re)
5046 (- (match-end 0) (match-beginning 0) 1)
5048 (error 1))))
5049 (new-level (or force-level (max previous-level next-level)))
5050 (shift (if (or (= old-level -1)
5051 (= new-level -1)
5052 (= old-level new-level))
5054 (- new-level old-level)))
5055 (delta (if (> shift 0) -1 1))
5056 (func (if (> shift 0) 'org-demote 'org-promote))
5057 (org-odd-levels-only nil)
5058 beg end)
5059 ;; Remove the forced level indicator
5060 (if force-level
5061 (delete-region (point-at-bol) (point)))
5062 ;; Paste
5063 (beginning-of-line 1)
5064 (org-back-over-empty-lines)
5065 (setq beg (point))
5066 (insert-before-markers txt)
5067 (unless (string-match "\n\\'" txt) (insert "\n"))
5068 (org-reinstall-markers-in-region beg)
5069 (setq end (point))
5070 (goto-char beg)
5071 (skip-chars-forward " \t\n\r")
5072 (setq beg (point))
5073 (if (and (org-invisible-p) visp)
5074 (save-excursion (outline-show-heading)))
5075 ;; Shift if necessary
5076 (unless (= shift 0)
5077 (save-restriction
5078 (narrow-to-region beg end)
5079 (while (not (= shift 0))
5080 (org-map-region func (point-min) (point-max))
5081 (setq shift (+ delta shift)))
5082 (goto-char (point-min))))
5083 (when (interactive-p)
5084 (message "Clipboard pasted as level %d subtree" new-level))
5085 (if (and kill-ring
5086 (eq org-subtree-clip (current-kill 0))
5087 org-subtree-clip-folded)
5088 ;; The tree was folded before it was killed/copied
5089 (hide-subtree))))
5091 (defun org-kill-is-subtree-p (&optional txt)
5092 "Check if the current kill is an outline subtree, or a set of trees.
5093 Returns nil if kill does not start with a headline, or if the first
5094 headline level is not the largest headline level in the tree.
5095 So this will actually accept several entries of equal levels as well,
5096 which is OK for `org-paste-subtree'.
5097 If optional TXT is given, check this string instead of the current kill."
5098 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
5099 (start-level (and kill
5100 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
5101 org-outline-regexp "\\)")
5102 kill)
5103 (- (match-end 2) (match-beginning 2) 1)))
5104 (re (concat "^" org-outline-regexp))
5105 (start (1+ (or (match-beginning 2) -1))))
5106 (if (not start-level)
5107 (progn
5108 nil) ;; does not even start with a heading
5109 (catch 'exit
5110 (while (setq start (string-match re kill (1+ start)))
5111 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
5112 (throw 'exit nil)))
5113 t))))
5115 (defvar org-markers-to-move nil
5116 "Markers that should be moved with a cut-and-paste operation.
5117 Those markers are stored together with their positions relative to
5118 the start of the region.")
5120 (defun org-save-markers-in-region (beg end)
5121 "Check markers in region.
5122 If these markers are between BEG and END, record their position relative
5123 to BEG, so that after moving the block of text, we can put the markers back
5124 into place.
5125 This function gets called just before an entry or tree gets cut from the
5126 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
5127 called immediately, to move the markers with the entries."
5128 (setq org-markers-to-move nil)
5129 (when (featurep 'org-clock)
5130 (org-clock-save-markers-for-cut-and-paste beg end))
5131 (when (featurep 'org-agenda)
5132 (org-agenda-save-markers-for-cut-and-paste beg end)))
5134 (defun org-check-and-save-marker (marker beg end)
5135 "Check if MARKER is between BEG and END.
5136 If yes, remember the marker and the distance to BEG."
5137 (when (and (marker-buffer marker)
5138 (equal (marker-buffer marker) (current-buffer)))
5139 (if (and (>= marker beg) (< marker end))
5140 (push (cons marker (- marker beg)) org-markers-to-move))))
5142 (defun org-reinstall-markers-in-region (beg)
5143 "Move all remembered markers to their position relative to BEG."
5144 (mapc (lambda (x)
5145 (move-marker (car x) (+ beg (cdr x))))
5146 org-markers-to-move)
5147 (setq org-markers-to-move nil))
5149 (defun org-narrow-to-subtree ()
5150 "Narrow buffer to the current subtree."
5151 (interactive)
5152 (save-excursion
5153 (save-match-data
5154 (narrow-to-region
5155 (progn (org-back-to-heading) (point))
5156 (progn (org-end-of-subtree t) (point))))))
5159 ;;; Outline Sorting
5161 (defun org-sort (with-case)
5162 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
5163 Optional argument WITH-CASE means sort case-sensitively."
5164 (interactive "P")
5165 (if (org-at-table-p)
5166 (org-call-with-arg 'org-table-sort-lines with-case)
5167 (org-call-with-arg 'org-sort-entries-or-items with-case)))
5169 (defun org-sort-remove-invisible (s)
5170 (remove-text-properties 0 (length s) org-rm-props s)
5171 (while (string-match org-bracket-link-regexp s)
5172 (setq s (replace-match (if (match-end 2)
5173 (match-string 3 s)
5174 (match-string 1 s)) t t s)))
5177 (defvar org-priority-regexp) ; defined later in the file
5179 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
5180 "Sort entries on a certain level of an outline tree.
5181 If there is an active region, the entries in the region are sorted.
5182 Else, if the cursor is before the first entry, sort the top-level items.
5183 Else, the children of the entry at point are sorted.
5185 Sorting can be alphabetically, numerically, and by date/time as given by
5186 the first time stamp in the entry. The command prompts for the sorting
5187 type unless it has been given to the function through the SORTING-TYPE
5188 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
5189 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
5190 called with point at the beginning of the record. It must return either
5191 a string or a number that should serve as the sorting key for that record.
5193 Comparing entries ignores case by default. However, with an optional argument
5194 WITH-CASE, the sorting considers case as well."
5195 (interactive "P")
5196 (let ((case-func (if with-case 'identity 'downcase))
5197 start beg end stars re re2
5198 txt what tmp plain-list-p)
5199 ;; Find beginning and end of region to sort
5200 (cond
5201 ((org-region-active-p)
5202 ;; we will sort the region
5203 (setq end (region-end)
5204 what "region")
5205 (goto-char (region-beginning))
5206 (if (not (org-on-heading-p)) (outline-next-heading))
5207 (setq start (point)))
5208 ((org-at-item-p)
5209 ;; we will sort this plain list
5210 (org-beginning-of-item-list) (setq start (point))
5211 (org-end-of-item-list) (setq end (point))
5212 (goto-char start)
5213 (setq plain-list-p t
5214 what "plain list"))
5215 ((or (org-on-heading-p)
5216 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
5217 ;; we will sort the children of the current headline
5218 (org-back-to-heading)
5219 (setq start (point)
5220 end (progn (org-end-of-subtree t t)
5221 (org-back-over-empty-lines)
5222 (point))
5223 what "children")
5224 (goto-char start)
5225 (show-subtree)
5226 (outline-next-heading))
5228 ;; we will sort the top-level entries in this file
5229 (goto-char (point-min))
5230 (or (org-on-heading-p) (outline-next-heading))
5231 (setq start (point) end (point-max) what "top-level")
5232 (goto-char start)
5233 (show-all)))
5235 (setq beg (point))
5236 (if (>= beg end) (error "Nothing to sort"))
5238 (unless plain-list-p
5239 (looking-at "\\(\\*+\\)")
5240 (setq stars (match-string 1)
5241 re (concat "^" (regexp-quote stars) " +")
5242 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
5243 txt (buffer-substring beg end))
5244 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
5245 (if (and (not (equal stars "*")) (string-match re2 txt))
5246 (error "Region to sort contains a level above the first entry")))
5248 (unless sorting-type
5249 (message
5250 (if plain-list-p
5251 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
5252 "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:")
5253 what)
5254 (setq sorting-type (read-char-exclusive))
5256 (and (= (downcase sorting-type) ?f)
5257 (setq getkey-func
5258 (completing-read "Sort using function: "
5259 obarray 'fboundp t nil nil))
5260 (setq getkey-func (intern getkey-func)))
5262 (and (= (downcase sorting-type) ?r)
5263 (setq property
5264 (completing-read "Property: "
5265 (mapcar 'list (org-buffer-property-keys t))
5266 nil t))))
5268 (message "Sorting entries...")
5270 (save-restriction
5271 (narrow-to-region start end)
5273 (let ((dcst (downcase sorting-type))
5274 (now (current-time)))
5275 (sort-subr
5276 (/= dcst sorting-type)
5277 ;; This function moves to the beginning character of the "record" to
5278 ;; be sorted.
5279 (if plain-list-p
5280 (lambda nil
5281 (if (org-at-item-p) t (goto-char (point-max))))
5282 (lambda nil
5283 (if (re-search-forward re nil t)
5284 (goto-char (match-beginning 0))
5285 (goto-char (point-max)))))
5286 ;; This function moves to the last character of the "record" being
5287 ;; sorted.
5288 (if plain-list-p
5289 'org-end-of-item
5290 (lambda nil
5291 (save-match-data
5292 (condition-case nil
5293 (outline-forward-same-level 1)
5294 (error
5295 (goto-char (point-max)))))))
5297 ;; This function returns the value that gets sorted against.
5298 (if plain-list-p
5299 (lambda nil
5300 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
5301 (cond
5302 ((= dcst ?n)
5303 (string-to-number (buffer-substring (match-end 0)
5304 (point-at-eol))))
5305 ((= dcst ?a)
5306 (buffer-substring (match-end 0) (point-at-eol)))
5307 ((= dcst ?t)
5308 (if (re-search-forward org-ts-regexp
5309 (point-at-eol) t)
5310 (org-time-string-to-time (match-string 0))
5311 now))
5312 ((= dcst ?f)
5313 (if getkey-func
5314 (progn
5315 (setq tmp (funcall getkey-func))
5316 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5317 tmp)
5318 (error "Invalid key function `%s'" getkey-func)))
5319 (t (error "Invalid sorting type `%c'" sorting-type)))))
5320 (lambda nil
5321 (cond
5322 ((= dcst ?n)
5323 (if (looking-at org-complex-heading-regexp)
5324 (string-to-number (match-string 4))
5325 nil))
5326 ((= dcst ?a)
5327 (if (looking-at org-complex-heading-regexp)
5328 (funcall case-func (match-string 4))
5329 nil))
5330 ((= dcst ?t)
5331 (if (re-search-forward org-ts-regexp
5332 (save-excursion
5333 (forward-line 2)
5334 (point)) t)
5335 (org-time-string-to-time (match-string 0))
5336 now))
5337 ((= dcst ?p)
5338 (if (re-search-forward org-priority-regexp (point-at-eol) t)
5339 (string-to-char (match-string 2))
5340 org-default-priority))
5341 ((= dcst ?r)
5342 (or (org-entry-get nil property) ""))
5343 ((= dcst ?o)
5344 (if (looking-at org-complex-heading-regexp)
5345 (- 9999 (length (member (match-string 2)
5346 org-todo-keywords-1)))))
5347 ((= dcst ?f)
5348 (if getkey-func
5349 (progn
5350 (setq tmp (funcall getkey-func))
5351 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5352 tmp)
5353 (error "Invalid key function `%s'" getkey-func)))
5354 (t (error "Invalid sorting type `%c'" sorting-type)))))
5356 (cond
5357 ((= dcst ?a) 'string<)
5358 ((= dcst ?t) 'time-less-p)
5359 (t nil)))))
5360 (message "Sorting entries...done")))
5362 (defun org-do-sort (table what &optional with-case sorting-type)
5363 "Sort TABLE of WHAT according to SORTING-TYPE.
5364 The user will be prompted for the SORTING-TYPE if the call to this
5365 function does not specify it. WHAT is only for the prompt, to indicate
5366 what is being sorted. The sorting key will be extracted from
5367 the car of the elements of the table.
5368 If WITH-CASE is non-nil, the sorting will be case-sensitive."
5369 (unless sorting-type
5370 (message
5371 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
5372 what)
5373 (setq sorting-type (read-char-exclusive)))
5374 (let ((dcst (downcase sorting-type))
5375 extractfun comparefun)
5376 ;; Define the appropriate functions
5377 (cond
5378 ((= dcst ?n)
5379 (setq extractfun 'string-to-number
5380 comparefun (if (= dcst sorting-type) '< '>)))
5381 ((= dcst ?a)
5382 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
5383 (lambda(x) (downcase (org-sort-remove-invisible x))))
5384 comparefun (if (= dcst sorting-type)
5385 'string<
5386 (lambda (a b) (and (not (string< a b))
5387 (not (string= a b)))))))
5388 ((= dcst ?t)
5389 (setq extractfun
5390 (lambda (x)
5391 (if (string-match org-ts-regexp x)
5392 (time-to-seconds
5393 (org-time-string-to-time (match-string 0 x)))
5395 comparefun (if (= dcst sorting-type) '< '>)))
5396 (t (error "Invalid sorting type `%c'" sorting-type)))
5398 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5399 table)
5400 (lambda (a b) (funcall comparefun (car a) (car b))))))
5402 ;;; Editing source examples
5404 (defvar org-exit-edit-mode-map (make-sparse-keymap))
5405 (define-key org-exit-edit-mode-map "\C-c'" 'org-edit-src-exit)
5406 (defvar org-edit-src-force-single-line nil)
5407 (defvar org-edit-src-from-org-mode nil)
5408 (defvar org-edit-src-picture nil)
5410 (define-minor-mode org-exit-edit-mode
5411 "Minor mode installing a single key binding, \"C-c '\" to exit special edit.")
5413 (defun org-edit-src-code ()
5414 "Edit the source code example at point.
5415 An indirect buffer is created, and that buffer is then narrowed to the
5416 example at point and switched to the correct language mode. When done,
5417 exit by killing the buffer with \\[org-edit-src-exit]."
5418 (interactive)
5419 (let ((line (org-current-line))
5420 (case-fold-search t)
5421 (msg (substitute-command-keys
5422 "Edit, then exit with C-c ' (C-c and single quote)"))
5423 (info (org-edit-src-find-region-and-lang))
5424 (org-mode-p (eq major-mode 'org-mode))
5425 beg end lang lang-f single)
5426 (if (not info)
5428 (setq beg (nth 0 info)
5429 end (nth 1 info)
5430 lang (nth 2 info)
5431 single (nth 3 info)
5432 lang-f (intern (concat lang "-mode")))
5433 (unless (functionp lang-f)
5434 (error "No such language mode: %s" lang-f))
5435 (goto-line line)
5436 (if (get-buffer "*Org Edit Src Example*")
5437 (kill-buffer "*Org Edit Src Example*"))
5438 (switch-to-buffer (make-indirect-buffer (current-buffer)
5439 "*Org Edit Src Example*"))
5440 (narrow-to-region beg end)
5441 (remove-text-properties beg end '(display nil invisible nil
5442 intangible nil))
5443 (let ((org-inhibit-startup t))
5444 (funcall lang-f))
5445 (set (make-local-variable 'org-edit-src-force-single-line) single)
5446 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5447 (when org-mode-p
5448 (goto-char (point-min))
5449 (while (re-search-forward "^," nil t)
5450 (replace-match "")))
5451 (goto-line line)
5452 (org-exit-edit-mode)
5453 (org-set-local 'header-line-format msg)
5454 (message "%s" msg)
5455 t)))
5457 (defun org-edit-fixed-width-region ()
5458 "Edit the fixed-width ascii drawing at point.
5459 This must be a region where each line starts with ca colon followed by
5460 a space character.
5461 An indirect buffer is created, and that buffer is then narrowed to the
5462 example at point and switched to artist-mode. When done,
5463 exit by killing the buffer with \\[org-edit-src-exit]."
5464 (interactive)
5465 (let ((line (org-current-line))
5466 (case-fold-search t)
5467 (msg (substitute-command-keys
5468 "Edit, then exit with C-c ' (C-c and single quote)"))
5469 (org-mode-p (eq major-mode 'org-mode))
5470 beg end lang lang-f)
5471 (beginning-of-line 1)
5472 (if (looking-at "[ \t]*[^:\n \t]")
5474 (if (looking-at "[ \t]*\\(\n\\|\\'\\)]")
5475 (setq beg (point) end (match-end 0))
5476 (save-excursion
5477 (if (re-search-backward "^[ \t]*[^:]" nil 'move)
5478 (setq beg (point-at-bol 2))
5479 (setq beg (point))))
5480 (save-excursion
5481 (if (re-search-forward "^[ \t]*[^:]" nil 'move)
5482 (setq end (match-beginning 0))
5483 (setq end (point))))
5484 (goto-line line)
5485 (if (get-buffer "*Org Edit Picture*")
5486 (kill-buffer "*Org Edit Picture*"))
5487 (switch-to-buffer (make-indirect-buffer (current-buffer)
5488 "*Org Edit Picture*"))
5489 (narrow-to-region beg end)
5490 (remove-text-properties beg end '(display nil invisible nil
5491 intangible nil))
5492 (when (fboundp 'font-lock-unfontify-region)
5493 (font-lock-unfontify-region (point-min) (point-max)))
5494 (cond
5495 ((eq org-edit-fixed-width-region-mode 'artist-mode)
5496 (fundamental-mode)
5497 (artist-mode 1))
5498 (t (funcall org-edit-fixed-width-region-mode)))
5499 (set (make-local-variable 'org-edit-src-force-single-line) nil)
5500 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5501 (set (make-local-variable 'org-edit-src-picture) t)
5502 (goto-char (point-min))
5503 (while (re-search-forward "^[ \t]*: " nil t)
5504 (replace-match ""))
5505 (goto-line line)
5506 (org-exit-edit-mode)
5507 (org-set-local 'header-line-format msg)
5508 (message "%s" msg)
5509 t))))
5512 (defun org-edit-src-find-region-and-lang ()
5513 "Find the region and language for a local edit.
5514 Return a list with beginning and end of the region, a string representing
5515 the language, a switch telling of the content should be in a single line."
5516 (let ((re-list
5517 (append
5518 org-edit-src-region-extra
5520 ("<src\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</src>" lang)
5521 ("<literal\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</literal>" style)
5522 ("<example>[ \t]*\n?" "\n?[ \t]*</example>" "fundamental")
5523 ("<lisp>[ \t]*\n?" "\n?[ \t]*</lisp>" "emacs-lisp")
5524 ("<perl>[ \t]*\n?" "\n?[ \t]*</perl>" "perl")
5525 ("<python>[ \t]*\n?" "\n?[ \t]*</python>" "python")
5526 ("<ruby>[ \t]*\n?" "\n?[ \t]*</ruby>" "ruby")
5527 ("^#\\+begin_src\\( \\([^ \t\n]+\\)\\)?.*\n" "\n#\\+end_src" 2)
5528 ("^#\\+begin_example.*\n" "\n#\\+end_example" "fundamental")
5529 ("^#\\+html:" "\n" "html" single-line)
5530 ("^#\\+begin_html.*\n" "\n#\\+end_html" "html")
5531 ("^#\\+begin_latex.*\n" "\n#\\+end_latex" "latex")
5532 ("^#\\+latex:" "\n" "latex" single-line)
5533 ("^#\\+begin_ascii.*\n" "\n#\\+end_ascii" "fundamental")
5534 ("^#\\+ascii:" "\n" "ascii" single-line)
5536 (pos (point))
5537 re re1 re2 single beg end lang)
5538 (catch 'exit
5539 (while (setq entry (pop re-list))
5540 (setq re1 (car entry) re2 (nth 1 entry) lang (nth 2 entry)
5541 single (nth 3 entry))
5542 (save-excursion
5543 (if (or (looking-at re1)
5544 (re-search-backward re1 nil t))
5545 (progn
5546 (setq beg (match-end 0) lang (org-edit-src-get-lang lang))
5547 (if (and (re-search-forward re2 nil t)
5548 (>= (match-end 0) pos))
5549 (throw 'exit (list beg (match-beginning 0) lang single))))
5550 (if (or (looking-at re2)
5551 (re-search-forward re2 nil t))
5552 (progn
5553 (setq end (match-beginning 0))
5554 (if (and (re-search-backward re1 nil t)
5555 (<= (match-beginning 0) pos))
5556 (throw 'exit
5557 (list (match-end 0) end
5558 (org-edit-src-get-lang lang) single)))))))))))
5560 (defun org-edit-src-get-lang (lang)
5561 "Extract the src language."
5562 (let ((m (match-string 0)))
5563 (cond
5564 ((stringp lang) lang)
5565 ((integerp lang) (match-string lang))
5566 ((and (eq lang 'lang)
5567 (string-match "\\<lang=\"\\([^ \t\n\"]+\\)\"" m))
5568 (match-string 1 m))
5569 ((and (eq lang 'style)
5570 (string-match "\\<style=\"\\([^ \t\n\"]+\\)\"" m))
5571 (match-string 1 m))
5572 (t "fundamental"))))
5574 (defun org-edit-src-exit ()
5575 "Exit special edit and protect problematic lines."
5576 (interactive)
5577 (unless (buffer-base-buffer (current-buffer))
5578 (error "This is not an indirect buffer, something is wrong..."))
5579 (unless (> (point-min) 1)
5580 (error "This buffer is not narrowed, something is wrong..."))
5581 (goto-char (point-min))
5582 (if (looking-at "[ \t\n]*\n") (replace-match ""))
5583 (if (re-search-forward "\n[ \t\n]*\\'" nil t) (replace-match ""))
5584 (when (org-bound-and-true-p org-edit-src-force-single-line)
5585 (goto-char (point-min))
5586 (while (re-search-forward "\n" nil t)
5587 (replace-match " "))
5588 (goto-char (point-min))
5589 (if (looking-at "\\s-*") (replace-match " "))
5590 (if (re-search-forward "\\s-+\\'" nil t)
5591 (replace-match "")))
5592 (when (org-bound-and-true-p org-edit-src-from-org-mode)
5593 (goto-char (point-min))
5594 (while (re-search-forward (if (org-mode-p) "^\\(.\\)" "^\\([*#]\\)") nil t)
5595 (replace-match ",\\1"))
5596 (when font-lock-mode
5597 (font-lock-unfontify-region (point-min) (point-max)))
5598 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
5599 (when (org-bound-and-true-p org-edit-src-picture)
5600 (goto-char (point-min))
5601 (while (re-search-forward "^" nil t)
5602 (replace-match ": "))
5603 (when font-lock-mode
5604 (font-lock-unfontify-region (point-min) (point-max)))
5605 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
5606 (kill-buffer (current-buffer))
5607 (and (org-mode-p) (org-restart-font-lock)))
5610 ;;; The orgstruct minor mode
5612 ;; Define a minor mode which can be used in other modes in order to
5613 ;; integrate the org-mode structure editing commands.
5615 ;; This is really a hack, because the org-mode structure commands use
5616 ;; keys which normally belong to the major mode. Here is how it
5617 ;; works: The minor mode defines all the keys necessary to operate the
5618 ;; structure commands, but wraps the commands into a function which
5619 ;; tests if the cursor is currently at a headline or a plain list
5620 ;; item. If that is the case, the structure command is used,
5621 ;; temporarily setting many Org-mode variables like regular
5622 ;; expressions for filling etc. However, when any of those keys is
5623 ;; used at a different location, function uses `key-binding' to look
5624 ;; up if the key has an associated command in another currently active
5625 ;; keymap (minor modes, major mode, global), and executes that
5626 ;; command. There might be problems if any of the keys is otherwise
5627 ;; used as a prefix key.
5629 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
5630 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
5631 ;; addresses this by checking explicitly for both bindings.
5633 (defvar orgstruct-mode-map (make-sparse-keymap)
5634 "Keymap for the minor `orgstruct-mode'.")
5636 (defvar org-local-vars nil
5637 "List of local variables, for use by `orgstruct-mode'")
5639 ;;;###autoload
5640 (define-minor-mode orgstruct-mode
5641 "Toggle the minor more `orgstruct-mode'.
5642 This mode is for using Org-mode structure commands in other modes.
5643 The following key behave as if Org-mode was active, if the cursor
5644 is on a headline, or on a plain list item (both in the definition
5645 of Org-mode).
5647 M-up Move entry/item up
5648 M-down Move entry/item down
5649 M-left Promote
5650 M-right Demote
5651 M-S-up Move entry/item up
5652 M-S-down Move entry/item down
5653 M-S-left Promote subtree
5654 M-S-right Demote subtree
5655 M-q Fill paragraph and items like in Org-mode
5656 C-c ^ Sort entries
5657 C-c - Cycle list bullet
5658 TAB Cycle item visibility
5659 M-RET Insert new heading/item
5660 S-M-RET Insert new TODO heading / Chekbox item
5661 C-c C-c Set tags / toggle checkbox"
5662 nil " OrgStruct" nil
5663 (org-load-modules-maybe)
5664 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
5666 ;;;###autoload
5667 (defun turn-on-orgstruct ()
5668 "Unconditionally turn on `orgstruct-mode'."
5669 (orgstruct-mode 1))
5671 ;;;###autoload
5672 (defun turn-on-orgstruct++ ()
5673 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
5674 In addition to setting orgstruct-mode, this also exports all indentation and
5675 autofilling variables from org-mode into the buffer. Note that turning
5676 off orgstruct-mode will *not* remove these additional settings."
5677 (orgstruct-mode 1)
5678 (let (var val)
5679 (mapc
5680 (lambda (x)
5681 (when (string-match
5682 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
5683 (symbol-name (car x)))
5684 (setq var (car x) val (nth 1 x))
5685 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
5686 org-local-vars)))
5688 (defun orgstruct-error ()
5689 "Error when there is no default binding for a structure key."
5690 (interactive)
5691 (error "This key has no function outside structure elements"))
5693 (defun orgstruct-setup ()
5694 "Setup orgstruct keymaps."
5695 (let ((nfunc 0)
5696 (bindings
5697 (list
5698 '([(meta up)] org-metaup)
5699 '([(meta down)] org-metadown)
5700 '([(meta left)] org-metaleft)
5701 '([(meta right)] org-metaright)
5702 '([(meta shift up)] org-shiftmetaup)
5703 '([(meta shift down)] org-shiftmetadown)
5704 '([(meta shift left)] org-shiftmetaleft)
5705 '([(meta shift right)] org-shiftmetaright)
5706 '([(shift up)] org-shiftup)
5707 '([(shift down)] org-shiftdown)
5708 '("\C-c\C-c" org-ctrl-c-ctrl-c)
5709 '("\M-q" fill-paragraph)
5710 '("\C-c^" org-sort)
5711 '("\C-c-" org-cycle-list-bullet)))
5712 elt key fun cmd)
5713 (while (setq elt (pop bindings))
5714 (setq nfunc (1+ nfunc))
5715 (setq key (org-key (car elt))
5716 fun (nth 1 elt)
5717 cmd (orgstruct-make-binding fun nfunc key))
5718 (org-defkey orgstruct-mode-map key cmd))
5720 ;; Special treatment needed for TAB and RET
5721 (org-defkey orgstruct-mode-map [(tab)]
5722 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
5723 (org-defkey orgstruct-mode-map "\C-i"
5724 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
5726 (org-defkey orgstruct-mode-map "\M-\C-m"
5727 (orgstruct-make-binding 'org-insert-heading 105
5728 "\M-\C-m" [(meta return)]))
5729 (org-defkey orgstruct-mode-map [(meta return)]
5730 (orgstruct-make-binding 'org-insert-heading 106
5731 [(meta return)] "\M-\C-m"))
5733 (org-defkey orgstruct-mode-map [(shift meta return)]
5734 (orgstruct-make-binding 'org-insert-todo-heading 107
5735 [(meta return)] "\M-\C-m"))
5737 (unless org-local-vars
5738 (setq org-local-vars (org-get-local-variables)))
5742 (defun orgstruct-make-binding (fun n &rest keys)
5743 "Create a function for binding in the structure minor mode.
5744 FUN is the command to call inside a table. N is used to create a unique
5745 command name. KEYS are keys that should be checked in for a command
5746 to execute outside of tables."
5747 (eval
5748 (list 'defun
5749 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
5750 '(arg)
5751 (concat "In Structure, run `" (symbol-name fun) "'.\n"
5752 "Outside of structure, run the binding of `"
5753 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
5754 "'.")
5755 '(interactive "p")
5756 (list 'if
5757 '(org-context-p 'headline 'item)
5758 (list 'org-run-like-in-org-mode (list 'quote fun))
5759 (list 'let '(orgstruct-mode)
5760 (list 'call-interactively
5761 (append '(or)
5762 (mapcar (lambda (k)
5763 (list 'key-binding k))
5764 keys)
5765 '('orgstruct-error))))))))
5767 (defun org-context-p (&rest contexts)
5768 "Check if local context is any of CONTEXTS.
5769 Possible values in the list of contexts are `table', `headline', and `item'."
5770 (let ((pos (point)))
5771 (goto-char (point-at-bol))
5772 (prog1 (or (and (memq 'table contexts)
5773 (looking-at "[ \t]*|"))
5774 (and (memq 'headline contexts)
5775 ;;????????? (looking-at "\\*+"))
5776 (looking-at outline-regexp))
5777 (and (memq 'item contexts)
5778 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
5779 (goto-char pos))))
5781 (defun org-get-local-variables ()
5782 "Return a list of all local variables in an org-mode buffer."
5783 (let (varlist)
5784 (with-current-buffer (get-buffer-create "*Org tmp*")
5785 (erase-buffer)
5786 (org-mode)
5787 (setq varlist (buffer-local-variables)))
5788 (kill-buffer "*Org tmp*")
5789 (delq nil
5790 (mapcar
5791 (lambda (x)
5792 (setq x
5793 (if (symbolp x)
5794 (list x)
5795 (list (car x) (list 'quote (cdr x)))))
5796 (if (string-match
5797 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
5798 (symbol-name (car x)))
5799 x nil))
5800 varlist))))
5802 ;;;###autoload
5803 (defun org-run-like-in-org-mode (cmd)
5804 (org-load-modules-maybe)
5805 (unless org-local-vars
5806 (setq org-local-vars (org-get-local-variables)))
5807 (eval (list 'let org-local-vars
5808 (list 'call-interactively (list 'quote cmd)))))
5810 ;;;; Archiving
5812 (defun org-get-category (&optional pos)
5813 "Get the category applying to position POS."
5814 (get-text-property (or pos (point)) 'org-category))
5816 (defun org-refresh-category-properties ()
5817 "Refresh category text properties in the buffer."
5818 (let ((def-cat (cond
5819 ((null org-category)
5820 (if buffer-file-name
5821 (file-name-sans-extension
5822 (file-name-nondirectory buffer-file-name))
5823 "???"))
5824 ((symbolp org-category) (symbol-name org-category))
5825 (t org-category)))
5826 beg end cat pos optionp)
5827 (org-unmodified
5828 (save-excursion
5829 (save-restriction
5830 (widen)
5831 (goto-char (point-min))
5832 (put-text-property (point) (point-max) 'org-category def-cat)
5833 (while (re-search-forward
5834 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
5835 (setq pos (match-end 0)
5836 optionp (equal (char-after (match-beginning 0)) ?#)
5837 cat (org-trim (match-string 2)))
5838 (if optionp
5839 (setq beg (point-at-bol) end (point-max))
5840 (org-back-to-heading t)
5841 (setq beg (point) end (org-end-of-subtree t t)))
5842 (put-text-property beg end 'org-category cat)
5843 (goto-char pos)))))))
5846 ;;;; Link Stuff
5848 ;;; Link abbreviations
5850 (defun org-link-expand-abbrev (link)
5851 "Apply replacements as defined in `org-link-abbrev-alist."
5852 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
5853 (let* ((key (match-string 1 link))
5854 (as (or (assoc key org-link-abbrev-alist-local)
5855 (assoc key org-link-abbrev-alist)))
5856 (tag (and (match-end 2) (match-string 3 link)))
5857 rpl)
5858 (if (not as)
5859 link
5860 (setq rpl (cdr as))
5861 (cond
5862 ((symbolp rpl) (funcall rpl tag))
5863 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
5864 (t (concat rpl tag)))))
5865 link))
5867 ;;; Storing and inserting links
5869 (defvar org-insert-link-history nil
5870 "Minibuffer history for links inserted with `org-insert-link'.")
5872 (defvar org-stored-links nil
5873 "Contains the links stored with `org-store-link'.")
5875 (defvar org-store-link-plist nil
5876 "Plist with info about the most recently link created with `org-store-link'.")
5878 (defvar org-link-protocols nil
5879 "Link protocols added to Org-mode using `org-add-link-type'.")
5881 (defvar org-store-link-functions nil
5882 "List of functions that are called to create and store a link.
5883 Each function will be called in turn until one returns a non-nil
5884 value. Each function should check if it is responsible for creating
5885 this link (for example by looking at the major mode).
5886 If not, it must exit and return nil.
5887 If yes, it should return a non-nil value after a calling
5888 `org-store-link-props' with a list of properties and values.
5889 Special properties are:
5891 :type The link prefix. like \"http\". This must be given.
5892 :link The link, like \"http://www.astro.uva.nl/~dominik\".
5893 This is obligatory as well.
5894 :description Optional default description for the second pair
5895 of brackets in an Org-mode link. The user can still change
5896 this when inserting this link into an Org-mode buffer.
5898 In addition to these, any additional properties can be specified
5899 and then used in remember templates.")
5901 (defun org-add-link-type (type &optional follow export)
5902 "Add TYPE to the list of `org-link-types'.
5903 Re-compute all regular expressions depending on `org-link-types'
5905 FOLLOW and EXPORT are two functions.
5907 FOLLOW should take the link path as the single argument and do whatever
5908 is necessary to follow the link, for example find a file or display
5909 a mail message.
5911 EXPORT should format the link path for export to one of the export formats.
5912 It should be a function accepting three arguments:
5914 path the path of the link, the text after the prefix (like \"http:\")
5915 desc the description of the link, if any, nil if there was no descripton
5916 format the export format, a symbol like `html' or `latex'.
5918 The function may use the FORMAT information to return different values
5919 depending on the format. The return value will be put literally into
5920 the exported file.
5921 Org-mode has a built-in default for exporting links. If you are happy with
5922 this default, there is no need to define an export function for the link
5923 type. For a simple example of an export function, see `org-bbdb.el'."
5924 (add-to-list 'org-link-types type t)
5925 (org-make-link-regexps)
5926 (if (assoc type org-link-protocols)
5927 (setcdr (assoc type org-link-protocols) (list follow export))
5928 (push (list type follow export) org-link-protocols)))
5931 ;;;###autoload
5932 (defun org-store-link (arg)
5933 "\\<org-mode-map>Store an org-link to the current location.
5934 This link is added to `org-stored-links' and can later be inserted
5935 into an org-buffer with \\[org-insert-link].
5937 For some link types, a prefix arg is interpreted:
5938 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
5939 For file links, arg negates `org-context-in-file-links'."
5940 (interactive "P")
5941 (org-load-modules-maybe)
5942 (setq org-store-link-plist nil) ; reset
5943 (let (link cpltxt desc description search txt)
5944 (cond
5946 ((run-hook-with-args-until-success 'org-store-link-functions)
5947 (setq link (plist-get org-store-link-plist :link)
5948 desc (or (plist-get org-store-link-plist :description) link)))
5950 ((eq major-mode 'calendar-mode)
5951 (let ((cd (calendar-cursor-to-date)))
5952 (setq link
5953 (format-time-string
5954 (car org-time-stamp-formats)
5955 (apply 'encode-time
5956 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
5957 nil nil nil))))
5958 (org-store-link-props :type "calendar" :date cd)))
5960 ((eq major-mode 'w3-mode)
5961 (setq cpltxt (url-view-url t)
5962 link (org-make-link cpltxt))
5963 (org-store-link-props :type "w3" :url (url-view-url t)))
5965 ((eq major-mode 'w3m-mode)
5966 (setq cpltxt (or w3m-current-title w3m-current-url)
5967 link (org-make-link w3m-current-url))
5968 (org-store-link-props :type "w3m" :url (url-view-url t)))
5970 ((setq search (run-hook-with-args-until-success
5971 'org-create-file-search-functions))
5972 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
5973 "::" search))
5974 (setq cpltxt (or description link)))
5976 ((eq major-mode 'image-mode)
5977 (setq cpltxt (concat "file:"
5978 (abbreviate-file-name buffer-file-name))
5979 link (org-make-link cpltxt))
5980 (org-store-link-props :type "image" :file buffer-file-name))
5982 ((eq major-mode 'dired-mode)
5983 ;; link to the file in the current line
5984 (setq cpltxt (concat "file:"
5985 (abbreviate-file-name
5986 (expand-file-name
5987 (dired-get-filename nil t))))
5988 link (org-make-link cpltxt)))
5990 ((and buffer-file-name (org-mode-p))
5991 ;; Just link to current headline
5992 (setq cpltxt (concat "file:"
5993 (abbreviate-file-name buffer-file-name)))
5994 ;; Add a context search string
5995 (when (org-xor org-context-in-file-links arg)
5996 ;; Check if we are on a target
5997 (if (org-in-regexp "<<\\(.*?\\)>>")
5998 (setq cpltxt (concat cpltxt "::" (match-string 1)))
5999 (setq txt (cond
6000 ((org-on-heading-p) nil)
6001 ((org-region-active-p)
6002 (buffer-substring (region-beginning) (region-end)))
6003 (t nil)))
6004 (when (or (null txt) (string-match "\\S-" txt))
6005 (setq cpltxt
6006 (concat cpltxt "::"
6007 (condition-case nil
6008 (org-make-org-heading-search-string txt)
6009 (error "")))
6010 desc "NONE"))))
6011 (if (string-match "::\\'" cpltxt)
6012 (setq cpltxt (substring cpltxt 0 -2)))
6013 (setq link (org-make-link cpltxt)))
6015 ((buffer-file-name (buffer-base-buffer))
6016 ;; Just link to this file here.
6017 (setq cpltxt (concat "file:"
6018 (abbreviate-file-name
6019 (buffer-file-name (buffer-base-buffer)))))
6020 ;; Add a context string
6021 (when (org-xor org-context-in-file-links arg)
6022 (setq txt (if (org-region-active-p)
6023 (buffer-substring (region-beginning) (region-end))
6024 (buffer-substring (point-at-bol) (point-at-eol))))
6025 ;; Only use search option if there is some text.
6026 (when (string-match "\\S-" txt)
6027 (setq cpltxt
6028 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6029 desc "NONE")))
6030 (setq link (org-make-link cpltxt)))
6032 ((interactive-p)
6033 (error "Cannot link to a buffer which is not visiting a file"))
6035 (t (setq link nil)))
6037 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6038 (setq link (or link cpltxt)
6039 desc (or desc cpltxt))
6040 (if (equal desc "NONE") (setq desc nil))
6042 (if (and (interactive-p) link)
6043 (progn
6044 (setq org-stored-links
6045 (cons (list link desc) org-stored-links))
6046 (message "Stored: %s" (or desc link)))
6047 (and link (org-make-link-string link desc)))))
6049 (defun org-store-link-props (&rest plist)
6050 "Store link properties, extract names and addresses."
6051 (let (x adr)
6052 (when (setq x (plist-get plist :from))
6053 (setq adr (mail-extract-address-components x))
6054 (plist-put plist :fromname (car adr))
6055 (plist-put plist :fromaddress (nth 1 adr)))
6056 (when (setq x (plist-get plist :to))
6057 (setq adr (mail-extract-address-components x))
6058 (plist-put plist :toname (car adr))
6059 (plist-put plist :toaddress (nth 1 adr))))
6060 (let ((from (plist-get plist :from))
6061 (to (plist-get plist :to)))
6062 (when (and from to org-from-is-user-regexp)
6063 (plist-put plist :fromto
6064 (if (string-match org-from-is-user-regexp from)
6065 (concat "to %t")
6066 (concat "from %f")))))
6067 (setq org-store-link-plist plist))
6069 (defun org-add-link-props (&rest plist)
6070 "Add these properties to the link property list."
6071 (let (key value)
6072 (while plist
6073 (setq key (pop plist) value (pop plist))
6074 (setq org-store-link-plist
6075 (plist-put org-store-link-plist key value)))))
6077 (defun org-email-link-description (&optional fmt)
6078 "Return the description part of an email link.
6079 This takes information from `org-store-link-plist' and formats it
6080 according to FMT (default from `org-email-link-description-format')."
6081 (setq fmt (or fmt org-email-link-description-format))
6082 (let* ((p org-store-link-plist)
6083 (to (plist-get p :toaddress))
6084 (from (plist-get p :fromaddress))
6085 (table
6086 (list
6087 (cons "%c" (plist-get p :fromto))
6088 (cons "%F" (plist-get p :from))
6089 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
6090 (cons "%T" (plist-get p :to))
6091 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
6092 (cons "%s" (plist-get p :subject))
6093 (cons "%m" (plist-get p :message-id)))))
6094 (when (string-match "%c" fmt)
6095 ;; Check if the user wrote this message
6096 (if (and org-from-is-user-regexp from to
6097 (save-match-data (string-match org-from-is-user-regexp from)))
6098 (setq fmt (replace-match "to %t" t t fmt))
6099 (setq fmt (replace-match "from %f" t t fmt))))
6100 (org-replace-escapes fmt table)))
6102 (defun org-make-org-heading-search-string (&optional string heading)
6103 "Make search string for STRING or current headline."
6104 (interactive)
6105 (let ((s (or string (org-get-heading))))
6106 (unless (and string (not heading))
6107 ;; We are using a headline, clean up garbage in there.
6108 (if (string-match org-todo-regexp s)
6109 (setq s (replace-match "" t t s)))
6110 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
6111 (setq s (replace-match "" t t s)))
6112 (setq s (org-trim s))
6113 (if (string-match (concat "^\\(" org-quote-string "\\|"
6114 org-comment-string "\\)") s)
6115 (setq s (replace-match "" t t s)))
6116 (while (string-match org-ts-regexp s)
6117 (setq s (replace-match "" t t s))))
6118 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
6119 (setq s (replace-match " " t t s)))
6120 (or string (setq s (concat "*" s))) ; Add * for headlines
6121 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
6123 (defun org-make-link (&rest strings)
6124 "Concatenate STRINGS."
6125 (apply 'concat strings))
6127 (defun org-make-link-string (link &optional description)
6128 "Make a link with brackets, consisting of LINK and DESCRIPTION."
6129 (unless (string-match "\\S-" link)
6130 (error "Empty link"))
6131 (when (stringp description)
6132 ;; Remove brackets from the description, they are fatal.
6133 (while (string-match "\\[" description)
6134 (setq description (replace-match "{" t t description)))
6135 (while (string-match "\\]" description)
6136 (setq description (replace-match "}" t t description))))
6137 (when (equal (org-link-escape link) description)
6138 ;; No description needed, it is identical
6139 (setq description nil))
6140 (when (and (not description)
6141 (not (equal link (org-link-escape link))))
6142 (setq description (org-extract-attributes link)))
6143 (concat "[[" (org-link-escape link) "]"
6144 (if description (concat "[" description "]") "")
6145 "]"))
6147 (defconst org-link-escape-chars
6148 '((?\ . "%20")
6149 (?\[ . "%5B")
6150 (?\] . "%5D")
6151 (?\340 . "%E0") ; `a
6152 (?\342 . "%E2") ; ^a
6153 (?\347 . "%E7") ; ,c
6154 (?\350 . "%E8") ; `e
6155 (?\351 . "%E9") ; 'e
6156 (?\352 . "%EA") ; ^e
6157 (?\356 . "%EE") ; ^i
6158 (?\364 . "%F4") ; ^o
6159 (?\371 . "%F9") ; `u
6160 (?\373 . "%FB") ; ^u
6161 (?\; . "%3B")
6162 (?? . "%3F")
6163 (?= . "%3D")
6164 (?+ . "%2B")
6166 "Association list of escapes for some characters problematic in links.
6167 This is the list that is used for internal purposes.")
6169 (defconst org-link-escape-chars-browser
6170 '((?\ . "%20")) ; 32 for the SPC char
6171 "Association list of escapes for some characters problematic in links.
6172 This is the list that is used before handing over to the browser.")
6174 (defun org-link-escape (text &optional table)
6175 "Escape charaters in TEXT that are problematic for links."
6176 (setq table (or table org-link-escape-chars))
6177 (when text
6178 (let ((re (mapconcat (lambda (x) (regexp-quote
6179 (char-to-string (car x))))
6180 table "\\|")))
6181 (while (string-match re text)
6182 (setq text
6183 (replace-match
6184 (cdr (assoc (string-to-char (match-string 0 text))
6185 table))
6186 t t text)))
6187 text)))
6189 (defun org-link-unescape (text &optional table)
6190 "Reverse the action of `org-link-escape'."
6191 (setq table (or table org-link-escape-chars))
6192 (when text
6193 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
6194 table "\\|")))
6195 (while (string-match re text)
6196 (setq text
6197 (replace-match
6198 (char-to-string (car (rassoc (match-string 0 text) table)))
6199 t t text)))
6200 text)))
6202 (defun org-xor (a b)
6203 "Exclusive or."
6204 (if a (not b) b))
6206 (defun org-get-header (header)
6207 "Find a header field in the current buffer."
6208 (save-excursion
6209 (goto-char (point-min))
6210 (let ((case-fold-search t) s)
6211 (cond
6212 ((eq header 'from)
6213 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
6214 (setq s (match-string 1)))
6215 (while (string-match "\"" s)
6216 (setq s (replace-match "" t t s)))
6217 (if (string-match "[<(].*" s)
6218 (setq s (replace-match "" t t s))))
6219 ((eq header 'message-id)
6220 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
6221 (setq s (match-string 1))))
6222 ((eq header 'subject)
6223 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
6224 (setq s (match-string 1)))))
6225 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
6226 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
6227 s)))
6230 (defun org-fixup-message-id-for-http (s)
6231 "Replace special characters in a message id, so it can be used in an http query."
6232 (while (string-match "<" s)
6233 (setq s (replace-match "%3C" t t s)))
6234 (while (string-match ">" s)
6235 (setq s (replace-match "%3E" t t s)))
6236 (while (string-match "@" s)
6237 (setq s (replace-match "%40" t t s)))
6240 ;;;###autoload
6241 (defun org-insert-link-global ()
6242 "Insert a link like Org-mode does.
6243 This command can be called in any mode to insert a link in Org-mode syntax."
6244 (interactive)
6245 (org-load-modules-maybe)
6246 (org-run-like-in-org-mode 'org-insert-link))
6248 (defun org-insert-link (&optional complete-file link-location)
6249 "Insert a link. At the prompt, enter the link.
6251 Completion can be used to select a link previously stored with
6252 `org-store-link'. When the empty string is entered (i.e. if you just
6253 press RET at the prompt), the link defaults to the most recently
6254 stored link. As SPC triggers completion in the minibuffer, you need to
6255 use M-SPC or C-q SPC to force the insertion of a space character.
6257 You will also be prompted for a description, and if one is given, it will
6258 be displayed in the buffer instead of the link.
6260 If there is already a link at point, this command will allow you to edit link
6261 and description parts.
6263 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
6264 be selected using completion. The path to the file will be relative to the
6265 current directory if the file is in the current directory or a subdirectory.
6266 Otherwise, the link will be the absolute path as completed in the minibuffer
6267 \(i.e. normally ~/path/to/file).
6269 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
6270 the current directory or below. With three \\[universal-argument] prefixes, negate the meaning
6271 of `org-keep-stored-link-after-insertion'.
6273 If `org-make-link-description-function' is non-nil, this function will be
6274 called with the link target, and the result will be the default
6275 link description.
6277 If the LINK-LOCATION parameter is non-nil, this value will be
6278 used as the link location instead of reading one interactively."
6279 (interactive "P")
6280 (let* ((wcf (current-window-configuration))
6281 (region (if (org-region-active-p)
6282 (buffer-substring (region-beginning) (region-end))))
6283 (remove (and region (list (region-beginning) (region-end))))
6284 (desc region)
6285 tmphist ; byte-compile incorrectly complains about this
6286 (link link-location)
6287 entry file)
6288 (cond
6289 (link-location) ; specified by arg, just use it.
6290 ((org-in-regexp org-bracket-link-regexp 1)
6291 ;; We do have a link at point, and we are going to edit it.
6292 (setq remove (list (match-beginning 0) (match-end 0)))
6293 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
6294 (setq link (read-string "Link: "
6295 (org-link-unescape
6296 (org-match-string-no-properties 1)))))
6297 ((or (org-in-regexp org-angle-link-re)
6298 (org-in-regexp org-plain-link-re))
6299 ;; Convert to bracket link
6300 (setq remove (list (match-beginning 0) (match-end 0))
6301 link (read-string "Link: "
6302 (org-remove-angle-brackets (match-string 0)))))
6303 ((equal complete-file '(4))
6304 ;; Completing read for file names.
6305 (setq file (read-file-name "File: "))
6306 (let ((pwd (file-name-as-directory (expand-file-name ".")))
6307 (pwd1 (file-name-as-directory (abbreviate-file-name
6308 (expand-file-name ".")))))
6309 (cond
6310 ((equal complete-file '(16))
6311 (setq link (org-make-link
6312 "file:"
6313 (abbreviate-file-name (expand-file-name file)))))
6314 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
6315 (setq link (org-make-link "file:" (match-string 1 file))))
6316 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
6317 (expand-file-name file))
6318 (setq link (org-make-link
6319 "file:" (match-string 1 (expand-file-name file)))))
6320 (t (setq link (org-make-link "file:" file))))))
6322 ;; Read link, with completion for stored links.
6323 (with-output-to-temp-buffer "*Org Links*"
6324 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
6325 (when org-stored-links
6326 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
6327 (princ (mapconcat
6328 (lambda (x)
6329 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
6330 (reverse org-stored-links) "\n"))))
6331 (let ((cw (selected-window)))
6332 (select-window (get-buffer-window "*Org Links*"))
6333 (shrink-window-if-larger-than-buffer)
6334 (setq truncate-lines t)
6335 (select-window cw))
6336 ;; Fake a link history, containing the stored links.
6337 (setq tmphist (append (mapcar 'car org-stored-links)
6338 org-insert-link-history))
6339 (unwind-protect
6340 (setq link (org-completing-read
6341 "Link: "
6342 (append
6343 (mapcar (lambda (x) (list (concat (car x) ":")))
6344 (append org-link-abbrev-alist-local org-link-abbrev-alist))
6345 (mapcar (lambda (x) (list (concat x ":")))
6346 org-link-types))
6347 nil nil nil
6348 'tmphist
6349 (or (car (car org-stored-links)))))
6350 (set-window-configuration wcf)
6351 (kill-buffer "*Org Links*"))
6352 (setq entry (assoc link org-stored-links))
6353 (or entry (push link org-insert-link-history))
6354 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
6355 (not org-keep-stored-link-after-insertion))
6356 (setq org-stored-links (delq (assoc link org-stored-links)
6357 org-stored-links)))
6358 (setq desc (or desc (nth 1 entry)))))
6360 (if (string-match org-plain-link-re link)
6361 ;; URL-like link, normalize the use of angular brackets.
6362 (setq link (org-make-link (org-remove-angle-brackets link))))
6364 ;; Check if we are linking to the current file with a search option
6365 ;; If yes, simplify the link by using only the search option.
6366 (when (and buffer-file-name
6367 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
6368 (let* ((path (match-string 1 link))
6369 (case-fold-search nil)
6370 (search (match-string 2 link)))
6371 (save-match-data
6372 (if (equal (file-truename buffer-file-name) (file-truename path))
6373 ;; We are linking to this same file, with a search option
6374 (setq link search)))))
6376 ;; Check if we can/should use a relative path. If yes, simplify the link
6377 (when (string-match "\\<file:\\(.*\\)" link)
6378 (let* ((path (match-string 1 link))
6379 (origpath path)
6380 (case-fold-search nil))
6381 (cond
6382 ((eq org-link-file-path-type 'absolute)
6383 (setq path (abbreviate-file-name (expand-file-name path))))
6384 ((eq org-link-file-path-type 'noabbrev)
6385 (setq path (expand-file-name path)))
6386 ((eq org-link-file-path-type 'relative)
6387 (setq path (file-relative-name path)))
6389 (save-match-data
6390 (if (string-match (concat "^" (regexp-quote
6391 (file-name-as-directory
6392 (expand-file-name "."))))
6393 (expand-file-name path))
6394 ;; We are linking a file with relative path name.
6395 (setq path (substring (expand-file-name path)
6396 (match-end 0)))))))
6397 (setq link (concat "file:" path))
6398 (if (equal desc origpath)
6399 (setq desc path))))
6401 (if org-make-link-description-function
6402 (setq desc (funcall org-make-link-description-function link desc)))
6404 (setq desc (read-string "Description: " desc))
6405 (unless (string-match "\\S-" desc) (setq desc nil))
6406 (if remove (apply 'delete-region remove))
6407 (insert (org-make-link-string link desc))))
6409 (defun org-completing-read (&rest args)
6410 (let ((minibuffer-local-completion-map
6411 (copy-keymap minibuffer-local-completion-map)))
6412 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
6413 (apply 'completing-read args)))
6415 (defun org-extract-attributes (s)
6416 "Extract the attributes cookie from a string and set as text property."
6417 (let (a attr (start 0) key value)
6418 (save-match-data
6419 (when (string-match "{{\\([^}]+\\)}}$" s)
6420 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
6421 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
6422 (setq key (match-string 1 a) value (match-string 2 a)
6423 start (match-end 0)
6424 attr (plist-put attr (intern key) value))))
6425 (org-add-props s nil 'org-attributes attr))
6428 (defun org-attributes-to-string (plist)
6429 "Format a property list into an HTML attribute list."
6430 (let ((s "") key value)
6431 (while plist
6432 (setq key (pop plist) value (pop plist))
6433 (setq s (concat s " "(symbol-name key) "=\"" value "\"")))
6436 ;;; Opening/following a link
6438 (defvar org-link-search-failed nil)
6440 (defun org-next-link ()
6441 "Move forward to the next link.
6442 If the link is in hidden text, expose it."
6443 (interactive)
6444 (when (and org-link-search-failed (eq this-command last-command))
6445 (goto-char (point-min))
6446 (message "Link search wrapped back to beginning of buffer"))
6447 (setq org-link-search-failed nil)
6448 (let* ((pos (point))
6449 (ct (org-context))
6450 (a (assoc :link ct)))
6451 (if a (goto-char (nth 2 a)))
6452 (if (re-search-forward org-any-link-re nil t)
6453 (progn
6454 (goto-char (match-beginning 0))
6455 (if (org-invisible-p) (org-show-context)))
6456 (goto-char pos)
6457 (setq org-link-search-failed t)
6458 (error "No further link found"))))
6460 (defun org-previous-link ()
6461 "Move backward to the previous link.
6462 If the link is in hidden text, expose it."
6463 (interactive)
6464 (when (and org-link-search-failed (eq this-command last-command))
6465 (goto-char (point-max))
6466 (message "Link search wrapped back to end of buffer"))
6467 (setq org-link-search-failed nil)
6468 (let* ((pos (point))
6469 (ct (org-context))
6470 (a (assoc :link ct)))
6471 (if a (goto-char (nth 1 a)))
6472 (if (re-search-backward org-any-link-re nil t)
6473 (progn
6474 (goto-char (match-beginning 0))
6475 (if (org-invisible-p) (org-show-context)))
6476 (goto-char pos)
6477 (setq org-link-search-failed t)
6478 (error "No further link found"))))
6480 (defun org-find-file-at-mouse (ev)
6481 "Open file link or URL at mouse."
6482 (interactive "e")
6483 (mouse-set-point ev)
6484 (org-open-at-point 'in-emacs))
6486 (defun org-open-at-mouse (ev)
6487 "Open file link or URL at mouse."
6488 (interactive "e")
6489 (mouse-set-point ev)
6490 (org-open-at-point))
6492 (defvar org-window-config-before-follow-link nil
6493 "The window configuration before following a link.
6494 This is saved in case the need arises to restore it.")
6496 (defvar org-open-link-marker (make-marker)
6497 "Marker pointing to the location where `org-open-at-point; was called.")
6499 ;;;###autoload
6500 (defun org-open-at-point-global ()
6501 "Follow a link like Org-mode does.
6502 This command can be called in any mode to follow a link that has
6503 Org-mode syntax."
6504 (interactive)
6505 (org-run-like-in-org-mode 'org-open-at-point))
6507 ;;;###autoload
6508 (defun org-open-link-from-string (s &optional arg)
6509 "Open a link in the string S, as if it was in Org-mode."
6510 (interactive "sLink: \nP")
6511 (with-temp-buffer
6512 (let ((org-inhibit-startup t))
6513 (org-mode)
6514 (insert s)
6515 (goto-char (point-min))
6516 (org-open-at-point arg))))
6518 (defun org-open-at-point (&optional in-emacs)
6519 "Open link at or after point.
6520 If there is no link at point, this function will search forward up to
6521 the end of the current subtree.
6522 Normally, files will be opened by an appropriate application. If the
6523 optional argument IN-EMACS is non-nil, Emacs will visit the file."
6524 (interactive "P")
6525 (org-load-modules-maybe)
6526 (move-marker org-open-link-marker (point))
6527 (setq org-window-config-before-follow-link (current-window-configuration))
6528 (org-remove-occur-highlights nil nil t)
6529 (if (org-at-timestamp-p t)
6530 (org-follow-timestamp-link)
6531 (let (type path link line search (pos (point)))
6532 (catch 'match
6533 (save-excursion
6534 (skip-chars-forward "^]\n\r")
6535 (when (org-in-regexp org-bracket-link-regexp)
6536 (setq link (org-extract-attributes
6537 (org-link-unescape (org-match-string-no-properties 1))))
6538 (while (string-match " *\n *" link)
6539 (setq link (replace-match " " t t link)))
6540 (setq link (org-link-expand-abbrev link))
6541 (cond
6542 ((or (file-name-absolute-p link)
6543 (string-match "^\\.\\.?/" link))
6544 (setq type "file" path link))
6545 ((string-match org-link-re-with-space2 link)
6546 (setq type (match-string 1 link) path (match-string 2 link)))
6547 (t (setq type "thisfile" path link)))
6548 (throw 'match t)))
6550 (when (get-text-property (point) 'org-linked-text)
6551 (setq type "thisfile"
6552 pos (if (get-text-property (1+ (point)) 'org-linked-text)
6553 (1+ (point)) (point))
6554 path (buffer-substring
6555 (previous-single-property-change pos 'org-linked-text)
6556 (next-single-property-change pos 'org-linked-text)))
6557 (throw 'match t))
6559 (save-excursion
6560 (when (or (org-in-regexp org-angle-link-re)
6561 (org-in-regexp org-plain-link-re))
6562 (setq type (match-string 1) path (match-string 2))
6563 (throw 'match t)))
6564 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
6565 (setq type "tree-match"
6566 path (match-string 1))
6567 (throw 'match t))
6568 (save-excursion
6569 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
6570 (setq type "tags"
6571 path (match-string 1))
6572 (while (string-match ":" path)
6573 (setq path (replace-match "+" t t path)))
6574 (throw 'match t))))
6575 (unless path
6576 (error "No link found"))
6577 ;; Remove any trailing spaces in path
6578 (if (string-match " +\\'" path)
6579 (setq path (replace-match "" t t path)))
6581 (cond
6583 ((assoc type org-link-protocols)
6584 (funcall (nth 1 (assoc type org-link-protocols)) path))
6586 ((equal type "mailto")
6587 (let ((cmd (car org-link-mailto-program))
6588 (args (cdr org-link-mailto-program)) args1
6589 (address path) (subject "") a)
6590 (if (string-match "\\(.*\\)::\\(.*\\)" path)
6591 (setq address (match-string 1 path)
6592 subject (org-link-escape (match-string 2 path))))
6593 (while args
6594 (cond
6595 ((not (stringp (car args))) (push (pop args) args1))
6596 (t (setq a (pop args))
6597 (if (string-match "%a" a)
6598 (setq a (replace-match address t t a)))
6599 (if (string-match "%s" a)
6600 (setq a (replace-match subject t t a)))
6601 (push a args1))))
6602 (apply cmd (nreverse args1))))
6604 ((member type '("http" "https" "ftp" "news"))
6605 (browse-url (concat type ":" (org-link-escape
6606 path org-link-escape-chars-browser))))
6608 ((member type '("message"))
6609 (browse-url (concat type ":" path)))
6611 ((string= type "tags")
6612 (org-tags-view in-emacs path))
6613 ((string= type "thisfile")
6614 (if in-emacs
6615 (switch-to-buffer-other-window
6616 (org-get-buffer-for-internal-link (current-buffer)))
6617 (org-mark-ring-push))
6618 (let ((cmd `(org-link-search
6619 ,path
6620 ,(cond ((equal in-emacs '(4)) 'occur)
6621 ((equal in-emacs '(16)) 'org-occur)
6622 (t nil))
6623 ,pos)))
6624 (condition-case nil (eval cmd)
6625 (error (progn (widen) (eval cmd))))))
6627 ((string= type "tree-match")
6628 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
6630 ((string= type "file")
6631 (if (string-match "::\\([0-9]+\\)\\'" path)
6632 (setq line (string-to-number (match-string 1 path))
6633 path (substring path 0 (match-beginning 0)))
6634 (if (string-match "::\\(.+\\)\\'" path)
6635 (setq search (match-string 1 path)
6636 path (substring path 0 (match-beginning 0)))))
6637 (if (string-match "[*?{]" (file-name-nondirectory path))
6638 (dired path)
6639 (org-open-file path in-emacs line search)))
6641 ((string= type "news")
6642 (require 'org-gnus)
6643 (org-gnus-follow-link path))
6645 ((string= type "shell")
6646 (let ((cmd path))
6647 (if (or (not org-confirm-shell-link-function)
6648 (funcall org-confirm-shell-link-function
6649 (format "Execute \"%s\" in shell? "
6650 (org-add-props cmd nil
6651 'face 'org-warning))))
6652 (progn
6653 (message "Executing %s" cmd)
6654 (shell-command cmd))
6655 (error "Abort"))))
6657 ((string= type "elisp")
6658 (let ((cmd path))
6659 (if (or (not org-confirm-elisp-link-function)
6660 (funcall org-confirm-elisp-link-function
6661 (format "Execute \"%s\" as elisp? "
6662 (org-add-props cmd nil
6663 'face 'org-warning))))
6664 (message "%s => %s" cmd (eval (read cmd)))
6665 (error "Abort"))))
6668 (browse-url-at-point)))))
6669 (move-marker org-open-link-marker nil)
6670 (run-hook-with-args 'org-follow-link-hook))
6672 ;;;; Time estimates
6674 (defun org-get-effort (&optional pom)
6675 "Get the effort estimate for the current entry."
6676 (org-entry-get pom org-effort-property))
6678 ;;; File search
6680 (defvar org-create-file-search-functions nil
6681 "List of functions to construct the right search string for a file link.
6682 These functions are called in turn with point at the location to
6683 which the link should point.
6685 A function in the hook should first test if it would like to
6686 handle this file type, for example by checking the major-mode or
6687 the file extension. If it decides not to handle this file, it
6688 should just return nil to give other functions a chance. If it
6689 does handle the file, it must return the search string to be used
6690 when following the link. The search string will be part of the
6691 file link, given after a double colon, and `org-open-at-point'
6692 will automatically search for it. If special measures must be
6693 taken to make the search successful, another function should be
6694 added to the companion hook `org-execute-file-search-functions',
6695 which see.
6697 A function in this hook may also use `setq' to set the variable
6698 `description' to provide a suggestion for the descriptive text to
6699 be used for this link when it gets inserted into an Org-mode
6700 buffer with \\[org-insert-link].")
6702 (defvar org-execute-file-search-functions nil
6703 "List of functions to execute a file search triggered by a link.
6705 Functions added to this hook must accept a single argument, the
6706 search string that was part of the file link, the part after the
6707 double colon. The function must first check if it would like to
6708 handle this search, for example by checking the major-mode or the
6709 file extension. If it decides not to handle this search, it
6710 should just return nil to give other functions a chance. If it
6711 does handle the search, it must return a non-nil value to keep
6712 other functions from trying.
6714 Each function can access the current prefix argument through the
6715 variable `current-prefix-argument'. Note that a single prefix is
6716 used to force opening a link in Emacs, so it may be good to only
6717 use a numeric or double prefix to guide the search function.
6719 In case this is needed, a function in this hook can also restore
6720 the window configuration before `org-open-at-point' was called using:
6722 (set-window-configuration org-window-config-before-follow-link)")
6724 (defun org-link-search (s &optional type avoid-pos)
6725 "Search for a link search option.
6726 If S is surrounded by forward slashes, it is interpreted as a
6727 regular expression. In org-mode files, this will create an `org-occur'
6728 sparse tree. In ordinary files, `occur' will be used to list matches.
6729 If the current buffer is in `dired-mode', grep will be used to search
6730 in all files. If AVOID-POS is given, ignore matches near that position."
6731 (let ((case-fold-search t)
6732 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
6733 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
6734 (append '(("") (" ") ("\t") ("\n"))
6735 org-emphasis-alist)
6736 "\\|") "\\)"))
6737 (pos (point))
6738 (pre nil) (post nil)
6739 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
6740 (cond
6741 ;; First check if there are any special
6742 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
6743 ;; Now try the builtin stuff
6744 ((save-excursion
6745 (goto-char (point-min))
6746 (and
6747 (re-search-forward
6748 (concat "<<" (regexp-quote s0) ">>") nil t)
6749 (setq type 'dedicated
6750 pos (match-beginning 0))))
6751 ;; There is an exact target for this
6752 (goto-char pos))
6753 ((string-match "^/\\(.*\\)/$" s)
6754 ;; A regular expression
6755 (cond
6756 ((org-mode-p)
6757 (org-occur (match-string 1 s)))
6758 ;;((eq major-mode 'dired-mode)
6759 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
6760 (t (org-do-occur (match-string 1 s)))))
6762 ;; A normal search strings
6763 (when (equal (string-to-char s) ?*)
6764 ;; Anchor on headlines, post may include tags.
6765 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
6766 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
6767 s (substring s 1)))
6768 (remove-text-properties
6769 0 (length s)
6770 '(face nil mouse-face nil keymap nil fontified nil) s)
6771 ;; Make a series of regular expressions to find a match
6772 (setq words (org-split-string s "[ \n\r\t]+")
6774 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
6775 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
6776 "\\)" markers)
6777 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
6778 re2a (concat "[ \t\r\n]" re2a_)
6779 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
6780 re4 (concat "[^a-zA-Z_]" re4_)
6782 re1 (concat pre re2 post)
6783 re3 (concat pre (if pre re4_ re4) post)
6784 re5 (concat pre ".*" re4)
6785 re2 (concat pre re2)
6786 re2a (concat pre (if pre re2a_ re2a))
6787 re4 (concat pre (if pre re4_ re4))
6788 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
6789 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
6790 re5 "\\)"
6792 (cond
6793 ((eq type 'org-occur) (org-occur reall))
6794 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
6795 (t (goto-char (point-min))
6796 (setq type 'fuzzy)
6797 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
6798 (org-search-not-self 1 re1 nil t)
6799 (org-search-not-self 1 re2 nil t)
6800 (org-search-not-self 1 re2a nil t)
6801 (org-search-not-self 1 re3 nil t)
6802 (org-search-not-self 1 re4 nil t)
6803 (org-search-not-self 1 re5 nil t)
6805 (goto-char (match-beginning 1))
6806 (goto-char pos)
6807 (error "No match")))))
6809 ;; Normal string-search
6810 (goto-char (point-min))
6811 (if (search-forward s nil t)
6812 (goto-char (match-beginning 0))
6813 (error "No match"))))
6814 (and (org-mode-p) (org-show-context 'link-search))
6815 type))
6817 (defun org-search-not-self (group &rest args)
6818 "Execute `re-search-forward', but only accept matches that do not
6819 enclose the position of `org-open-link-marker'."
6820 (let ((m org-open-link-marker))
6821 (catch 'exit
6822 (while (apply 're-search-forward args)
6823 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
6824 (goto-char (match-end group))
6825 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
6826 (> (match-beginning 0) (marker-position m))
6827 (< (match-end 0) (marker-position m)))
6828 (save-match-data
6829 (or (not (org-in-regexp
6830 org-bracket-link-analytic-regexp 1))
6831 (not (match-end 4)) ; no description
6832 (and (<= (match-beginning 4) (point))
6833 (>= (match-end 4) (point))))))
6834 (throw 'exit (point))))))))
6836 (defun org-get-buffer-for-internal-link (buffer)
6837 "Return a buffer to be used for displaying the link target of internal links."
6838 (cond
6839 ((not org-display-internal-link-with-indirect-buffer)
6840 buffer)
6841 ((string-match "(Clone)$" (buffer-name buffer))
6842 (message "Buffer is already a clone, not making another one")
6843 ;; we also do not modify visibility in this case
6844 buffer)
6845 (t ; make a new indirect buffer for displaying the link
6846 (let* ((bn (buffer-name buffer))
6847 (ibn (concat bn "(Clone)"))
6848 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
6849 (with-current-buffer ib (org-overview))
6850 ib))))
6852 (defun org-do-occur (regexp &optional cleanup)
6853 "Call the Emacs command `occur'.
6854 If CLEANUP is non-nil, remove the printout of the regular expression
6855 in the *Occur* buffer. This is useful if the regex is long and not useful
6856 to read."
6857 (occur regexp)
6858 (when cleanup
6859 (let ((cwin (selected-window)) win beg end)
6860 (when (setq win (get-buffer-window "*Occur*"))
6861 (select-window win))
6862 (goto-char (point-min))
6863 (when (re-search-forward "match[a-z]+" nil t)
6864 (setq beg (match-end 0))
6865 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
6866 (setq end (1- (match-beginning 0)))))
6867 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
6868 (goto-char (point-min))
6869 (select-window cwin))))
6871 ;;; The mark ring for links jumps
6873 (defvar org-mark-ring nil
6874 "Mark ring for positions before jumps in Org-mode.")
6875 (defvar org-mark-ring-last-goto nil
6876 "Last position in the mark ring used to go back.")
6877 ;; Fill and close the ring
6878 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
6879 (loop for i from 1 to org-mark-ring-length do
6880 (push (make-marker) org-mark-ring))
6881 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
6882 org-mark-ring)
6884 (defun org-mark-ring-push (&optional pos buffer)
6885 "Put the current position or POS into the mark ring and rotate it."
6886 (interactive)
6887 (setq pos (or pos (point)))
6888 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
6889 (move-marker (car org-mark-ring)
6890 (or pos (point))
6891 (or buffer (current-buffer)))
6892 (message "%s"
6893 (substitute-command-keys
6894 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
6896 (defun org-mark-ring-goto (&optional n)
6897 "Jump to the previous position in the mark ring.
6898 With prefix arg N, jump back that many stored positions. When
6899 called several times in succession, walk through the entire ring.
6900 Org-mode commands jumping to a different position in the current file,
6901 or to another Org-mode file, automatically push the old position
6902 onto the ring."
6903 (interactive "p")
6904 (let (p m)
6905 (if (eq last-command this-command)
6906 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
6907 (setq p org-mark-ring))
6908 (setq org-mark-ring-last-goto p)
6909 (setq m (car p))
6910 (switch-to-buffer (marker-buffer m))
6911 (goto-char m)
6912 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
6914 (defun org-remove-angle-brackets (s)
6915 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
6916 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
6918 (defun org-add-angle-brackets (s)
6919 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
6920 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
6922 (defun org-remove-double-quotes (s)
6923 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
6924 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
6927 ;;; Following specific links
6929 (defun org-follow-timestamp-link ()
6930 (cond
6931 ((org-at-date-range-p t)
6932 (let ((org-agenda-start-on-weekday)
6933 (t1 (match-string 1))
6934 (t2 (match-string 2)))
6935 (setq t1 (time-to-days (org-time-string-to-time t1))
6936 t2 (time-to-days (org-time-string-to-time t2)))
6937 (org-agenda-list nil t1 (1+ (- t2 t1)))))
6938 ((org-at-timestamp-p t)
6939 (org-agenda-list nil (time-to-days (org-time-string-to-time
6940 (substring (match-string 1) 0 10)))
6942 (t (error "This should not happen"))))
6945 ;;; Following file links
6946 (defvar org-wait nil)
6947 (defun org-open-file (path &optional in-emacs line search)
6948 "Open the file at PATH.
6949 First, this expands any special file name abbreviations. Then the
6950 configuration variable `org-file-apps' is checked if it contains an
6951 entry for this file type, and if yes, the corresponding command is launched.
6952 If no application is found, Emacs simply visits the file.
6953 With optional argument IN-EMACS, Emacs will visit the file.
6954 Optional LINE specifies a line to go to, optional SEARCH a string to
6955 search for. If LINE or SEARCH is given, the file will always be
6956 opened in Emacs.
6957 If the file does not exist, an error is thrown."
6958 (setq in-emacs (or in-emacs line search))
6959 (let* ((file (if (equal path "")
6960 buffer-file-name
6961 (substitute-in-file-name (expand-file-name path))))
6962 (apps (append org-file-apps (org-default-apps)))
6963 (remp (and (assq 'remote apps) (org-file-remote-p file)))
6964 (dirp (if remp nil (file-directory-p file)))
6965 (file (if (and dirp org-open-directory-means-index-dot-org)
6966 (concat (file-name-as-directory file) "index.org")
6967 file))
6968 (dfile (downcase file))
6969 (old-buffer (current-buffer))
6970 (old-pos (point))
6971 (old-mode major-mode)
6972 ext cmd)
6973 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
6974 (setq ext (match-string 1 dfile))
6975 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
6976 (setq ext (match-string 1 dfile))))
6977 (if in-emacs
6978 (setq cmd 'emacs)
6979 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
6980 (and dirp (cdr (assoc 'directory apps)))
6981 (cdr (assoc ext apps))
6982 (cdr (assoc t apps)))))
6983 (when (eq cmd 'mailcap)
6984 (require 'mailcap)
6985 (mailcap-parse-mailcaps)
6986 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
6987 (command (mailcap-mime-info mime-type)))
6988 (if (stringp command)
6989 (setq cmd command)
6990 (setq cmd 'emacs))))
6991 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
6992 (not (file-exists-p file))
6993 (not org-open-non-existing-files))
6994 (error "No such file: %s" file))
6995 (cond
6996 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
6997 ;; Remove quotes around the file name - we'll use shell-quote-argument.
6998 (while (string-match "['\"]%s['\"]" cmd)
6999 (setq cmd (replace-match "%s" t t cmd)))
7000 (while (string-match "%s" cmd)
7001 (setq cmd (replace-match
7002 (save-match-data
7003 (shell-quote-argument
7004 (convert-standard-filename file)))
7005 t t cmd)))
7006 (save-window-excursion
7007 (start-process-shell-command cmd nil cmd)
7008 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
7010 ((or (stringp cmd)
7011 (eq cmd 'emacs))
7012 (funcall (cdr (assq 'file org-link-frame-setup)) file)
7013 (widen)
7014 (if line (goto-line line)
7015 (if search (org-link-search search))))
7016 ((consp cmd)
7017 (let ((file (convert-standard-filename file)))
7018 (eval cmd)))
7019 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7020 (and (org-mode-p) (eq old-mode 'org-mode)
7021 (or (not (equal old-buffer (current-buffer)))
7022 (not (equal old-pos (point))))
7023 (org-mark-ring-push old-pos old-buffer))))
7025 (defun org-default-apps ()
7026 "Return the default applications for this operating system."
7027 (cond
7028 ((eq system-type 'darwin)
7029 org-file-apps-defaults-macosx)
7030 ((eq system-type 'windows-nt)
7031 org-file-apps-defaults-windowsnt)
7032 (t org-file-apps-defaults-gnu)))
7034 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
7035 (defun org-file-remote-p (file)
7036 "Test whether FILE specifies a location on a remote system.
7037 Return non-nil if the location is indeed remote.
7039 For example, the filename \"/user@host:/foo\" specifies a location
7040 on the system \"/user@host:\"."
7041 (cond ((fboundp 'file-remote-p)
7042 (file-remote-p file))
7043 ((fboundp 'tramp-handle-file-remote-p)
7044 (tramp-handle-file-remote-p file))
7045 ((and (boundp 'ange-ftp-name-format)
7046 (string-match (car ange-ftp-name-format) file))
7048 (t nil)))
7051 ;;;; Refiling
7053 (defun org-get-org-file ()
7054 "Read a filename, with default directory `org-directory'."
7055 (let ((default (or org-default-notes-file remember-data-file)))
7056 (read-file-name (format "File name [%s]: " default)
7057 (file-name-as-directory org-directory)
7058 default)))
7060 (defun org-notes-order-reversed-p ()
7061 "Check if the current file should receive notes in reversed order."
7062 (cond
7063 ((not org-reverse-note-order) nil)
7064 ((eq t org-reverse-note-order) t)
7065 ((not (listp org-reverse-note-order)) nil)
7066 (t (catch 'exit
7067 (let ((all org-reverse-note-order)
7068 entry)
7069 (while (setq entry (pop all))
7070 (if (string-match (car entry) buffer-file-name)
7071 (throw 'exit (cdr entry))))
7072 nil)))))
7074 (defvar org-refile-target-table nil
7075 "The list of refile targets, created by `org-refile'.")
7077 (defvar org-agenda-new-buffers nil
7078 "Buffers created to visit agenda files.")
7080 (defun org-get-refile-targets (&optional default-buffer)
7081 "Produce a table with refile targets."
7082 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
7083 targets txt re files f desc descre)
7084 (with-current-buffer (or default-buffer (current-buffer))
7085 (while (setq entry (pop entries))
7086 (setq files (car entry) desc (cdr entry))
7087 (cond
7088 ((null files) (setq files (list (current-buffer))))
7089 ((eq files 'org-agenda-files)
7090 (setq files (org-agenda-files 'unrestricted)))
7091 ((and (symbolp files) (fboundp files))
7092 (setq files (funcall files)))
7093 ((and (symbolp files) (boundp files))
7094 (setq files (symbol-value files))))
7095 (if (stringp files) (setq files (list files)))
7096 (cond
7097 ((eq (car desc) :tag)
7098 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
7099 ((eq (car desc) :todo)
7100 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
7101 ((eq (car desc) :regexp)
7102 (setq descre (cdr desc)))
7103 ((eq (car desc) :level)
7104 (setq descre (concat "^\\*\\{" (number-to-string
7105 (if org-odd-levels-only
7106 (1- (* 2 (cdr desc)))
7107 (cdr desc)))
7108 "\\}[ \t]")))
7109 ((eq (car desc) :maxlevel)
7110 (setq descre (concat "^\\*\\{1," (number-to-string
7111 (if org-odd-levels-only
7112 (1- (* 2 (cdr desc)))
7113 (cdr desc)))
7114 "\\}[ \t]")))
7115 (t (error "Bad refiling target description %s" desc)))
7116 (while (setq f (pop files))
7117 (save-excursion
7118 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
7119 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
7120 (save-excursion
7121 (save-restriction
7122 (widen)
7123 (goto-char (point-min))
7124 (while (re-search-forward descre nil t)
7125 (goto-char (point-at-bol))
7126 (when (looking-at org-complex-heading-regexp)
7127 (setq txt (org-link-display-format (match-string 4))
7128 re (concat "^" (regexp-quote
7129 (buffer-substring (match-beginning 1)
7130 (match-end 4)))))
7131 (if (match-end 5) (setq re (concat re "[ \t]+"
7132 (regexp-quote
7133 (match-string 5)))))
7134 (setq re (concat re "[ \t]*$"))
7135 (when org-refile-use-outline-path
7136 (setq txt (mapconcat 'org-protect-slash
7137 (append
7138 (if (eq org-refile-use-outline-path 'file)
7139 (list (file-name-nondirectory
7140 (buffer-file-name (buffer-base-buffer))))
7141 (if (eq org-refile-use-outline-path 'full-file-path)
7142 (list (buffer-file-name (buffer-base-buffer)))))
7143 (org-get-outline-path)
7144 (list txt))
7145 "/")))
7146 (push (list txt f re (point)) targets))
7147 (goto-char (point-at-eol))))))))
7148 (nreverse targets))))
7150 (defun org-protect-slash (s)
7151 (while (string-match "/" s)
7152 (setq s (replace-match "\\" t t s)))
7155 (defun org-get-outline-path ()
7156 "Return the outline path to the current entry, as a list."
7157 (let (rtn)
7158 (save-excursion
7159 (while (org-up-heading-safe)
7160 (when (looking-at org-complex-heading-regexp)
7161 (push (org-match-string-no-properties 4) rtn)))
7162 rtn)))
7164 (defvar org-refile-history nil
7165 "History for refiling operations.")
7167 (defun org-refile (&optional goto default-buffer)
7168 "Move the entry at point to another heading.
7169 The list of target headings is compiled using the information in
7170 `org-refile-targets', which see. This list is created before each use
7171 and will therefore always be up-to-date.
7173 At the target location, the entry is filed as a subitem of the target heading.
7174 Depending on `org-reverse-note-order', the new subitem will either be the
7175 first of the last subitem.
7177 With prefix arg GOTO, the command will only visit the target location,
7178 not actually move anything.
7179 With a double prefix `C-u C-u', go to the location where the last refiling
7180 operation has put the subtree."
7181 (interactive "P")
7182 (let* ((cbuf (current-buffer))
7183 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7184 pos it nbuf file re level reversed)
7185 (if (equal goto '(16))
7186 (org-refile-goto-last-stored)
7187 (when (setq it (org-refile-get-location
7188 (if goto "Goto: " "Refile to: ") default-buffer))
7189 (setq file (nth 1 it)
7190 re (nth 2 it)
7191 pos (nth 3 it))
7192 (setq nbuf (or (find-buffer-visiting file)
7193 (find-file-noselect file)))
7194 (if goto
7195 (progn
7196 (switch-to-buffer nbuf)
7197 (goto-char pos)
7198 (org-show-context 'org-goto))
7199 (org-copy-subtree 1 nil t)
7200 (save-excursion
7201 (set-buffer (setq nbuf (or (find-buffer-visiting file)
7202 (find-file-noselect file))))
7203 (setq reversed (org-notes-order-reversed-p))
7204 (save-excursion
7205 (save-restriction
7206 (widen)
7207 (goto-char pos)
7208 (looking-at outline-regexp)
7209 (setq level (org-get-valid-level (funcall outline-level) 1))
7210 (goto-char
7211 (if reversed
7212 (or (outline-next-heading) (point-max))
7213 (or (save-excursion (outline-get-next-sibling))
7214 (org-end-of-subtree t t)
7215 (point-max))))
7216 (if (not (bolp)) (newline))
7217 (bookmark-set "org-refile-last-stored")
7218 (org-paste-subtree level))))
7219 (org-cut-subtree)
7220 (setq org-markers-to-move nil)
7221 (message "Entry refiled to \"%s\"" (car it)))))))
7223 (defun org-refile-goto-last-stored ()
7224 "Go to the location where the last refile was stored."
7225 (interactive)
7226 (bookmark-jump "org-refile-last-stored")
7227 (message "This is the location of the last refile"))
7229 (defun org-refile-get-location (&optional prompt default-buffer)
7230 "Prompt the user for a refile location, using PROMPT."
7231 (let ((org-refile-targets org-refile-targets)
7232 (org-refile-use-outline-path org-refile-use-outline-path))
7233 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
7234 (unless org-refile-target-table
7235 (error "No refile targets"))
7236 (let* ((cbuf (current-buffer))
7237 (cfunc (if org-refile-use-outline-path
7238 'org-olpath-completing-read
7239 'completing-read))
7240 (extra (if org-refile-use-outline-path "/" ""))
7241 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7242 (fname (and filename (file-truename filename)))
7243 (tbl (mapcar
7244 (lambda (x)
7245 (if (not (equal fname (file-truename (nth 1 x))))
7246 (cons (concat (car x) extra " ("
7247 (file-name-nondirectory (nth 1 x)) ")")
7248 (cdr x))
7249 (cons (concat (car x) extra) (cdr x))))
7250 org-refile-target-table))
7251 (completion-ignore-case t))
7252 (assoc (funcall cfunc prompt tbl nil t nil 'org-refile-history)
7253 tbl)))
7255 (defun org-olpath-completing-read (prompt collection &rest args)
7256 "Read an outline path like a file name."
7257 (let ((thetable collection))
7258 (apply
7259 'completing-read prompt
7260 (lambda (string predicate &optional flag)
7261 (let (rtn r s f (l (length string)))
7262 (cond
7263 ((eq flag nil)
7264 ;; try completion
7265 (try-completion string thetable))
7266 ((eq flag t)
7267 ;; all-completions
7268 (setq rtn (all-completions string thetable predicate))
7269 (mapcar
7270 (lambda (x)
7271 (setq r (substring x l))
7272 (if (string-match " ([^)]*)$" x)
7273 (setq f (match-string 0 x))
7274 (setq f ""))
7275 (if (string-match "/" r)
7276 (concat string (substring r 0 (match-end 0)) f)
7278 rtn))
7279 ((eq flag 'lambda)
7280 ;; exact match?
7281 (assoc string thetable)))
7283 args)))
7285 ;;;; Dynamic blocks
7287 (defun org-find-dblock (name)
7288 "Find the first dynamic block with name NAME in the buffer.
7289 If not found, stay at current position and return nil."
7290 (let (pos)
7291 (save-excursion
7292 (goto-char (point-min))
7293 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
7294 nil t)
7295 (match-beginning 0))))
7296 (if pos (goto-char pos))
7297 pos))
7299 (defconst org-dblock-start-re
7300 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
7301 "Matches the startline of a dynamic block, with parameters.")
7303 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
7304 "Matches the end of a dyhamic block.")
7306 (defun org-create-dblock (plist)
7307 "Create a dynamic block section, with parameters taken from PLIST.
7308 PLIST must containe a :name entry which is used as name of the block."
7309 (unless (bolp) (newline))
7310 (let ((name (plist-get plist :name)))
7311 (insert "#+BEGIN: " name)
7312 (while plist
7313 (if (eq (car plist) :name)
7314 (setq plist (cddr plist))
7315 (insert " " (prin1-to-string (pop plist)))))
7316 (insert "\n\n#+END:\n")
7317 (beginning-of-line -2)))
7319 (defun org-prepare-dblock ()
7320 "Prepare dynamic block for refresh.
7321 This empties the block, puts the cursor at the insert position and returns
7322 the property list including an extra property :name with the block name."
7323 (unless (looking-at org-dblock-start-re)
7324 (error "Not at a dynamic block"))
7325 (let* ((begdel (1+ (match-end 0)))
7326 (name (org-no-properties (match-string 1)))
7327 (params (append (list :name name)
7328 (read (concat "(" (match-string 3) ")")))))
7329 (unless (re-search-forward org-dblock-end-re nil t)
7330 (error "Dynamic block not terminated"))
7331 (setq params
7332 (append params
7333 (list :content (buffer-substring
7334 begdel (match-beginning 0)))))
7335 (delete-region begdel (match-beginning 0))
7336 (goto-char begdel)
7337 (open-line 1)
7338 params))
7340 (defun org-map-dblocks (&optional command)
7341 "Apply COMMAND to all dynamic blocks in the current buffer.
7342 If COMMAND is not given, use `org-update-dblock'."
7343 (let ((cmd (or command 'org-update-dblock))
7344 pos)
7345 (save-excursion
7346 (goto-char (point-min))
7347 (while (re-search-forward org-dblock-start-re nil t)
7348 (goto-char (setq pos (match-beginning 0)))
7349 (condition-case nil
7350 (funcall cmd)
7351 (error (message "Error during update of dynamic block")))
7352 (goto-char pos)
7353 (unless (re-search-forward org-dblock-end-re nil t)
7354 (error "Dynamic block not terminated"))))))
7356 (defun org-dblock-update (&optional arg)
7357 "User command for updating dynamic blocks.
7358 Update the dynamic block at point. With prefix ARG, update all dynamic
7359 blocks in the buffer."
7360 (interactive "P")
7361 (if arg
7362 (org-update-all-dblocks)
7363 (or (looking-at org-dblock-start-re)
7364 (org-beginning-of-dblock))
7365 (org-update-dblock)))
7367 (defun org-update-dblock ()
7368 "Update the dynamic block at point
7369 This means to empty the block, parse for parameters and then call
7370 the correct writing function."
7371 (save-window-excursion
7372 (let* ((pos (point))
7373 (line (org-current-line))
7374 (params (org-prepare-dblock))
7375 (name (plist-get params :name))
7376 (cmd (intern (concat "org-dblock-write:" name))))
7377 (message "Updating dynamic block `%s' at line %d..." name line)
7378 (funcall cmd params)
7379 (message "Updating dynamic block `%s' at line %d...done" name line)
7380 (goto-char pos))))
7382 (defun org-beginning-of-dblock ()
7383 "Find the beginning of the dynamic block at point.
7384 Error if there is no scuh block at point."
7385 (let ((pos (point))
7386 beg)
7387 (end-of-line 1)
7388 (if (and (re-search-backward org-dblock-start-re nil t)
7389 (setq beg (match-beginning 0))
7390 (re-search-forward org-dblock-end-re nil t)
7391 (> (match-end 0) pos))
7392 (goto-char beg)
7393 (goto-char pos)
7394 (error "Not in a dynamic block"))))
7396 (defun org-update-all-dblocks ()
7397 "Update all dynamic blocks in the buffer.
7398 This function can be used in a hook."
7399 (when (org-mode-p)
7400 (org-map-dblocks 'org-update-dblock)))
7403 ;;;; Completion
7405 (defconst org-additional-option-like-keywords
7406 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
7407 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
7408 "BEGIN_EXAMPLE" "END_EXAMPLE"
7409 "BEGIN_QUOTE" "END_QUOTE"
7410 "BEGIN_VERSE" "END_VERSE"
7411 "BEGIN_SRC" "END_SRC"))
7413 (defcustom org-structure-template-alist
7415 ("s" "#+begin_src ?\n\n#+end_src"
7416 "<src lang=\"?\">\n\n</src>")
7417 ("e" "#+begin_example\n?\n#+end_example"
7418 "<example>\n?\n</example>")
7419 ("q" "#+begin_quote\n?\n#+end_quote"
7420 "<quote>\n?\n</quote>")
7421 ("v" "#+begin_verse\n?\n#+end_verse"
7422 "<verse>\n?\n/verse>")
7423 ("l" "#+begin_latex\n?\n#+end_latex"
7424 "<literal style=\"latex\">\n?\n</literal>")
7425 ("L" "#+latex: "
7426 "<literal style=\"latex\">?</literal>")
7427 ("h" "#+begin_html\n?\n#+end_html"
7428 "<literal style=\"html\">\n?\n</literal>")
7429 ("H" "#+html: "
7430 "<literal style=\"html\">?</literal>")
7431 ("a" "#+begin_ascii\n?\n#+end_ascii")
7432 ("A" "#+ascii: ")
7433 ("i" "#+include %file ?"
7434 "<include file=%file markup=\"?\">")
7436 "Structure completion elements.
7437 This is a list of abbreviation keys and values. The value gets inserted
7438 it you type @samp{.} followed by the key and then the completion key,
7439 usually `M-TAB'. %file will be replaced by a file name after prompting
7440 for the file uning completion.
7441 There are two templates for each key, the first uses the original Org syntax,
7442 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
7443 the default when the /org-mtags.el/ module has been loaded. See also the
7444 variable `org-mtags-prefere-muse-templates'.
7445 This is an experimental feature, it is undecided if it is going to stay in."
7446 :group 'org-completion
7447 :type '(repeat
7448 (string :tag "Key")
7449 (string :tag "Template")
7450 (string :tag "Muse Template")))
7452 (defun org-try-structure-completion ()
7453 "Try to complete a structure template before point.
7454 This looks for strings like \"<e\" on an otherwise empty line and
7455 expands them."
7456 (let ((l (buffer-substring (point-at-bol) (point)))
7458 (when (and (looking-at "[ \t]*$")
7459 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
7460 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
7461 (org-complete-expand-structure-template (+ -1 (point-at-bol)
7462 (match-beginning 1)) a)
7463 t)))
7465 (defun org-complete-expand-structure-template (start cell)
7466 "Expand a structure template."
7467 (let* ((musep (org-bound-and-true-p org-mtags-prefere-muse-templates))
7468 (rpl (nth (if musep 2 1) cell)))
7469 (delete-region start (point))
7470 (when (string-match "\\`#\\+" rpl)
7471 (cond
7472 ((bolp))
7473 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
7474 (delete-region (point-at-bol) (point)))
7475 (t (newline))))
7476 (setq start (point))
7477 (if (string-match "%file" rpl)
7478 (setq rpl (replace-match
7479 (concat
7480 "\""
7481 (save-match-data
7482 (abbreviate-file-name (read-file-name "Include file: ")))
7483 "\"")
7484 t t rpl)))
7485 (insert rpl)
7486 (if (re-search-backward "\\?" start t) (delete-char 1))))
7489 (defun org-complete (&optional arg)
7490 "Perform completion on word at point.
7491 At the beginning of a headline, this completes TODO keywords as given in
7492 `org-todo-keywords'.
7493 If the current word is preceded by a backslash, completes the TeX symbols
7494 that are supported for HTML support.
7495 If the current word is preceded by \"#+\", completes special words for
7496 setting file options.
7497 In the line after \"#+STARTUP:, complete valid keywords.\"
7498 At all other locations, this simply calls the value of
7499 `org-completion-fallback-command'."
7500 (interactive "P")
7501 (org-without-partial-completion
7502 (catch 'exit
7503 (let* ((a nil)
7504 (end (point))
7505 (beg1 (save-excursion
7506 (skip-chars-backward (org-re "[:alnum:]_@"))
7507 (point)))
7508 (beg (save-excursion
7509 (skip-chars-backward "a-zA-Z0-9_:$")
7510 (point)))
7511 (confirm (lambda (x) (stringp (car x))))
7512 (searchhead (equal (char-before beg) ?*))
7513 (struct
7514 (when (and (member (char-before beg1) '(?. ?<))
7515 (setq a (assoc (buffer-substring beg1 (point))
7516 org-structure-template-alist)))
7517 (org-complete-expand-structure-template (1- beg1) a)
7518 (throw 'exit t)))
7519 (tag (and (equal (char-before beg1) ?:)
7520 (equal (char-after (point-at-bol)) ?*)))
7521 (prop (and (equal (char-before beg1) ?:)
7522 (not (equal (char-after (point-at-bol)) ?*))))
7523 (texp (equal (char-before beg) ?\\))
7524 (link (equal (char-before beg) ?\[))
7525 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
7526 beg)
7527 "#+"))
7528 (startup (string-match "^#\\+STARTUP:.*"
7529 (buffer-substring (point-at-bol) (point))))
7530 (completion-ignore-case opt)
7531 (type nil)
7532 (tbl nil)
7533 (table (cond
7534 (opt
7535 (setq type :opt)
7536 (require 'org-exp)
7537 (append
7538 (mapcar
7539 (lambda (x)
7540 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
7541 (cons (match-string 2 x) (match-string 1 x)))
7542 (org-split-string (org-get-current-options) "\n"))
7543 (mapcar 'list org-additional-option-like-keywords)))
7544 (startup
7545 (setq type :startup)
7546 org-startup-options)
7547 (link (append org-link-abbrev-alist-local
7548 org-link-abbrev-alist))
7549 (texp
7550 (setq type :tex)
7551 org-html-entities)
7552 ((string-match "\\`\\*+[ \t]+\\'"
7553 (buffer-substring (point-at-bol) beg))
7554 (setq type :todo)
7555 (mapcar 'list org-todo-keywords-1))
7556 (searchhead
7557 (setq type :searchhead)
7558 (save-excursion
7559 (goto-char (point-min))
7560 (while (re-search-forward org-todo-line-regexp nil t)
7561 (push (list
7562 (org-make-org-heading-search-string
7563 (match-string 3) t))
7564 tbl)))
7565 tbl)
7566 (tag (setq type :tag beg beg1)
7567 (or org-tag-alist (org-get-buffer-tags)))
7568 (prop (setq type :prop beg beg1)
7569 (mapcar 'list (org-buffer-property-keys nil t t)))
7570 (t (progn
7571 (call-interactively org-completion-fallback-command)
7572 (throw 'exit nil)))))
7573 (pattern (buffer-substring-no-properties beg end))
7574 (completion (try-completion pattern table confirm)))
7575 (cond ((eq completion t)
7576 (if (not (assoc (upcase pattern) table))
7577 (message "Already complete")
7578 (if (and (equal type :opt)
7579 (not (member (car (assoc (upcase pattern) table))
7580 org-additional-option-like-keywords)))
7581 (insert (substring (cdr (assoc (upcase pattern) table))
7582 (length pattern)))
7583 (if (memq type '(:tag :prop)) (insert ":")))))
7584 ((null completion)
7585 (message "Can't find completion for \"%s\"" pattern)
7586 (ding))
7587 ((not (string= pattern completion))
7588 (delete-region beg end)
7589 (if (string-match " +$" completion)
7590 (setq completion (replace-match "" t t completion)))
7591 (insert completion)
7592 (if (get-buffer-window "*Completions*")
7593 (delete-window (get-buffer-window "*Completions*")))
7594 (if (assoc completion table)
7595 (if (eq type :todo) (insert " ")
7596 (if (memq type '(:tag :prop)) (insert ":"))))
7597 (if (and (equal type :opt) (assoc completion table))
7598 (message "%s" (substitute-command-keys
7599 "Press \\[org-complete] again to insert example settings"))))
7601 (message "Making completion list...")
7602 (let ((list (sort (all-completions pattern table confirm)
7603 'string<)))
7604 (with-output-to-temp-buffer "*Completions*"
7605 (condition-case nil
7606 ;; Protection needed for XEmacs and emacs 21
7607 (display-completion-list list pattern)
7608 (error (display-completion-list list)))))
7609 (message "Making completion list...%s" "done")))))))
7611 ;;;; TODO, DEADLINE, Comments
7613 (defun org-toggle-comment ()
7614 "Change the COMMENT state of an entry."
7615 (interactive)
7616 (save-excursion
7617 (org-back-to-heading)
7618 (let (case-fold-search)
7619 (if (looking-at (concat outline-regexp
7620 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
7621 (replace-match "" t t nil 1)
7622 (if (looking-at outline-regexp)
7623 (progn
7624 (goto-char (match-end 0))
7625 (insert org-comment-string " ")))))))
7627 (defvar org-last-todo-state-is-todo nil
7628 "This is non-nil when the last TODO state change led to a TODO state.
7629 If the last change removed the TODO tag or switched to DONE, then
7630 this is nil.")
7632 (defvar org-setting-tags nil) ; dynamically skiped
7634 (defun org-parse-local-options (string var)
7635 "Parse STRING for startup setting relevant for variable VAR."
7636 (let ((rtn (symbol-value var))
7637 e opts)
7638 (save-match-data
7639 (if (or (not string) (not (string-match "\\S-" string)))
7641 (setq opts (delq nil (mapcar (lambda (x)
7642 (setq e (assoc x org-startup-options))
7643 (if (eq (nth 1 e) var) e nil))
7644 (org-split-string string "[ \t]+"))))
7645 (if (not opts)
7647 (setq rtn nil)
7648 (while (setq e (pop opts))
7649 (if (not (nth 3 e))
7650 (setq rtn (nth 2 e))
7651 (if (not (listp rtn)) (setq rtn nil))
7652 (push (nth 2 e) rtn)))
7653 rtn)))))
7655 (defvar org-blocker-hook nil
7656 "Hook for functions that are allowed to block a state change.
7658 Each function gets as its single argument a property list, see
7659 `org-trigger-hook' for more information about this list.
7661 If any of the functions in this hook returns nil, the state change
7662 is blocked.")
7664 (defvar org-trigger-hook nil
7665 "Hook for functions that are triggered by a state change.
7667 Each function gets as its single argument a property list with at least
7668 the following elements:
7670 (:type type-of-change :position pos-at-entry-start
7671 :from old-state :to new-state)
7673 Depending on the type, more properties may be present.
7675 This mechanism is currently implemented for:
7677 TODO state changes
7678 ------------------
7679 :type todo-state-change
7680 :from previous state (keyword as a string), or nil
7681 :to new state (keyword as a string), or nil")
7684 (defun org-todo (&optional arg)
7685 "Change the TODO state of an item.
7686 The state of an item is given by a keyword at the start of the heading,
7687 like
7688 *** TODO Write paper
7689 *** DONE Call mom
7691 The different keywords are specified in the variable `org-todo-keywords'.
7692 By default the available states are \"TODO\" and \"DONE\".
7693 So for this example: when the item starts with TODO, it is changed to DONE.
7694 When it starts with DONE, the DONE is removed. And when neither TODO nor
7695 DONE are present, add TODO at the beginning of the heading.
7697 With C-u prefix arg, use completion to determine the new state.
7698 With numeric prefix arg, switch to that state.
7700 For calling through lisp, arg is also interpreted in the following way:
7701 'none -> empty state
7702 \"\"(empty string) -> switch to empty state
7703 'done -> switch to DONE
7704 'nextset -> switch to the next set of keywords
7705 'previousset -> switch to the previous set of keywords
7706 \"WAITING\" -> switch to the specified keyword, but only if it
7707 really is a member of `org-todo-keywords'."
7708 (interactive "P")
7709 (save-excursion
7710 (catch 'exit
7711 (org-back-to-heading)
7712 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
7713 (or (looking-at (concat " +" org-todo-regexp " *"))
7714 (looking-at " *"))
7715 (let* ((match-data (match-data))
7716 (startpos (point-at-bol))
7717 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
7718 (org-log-done org-log-done)
7719 (org-log-repeat org-log-repeat)
7720 (org-todo-log-states org-todo-log-states)
7721 (this (match-string 1))
7722 (hl-pos (match-beginning 0))
7723 (head (org-get-todo-sequence-head this))
7724 (ass (assoc head org-todo-kwd-alist))
7725 (interpret (nth 1 ass))
7726 (done-word (nth 3 ass))
7727 (final-done-word (nth 4 ass))
7728 (last-state (or this ""))
7729 (completion-ignore-case t)
7730 (member (member this org-todo-keywords-1))
7731 (tail (cdr member))
7732 (state (cond
7733 ((and org-todo-key-trigger
7734 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
7735 (and (not arg) org-use-fast-todo-selection
7736 (not (eq org-use-fast-todo-selection 'prefix)))))
7737 ;; Use fast selection
7738 (org-fast-todo-selection))
7739 ((and (equal arg '(4))
7740 (or (not org-use-fast-todo-selection)
7741 (not org-todo-key-trigger)))
7742 ;; Read a state with completion
7743 (completing-read "State: " (mapcar (lambda(x) (list x))
7744 org-todo-keywords-1)
7745 nil t))
7746 ((eq arg 'right)
7747 (if this
7748 (if tail (car tail) nil)
7749 (car org-todo-keywords-1)))
7750 ((eq arg 'left)
7751 (if (equal member org-todo-keywords-1)
7753 (if this
7754 (nth (- (length org-todo-keywords-1) (length tail) 2)
7755 org-todo-keywords-1)
7756 (org-last org-todo-keywords-1))))
7757 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
7758 (setq arg nil))) ; hack to fall back to cycling
7759 (arg
7760 ;; user or caller requests a specific state
7761 (cond
7762 ((equal arg "") nil)
7763 ((eq arg 'none) nil)
7764 ((eq arg 'done) (or done-word (car org-done-keywords)))
7765 ((eq arg 'nextset)
7766 (or (car (cdr (member head org-todo-heads)))
7767 (car org-todo-heads)))
7768 ((eq arg 'previousset)
7769 (let ((org-todo-heads (reverse org-todo-heads)))
7770 (or (car (cdr (member head org-todo-heads)))
7771 (car org-todo-heads))))
7772 ((car (member arg org-todo-keywords-1)))
7773 ((nth (1- (prefix-numeric-value arg))
7774 org-todo-keywords-1))))
7775 ((null member) (or head (car org-todo-keywords-1)))
7776 ((equal this final-done-word) nil) ;; -> make empty
7777 ((null tail) nil) ;; -> first entry
7778 ((eq interpret 'sequence)
7779 (car tail))
7780 ((memq interpret '(type priority))
7781 (if (eq this-command last-command)
7782 (car tail)
7783 (if (> (length tail) 0)
7784 (or done-word (car org-done-keywords))
7785 nil)))
7786 (t nil)))
7787 (next (if state (concat " " state " ") " "))
7788 (change-plist (list :type 'todo-state-change :from this :to state
7789 :position startpos))
7790 dolog now-done-p)
7791 (when org-blocker-hook
7792 (unless (save-excursion
7793 (save-match-data
7794 (run-hook-with-args-until-failure
7795 'org-blocker-hook change-plist)))
7796 (if (interactive-p)
7797 (error "TODO state change from %s to %s blocked" this state)
7798 ;; fail silently
7799 (message "TODO state change from %s to %s blocked" this state)
7800 (throw 'exit nil))))
7801 (store-match-data match-data)
7802 (replace-match next t t)
7803 (unless (pos-visible-in-window-p hl-pos)
7804 (message "TODO state changed to %s" (org-trim next)))
7805 (unless head
7806 (setq head (org-get-todo-sequence-head state)
7807 ass (assoc head org-todo-kwd-alist)
7808 interpret (nth 1 ass)
7809 done-word (nth 3 ass)
7810 final-done-word (nth 4 ass)))
7811 (when (memq arg '(nextset previousset))
7812 (message "Keyword-Set %d/%d: %s"
7813 (- (length org-todo-sets) -1
7814 (length (memq (assoc state org-todo-sets) org-todo-sets)))
7815 (length org-todo-sets)
7816 (mapconcat 'identity (assoc state org-todo-sets) " ")))
7817 (setq org-last-todo-state-is-todo
7818 (not (member state org-done-keywords)))
7819 (setq now-done-p (and (member state org-done-keywords)
7820 (not (member this org-done-keywords))))
7821 (and logging (org-local-logging logging))
7822 (when (and (or org-todo-log-states org-log-done)
7823 (not (memq arg '(nextset previousset))))
7824 ;; we need to look at recording a time and note
7825 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
7826 (nth 2 (assoc this org-todo-log-states))))
7827 (when (and state
7828 (member state org-not-done-keywords)
7829 (not (member this org-not-done-keywords)))
7830 ;; This is now a todo state and was not one before
7831 ;; If there was a CLOSED time stamp, get rid of it.
7832 (org-add-planning-info nil nil 'closed))
7833 (when (and now-done-p org-log-done)
7834 ;; It is now done, and it was not done before
7835 (org-add-planning-info 'closed (org-current-time))
7836 (if (and (not dolog) (eq 'note org-log-done))
7837 (org-add-log-setup 'done state 'findpos 'note)))
7838 (when (and state dolog)
7839 ;; This is a non-nil state, and we need to log it
7840 (org-add-log-setup 'state state 'findpos dolog)))
7841 ;; Fixup tag positioning
7842 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
7843 (when org-provide-todo-statistics
7844 (org-update-parent-todo-statistics))
7845 (run-hooks 'org-after-todo-state-change-hook)
7846 (if (and arg (not (member state org-done-keywords)))
7847 (setq head (org-get-todo-sequence-head state)))
7848 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
7849 ;; Do we need to trigger a repeat?
7850 (when now-done-p (org-auto-repeat-maybe state))
7851 ;; Fixup cursor location if close to the keyword
7852 (if (and (outline-on-heading-p)
7853 (not (bolp))
7854 (save-excursion (beginning-of-line 1)
7855 (looking-at org-todo-line-regexp))
7856 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
7857 (progn
7858 (goto-char (or (match-end 2) (match-end 1)))
7859 (just-one-space)))
7860 (when org-trigger-hook
7861 (save-excursion
7862 (run-hook-with-args 'org-trigger-hook change-plist)))))))
7864 (defun org-update-parent-todo-statistics ()
7865 "Update any statistics cookie in the parent of the current headline."
7866 (interactive)
7867 (let ((box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
7868 level (cnt-all 0) (cnt-done 0) is-percent kwd)
7869 (catch 'exit
7870 (save-excursion
7871 (setq level (org-up-heading-safe))
7872 (unless (and level
7873 (re-search-forward box-re (point-at-eol) t))
7874 (throw 'exit nil))
7875 (setq is-percent (match-end 2))
7876 (save-match-data
7877 (unless (outline-next-heading) (throw 'exit nil))
7878 (while (looking-at org-todo-line-regexp)
7879 (setq kwd (match-string 2))
7880 (and kwd (setq cnt-all (1+ cnt-all)))
7881 (and (member kwd org-done-keywords)
7882 (setq cnt-done (1+ cnt-done)))
7883 (condition-case nil
7884 (org-forward-same-level 1)
7885 (error (end-of-line 1)))))
7886 (replace-match
7887 (if is-percent
7888 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
7889 (format "[%d/%d]" cnt-done cnt-all)))
7890 (run-hook-with-args 'org-after-todo-statistics-hook
7891 cnt-done (- cnt-all cnt-done))))))
7893 (defvar org-after-todo-statistics-hook nil
7894 "Hook that is called after a TODO statistics cookie has been updated.
7895 Each function is called with two arguments: the number of not-done entries
7896 and the number of done entries.
7898 For example, the following function, when added to this hook, will switch
7899 an entry to DONE when all children are done, and back to TODO when new
7900 entries are set to a TODO status. Note that this hook is only called
7901 when there is a statistics cookie in the headline!
7903 (defun org-summary-todo (n-done n-not-done)
7904 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
7905 (let (org-log-done org-log-states) ; turn off logging
7906 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
7909 (defun org-local-logging (value)
7910 "Get logging settings from a property VALUE."
7911 (let* (words w a)
7912 ;; directly set the variables, they are already local.
7913 (setq org-log-done nil
7914 org-log-repeat nil
7915 org-todo-log-states nil)
7916 (setq words (org-split-string value))
7917 (while (setq w (pop words))
7918 (cond
7919 ((setq a (assoc w org-startup-options))
7920 (and (member (nth 1 a) '(org-log-done org-log-repeat))
7921 (set (nth 1 a) (nth 2 a))))
7922 ((setq a (org-extract-log-state-settings w))
7923 (and (member (car a) org-todo-keywords-1)
7924 (push a org-todo-log-states)))))))
7926 (defun org-get-todo-sequence-head (kwd)
7927 "Return the head of the TODO sequence to which KWD belongs.
7928 If KWD is not set, check if there is a text property remembering the
7929 right sequence."
7930 (let (p)
7931 (cond
7932 ((not kwd)
7933 (or (get-text-property (point-at-bol) 'org-todo-head)
7934 (progn
7935 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
7936 nil (point-at-eol)))
7937 (get-text-property p 'org-todo-head))))
7938 ((not (member kwd org-todo-keywords-1))
7939 (car org-todo-keywords-1))
7940 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
7942 (defun org-fast-todo-selection ()
7943 "Fast TODO keyword selection with single keys.
7944 Returns the new TODO keyword, or nil if no state change should occur."
7945 (let* ((fulltable org-todo-key-alist)
7946 (done-keywords org-done-keywords) ;; needed for the faces.
7947 (maxlen (apply 'max (mapcar
7948 (lambda (x)
7949 (if (stringp (car x)) (string-width (car x)) 0))
7950 fulltable)))
7951 (expert nil)
7952 (fwidth (+ maxlen 3 1 3))
7953 (ncol (/ (- (window-width) 4) fwidth))
7954 tg cnt e c tbl
7955 groups ingroup)
7956 (save-window-excursion
7957 (if expert
7958 (set-buffer (get-buffer-create " *Org todo*"))
7959 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
7960 (erase-buffer)
7961 (org-set-local 'org-done-keywords done-keywords)
7962 (setq tbl fulltable cnt 0)
7963 (while (setq e (pop tbl))
7964 (cond
7965 ((equal e '(:startgroup))
7966 (push '() groups) (setq ingroup t)
7967 (when (not (= cnt 0))
7968 (setq cnt 0)
7969 (insert "\n"))
7970 (insert "{ "))
7971 ((equal e '(:endgroup))
7972 (setq ingroup nil cnt 0)
7973 (insert "}\n"))
7975 (setq tg (car e) c (cdr e))
7976 (if ingroup (push tg (car groups)))
7977 (setq tg (org-add-props tg nil 'face
7978 (org-get-todo-face tg)))
7979 (if (and (= cnt 0) (not ingroup)) (insert " "))
7980 (insert "[" c "] " tg (make-string
7981 (- fwidth 4 (length tg)) ?\ ))
7982 (when (= (setq cnt (1+ cnt)) ncol)
7983 (insert "\n")
7984 (if ingroup (insert " "))
7985 (setq cnt 0)))))
7986 (insert "\n")
7987 (goto-char (point-min))
7988 (if (and (not expert) (fboundp 'fit-window-to-buffer))
7989 (fit-window-to-buffer))
7990 (message "[a-z..]:Set [SPC]:clear")
7991 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
7992 (cond
7993 ((or (= c ?\C-g)
7994 (and (= c ?q) (not (rassoc c fulltable))))
7995 (setq quit-flag t))
7996 ((= c ?\ ) nil)
7997 ((setq e (rassoc c fulltable) tg (car e))
7999 (t (setq quit-flag t))))))
8001 (defun org-entry-is-todo-p ()
8002 (member (org-get-todo-state) org-not-done-keywords))
8004 (defun org-entry-is-done-p ()
8005 (member (org-get-todo-state) org-done-keywords))
8007 (defun org-get-todo-state ()
8008 (save-excursion
8009 (org-back-to-heading t)
8010 (and (looking-at org-todo-line-regexp)
8011 (match-end 2)
8012 (match-string 2))))
8014 (defun org-at-date-range-p (&optional inactive-ok)
8015 "Is the cursor inside a date range?"
8016 (interactive)
8017 (save-excursion
8018 (catch 'exit
8019 (let ((pos (point)))
8020 (skip-chars-backward "^[<\r\n")
8021 (skip-chars-backward "<[")
8022 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8023 (>= (match-end 0) pos)
8024 (throw 'exit t))
8025 (skip-chars-backward "^<[\r\n")
8026 (skip-chars-backward "<[")
8027 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8028 (>= (match-end 0) pos)
8029 (throw 'exit t)))
8030 nil)))
8032 (defun org-get-repeat ()
8033 "Check if there is a deadline/schedule with repeater in this entry."
8034 (save-match-data
8035 (save-excursion
8036 (org-back-to-heading t)
8037 (if (re-search-forward
8038 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
8039 (match-string 1)))))
8041 (defvar org-last-changed-timestamp)
8042 (defvar org-last-inserted-timestamp)
8043 (defvar org-log-post-message)
8044 (defvar org-log-note-purpose)
8045 (defvar org-log-note-how)
8046 (defvar org-log-note-extra)
8047 (defun org-auto-repeat-maybe (done-word)
8048 "Check if the current headline contains a repeated deadline/schedule.
8049 If yes, set TODO state back to what it was and change the base date
8050 of repeating deadline/scheduled time stamps to new date.
8051 This function is run automatically after each state change to a DONE state."
8052 ;; last-state is dynamically scoped into this function
8053 (let* ((repeat (org-get-repeat))
8054 (aa (assoc last-state org-todo-kwd-alist))
8055 (interpret (nth 1 aa))
8056 (head (nth 2 aa))
8057 (whata '(("d" . day) ("m" . month) ("y" . year)))
8058 (msg "Entry repeats: ")
8059 (org-log-done nil)
8060 (org-todo-log-states nil)
8061 (nshiftmax 10) (nshift 0)
8062 re type n what ts mb0 time)
8063 (when repeat
8064 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
8065 (org-todo (if (eq interpret 'type) last-state head))
8066 (when org-log-repeat
8067 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
8068 (memq 'org-add-log-note post-command-hook))
8069 ;; OK, we are already setup for some record
8070 (if (eq org-log-repeat 'note)
8071 ;; make sure we take a note, not only a time stamp
8072 (setq org-log-note-how 'note))
8073 ;; Set up for taking a record
8074 (org-add-log-setup 'state (or done-word (car org-done-keywords))
8075 'findpos org-log-repeat)))
8076 (org-back-to-heading t)
8077 (org-add-planning-info nil nil 'closed)
8078 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
8079 org-deadline-time-regexp "\\)\\|\\("
8080 org-ts-regexp "\\)"))
8081 (while (re-search-forward
8082 re (save-excursion (outline-next-heading) (point)) t)
8083 (setq type (if (match-end 1) org-scheduled-string
8084 (if (match-end 3) org-deadline-string "Plain:"))
8085 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0)))
8086 mb0 (match-beginning 0))
8087 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
8088 (setq n (string-to-number (match-string 2 ts))
8089 what (match-string 3 ts))
8090 (if (equal what "w") (setq n (* n 7) what "d"))
8091 ;; Preparation, see if we need to modify the start date for the change
8092 (when (match-end 1)
8093 (setq time (save-match-data (org-time-string-to-time ts)))
8094 (cond
8095 ((equal (match-string 1 ts) ".")
8096 ;; Shift starting date to today
8097 (org-timestamp-change
8098 (- (time-to-days (current-time)) (time-to-days time))
8099 'day))
8100 ((equal (match-string 1 ts) "+")
8101 (while (or (= nshift 0)
8102 (<= (time-to-days time) (time-to-days (current-time))))
8103 (when (= (incf nshift) nshiftmax)
8104 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
8105 (error "Abort")))
8106 (org-timestamp-change n (cdr (assoc what whata)))
8107 (org-at-timestamp-p t)
8108 (setq ts (match-string 1))
8109 (setq time (save-match-data (org-time-string-to-time ts))))
8110 (org-timestamp-change (- n) (cdr (assoc what whata)))
8111 ;; rematch, so that we have everything in place for the real shift
8112 (org-at-timestamp-p t)
8113 (setq ts (match-string 1))
8114 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
8115 (org-timestamp-change n (cdr (assoc what whata)))
8116 (setq msg (concat msg type org-last-changed-timestamp " "))))
8117 (setq org-log-post-message msg)
8118 (message "%s" msg))))
8120 (defun org-show-todo-tree (arg)
8121 "Make a compact tree which shows all headlines marked with TODO.
8122 The tree will show the lines where the regexp matches, and all higher
8123 headlines above the match.
8124 With a \\[universal-argument] prefix, also show the DONE entries.
8125 With a numeric prefix N, construct a sparse tree for the Nth element
8126 of `org-todo-keywords-1'."
8127 (interactive "P")
8128 (let ((case-fold-search nil)
8129 (kwd-re
8130 (cond ((null arg) org-not-done-regexp)
8131 ((equal arg '(4))
8132 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
8133 (mapcar 'list org-todo-keywords-1))))
8134 (concat "\\("
8135 (mapconcat 'identity (org-split-string kwd "|") "\\|")
8136 "\\)\\>")))
8137 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
8138 (regexp-quote (nth (1- (prefix-numeric-value arg))
8139 org-todo-keywords-1)))
8140 (t (error "Invalid prefix argument: %s" arg)))))
8141 (message "%d TODO entries found"
8142 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
8144 (defun org-deadline (&optional remove time)
8145 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
8146 With argument REMOVE, remove any deadline from the item.
8147 When TIME is set, it should be an internal time specification, and the
8148 scheduling will use the corresponding date."
8149 (interactive "P")
8150 (if remove
8151 (progn
8152 (org-remove-timestamp-with-keyword org-deadline-string)
8153 (message "Item no longer has a deadline."))
8154 (if (org-get-repeat)
8155 (error "Cannot change deadline on task with repeater, please do that by hand")
8156 (org-add-planning-info 'deadline time 'closed)
8157 (message "Deadline on %s" org-last-inserted-timestamp))))
8159 (defun org-schedule (&optional remove time)
8160 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
8161 With argument REMOVE, remove any scheduling date from the item.
8162 When TIME is set, it should be an internal time specification, and the
8163 scheduling will use the corresponding date."
8164 (interactive "P")
8165 (if remove
8166 (progn
8167 (org-remove-timestamp-with-keyword org-scheduled-string)
8168 (message "Item is no longer scheduled."))
8169 (if (org-get-repeat)
8170 (error "Cannot reschedule task with repeater, please do that by hand")
8171 (org-add-planning-info 'scheduled time 'closed)
8172 (message "Scheduled to %s" org-last-inserted-timestamp))))
8174 (defun org-remove-timestamp-with-keyword (keyword)
8175 "Remove all time stamps with KEYWORD in the current entry."
8176 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
8177 beg)
8178 (save-excursion
8179 (org-back-to-heading t)
8180 (setq beg (point))
8181 (org-end-of-subtree t t)
8182 (while (re-search-backward re beg t)
8183 (replace-match "")
8184 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
8185 (equal (char-before) ?\ ))
8186 (backward-delete-char 1)
8187 (if (string-match "^[ \t]*$" (buffer-substring
8188 (point-at-bol) (point-at-eol)))
8189 (delete-region (point-at-bol)
8190 (min (point-max) (1+ (point-at-eol))))))))))
8192 (defun org-add-planning-info (what &optional time &rest remove)
8193 "Insert new timestamp with keyword in the line directly after the headline.
8194 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
8195 If non is given, the user is prompted for a date.
8196 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
8197 be removed."
8198 (interactive)
8199 (let (org-time-was-given org-end-time-was-given ts
8200 end default-time default-input)
8202 (when (and (not time) (memq what '(scheduled deadline)))
8203 ;; Try to get a default date/time from existing timestamp
8204 (save-excursion
8205 (org-back-to-heading t)
8206 (setq end (save-excursion (outline-next-heading) (point)))
8207 (when (re-search-forward (if (eq what 'scheduled)
8208 org-scheduled-time-regexp
8209 org-deadline-time-regexp)
8210 end t)
8211 (setq ts (match-string 1)
8212 default-time
8213 (apply 'encode-time (org-parse-time-string ts))
8214 default-input (and ts (org-get-compact-tod ts))))))
8215 (when what
8216 ;; If necessary, get the time from the user
8217 (setq time (or time (org-read-date nil 'to-time nil nil
8218 default-time default-input))))
8220 (when (and org-insert-labeled-timestamps-at-point
8221 (member what '(scheduled deadline)))
8222 (insert
8223 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
8224 (org-insert-time-stamp time org-time-was-given
8225 nil nil nil (list org-end-time-was-given))
8226 (setq what nil))
8227 (save-excursion
8228 (save-restriction
8229 (let (col list elt ts buffer-invisibility-spec)
8230 (org-back-to-heading t)
8231 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
8232 (goto-char (match-end 1))
8233 (setq col (current-column))
8234 (goto-char (match-end 0))
8235 (if (eobp) (insert "\n") (forward-char 1))
8236 (if (and (not (looking-at outline-regexp))
8237 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
8238 "[^\r\n]*"))
8239 (not (equal (match-string 1) org-clock-string)))
8240 (narrow-to-region (match-beginning 0) (match-end 0))
8241 (insert-before-markers "\n")
8242 (backward-char 1)
8243 (narrow-to-region (point) (point))
8244 (and org-adapt-indentation (org-indent-to-column col)))
8245 ;; Check if we have to remove something.
8246 (setq list (cons what remove))
8247 (while list
8248 (setq elt (pop list))
8249 (goto-char (point-min))
8250 (when (or (and (eq elt 'scheduled)
8251 (re-search-forward org-scheduled-time-regexp nil t))
8252 (and (eq elt 'deadline)
8253 (re-search-forward org-deadline-time-regexp nil t))
8254 (and (eq elt 'closed)
8255 (re-search-forward org-closed-time-regexp nil t)))
8256 (replace-match "")
8257 (if (looking-at "--+<[^>]+>") (replace-match ""))
8258 (if (looking-at " +") (replace-match ""))))
8259 (goto-char (point-max))
8260 (when what
8261 (insert
8262 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
8263 (cond ((eq what 'scheduled) org-scheduled-string)
8264 ((eq what 'deadline) org-deadline-string)
8265 ((eq what 'closed) org-closed-string))
8266 " ")
8267 (setq ts (org-insert-time-stamp
8268 time
8269 (or org-time-was-given
8270 (and (eq what 'closed) org-log-done-with-time))
8271 (eq what 'closed)
8272 nil nil (list org-end-time-was-given)))
8273 (end-of-line 1))
8274 (goto-char (point-min))
8275 (widen)
8276 (if (and (looking-at "[ \t]+\n")
8277 (equal (char-before) ?\n))
8278 (delete-region (1- (point)) (point-at-eol)))
8279 ts)))))
8281 (defvar org-log-note-marker (make-marker))
8282 (defvar org-log-note-purpose nil)
8283 (defvar org-log-note-state nil)
8284 (defvar org-log-note-how nil)
8285 (defvar org-log-note-extra nil)
8286 (defvar org-log-note-window-configuration nil)
8287 (defvar org-log-note-return-to (make-marker))
8288 (defvar org-log-post-message nil
8289 "Message to be displayed after a log note has been stored.
8290 The auto-repeater uses this.")
8292 (defun org-add-note ()
8293 "Add a note to the current entry.
8294 This is done in the same way as adding a state change note."
8295 (interactive)
8296 (org-add-log-setup 'note nil 'findpos nil))
8298 (defvar org-property-end-re)
8299 (defun org-add-log-setup (&optional purpose state findpos how &optional extra)
8300 "Set up the post command hook to take a note.
8301 If this is about to TODO state change, the new state is expected in STATE.
8302 When FINDPOS is non-nil, find the correct position for the note in
8303 the current entry. If not, assume that it can be inserted at point.
8304 HOW is an indicator what kind of note should be created.
8305 EXTRA is additional text that will be inserted into the notes buffer."
8306 (save-restriction
8307 (save-excursion
8308 (when findpos
8309 (org-back-to-heading t)
8310 (org-narrow-to-subtree)
8311 (while (re-search-forward
8312 (concat "\\(" org-drawer-regexp "\\|" org-property-end-re "\\)")
8313 (point-max) t) (forward-line))
8314 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
8315 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
8316 "[^\r\n]*\\)?"))
8317 (goto-char (match-end 0))
8318 (unless org-log-states-order-reversed
8319 (and (= (char-after) ?\n) (forward-char 1))
8320 (org-skip-over-state-notes)
8321 (skip-chars-backward " \t\n\r")))
8322 (move-marker org-log-note-marker (point))
8323 (setq org-log-note-purpose purpose
8324 org-log-note-state state
8325 org-log-note-how how
8326 org-log-note-extra extra)
8327 (add-hook 'post-command-hook 'org-add-log-note 'append))))
8329 (defun org-skip-over-state-notes ()
8330 "Skip past the list of State notes in an entry."
8331 (if (looking-at "\n[ \t]*- State") (forward-char 1))
8332 (while (looking-at "[ \t]*- State")
8333 (condition-case nil
8334 (org-next-item)
8335 (error (org-end-of-item)))))
8337 (defun org-add-log-note (&optional purpose)
8338 "Pop up a window for taking a note, and add this note later at point."
8339 (remove-hook 'post-command-hook 'org-add-log-note)
8340 (setq org-log-note-window-configuration (current-window-configuration))
8341 (delete-other-windows)
8342 (move-marker org-log-note-return-to (point))
8343 (switch-to-buffer (marker-buffer org-log-note-marker))
8344 (goto-char org-log-note-marker)
8345 (org-switch-to-buffer-other-window "*Org Note*")
8346 (erase-buffer)
8347 (if (memq org-log-note-how '(time state))
8348 (org-store-log-note)
8349 (let ((org-inhibit-startup t)) (org-mode))
8350 (insert (format "# Insert note for %s.
8351 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
8352 (cond
8353 ((eq org-log-note-purpose 'clock-out) "stopped clock")
8354 ((eq org-log-note-purpose 'done) "closed todo item")
8355 ((eq org-log-note-purpose 'state)
8356 (format "state change to \"%s\"" org-log-note-state))
8357 ((eq org-log-note-purpose 'note)
8358 "this entry")
8359 (t (error "This should not happen")))))
8360 (if org-log-note-extra (insert org-log-note-extra))
8361 (org-set-local 'org-finish-function 'org-store-log-note)))
8363 (defvar org-note-abort nil) ; dynamically scoped
8364 (defun org-store-log-note ()
8365 "Finish taking a log note, and insert it to where it belongs."
8366 (let ((txt (buffer-string))
8367 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
8368 lines ind)
8369 (kill-buffer (current-buffer))
8370 (while (string-match "\\`#.*\n[ \t\n]*" txt)
8371 (setq txt (replace-match "" t t txt)))
8372 (if (string-match "\\s-+\\'" txt)
8373 (setq txt (replace-match "" t t txt)))
8374 (setq lines (org-split-string txt "\n"))
8375 (when (and note (string-match "\\S-" note))
8376 (setq note
8377 (org-replace-escapes
8378 note
8379 (list (cons "%u" (user-login-name))
8380 (cons "%U" user-full-name)
8381 (cons "%t" (format-time-string
8382 (org-time-stamp-format 'long 'inactive)
8383 (current-time)))
8384 (cons "%s" (if org-log-note-state
8385 (concat "\"" org-log-note-state "\"")
8386 "")))))
8387 (if lines (setq note (concat note " \\\\")))
8388 (push note lines))
8389 (when (or current-prefix-arg org-note-abort) (setq lines nil))
8390 (when lines
8391 (save-excursion
8392 (set-buffer (marker-buffer org-log-note-marker))
8393 (save-excursion
8394 (goto-char org-log-note-marker)
8395 (move-marker org-log-note-marker nil)
8396 (end-of-line 1)
8397 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
8398 (indent-relative nil)
8399 (insert "- " (pop lines))
8400 (org-indent-line-function)
8401 (beginning-of-line 1)
8402 (looking-at "[ \t]*")
8403 (setq ind (concat (match-string 0) " "))
8404 (end-of-line 1)
8405 (while lines (insert "\n" ind (pop lines)))))))
8406 (set-window-configuration org-log-note-window-configuration)
8407 (with-current-buffer (marker-buffer org-log-note-return-to)
8408 (goto-char org-log-note-return-to))
8409 (move-marker org-log-note-return-to nil)
8410 (and org-log-post-message (message "%s" org-log-post-message)))
8412 (defun org-sparse-tree (&optional arg)
8413 "Create a sparse tree, prompt for the details.
8414 This command can create sparse trees. You first need to select the type
8415 of match used to create the tree:
8417 t Show entries with a specific TODO keyword.
8418 T Show entries selected by a tags match.
8419 p Enter a property name and its value (both with completion on existing
8420 names/values) and show entries with that property.
8421 r Show entries matching a regular expression
8422 d Show deadlines due within `org-deadline-warning-days'."
8423 (interactive "P")
8424 (let (ans kwd value)
8425 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
8426 (setq ans (read-char-exclusive))
8427 (cond
8428 ((equal ans ?d)
8429 (call-interactively 'org-check-deadlines))
8430 ((equal ans ?b)
8431 (call-interactively 'org-check-before-date))
8432 ((equal ans ?t)
8433 (org-show-todo-tree '(4)))
8434 ((equal ans ?T)
8435 (call-interactively 'org-tags-sparse-tree))
8436 ((member ans '(?p ?P))
8437 (setq kwd (completing-read "Property: "
8438 (mapcar 'list (org-buffer-property-keys))))
8439 (setq value (completing-read "Value: "
8440 (mapcar 'list (org-property-values kwd))))
8441 (unless (string-match "\\`{.*}\\'" value)
8442 (setq value (concat "\"" value "\"")))
8443 (org-tags-sparse-tree arg (concat kwd "=" value)))
8444 ((member ans '(?r ?R ?/))
8445 (call-interactively 'org-occur))
8446 (t (error "No such sparse tree command \"%c\"" ans)))))
8448 (defvar org-occur-highlights nil
8449 "List of overlays used for occur matches.")
8450 (make-variable-buffer-local 'org-occur-highlights)
8451 (defvar org-occur-parameters nil
8452 "Parameters of the active org-occur calls.
8453 This is a list, each call to org-occur pushes as cons cell,
8454 containing the regular expression and the callback, onto the list.
8455 The list can contain several entries if `org-occur' has been called
8456 several time with the KEEP-PREVIOUS argument. Otherwise, this list
8457 will only contain one set of parameters. When the highlights are
8458 removed (for example with `C-c C-c', or with the next edit (depending
8459 on `org-remove-highlights-with-change'), this variable is emptied
8460 as well.")
8461 (make-variable-buffer-local 'org-occur-parameters)
8463 (defun org-occur (regexp &optional keep-previous callback)
8464 "Make a compact tree which shows all matches of REGEXP.
8465 The tree will show the lines where the regexp matches, and all higher
8466 headlines above the match. It will also show the heading after the match,
8467 to make sure editing the matching entry is easy.
8468 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
8469 call to `org-occur' will be kept, to allow stacking of calls to this
8470 command.
8471 If CALLBACK is non-nil, it is a function which is called to confirm
8472 that the match should indeed be shown."
8473 (interactive "sRegexp: \nP")
8474 (unless keep-previous
8475 (org-remove-occur-highlights nil nil t))
8476 (push (cons regexp callback) org-occur-parameters)
8477 (let ((cnt 0))
8478 (save-excursion
8479 (goto-char (point-min))
8480 (if (or (not keep-previous) ; do not want to keep
8481 (not org-occur-highlights)) ; no previous matches
8482 ;; hide everything
8483 (org-overview))
8484 (while (re-search-forward regexp nil t)
8485 (when (or (not callback)
8486 (save-match-data (funcall callback)))
8487 (setq cnt (1+ cnt))
8488 (when org-highlight-sparse-tree-matches
8489 (org-highlight-new-match (match-beginning 0) (match-end 0)))
8490 (org-show-context 'occur-tree))))
8491 (when org-remove-highlights-with-change
8492 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
8493 nil 'local))
8494 (unless org-sparse-tree-open-archived-trees
8495 (org-hide-archived-subtrees (point-min) (point-max)))
8496 (run-hooks 'org-occur-hook)
8497 (if (interactive-p)
8498 (message "%d match(es) for regexp %s" cnt regexp))
8499 cnt))
8501 (defun org-show-context (&optional key)
8502 "Make sure point and context and visible.
8503 How much context is shown depends upon the variables
8504 `org-show-hierarchy-above', `org-show-following-heading'. and
8505 `org-show-siblings'."
8506 (let ((heading-p (org-on-heading-p t))
8507 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
8508 (following-p (org-get-alist-option org-show-following-heading key))
8509 (entry-p (org-get-alist-option org-show-entry-below key))
8510 (siblings-p (org-get-alist-option org-show-siblings key)))
8511 (catch 'exit
8512 ;; Show heading or entry text
8513 (if (and heading-p (not entry-p))
8514 (org-flag-heading nil) ; only show the heading
8515 (and (or entry-p (org-invisible-p) (org-invisible-p2))
8516 (org-show-hidden-entry))) ; show entire entry
8517 (when following-p
8518 ;; Show next sibling, or heading below text
8519 (save-excursion
8520 (and (if heading-p (org-goto-sibling) (outline-next-heading))
8521 (org-flag-heading nil))))
8522 (when siblings-p (org-show-siblings))
8523 (when hierarchy-p
8524 ;; show all higher headings, possibly with siblings
8525 (save-excursion
8526 (while (and (condition-case nil
8527 (progn (org-up-heading-all 1) t)
8528 (error nil))
8529 (not (bobp)))
8530 (org-flag-heading nil)
8531 (when siblings-p (org-show-siblings))))))))
8533 (defun org-reveal (&optional siblings)
8534 "Show current entry, hierarchy above it, and the following headline.
8535 This can be used to show a consistent set of context around locations
8536 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
8537 not t for the search context.
8539 With optional argument SIBLINGS, on each level of the hierarchy all
8540 siblings are shown. This repairs the tree structure to what it would
8541 look like when opened with hierarchical calls to `org-cycle'."
8542 (interactive "P")
8543 (let ((org-show-hierarchy-above t)
8544 (org-show-following-heading t)
8545 (org-show-siblings (if siblings t org-show-siblings)))
8546 (org-show-context nil)))
8548 (defun org-highlight-new-match (beg end)
8549 "Highlight from BEG to END and mark the highlight is an occur headline."
8550 (let ((ov (org-make-overlay beg end)))
8551 (org-overlay-put ov 'face 'secondary-selection)
8552 (push ov org-occur-highlights)))
8554 (defun org-remove-occur-highlights (&optional beg end noremove)
8555 "Remove the occur highlights from the buffer.
8556 BEG and END are ignored. If NOREMOVE is nil, remove this function
8557 from the `before-change-functions' in the current buffer."
8558 (interactive)
8559 (unless org-inhibit-highlight-removal
8560 (mapc 'org-delete-overlay org-occur-highlights)
8561 (setq org-occur-highlights nil)
8562 (setq org-occur-parameters nil)
8563 (unless noremove
8564 (remove-hook 'before-change-functions
8565 'org-remove-occur-highlights 'local))))
8567 ;;;; Priorities
8569 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
8570 "Regular expression matching the priority indicator.")
8572 (defvar org-remove-priority-next-time nil)
8574 (defun org-priority-up ()
8575 "Increase the priority of the current item."
8576 (interactive)
8577 (org-priority 'up))
8579 (defun org-priority-down ()
8580 "Decrease the priority of the current item."
8581 (interactive)
8582 (org-priority 'down))
8584 (defun org-priority (&optional action)
8585 "Change the priority of an item by ARG.
8586 ACTION can be `set', `up', `down', or a character."
8587 (interactive)
8588 (setq action (or action 'set))
8589 (let (current new news have remove)
8590 (save-excursion
8591 (org-back-to-heading)
8592 (if (looking-at org-priority-regexp)
8593 (setq current (string-to-char (match-string 2))
8594 have t)
8595 (setq current org-default-priority))
8596 (cond
8597 ((or (eq action 'set)
8598 (if (featurep 'xemacs) (characterp action) (integerp action)))
8599 (if (not (eq action 'set))
8600 (setq new action)
8601 (message "Priority %c-%c, SPC to remove: "
8602 org-highest-priority org-lowest-priority)
8603 (setq new (read-char-exclusive)))
8604 (if (and (= (upcase org-highest-priority) org-highest-priority)
8605 (= (upcase org-lowest-priority) org-lowest-priority))
8606 (setq new (upcase new)))
8607 (cond ((equal new ?\ ) (setq remove t))
8608 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
8609 (error "Priority must be between `%c' and `%c'"
8610 org-highest-priority org-lowest-priority))))
8611 ((eq action 'up)
8612 (if (and (not have) (eq last-command this-command))
8613 (setq new org-lowest-priority)
8614 (setq new (if (and org-priority-start-cycle-with-default (not have))
8615 org-default-priority (1- current)))))
8616 ((eq action 'down)
8617 (if (and (not have) (eq last-command this-command))
8618 (setq new org-highest-priority)
8619 (setq new (if (and org-priority-start-cycle-with-default (not have))
8620 org-default-priority (1+ current)))))
8621 (t (error "Invalid action")))
8622 (if (or (< (upcase new) org-highest-priority)
8623 (> (upcase new) org-lowest-priority))
8624 (setq remove t))
8625 (setq news (format "%c" new))
8626 (if have
8627 (if remove
8628 (replace-match "" t t nil 1)
8629 (replace-match news t t nil 2))
8630 (if remove
8631 (error "No priority cookie found in line")
8632 (looking-at org-todo-line-regexp)
8633 (if (match-end 2)
8634 (progn
8635 (goto-char (match-end 2))
8636 (insert " [#" news "]"))
8637 (goto-char (match-beginning 3))
8638 (insert "[#" news "] ")))))
8639 (org-preserve-lc (org-set-tags nil 'align))
8640 (if remove
8641 (message "Priority removed")
8642 (message "Priority of current item set to %s" news))))
8645 (defun org-get-priority (s)
8646 "Find priority cookie and return priority."
8647 (save-match-data
8648 (if (not (string-match org-priority-regexp s))
8649 (* 1000 (- org-lowest-priority org-default-priority))
8650 (* 1000 (- org-lowest-priority
8651 (string-to-char (match-string 2 s)))))))
8653 ;;;; Tags
8655 (defvar org-agenda-archives-mode)
8656 (defun org-scan-tags (action matcher &optional todo-only)
8657 "Scan headline tags with inheritance and produce output ACTION.
8659 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
8660 or `agenda' to produce an entry list for an agenda view. It can also be
8661 a Lisp form or a function that should be called at each matched headline, in
8662 this case the return value is a list of all return values from these calls.
8664 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
8665 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
8666 only lines with a TODO keyword are included in the output."
8667 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
8668 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
8669 (org-re
8670 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
8671 (props (list 'face 'default
8672 'done-face 'org-done
8673 'undone-face 'default
8674 'mouse-face 'highlight
8675 'org-not-done-regexp org-not-done-regexp
8676 'org-todo-regexp org-todo-regexp
8677 'keymap org-agenda-keymap
8678 'help-echo
8679 (format "mouse-2 or RET jump to org file %s"
8680 (abbreviate-file-name
8681 (or (buffer-file-name (buffer-base-buffer))
8682 (buffer-name (buffer-base-buffer)))))))
8683 (case-fold-search nil)
8684 lspos tags tags-list
8685 (tags-alist (list (cons 0 (mapcar 'downcase org-file-tags))))
8686 (llast 0) rtn rtn1 level category i txt
8687 todo marker entry priority)
8688 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
8689 (setq action (list 'lambda nil action)))
8690 (save-excursion
8691 (goto-char (point-min))
8692 (when (eq action 'sparse-tree)
8693 (org-overview)
8694 (org-remove-occur-highlights))
8695 (while (re-search-forward re nil t)
8696 (catch :skip
8697 (setq todo (if (match-end 1) (match-string 2))
8698 tags (if (match-end 4) (match-string 4)))
8699 (goto-char (setq lspos (1+ (match-beginning 0))))
8700 (setq level (org-reduced-level (funcall outline-level))
8701 category (org-get-category))
8702 (setq i llast llast level)
8703 ;; remove tag lists from same and sublevels
8704 (while (>= i level)
8705 (when (setq entry (assoc i tags-alist))
8706 (setq tags-alist (delete entry tags-alist)))
8707 (setq i (1- i)))
8708 ;; add the next tags
8709 (when tags
8710 (setq tags (mapcar 'downcase (org-split-string tags ":"))
8711 tags-alist
8712 (cons (cons level tags) tags-alist)))
8713 ;; compile tags for current headline
8714 (setq tags-list
8715 (if org-use-tag-inheritance
8716 (apply 'append (mapcar 'cdr tags-alist))
8717 tags))
8718 (when (and tags org-use-tag-inheritance
8719 (not (eq t org-use-tag-inheritance)))
8720 ;; selective inheritance, remove uninherited ones
8721 (setcdr (car tags-alist)
8722 (org-remove-uniherited-tags (cdar tags-alist))))
8723 (when (and (or (not todo-only) (member todo org-not-done-keywords))
8724 (let ((case-fold-search t)) (eval matcher))
8726 (not (member org-archive-tag tags-list))
8727 ;; we have an archive tag, should we use this anyway?
8728 (or (not org-agenda-skip-archived-trees)
8729 (and (eq action 'agenda) org-agenda-archives-mode))))
8730 (unless (eq action 'sparse-tree) (org-agenda-skip))
8732 ;; select this headline
8734 (cond
8735 ((eq action 'sparse-tree)
8736 (and org-highlight-sparse-tree-matches
8737 (org-get-heading) (match-end 0)
8738 (org-highlight-new-match
8739 (match-beginning 0) (match-beginning 1)))
8740 (org-show-context 'tags-tree))
8741 ((eq action 'agenda)
8742 (setq txt (org-format-agenda-item
8744 (concat
8745 (if org-tags-match-list-sublevels
8746 (make-string (1- level) ?.) "")
8747 (org-get-heading))
8748 category tags-list)
8749 priority (org-get-priority txt))
8750 (goto-char lspos)
8751 (setq marker (org-agenda-new-marker))
8752 (org-add-props txt props
8753 'org-marker marker 'org-hd-marker marker 'org-category category
8754 'priority priority 'type "tagsmatch")
8755 (push txt rtn))
8756 ((functionp action)
8757 (save-excursion
8758 (setq rtn1 (funcall action))
8759 (push rtn1 rtn))
8760 (goto-char (point-at-eol)))
8761 (t (error "Invalid action")))
8763 ;; if we are to skip sublevels, jump to end of subtree
8764 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
8765 (when (and (eq action 'sparse-tree)
8766 (not org-sparse-tree-open-archived-trees))
8767 (org-hide-archived-subtrees (point-min) (point-max)))
8768 (nreverse rtn)))
8770 (defun org-remove-uniherited-tags (tags)
8771 "Remove all tags that are not inherited from the list TAGS."
8772 (cond
8773 ((eq org-use-tag-inheritance t) tags)
8774 ((not org-use-tag-inheritance) nil)
8775 ((stringp org-use-tag-inheritance)
8776 (delq nil (mapcar
8777 (lambda (x) (if (string-match org-use-tag-inheritance x) x nil))
8778 tags)))
8779 ((listp org-use-tag-inheritance)
8780 (org-delete-all org-use-tag-inheritance tags))))
8782 (defvar todo-only) ;; dynamically scoped
8784 (defun org-tags-sparse-tree (&optional todo-only match)
8785 "Create a sparse tree according to tags string MATCH.
8786 MATCH can contain positive and negative selection of tags, like
8787 \"+WORK+URGENT-WITHBOSS\".
8788 If optional argument TODO_ONLY is non-nil, only select lines that are
8789 also TODO lines."
8790 (interactive "P")
8791 (org-prepare-agenda-buffers (list (current-buffer)))
8792 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
8794 (defvar org-cached-props nil)
8795 (defun org-cached-entry-get (pom property)
8796 (if (or (eq t org-use-property-inheritance)
8797 (and (stringp org-use-property-inheritance)
8798 (string-match org-use-property-inheritance property))
8799 (and (listp org-use-property-inheritance)
8800 (member property org-use-property-inheritance)))
8801 ;; Caching is not possible, check it directly
8802 (org-entry-get pom property 'inherit)
8803 ;; Get all properties, so that we can do complicated checks easily
8804 (cdr (assoc property (or org-cached-props
8805 (setq org-cached-props
8806 (org-entry-properties pom)))))))
8808 (defun org-global-tags-completion-table (&optional files)
8809 "Return the list of all tags in all agenda buffer/files."
8810 (save-excursion
8811 (org-uniquify
8812 (delq nil
8813 (apply 'append
8814 (mapcar
8815 (lambda (file)
8816 (set-buffer (find-file-noselect file))
8817 (append (org-get-buffer-tags)
8818 (mapcar (lambda (x) (if (stringp (car-safe x))
8819 (list (car-safe x)) nil))
8820 org-tag-alist)))
8821 (if (and files (car files))
8822 files
8823 (org-agenda-files))))))))
8825 (defun org-make-tags-matcher (match)
8826 "Create the TAGS//TODO matcher form for the selection string MATCH."
8827 ;; todo-only is scoped dynamically into this function, and the function
8828 ;; may change it it the matcher asksk for it.
8829 (unless match
8830 ;; Get a new match request, with completion
8831 (let ((org-last-tags-completion-table
8832 (org-global-tags-completion-table)))
8833 (setq match (completing-read
8834 "Match: " 'org-tags-completion-function nil nil nil
8835 'org-tags-history))))
8837 ;; Parse the string and create a lisp form
8838 (let ((match0 match)
8839 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
8840 minus tag mm
8841 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
8842 orterms term orlist re-p str-p level-p level-op time-p
8843 prop-p pn pv po cat-p gv)
8844 (if (string-match "/+" match)
8845 ;; match contains also a todo-matching request
8846 (progn
8847 (setq tagsmatch (substring match 0 (match-beginning 0))
8848 todomatch (substring match (match-end 0)))
8849 (if (string-match "^!" todomatch)
8850 (setq todo-only t todomatch (substring todomatch 1)))
8851 (if (string-match "^\\s-*$" todomatch)
8852 (setq todomatch nil)))
8853 ;; only matching tags
8854 (setq tagsmatch match todomatch nil))
8856 ;; Make the tags matcher
8857 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
8858 (setq tagsmatcher t)
8859 (setq orterms (org-split-string tagsmatch "|") orlist nil)
8860 (while (setq term (pop orterms))
8861 (while (and (equal (substring term -1) "\\") orterms)
8862 (setq term (concat term "|" (pop orterms)))) ; repair bad split
8863 (while (string-match re term)
8864 (setq minus (and (match-end 1)
8865 (equal (match-string 1 term) "-"))
8866 tag (match-string 2 term)
8867 re-p (equal (string-to-char tag) ?{)
8868 level-p (match-end 4)
8869 prop-p (match-end 5)
8870 mm (cond
8871 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
8872 (level-p
8873 (setq level-op (org-op-to-function (match-string 3 term)))
8874 `(,level-op level ,(string-to-number
8875 (match-string 4 term))))
8876 (prop-p
8877 (setq pn (match-string 5 term)
8878 po (match-string 6 term)
8879 pv (match-string 7 term)
8880 cat-p (equal pn "CATEGORY")
8881 re-p (equal (string-to-char pv) ?{)
8882 str-p (equal (string-to-char pv) ?\")
8883 time-p (save-match-data (string-match "^\"<.*>\"$" pv))
8884 pv (if (or re-p str-p) (substring pv 1 -1) pv))
8885 (if time-p (setq pv (org-matcher-time pv)))
8886 (setq po (org-op-to-function po (if time-p 'time str-p)))
8887 (if (equal pn "CATEGORY")
8888 (setq gv '(get-text-property (point) 'org-category))
8889 (setq gv `(org-cached-entry-get nil ,pn)))
8890 (if re-p
8891 (if (eq po 'org<>)
8892 `(not (string-match ,pv (or ,gv "")))
8893 `(string-match ,pv (or ,gv "")))
8894 (if str-p
8895 `(,po (or ,gv "") ,pv)
8896 `(,po (string-to-number (or ,gv ""))
8897 ,(string-to-number pv) ))))
8898 (t `(member ,(downcase tag) tags-list)))
8899 mm (if minus (list 'not mm) mm)
8900 term (substring term (match-end 0)))
8901 (push mm tagsmatcher))
8902 (push (if (> (length tagsmatcher) 1)
8903 (cons 'and tagsmatcher)
8904 (car tagsmatcher))
8905 orlist)
8906 (setq tagsmatcher nil))
8907 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
8908 (setq tagsmatcher
8909 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
8910 ;; Make the todo matcher
8911 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
8912 (setq todomatcher t)
8913 (setq orterms (org-split-string todomatch "|") orlist nil)
8914 (while (setq term (pop orterms))
8915 (while (string-match re term)
8916 (setq minus (and (match-end 1)
8917 (equal (match-string 1 term) "-"))
8918 kwd (match-string 2 term)
8919 re-p (equal (string-to-char kwd) ?{)
8920 term (substring term (match-end 0))
8921 mm (if re-p
8922 `(string-match ,(substring kwd 1 -1) todo)
8923 (list 'equal 'todo kwd))
8924 mm (if minus (list 'not mm) mm))
8925 (push mm todomatcher))
8926 (push (if (> (length todomatcher) 1)
8927 (cons 'and todomatcher)
8928 (car todomatcher))
8929 orlist)
8930 (setq todomatcher nil))
8931 (setq todomatcher (if (> (length orlist) 1)
8932 (cons 'or orlist) (car orlist))))
8934 ;; Return the string and lisp forms of the matcher
8935 (setq matcher (if todomatcher
8936 (list 'and tagsmatcher todomatcher)
8937 tagsmatcher))
8938 (cons match0 matcher)))
8940 (defun org-op-to-function (op &optional stringp)
8941 "Turn an operator into the appropriate function."
8942 (setq op
8943 (cond
8944 ((equal op "<" ) '(< string< org-time<))
8945 ((equal op ">" ) '(> org-string> org-time>))
8946 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
8947 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
8948 ((member op '("=" "==")) '(= string= org-time=))
8949 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
8950 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
8952 (defun org<> (a b) (not (= a b)))
8953 (defun org-string<= (a b) (or (string= a b) (string< a b)))
8954 (defun org-string>= (a b) (not (string< a b)))
8955 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
8956 (defun org-string<> (a b) (not (string= a b)))
8957 (defun org-time= (a b) (= (org-2ft a) (org-2ft b)))
8958 (defun org-time< (a b) (< (org-2ft a) (org-2ft b)))
8959 (defun org-time<= (a b) (<= (org-2ft a) (org-2ft b)))
8960 (defun org-time> (a b) (> (org-2ft a) (org-2ft b)))
8961 (defun org-time>= (a b) (>= (org-2ft a) (org-2ft b)))
8962 (defun org-time<> (a b) (org<> (org-2ft a) (org-2ft b)))
8963 (defun org-2ft (s)
8964 "Convert S to a floating point time.
8965 If S is already a number, just return it. If it is a string, parse
8966 it as a time string and apply `float-time' to it. f S is nil, just return 0."
8967 (cond
8968 ((numberp s) s)
8969 ((stringp s)
8970 (condition-case nil
8971 (float-time (apply 'encode-time (org-parse-time-string s)))
8972 (error 0.)))
8973 (t 0.)))
8975 (defun org-matcher-time (s)
8976 (cond
8977 ((equal s "<now>") (float-time))
8978 ((equal s "<today>")
8979 (float-time (append '(0 0 0) (nthcdr 3 (decode-time)))))
8980 (t (org-2ft s))))
8982 (defun org-match-any-p (re list)
8983 "Does re match any element of list?"
8984 (setq list (mapcar (lambda (x) (string-match re x)) list))
8985 (delq nil list))
8987 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
8988 (defvar org-tags-overlay (org-make-overlay 1 1))
8989 (org-detach-overlay org-tags-overlay)
8991 (defun org-get-local-tags-at (&optional pos)
8992 "Get a list of tags defined in the current headline."
8993 (org-get-tags-at pos 'local))
8995 (defun org-get-local-tags ()
8996 "Get a list of tags defined in the current headline."
8997 (org-get-tags-at nil 'local))
8999 (defun org-get-tags-at (&optional pos local)
9000 "Get a list of all headline tags applicable at POS.
9001 POS defaults to point. If tags are inherited, the list contains
9002 the targets in the same sequence as the headlines appear, i.e.
9003 the tags of the current headline come last.
9004 When LOCAL is non-nil, only return tags from the current headline,
9005 ignore inherited ones."
9006 (interactive)
9007 (let (tags ltags lastpos parent)
9008 (save-excursion
9009 (save-restriction
9010 (widen)
9011 (goto-char (or pos (point)))
9012 (save-match-data
9013 (catch 'done
9014 (condition-case nil
9015 (progn
9016 (org-back-to-heading t)
9017 (while (not (equal lastpos (point)))
9018 (setq lastpos (point))
9019 (when (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
9020 (setq ltags (org-split-string
9021 (org-match-string-no-properties 1) ":"))
9022 (setq tags (append
9023 (if parent
9024 (org-remove-uniherited-tags ltags)
9025 ltags)
9026 tags)))
9027 (or org-use-tag-inheritance (throw 'done t))
9028 (if local (throw 'done t))
9029 (org-up-heading-all 1)
9030 (setq parent t)))
9031 (error nil)))))
9032 (append (org-remove-uniherited-tags org-file-tags) tags))))
9034 (defun org-toggle-tag (tag &optional onoff)
9035 "Toggle the tag TAG for the current line.
9036 If ONOFF is `on' or `off', don't toggle but set to this state."
9037 (unless (org-on-heading-p t) (error "Not on headling"))
9038 (let (res current)
9039 (save-excursion
9040 (beginning-of-line)
9041 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
9042 (point-at-eol) t)
9043 (progn
9044 (setq current (match-string 1))
9045 (replace-match ""))
9046 (setq current ""))
9047 (setq current (nreverse (org-split-string current ":")))
9048 (cond
9049 ((eq onoff 'on)
9050 (setq res t)
9051 (or (member tag current) (push tag current)))
9052 ((eq onoff 'off)
9053 (or (not (member tag current)) (setq current (delete tag current))))
9054 (t (if (member tag current)
9055 (setq current (delete tag current))
9056 (setq res t)
9057 (push tag current))))
9058 (end-of-line 1)
9059 (if current
9060 (progn
9061 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
9062 (org-set-tags nil t))
9063 (delete-horizontal-space))
9064 (run-hooks 'org-after-tags-change-hook))
9065 res))
9067 (defun org-align-tags-here (to-col)
9068 ;; Assumes that this is a headline
9069 (let ((pos (point)) (col (current-column)) ncol tags-l p)
9070 (beginning-of-line 1)
9071 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9072 (< pos (match-beginning 2)))
9073 (progn
9074 (setq tags-l (- (match-end 2) (match-beginning 2)))
9075 (goto-char (match-beginning 1))
9076 (insert " ")
9077 (delete-region (point) (1+ (match-beginning 2)))
9078 (setq ncol (max (1+ (current-column))
9079 (1+ col)
9080 (if (> to-col 0)
9081 to-col
9082 (- (abs to-col) tags-l))))
9083 (setq p (point))
9084 (insert (make-string (- ncol (current-column)) ?\ ))
9085 (setq ncol (current-column))
9086 (when indent-tabs-mode (tabify p (point-at-eol)))
9087 (org-move-to-column (min ncol col) t))
9088 (goto-char pos))))
9090 (defun org-set-tags (&optional arg just-align)
9091 "Set the tags for the current headline.
9092 With prefix ARG, realign all tags in headings in the current buffer."
9093 (interactive "P")
9094 (let* ((re (concat "^" outline-regexp))
9095 (current (org-get-tags-string))
9096 (col (current-column))
9097 (org-setting-tags t)
9098 table current-tags inherited-tags ; computed below when needed
9099 tags p0 c0 c1 rpl)
9100 (if arg
9101 (save-excursion
9102 (goto-char (point-min))
9103 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
9104 (while (re-search-forward re nil t)
9105 (org-set-tags nil t)
9106 (end-of-line 1)))
9107 (message "All tags realigned to column %d" org-tags-column))
9108 (if just-align
9109 (setq tags current)
9110 ;; Get a new set of tags from the user
9111 (save-excursion
9112 (setq table (or org-tag-alist (org-get-buffer-tags))
9113 org-last-tags-completion-table table
9114 current-tags (org-split-string current ":")
9115 inherited-tags (nreverse
9116 (nthcdr (length current-tags)
9117 (nreverse (org-get-tags-at))))
9118 tags
9119 (if (or (eq t org-use-fast-tag-selection)
9120 (and org-use-fast-tag-selection
9121 (delq nil (mapcar 'cdr table))))
9122 (org-fast-tag-selection
9123 current-tags inherited-tags table
9124 (if org-fast-tag-selection-include-todo org-todo-key-alist))
9125 (let ((org-add-colon-after-tag-completion t))
9126 (org-trim
9127 (org-without-partial-completion
9128 (completing-read "Tags: " 'org-tags-completion-function
9129 nil nil current 'org-tags-history)))))))
9130 (while (string-match "[-+&]+" tags)
9131 ;; No boolean logic, just a list
9132 (setq tags (replace-match ":" t t tags))))
9134 (if (string-match "\\`[\t ]*\\'" tags)
9135 (setq tags "")
9136 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
9137 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
9139 ;; Insert new tags at the correct column
9140 (beginning-of-line 1)
9141 (cond
9142 ((and (equal current "") (equal tags "")))
9143 ((re-search-forward
9144 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
9145 (point-at-eol) t)
9146 (if (equal tags "")
9147 (setq rpl "")
9148 (goto-char (match-beginning 0))
9149 (setq c0 (current-column) p0 (point)
9150 c1 (max (1+ c0) (if (> org-tags-column 0)
9151 org-tags-column
9152 (- (- org-tags-column) (length tags))))
9153 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
9154 (replace-match rpl t t)
9155 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
9156 tags)
9157 (t (error "Tags alignment failed")))
9158 (org-move-to-column col)
9159 (unless just-align
9160 (run-hooks 'org-after-tags-change-hook)))))
9162 (defun org-change-tag-in-region (beg end tag off)
9163 "Add or remove TAG for each entry in the region.
9164 This works in the agenda, and also in an org-mode buffer."
9165 (interactive
9166 (list (region-beginning) (region-end)
9167 (let ((org-last-tags-completion-table
9168 (if (org-mode-p)
9169 (org-get-buffer-tags)
9170 (org-global-tags-completion-table))))
9171 (completing-read
9172 "Tag: " 'org-tags-completion-function nil nil nil
9173 'org-tags-history))
9174 (progn
9175 (message "[s]et or [r]emove? ")
9176 (equal (read-char-exclusive) ?r))))
9177 (if (fboundp 'deactivate-mark) (deactivate-mark))
9178 (let ((agendap (equal major-mode 'org-agenda-mode))
9179 l1 l2 m buf pos newhead (cnt 0))
9180 (goto-char end)
9181 (setq l2 (1- (org-current-line)))
9182 (goto-char beg)
9183 (setq l1 (org-current-line))
9184 (loop for l from l1 to l2 do
9185 (goto-line l)
9186 (setq m (get-text-property (point) 'org-hd-marker))
9187 (when (or (and (org-mode-p) (org-on-heading-p))
9188 (and agendap m))
9189 (setq buf (if agendap (marker-buffer m) (current-buffer))
9190 pos (if agendap m (point)))
9191 (with-current-buffer buf
9192 (save-excursion
9193 (save-restriction
9194 (goto-char pos)
9195 (setq cnt (1+ cnt))
9196 (org-toggle-tag tag (if off 'off 'on))
9197 (setq newhead (org-get-heading)))))
9198 (and agendap (org-agenda-change-all-lines newhead m))))
9199 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
9201 (defun org-tags-completion-function (string predicate &optional flag)
9202 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
9203 (confirm (lambda (x) (stringp (car x)))))
9204 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
9205 (setq s1 (match-string 1 string)
9206 s2 (match-string 2 string))
9207 (setq s1 "" s2 string))
9208 (cond
9209 ((eq flag nil)
9210 ;; try completion
9211 (setq rtn (try-completion s2 ctable confirm))
9212 (if (stringp rtn)
9213 (setq rtn
9214 (concat s1 s2 (substring rtn (length s2))
9215 (if (and org-add-colon-after-tag-completion
9216 (assoc rtn ctable))
9217 ":" ""))))
9218 rtn)
9219 ((eq flag t)
9220 ;; all-completions
9221 (all-completions s2 ctable confirm)
9223 ((eq flag 'lambda)
9224 ;; exact match?
9225 (assoc s2 ctable)))
9228 (defun org-fast-tag-insert (kwd tags face &optional end)
9229 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
9230 (insert (format "%-12s" (concat kwd ":"))
9231 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
9232 (or end "")))
9234 (defun org-fast-tag-show-exit (flag)
9235 (save-excursion
9236 (goto-line 3)
9237 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
9238 (replace-match ""))
9239 (when flag
9240 (end-of-line 1)
9241 (org-move-to-column (- (window-width) 19) t)
9242 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
9244 (defun org-set-current-tags-overlay (current prefix)
9245 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
9246 (if (featurep 'xemacs)
9247 (org-overlay-display org-tags-overlay (concat prefix s)
9248 'secondary-selection)
9249 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
9250 (org-overlay-display org-tags-overlay (concat prefix s)))))
9252 (defun org-fast-tag-selection (current inherited table &optional todo-table)
9253 "Fast tag selection with single keys.
9254 CURRENT is the current list of tags in the headline, INHERITED is the
9255 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
9256 possibly with grouping information. TODO-TABLE is a similar table with
9257 TODO keywords, should these have keys assigned to them.
9258 If the keys are nil, a-z are automatically assigned.
9259 Returns the new tags string, or nil to not change the current settings."
9260 (let* ((fulltable (append table todo-table))
9261 (maxlen (apply 'max (mapcar
9262 (lambda (x)
9263 (if (stringp (car x)) (string-width (car x)) 0))
9264 fulltable)))
9265 (buf (current-buffer))
9266 (expert (eq org-fast-tag-selection-single-key 'expert))
9267 (buffer-tags nil)
9268 (fwidth (+ maxlen 3 1 3))
9269 (ncol (/ (- (window-width) 4) fwidth))
9270 (i-face 'org-done)
9271 (c-face 'org-todo)
9272 tg cnt e c char c1 c2 ntable tbl rtn
9273 ov-start ov-end ov-prefix
9274 (exit-after-next org-fast-tag-selection-single-key)
9275 (done-keywords org-done-keywords)
9276 groups ingroup)
9277 (save-excursion
9278 (beginning-of-line 1)
9279 (if (looking-at
9280 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9281 (setq ov-start (match-beginning 1)
9282 ov-end (match-end 1)
9283 ov-prefix "")
9284 (setq ov-start (1- (point-at-eol))
9285 ov-end (1+ ov-start))
9286 (skip-chars-forward "^\n\r")
9287 (setq ov-prefix
9288 (concat
9289 (buffer-substring (1- (point)) (point))
9290 (if (> (current-column) org-tags-column)
9292 (make-string (- org-tags-column (current-column)) ?\ ))))))
9293 (org-move-overlay org-tags-overlay ov-start ov-end)
9294 (save-window-excursion
9295 (if expert
9296 (set-buffer (get-buffer-create " *Org tags*"))
9297 (delete-other-windows)
9298 (split-window-vertically)
9299 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
9300 (erase-buffer)
9301 (org-set-local 'org-done-keywords done-keywords)
9302 (org-fast-tag-insert "Inherited" inherited i-face "\n")
9303 (org-fast-tag-insert "Current" current c-face "\n\n")
9304 (org-fast-tag-show-exit exit-after-next)
9305 (org-set-current-tags-overlay current ov-prefix)
9306 (setq tbl fulltable char ?a cnt 0)
9307 (while (setq e (pop tbl))
9308 (cond
9309 ((equal e '(:startgroup))
9310 (push '() groups) (setq ingroup t)
9311 (when (not (= cnt 0))
9312 (setq cnt 0)
9313 (insert "\n"))
9314 (insert "{ "))
9315 ((equal e '(:endgroup))
9316 (setq ingroup nil cnt 0)
9317 (insert "}\n"))
9319 (setq tg (car e) c2 nil)
9320 (if (cdr e)
9321 (setq c (cdr e))
9322 ;; automatically assign a character.
9323 (setq c1 (string-to-char
9324 (downcase (substring
9325 tg (if (= (string-to-char tg) ?@) 1 0)))))
9326 (if (or (rassoc c1 ntable) (rassoc c1 table))
9327 (while (or (rassoc char ntable) (rassoc char table))
9328 (setq char (1+ char)))
9329 (setq c2 c1))
9330 (setq c (or c2 char)))
9331 (if ingroup (push tg (car groups)))
9332 (setq tg (org-add-props tg nil 'face
9333 (cond
9334 ((not (assoc tg table))
9335 (org-get-todo-face tg))
9336 ((member tg current) c-face)
9337 ((member tg inherited) i-face)
9338 (t nil))))
9339 (if (and (= cnt 0) (not ingroup)) (insert " "))
9340 (insert "[" c "] " tg (make-string
9341 (- fwidth 4 (length tg)) ?\ ))
9342 (push (cons tg c) ntable)
9343 (when (= (setq cnt (1+ cnt)) ncol)
9344 (insert "\n")
9345 (if ingroup (insert " "))
9346 (setq cnt 0)))))
9347 (setq ntable (nreverse ntable))
9348 (insert "\n")
9349 (goto-char (point-min))
9350 (if (and (not expert) (fboundp 'fit-window-to-buffer))
9351 (fit-window-to-buffer))
9352 (setq rtn
9353 (catch 'exit
9354 (while t
9355 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
9356 (if groups " [!] no groups" " [!]groups")
9357 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
9358 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9359 (cond
9360 ((= c ?\r) (throw 'exit t))
9361 ((= c ?!)
9362 (setq groups (not groups))
9363 (goto-char (point-min))
9364 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
9365 ((= c ?\C-c)
9366 (if (not expert)
9367 (org-fast-tag-show-exit
9368 (setq exit-after-next (not exit-after-next)))
9369 (setq expert nil)
9370 (delete-other-windows)
9371 (split-window-vertically)
9372 (org-switch-to-buffer-other-window " *Org tags*")
9373 (and (fboundp 'fit-window-to-buffer)
9374 (fit-window-to-buffer))))
9375 ((or (= c ?\C-g)
9376 (and (= c ?q) (not (rassoc c ntable))))
9377 (org-detach-overlay org-tags-overlay)
9378 (setq quit-flag t))
9379 ((= c ?\ )
9380 (setq current nil)
9381 (if exit-after-next (setq exit-after-next 'now)))
9382 ((= c ?\t)
9383 (condition-case nil
9384 (setq tg (completing-read
9385 "Tag: "
9386 (or buffer-tags
9387 (with-current-buffer buf
9388 (org-get-buffer-tags)))))
9389 (quit (setq tg "")))
9390 (when (string-match "\\S-" tg)
9391 (add-to-list 'buffer-tags (list tg))
9392 (if (member tg current)
9393 (setq current (delete tg current))
9394 (push tg current)))
9395 (if exit-after-next (setq exit-after-next 'now)))
9396 ((setq e (rassoc c todo-table) tg (car e))
9397 (with-current-buffer buf
9398 (save-excursion (org-todo tg)))
9399 (if exit-after-next (setq exit-after-next 'now)))
9400 ((setq e (rassoc c ntable) tg (car e))
9401 (if (member tg current)
9402 (setq current (delete tg current))
9403 (loop for g in groups do
9404 (if (member tg g)
9405 (mapc (lambda (x)
9406 (setq current (delete x current)))
9407 g)))
9408 (push tg current))
9409 (if exit-after-next (setq exit-after-next 'now))))
9411 ;; Create a sorted list
9412 (setq current
9413 (sort current
9414 (lambda (a b)
9415 (assoc b (cdr (memq (assoc a ntable) ntable))))))
9416 (if (eq exit-after-next 'now) (throw 'exit t))
9417 (goto-char (point-min))
9418 (beginning-of-line 2)
9419 (delete-region (point) (point-at-eol))
9420 (org-fast-tag-insert "Current" current c-face)
9421 (org-set-current-tags-overlay current ov-prefix)
9422 (while (re-search-forward
9423 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
9424 (setq tg (match-string 1))
9425 (add-text-properties
9426 (match-beginning 1) (match-end 1)
9427 (list 'face
9428 (cond
9429 ((member tg current) c-face)
9430 ((member tg inherited) i-face)
9431 (t (get-text-property (match-beginning 1) 'face))))))
9432 (goto-char (point-min)))))
9433 (org-detach-overlay org-tags-overlay)
9434 (if rtn
9435 (mapconcat 'identity current ":")
9436 nil))))
9438 (defun org-get-tags-string ()
9439 "Get the TAGS string in the current headline."
9440 (unless (org-on-heading-p t)
9441 (error "Not on a heading"))
9442 (save-excursion
9443 (beginning-of-line 1)
9444 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9445 (org-match-string-no-properties 1)
9446 "")))
9448 (defun org-get-tags ()
9449 "Get the list of tags specified in the current headline."
9450 (org-split-string (org-get-tags-string) ":"))
9452 (defun org-get-buffer-tags ()
9453 "Get a table of all tags used in the buffer, for completion."
9454 (let (tags)
9455 (save-excursion
9456 (goto-char (point-min))
9457 (while (re-search-forward
9458 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
9459 (when (equal (char-after (point-at-bol 0)) ?*)
9460 (mapc (lambda (x) (add-to-list 'tags x))
9461 (org-split-string (org-match-string-no-properties 1) ":")))))
9462 (mapcar 'list tags)))
9464 ;;;; The mapping API
9466 ;;;###autoload
9467 (defun org-map-entries (func &optional match scope &rest skip)
9468 "Call FUNC at each headline selected by MATCH in SCOPE.
9470 FUNC is a function or a lisp form. The function will be called without
9471 arguments, with the cursor positioned at the beginning of the headline.
9472 The return values of all calls to the function will be collected and
9473 returned as a list.
9475 MATCH is a tags/property/todo match as it is used in the agenda tags view.
9476 Only headlines that are matched by this query will be considered during
9477 the iteration. When MATCH is nil or t, all headlines will be
9478 visited by the iteration.
9480 SCOPE determines the scope of this command. It can be any of:
9482 nil The current buffer, respecting the restriction if any
9483 tree The subtree started with the entry at point
9484 file The current buffer, without restriction
9485 file-with-archives
9486 The current buffer, and any archives associated with it
9487 agenda All agenda files
9488 agenda-with-archives
9489 All agenda files with any archive files associated with them
9490 \(file1 file2 ...)
9491 If this is a list, all files in the list will be scanned
9493 The remaining args are treated as settings for the skipping facilities of
9494 the scanner. The following items can be given here:
9496 archive skip trees with the archive tag.
9497 comment skip trees with the COMMENT keyword
9498 function or Emacs Lisp form:
9499 will be used as value for `org-agenda-skip-function', so whenever
9500 the the function returns t, FUNC will not be called for that
9501 entry and search will continue from the point where the
9502 function leaves it."
9503 (let* ((org-agenda-archives-mode nil) ; just to make sure
9504 (org-agenda-skip-archived-trees (memq 'archive skip))
9505 (org-agenda-skip-comment-trees (memq 'comment skip))
9506 (org-agenda-skip-function
9507 (car (org-delete-all '(comment archive) skip)))
9508 (org-tags-match-list-sublevels t)
9509 matcher pos file
9510 org-todo-keywords-for-agenda
9511 org-done-keywords-for-agenda
9512 org-todo-keyword-alist-for-agenda
9513 org-tag-alist-for-agenda)
9515 (cond
9516 ((eq match t) (setq matcher t))
9517 ((eq match nil) (setq matcher t))
9518 (t (setq matcher (if match (org-make-tags-matcher match) t))))
9520 (when (eq scope 'tree)
9521 (org-back-to-heading t)
9522 (org-narrow-to-subtree)
9523 (setq scope nil))
9525 (if (not scope)
9526 (progn
9527 (org-prepare-agenda-buffers
9528 (list (buffer-file-name (current-buffer))))
9529 (org-scan-tags func matcher))
9530 ;; Get the right scope
9531 (setq pos (point))
9532 (cond
9533 ((and scope (listp scope) (symbolp (car scope)))
9534 (setq scope (eval scope)))
9535 ((eq scope 'agenda)
9536 (setq scope (org-agenda-files t)))
9537 ((eq scope 'agenda-with-archives)
9538 (setq scope (org-agenda-files t))
9539 (setq scope (org-add-archive-files scope)))
9540 ((eq scope 'file)
9541 (setq scope (list (buffer-file-name))))
9542 ((eq scope 'file-with-archives)
9543 (setq scope (org-add-archive-files (list (buffer-file-name))))))
9544 (org-prepare-agenda-buffers scope)
9545 (while (setq file (pop scope))
9546 (with-current-buffer (org-find-base-buffer-visiting file)
9547 (save-excursion
9548 (save-restriction
9549 (widen)
9550 (goto-char (point-min))
9551 (org-scan-tags func matcher))))))))
9553 ;;;; Properties
9555 ;;; Setting and retrieving properties
9557 (defconst org-special-properties
9558 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "PRIORITY"
9559 "TIMESTAMP" "TIMESTAMP_IA")
9560 "The special properties valid in Org-mode.
9562 These are properties that are not defined in the property drawer,
9563 but in some other way.")
9565 (defconst org-default-properties
9566 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
9567 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
9568 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
9569 "EXPORT_FILE_NAME" "EXPORT_TITLE")
9570 "Some properties that are used by Org-mode for various purposes.
9571 Being in this list makes sure that they are offered for completion.")
9573 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
9574 "Regular expression matching the first line of a property drawer.")
9576 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
9577 "Regular expression matching the first line of a property drawer.")
9579 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
9580 "Regular expression matching the first line of a property drawer.")
9582 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
9583 "Regular expression matching the first line of a property drawer.")
9585 (defconst org-property-drawer-re
9586 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
9587 org-property-end-re "\\)\n?")
9588 "Matches an entire property drawer.")
9590 (defconst org-clock-drawer-re
9591 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
9592 org-property-end-re "\\)\n?")
9593 "Matches an entire clock drawer.")
9595 (defun org-property-action ()
9596 "Do an action on properties."
9597 (interactive)
9598 (let (c)
9599 (org-at-property-p)
9600 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
9601 (setq c (read-char-exclusive))
9602 (cond
9603 ((equal c ?s)
9604 (call-interactively 'org-set-property))
9605 ((equal c ?d)
9606 (call-interactively 'org-delete-property))
9607 ((equal c ?D)
9608 (call-interactively 'org-delete-property-globally))
9609 ((equal c ?c)
9610 (call-interactively 'org-compute-property-at-point))
9611 (t (error "No such property action %c" c)))))
9613 (defun org-at-property-p ()
9614 "Is the cursor in a property line?"
9615 ;; FIXME: Does not check if we are actually in the drawer.
9616 ;; FIXME: also returns true on any drawers.....
9617 ;; This is used by C-c C-c for property action.
9618 (save-excursion
9619 (beginning-of-line 1)
9620 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
9622 (defun org-get-property-block (&optional beg end force)
9623 "Return the (beg . end) range of the body of the property drawer.
9624 BEG and END can be beginning and end of subtree, if not given
9625 they will be found.
9626 If the drawer does not exist and FORCE is non-nil, create the drawer."
9627 (catch 'exit
9628 (save-excursion
9629 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
9630 (end (or end (progn (outline-next-heading) (point)))))
9631 (goto-char beg)
9632 (if (re-search-forward org-property-start-re end t)
9633 (setq beg (1+ (match-end 0)))
9634 (if force
9635 (save-excursion
9636 (org-insert-property-drawer)
9637 (setq end (progn (outline-next-heading) (point))))
9638 (throw 'exit nil))
9639 (goto-char beg)
9640 (if (re-search-forward org-property-start-re end t)
9641 (setq beg (1+ (match-end 0)))))
9642 (if (re-search-forward org-property-end-re end t)
9643 (setq end (match-beginning 0))
9644 (or force (throw 'exit nil))
9645 (goto-char beg)
9646 (setq end beg)
9647 (org-indent-line-function)
9648 (insert ":END:\n"))
9649 (cons beg end)))))
9651 (defun org-entry-properties (&optional pom which)
9652 "Get all properties of the entry at point-or-marker POM.
9653 This includes the TODO keyword, the tags, time strings for deadline,
9654 scheduled, and clocking, and any additional properties defined in the
9655 entry. The return value is an alist, keys may occur multiple times
9656 if the property key was used several times.
9657 POM may also be nil, in which case the current entry is used.
9658 If WHICH is nil or `all', get all properties. If WHICH is
9659 `special' or `standard', only get that subclass."
9660 (setq which (or which 'all))
9661 (org-with-point-at pom
9662 (let ((clockstr (substring org-clock-string 0 -1))
9663 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
9664 beg end range props sum-props key value string clocksum)
9665 (save-excursion
9666 (when (condition-case nil (org-back-to-heading t) (error nil))
9667 (setq beg (point))
9668 (setq sum-props (get-text-property (point) 'org-summaries))
9669 (setq clocksum (get-text-property (point) :org-clock-minutes))
9670 (outline-next-heading)
9671 (setq end (point))
9672 (when (memq which '(all special))
9673 ;; Get the special properties, like TODO and tags
9674 (goto-char beg)
9675 (when (and (looking-at org-todo-line-regexp) (match-end 2))
9676 (push (cons "TODO" (org-match-string-no-properties 2)) props))
9677 (when (looking-at org-priority-regexp)
9678 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
9679 (when (and (setq value (org-get-tags-string))
9680 (string-match "\\S-" value))
9681 (push (cons "TAGS" value) props))
9682 (when (setq value (org-get-tags-at))
9683 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
9684 props))
9685 (while (re-search-forward org-maybe-keyword-time-regexp end t)
9686 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
9687 string (if (equal key clockstr)
9688 (org-no-properties
9689 (org-trim
9690 (buffer-substring
9691 (match-beginning 3) (goto-char (point-at-eol)))))
9692 (substring (org-match-string-no-properties 3) 1 -1)))
9693 (unless key
9694 (if (= (char-after (match-beginning 3)) ?\[)
9695 (setq key "TIMESTAMP_IA")
9696 (setq key "TIMESTAMP")))
9697 (when (or (equal key clockstr) (not (assoc key props)))
9698 (push (cons key string) props)))
9702 (when (memq which '(all standard))
9703 ;; Get the standard properties, like :PORP: ...
9704 (setq range (org-get-property-block beg end))
9705 (when range
9706 (goto-char (car range))
9707 (while (re-search-forward
9708 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
9709 (cdr range) t)
9710 (setq key (org-match-string-no-properties 1)
9711 value (org-trim (or (org-match-string-no-properties 2) "")))
9712 (unless (member key excluded)
9713 (push (cons key (or value "")) props)))))
9714 (if clocksum
9715 (push (cons "CLOCKSUM"
9716 (org-columns-number-to-string (/ (float clocksum) 60.)
9717 'add_times))
9718 props))
9719 (append sum-props (nreverse props)))))))
9721 (defun org-entry-get (pom property &optional inherit)
9722 "Get value of PROPERTY for entry at point-or-marker POM.
9723 If INHERIT is non-nil and the entry does not have the property,
9724 then also check higher levels of the hierarchy.
9725 If INHERIT is the symbol `selective', use inheritance only if the setting
9726 in `org-use-property-inheritance' selects PROPERTY for inheritance.
9727 If the property is present but empty, the return value is the empty string.
9728 If the property is not present at all, nil is returned."
9729 (org-with-point-at pom
9730 (if (and inherit (if (eq inherit 'selective)
9731 (org-property-inherit-p property)
9733 (org-entry-get-with-inheritance property)
9734 (if (member property org-special-properties)
9735 ;; We need a special property. Use brute force, get all properties.
9736 (cdr (assoc property (org-entry-properties nil 'special)))
9737 (let ((range (org-get-property-block)))
9738 (if (and range
9739 (goto-char (car range))
9740 (re-search-forward
9741 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
9742 (cdr range) t))
9743 ;; Found the property, return it.
9744 (if (match-end 1)
9745 (org-match-string-no-properties 1)
9746 "")))))))
9748 (defun org-property-or-variable-value (var &optional inherit)
9749 "Check if there is a property fixing the value of VAR.
9750 If yes, return this value. If not, return the current value of the variable."
9751 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
9752 (if (and prop (stringp prop) (string-match "\\S-" prop))
9753 (read prop)
9754 (symbol-value var))))
9756 (defun org-entry-delete (pom property)
9757 "Delete the property PROPERTY from entry at point-or-marker POM."
9758 (org-with-point-at pom
9759 (if (member property org-special-properties)
9760 nil ; cannot delete these properties.
9761 (let ((range (org-get-property-block)))
9762 (if (and range
9763 (goto-char (car range))
9764 (re-search-forward
9765 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
9766 (cdr range) t))
9767 (progn
9768 (delete-region (match-beginning 0) (1+ (point-at-eol)))
9770 nil)))))
9772 ;; Multi-values properties are properties that contain multiple values
9773 ;; These values are assumed to be single words, separated by whitespace.
9774 (defun org-entry-add-to-multivalued-property (pom property value)
9775 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
9776 (let* ((old (org-entry-get pom property))
9777 (values (and old (org-split-string old "[ \t]"))))
9778 (unless (member value values)
9779 (setq values (cons value values))
9780 (org-entry-put pom property
9781 (mapconcat 'identity values " ")))))
9783 (defun org-entry-remove-from-multivalued-property (pom property value)
9784 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
9785 (let* ((old (org-entry-get pom property))
9786 (values (and old (org-split-string old "[ \t]"))))
9787 (when (member value values)
9788 (setq values (delete value values))
9789 (org-entry-put pom property
9790 (mapconcat 'identity values " ")))))
9792 (defun org-entry-member-in-multivalued-property (pom property value)
9793 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
9794 (let* ((old (org-entry-get pom property))
9795 (values (and old (org-split-string old "[ \t]"))))
9796 (member value values)))
9798 (defvar org-entry-property-inherited-from (make-marker))
9800 (defun org-entry-get-with-inheritance (property)
9801 "Get entry property, and search higher levels if not present."
9802 (let (tmp)
9803 (save-excursion
9804 (save-restriction
9805 (widen)
9806 (catch 'ex
9807 (while t
9808 (when (setq tmp (org-entry-get nil property))
9809 (org-back-to-heading t)
9810 (move-marker org-entry-property-inherited-from (point))
9811 (throw 'ex tmp))
9812 (or (org-up-heading-safe) (throw 'ex nil)))))
9813 (or tmp
9814 (cdr (assoc property org-file-properties))
9815 (cdr (assoc property org-global-properties))
9816 (cdr (assoc property org-global-properties-fixed))))))
9818 (defun org-entry-put (pom property value)
9819 "Set PROPERTY to VALUE for entry at point-or-marker POM."
9820 (org-with-point-at pom
9821 (org-back-to-heading t)
9822 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
9823 range)
9824 (cond
9825 ((equal property "TODO")
9826 (when (and (stringp value) (string-match "\\S-" value)
9827 (not (member value org-todo-keywords-1)))
9828 (error "\"%s\" is not a valid TODO state" value))
9829 (if (or (not value)
9830 (not (string-match "\\S-" value)))
9831 (setq value 'none))
9832 (org-todo value)
9833 (org-set-tags nil 'align))
9834 ((equal property "PRIORITY")
9835 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
9836 (string-to-char value) ?\ ))
9837 (org-set-tags nil 'align))
9838 ((equal property "SCHEDULED")
9839 (if (re-search-forward org-scheduled-time-regexp end t)
9840 (cond
9841 ((eq value 'earlier) (org-timestamp-change -1 'day))
9842 ((eq value 'later) (org-timestamp-change 1 'day))
9843 (t (call-interactively 'org-schedule)))
9844 (call-interactively 'org-schedule)))
9845 ((equal property "DEADLINE")
9846 (if (re-search-forward org-deadline-time-regexp end t)
9847 (cond
9848 ((eq value 'earlier) (org-timestamp-change -1 'day))
9849 ((eq value 'later) (org-timestamp-change 1 'day))
9850 (t (call-interactively 'org-deadline)))
9851 (call-interactively 'org-deadline)))
9852 ((member property org-special-properties)
9853 (error "The %s property can not yet be set with `org-entry-put'"
9854 property))
9855 (t ; a non-special property
9856 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
9857 (setq range (org-get-property-block beg end 'force))
9858 (goto-char (car range))
9859 (if (re-search-forward
9860 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
9861 (progn
9862 (delete-region (match-beginning 1) (match-end 1))
9863 (goto-char (match-beginning 1)))
9864 (goto-char (cdr range))
9865 (insert "\n")
9866 (backward-char 1)
9867 (org-indent-line-function)
9868 (insert ":" property ":"))
9869 (and value (insert " " value))
9870 (org-indent-line-function)))))))
9872 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
9873 "Get all property keys in the current buffer.
9874 With INCLUDE-SPECIALS, also list the special properties that relect things
9875 like tags and TODO state.
9876 With INCLUDE-DEFAULTS, also include properties that has special meaning
9877 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
9878 With INCLUDE-COLUMNS, also include property names given in COLUMN
9879 formats in the current buffer."
9880 (let (rtn range cfmt cols s p)
9881 (save-excursion
9882 (save-restriction
9883 (widen)
9884 (goto-char (point-min))
9885 (while (re-search-forward org-property-start-re nil t)
9886 (setq range (org-get-property-block))
9887 (goto-char (car range))
9888 (while (re-search-forward
9889 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
9890 (cdr range) t)
9891 (add-to-list 'rtn (org-match-string-no-properties 1)))
9892 (outline-next-heading))))
9894 (when include-specials
9895 (setq rtn (append org-special-properties rtn)))
9897 (when include-defaults
9898 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
9900 (when include-columns
9901 (save-excursion
9902 (save-restriction
9903 (widen)
9904 (goto-char (point-min))
9905 (while (re-search-forward
9906 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
9907 nil t)
9908 (setq cfmt (match-string 2) s 0)
9909 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
9910 cfmt s)
9911 (setq s (match-end 0)
9912 p (match-string 1 cfmt))
9913 (unless (or (equal p "ITEM")
9914 (member p org-special-properties))
9915 (add-to-list 'rtn (match-string 1 cfmt))))))))
9917 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
9919 (defun org-property-values (key)
9920 "Return a list of all values of property KEY."
9921 (save-excursion
9922 (save-restriction
9923 (widen)
9924 (goto-char (point-min))
9925 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
9926 values)
9927 (while (re-search-forward re nil t)
9928 (add-to-list 'values (org-trim (match-string 1))))
9929 (delete "" values)))))
9931 (defun org-insert-property-drawer ()
9932 "Insert a property drawer into the current entry."
9933 (interactive)
9934 (org-back-to-heading t)
9935 (looking-at outline-regexp)
9936 (let ((indent (- (match-end 0)(match-beginning 0)))
9937 (beg (point))
9938 (re (concat "^[ \t]*" org-keyword-time-regexp))
9939 end hiddenp)
9940 (outline-next-heading)
9941 (setq end (point))
9942 (goto-char beg)
9943 (while (re-search-forward re end t))
9944 (setq hiddenp (org-invisible-p))
9945 (end-of-line 1)
9946 (and (equal (char-after) ?\n) (forward-char 1))
9947 (while (looking-at "^[ \t]*\\(:CLOCK:\\|CLOCK\\|:END:\\)")
9948 (beginning-of-line 2))
9949 (org-skip-over-state-notes)
9950 (skip-chars-backward " \t\n\r")
9951 (if (eq (char-before) ?*) (forward-char 1))
9952 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
9953 (beginning-of-line 0)
9954 (org-indent-to-column indent)
9955 (beginning-of-line 2)
9956 (org-indent-to-column indent)
9957 (beginning-of-line 0)
9958 (if hiddenp
9959 (save-excursion
9960 (org-back-to-heading t)
9961 (hide-entry))
9962 (org-flag-drawer t))))
9964 (defun org-set-property (property value)
9965 "In the current entry, set PROPERTY to VALUE.
9966 When called interactively, this will prompt for a property name, offering
9967 completion on existing and default properties. And then it will prompt
9968 for a value, offering competion either on allowed values (via an inherited
9969 xxx_ALL property) or on existing values in other instances of this property
9970 in the current file."
9971 (interactive
9972 (let* ((completion-ignore-case t)
9973 (keys (org-buffer-property-keys nil t t))
9974 (prop0 (completing-read "Property: " (mapcar 'list keys)))
9975 (prop (if (member prop0 keys)
9976 prop0
9977 (or (cdr (assoc (downcase prop0)
9978 (mapcar (lambda (x) (cons (downcase x) x))
9979 keys)))
9980 prop0)))
9981 (cur (org-entry-get nil prop))
9982 (allowed (org-property-get-allowed-values nil prop 'table))
9983 (existing (mapcar 'list (org-property-values prop)))
9984 (val (if allowed
9985 (org-completing-read "Value: " allowed nil 'req-match)
9986 (org-completing-read
9987 (concat "Value" (if (and cur (string-match "\\S-" cur))
9988 (concat "[" cur "]") "")
9989 ": ")
9990 existing nil nil "" nil cur))))
9991 (list prop (if (equal val "") cur val))))
9992 (unless (equal (org-entry-get nil property) value)
9993 (org-entry-put nil property value)))
9995 (defun org-delete-property (property)
9996 "In the current entry, delete PROPERTY."
9997 (interactive
9998 (let* ((completion-ignore-case t)
9999 (prop (completing-read
10000 "Property: " (org-entry-properties nil 'standard))))
10001 (list prop)))
10002 (message "Property %s %s" property
10003 (if (org-entry-delete nil property)
10004 "deleted"
10005 "was not present in the entry")))
10007 (defun org-delete-property-globally (property)
10008 "Remove PROPERTY globally, from all entries."
10009 (interactive
10010 (let* ((completion-ignore-case t)
10011 (prop (completing-read
10012 "Globally remove property: "
10013 (mapcar 'list (org-buffer-property-keys)))))
10014 (list prop)))
10015 (save-excursion
10016 (save-restriction
10017 (widen)
10018 (goto-char (point-min))
10019 (let ((cnt 0))
10020 (while (re-search-forward
10021 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
10022 nil t)
10023 (setq cnt (1+ cnt))
10024 (replace-match ""))
10025 (message "Property \"%s\" removed from %d entries" property cnt)))))
10027 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
10029 (defun org-compute-property-at-point ()
10030 "Compute the property at point.
10031 This looks for an enclosing column format, extracts the operator and
10032 then applies it to the proerty in the column format's scope."
10033 (interactive)
10034 (unless (org-at-property-p)
10035 (error "Not at a property"))
10036 (let ((prop (org-match-string-no-properties 2)))
10037 (org-columns-get-format-and-top-level)
10038 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
10039 (error "No operator defined for property %s" prop))
10040 (org-columns-compute prop)))
10042 (defun org-property-get-allowed-values (pom property &optional table)
10043 "Get allowed values for the property PROPERTY.
10044 When TABLE is non-nil, return an alist that can directly be used for
10045 completion."
10046 (let (vals)
10047 (cond
10048 ((equal property "TODO")
10049 (setq vals (org-with-point-at pom
10050 (append org-todo-keywords-1 '("")))))
10051 ((equal property "PRIORITY")
10052 (let ((n org-lowest-priority))
10053 (while (>= n org-highest-priority)
10054 (push (char-to-string n) vals)
10055 (setq n (1- n)))))
10056 ((member property org-special-properties))
10058 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
10060 (when (and vals (string-match "\\S-" vals))
10061 (setq vals (car (read-from-string (concat "(" vals ")"))))
10062 (setq vals (mapcar (lambda (x)
10063 (cond ((stringp x) x)
10064 ((numberp x) (number-to-string x))
10065 ((symbolp x) (symbol-name x))
10066 (t "???")))
10067 vals)))))
10068 (if table (mapcar 'list vals) vals)))
10070 (defun org-property-previous-allowed-value (&optional previous)
10071 "Switch to the next allowed value for this property."
10072 (interactive)
10073 (org-property-next-allowed-value t))
10075 (defun org-property-next-allowed-value (&optional previous)
10076 "Switch to the next allowed value for this property."
10077 (interactive)
10078 (unless (org-at-property-p)
10079 (error "Not at a property"))
10080 (let* ((key (match-string 2))
10081 (value (match-string 3))
10082 (allowed (or (org-property-get-allowed-values (point) key)
10083 (and (member value '("[ ]" "[-]" "[X]"))
10084 '("[ ]" "[X]"))))
10085 nval)
10086 (unless allowed
10087 (error "Allowed values for this property have not been defined"))
10088 (if previous (setq allowed (reverse allowed)))
10089 (if (member value allowed)
10090 (setq nval (car (cdr (member value allowed)))))
10091 (setq nval (or nval (car allowed)))
10092 (if (equal nval value)
10093 (error "Only one allowed value for this property"))
10094 (org-at-property-p)
10095 (replace-match (concat " :" key ": " nval) t t)
10096 (org-indent-line-function)
10097 (beginning-of-line 1)
10098 (skip-chars-forward " \t")))
10100 (defun org-find-entry-with-id (ident)
10101 "Locate the entry that contains the ID property with exact value IDENT.
10102 IDENT can be a string, a symbol or a number, this function will search for
10103 the string representation of it.
10104 Return the position where this entry starts, or nil if there is no such entry."
10105 (let ((id (cond
10106 ((stringp ident) ident)
10107 ((symbol-name ident) (symbol-name ident))
10108 ((numberp ident) (number-to-string ident))
10109 (t (error "IDENT %s must be a string, symbol or number" ident))))
10110 (case-fold-search nil))
10111 (save-excursion
10112 (save-restriction
10113 (widen)
10114 (goto-char (point-min))
10115 (when (re-search-forward
10116 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
10117 nil t)
10118 (org-back-to-heading)
10119 (point))))))
10121 ;;;; Timestamps
10123 (defvar org-last-changed-timestamp nil)
10124 (defvar org-last-inserted-timestamp nil
10125 "The last time stamp inserted with `org-insert-time-stamp'.")
10126 (defvar org-time-was-given) ; dynamically scoped parameter
10127 (defvar org-end-time-was-given) ; dynamically scoped parameter
10128 (defvar org-ts-what) ; dynamically scoped parameter
10130 (defun org-time-stamp (arg)
10131 "Prompt for a date/time and insert a time stamp.
10132 If the user specifies a time like HH:MM, or if this command is called
10133 with a prefix argument, the time stamp will contain date and time.
10134 Otherwise, only the date will be included. All parts of a date not
10135 specified by the user will be filled in from the current date/time.
10136 So if you press just return without typing anything, the time stamp
10137 will represent the current date/time. If there is already a timestamp
10138 at the cursor, it will be modified."
10139 (interactive "P")
10140 (let* ((ts nil)
10141 (default-time
10142 ;; Default time is either today, or, when entering a range,
10143 ;; the range start.
10144 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
10145 (save-excursion
10146 (re-search-backward
10147 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
10148 (- (point) 20) t)))
10149 (apply 'encode-time (org-parse-time-string (match-string 1)))
10150 (current-time)))
10151 (default-input (and ts (org-get-compact-tod ts)))
10152 org-time-was-given org-end-time-was-given time)
10153 (cond
10154 ((and (org-at-timestamp-p)
10155 (eq last-command 'org-time-stamp)
10156 (eq this-command 'org-time-stamp))
10157 (insert "--")
10158 (setq time (let ((this-command this-command))
10159 (org-read-date arg 'totime nil nil default-time default-input)))
10160 (org-insert-time-stamp time (or org-time-was-given arg)))
10161 ((org-at-timestamp-p)
10162 (setq time (let ((this-command this-command))
10163 (org-read-date arg 'totime nil nil default-time default-input)))
10164 (when (org-at-timestamp-p) ; just to get the match data
10165 (replace-match "")
10166 (setq org-last-changed-timestamp
10167 (org-insert-time-stamp
10168 time (or org-time-was-given arg)
10169 nil nil nil (list org-end-time-was-given))))
10170 (message "Timestamp updated"))
10172 (setq time (let ((this-command this-command))
10173 (org-read-date arg 'totime nil nil default-time default-input)))
10174 (org-insert-time-stamp time (or org-time-was-given arg)
10175 nil nil nil (list org-end-time-was-given))))))
10177 ;; FIXME: can we use this for something else, like computing time differences?
10178 (defun org-get-compact-tod (s)
10179 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
10180 (let* ((t1 (match-string 1 s))
10181 (h1 (string-to-number (match-string 2 s)))
10182 (m1 (string-to-number (match-string 3 s)))
10183 (t2 (and (match-end 4) (match-string 5 s)))
10184 (h2 (and t2 (string-to-number (match-string 6 s))))
10185 (m2 (and t2 (string-to-number (match-string 7 s))))
10186 dh dm)
10187 (if (not t2)
10189 (setq dh (- h2 h1) dm (- m2 m1))
10190 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
10191 (concat t1 "+" (number-to-string dh)
10192 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
10194 (defun org-time-stamp-inactive (&optional arg)
10195 "Insert an inactive time stamp.
10196 An inactive time stamp is enclosed in square brackets instead of angle
10197 brackets. It is inactive in the sense that it does not trigger agenda entries,
10198 does not link to the calendar and cannot be changed with the S-cursor keys.
10199 So these are more for recording a certain time/date."
10200 (interactive "P")
10201 (let (org-time-was-given org-end-time-was-given time)
10202 (setq time (org-read-date arg 'totime))
10203 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
10204 nil nil (list org-end-time-was-given))))
10206 (defvar org-date-ovl (org-make-overlay 1 1))
10207 (org-overlay-put org-date-ovl 'face 'org-warning)
10208 (org-detach-overlay org-date-ovl)
10210 (defvar org-ans1) ; dynamically scoped parameter
10211 (defvar org-ans2) ; dynamically scoped parameter
10213 (defvar org-plain-time-of-day-regexp) ; defined below
10215 (defvar org-overriding-default-time nil) ; dynamically scoped
10216 (defvar org-read-date-overlay nil)
10217 (defvar org-dcst nil) ; dynamically scoped
10219 (defun org-read-date (&optional with-time to-time from-string prompt
10220 default-time default-input)
10221 "Read a date, possibly a time, and make things smooth for the user.
10222 The prompt will suggest to enter an ISO date, but you can also enter anything
10223 which will at least partially be understood by `parse-time-string'.
10224 Unrecognized parts of the date will default to the current day, month, year,
10225 hour and minute. If this command is called to replace a timestamp at point,
10226 of to enter the second timestamp of a range, the default time is taken from the
10227 existing stamp. For example,
10228 3-2-5 --> 2003-02-05
10229 feb 15 --> currentyear-02-15
10230 sep 12 9 --> 2009-09-12
10231 12:45 --> today 12:45
10232 22 sept 0:34 --> currentyear-09-22 0:34
10233 12 --> currentyear-currentmonth-12
10234 Fri --> nearest Friday (today or later)
10235 etc.
10237 Furthermore you can specify a relative date by giving, as the *first* thing
10238 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
10239 change in days weeks, months, years.
10240 With a single plus or minus, the date is relative to today. With a double
10241 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
10242 +4d --> four days from today
10243 +4 --> same as above
10244 +2w --> two weeks from today
10245 ++5 --> five days from default date
10247 The function understands only English month and weekday abbreviations,
10248 but this can be configured with the variables `parse-time-months' and
10249 `parse-time-weekdays'.
10251 While prompting, a calendar is popped up - you can also select the
10252 date with the mouse (button 1). The calendar shows a period of three
10253 months. To scroll it to other months, use the keys `>' and `<'.
10254 If you don't like the calendar, turn it off with
10255 \(setq org-read-date-popup-calendar nil)
10257 With optional argument TO-TIME, the date will immediately be converted
10258 to an internal time.
10259 With an optional argument WITH-TIME, the prompt will suggest to also
10260 insert a time. Note that when WITH-TIME is not set, you can still
10261 enter a time, and this function will inform the calling routine about
10262 this change. The calling routine may then choose to change the format
10263 used to insert the time stamp into the buffer to include the time.
10264 With optional argument FROM-STRING, read from this string instead from
10265 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
10266 the time/date that is used for everything that is not specified by the
10267 user."
10268 (require 'parse-time)
10269 (let* ((org-time-stamp-rounding-minutes
10270 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
10271 (org-dcst org-display-custom-times)
10272 (ct (org-current-time))
10273 (def (or org-overriding-default-time default-time ct))
10274 (defdecode (decode-time def))
10275 (dummy (progn
10276 (when (< (nth 2 defdecode) org-extend-today-until)
10277 (setcar (nthcdr 2 defdecode) -1)
10278 (setcar (nthcdr 1 defdecode) 59)
10279 (setq def (apply 'encode-time defdecode)
10280 defdecode (decode-time def)))))
10281 (calendar-move-hook nil)
10282 (calendar-view-diary-initially-flag nil)
10283 (view-diary-entries-initially nil)
10284 (calendar-view-holidays-initially-flag nil)
10285 (view-calendar-holidays-initially nil)
10286 (timestr (format-time-string
10287 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
10288 (prompt (concat (if prompt (concat prompt " ") "")
10289 (format "Date+time [%s]: " timestr)))
10290 ans (org-ans0 "") org-ans1 org-ans2 final)
10292 (cond
10293 (from-string (setq ans from-string))
10294 (org-read-date-popup-calendar
10295 (save-excursion
10296 (save-window-excursion
10297 (calendar)
10298 (calendar-forward-day (- (time-to-days def)
10299 (calendar-absolute-from-gregorian
10300 (calendar-current-date))))
10301 (org-eval-in-calendar nil t)
10302 (let* ((old-map (current-local-map))
10303 (map (copy-keymap calendar-mode-map))
10304 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
10305 (org-defkey map (kbd "RET") 'org-calendar-select)
10306 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
10307 'org-calendar-select-mouse)
10308 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
10309 'org-calendar-select-mouse)
10310 (org-defkey minibuffer-local-map [(meta shift left)]
10311 (lambda () (interactive)
10312 (org-eval-in-calendar '(calendar-backward-month 1))))
10313 (org-defkey minibuffer-local-map [(meta shift right)]
10314 (lambda () (interactive)
10315 (org-eval-in-calendar '(calendar-forward-month 1))))
10316 (org-defkey minibuffer-local-map [(meta shift up)]
10317 (lambda () (interactive)
10318 (org-eval-in-calendar '(calendar-backward-year 1))))
10319 (org-defkey minibuffer-local-map [(meta shift down)]
10320 (lambda () (interactive)
10321 (org-eval-in-calendar '(calendar-forward-year 1))))
10322 (org-defkey minibuffer-local-map [(shift up)]
10323 (lambda () (interactive)
10324 (org-eval-in-calendar '(calendar-backward-week 1))))
10325 (org-defkey minibuffer-local-map [(shift down)]
10326 (lambda () (interactive)
10327 (org-eval-in-calendar '(calendar-forward-week 1))))
10328 (org-defkey minibuffer-local-map [(shift left)]
10329 (lambda () (interactive)
10330 (org-eval-in-calendar '(calendar-backward-day 1))))
10331 (org-defkey minibuffer-local-map [(shift right)]
10332 (lambda () (interactive)
10333 (org-eval-in-calendar '(calendar-forward-day 1))))
10334 (org-defkey minibuffer-local-map ">"
10335 (lambda () (interactive)
10336 (org-eval-in-calendar '(scroll-calendar-left 1))))
10337 (org-defkey minibuffer-local-map "<"
10338 (lambda () (interactive)
10339 (org-eval-in-calendar '(scroll-calendar-right 1))))
10340 (unwind-protect
10341 (progn
10342 (use-local-map map)
10343 (add-hook 'post-command-hook 'org-read-date-display)
10344 (setq org-ans0 (read-string prompt default-input nil nil))
10345 ;; org-ans0: from prompt
10346 ;; org-ans1: from mouse click
10347 ;; org-ans2: from calendar motion
10348 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
10349 (remove-hook 'post-command-hook 'org-read-date-display)
10350 (use-local-map old-map)
10351 (when org-read-date-overlay
10352 (org-delete-overlay org-read-date-overlay)
10353 (setq org-read-date-overlay nil)))))))
10355 (t ; Naked prompt only
10356 (unwind-protect
10357 (setq ans (read-string prompt default-input nil timestr))
10358 (when org-read-date-overlay
10359 (org-delete-overlay org-read-date-overlay)
10360 (setq org-read-date-overlay nil)))))
10362 (setq final (org-read-date-analyze ans def defdecode))
10364 (if to-time
10365 (apply 'encode-time final)
10366 (if (and (boundp 'org-time-was-given) org-time-was-given)
10367 (format "%04d-%02d-%02d %02d:%02d"
10368 (nth 5 final) (nth 4 final) (nth 3 final)
10369 (nth 2 final) (nth 1 final))
10370 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
10371 (defvar def)
10372 (defvar defdecode)
10373 (defvar with-time)
10374 (defun org-read-date-display ()
10375 "Display the currrent date prompt interpretation in the minibuffer."
10376 (when org-read-date-display-live
10377 (when org-read-date-overlay
10378 (org-delete-overlay org-read-date-overlay))
10379 (let ((p (point)))
10380 (end-of-line 1)
10381 (while (not (equal (buffer-substring
10382 (max (point-min) (- (point) 4)) (point))
10383 " "))
10384 (insert " "))
10385 (goto-char p))
10386 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
10387 " " (or org-ans1 org-ans2)))
10388 (org-end-time-was-given nil)
10389 (f (org-read-date-analyze ans def defdecode))
10390 (fmts (if org-dcst
10391 org-time-stamp-custom-formats
10392 org-time-stamp-formats))
10393 (fmt (if (or with-time
10394 (and (boundp 'org-time-was-given) org-time-was-given))
10395 (cdr fmts)
10396 (car fmts)))
10397 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
10398 (when (and org-end-time-was-given
10399 (string-match org-plain-time-of-day-regexp txt))
10400 (setq txt (concat (substring txt 0 (match-end 0)) "-"
10401 org-end-time-was-given
10402 (substring txt (match-end 0)))))
10403 (setq org-read-date-overlay
10404 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
10405 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
10407 (defun org-read-date-analyze (ans def defdecode)
10408 "Analyze the combined answer of the date prompt."
10409 ;; FIXME: cleanup and comment
10410 (let (delta deltan deltaw deltadef year month day
10411 hour minute second wday pm h2 m2 tl wday1
10412 iso-year iso-weekday iso-week iso-year iso-date)
10414 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
10415 (setq ans "+0"))
10417 (when (setq delta (org-read-date-get-relative ans (current-time) def))
10418 (setq ans (replace-match "" t t ans)
10419 deltan (car delta)
10420 deltaw (nth 1 delta)
10421 deltadef (nth 2 delta)))
10423 ;; Check if there is an iso week date in there
10424 ;; If yes, sore the info and ostpone interpreting it until the rest
10425 ;; of the parsing is done
10426 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
10427 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
10428 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
10429 iso-week (string-to-number (match-string 2 ans)))
10430 (setq ans (replace-match "" t t ans)))
10432 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
10433 (when (string-match
10434 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
10435 (setq year (if (match-end 2)
10436 (string-to-number (match-string 2 ans))
10437 (string-to-number (format-time-string "%Y")))
10438 month (string-to-number (match-string 3 ans))
10439 day (string-to-number (match-string 4 ans)))
10440 (if (< year 100) (setq year (+ 2000 year)))
10441 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
10442 t nil ans)))
10443 ;; Help matching am/pm times, because `parse-time-string' does not do that.
10444 ;; If there is a time with am/pm, and *no* time without it, we convert
10445 ;; so that matching will be successful.
10446 (loop for i from 1 to 2 do ; twice, for end time as well
10447 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
10448 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
10449 (setq hour (string-to-number (match-string 1 ans))
10450 minute (if (match-end 3)
10451 (string-to-number (match-string 3 ans))
10453 pm (equal ?p
10454 (string-to-char (downcase (match-string 4 ans)))))
10455 (if (and (= hour 12) (not pm))
10456 (setq hour 0)
10457 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
10458 (setq ans (replace-match (format "%02d:%02d" hour minute)
10459 t t ans))))
10461 ;; Check if a time range is given as a duration
10462 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
10463 (setq hour (string-to-number (match-string 1 ans))
10464 h2 (+ hour (string-to-number (match-string 3 ans)))
10465 minute (string-to-number (match-string 2 ans))
10466 m2 (+ minute (if (match-end 5) (string-to-number
10467 (match-string 5 ans))0)))
10468 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
10469 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
10470 t t ans)))
10472 ;; Check if there is a time range
10473 (when (boundp 'org-end-time-was-given)
10474 (setq org-time-was-given nil)
10475 (when (and (string-match org-plain-time-of-day-regexp ans)
10476 (match-end 8))
10477 (setq org-end-time-was-given (match-string 8 ans))
10478 (setq ans (concat (substring ans 0 (match-beginning 7))
10479 (substring ans (match-end 7))))))
10481 (setq tl (parse-time-string ans)
10482 day (or (nth 3 tl) (nth 3 defdecode))
10483 month (or (nth 4 tl)
10484 (if (and org-read-date-prefer-future
10485 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
10486 (1+ (nth 4 defdecode))
10487 (nth 4 defdecode)))
10488 year (or (nth 5 tl)
10489 (if (and org-read-date-prefer-future
10490 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
10491 (1+ (nth 5 defdecode))
10492 (nth 5 defdecode)))
10493 hour (or (nth 2 tl) (nth 2 defdecode))
10494 minute (or (nth 1 tl) (nth 1 defdecode))
10495 second (or (nth 0 tl) 0)
10496 wday (nth 6 tl))
10498 ;; Special date definitions below
10499 (cond
10500 (iso-week
10501 ;; There was an iso week
10502 (setq year (or iso-year year)
10503 day (or iso-weekday wday 1)
10504 wday nil ; to make sure that the trigger below does not match
10505 iso-date (calendar-gregorian-from-absolute
10506 (calendar-absolute-from-iso
10507 (list iso-week day year))))
10508 ; FIXME: Should we also push ISO weeks into the future?
10509 ; (when (and org-read-date-prefer-future
10510 ; (not iso-year)
10511 ; (< (calendar-absolute-from-gregorian iso-date)
10512 ; (time-to-days (current-time))))
10513 ; (setq year (1+ year)
10514 ; iso-date (calendar-gregorian-from-absolute
10515 ; (calendar-absolute-from-iso
10516 ; (list iso-week day year)))))
10517 (setq month (car iso-date)
10518 year (nth 2 iso-date)
10519 day (nth 1 iso-date)))
10520 (deltan
10521 (unless deltadef
10522 (let ((now (decode-time (current-time))))
10523 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
10524 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
10525 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
10526 ((equal deltaw "m") (setq month (+ month deltan)))
10527 ((equal deltaw "y") (setq year (+ year deltan)))))
10528 ((and wday (not (nth 3 tl)))
10529 ;; Weekday was given, but no day, so pick that day in the week
10530 ;; on or after the derived date.
10531 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
10532 (unless (equal wday wday1)
10533 (setq day (+ day (% (- wday wday1 -7) 7))))))
10534 (if (and (boundp 'org-time-was-given)
10535 (nth 2 tl))
10536 (setq org-time-was-given t))
10537 (if (< year 100) (setq year (+ 2000 year)))
10538 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
10539 (list second minute hour day month year)))
10541 (defvar parse-time-weekdays)
10543 (defun org-read-date-get-relative (s today default)
10544 "Check string S for special relative date string.
10545 TODAY and DEFAULT are internal times, for today and for a default.
10546 Return shift list (N what def-flag)
10547 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
10548 N is the number of WHATs to shift.
10549 DEF-FLAG is t when a double ++ or -- indicates shift relative to
10550 the DEFAULT date rather than TODAY."
10551 (when (and
10552 (string-match
10553 (concat
10554 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
10555 "\\([0-9]+\\)?"
10556 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
10557 "\\([ \t]\\|$\\)") s)
10558 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
10559 (let* ((dir (if (> (match-end 1) (match-beginning 1))
10560 (string-to-char (substring (match-string 1 s) -1))
10561 ?+))
10562 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
10563 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
10564 (what (if (match-end 3) (match-string 3 s) "d"))
10565 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
10566 (date (if rel default today))
10567 (wday (nth 6 (decode-time date)))
10568 delta)
10569 (if wday1
10570 (progn
10571 (setq delta (mod (+ 7 (- wday1 wday)) 7))
10572 (if (= dir ?-) (setq delta (- delta 7)))
10573 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
10574 (list delta "d" rel))
10575 (list (* n (if (= dir ?-) -1 1)) what rel)))))
10577 (defun org-eval-in-calendar (form &optional keepdate)
10578 "Eval FORM in the calendar window and return to current window.
10579 Also, store the cursor date in variable org-ans2."
10580 (let ((sw (selected-window)))
10581 (select-window (get-buffer-window "*Calendar*"))
10582 (eval form)
10583 (when (and (not keepdate) (calendar-cursor-to-date))
10584 (let* ((date (calendar-cursor-to-date))
10585 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10586 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
10587 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
10588 (select-window sw)))
10590 ; ;; Update the prompt to show new default date
10591 ; (save-excursion
10592 ; (goto-char (point-min))
10593 ; (when (and org-ans2
10594 ; (re-search-forward "\\[[-0-9]+\\]" nil t)
10595 ; (get-text-property (match-end 0) 'field))
10596 ; (let ((inhibit-read-only t))
10597 ; (replace-match (concat "[" org-ans2 "]") t t)
10598 ; (add-text-properties (point-min) (1+ (match-end 0))
10599 ; (text-properties-at (1+ (point-min)))))))))
10601 (defun org-calendar-select ()
10602 "Return to `org-read-date' with the date currently selected.
10603 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
10604 (interactive)
10605 (when (calendar-cursor-to-date)
10606 (let* ((date (calendar-cursor-to-date))
10607 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10608 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
10609 (if (active-minibuffer-window) (exit-minibuffer))))
10611 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
10612 "Insert a date stamp for the date given by the internal TIME.
10613 WITH-HM means, use the stamp format that includes the time of the day.
10614 INACTIVE means use square brackets instead of angular ones, so that the
10615 stamp will not contribute to the agenda.
10616 PRE and POST are optional strings to be inserted before and after the
10617 stamp.
10618 The command returns the inserted time stamp."
10619 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
10620 stamp)
10621 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
10622 (insert-before-markers (or pre ""))
10623 (insert-before-markers (setq stamp (format-time-string fmt time)))
10624 (when (listp extra)
10625 (setq extra (car extra))
10626 (if (and (stringp extra)
10627 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
10628 (setq extra (format "-%02d:%02d"
10629 (string-to-number (match-string 1 extra))
10630 (string-to-number (match-string 2 extra))))
10631 (setq extra nil)))
10632 (when extra
10633 (backward-char 1)
10634 (insert-before-markers extra)
10635 (forward-char 1))
10636 (insert-before-markers (or post ""))
10637 (setq org-last-inserted-timestamp stamp)))
10639 (defun org-toggle-time-stamp-overlays ()
10640 "Toggle the use of custom time stamp formats."
10641 (interactive)
10642 (setq org-display-custom-times (not org-display-custom-times))
10643 (unless org-display-custom-times
10644 (let ((p (point-min)) (bmp (buffer-modified-p)))
10645 (while (setq p (next-single-property-change p 'display))
10646 (if (and (get-text-property p 'display)
10647 (eq (get-text-property p 'face) 'org-date))
10648 (remove-text-properties
10649 p (setq p (next-single-property-change p 'display))
10650 '(display t))))
10651 (set-buffer-modified-p bmp)))
10652 (if (featurep 'xemacs)
10653 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
10654 (org-restart-font-lock)
10655 (setq org-table-may-need-update t)
10656 (if org-display-custom-times
10657 (message "Time stamps are overlayed with custom format")
10658 (message "Time stamp overlays removed")))
10660 (defun org-display-custom-time (beg end)
10661 "Overlay modified time stamp format over timestamp between BEG and END."
10662 (let* ((ts (buffer-substring beg end))
10663 t1 w1 with-hm tf time str w2 (off 0))
10664 (save-match-data
10665 (setq t1 (org-parse-time-string ts t))
10666 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
10667 (setq off (- (match-end 0) (match-beginning 0)))))
10668 (setq end (- end off))
10669 (setq w1 (- end beg)
10670 with-hm (and (nth 1 t1) (nth 2 t1))
10671 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
10672 time (org-fix-decoded-time t1)
10673 str (org-add-props
10674 (format-time-string
10675 (substring tf 1 -1) (apply 'encode-time time))
10676 nil 'mouse-face 'highlight)
10677 w2 (length str))
10678 (if (not (= w2 w1))
10679 (add-text-properties (1+ beg) (+ 2 beg)
10680 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
10681 (if (featurep 'xemacs)
10682 (progn
10683 (put-text-property beg end 'invisible t)
10684 (put-text-property beg end 'end-glyph (make-glyph str)))
10685 (put-text-property beg end 'display str))))
10687 (defun org-translate-time (string)
10688 "Translate all timestamps in STRING to custom format.
10689 But do this only if the variable `org-display-custom-times' is set."
10690 (when org-display-custom-times
10691 (save-match-data
10692 (let* ((start 0)
10693 (re org-ts-regexp-both)
10694 t1 with-hm inactive tf time str beg end)
10695 (while (setq start (string-match re string start))
10696 (setq beg (match-beginning 0)
10697 end (match-end 0)
10698 t1 (save-match-data
10699 (org-parse-time-string (substring string beg end) t))
10700 with-hm (and (nth 1 t1) (nth 2 t1))
10701 inactive (equal (substring string beg (1+ beg)) "[")
10702 tf (funcall (if with-hm 'cdr 'car)
10703 org-time-stamp-custom-formats)
10704 time (org-fix-decoded-time t1)
10705 str (format-time-string
10706 (concat
10707 (if inactive "[" "<") (substring tf 1 -1)
10708 (if inactive "]" ">"))
10709 (apply 'encode-time time))
10710 string (replace-match str t t string)
10711 start (+ start (length str)))))))
10712 string)
10714 (defun org-fix-decoded-time (time)
10715 "Set 0 instead of nil for the first 6 elements of time.
10716 Don't touch the rest."
10717 (let ((n 0))
10718 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
10720 (defun org-days-to-time (timestamp-string)
10721 "Difference between TIMESTAMP-STRING and now in days."
10722 (- (time-to-days (org-time-string-to-time timestamp-string))
10723 (time-to-days (current-time))))
10725 (defun org-deadline-close (timestamp-string &optional ndays)
10726 "Is the time in TIMESTAMP-STRING close to the current date?"
10727 (setq ndays (or ndays (org-get-wdays timestamp-string)))
10728 (and (< (org-days-to-time timestamp-string) ndays)
10729 (not (org-entry-is-done-p))))
10731 (defun org-get-wdays (ts)
10732 "Get the deadline lead time appropriate for timestring TS."
10733 (cond
10734 ((<= org-deadline-warning-days 0)
10735 ;; 0 or negative, enforce this value no matter what
10736 (- org-deadline-warning-days))
10737 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
10738 ;; lead time is specified.
10739 (floor (* (string-to-number (match-string 1 ts))
10740 (cdr (assoc (match-string 2 ts)
10741 '(("d" . 1) ("w" . 7)
10742 ("m" . 30.4) ("y" . 365.25)))))))
10743 ;; go for the default.
10744 (t org-deadline-warning-days)))
10746 (defun org-calendar-select-mouse (ev)
10747 "Return to `org-read-date' with the date currently selected.
10748 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
10749 (interactive "e")
10750 (mouse-set-point ev)
10751 (when (calendar-cursor-to-date)
10752 (let* ((date (calendar-cursor-to-date))
10753 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10754 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
10755 (if (active-minibuffer-window) (exit-minibuffer))))
10757 (defun org-check-deadlines (ndays)
10758 "Check if there are any deadlines due or past due.
10759 A deadline is considered due if it happens within `org-deadline-warning-days'
10760 days from today's date. If the deadline appears in an entry marked DONE,
10761 it is not shown. The prefix arg NDAYS can be used to test that many
10762 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
10763 (interactive "P")
10764 (let* ((org-warn-days
10765 (cond
10766 ((equal ndays '(4)) 100000)
10767 (ndays (prefix-numeric-value ndays))
10768 (t (abs org-deadline-warning-days))))
10769 (case-fold-search nil)
10770 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
10771 (callback
10772 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
10774 (message "%d deadlines past-due or due within %d days"
10775 (org-occur regexp nil callback)
10776 org-warn-days)))
10778 (defun org-check-before-date (date)
10779 "Check if there are deadlines or scheduled entries before DATE."
10780 (interactive (list (org-read-date)))
10781 (let ((case-fold-search nil)
10782 (regexp (concat "\\<\\(" org-deadline-string
10783 "\\|" org-scheduled-string
10784 "\\) *<\\([^>]+\\)>"))
10785 (callback
10786 (lambda () (time-less-p
10787 (org-time-string-to-time (match-string 2))
10788 (org-time-string-to-time date)))))
10789 (message "%d entries before %s"
10790 (org-occur regexp nil callback) date)))
10792 (defun org-evaluate-time-range (&optional to-buffer)
10793 "Evaluate a time range by computing the difference between start and end.
10794 Normally the result is just printed in the echo area, but with prefix arg
10795 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
10796 If the time range is actually in a table, the result is inserted into the
10797 next column.
10798 For time difference computation, a year is assumed to be exactly 365
10799 days in order to avoid rounding problems."
10800 (interactive "P")
10802 (org-clock-update-time-maybe)
10803 (save-excursion
10804 (unless (org-at-date-range-p t)
10805 (goto-char (point-at-bol))
10806 (re-search-forward org-tr-regexp-both (point-at-eol) t))
10807 (if (not (org-at-date-range-p t))
10808 (error "Not at a time-stamp range, and none found in current line")))
10809 (let* ((ts1 (match-string 1))
10810 (ts2 (match-string 2))
10811 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
10812 (match-end (match-end 0))
10813 (time1 (org-time-string-to-time ts1))
10814 (time2 (org-time-string-to-time ts2))
10815 (t1 (time-to-seconds time1))
10816 (t2 (time-to-seconds time2))
10817 (diff (abs (- t2 t1)))
10818 (negative (< (- t2 t1) 0))
10819 ;; (ys (floor (* 365 24 60 60)))
10820 (ds (* 24 60 60))
10821 (hs (* 60 60))
10822 (fy "%dy %dd %02d:%02d")
10823 (fy1 "%dy %dd")
10824 (fd "%dd %02d:%02d")
10825 (fd1 "%dd")
10826 (fh "%02d:%02d")
10827 y d h m align)
10828 (if havetime
10829 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
10831 d (floor (/ diff ds)) diff (mod diff ds)
10832 h (floor (/ diff hs)) diff (mod diff hs)
10833 m (floor (/ diff 60)))
10834 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
10836 d (floor (+ (/ diff ds) 0.5))
10837 h 0 m 0))
10838 (if (not to-buffer)
10839 (message "%s" (org-make-tdiff-string y d h m))
10840 (if (org-at-table-p)
10841 (progn
10842 (goto-char match-end)
10843 (setq align t)
10844 (and (looking-at " *|") (goto-char (match-end 0))))
10845 (goto-char match-end))
10846 (if (looking-at
10847 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
10848 (replace-match ""))
10849 (if negative (insert " -"))
10850 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
10851 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
10852 (insert " " (format fh h m))))
10853 (if align (org-table-align))
10854 (message "Time difference inserted")))))
10856 (defun org-make-tdiff-string (y d h m)
10857 (let ((fmt "")
10858 (l nil))
10859 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
10860 l (push y l)))
10861 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
10862 l (push d l)))
10863 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
10864 l (push h l)))
10865 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
10866 l (push m l)))
10867 (apply 'format fmt (nreverse l))))
10869 (defun org-time-string-to-time (s)
10870 (apply 'encode-time (org-parse-time-string s)))
10872 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
10873 "Convert a time stamp to an absolute day number.
10874 If there is a specifyer for a cyclic time stamp, get the closest date to
10875 DAYNR.
10876 PREFER and SHOW_ALL are passed through to `org-closest-date'."
10877 (cond
10878 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
10879 (if (org-diary-sexp-entry (match-string 1 s) "" date)
10880 daynr
10881 (+ daynr 1000)))
10882 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
10883 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
10884 (time-to-days (current-time))) (match-string 0 s)
10885 prefer show-all))
10886 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
10888 (defun org-days-to-iso-week (days)
10889 "Return the iso week number."
10890 (require 'cal-iso)
10891 (car (calendar-iso-from-absolute days)))
10893 (defun org-small-year-to-year (year)
10894 "Convert 2-digit years into 4-digit years.
10895 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
10896 The year 2000 cannot be abbreviated. Any year lager than 99
10897 is retrned unchanged."
10898 (if (< year 38)
10899 (setq year (+ 2000 year))
10900 (if (< year 100)
10901 (setq year (+ 1900 year))))
10902 year)
10904 (defun org-time-from-absolute (d)
10905 "Return the time corresponding to date D.
10906 D may be an absolute day number, or a calendar-type list (month day year)."
10907 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
10908 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
10910 (defun org-calendar-holiday ()
10911 "List of holidays, for Diary display in Org-mode."
10912 (require 'holidays)
10913 (let ((hl (funcall
10914 (if (fboundp 'calendar-check-holidays)
10915 'calendar-check-holidays 'check-calendar-holidays) date)))
10916 (if hl (mapconcat 'identity hl "; "))))
10918 (defun org-diary-sexp-entry (sexp entry date)
10919 "Process a SEXP diary ENTRY for DATE."
10920 (require 'diary-lib)
10921 (let ((result (if calendar-debug-sexp
10922 (let ((stack-trace-on-error t))
10923 (eval (car (read-from-string sexp))))
10924 (condition-case nil
10925 (eval (car (read-from-string sexp)))
10926 (error
10927 (beep)
10928 (message "Bad sexp at line %d in %s: %s"
10929 (org-current-line)
10930 (buffer-file-name) sexp)
10931 (sleep-for 2))))))
10932 (cond ((stringp result) result)
10933 ((and (consp result)
10934 (stringp (cdr result))) (cdr result))
10935 (result entry)
10936 (t nil))))
10938 (defun org-diary-to-ical-string (frombuf)
10939 "Get iCalendar entries from diary entries in buffer FROMBUF.
10940 This uses the icalendar.el library."
10941 (let* ((tmpdir (if (featurep 'xemacs)
10942 (temp-directory)
10943 temporary-file-directory))
10944 (tmpfile (make-temp-name
10945 (expand-file-name "orgics" tmpdir)))
10946 buf rtn b e)
10947 (save-excursion
10948 (set-buffer frombuf)
10949 (icalendar-export-region (point-min) (point-max) tmpfile)
10950 (setq buf (find-buffer-visiting tmpfile))
10951 (set-buffer buf)
10952 (goto-char (point-min))
10953 (if (re-search-forward "^BEGIN:VEVENT" nil t)
10954 (setq b (match-beginning 0)))
10955 (goto-char (point-max))
10956 (if (re-search-backward "^END:VEVENT" nil t)
10957 (setq e (match-end 0)))
10958 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
10959 (kill-buffer buf)
10960 (delete-file tmpfile)
10961 rtn))
10963 (defun org-closest-date (start current change prefer show-all)
10964 "Find the date closest to CURRENT that is consistent with START and CHANGE.
10965 When PREFER is `past' return a date that is either CURRENT or past.
10966 When PREFER is `future', return a date that is either CURRENT or future.
10967 When SHOW-ALL is nil, only return the current occurence of a time stamp."
10968 ;; Make the proper lists from the dates
10969 (catch 'exit
10970 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
10971 dn dw sday cday n1 n2
10972 d m y y1 y2 date1 date2 nmonths nm ny m2)
10974 (setq start (org-date-to-gregorian start)
10975 current (org-date-to-gregorian
10976 (if show-all
10977 current
10978 (time-to-days (current-time))))
10979 sday (calendar-absolute-from-gregorian start)
10980 cday (calendar-absolute-from-gregorian current))
10982 (if (<= cday sday) (throw 'exit sday))
10984 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
10985 (setq dn (string-to-number (match-string 1 change))
10986 dw (cdr (assoc (match-string 2 change) a1)))
10987 (error "Invalid change specifyer: %s" change))
10988 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
10989 (cond
10990 ((eq dw 'day)
10991 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
10992 n2 (+ n1 dn)))
10993 ((eq dw 'year)
10994 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
10995 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
10996 (setq date1 (list m d y1)
10997 n1 (calendar-absolute-from-gregorian date1)
10998 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
10999 n2 (calendar-absolute-from-gregorian date2)))
11000 ((eq dw 'month)
11001 ;; approx number of month between the two dates
11002 (setq nmonths (floor (/ (- cday sday) 30.436875)))
11003 ;; How often does dn fit in there?
11004 (setq d (nth 1 start) m (car start) y (nth 2 start)
11005 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
11006 m (+ m nm)
11007 ny (floor (/ m 12))
11008 y (+ y ny)
11009 m (- m (* ny 12)))
11010 (while (> m 12) (setq m (- m 12) y (1+ y)))
11011 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
11012 (setq m2 (+ m dn) y2 y)
11013 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11014 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
11015 (while (<= n2 cday)
11016 (setq n1 n2 m m2 y y2)
11017 (setq m2 (+ m dn) y2 y)
11018 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11019 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
11020 (if show-all
11021 (cond
11022 ((eq prefer 'past) n1)
11023 ((eq prefer 'future) (if (= cday n1) n1 n2))
11024 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
11025 (cond
11026 ((eq prefer 'past) n1)
11027 ((eq prefer 'future) (if (= cday n1) n1 n2))
11028 (t (if (= cday n1) n1 n2)))))))
11030 (defun org-date-to-gregorian (date)
11031 "Turn any specification of DATE into a gregorian date for the calendar."
11032 (cond ((integerp date) (calendar-gregorian-from-absolute date))
11033 ((and (listp date) (= (length date) 3)) date)
11034 ((stringp date)
11035 (setq date (org-parse-time-string date))
11036 (list (nth 4 date) (nth 3 date) (nth 5 date)))
11037 ((listp date)
11038 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
11040 (defun org-parse-time-string (s &optional nodefault)
11041 "Parse the standard Org-mode time string.
11042 This should be a lot faster than the normal `parse-time-string'.
11043 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
11044 hour and minute fields will be nil if not given."
11045 (if (string-match org-ts-regexp0 s)
11046 (list 0
11047 (if (or (match-beginning 8) (not nodefault))
11048 (string-to-number (or (match-string 8 s) "0")))
11049 (if (or (match-beginning 7) (not nodefault))
11050 (string-to-number (or (match-string 7 s) "0")))
11051 (string-to-number (match-string 4 s))
11052 (string-to-number (match-string 3 s))
11053 (string-to-number (match-string 2 s))
11054 nil nil nil)
11055 (make-list 9 0)))
11057 (defun org-timestamp-up (&optional arg)
11058 "Increase the date item at the cursor by one.
11059 If the cursor is on the year, change the year. If it is on the month or
11060 the day, change that.
11061 With prefix ARG, change by that many units."
11062 (interactive "p")
11063 (org-timestamp-change (prefix-numeric-value arg)))
11065 (defun org-timestamp-down (&optional arg)
11066 "Decrease the date item at the cursor by one.
11067 If the cursor is on the year, change the year. If it is on the month or
11068 the day, change that.
11069 With prefix ARG, change by that many units."
11070 (interactive "p")
11071 (org-timestamp-change (- (prefix-numeric-value arg))))
11073 (defun org-timestamp-up-day (&optional arg)
11074 "Increase the date in the time stamp by one day.
11075 With prefix ARG, change that many days."
11076 (interactive "p")
11077 (if (and (not (org-at-timestamp-p t))
11078 (org-on-heading-p))
11079 (org-todo 'up)
11080 (org-timestamp-change (prefix-numeric-value arg) 'day)))
11082 (defun org-timestamp-down-day (&optional arg)
11083 "Decrease the date in the time stamp by one day.
11084 With prefix ARG, change that many days."
11085 (interactive "p")
11086 (if (and (not (org-at-timestamp-p t))
11087 (org-on-heading-p))
11088 (org-todo 'down)
11089 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
11091 (defun org-at-timestamp-p (&optional inactive-ok)
11092 "Determine if the cursor is in or at a timestamp."
11093 (interactive)
11094 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
11095 (pos (point))
11096 (ans (or (looking-at tsr)
11097 (save-excursion
11098 (skip-chars-backward "^[<\n\r\t")
11099 (if (> (point) (point-min)) (backward-char 1))
11100 (and (looking-at tsr)
11101 (> (- (match-end 0) pos) -1))))))
11102 (and ans
11103 (boundp 'org-ts-what)
11104 (setq org-ts-what
11105 (cond
11106 ((= pos (match-beginning 0)) 'bracket)
11107 ((= pos (1- (match-end 0))) 'bracket)
11108 ((org-pos-in-match-range pos 2) 'year)
11109 ((org-pos-in-match-range pos 3) 'month)
11110 ((org-pos-in-match-range pos 7) 'hour)
11111 ((org-pos-in-match-range pos 8) 'minute)
11112 ((or (org-pos-in-match-range pos 4)
11113 (org-pos-in-match-range pos 5)) 'day)
11114 ((and (> pos (or (match-end 8) (match-end 5)))
11115 (< pos (match-end 0)))
11116 (- pos (or (match-end 8) (match-end 5))))
11117 (t 'day))))
11118 ans))
11120 (defun org-toggle-timestamp-type ()
11121 "Toggle the type (<active> or [inactive]) of a time stamp."
11122 (interactive)
11123 (when (org-at-timestamp-p t)
11124 (save-excursion
11125 (goto-char (match-beginning 0))
11126 (insert (if (equal (char-after) ?<) "[" "<")) (delete-char 1)
11127 (goto-char (1- (match-end 0)))
11128 (insert (if (equal (char-after) ?>) "]" ">")) (delete-char 1))
11129 (message "Timestamp is now %sactive"
11130 (if (equal (char-before) ?>) "in" ""))))
11132 (defun org-timestamp-change (n &optional what)
11133 "Change the date in the time stamp at point.
11134 The date will be changed by N times WHAT. WHAT can be `day', `month',
11135 `year', `minute', `second'. If WHAT is not given, the cursor position
11136 in the timestamp determines what will be changed."
11137 (let ((pos (point))
11138 with-hm inactive
11139 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
11140 org-ts-what
11141 extra rem
11142 ts time time0)
11143 (if (not (org-at-timestamp-p t))
11144 (error "Not at a timestamp"))
11145 (if (and (not what) (eq org-ts-what 'bracket))
11146 (org-toggle-timestamp-type)
11147 (if (and (not what) (not (eq org-ts-what 'day))
11148 org-display-custom-times
11149 (get-text-property (point) 'display)
11150 (not (get-text-property (1- (point)) 'display)))
11151 (setq org-ts-what 'day))
11152 (setq org-ts-what (or what org-ts-what)
11153 inactive (= (char-after (match-beginning 0)) ?\[)
11154 ts (match-string 0))
11155 (replace-match "")
11156 (if (string-match
11157 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
11159 (setq extra (match-string 1 ts)))
11160 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
11161 (setq with-hm t))
11162 (setq time0 (org-parse-time-string ts))
11163 (when (and (eq org-ts-what 'minute)
11164 (eq current-prefix-arg nil))
11165 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
11166 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
11167 (setcar (cdr time0) (+ (nth 1 time0)
11168 (if (> n 0) (- rem) (- dm rem))))))
11169 (setq time
11170 (encode-time (or (car time0) 0)
11171 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
11172 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
11173 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
11174 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
11175 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
11176 (nthcdr 6 time0)))
11177 (when (integerp org-ts-what)
11178 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
11179 (if (eq what 'calendar)
11180 (let ((cal-date (org-get-date-from-calendar)))
11181 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
11182 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
11183 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
11184 (setcar time0 (or (car time0) 0))
11185 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
11186 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
11187 (setq time (apply 'encode-time time0))))
11188 (setq org-last-changed-timestamp
11189 (org-insert-time-stamp time with-hm inactive nil nil extra))
11190 (org-clock-update-time-maybe)
11191 (goto-char pos)
11192 ;; Try to recenter the calendar window, if any
11193 (if (and org-calendar-follow-timestamp-change
11194 (get-buffer-window "*Calendar*" t)
11195 (memq org-ts-what '(day month year)))
11196 (org-recenter-calendar (time-to-days time))))))
11198 (defun org-modify-ts-extra (s pos n dm)
11199 "Change the different parts of the lead-time and repeat fields in timestamp."
11200 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
11201 ng h m new rem)
11202 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
11203 (cond
11204 ((or (org-pos-in-match-range pos 2)
11205 (org-pos-in-match-range pos 3))
11206 (setq m (string-to-number (match-string 3 s))
11207 h (string-to-number (match-string 2 s)))
11208 (if (org-pos-in-match-range pos 2)
11209 (setq h (+ h n))
11210 (setq n (* dm (org-no-warnings (signum n))))
11211 (when (not (= 0 (setq rem (% m dm))))
11212 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
11213 (setq m (+ m n)))
11214 (if (< m 0) (setq m (+ m 60) h (1- h)))
11215 (if (> m 59) (setq m (- m 60) h (1+ h)))
11216 (setq h (min 24 (max 0 h)))
11217 (setq ng 1 new (format "-%02d:%02d" h m)))
11218 ((org-pos-in-match-range pos 6)
11219 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
11220 ((org-pos-in-match-range pos 5)
11221 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
11223 ((org-pos-in-match-range pos 9)
11224 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
11225 ((org-pos-in-match-range pos 8)
11226 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
11228 (when ng
11229 (setq s (concat
11230 (substring s 0 (match-beginning ng))
11232 (substring s (match-end ng))))))
11235 (defun org-recenter-calendar (date)
11236 "If the calendar is visible, recenter it to DATE."
11237 (let* ((win (selected-window))
11238 (cwin (get-buffer-window "*Calendar*" t))
11239 (calendar-move-hook nil))
11240 (when cwin
11241 (select-window cwin)
11242 (calendar-goto-date (if (listp date) date
11243 (calendar-gregorian-from-absolute date)))
11244 (select-window win))))
11246 (defun org-goto-calendar (&optional arg)
11247 "Go to the Emacs calendar at the current date.
11248 If there is a time stamp in the current line, go to that date.
11249 A prefix ARG can be used to force the current date."
11250 (interactive "P")
11251 (let ((tsr org-ts-regexp) diff
11252 (calendar-move-hook nil)
11253 (calendar-view-holidays-initially-flag nil)
11254 (view-calendar-holidays-initially nil)
11255 (calendar-view-diary-initially-flag nil)
11256 (view-diary-entries-initially nil))
11257 (if (or (org-at-timestamp-p)
11258 (save-excursion
11259 (beginning-of-line 1)
11260 (looking-at (concat ".*" tsr))))
11261 (let ((d1 (time-to-days (current-time)))
11262 (d2 (time-to-days
11263 (org-time-string-to-time (match-string 1)))))
11264 (setq diff (- d2 d1))))
11265 (calendar)
11266 (calendar-goto-today)
11267 (if (and diff (not arg)) (calendar-forward-day diff))))
11269 (defun org-get-date-from-calendar ()
11270 "Return a list (month day year) of date at point in calendar."
11271 (with-current-buffer "*Calendar*"
11272 (save-match-data
11273 (calendar-cursor-to-date))))
11275 (defun org-date-from-calendar ()
11276 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
11277 If there is already a time stamp at the cursor position, update it."
11278 (interactive)
11279 (if (org-at-timestamp-p t)
11280 (org-timestamp-change 0 'calendar)
11281 (let ((cal-date (org-get-date-from-calendar)))
11282 (org-insert-time-stamp
11283 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
11285 (defun org-minutes-to-hh:mm-string (m)
11286 "Compute H:MM from a number of minutes."
11287 (let ((h (/ m 60)))
11288 (setq m (- m (* 60 h)))
11289 (format org-time-clocksum-format h m)))
11291 (defun org-hh:mm-string-to-minutes (s)
11292 "Convert a string H:MM to a number of minutes."
11293 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
11294 (+ (* (string-to-number (match-string 1 s)) 60)
11295 (string-to-number (match-string 2 s)))
11298 ;;;; Agenda files
11300 ;;;###autoload
11301 (defun org-iswitchb (&optional arg)
11302 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
11303 With a prefix argument, restrict available to files.
11304 With two prefix arguments, restrict available buffers to agenda files.
11306 Due to some yet unresolved reason, the global function
11307 `iswitchb-mode' needs to be active for this function to work."
11308 (interactive "P")
11309 (require 'iswitchb)
11310 (let ((enabled iswitchb-mode) blist)
11311 (or enabled (iswitchb-mode 1))
11312 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
11313 ((equal arg '(16)) (org-buffer-list 'agenda))
11314 (t (org-buffer-list))))
11315 (unwind-protect
11316 (let ((iswitchb-make-buflist-hook
11317 (lambda ()
11318 (setq iswitchb-temp-buflist
11319 (mapcar 'buffer-name blist)))))
11320 (switch-to-buffer
11321 (iswitchb-read-buffer
11322 "Switch-to: " nil t))
11323 (or enabled (iswitchb-mode -1))))))
11325 (defun org-buffer-list (&optional predicate exclude-tmp)
11326 "Return a list of Org buffers.
11327 PREDICATE can be `export', `files' or `agenda'.
11329 export restrict the list to Export buffers.
11330 files restrict the list to buffers visiting Org files.
11331 agenda restrict the list to buffers visiting agenda files.
11333 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
11334 (let* ((bfn nil)
11335 (agenda-files (and (eq predicate 'agenda)
11336 (mapcar 'file-truename (org-agenda-files t))))
11337 (filter
11338 (cond
11339 ((eq predicate 'files)
11340 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
11341 ((eq predicate 'export)
11342 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
11343 ((eq predicate 'agenda)
11344 (lambda (b)
11345 (with-current-buffer b
11346 (and (eq major-mode 'org-mode)
11347 (setq bfn (buffer-file-name b))
11348 (member (file-truename bfn) agenda-files)))))
11349 (t (lambda (b) (with-current-buffer b
11350 (or (eq major-mode 'org-mode)
11351 (string-match "\*Org .*Export"
11352 (buffer-name b)))))))))
11353 (delq nil
11354 (mapcar
11355 (lambda(b)
11356 (if (and (funcall filter b)
11357 (or (not exclude-tmp)
11358 (not (string-match "tmp" (buffer-name b)))))
11360 nil))
11361 (buffer-list)))))
11363 (defun org-agenda-files (&optional unrestricted archives)
11364 "Get the list of agenda files.
11365 Optional UNRESTRICTED means return the full list even if a restriction
11366 is currently in place.
11367 When ARCHIVES is t, include all archive files hat are really being
11368 used by the agenda files. If ARCHIVE is `ifmode', do this only if
11369 `org-agenda-archives-mode' is t."
11370 (let ((files
11371 (cond
11372 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
11373 ((stringp org-agenda-files) (org-read-agenda-file-list))
11374 ((listp org-agenda-files) org-agenda-files)
11375 (t (error "Invalid value of `org-agenda-files'")))))
11376 (setq files (apply 'append
11377 (mapcar (lambda (f)
11378 (if (file-directory-p f)
11379 (directory-files
11380 f t org-agenda-file-regexp)
11381 (list f)))
11382 files)))
11383 (when org-agenda-skip-unavailable-files
11384 (setq files (delq nil
11385 (mapcar (function
11386 (lambda (file)
11387 (and (file-readable-p file) file)))
11388 files))))
11389 (when (or (eq archives t)
11390 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
11391 (setq files (org-add-archive-files files)))
11392 files))
11394 (defun org-edit-agenda-file-list ()
11395 "Edit the list of agenda files.
11396 Depending on setup, this either uses customize to edit the variable
11397 `org-agenda-files', or it visits the file that is holding the list. In the
11398 latter case, the buffer is set up in a way that saving it automatically kills
11399 the buffer and restores the previous window configuration."
11400 (interactive)
11401 (if (stringp org-agenda-files)
11402 (let ((cw (current-window-configuration)))
11403 (find-file org-agenda-files)
11404 (org-set-local 'org-window-configuration cw)
11405 (org-add-hook 'after-save-hook
11406 (lambda ()
11407 (set-window-configuration
11408 (prog1 org-window-configuration
11409 (kill-buffer (current-buffer))))
11410 (org-install-agenda-files-menu)
11411 (message "New agenda file list installed"))
11412 nil 'local)
11413 (message "%s" (substitute-command-keys
11414 "Edit list and finish with \\[save-buffer]")))
11415 (customize-variable 'org-agenda-files)))
11417 (defun org-store-new-agenda-file-list (list)
11418 "Set new value for the agenda file list and save it correcly."
11419 (if (stringp org-agenda-files)
11420 (let ((f org-agenda-files) b)
11421 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
11422 (with-temp-file f
11423 (insert (mapconcat 'identity list "\n") "\n")))
11424 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
11425 (setq org-agenda-files list)
11426 (customize-save-variable 'org-agenda-files org-agenda-files))))
11428 (defun org-read-agenda-file-list ()
11429 "Read the list of agenda files from a file."
11430 (when (file-directory-p org-agenda-files)
11431 (error "`org-agenda-files' cannot be a single directory"))
11432 (when (stringp org-agenda-files)
11433 (with-temp-buffer
11434 (insert-file-contents org-agenda-files)
11435 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
11438 ;;;###autoload
11439 (defun org-cycle-agenda-files ()
11440 "Cycle through the files in `org-agenda-files'.
11441 If the current buffer visits an agenda file, find the next one in the list.
11442 If the current buffer does not, find the first agenda file."
11443 (interactive)
11444 (let* ((fs (org-agenda-files t))
11445 (files (append fs (list (car fs))))
11446 (tcf (if buffer-file-name (file-truename buffer-file-name)))
11447 file)
11448 (unless files (error "No agenda files"))
11449 (catch 'exit
11450 (while (setq file (pop files))
11451 (if (equal (file-truename file) tcf)
11452 (when (car files)
11453 (find-file (car files))
11454 (throw 'exit t))))
11455 (find-file (car fs)))
11456 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
11458 (defun org-agenda-file-to-front (&optional to-end)
11459 "Move/add the current file to the top of the agenda file list.
11460 If the file is not present in the list, it is added to the front. If it is
11461 present, it is moved there. With optional argument TO-END, add/move to the
11462 end of the list."
11463 (interactive "P")
11464 (let ((org-agenda-skip-unavailable-files nil)
11465 (file-alist (mapcar (lambda (x)
11466 (cons (file-truename x) x))
11467 (org-agenda-files t)))
11468 (ctf (file-truename buffer-file-name))
11469 x had)
11470 (setq x (assoc ctf file-alist) had x)
11472 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
11473 (if to-end
11474 (setq file-alist (append (delq x file-alist) (list x)))
11475 (setq file-alist (cons x (delq x file-alist))))
11476 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
11477 (org-install-agenda-files-menu)
11478 (message "File %s to %s of agenda file list"
11479 (if had "moved" "added") (if to-end "end" "front"))))
11481 (defun org-remove-file (&optional file)
11482 "Remove current file from the list of files in variable `org-agenda-files'.
11483 These are the files which are being checked for agenda entries.
11484 Optional argument FILE means, use this file instead of the current."
11485 (interactive)
11486 (let* ((org-agenda-skip-unavailable-files nil)
11487 (file (or file buffer-file-name))
11488 (true-file (file-truename file))
11489 (afile (abbreviate-file-name file))
11490 (files (delq nil (mapcar
11491 (lambda (x)
11492 (if (equal true-file
11493 (file-truename x))
11494 nil x))
11495 (org-agenda-files t)))))
11496 (if (not (= (length files) (length (org-agenda-files t))))
11497 (progn
11498 (org-store-new-agenda-file-list files)
11499 (org-install-agenda-files-menu)
11500 (message "Removed file: %s" afile))
11501 (message "File was not in list: %s (not removed)" afile))))
11503 (defun org-file-menu-entry (file)
11504 (vector file (list 'find-file file) t))
11506 (defun org-check-agenda-file (file)
11507 "Make sure FILE exists. If not, ask user what to do."
11508 (when (not (file-exists-p file))
11509 (message "non-existent file %s. [R]emove from list or [A]bort?"
11510 (abbreviate-file-name file))
11511 (let ((r (downcase (read-char-exclusive))))
11512 (cond
11513 ((equal r ?r)
11514 (org-remove-file file)
11515 (throw 'nextfile t))
11516 (t (error "Abort"))))))
11518 (defun org-get-agenda-file-buffer (file)
11519 "Get a buffer visiting FILE. If the buffer needs to be created, add
11520 it to the list of buffers which might be released later."
11521 (let ((buf (org-find-base-buffer-visiting file)))
11522 (if buf
11523 buf ; just return it
11524 ;; Make a new buffer and remember it
11525 (setq buf (find-file-noselect file))
11526 (if buf (push buf org-agenda-new-buffers))
11527 buf)))
11529 (defun org-release-buffers (blist)
11530 "Release all buffers in list, asking the user for confirmation when needed.
11531 When a buffer is unmodified, it is just killed. When modified, it is saved
11532 \(if the user agrees) and then killed."
11533 (let (buf file)
11534 (while (setq buf (pop blist))
11535 (setq file (buffer-file-name buf))
11536 (when (and (buffer-modified-p buf)
11537 file
11538 (y-or-n-p (format "Save file %s? " file)))
11539 (with-current-buffer buf (save-buffer)))
11540 (kill-buffer buf))))
11542 (defun org-prepare-agenda-buffers (files)
11543 "Create buffers for all agenda files, protect archived trees and comments."
11544 (interactive)
11545 (let ((pa '(:org-archived t))
11546 (pc '(:org-comment t))
11547 (pall '(:org-archived t :org-comment t))
11548 (inhibit-read-only t)
11549 (rea (concat ":" org-archive-tag ":"))
11550 bmp file re)
11551 (save-excursion
11552 (save-restriction
11553 (while (setq file (pop files))
11554 (if (bufferp file)
11555 (set-buffer file)
11556 (org-check-agenda-file file)
11557 (set-buffer (org-get-agenda-file-buffer file)))
11558 (widen)
11559 (setq bmp (buffer-modified-p))
11560 (org-refresh-category-properties)
11561 (setq org-todo-keywords-for-agenda
11562 (append org-todo-keywords-for-agenda org-todo-keywords-1))
11563 (setq org-done-keywords-for-agenda
11564 (append org-done-keywords-for-agenda org-done-keywords))
11565 (setq org-todo-keyword-alist-for-agenda
11566 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
11567 (setq org-tag-alist-for-agenda
11568 (append org-tag-alist-for-agenda org-tag-alist))
11570 (save-excursion
11571 (remove-text-properties (point-min) (point-max) pall)
11572 (when org-agenda-skip-archived-trees
11573 (goto-char (point-min))
11574 (while (re-search-forward rea nil t)
11575 (if (org-on-heading-p t)
11576 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
11577 (goto-char (point-min))
11578 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
11579 (while (re-search-forward re nil t)
11580 (add-text-properties
11581 (match-beginning 0) (org-end-of-subtree t) pc)))
11582 (set-buffer-modified-p bmp))))
11583 (setq org-todo-keyword-alist-for-agenda
11584 (org-uniquify org-todo-keyword-alist-for-agenda)
11585 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
11587 ;;;; Embedded LaTeX
11589 (defvar org-cdlatex-mode-map (make-sparse-keymap)
11590 "Keymap for the minor `org-cdlatex-mode'.")
11592 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
11593 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
11594 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
11595 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
11596 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
11598 (defvar org-cdlatex-texmathp-advice-is-done nil
11599 "Flag remembering if we have applied the advice to texmathp already.")
11601 (define-minor-mode org-cdlatex-mode
11602 "Toggle the minor `org-cdlatex-mode'.
11603 This mode supports entering LaTeX environment and math in LaTeX fragments
11604 in Org-mode.
11605 \\{org-cdlatex-mode-map}"
11606 nil " OCDL" nil
11607 (when org-cdlatex-mode (require 'cdlatex))
11608 (unless org-cdlatex-texmathp-advice-is-done
11609 (setq org-cdlatex-texmathp-advice-is-done t)
11610 (defadvice texmathp (around org-math-always-on activate)
11611 "Always return t in org-mode buffers.
11612 This is because we want to insert math symbols without dollars even outside
11613 the LaTeX math segments. If Orgmode thinks that point is actually inside
11614 en embedded LaTeX fragement, let texmathp do its job.
11615 \\[org-cdlatex-mode-map]"
11616 (interactive)
11617 (let (p)
11618 (cond
11619 ((not (org-mode-p)) ad-do-it)
11620 ((eq this-command 'cdlatex-math-symbol)
11621 (setq ad-return-value t
11622 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
11624 (let ((p (org-inside-LaTeX-fragment-p)))
11625 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
11626 (setq ad-return-value t
11627 texmathp-why '("Org-mode embedded math" . 0))
11628 (if p ad-do-it)))))))))
11630 (defun turn-on-org-cdlatex ()
11631 "Unconditionally turn on `org-cdlatex-mode'."
11632 (org-cdlatex-mode 1))
11634 (defun org-inside-LaTeX-fragment-p ()
11635 "Test if point is inside a LaTeX fragment.
11636 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
11637 sequence appearing also before point.
11638 Even though the matchers for math are configurable, this function assumes
11639 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
11640 delimiters are skipped when they have been removed by customization.
11641 The return value is nil, or a cons cell with the delimiter and
11642 and the position of this delimiter.
11644 This function does a reasonably good job, but can locally be fooled by
11645 for example currency specifications. For example it will assume being in
11646 inline math after \"$22.34\". The LaTeX fragment formatter will only format
11647 fragments that are properly closed, but during editing, we have to live
11648 with the uncertainty caused by missing closing delimiters. This function
11649 looks only before point, not after."
11650 (catch 'exit
11651 (let ((pos (point))
11652 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
11653 (lim (progn
11654 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
11655 (point)))
11656 dd-on str (start 0) m re)
11657 (goto-char pos)
11658 (when dodollar
11659 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
11660 re (nth 1 (assoc "$" org-latex-regexps)))
11661 (while (string-match re str start)
11662 (cond
11663 ((= (match-end 0) (length str))
11664 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
11665 ((= (match-end 0) (- (length str) 5))
11666 (throw 'exit nil))
11667 (t (setq start (match-end 0))))))
11668 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
11669 (goto-char pos)
11670 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
11671 (and (match-beginning 2) (throw 'exit nil))
11672 ;; count $$
11673 (while (re-search-backward "\\$\\$" lim t)
11674 (setq dd-on (not dd-on)))
11675 (goto-char pos)
11676 (if dd-on (cons "$$" m))))))
11679 (defun org-try-cdlatex-tab ()
11680 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
11681 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
11682 - inside a LaTeX fragment, or
11683 - after the first word in a line, where an abbreviation expansion could
11684 insert a LaTeX environment."
11685 (when org-cdlatex-mode
11686 (cond
11687 ((save-excursion
11688 (skip-chars-backward "a-zA-Z0-9*")
11689 (skip-chars-backward " \t")
11690 (bolp))
11691 (cdlatex-tab) t)
11692 ((org-inside-LaTeX-fragment-p)
11693 (cdlatex-tab) t)
11694 (t nil))))
11696 (defun org-cdlatex-underscore-caret (&optional arg)
11697 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
11698 Revert to the normal definition outside of these fragments."
11699 (interactive "P")
11700 (if (org-inside-LaTeX-fragment-p)
11701 (call-interactively 'cdlatex-sub-superscript)
11702 (let (org-cdlatex-mode)
11703 (call-interactively (key-binding (vector last-input-event))))))
11705 (defun org-cdlatex-math-modify (&optional arg)
11706 "Execute `cdlatex-math-modify' in LaTeX fragments.
11707 Revert to the normal definition outside of these fragments."
11708 (interactive "P")
11709 (if (org-inside-LaTeX-fragment-p)
11710 (call-interactively 'cdlatex-math-modify)
11711 (let (org-cdlatex-mode)
11712 (call-interactively (key-binding (vector last-input-event))))))
11714 (defvar org-latex-fragment-image-overlays nil
11715 "List of overlays carrying the images of latex fragments.")
11716 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
11718 (defun org-remove-latex-fragment-image-overlays ()
11719 "Remove all overlays with LaTeX fragment images in current buffer."
11720 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
11721 (setq org-latex-fragment-image-overlays nil))
11723 (defun org-preview-latex-fragment (&optional subtree)
11724 "Preview the LaTeX fragment at point, or all locally or globally.
11725 If the cursor is in a LaTeX fragment, create the image and overlay
11726 it over the source code. If there is no fragment at point, display
11727 all fragments in the current text, from one headline to the next. With
11728 prefix SUBTREE, display all fragments in the current subtree. With a
11729 double prefix `C-u C-u', or when the cursor is before the first headline,
11730 display all fragments in the buffer.
11731 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
11732 (interactive "P")
11733 (org-remove-latex-fragment-image-overlays)
11734 (save-excursion
11735 (save-restriction
11736 (let (beg end at msg)
11737 (cond
11738 ((or (equal subtree '(16))
11739 (not (save-excursion
11740 (re-search-backward (concat "^" outline-regexp) nil t))))
11741 (setq beg (point-min) end (point-max)
11742 msg "Creating images for buffer...%s"))
11743 ((equal subtree '(4))
11744 (org-back-to-heading)
11745 (setq beg (point) end (org-end-of-subtree t)
11746 msg "Creating images for subtree...%s"))
11748 (if (setq at (org-inside-LaTeX-fragment-p))
11749 (goto-char (max (point-min) (- (cdr at) 2)))
11750 (org-back-to-heading))
11751 (setq beg (point) end (progn (outline-next-heading) (point))
11752 msg (if at "Creating image...%s"
11753 "Creating images for entry...%s"))))
11754 (message msg "")
11755 (narrow-to-region beg end)
11756 (goto-char beg)
11757 (org-format-latex
11758 (concat "ltxpng/" (file-name-sans-extension
11759 (file-name-nondirectory
11760 buffer-file-name)))
11761 default-directory 'overlays msg at 'forbuffer)
11762 (message msg "done. Use `C-c C-c' to remove images.")))))
11764 (defvar org-latex-regexps
11765 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
11766 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
11767 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
11768 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
11769 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
11770 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
11771 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
11772 "Regular expressions for matching embedded LaTeX.")
11774 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
11775 "Replace LaTeX fragments with links to an image, and produce images."
11776 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
11777 (let* ((prefixnodir (file-name-nondirectory prefix))
11778 (absprefix (expand-file-name prefix dir))
11779 (todir (file-name-directory absprefix))
11780 (opt org-format-latex-options)
11781 (matchers (plist-get opt :matchers))
11782 (re-list org-latex-regexps)
11783 (cnt 0) txt link beg end re e checkdir
11784 m n block linkfile movefile ov)
11785 ;; Check if there are old images files with this prefix, and remove them
11786 (when (file-directory-p todir)
11787 (mapc 'delete-file
11788 (directory-files
11789 todir 'full
11790 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
11791 ;; Check the different regular expressions
11792 (while (setq e (pop re-list))
11793 (setq m (car e) re (nth 1 e) n (nth 2 e)
11794 block (if (nth 3 e) "\n\n" ""))
11795 (when (member m matchers)
11796 (goto-char (point-min))
11797 (while (re-search-forward re nil t)
11798 (when (or (not at) (equal (cdr at) (match-beginning n)))
11799 (setq txt (match-string n)
11800 beg (match-beginning n) end (match-end n)
11801 cnt (1+ cnt)
11802 linkfile (format "%s_%04d.png" prefix cnt)
11803 movefile (format "%s_%04d.png" absprefix cnt)
11804 link (concat block "[[file:" linkfile "]]" block))
11805 (if msg (message msg cnt))
11806 (goto-char beg)
11807 (unless checkdir ; make sure the directory exists
11808 (setq checkdir t)
11809 (or (file-directory-p todir) (make-directory todir)))
11810 (org-create-formula-image
11811 txt movefile opt forbuffer)
11812 (if overlays
11813 (progn
11814 (setq ov (org-make-overlay beg end))
11815 (if (featurep 'xemacs)
11816 (progn
11817 (org-overlay-put ov 'invisible t)
11818 (org-overlay-put
11819 ov 'end-glyph
11820 (make-glyph (vector 'png :file movefile))))
11821 (org-overlay-put
11822 ov 'display
11823 (list 'image :type 'png :file movefile :ascent 'center)))
11824 (push ov org-latex-fragment-image-overlays)
11825 (goto-char end))
11826 (delete-region beg end)
11827 (insert link))))))))
11829 ;; This function borrows from Ganesh Swami's latex2png.el
11830 (defun org-create-formula-image (string tofile options buffer)
11831 (let* ((tmpdir (if (featurep 'xemacs)
11832 (temp-directory)
11833 temporary-file-directory))
11834 (texfilebase (make-temp-name
11835 (expand-file-name "orgtex" tmpdir)))
11836 (texfile (concat texfilebase ".tex"))
11837 (dvifile (concat texfilebase ".dvi"))
11838 (pngfile (concat texfilebase ".png"))
11839 (fnh (if (featurep 'xemacs)
11840 (font-height (get-face-font 'default))
11841 (face-attribute 'default :height nil)))
11842 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
11843 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
11844 (fg (or (plist-get options (if buffer :foreground :html-foreground))
11845 "Black"))
11846 (bg (or (plist-get options (if buffer :background :html-background))
11847 "Transparent")))
11848 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
11849 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
11850 (with-temp-file texfile
11851 (insert org-format-latex-header
11852 "\n\\begin{document}\n" string "\n\\end{document}\n"))
11853 (let ((dir default-directory))
11854 (condition-case nil
11855 (progn
11856 (cd tmpdir)
11857 (call-process "latex" nil nil nil texfile))
11858 (error nil))
11859 (cd dir))
11860 (if (not (file-exists-p dvifile))
11861 (progn (message "Failed to create dvi file from %s" texfile) nil)
11862 (condition-case nil
11863 (call-process "dvipng" nil nil nil
11864 "-E" "-fg" fg "-bg" bg
11865 "-D" dpi
11866 ;;"-x" scale "-y" scale
11867 "-T" "tight"
11868 "-o" pngfile
11869 dvifile)
11870 (error nil))
11871 (if (not (file-exists-p pngfile))
11872 (progn (message "Failed to create png file from %s" texfile) nil)
11873 ;; Use the requested file name and clean up
11874 (copy-file pngfile tofile 'replace)
11875 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
11876 (delete-file (concat texfilebase e)))
11877 pngfile))))
11879 (defun org-dvipng-color (attr)
11880 "Return an rgb color specification for dvipng."
11881 (apply 'format "rgb %s %s %s"
11882 (mapcar 'org-normalize-color
11883 (color-values (face-attribute 'default attr nil)))))
11885 (defun org-normalize-color (value)
11886 "Return string to be used as color value for an RGB component."
11887 (format "%g" (/ value 65535.0)))
11890 ;;;; Key bindings
11892 ;; Make `C-c C-x' a prefix key
11893 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
11895 ;; TAB key with modifiers
11896 (org-defkey org-mode-map "\C-i" 'org-cycle)
11897 (org-defkey org-mode-map [(tab)] 'org-cycle)
11898 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
11899 (org-defkey org-mode-map [(meta tab)] 'org-complete)
11900 (org-defkey org-mode-map "\M-\t" 'org-complete)
11901 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
11902 ;; The following line is necessary under Suse GNU/Linux
11903 (unless (featurep 'xemacs)
11904 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
11905 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
11906 (define-key org-mode-map [backtab] 'org-shifttab)
11908 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
11909 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
11910 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
11912 ;; Cursor keys with modifiers
11913 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
11914 (org-defkey org-mode-map [(meta right)] 'org-metaright)
11915 (org-defkey org-mode-map [(meta up)] 'org-metaup)
11916 (org-defkey org-mode-map [(meta down)] 'org-metadown)
11918 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
11919 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
11920 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
11921 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
11923 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
11924 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
11925 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
11926 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
11928 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
11929 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
11931 ;;; Extra keys for tty access.
11932 ;; We only set them when really needed because otherwise the
11933 ;; menus don't show the simple keys
11935 (when (or org-use-extra-keys
11936 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
11937 (not window-system))
11938 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
11939 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
11940 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
11941 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
11942 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
11943 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
11944 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
11945 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
11946 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
11947 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
11948 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
11949 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
11950 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
11951 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
11952 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
11953 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
11954 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
11955 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
11956 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
11957 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
11958 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
11959 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
11961 ;; All the other keys
11963 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
11964 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
11965 (if (boundp 'narrow-map)
11966 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
11967 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
11968 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
11969 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
11970 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
11971 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
11972 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
11973 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
11974 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
11975 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
11976 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
11977 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
11978 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
11979 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
11980 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
11981 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
11982 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
11983 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
11984 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
11985 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
11986 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
11987 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
11988 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
11989 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
11990 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
11991 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
11992 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
11993 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
11994 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
11995 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
11996 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
11997 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
11998 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
11999 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
12000 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
12001 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
12002 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
12003 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
12004 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
12005 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
12006 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
12007 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
12008 (org-defkey org-mode-map "\C-c^" 'org-sort)
12009 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
12010 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
12011 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
12012 (org-defkey org-mode-map "\C-m" 'org-return)
12013 (org-defkey org-mode-map "\C-j" 'org-return-indent)
12014 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
12015 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
12016 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
12017 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
12018 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
12019 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
12020 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
12021 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
12022 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
12023 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
12024 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
12025 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
12026 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
12027 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
12028 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
12030 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
12031 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
12032 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
12033 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
12035 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
12036 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
12037 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
12038 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
12039 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
12040 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
12041 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
12042 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
12043 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
12044 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
12045 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
12046 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
12048 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
12050 (when (featurep 'xemacs)
12051 (org-defkey org-mode-map 'button3 'popup-mode-menu))
12053 (defvar org-table-auto-blank-field) ; defined in org-table.el
12054 (defun org-self-insert-command (N)
12055 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
12056 If the cursor is in a table looking at whitespace, the whitespace is
12057 overwritten, and the table is not marked as requiring realignment."
12058 (interactive "p")
12059 (if (and (org-table-p)
12060 (progn
12061 ;; check if we blank the field, and if that triggers align
12062 (and (featurep 'org-table) org-table-auto-blank-field
12063 (member last-command
12064 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
12065 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
12066 ;; got extra space, this field does not determine column width
12067 (let (org-table-may-need-update) (org-table-blank-field))
12068 ;; no extra space, this field may determine column width
12069 (org-table-blank-field)))
12071 (eq N 1)
12072 (looking-at "[^|\n]* |"))
12073 (let (org-table-may-need-update)
12074 (goto-char (1- (match-end 0)))
12075 (delete-backward-char 1)
12076 (goto-char (match-beginning 0))
12077 (self-insert-command N))
12078 (setq org-table-may-need-update t)
12079 (self-insert-command N)
12080 (org-fix-tags-on-the-fly)))
12082 (defun org-fix-tags-on-the-fly ()
12083 (when (and (equal (char-after (point-at-bol)) ?*)
12084 (org-on-heading-p))
12085 (org-align-tags-here org-tags-column)))
12087 (defun org-delete-backward-char (N)
12088 "Like `delete-backward-char', insert whitespace at field end in tables.
12089 When deleting backwards, in tables this function will insert whitespace in
12090 front of the next \"|\" separator, to keep the table aligned. The table will
12091 still be marked for re-alignment if the field did fill the entire column,
12092 because, in this case the deletion might narrow the column."
12093 (interactive "p")
12094 (if (and (org-table-p)
12095 (eq N 1)
12096 (string-match "|" (buffer-substring (point-at-bol) (point)))
12097 (looking-at ".*?|"))
12098 (let ((pos (point))
12099 (noalign (looking-at "[^|\n\r]* |"))
12100 (c org-table-may-need-update))
12101 (backward-delete-char N)
12102 (skip-chars-forward "^|")
12103 (insert " ")
12104 (goto-char (1- pos))
12105 ;; noalign: if there were two spaces at the end, this field
12106 ;; does not determine the width of the column.
12107 (if noalign (setq org-table-may-need-update c)))
12108 (backward-delete-char N)
12109 (org-fix-tags-on-the-fly)))
12111 (defun org-delete-char (N)
12112 "Like `delete-char', but insert whitespace at field end in tables.
12113 When deleting characters, in tables this function will insert whitespace in
12114 front of the next \"|\" separator, to keep the table aligned. The table will
12115 still be marked for re-alignment if the field did fill the entire column,
12116 because, in this case the deletion might narrow the column."
12117 (interactive "p")
12118 (if (and (org-table-p)
12119 (not (bolp))
12120 (not (= (char-after) ?|))
12121 (eq N 1))
12122 (if (looking-at ".*?|")
12123 (let ((pos (point))
12124 (noalign (looking-at "[^|\n\r]* |"))
12125 (c org-table-may-need-update))
12126 (replace-match (concat
12127 (substring (match-string 0) 1 -1)
12128 " |"))
12129 (goto-char pos)
12130 ;; noalign: if there were two spaces at the end, this field
12131 ;; does not determine the width of the column.
12132 (if noalign (setq org-table-may-need-update c)))
12133 (delete-char N))
12134 (delete-char N)
12135 (org-fix-tags-on-the-fly)))
12137 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
12138 (put 'org-self-insert-command 'delete-selection t)
12139 (put 'orgtbl-self-insert-command 'delete-selection t)
12140 (put 'org-delete-char 'delete-selection 'supersede)
12141 (put 'org-delete-backward-char 'delete-selection 'supersede)
12143 ;; Make `flyspell-mode' delay after some commands
12144 (put 'org-self-insert-command 'flyspell-delayed t)
12145 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
12146 (put 'org-delete-char 'flyspell-delayed t)
12147 (put 'org-delete-backward-char 'flyspell-delayed t)
12149 ;; Make pabbrev-mode expand after org-mode commands
12150 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
12151 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
12153 ;; How to do this: Measure non-white length of current string
12154 ;; If equal to column width, we should realign.
12156 (defun org-remap (map &rest commands)
12157 "In MAP, remap the functions given in COMMANDS.
12158 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
12159 (let (new old)
12160 (while commands
12161 (setq old (pop commands) new (pop commands))
12162 (if (fboundp 'command-remapping)
12163 (org-defkey map (vector 'remap old) new)
12164 (substitute-key-definition old new map global-map)))))
12166 (when (eq org-enable-table-editor 'optimized)
12167 ;; If the user wants maximum table support, we need to hijack
12168 ;; some standard editing functions
12169 (org-remap org-mode-map
12170 'self-insert-command 'org-self-insert-command
12171 'delete-char 'org-delete-char
12172 'delete-backward-char 'org-delete-backward-char)
12173 (org-defkey org-mode-map "|" 'org-force-self-insert))
12175 (defun org-shiftcursor-error ()
12176 "Throw an error because Shift-Cursor command was applied in wrong context."
12177 (error "This command is active in special context like tables, headlines or timestamps"))
12179 (defun org-shifttab (&optional arg)
12180 "Global visibility cycling or move to previous table field.
12181 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
12182 on context.
12183 See the individual commands for more information."
12184 (interactive "P")
12185 (cond
12186 ((org-at-table-p) (call-interactively 'org-table-previous-field))
12187 ((integerp arg)
12188 (message "Content view to level: %d" arg)
12189 (org-content (prefix-numeric-value arg))
12190 (setq org-cycle-global-status 'overview))
12191 (t (call-interactively 'org-global-cycle))))
12193 (defun org-shiftmetaleft ()
12194 "Promote subtree or delete table column.
12195 Calls `org-promote-subtree', `org-outdent-item',
12196 or `org-table-delete-column', depending on context.
12197 See the individual commands for more information."
12198 (interactive)
12199 (cond
12200 ((org-at-table-p) (call-interactively 'org-table-delete-column))
12201 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
12202 ((org-at-item-p) (call-interactively 'org-outdent-item))
12203 (t (org-shiftcursor-error))))
12205 (defun org-shiftmetaright ()
12206 "Demote subtree or insert table column.
12207 Calls `org-demote-subtree', `org-indent-item',
12208 or `org-table-insert-column', depending on context.
12209 See the individual commands for more information."
12210 (interactive)
12211 (cond
12212 ((org-at-table-p) (call-interactively 'org-table-insert-column))
12213 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
12214 ((org-at-item-p) (call-interactively 'org-indent-item))
12215 (t (org-shiftcursor-error))))
12217 (defun org-shiftmetaup (&optional arg)
12218 "Move subtree up or kill table row.
12219 Calls `org-move-subtree-up' or `org-table-kill-row' or
12220 `org-move-item-up' depending on context. See the individual commands
12221 for more information."
12222 (interactive "P")
12223 (cond
12224 ((org-at-table-p) (call-interactively 'org-table-kill-row))
12225 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12226 ((org-at-item-p) (call-interactively 'org-move-item-up))
12227 (t (org-shiftcursor-error))))
12228 (defun org-shiftmetadown (&optional arg)
12229 "Move subtree down or insert table row.
12230 Calls `org-move-subtree-down' or `org-table-insert-row' or
12231 `org-move-item-down', depending on context. See the individual
12232 commands for more information."
12233 (interactive "P")
12234 (cond
12235 ((org-at-table-p) (call-interactively 'org-table-insert-row))
12236 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12237 ((org-at-item-p) (call-interactively 'org-move-item-down))
12238 (t (org-shiftcursor-error))))
12240 (defun org-metaleft (&optional arg)
12241 "Promote heading or move table column to left.
12242 Calls `org-do-promote' or `org-table-move-column', depending on context.
12243 With no specific context, calls the Emacs default `backward-word'.
12244 See the individual commands for more information."
12245 (interactive "P")
12246 (cond
12247 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
12248 ((or (org-on-heading-p) (org-region-active-p))
12249 (call-interactively 'org-do-promote))
12250 ((org-at-item-p) (call-interactively 'org-outdent-item))
12251 (t (call-interactively 'backward-word))))
12253 (defun org-metaright (&optional arg)
12254 "Demote subtree or move table column to right.
12255 Calls `org-do-demote' or `org-table-move-column', depending on context.
12256 With no specific context, calls the Emacs default `forward-word'.
12257 See the individual commands for more information."
12258 (interactive "P")
12259 (cond
12260 ((org-at-table-p) (call-interactively 'org-table-move-column))
12261 ((or (org-on-heading-p) (org-region-active-p))
12262 (call-interactively 'org-do-demote))
12263 ((org-at-item-p) (call-interactively 'org-indent-item))
12264 (t (call-interactively 'forward-word))))
12266 (defun org-metaup (&optional arg)
12267 "Move subtree up or move table row up.
12268 Calls `org-move-subtree-up' or `org-table-move-row' or
12269 `org-move-item-up', depending on context. See the individual commands
12270 for more information."
12271 (interactive "P")
12272 (cond
12273 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
12274 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12275 ((org-at-item-p) (call-interactively 'org-move-item-up))
12276 (t (transpose-lines 1) (beginning-of-line -1))))
12278 (defun org-metadown (&optional arg)
12279 "Move subtree down or move table row down.
12280 Calls `org-move-subtree-down' or `org-table-move-row' or
12281 `org-move-item-down', depending on context. See the individual
12282 commands for more information."
12283 (interactive "P")
12284 (cond
12285 ((org-at-table-p) (call-interactively 'org-table-move-row))
12286 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12287 ((org-at-item-p) (call-interactively 'org-move-item-down))
12288 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
12290 (defun org-shiftup (&optional arg)
12291 "Increase item in timestamp or increase priority of current headline.
12292 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
12293 depending on context. See the individual commands for more information."
12294 (interactive "P")
12295 (cond
12296 ((org-at-timestamp-p t)
12297 (call-interactively (if org-edit-timestamp-down-means-later
12298 'org-timestamp-down 'org-timestamp-up)))
12299 ((org-on-heading-p) (call-interactively 'org-priority-up))
12300 ((org-at-item-p) (call-interactively 'org-previous-item))
12301 ((org-clocktable-try-shift 'up arg))
12302 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
12304 (defun org-shiftdown (&optional arg)
12305 "Decrease item in timestamp or decrease priority of current headline.
12306 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
12307 depending on context. See the individual commands for more information."
12308 (interactive "P")
12309 (cond
12310 ((org-at-timestamp-p t)
12311 (call-interactively (if org-edit-timestamp-down-means-later
12312 'org-timestamp-up 'org-timestamp-down)))
12313 ((org-on-heading-p) (call-interactively 'org-priority-down))
12314 ((org-clocktable-try-shift 'down arg))
12315 (t (call-interactively 'org-next-item))))
12317 (defun org-shiftright (&optional arg)
12318 "Next TODO keyword or timestamp one day later, depending on context."
12319 (interactive "P")
12320 (cond
12321 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
12322 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
12323 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
12324 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
12325 ((org-clocktable-try-shift 'right arg))
12326 (t (org-shiftcursor-error))))
12328 (defun org-shiftleft (&optional arg)
12329 "Previous TODO keyword or timestamp one day earlier, depending on context."
12330 (interactive "P")
12331 (cond
12332 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
12333 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
12334 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
12335 ((org-at-property-p)
12336 (call-interactively 'org-property-previous-allowed-value))
12337 ((org-clocktable-try-shift 'left arg))
12338 (t (org-shiftcursor-error))))
12340 (defun org-shiftcontrolright ()
12341 "Switch to next TODO set."
12342 (interactive)
12343 (cond
12344 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
12345 (t (org-shiftcursor-error))))
12347 (defun org-shiftcontrolleft ()
12348 "Switch to previous TODO set."
12349 (interactive)
12350 (cond
12351 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
12352 (t (org-shiftcursor-error))))
12354 (defun org-ctrl-c-ret ()
12355 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
12356 (interactive)
12357 (cond
12358 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
12359 (t (call-interactively 'org-insert-heading))))
12361 (defun org-copy-special ()
12362 "Copy region in table or copy current subtree.
12363 Calls `org-table-copy' or `org-copy-subtree', depending on context.
12364 See the individual commands for more information."
12365 (interactive)
12366 (call-interactively
12367 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
12369 (defun org-cut-special ()
12370 "Cut region in table or cut current subtree.
12371 Calls `org-table-copy' or `org-cut-subtree', depending on context.
12372 See the individual commands for more information."
12373 (interactive)
12374 (call-interactively
12375 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
12377 (defun org-paste-special (arg)
12378 "Paste rectangular region into table, or past subtree relative to level.
12379 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
12380 See the individual commands for more information."
12381 (interactive "P")
12382 (if (org-at-table-p)
12383 (org-table-paste-rectangle)
12384 (org-paste-subtree arg)))
12386 (defun org-edit-special ()
12387 "Call a special editor for the stuff at point.
12388 When at a table, call the formula editor with `org-table-edit-formulas'.
12389 When at the first line of an src example, call `org-edit-src-code'.
12390 When in an #+include line, visit the include file. Otherwise call
12391 `ffap' to visit the file at point."
12392 (interactive)
12393 (cond
12394 ((org-at-table-p)
12395 (call-interactively 'org-table-edit-formulas))
12396 ((save-excursion
12397 (beginning-of-line 1)
12398 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
12399 (find-file (org-trim (match-string 1))))
12400 ((org-edit-src-code))
12401 ((org-edit-fixed-width-region))
12402 (t (call-interactively 'ffap))))
12404 (defun org-ctrl-c-ctrl-c (&optional arg)
12405 "Set tags in headline, or update according to changed information at point.
12407 This command does many different things, depending on context:
12409 - If the cursor is in a headline, prompt for tags and insert them
12410 into the current line, aligned to `org-tags-column'. When called
12411 with prefix arg, realign all tags in the current buffer.
12413 - If the cursor is in one of the special #+KEYWORD lines, this
12414 triggers scanning the buffer for these lines and updating the
12415 information.
12417 - If the cursor is inside a table, realign the table. This command
12418 works even if the automatic table editor has been turned off.
12420 - If the cursor is on a #+TBLFM line, re-apply the formulas to
12421 the entire table.
12423 - If the cursor is a the beginning of a dynamic block, update it.
12425 - If the cursor is inside a table created by the table.el package,
12426 activate that table.
12428 - If the current buffer is a remember buffer, close note and file it.
12429 with a prefix argument, file it without further interaction to the default
12430 location.
12432 - If the cursor is on a <<<target>>>, update radio targets and corresponding
12433 links in this buffer.
12435 - If the cursor is on a numbered item in a plain list, renumber the
12436 ordered list.
12438 - If the cursor is on a checkbox, toggle it."
12439 (interactive "P")
12440 (let ((org-enable-table-editor t))
12441 (cond
12442 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
12443 org-occur-highlights
12444 org-latex-fragment-image-overlays)
12445 (and (boundp 'org-clock-overlays) (org-remove-clock-overlays))
12446 (org-remove-occur-highlights)
12447 (org-remove-latex-fragment-image-overlays)
12448 (message "Temporary highlights/overlays removed from current buffer"))
12449 ((and (local-variable-p 'org-finish-function (current-buffer))
12450 (fboundp org-finish-function))
12451 (funcall org-finish-function))
12452 ((org-at-property-p)
12453 (call-interactively 'org-property-action))
12454 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
12455 ((org-on-heading-p) (call-interactively 'org-set-tags))
12456 ((org-at-table.el-p)
12457 (require 'table)
12458 (beginning-of-line 1)
12459 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
12460 (call-interactively 'table-recognize-table))
12461 ((org-at-table-p)
12462 (org-table-maybe-eval-formula)
12463 (if arg
12464 (call-interactively 'org-table-recalculate)
12465 (org-table-maybe-recalculate-line))
12466 (call-interactively 'org-table-align))
12467 ((org-at-item-checkbox-p)
12468 (call-interactively 'org-toggle-checkbox))
12469 ((org-at-item-p)
12470 (call-interactively 'org-maybe-renumber-ordered-list))
12471 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
12472 ;; Dynamic block
12473 (beginning-of-line 1)
12474 (save-excursion (org-update-dblock)))
12475 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
12476 (cond
12477 ((equal (match-string 1) "TBLFM")
12478 ;; Recalculate the table before this line
12479 (save-excursion
12480 (beginning-of-line 1)
12481 (skip-chars-backward " \r\n\t")
12482 (if (org-at-table-p)
12483 (org-call-with-arg 'org-table-recalculate t))))
12485 ; (org-set-regexps-and-options)
12486 ; (org-restart-font-lock)
12487 (let ((org-inhibit-startup t)) (org-mode-restart))
12488 (message "Local setup has been refreshed"))))
12489 (t (error "C-c C-c can do nothing useful at this location.")))))
12491 (defun org-mode-restart ()
12492 "Restart Org-mode, to scan again for special lines.
12493 Also updates the keyword regular expressions."
12494 (interactive)
12495 (org-mode)
12496 (message "Org-mode restarted"))
12498 (defun org-kill-note-or-show-branches ()
12499 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
12500 (interactive)
12501 (if (not org-finish-function)
12502 (call-interactively 'show-branches)
12503 (let ((org-note-abort t))
12504 (funcall org-finish-function))))
12506 (defun org-return (&optional indent)
12507 "Goto next table row or insert a newline.
12508 Calls `org-table-next-row' or `newline', depending on context.
12509 See the individual commands for more information."
12510 (interactive)
12511 (cond
12512 ((bobp) (if indent (newline-and-indent) (newline)))
12513 ((and (org-at-heading-p)
12514 (looking-at
12515 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
12516 (org-show-entry)
12517 (end-of-line 1)
12518 (newline))
12519 ((org-at-table-p)
12520 (org-table-justify-field-maybe)
12521 (call-interactively 'org-table-next-row))
12522 (t (if indent (newline-and-indent) (newline)))))
12524 (defun org-return-indent ()
12525 "Goto next table row or insert a newline and indent.
12526 Calls `org-table-next-row' or `newline-and-indent', depending on
12527 context. See the individual commands for more information."
12528 (interactive)
12529 (org-return t))
12531 (defun org-ctrl-c-star ()
12532 "Compute table, or change heading status of lines.
12533 Calls `org-table-recalculate' or `org-toggle-region-headings',
12534 depending on context. This will also turn a plain list item or a normal
12535 line into a subheading."
12536 (interactive)
12537 (cond
12538 ((org-at-table-p)
12539 (call-interactively 'org-table-recalculate))
12540 ((org-region-active-p)
12541 ;; Convert all lines in region to list items
12542 (call-interactively 'org-toggle-region-headings))
12543 ((org-on-heading-p)
12544 (org-toggle-region-headings (point-at-bol)
12545 (min (1+ (point-at-eol)) (point-max))))
12546 ((org-at-item-p)
12547 ;; Convert to heading
12548 (let ((level (save-match-data
12549 (save-excursion
12550 (condition-case nil
12551 (progn
12552 (org-back-to-heading t)
12553 (funcall outline-level))
12554 (error 0))))))
12555 (replace-match
12556 (concat (make-string (org-get-valid-level level 1) ?*) " ") t t)))
12557 (t (org-toggle-region-headings (point-at-bol)
12558 (min (1+ (point-at-eol)) (point-max))))))
12560 (defun org-ctrl-c-minus ()
12561 "Insert separator line in table or modify bullet status of line.
12562 Also turns a plain line or a region of lines into list items.
12563 Calls `org-table-insert-hline', `org-toggle-region-items', or
12564 `org-cycle-list-bullet', depending on context."
12565 (interactive)
12566 (cond
12567 ((org-at-table-p)
12568 (call-interactively 'org-table-insert-hline))
12569 ((org-on-heading-p)
12570 ;; Convert to item
12571 (save-excursion
12572 (beginning-of-line 1)
12573 (if (looking-at "\\*+ ")
12574 (replace-match (concat (make-string (- (match-end 0) (point) 1) ?\ ) "- ")))))
12575 ((org-region-active-p)
12576 ;; Convert all lines in region to list items
12577 (call-interactively 'org-toggle-region-items))
12578 ((org-in-item-p)
12579 (call-interactively 'org-cycle-list-bullet))
12580 (t (org-toggle-region-items (point-at-bol)
12581 (min (1+ (point-at-eol)) (point-max))))))
12583 (defun org-toggle-region-items (beg end)
12584 "Convert all lines in region to list items.
12585 If the first line is already an item, convert all list items in the region
12586 to normal lines."
12587 (interactive "r")
12588 (let (l2 l)
12589 (save-excursion
12590 (goto-char end)
12591 (setq l2 (org-current-line))
12592 (goto-char beg)
12593 (beginning-of-line 1)
12594 (setq l (1- (org-current-line)))
12595 (if (org-at-item-p)
12596 ;; We already have items, de-itemize
12597 (while (< (setq l (1+ l)) l2)
12598 (when (org-at-item-p)
12599 (goto-char (match-beginning 2))
12600 (delete-region (match-beginning 2) (match-end 2))
12601 (and (looking-at "[ \t]+") (replace-match "")))
12602 (beginning-of-line 2))
12603 (while (< (setq l (1+ l)) l2)
12604 (unless (org-at-item-p)
12605 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
12606 (replace-match "\\1- \\2")))
12607 (beginning-of-line 2))))))
12609 (defun org-toggle-region-headings (beg end)
12610 "Convert all lines in region to list items.
12611 If the first line is already an item, convert all list items in the region
12612 to normal lines."
12613 (interactive "r")
12614 (let (l2 l)
12615 (save-excursion
12616 (goto-char end)
12617 (setq l2 (org-current-line))
12618 (goto-char beg)
12619 (beginning-of-line 1)
12620 (setq l (1- (org-current-line)))
12621 (if (org-on-heading-p)
12622 ;; We already have headlines, de-star them
12623 (while (< (setq l (1+ l)) l2)
12624 (when (org-on-heading-p t)
12625 (and (looking-at outline-regexp) (replace-match "")))
12626 (beginning-of-line 2))
12627 (let* ((stars (save-excursion
12628 (re-search-backward org-complex-heading-regexp nil t)
12629 (or (match-string 1) "*")))
12630 (add-stars (if org-odd-levels-only "**" "*"))
12631 (rpl (concat stars add-stars " \\2")))
12632 (while (< (setq l (1+ l)) l2)
12633 (unless (org-on-heading-p)
12634 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
12635 (replace-match rpl)))
12636 (beginning-of-line 2)))))))
12638 (defun org-meta-return (&optional arg)
12639 "Insert a new heading or wrap a region in a table.
12640 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
12641 See the individual commands for more information."
12642 (interactive "P")
12643 (cond
12644 ((org-at-table-p)
12645 (call-interactively 'org-table-wrap-region))
12646 (t (call-interactively 'org-insert-heading))))
12648 ;;; Menu entries
12650 ;; Define the Org-mode menus
12651 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
12652 '("Tbl"
12653 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
12654 ["Next Field" org-cycle (org-at-table-p)]
12655 ["Previous Field" org-shifttab (org-at-table-p)]
12656 ["Next Row" org-return (org-at-table-p)]
12657 "--"
12658 ["Blank Field" org-table-blank-field (org-at-table-p)]
12659 ["Edit Field" org-table-edit-field (org-at-table-p)]
12660 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
12661 "--"
12662 ("Column"
12663 ["Move Column Left" org-metaleft (org-at-table-p)]
12664 ["Move Column Right" org-metaright (org-at-table-p)]
12665 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
12666 ["Insert Column" org-shiftmetaright (org-at-table-p)])
12667 ("Row"
12668 ["Move Row Up" org-metaup (org-at-table-p)]
12669 ["Move Row Down" org-metadown (org-at-table-p)]
12670 ["Delete Row" org-shiftmetaup (org-at-table-p)]
12671 ["Insert Row" org-shiftmetadown (org-at-table-p)]
12672 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
12673 "--"
12674 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
12675 ("Rectangle"
12676 ["Copy Rectangle" org-copy-special (org-at-table-p)]
12677 ["Cut Rectangle" org-cut-special (org-at-table-p)]
12678 ["Paste Rectangle" org-paste-special (org-at-table-p)]
12679 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
12680 "--"
12681 ("Calculate"
12682 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
12683 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
12684 ["Edit Formulas" org-edit-special (org-at-table-p)]
12685 "--"
12686 ["Recalculate line" org-table-recalculate (org-at-table-p)]
12687 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
12688 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
12689 "--"
12690 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
12691 "--"
12692 ["Sum Column/Rectangle" org-table-sum
12693 (or (org-at-table-p) (org-region-active-p))]
12694 ["Which Column?" org-table-current-column (org-at-table-p)])
12695 ["Debug Formulas"
12696 org-table-toggle-formula-debugger
12697 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
12698 ["Show Col/Row Numbers"
12699 org-table-toggle-coordinate-overlays
12700 :style toggle
12701 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
12702 "--"
12703 ["Create" org-table-create (and (not (org-at-table-p))
12704 org-enable-table-editor)]
12705 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
12706 ["Import from File" org-table-import (not (org-at-table-p))]
12707 ["Export to File" org-table-export (org-at-table-p)]
12708 "--"
12709 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
12711 (easy-menu-define org-org-menu org-mode-map "Org menu"
12712 '("Org"
12713 ("Show/Hide"
12714 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
12715 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
12716 ["Sparse Tree..." org-sparse-tree t]
12717 ["Reveal Context" org-reveal t]
12718 ["Show All" show-all t]
12719 "--"
12720 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
12721 "--"
12722 ["New Heading" org-insert-heading t]
12723 ("Navigate Headings"
12724 ["Up" outline-up-heading t]
12725 ["Next" outline-next-visible-heading t]
12726 ["Previous" outline-previous-visible-heading t]
12727 ["Next Same Level" outline-forward-same-level t]
12728 ["Previous Same Level" outline-backward-same-level t]
12729 "--"
12730 ["Jump" org-goto t])
12731 ("Edit Structure"
12732 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
12733 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
12734 "--"
12735 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
12736 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
12737 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
12738 "--"
12739 ["Promote Heading" org-metaleft (not (org-at-table-p))]
12740 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
12741 ["Demote Heading" org-metaright (not (org-at-table-p))]
12742 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
12743 "--"
12744 ["Sort Region/Children" org-sort (not (org-at-table-p))]
12745 "--"
12746 ["Convert to odd levels" org-convert-to-odd-levels t]
12747 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
12748 ("Editing"
12749 ["Emphasis..." org-emphasize t]
12750 ["Edit Source Example" org-edit-special t])
12751 ("Archive"
12752 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
12753 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
12754 ; :active t :keys "C-u C-c C-x C-a"]
12755 ["Sparse trees open ARCHIVE trees"
12756 (setq org-sparse-tree-open-archived-trees
12757 (not org-sparse-tree-open-archived-trees))
12758 :style toggle :selected org-sparse-tree-open-archived-trees]
12759 ["Cycling opens ARCHIVE trees"
12760 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
12761 :style toggle :selected org-cycle-open-archived-trees]
12762 "--"
12763 ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
12764 ["Move Subtree to Archive" org-advertized-archive-subtree t]
12765 ; ["Check and Move Children" (org-archive-subtree '(4))
12766 ; :active t :keys "C-u C-c C-x C-s"]
12768 "--"
12769 ("TODO Lists"
12770 ["TODO/DONE/-" org-todo t]
12771 ("Select keyword"
12772 ["Next keyword" org-shiftright (org-on-heading-p)]
12773 ["Previous keyword" org-shiftleft (org-on-heading-p)]
12774 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
12775 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
12776 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
12777 ["Show TODO Tree" org-show-todo-tree t]
12778 ["Global TODO list" org-todo-list t]
12779 "--"
12780 ["Set Priority" org-priority t]
12781 ["Priority Up" org-shiftup t]
12782 ["Priority Down" org-shiftdown t])
12783 ("TAGS and Properties"
12784 ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
12785 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
12786 "--"
12787 ["Set property" 'org-set-property t]
12788 ["Column view of properties" org-columns t]
12789 ["Insert Column View DBlock" org-insert-columns-dblock t])
12790 ("Dates and Scheduling"
12791 ["Timestamp" org-time-stamp t]
12792 ["Timestamp (inactive)" org-time-stamp-inactive t]
12793 ("Change Date"
12794 ["1 Day Later" org-shiftright t]
12795 ["1 Day Earlier" org-shiftleft t]
12796 ["1 ... Later" org-shiftup t]
12797 ["1 ... Earlier" org-shiftdown t])
12798 ["Compute Time Range" org-evaluate-time-range t]
12799 ["Schedule Item" org-schedule t]
12800 ["Deadline" org-deadline t]
12801 "--"
12802 ["Custom time format" org-toggle-time-stamp-overlays
12803 :style radio :selected org-display-custom-times]
12804 "--"
12805 ["Goto Calendar" org-goto-calendar t]
12806 ["Date from Calendar" org-date-from-calendar t])
12807 ("Logging work"
12808 ["Clock in" org-clock-in t]
12809 ["Clock out" org-clock-out t]
12810 ["Clock cancel" org-clock-cancel t]
12811 ["Goto running clock" org-clock-goto t]
12812 ["Display times" org-clock-display t]
12813 ["Create clock table" org-clock-report t]
12814 "--"
12815 ["Record DONE time"
12816 (progn (setq org-log-done (not org-log-done))
12817 (message "Switching to %s will %s record a timestamp"
12818 (car org-done-keywords)
12819 (if org-log-done "automatically" "not")))
12820 :style toggle :selected org-log-done])
12821 "--"
12822 ["Agenda Command..." org-agenda t]
12823 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
12824 ("File List for Agenda")
12825 ("Special views current file"
12826 ["TODO Tree" org-show-todo-tree t]
12827 ["Check Deadlines" org-check-deadlines t]
12828 ["Timeline" org-timeline t]
12829 ["Tags Tree" org-tags-sparse-tree t])
12830 "--"
12831 ("Hyperlinks"
12832 ["Store Link (Global)" org-store-link t]
12833 ["Insert Link" org-insert-link t]
12834 ["Follow Link" org-open-at-point t]
12835 "--"
12836 ["Next link" org-next-link t]
12837 ["Previous link" org-previous-link t]
12838 "--"
12839 ["Descriptive Links"
12840 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
12841 :style radio
12842 :selected (member '(org-link) buffer-invisibility-spec)]
12843 ["Literal Links"
12844 (progn
12845 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
12846 :style radio
12847 :selected (not (member '(org-link) buffer-invisibility-spec))])
12848 "--"
12849 ["Export/Publish..." org-export t]
12850 ("LaTeX"
12851 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
12852 :selected org-cdlatex-mode]
12853 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
12854 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
12855 ["Modify math symbol" org-cdlatex-math-modify
12856 (org-inside-LaTeX-fragment-p)]
12857 ["Export LaTeX fragments as images"
12858 (if (featurep 'org-exp)
12859 (setq org-export-with-LaTeX-fragments
12860 (not org-export-with-LaTeX-fragments))
12861 (require 'org-exp))
12862 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
12863 org-export-with-LaTeX-fragments)])
12864 "--"
12865 ("Documentation"
12866 ["Show Version" org-version t]
12867 ["Info Documentation" org-info t])
12868 ("Customize"
12869 ["Browse Org Group" org-customize t]
12870 "--"
12871 ["Expand This Menu" org-create-customize-menu
12872 (fboundp 'customize-menu-create)])
12873 "--"
12874 ["Refresh setup" org-mode-restart t]
12877 (defun org-info (&optional node)
12878 "Read documentation for Org-mode in the info system.
12879 With optional NODE, go directly to that node."
12880 (interactive)
12881 (info (format "(org)%s" (or node ""))))
12883 (defun org-install-agenda-files-menu ()
12884 (let ((bl (buffer-list)))
12885 (save-excursion
12886 (while bl
12887 (set-buffer (pop bl))
12888 (if (org-mode-p) (setq bl nil)))
12889 (when (org-mode-p)
12890 (easy-menu-change
12891 '("Org") "File List for Agenda"
12892 (append
12893 (list
12894 ["Edit File List" (org-edit-agenda-file-list) t]
12895 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
12896 ["Remove Current File from List" org-remove-file t]
12897 ["Cycle through agenda files" org-cycle-agenda-files t]
12898 ["Occur in all agenda files" org-occur-in-agenda-files t]
12899 "--")
12900 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
12902 ;;;; Documentation
12904 ;;;###autoload
12905 (defun org-require-autoloaded-modules ()
12906 (interactive)
12907 (mapc 'require
12908 '(org-agenda org-archive org-clock org-colview
12909 org-exp org-id org-export-latex org-publish
12910 org-remember org-table)))
12912 ;;;###autoload
12913 (defun org-customize ()
12914 "Call the customize function with org as argument."
12915 (interactive)
12916 (org-load-modules-maybe)
12917 (org-require-autoloaded-modules)
12918 (customize-browse 'org))
12920 (defun org-create-customize-menu ()
12921 "Create a full customization menu for Org-mode, insert it into the menu."
12922 (interactive)
12923 (org-load-modules-maybe)
12924 (org-require-autoloaded-modules)
12925 (if (fboundp 'customize-menu-create)
12926 (progn
12927 (easy-menu-change
12928 '("Org") "Customize"
12929 `(["Browse Org group" org-customize t]
12930 "--"
12931 ,(customize-menu-create 'org)
12932 ["Set" Custom-set t]
12933 ["Save" Custom-save t]
12934 ["Reset to Current" Custom-reset-current t]
12935 ["Reset to Saved" Custom-reset-saved t]
12936 ["Reset to Standard Settings" Custom-reset-standard t]))
12937 (message "\"Org\"-menu now contains full customization menu"))
12938 (error "Cannot expand menu (outdated version of cus-edit.el)")))
12940 ;;;; Miscellaneous stuff
12942 ;;; Generally useful functions
12944 (defun org-display-warning (message) ;; Copied from Emacs-Muse
12945 "Display the given MESSAGE as a warning."
12946 (if (fboundp 'display-warning)
12947 (display-warning 'org message
12948 (if (featurep 'xemacs)
12949 'warning
12950 :warning))
12951 (let ((buf (get-buffer-create "*Org warnings*")))
12952 (with-current-buffer buf
12953 (goto-char (point-max))
12954 (insert "Warning (Org): " message)
12955 (unless (bolp)
12956 (newline)))
12957 (display-buffer buf)
12958 (sit-for 0))))
12960 (defun org-goto-marker-or-bmk (marker &optional bookmark)
12961 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
12962 (if (and marker (marker-buffer marker)
12963 (buffer-live-p (marker-buffer marker)))
12964 (progn
12965 (switch-to-buffer (marker-buffer marker))
12966 (if (or (> marker (point-max)) (< marker (point-min)))
12967 (widen))
12968 (goto-char marker))
12969 (if bookmark
12970 (bookmark-jump bookmark)
12971 (error "Cannot find location"))))
12973 (defun org-quote-csv-field (s)
12974 "Quote field for inclusion in CSV material."
12975 (if (string-match "[\",]" s)
12976 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
12979 (defun org-plist-delete (plist property)
12980 "Delete PROPERTY from PLIST.
12981 This is in contrast to merely setting it to 0."
12982 (let (p)
12983 (while plist
12984 (if (not (eq property (car plist)))
12985 (setq p (plist-put p (car plist) (nth 1 plist))))
12986 (setq plist (cddr plist)))
12989 (defun org-force-self-insert (N)
12990 "Needed to enforce self-insert under remapping."
12991 (interactive "p")
12992 (self-insert-command N))
12994 (defun org-string-width (s)
12995 "Compute width of string, ignoring invisible characters.
12996 This ignores character with invisibility property `org-link', and also
12997 characters with property `org-cwidth', because these will become invisible
12998 upon the next fontification round."
12999 (let (b l)
13000 (when (or (eq t buffer-invisibility-spec)
13001 (assq 'org-link buffer-invisibility-spec))
13002 (while (setq b (text-property-any 0 (length s)
13003 'invisible 'org-link s))
13004 (setq s (concat (substring s 0 b)
13005 (substring s (or (next-single-property-change
13006 b 'invisible s) (length s)))))))
13007 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
13008 (setq s (concat (substring s 0 b)
13009 (substring s (or (next-single-property-change
13010 b 'org-cwidth s) (length s))))))
13011 (setq l (string-width s) b -1)
13012 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
13013 (setq l (- l (get-text-property b 'org-dwidth-n s))))
13016 (defun org-get-indentation (&optional line)
13017 "Get the indentation of the current line, interpreting tabs.
13018 When LINE is given, assume it represents a line and compute its indentation."
13019 (if line
13020 (if (string-match "^ *" (org-remove-tabs line))
13021 (match-end 0))
13022 (save-excursion
13023 (beginning-of-line 1)
13024 (skip-chars-forward " \t")
13025 (current-column))))
13027 (defun org-remove-tabs (s &optional width)
13028 "Replace tabulators in S with spaces.
13029 Assumes that s is a single line, starting in column 0."
13030 (setq width (or width tab-width))
13031 (while (string-match "\t" s)
13032 (setq s (replace-match
13033 (make-string
13034 (- (* width (/ (+ (match-beginning 0) width) width))
13035 (match-beginning 0)) ?\ )
13036 t t s)))
13039 (defun org-fix-indentation (line ind)
13040 "Fix indentation in LINE.
13041 IND is a cons cell with target and minimum indentation.
13042 If the current indenation in LINE is smaller than the minimum,
13043 leave it alone. If it is larger than ind, set it to the target."
13044 (let* ((l (org-remove-tabs line))
13045 (i (org-get-indentation l))
13046 (i1 (car ind)) (i2 (cdr ind)))
13047 (if (>= i i2) (setq l (substring line i2)))
13048 (if (> i1 0)
13049 (concat (make-string i1 ?\ ) l)
13050 l)))
13052 (defun org-base-buffer (buffer)
13053 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
13054 (if (not buffer)
13055 buffer
13056 (or (buffer-base-buffer buffer)
13057 buffer)))
13059 (defun org-trim (s)
13060 "Remove whitespace at beginning and end of string."
13061 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
13062 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
13065 (defun org-wrap (string &optional width lines)
13066 "Wrap string to either a number of lines, or a width in characters.
13067 If WIDTH is non-nil, the string is wrapped to that width, however many lines
13068 that costs. If there is a word longer than WIDTH, the text is actually
13069 wrapped to the length of that word.
13070 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
13071 many lines, whatever width that takes.
13072 The return value is a list of lines, without newlines at the end."
13073 (let* ((words (org-split-string string "[ \t\n]+"))
13074 (maxword (apply 'max (mapcar 'org-string-width words)))
13075 w ll)
13076 (cond (width
13077 (org-do-wrap words (max maxword width)))
13078 (lines
13079 (setq w maxword)
13080 (setq ll (org-do-wrap words maxword))
13081 (if (<= (length ll) lines)
13083 (setq ll words)
13084 (while (> (length ll) lines)
13085 (setq w (1+ w))
13086 (setq ll (org-do-wrap words w)))
13087 ll))
13088 (t (error "Cannot wrap this")))))
13090 (defun org-do-wrap (words width)
13091 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
13092 (let (lines line)
13093 (while words
13094 (setq line (pop words))
13095 (while (and words (< (+ (length line) (length (car words))) width))
13096 (setq line (concat line " " (pop words))))
13097 (setq lines (push line lines)))
13098 (nreverse lines)))
13100 (defun org-split-string (string &optional separators)
13101 "Splits STRING into substrings at SEPARATORS.
13102 No empty strings are returned if there are matches at the beginning
13103 and end of string."
13104 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
13105 (start 0)
13106 notfirst
13107 (list nil))
13108 (while (and (string-match rexp string
13109 (if (and notfirst
13110 (= start (match-beginning 0))
13111 (< start (length string)))
13112 (1+ start) start))
13113 (< (match-beginning 0) (length string)))
13114 (setq notfirst t)
13115 (or (eq (match-beginning 0) 0)
13116 (and (eq (match-beginning 0) (match-end 0))
13117 (eq (match-beginning 0) start))
13118 (setq list
13119 (cons (substring string start (match-beginning 0))
13120 list)))
13121 (setq start (match-end 0)))
13122 (or (eq start (length string))
13123 (setq list
13124 (cons (substring string start)
13125 list)))
13126 (nreverse list)))
13128 (defun org-context ()
13129 "Return a list of contexts of the current cursor position.
13130 If several contexts apply, all are returned.
13131 Each context entry is a list with a symbol naming the context, and
13132 two positions indicating start and end of the context. Possible
13133 contexts are:
13135 :headline anywhere in a headline
13136 :headline-stars on the leading stars in a headline
13137 :todo-keyword on a TODO keyword (including DONE) in a headline
13138 :tags on the TAGS in a headline
13139 :priority on the priority cookie in a headline
13140 :item on the first line of a plain list item
13141 :item-bullet on the bullet/number of a plain list item
13142 :checkbox on the checkbox in a plain list item
13143 :table in an org-mode table
13144 :table-special on a special filed in a table
13145 :table-table in a table.el table
13146 :link on a hyperlink
13147 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
13148 :target on a <<target>>
13149 :radio-target on a <<<radio-target>>>
13150 :latex-fragment on a LaTeX fragment
13151 :latex-preview on a LaTeX fragment with overlayed preview image
13153 This function expects the position to be visible because it uses font-lock
13154 faces as a help to recognize the following contexts: :table-special, :link,
13155 and :keyword."
13156 (let* ((f (get-text-property (point) 'face))
13157 (faces (if (listp f) f (list f)))
13158 (p (point)) clist o)
13159 ;; First the large context
13160 (cond
13161 ((org-on-heading-p t)
13162 (push (list :headline (point-at-bol) (point-at-eol)) clist)
13163 (when (progn
13164 (beginning-of-line 1)
13165 (looking-at org-todo-line-tags-regexp))
13166 (push (org-point-in-group p 1 :headline-stars) clist)
13167 (push (org-point-in-group p 2 :todo-keyword) clist)
13168 (push (org-point-in-group p 4 :tags) clist))
13169 (goto-char p)
13170 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
13171 (if (looking-at "\\[#[A-Z0-9]\\]")
13172 (push (org-point-in-group p 0 :priority) clist)))
13174 ((org-at-item-p)
13175 (push (org-point-in-group p 2 :item-bullet) clist)
13176 (push (list :item (point-at-bol)
13177 (save-excursion (org-end-of-item) (point)))
13178 clist)
13179 (and (org-at-item-checkbox-p)
13180 (push (org-point-in-group p 0 :checkbox) clist)))
13182 ((org-at-table-p)
13183 (push (list :table (org-table-begin) (org-table-end)) clist)
13184 (if (memq 'org-formula faces)
13185 (push (list :table-special
13186 (previous-single-property-change p 'face)
13187 (next-single-property-change p 'face)) clist)))
13188 ((org-at-table-p 'any)
13189 (push (list :table-table) clist)))
13190 (goto-char p)
13192 ;; Now the small context
13193 (cond
13194 ((org-at-timestamp-p)
13195 (push (org-point-in-group p 0 :timestamp) clist))
13196 ((memq 'org-link faces)
13197 (push (list :link
13198 (previous-single-property-change p 'face)
13199 (next-single-property-change p 'face)) clist))
13200 ((memq 'org-special-keyword faces)
13201 (push (list :keyword
13202 (previous-single-property-change p 'face)
13203 (next-single-property-change p 'face)) clist))
13204 ((org-on-target-p)
13205 (push (org-point-in-group p 0 :target) clist)
13206 (goto-char (1- (match-beginning 0)))
13207 (if (looking-at org-radio-target-regexp)
13208 (push (org-point-in-group p 0 :radio-target) clist))
13209 (goto-char p))
13210 ((setq o (car (delq nil
13211 (mapcar
13212 (lambda (x)
13213 (if (memq x org-latex-fragment-image-overlays) x))
13214 (org-overlays-at (point))))))
13215 (push (list :latex-fragment
13216 (org-overlay-start o) (org-overlay-end o)) clist)
13217 (push (list :latex-preview
13218 (org-overlay-start o) (org-overlay-end o)) clist))
13219 ((org-inside-LaTeX-fragment-p)
13220 ;; FIXME: positions wrong.
13221 (push (list :latex-fragment (point) (point)) clist)))
13223 (setq clist (nreverse (delq nil clist)))
13224 clist))
13226 ;; FIXME: Compare with at-regexp-p Do we need both?
13227 (defun org-in-regexp (re &optional nlines visually)
13228 "Check if point is inside a match of regexp.
13229 Normally only the current line is checked, but you can include NLINES extra
13230 lines both before and after point into the search.
13231 If VISUALLY is set, require that the cursor is not after the match but
13232 really on, so that the block visually is on the match."
13233 (catch 'exit
13234 (let ((pos (point))
13235 (eol (point-at-eol (+ 1 (or nlines 0))))
13236 (inc (if visually 1 0)))
13237 (save-excursion
13238 (beginning-of-line (- 1 (or nlines 0)))
13239 (while (re-search-forward re eol t)
13240 (if (and (<= (match-beginning 0) pos)
13241 (>= (+ inc (match-end 0)) pos))
13242 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
13244 (defun org-at-regexp-p (regexp)
13245 "Is point inside a match of REGEXP in the current line?"
13246 (catch 'exit
13247 (save-excursion
13248 (let ((pos (point)) (end (point-at-eol)))
13249 (beginning-of-line 1)
13250 (while (re-search-forward regexp end t)
13251 (if (and (<= (match-beginning 0) pos)
13252 (>= (match-end 0) pos))
13253 (throw 'exit t)))
13254 nil))))
13256 (defun org-occur-in-agenda-files (regexp &optional nlines)
13257 "Call `multi-occur' with buffers for all agenda files."
13258 (interactive "sOrg-files matching: \np")
13259 (let* ((files (org-agenda-files))
13260 (tnames (mapcar 'file-truename files))
13261 (extra org-agenda-text-search-extra-files)
13263 (when (eq (car extra) 'agenda-archives)
13264 (setq extra (cdr extra))
13265 (setq files (org-add-archive-files files)))
13266 (while (setq f (pop extra))
13267 (unless (member (file-truename f) tnames)
13268 (add-to-list 'files f 'append)
13269 (add-to-list 'tnames (file-truename f) 'append)))
13270 (multi-occur
13271 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
13272 regexp)))
13274 (if (boundp 'occur-mode-find-occurrence-hook)
13275 ;; Emacs 23
13276 (add-hook 'occur-mode-find-occurrence-hook
13277 (lambda ()
13278 (when (org-mode-p)
13279 (org-reveal))))
13280 ;; Emacs 22
13281 (defadvice occur-mode-goto-occurrence
13282 (after org-occur-reveal activate)
13283 (and (org-mode-p) (org-reveal)))
13284 (defadvice occur-mode-goto-occurrence-other-window
13285 (after org-occur-reveal activate)
13286 (and (org-mode-p) (org-reveal)))
13287 (defadvice occur-mode-display-occurrence
13288 (after org-occur-reveal activate)
13289 (when (org-mode-p)
13290 (let ((pos (occur-mode-find-occurrence)))
13291 (with-current-buffer (marker-buffer pos)
13292 (save-excursion
13293 (goto-char pos)
13294 (org-reveal)))))))
13296 (defun org-uniquify (list)
13297 "Remove duplicate elements from LIST."
13298 (let (res)
13299 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
13300 res))
13302 (defun org-delete-all (elts list)
13303 "Remove all elements in ELTS from LIST."
13304 (while elts
13305 (setq list (delete (pop elts) list)))
13306 list)
13308 (defun org-back-over-empty-lines ()
13309 "Move backwards over witespace, to the beginning of the first empty line.
13310 Returns the number of empty lines passed."
13311 (let ((pos (point)))
13312 (skip-chars-backward " \t\n\r")
13313 (beginning-of-line 2)
13314 (goto-char (min (point) pos))
13315 (count-lines (point) pos)))
13317 (defun org-skip-whitespace ()
13318 (skip-chars-forward " \t\n\r"))
13320 (defun org-point-in-group (point group &optional context)
13321 "Check if POINT is in match-group GROUP.
13322 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
13323 match. If the match group does ot exist or point is not inside it,
13324 return nil."
13325 (and (match-beginning group)
13326 (>= point (match-beginning group))
13327 (<= point (match-end group))
13328 (if context
13329 (list context (match-beginning group) (match-end group))
13330 t)))
13332 (defun org-switch-to-buffer-other-window (&rest args)
13333 "Switch to buffer in a second window on the current frame.
13334 In particular, do not allow pop-up frames."
13335 (let (pop-up-frames special-display-buffer-names special-display-regexps
13336 special-display-function)
13337 (apply 'switch-to-buffer-other-window args)))
13339 (defun org-combine-plists (&rest plists)
13340 "Create a single property list from all plists in PLISTS.
13341 The process starts by copying the first list, and then setting properties
13342 from the other lists. Settings in the last list are the most significant
13343 ones and overrule settings in the other lists."
13344 (let ((rtn (copy-sequence (pop plists)))
13345 p v ls)
13346 (while plists
13347 (setq ls (pop plists))
13348 (while ls
13349 (setq p (pop ls) v (pop ls))
13350 (setq rtn (plist-put rtn p v))))
13351 rtn))
13353 (defun org-move-line-down (arg)
13354 "Move the current line down. With prefix argument, move it past ARG lines."
13355 (interactive "p")
13356 (let ((col (current-column))
13357 beg end pos)
13358 (beginning-of-line 1) (setq beg (point))
13359 (beginning-of-line 2) (setq end (point))
13360 (beginning-of-line (+ 1 arg))
13361 (setq pos (move-marker (make-marker) (point)))
13362 (insert (delete-and-extract-region beg end))
13363 (goto-char pos)
13364 (org-move-to-column col)))
13366 (defun org-move-line-up (arg)
13367 "Move the current line up. With prefix argument, move it past ARG lines."
13368 (interactive "p")
13369 (let ((col (current-column))
13370 beg end pos)
13371 (beginning-of-line 1) (setq beg (point))
13372 (beginning-of-line 2) (setq end (point))
13373 (beginning-of-line (- arg))
13374 (setq pos (move-marker (make-marker) (point)))
13375 (insert (delete-and-extract-region beg end))
13376 (goto-char pos)
13377 (org-move-to-column col)))
13379 (defun org-replace-escapes (string table)
13380 "Replace %-escapes in STRING with values in TABLE.
13381 TABLE is an association list with keys like \"%a\" and string values.
13382 The sequences in STRING may contain normal field width and padding information,
13383 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
13384 so values can contain further %-escapes if they are define later in TABLE."
13385 (let ((case-fold-search nil)
13386 e re rpl)
13387 (while (setq e (pop table))
13388 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
13389 (while (string-match re string)
13390 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
13391 (cdr e)))
13392 (setq string (replace-match rpl t t string))))
13393 string))
13396 (defun org-sublist (list start end)
13397 "Return a section of LIST, from START to END.
13398 Counting starts at 1."
13399 (let (rtn (c start))
13400 (setq list (nthcdr (1- start) list))
13401 (while (and list (<= c end))
13402 (push (pop list) rtn)
13403 (setq c (1+ c)))
13404 (nreverse rtn)))
13406 (defun org-find-base-buffer-visiting (file)
13407 "Like `find-buffer-visiting' but alway return the base buffer and
13408 not an indirect buffer."
13409 (let ((buf (find-buffer-visiting file)))
13410 (if buf
13411 (or (buffer-base-buffer buf) buf)
13412 nil)))
13414 (defun org-image-file-name-regexp ()
13415 "Return regexp matching the file names of images."
13416 (if (fboundp 'image-file-name-regexp)
13417 (image-file-name-regexp)
13418 (let ((image-file-name-extensions
13419 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
13420 "xbm" "xpm" "pbm" "pgm" "ppm")))
13421 (concat "\\."
13422 (regexp-opt (nconc (mapcar 'upcase
13423 image-file-name-extensions)
13424 image-file-name-extensions)
13426 "\\'"))))
13428 (defun org-file-image-p (file)
13429 "Return non-nil if FILE is an image."
13430 (save-match-data
13431 (string-match (org-image-file-name-regexp) file)))
13433 (defun org-get-cursor-date ()
13434 "Return the date at cursor in as a time.
13435 This works in the calendar and in the agenda, anywhere else it just
13436 returns the current time."
13437 (let (date day defd)
13438 (cond
13439 ((eq major-mode 'calendar-mode)
13440 (setq date (calendar-cursor-to-date)
13441 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13442 ((eq major-mode 'org-agenda-mode)
13443 (setq day (get-text-property (point) 'day))
13444 (if day
13445 (setq date (calendar-gregorian-from-absolute day)
13446 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
13447 (nth 2 date))))))
13448 (or defd (current-time))))
13450 (defvar org-agenda-action-marker (make-marker)
13451 "Marker pointing to the entry for the next agenda action.")
13453 (defun org-mark-entry-for-agenda-action ()
13454 "Mark the current entry as target of an agenda action.
13455 Agenda actions are actions executed from the agenda with the key `k',
13456 which make use of the date at the cursor."
13457 (interactive)
13458 (move-marker org-agenda-action-marker
13459 (save-excursion (org-back-to-heading t) (point))
13460 (current-buffer))
13461 (message
13462 "Entry marked for action; press `k' at desired date in agenda or calendar"))
13464 ;;; Paragraph filling stuff.
13465 ;; We want this to be just right, so use the full arsenal.
13467 (defun org-indent-line-function ()
13468 "Indent line like previous, but further if previous was headline or item."
13469 (interactive)
13470 (let* ((pos (point))
13471 (itemp (org-at-item-p))
13472 column bpos bcol tpos tcol bullet btype bullet-type)
13473 ;; Find the previous relevant line
13474 (beginning-of-line 1)
13475 (cond
13476 ((looking-at "#") (setq column 0))
13477 ((looking-at "\\*+ ") (setq column 0))
13479 (beginning-of-line 0)
13480 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
13481 (beginning-of-line 0))
13482 (cond
13483 ((looking-at "\\*+[ \t]+")
13484 (if (not org-adapt-indentation)
13485 (setq column 0)
13486 (goto-char (match-end 0))
13487 (setq column (current-column))))
13488 ((org-in-item-p)
13489 (org-beginning-of-item)
13490 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
13491 (setq bpos (match-beginning 1) tpos (match-end 0)
13492 bcol (progn (goto-char bpos) (current-column))
13493 tcol (progn (goto-char tpos) (current-column))
13494 bullet (match-string 1)
13495 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
13496 (if (> tcol (+ bcol org-description-max-indent))
13497 (setq tcol (+ bcol 5)))
13498 (if (not itemp)
13499 (setq column tcol)
13500 (goto-char pos)
13501 (beginning-of-line 1)
13502 (if (looking-at "\\S-")
13503 (progn
13504 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
13505 (setq bullet (match-string 1)
13506 btype (if (string-match "[0-9]" bullet) "n" bullet))
13507 (setq column (if (equal btype bullet-type) bcol tcol)))
13508 (setq column (org-get-indentation)))))
13509 (t (setq column (org-get-indentation))))))
13510 (goto-char pos)
13511 (if (<= (current-column) (current-indentation))
13512 (org-indent-line-to column)
13513 (save-excursion (org-indent-line-to column)))
13514 (setq column (current-column))
13515 (beginning-of-line 1)
13516 (if (looking-at
13517 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
13518 (replace-match (concat "\\1" (format org-property-format
13519 (match-string 2) (match-string 3)))
13520 t nil))
13521 (org-move-to-column column)))
13523 (defun org-set-autofill-regexps ()
13524 (interactive)
13525 ;; In the paragraph separator we include headlines, because filling
13526 ;; text in a line directly attached to a headline would otherwise
13527 ;; fill the headline as well.
13528 (org-set-local 'comment-start-skip "^#+[ \t]*")
13529 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
13530 ;; The paragraph starter includes hand-formatted lists.
13531 (org-set-local 'paragraph-start
13532 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
13533 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
13534 ;; But only if the user has not turned off tables or fixed-width regions
13535 (org-set-local
13536 'auto-fill-inhibit-regexp
13537 (concat "\\*+ \\|#\\+"
13538 "\\|[ \t]*" org-keyword-time-regexp
13539 (if (or org-enable-table-editor org-enable-fixed-width-editor)
13540 (concat
13541 "\\|[ \t]*["
13542 (if org-enable-table-editor "|" "")
13543 (if org-enable-fixed-width-editor ":" "")
13544 "]"))))
13545 ;; We use our own fill-paragraph function, to make sure that tables
13546 ;; and fixed-width regions are not wrapped. That function will pass
13547 ;; through to `fill-paragraph' when appropriate.
13548 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
13549 ; Adaptive filling: To get full control, first make sure that
13550 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
13551 (org-set-local 'adaptive-fill-regexp "\000")
13552 (org-set-local 'adaptive-fill-function
13553 'org-adaptive-fill-function)
13554 (org-set-local
13555 'align-mode-rules-list
13556 '((org-in-buffer-settings
13557 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
13558 (modes . '(org-mode))))))
13560 (defun org-fill-paragraph (&optional justify)
13561 "Re-align a table, pass through to fill-paragraph if no table."
13562 (let ((table-p (org-at-table-p))
13563 (table.el-p (org-at-table.el-p)))
13564 (cond ((and (equal (char-after (point-at-bol)) ?*)
13565 (save-excursion (goto-char (point-at-bol))
13566 (looking-at outline-regexp)))
13567 t) ; skip headlines
13568 (table.el-p t) ; skip table.el tables
13569 (table-p (org-table-align) t) ; align org-mode tables
13570 (t nil)))) ; call paragraph-fill
13572 ;; For reference, this is the default value of adaptive-fill-regexp
13573 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
13575 (defun org-adaptive-fill-function ()
13576 "Return a fill prefix for org-mode files.
13577 In particular, this makes sure hanging paragraphs for hand-formatted lists
13578 work correctly."
13579 (cond ((looking-at "#[ \t]+")
13580 (match-string 0))
13581 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
13582 (save-excursion
13583 (if (> (match-end 1) (+ (match-beginning 1)
13584 org-description-max-indent))
13585 (goto-char (+ (match-beginning 1) 5))
13586 (goto-char (match-end 0)))
13587 (make-string (current-column) ?\ )))
13588 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
13589 (save-excursion
13590 (goto-char (match-end 0))
13591 (make-string (current-column) ?\ )))
13592 (t nil)))
13594 ;;; Other stuff.
13596 (defun org-toggle-fixed-width-section (arg)
13597 "Toggle the fixed-width export.
13598 If there is no active region, the QUOTE keyword at the current headline is
13599 inserted or removed. When present, it causes the text between this headline
13600 and the next to be exported as fixed-width text, and unmodified.
13601 If there is an active region, this command adds or removes a colon as the
13602 first character of this line. If the first character of a line is a colon,
13603 this line is also exported in fixed-width font."
13604 (interactive "P")
13605 (let* ((cc 0)
13606 (regionp (org-region-active-p))
13607 (beg (if regionp (region-beginning) (point)))
13608 (end (if regionp (region-end)))
13609 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
13610 (case-fold-search nil)
13611 (re "[ \t]*\\(:\\)")
13612 off)
13613 (if regionp
13614 (save-excursion
13615 (goto-char beg)
13616 (setq cc (current-column))
13617 (beginning-of-line 1)
13618 (setq off (looking-at re))
13619 (while (> nlines 0)
13620 (setq nlines (1- nlines))
13621 (beginning-of-line 1)
13622 (cond
13623 (arg
13624 (org-move-to-column cc t)
13625 (insert ":\n")
13626 (forward-line -1))
13627 ((and off (looking-at re))
13628 (replace-match "" t t nil 1))
13629 ((not off) (org-move-to-column cc t) (insert ":")))
13630 (forward-line 1)))
13631 (save-excursion
13632 (org-back-to-heading)
13633 (if (looking-at (concat outline-regexp
13634 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
13635 (replace-match "" t t nil 1)
13636 (if (looking-at outline-regexp)
13637 (progn
13638 (goto-char (match-end 0))
13639 (insert org-quote-string " "))))))))
13641 ;;;; Functions extending outline functionality
13643 (defun org-beginning-of-line (&optional arg)
13644 "Go to the beginning of the current line. If that is invisible, continue
13645 to a visible line beginning. This makes the function of C-a more intuitive.
13646 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
13647 first attempt, and only move to after the tags when the cursor is already
13648 beyond the end of the headline."
13649 (interactive "P")
13650 (let ((pos (point)) refpos)
13651 (beginning-of-line 1)
13652 (if (bobp)
13654 (backward-char 1)
13655 (if (org-invisible-p)
13656 (while (and (not (bobp)) (org-invisible-p))
13657 (backward-char 1)
13658 (beginning-of-line 1))
13659 (forward-char 1)))
13660 (when org-special-ctrl-a/e
13661 (cond
13662 ((and (looking-at org-complex-heading-regexp)
13663 (= (char-after (match-end 1)) ?\ ))
13664 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
13665 (point-at-eol)))
13666 (goto-char
13667 (if (eq org-special-ctrl-a/e t)
13668 (cond ((> pos refpos) refpos)
13669 ((= pos (point)) refpos)
13670 (t (point)))
13671 (cond ((> pos (point)) (point))
13672 ((not (eq last-command this-command)) (point))
13673 (t refpos)))))
13674 ((org-at-item-p)
13675 (goto-char
13676 (if (eq org-special-ctrl-a/e t)
13677 (cond ((> pos (match-end 4)) (match-end 4))
13678 ((= pos (point)) (match-end 4))
13679 (t (point)))
13680 (cond ((> pos (point)) (point))
13681 ((not (eq last-command this-command)) (point))
13682 (t (match-end 4))))))))
13683 (org-no-warnings
13684 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
13686 (defun org-end-of-line (&optional arg)
13687 "Go to the end of the line.
13688 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
13689 first attempt, and only move to after the tags when the cursor is already
13690 beyond the end of the headline."
13691 (interactive "P")
13692 (if (or (not org-special-ctrl-a/e)
13693 (not (org-on-heading-p)))
13694 (end-of-line arg)
13695 (let ((pos (point)))
13696 (beginning-of-line 1)
13697 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
13698 (if (eq org-special-ctrl-a/e t)
13699 (if (or (< pos (match-beginning 1))
13700 (= pos (match-end 0)))
13701 (goto-char (match-beginning 1))
13702 (goto-char (match-end 0)))
13703 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
13704 (goto-char (match-end 0))
13705 (goto-char (match-beginning 1))))
13706 (end-of-line arg))))
13707 (org-no-warnings
13708 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
13711 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
13712 (define-key org-mode-map "\C-e" 'org-end-of-line)
13714 (defun org-kill-line (&optional arg)
13715 "Kill line, to tags or end of line."
13716 (interactive "P")
13717 (cond
13718 ((or (not org-special-ctrl-k)
13719 (bolp)
13720 (not (org-on-heading-p)))
13721 (call-interactively 'kill-line))
13722 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
13723 (kill-region (point) (match-beginning 1))
13724 (org-set-tags nil t))
13725 (t (kill-region (point) (point-at-eol)))))
13728 (define-key org-mode-map "\C-k" 'org-kill-line)
13730 (defun org-yank ()
13731 "Yank, and if the yanked text is a single subtree, fold it.
13732 In fact, if the yanked text is a sequence of subtrees, fold all of them."
13733 (interactive)
13734 (if org-yank-folded-subtrees
13735 (let ((beg (point)) end)
13736 (call-interactively 'yank)
13737 (setq end (point))
13738 (goto-char beg)
13739 (when (and (bolp)
13740 (org-kill-is-subtree-p))
13741 (or (looking-at outline-regexp)
13742 (re-search-forward (concat "^" outline-regexp) end t))
13743 (while (and (< (point) end) (looking-at outline-regexp))
13744 (hide-subtree)
13745 (org-cycle-show-empty-lines 'folded)
13746 (condition-case nil
13747 (outline-forward-same-level 1)
13748 (error (goto-char end)))))
13749 (goto-char end)
13750 (skip-chars-forward " \t\n\r"))
13751 (call-interactively 'yank)))
13753 (define-key org-mode-map "\C-y" 'org-yank)
13755 (defun org-invisible-p ()
13756 "Check if point is at a character currently not visible."
13757 ;; Early versions of noutline don't have `outline-invisible-p'.
13758 (if (fboundp 'outline-invisible-p)
13759 (outline-invisible-p)
13760 (get-char-property (point) 'invisible)))
13762 (defun org-invisible-p2 ()
13763 "Check if point is at a character currently not visible."
13764 (save-excursion
13765 (if (and (eolp) (not (bobp))) (backward-char 1))
13766 ;; Early versions of noutline don't have `outline-invisible-p'.
13767 (if (fboundp 'outline-invisible-p)
13768 (outline-invisible-p)
13769 (get-char-property (point) 'invisible))))
13771 (defalias 'org-back-to-heading 'outline-back-to-heading)
13772 (defalias 'org-on-heading-p 'outline-on-heading-p)
13773 (defalias 'org-at-heading-p 'outline-on-heading-p)
13774 (defun org-at-heading-or-item-p ()
13775 (or (org-on-heading-p) (org-at-item-p)))
13777 (defun org-on-target-p ()
13778 (or (org-in-regexp org-radio-target-regexp)
13779 (org-in-regexp org-target-regexp)))
13781 (defun org-up-heading-all (arg)
13782 "Move to the heading line of which the present line is a subheading.
13783 This function considers both visible and invisible heading lines.
13784 With argument, move up ARG levels."
13785 (if (fboundp 'outline-up-heading-all)
13786 (outline-up-heading-all arg) ; emacs 21 version of outline.el
13787 (outline-up-heading arg t))) ; emacs 22 version of outline.el
13789 (defun org-up-heading-safe ()
13790 "Move to the heading line of which the present line is a subheading.
13791 This version will not throw an error. It will return the level of the
13792 headline found, or nil if no higher level is found."
13793 (let ((pos (point)) start-level level
13794 (re (concat "^" outline-regexp)))
13795 (catch 'exit
13796 (outline-back-to-heading t)
13797 (setq start-level (funcall outline-level))
13798 (if (equal start-level 1) (throw 'exit nil))
13799 (while (re-search-backward re nil t)
13800 (setq level (funcall outline-level))
13801 (if (< level start-level) (throw 'exit level)))
13802 nil)))
13804 (defun org-first-sibling-p ()
13805 "Is this heading the first child of its parents?"
13806 (interactive)
13807 (let ((re (concat "^" outline-regexp))
13808 level l)
13809 (unless (org-at-heading-p t)
13810 (error "Not at a heading"))
13811 (setq level (funcall outline-level))
13812 (save-excursion
13813 (if (not (re-search-backward re nil t))
13815 (setq l (funcall outline-level))
13816 (< l level)))))
13818 (defun org-goto-sibling (&optional previous)
13819 "Goto the next sibling, even if it is invisible.
13820 When PREVIOUS is set, go to the previous sibling instead. Returns t
13821 when a sibling was found. When none is found, return nil and don't
13822 move point."
13823 (let ((fun (if previous 're-search-backward 're-search-forward))
13824 (pos (point))
13825 (re (concat "^" outline-regexp))
13826 level l)
13827 (when (condition-case nil (org-back-to-heading t) (error nil))
13828 (setq level (funcall outline-level))
13829 (catch 'exit
13830 (or previous (forward-char 1))
13831 (while (funcall fun re nil t)
13832 (setq l (funcall outline-level))
13833 (when (< l level) (goto-char pos) (throw 'exit nil))
13834 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
13835 (goto-char pos)
13836 nil))))
13838 (defun org-show-siblings ()
13839 "Show all siblings of the current headline."
13840 (save-excursion
13841 (while (org-goto-sibling) (org-flag-heading nil)))
13842 (save-excursion
13843 (while (org-goto-sibling 'previous)
13844 (org-flag-heading nil))))
13846 (defun org-show-hidden-entry ()
13847 "Show an entry where even the heading is hidden."
13848 (save-excursion
13849 (org-show-entry)))
13851 (defun org-flag-heading (flag &optional entry)
13852 "Flag the current heading. FLAG non-nil means make invisible.
13853 When ENTRY is non-nil, show the entire entry."
13854 (save-excursion
13855 (org-back-to-heading t)
13856 ;; Check if we should show the entire entry
13857 (if entry
13858 (progn
13859 (org-show-entry)
13860 (save-excursion
13861 (and (outline-next-heading)
13862 (org-flag-heading nil))))
13863 (outline-flag-region (max (point-min) (1- (point)))
13864 (save-excursion (outline-end-of-heading) (point))
13865 flag))))
13867 (defun org-forward-same-level (arg)
13868 "Move forward to the ARG'th subheading at same level as this one.
13869 Stop at the first and last subheadings of a superior heading.
13870 This is like outline-forward-same-level, but invisible headings are ok."
13871 (interactive "p")
13872 (outline-back-to-heading t)
13873 (while (> arg 0)
13874 (let ((point-to-move-to (save-excursion
13875 (org-get-next-sibling))))
13876 (if point-to-move-to
13877 (progn
13878 (goto-char point-to-move-to)
13879 (setq arg (1- arg)))
13880 (progn
13881 (setq arg 0)
13882 (error "No following same-level heading"))))))
13884 (defun org-get-next-sibling ()
13885 "Move to next heading of the same level, and return point.
13886 If there is no such heading, return nil.
13887 This is like outline-next-sibling, but invisible headings are ok."
13888 (let ((level (funcall outline-level)))
13889 (outline-next-heading)
13890 (while (and (not (eobp)) (> (funcall outline-level) level))
13891 (outline-next-heading))
13892 (if (or (eobp) (< (funcall outline-level) level))
13894 (point))))
13896 (defun org-end-of-subtree (&optional invisible-OK to-heading)
13897 ;; This is an exact copy of the original function, but it uses
13898 ;; `org-back-to-heading', to make it work also in invisible
13899 ;; trees. And is uses an invisible-OK argument.
13900 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
13901 (org-back-to-heading invisible-OK)
13902 (let ((first t)
13903 (level (funcall outline-level)))
13904 (while (and (not (eobp))
13905 (or first (> (funcall outline-level) level)))
13906 (setq first nil)
13907 (outline-next-heading))
13908 (unless to-heading
13909 (if (memq (preceding-char) '(?\n ?\^M))
13910 (progn
13911 ;; Go to end of line before heading
13912 (forward-char -1)
13913 (if (memq (preceding-char) '(?\n ?\^M))
13914 ;; leave blank line before heading
13915 (forward-char -1))))))
13916 (point))
13918 (defun org-show-subtree ()
13919 "Show everything after this heading at deeper levels."
13920 (outline-flag-region
13921 (point)
13922 (save-excursion
13923 (outline-end-of-subtree) (outline-next-heading) (point))
13924 nil))
13926 (defun org-show-entry ()
13927 "Show the body directly following this heading.
13928 Show the heading too, if it is currently invisible."
13929 (interactive)
13930 (save-excursion
13931 (condition-case nil
13932 (progn
13933 (org-back-to-heading t)
13934 (outline-flag-region
13935 (max (point-min) (1- (point)))
13936 (save-excursion
13937 (re-search-forward
13938 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
13939 (or (match-beginning 1) (point-max)))
13940 nil))
13941 (error nil))))
13943 (defun org-make-options-regexp (kwds)
13944 "Make a regular expression for keyword lines."
13945 (concat
13947 "#?[ \t]*\\+\\("
13948 (mapconcat 'regexp-quote kwds "\\|")
13949 "\\):[ \t]*"
13950 "\\(.+\\)"))
13952 ;; Make isearch reveal the necessary context
13953 (defun org-isearch-end ()
13954 "Reveal context after isearch exits."
13955 (when isearch-success ; only if search was successful
13956 (if (featurep 'xemacs)
13957 ;; Under XEmacs, the hook is run in the correct place,
13958 ;; we directly show the context.
13959 (org-show-context 'isearch)
13960 ;; In Emacs the hook runs *before* restoring the overlays.
13961 ;; So we have to use a one-time post-command-hook to do this.
13962 ;; (Emacs 22 has a special variable, see function `org-mode')
13963 (unless (and (boundp 'isearch-mode-end-hook-quit)
13964 isearch-mode-end-hook-quit)
13965 ;; Only when the isearch was not quitted.
13966 (org-add-hook 'post-command-hook 'org-isearch-post-command
13967 'append 'local)))))
13969 (defun org-isearch-post-command ()
13970 "Remove self from hook, and show context."
13971 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
13972 (org-show-context 'isearch))
13975 ;;;; Integration with and fixes for other packages
13977 ;;; Imenu support
13979 (defvar org-imenu-markers nil
13980 "All markers currently used by Imenu.")
13981 (make-variable-buffer-local 'org-imenu-markers)
13983 (defun org-imenu-new-marker (&optional pos)
13984 "Return a new marker for use by Imenu, and remember the marker."
13985 (let ((m (make-marker)))
13986 (move-marker m (or pos (point)))
13987 (push m org-imenu-markers)
13990 (defun org-imenu-get-tree ()
13991 "Produce the index for Imenu."
13992 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
13993 (setq org-imenu-markers nil)
13994 (let* ((n org-imenu-depth)
13995 (re (concat "^" outline-regexp))
13996 (subs (make-vector (1+ n) nil))
13997 (last-level 0)
13998 m tree level head)
13999 (save-excursion
14000 (save-restriction
14001 (widen)
14002 (goto-char (point-max))
14003 (while (re-search-backward re nil t)
14004 (setq level (org-reduced-level (funcall outline-level)))
14005 (when (<= level n)
14006 (looking-at org-complex-heading-regexp)
14007 (setq head (org-link-display-format
14008 (org-match-string-no-properties 4))
14009 m (org-imenu-new-marker))
14010 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
14011 (if (>= level last-level)
14012 (push (cons head m) (aref subs level))
14013 (push (cons head (aref subs (1+ level))) (aref subs level))
14014 (loop for i from (1+ level) to n do (aset subs i nil)))
14015 (setq last-level level)))))
14016 (aref subs 1)))
14018 (eval-after-load "imenu"
14019 '(progn
14020 (add-hook 'imenu-after-jump-hook
14021 (lambda ()
14022 (if (eq major-mode 'org-mode)
14023 (org-show-context 'org-goto))))))
14025 (defun org-link-display-format (link)
14026 "Replace a link with either the description, or the link target
14027 if no description is present"
14028 (save-match-data
14029 (if (string-match org-bracket-link-analytic-regexp link)
14030 (replace-match (or (match-string 5 link)
14031 (concat (match-string 1 link)
14032 (match-string 3 link)))
14033 nil nil link)
14034 link)))
14036 ;; Speedbar support
14038 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
14039 "Overlay marking the agenda restriction line in speedbar.")
14040 (org-overlay-put org-speedbar-restriction-lock-overlay
14041 'face 'org-agenda-restriction-lock)
14042 (org-overlay-put org-speedbar-restriction-lock-overlay
14043 'help-echo "Agendas are currently limited to this item.")
14044 (org-detach-overlay org-speedbar-restriction-lock-overlay)
14046 (defun org-speedbar-set-agenda-restriction ()
14047 "Restrict future agenda commands to the location at point in speedbar.
14048 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
14049 (interactive)
14050 (require 'org-agenda)
14051 (let (p m tp np dir txt w)
14052 (cond
14053 ((setq p (text-property-any (point-at-bol) (point-at-eol)
14054 'org-imenu t))
14055 (setq m (get-text-property p 'org-imenu-marker))
14056 (save-excursion
14057 (save-restriction
14058 (set-buffer (marker-buffer m))
14059 (goto-char m)
14060 (org-agenda-set-restriction-lock 'subtree))))
14061 ((setq p (text-property-any (point-at-bol) (point-at-eol)
14062 'speedbar-function 'speedbar-find-file))
14063 (setq tp (previous-single-property-change
14064 (1+ p) 'speedbar-function)
14065 np (next-single-property-change
14066 tp 'speedbar-function)
14067 dir (speedbar-line-directory)
14068 txt (buffer-substring-no-properties (or tp (point-min))
14069 (or np (point-max))))
14070 (save-excursion
14071 (save-restriction
14072 (set-buffer (find-file-noselect
14073 (let ((default-directory dir))
14074 (expand-file-name txt))))
14075 (unless (org-mode-p)
14076 (error "Cannot restrict to non-Org-mode file"))
14077 (org-agenda-set-restriction-lock 'file))))
14078 (t (error "Don't know how to restrict Org-mode's agenda")))
14079 (org-move-overlay org-speedbar-restriction-lock-overlay
14080 (point-at-bol) (point-at-eol))
14081 (setq current-prefix-arg nil)
14082 (org-agenda-maybe-redo)))
14084 (eval-after-load "speedbar"
14085 '(progn
14086 (speedbar-add-supported-extension ".org")
14087 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
14088 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
14089 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
14090 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
14091 (add-hook 'speedbar-visiting-tag-hook
14092 (lambda () (org-show-context 'org-goto)))))
14095 ;;; Fixes and Hacks for problems with other packages
14097 ;; Make flyspell not check words in links, to not mess up our keymap
14098 (defun org-mode-flyspell-verify ()
14099 "Don't let flyspell put overlays at active buttons."
14100 (not (get-text-property (point) 'keymap)))
14102 ;; Make `bookmark-jump' show the jump location if it was hidden.
14103 (eval-after-load "bookmark"
14104 '(if (boundp 'bookmark-after-jump-hook)
14105 ;; We can use the hook
14106 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
14107 ;; Hook not available, use advice
14108 (defadvice bookmark-jump (after org-make-visible activate)
14109 "Make the position visible."
14110 (org-bookmark-jump-unhide))))
14112 (defun org-bookmark-jump-unhide ()
14113 "Unhide the current position, to show the bookmark location."
14114 (and (org-mode-p)
14115 (or (org-invisible-p)
14116 (save-excursion (goto-char (max (point-min) (1- (point))))
14117 (org-invisible-p)))
14118 (org-show-context 'bookmark-jump)))
14120 ;; Make session.el ignore our circular variable
14121 (eval-after-load "session"
14122 '(add-to-list 'session-globals-exclude 'org-mark-ring))
14124 ;;;; Experimental code
14126 (defun org-closed-in-range ()
14127 "Sparse tree of items closed in a certain time range.
14128 Still experimental, may disappear in the future."
14129 (interactive)
14130 ;; Get the time interval from the user.
14131 (let* ((time1 (time-to-seconds
14132 (org-read-date nil 'to-time nil "Starting date: ")))
14133 (time2 (time-to-seconds
14134 (org-read-date nil 'to-time nil "End date:")))
14135 ;; callback function
14136 (callback (lambda ()
14137 (let ((time
14138 (time-to-seconds
14139 (apply 'encode-time
14140 (org-parse-time-string
14141 (match-string 1))))))
14142 ;; check if time in interval
14143 (and (>= time time1) (<= time time2))))))
14144 ;; make tree, check each match with the callback
14145 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
14148 ;;;; Finish up
14150 (provide 'org)
14152 (run-hooks 'org-load-hook)
14154 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
14156 ;;; org.el ends here