Yank subtree back in a level-adjusted way.
[org-mode/org-tableheadings.git] / lisp / org.el
blob82e3ad5ca1c4cdfaaa059f1386af711a190ce0a2
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.10c
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.10c"
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-yank-adjusted-subtrees t
645 "Non-nil means, when yanking subtrees, adjust the level.
646 With this setting, `org-paste-subtree' is used to insert the subtree, see
647 this function for details."
648 :group 'org-edit-structure
649 :type 'boolean)
651 (defcustom org-M-RET-may-split-line '((default . t))
652 "Non-nil means, M-RET will split the line at the cursor position.
653 When nil, it will go to the end of the line before making a
654 new line.
655 You may also set this option in a different way for different
656 contexts. Valid contexts are:
658 headline when creating a new headline
659 item when creating a new item
660 table in a table field
661 default the value to be used for all contexts not explicitly
662 customized"
663 :group 'org-structure
664 :group 'org-table
665 :type '(choice
666 (const :tag "Always" t)
667 (const :tag "Never" nil)
668 (repeat :greedy t :tag "Individual contexts"
669 (cons
670 (choice :tag "Context"
671 (const headline)
672 (const item)
673 (const table)
674 (const default))
675 (boolean)))))
678 (defcustom org-insert-heading-respect-content nil
679 "Non-nil means, insert new headings after the current subtree.
680 When nil, the new heading is created directly after the current line.
681 The commands \\[org-insert-heading-respect-content] and
682 \\[org-insert-todo-heading-respect-content] turn this variable on
683 for the duration of the command."
684 :group 'org-structure
685 :type 'boolean)
687 (defcustom org-blank-before-new-entry '((heading . nil)
688 (plain-list-item . nil))
689 "Should `org-insert-heading' leave a blank line before new heading/item?
690 The value is an alist, with `heading' and `plain-list-item' as car,
691 and a boolean flag as cdr."
692 :group 'org-edit-structure
693 :type '(list
694 (cons (const heading) (boolean))
695 (cons (const plain-list-item) (boolean))))
697 (defcustom org-insert-heading-hook nil
698 "Hook being run after inserting a new heading."
699 :group 'org-edit-structure
700 :type 'hook)
702 (defcustom org-enable-fixed-width-editor t
703 "Non-nil means, lines starting with \":\" are treated as fixed-width.
704 This currently only means, they are never auto-wrapped.
705 When nil, such lines will be treated like ordinary lines.
706 See also the QUOTE keyword."
707 :group 'org-edit-structure
708 :type 'boolean)
710 (defcustom org-edit-src-region-extra nil
711 "Additional regexps to identify regions for editing with `org-edit-src-code'.
712 For examples see the function `org-edit-src-find-region-and-lang'.
713 The regular expression identifying the begin marker should end with a newline,
714 and the regexp marking the end line should start with a newline, to make sure
715 there are kept outside the narrowed region."
716 :group 'org-edit-structure
717 :type '(repeat
718 (list
719 (regexp :tag "begin regexp")
720 (regexp :tag "end regexp")
721 (choice :tag "language"
722 (string :tag "specify")
723 (integer :tag "from match group")
724 (const :tag "from `lang' element")
725 (const :tag "from `style' element")))))
727 (defcustom org-edit-fixed-width-region-mode 'artist-mode
728 "The mode that should be used to edit fixed-width regions.
729 These are the regions where each line starts with a colon."
730 :group 'org-edit-structure
731 :type '(choice
732 (const artist-mode)
733 (const picture-mode)
734 (const fundamental-mode)
735 (function :tag "Other (specify)")))
737 (defcustom org-goto-auto-isearch t
738 "Non-nil means, typing characters in org-goto starts incremental search."
739 :group 'org-edit-structure
740 :type 'boolean)
742 (defgroup org-sparse-trees nil
743 "Options concerning sparse trees in Org-mode."
744 :tag "Org Sparse Trees"
745 :group 'org-structure)
747 (defcustom org-highlight-sparse-tree-matches t
748 "Non-nil means, highlight all matches that define a sparse tree.
749 The highlights will automatically disappear the next time the buffer is
750 changed by an edit command."
751 :group 'org-sparse-trees
752 :type 'boolean)
754 (defcustom org-remove-highlights-with-change t
755 "Non-nil means, any change to the buffer will remove temporary highlights.
756 Such highlights are created by `org-occur' and `org-clock-display'.
757 When nil, `C-c C-c needs to be used to get rid of the highlights.
758 The highlights created by `org-preview-latex-fragment' always need
759 `C-c C-c' to be removed."
760 :group 'org-sparse-trees
761 :group 'org-time
762 :type 'boolean)
765 (defcustom org-occur-hook '(org-first-headline-recenter)
766 "Hook that is run after `org-occur' has constructed a sparse tree.
767 This can be used to recenter the window to show as much of the structure
768 as possible."
769 :group 'org-sparse-trees
770 :type 'hook)
772 (defgroup org-imenu-and-speedbar nil
773 "Options concerning imenu and speedbar in Org-mode."
774 :tag "Org Imenu and Speedbar"
775 :group 'org-structure)
777 (defcustom org-imenu-depth 2
778 "The maximum level for Imenu access to Org-mode headlines.
779 This also applied for speedbar access."
780 :group 'org-imenu-and-speedbar
781 :type 'number)
783 (defgroup org-table nil
784 "Options concerning tables in Org-mode."
785 :tag "Org Table"
786 :group 'org)
788 (defcustom org-enable-table-editor 'optimized
789 "Non-nil means, lines starting with \"|\" are handled by the table editor.
790 When nil, such lines will be treated like ordinary lines.
792 When equal to the symbol `optimized', the table editor will be optimized to
793 do the following:
794 - Automatic overwrite mode in front of whitespace in table fields.
795 This makes the structure of the table stay in tact as long as the edited
796 field does not exceed the column width.
797 - Minimize the number of realigns. Normally, the table is aligned each time
798 TAB or RET are pressed to move to another field. With optimization this
799 happens only if changes to a field might have changed the column width.
800 Optimization requires replacing the functions `self-insert-command',
801 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
802 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
803 very good at guessing when a re-align will be necessary, but you can always
804 force one with \\[org-ctrl-c-ctrl-c].
806 If you would like to use the optimized version in Org-mode, but the
807 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
809 This variable can be used to turn on and off the table editor during a session,
810 but in order to toggle optimization, a restart is required.
812 See also the variable `org-table-auto-blank-field'."
813 :group 'org-table
814 :type '(choice
815 (const :tag "off" nil)
816 (const :tag "on" t)
817 (const :tag "on, optimized" optimized)))
819 (defcustom org-table-tab-recognizes-table.el t
820 "Non-nil means, TAB will automatically notice a table.el table.
821 When it sees such a table, it moves point into it and - if necessary -
822 calls `table-recognize-table'."
823 :group 'org-table-editing
824 :type 'boolean)
826 (defgroup org-link nil
827 "Options concerning links in Org-mode."
828 :tag "Org Link"
829 :group 'org)
831 (defvar org-link-abbrev-alist-local nil
832 "Buffer-local version of `org-link-abbrev-alist', which see.
833 The value of this is taken from the #+LINK lines.")
834 (make-variable-buffer-local 'org-link-abbrev-alist-local)
836 (defcustom org-link-abbrev-alist nil
837 "Alist of link abbreviations.
838 The car of each element is a string, to be replaced at the start of a link.
839 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
840 links in Org-mode buffers can have an optional tag after a double colon, e.g.
842 [[linkkey:tag][description]]
844 If REPLACE is a string, the tag will simply be appended to create the link.
845 If the string contains \"%s\", the tag will be inserted there.
847 REPLACE may also be a function that will be called with the tag as the
848 only argument to create the link, which should be returned as a string.
850 See the manual for examples."
851 :group 'org-link
852 :type 'alist)
854 (defcustom org-descriptive-links t
855 "Non-nil means, hide link part and only show description of bracket links.
856 Bracket links are like [[link][descritpion]]. This variable sets the initial
857 state in new org-mode buffers. The setting can then be toggled on a
858 per-buffer basis from the Org->Hyperlinks menu."
859 :group 'org-link
860 :type 'boolean)
862 (defcustom org-link-file-path-type 'adaptive
863 "How the path name in file links should be stored.
864 Valid values are:
866 relative Relative to the current directory, i.e. the directory of the file
867 into which the link is being inserted.
868 absolute Absolute path, if possible with ~ for home directory.
869 noabbrev Absolute path, no abbreviation of home directory.
870 adaptive Use relative path for files in the current directory and sub-
871 directories of it. For other files, use an absolute path."
872 :group 'org-link
873 :type '(choice
874 (const relative)
875 (const absolute)
876 (const noabbrev)
877 (const adaptive)))
879 (defcustom org-activate-links '(bracket angle plain radio tag date)
880 "Types of links that should be activated in Org-mode files.
881 This is a list of symbols, each leading to the activation of a certain link
882 type. In principle, it does not hurt to turn on most link types - there may
883 be a small gain when turning off unused link types. The types are:
885 bracket The recommended [[link][description]] or [[link]] links with hiding.
886 angular Links in angular brackes that may contain whitespace like
887 <bbdb:Carsten Dominik>.
888 plain Plain links in normal text, no whitespace, like http://google.com.
889 radio Text that is matched by a radio target, see manual for details.
890 tag Tag settings in a headline (link to tag search).
891 date Time stamps (link to calendar).
893 Changing this variable requires a restart of Emacs to become effective."
894 :group 'org-link
895 :type '(set (const :tag "Double bracket links (new style)" bracket)
896 (const :tag "Angular bracket links (old style)" angular)
897 (const :tag "Plain text links" plain)
898 (const :tag "Radio target matches" radio)
899 (const :tag "Tags" tag)
900 (const :tag "Timestamps" date)))
902 (defcustom org-make-link-description-function nil
903 "Function to use to generate link descriptions from links. If
904 nil the link location will be used. This function must take two
905 parameters; the first is the link and the second the description
906 org-insert-link has generated, and should return the description
907 to use."
908 :group 'org-link
909 :type 'function)
911 (defgroup org-link-store nil
912 "Options concerning storing links in Org-mode."
913 :tag "Org Store Link"
914 :group 'org-link)
916 (defcustom org-email-link-description-format "Email %c: %.30s"
917 "Format of the description part of a link to an email or usenet message.
918 The following %-excapes will be replaced by corresponding information:
920 %F full \"From\" field
921 %f name, taken from \"From\" field, address if no name
922 %T full \"To\" field
923 %t first name in \"To\" field, address if no name
924 %c correspondent. Unually \"from NAME\", but if you sent it yourself, it
925 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
926 %s subject
927 %m message-id.
929 You may use normal field width specification between the % and the letter.
930 This is for example useful to limit the length of the subject.
932 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
933 :group 'org-link-store
934 :type 'string)
936 (defcustom org-from-is-user-regexp
937 (let (r1 r2)
938 (when (and user-mail-address (not (string= user-mail-address "")))
939 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
940 (when (and user-full-name (not (string= user-full-name "")))
941 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
942 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
943 "Regexp mached against the \"From:\" header of an email or usenet message.
944 It should match if the message is from the user him/herself."
945 :group 'org-link-store
946 :type 'regexp)
948 (defcustom org-context-in-file-links t
949 "Non-nil means, file links from `org-store-link' contain context.
950 A search string will be added to the file name with :: as separator and
951 used to find the context when the link is activated by the command
952 `org-open-at-point'.
953 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
954 negates this setting for the duration of the command."
955 :group 'org-link-store
956 :type 'boolean)
958 (defcustom org-keep-stored-link-after-insertion nil
959 "Non-nil means, keep link in list for entire session.
961 The command `org-store-link' adds a link pointing to the current
962 location to an internal list. These links accumulate during a session.
963 The command `org-insert-link' can be used to insert links into any
964 Org-mode file (offering completion for all stored links). When this
965 option is nil, every link which has been inserted once using \\[org-insert-link]
966 will be removed from the list, to make completing the unused links
967 more efficient."
968 :group 'org-link-store
969 :type 'boolean)
971 (defgroup org-link-follow nil
972 "Options concerning following links in Org-mode."
973 :tag "Org Follow Link"
974 :group 'org-link)
976 (defcustom org-follow-link-hook nil
977 "Hook that is run after a link has been followed."
978 :group 'org-link-follow
979 :type 'hook)
981 (defcustom org-tab-follows-link nil
982 "Non-nil means, on links TAB will follow the link.
983 Needs to be set before org.el is loaded."
984 :group 'org-link-follow
985 :type 'boolean)
987 (defcustom org-return-follows-link nil
988 "Non-nil means, on links RET will follow the link.
989 Needs to be set before org.el is loaded."
990 :group 'org-link-follow
991 :type 'boolean)
993 (defcustom org-mouse-1-follows-link
994 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
995 "Non-nil means, mouse-1 on a link will follow the link.
996 A longer mouse click will still set point. Does not work on XEmacs.
997 Needs to be set before org.el is loaded."
998 :group 'org-link-follow
999 :type 'boolean)
1001 (defcustom org-mark-ring-length 4
1002 "Number of different positions to be recorded in the ring
1003 Changing this requires a restart of Emacs to work correctly."
1004 :group 'org-link-follow
1005 :type 'interger)
1007 (defcustom org-link-frame-setup
1008 '((vm . vm-visit-folder-other-frame)
1009 (gnus . gnus-other-frame)
1010 (file . find-file-other-window))
1011 "Setup the frame configuration for following links.
1012 When following a link with Emacs, it may often be useful to display
1013 this link in another window or frame. This variable can be used to
1014 set this up for the different types of links.
1015 For VM, use any of
1016 `vm-visit-folder'
1017 `vm-visit-folder-other-frame'
1018 For Gnus, use any of
1019 `gnus'
1020 `gnus-other-frame'
1021 For FILE, use any of
1022 `find-file'
1023 `find-file-other-window'
1024 `find-file-other-frame'
1025 For the calendar, use the variable `calendar-setup'.
1026 For BBDB, it is currently only possible to display the matches in
1027 another window."
1028 :group 'org-link-follow
1029 :type '(list
1030 (cons (const vm)
1031 (choice
1032 (const vm-visit-folder)
1033 (const vm-visit-folder-other-window)
1034 (const vm-visit-folder-other-frame)))
1035 (cons (const gnus)
1036 (choice
1037 (const gnus)
1038 (const gnus-other-frame)))
1039 (cons (const file)
1040 (choice
1041 (const find-file)
1042 (const find-file-other-window)
1043 (const find-file-other-frame)))))
1045 (defcustom org-display-internal-link-with-indirect-buffer nil
1046 "Non-nil means, use indirect buffer to display infile links.
1047 Activating internal links (from one location in a file to another location
1048 in the same file) normally just jumps to the location. When the link is
1049 activated with a C-u prefix (or with mouse-3), the link is displayed in
1050 another window. When this option is set, the other window actually displays
1051 an indirect buffer clone of the current buffer, to avoid any visibility
1052 changes to the current buffer."
1053 :group 'org-link-follow
1054 :type 'boolean)
1056 (defcustom org-open-non-existing-files nil
1057 "Non-nil means, `org-open-file' will open non-existing files.
1058 When nil, an error will be generated."
1059 :group 'org-link-follow
1060 :type 'boolean)
1062 (defcustom org-open-directory-means-index-dot-org nil
1063 "Non-nil means, a link to a directory really means to index.org.
1064 When nil, following a directory link will run dired or open a finder/explorer
1065 window on that directory."
1066 :group 'org-link-follow
1067 :type 'boolean)
1069 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1070 "Function and arguments to call for following mailto links.
1071 This is a list with the first element being a lisp function, and the
1072 remaining elements being arguments to the function. In string arguments,
1073 %a will be replaced by the address, and %s will be replaced by the subject
1074 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1075 :group 'org-link-follow
1076 :type '(choice
1077 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1078 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1079 (const :tag "message-mail" (message-mail "%a" "%s"))
1080 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1082 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1083 "Non-nil means, ask for confirmation before executing shell links.
1084 Shell links can be dangerous: just think about a link
1086 [[shell:rm -rf ~/*][Google Search]]
1088 This link would show up in your Org-mode document as \"Google Search\",
1089 but really it would remove your entire home directory.
1090 Therefore we advise against setting this variable to nil.
1091 Just change it to `y-or-n-p' of you want to confirm with a
1092 single keystroke rather than having to type \"yes\"."
1093 :group 'org-link-follow
1094 :type '(choice
1095 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1096 (const :tag "with y-or-n (faster)" y-or-n-p)
1097 (const :tag "no confirmation (dangerous)" nil)))
1099 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1100 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1101 Elisp links can be dangerous: just think about a link
1103 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1105 This link would show up in your Org-mode document as \"Google Search\",
1106 but really it would remove your entire home directory.
1107 Therefore we advise against setting this variable to nil.
1108 Just change it to `y-or-n-p' of you want to confirm with a
1109 single keystroke rather than having to type \"yes\"."
1110 :group 'org-link-follow
1111 :type '(choice
1112 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1113 (const :tag "with y-or-n (faster)" y-or-n-p)
1114 (const :tag "no confirmation (dangerous)" nil)))
1116 (defconst org-file-apps-defaults-gnu
1117 '((remote . emacs)
1118 (t . mailcap))
1119 "Default file applications on a UNIX or GNU/Linux system.
1120 See `org-file-apps'.")
1122 (defconst org-file-apps-defaults-macosx
1123 '((remote . emacs)
1124 (t . "open %s")
1125 ("ps.gz" . "gv %s")
1126 ("eps.gz" . "gv %s")
1127 ("dvi" . "xdvi %s")
1128 ("fig" . "xfig %s"))
1129 "Default file applications on a MacOS X system.
1130 The system \"open\" is known as a default, but we use X11 applications
1131 for some files for which the OS does not have a good default.
1132 See `org-file-apps'.")
1134 (defconst org-file-apps-defaults-windowsnt
1135 (list
1136 '(remote . emacs)
1137 (cons t
1138 (list (if (featurep 'xemacs)
1139 'mswindows-shell-execute
1140 'w32-shell-execute)
1141 "open" 'file)))
1142 "Default file applications on a Windows NT system.
1143 The system \"open\" is used for most files.
1144 See `org-file-apps'.")
1146 (defcustom org-file-apps
1148 (auto-mode . emacs)
1149 ("\\.x?html?\\'" . default)
1150 ("\\.pdf\\'" . default)
1152 "External applications for opening `file:path' items in a document.
1153 Org-mode uses system defaults for different file types, but
1154 you can use this variable to set the application for a given file
1155 extension. The entries in this list are cons cells where the car identifies
1156 files and the cdr the corresponding command. Possible values for the
1157 file identifier are
1158 \"regex\" Regular expression matched against the file name. For backward
1159 compatibility, this can also be a string with only alphanumeric
1160 characters, which is then interpreted as an extension.
1161 `directory' Matches a directory
1162 `remote' Matches a remote file, accessible through tramp or efs.
1163 Remote files most likely should be visited through Emacs
1164 because external applications cannot handle such paths.
1165 `auto-mode' Matches files that are mached by any entry in `auto-mode-alist',
1166 so all files Emacs knows how to handle. Useing this with
1167 command `emacs' will open most files in Emacs. Beware that this
1168 will also open html files insite Emacs, unless you add
1169 (\"html\" . default) to the list as well.
1170 t Default for files not matched by any of the other options.
1172 Possible values for the command are:
1173 `emacs' The file will be visited by the current Emacs process.
1174 `default' Use the default application for this file type, which is the
1175 association for t in the list, most likely in the system-specific
1176 part.
1177 This can be used to overrule an unwanted seting in the
1178 system-specific variable.
1179 string A command to be executed by a shell; %s will be replaced
1180 by the path to the file.
1181 sexp A Lisp form which will be evaluated. The file path will
1182 be available in the Lisp variable `file'.
1183 For more examples, see the system specific constants
1184 `org-file-apps-defaults-macosx'
1185 `org-file-apps-defaults-windowsnt'
1186 `org-file-apps-defaults-gnu'."
1187 :group 'org-link-follow
1188 :type '(repeat
1189 (cons (choice :value ""
1190 (string :tag "Extension")
1191 (const :tag "Default for unrecognized files" t)
1192 (const :tag "Remote file" remote)
1193 (const :tag "Links to a directory" directory)
1194 (const :tag "Any files that have Emacs modes"
1195 auto-mode))
1196 (choice :value ""
1197 (const :tag "Visit with Emacs" emacs)
1198 (const :tag "Use system default" default)
1199 (string :tag "Command")
1200 (sexp :tag "Lisp form")))))
1202 (defgroup org-refile nil
1203 "Options concerning refiling entries in Org-mode."
1204 :tag "Org Remember"
1205 :group 'org)
1207 (defcustom org-directory "~/org"
1208 "Directory with org files.
1209 This directory will be used as default to prompt for org files.
1210 Used by the hooks for remember.el."
1211 :group 'org-refile
1212 :group 'org-remember
1213 :type 'directory)
1215 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1216 "Default target for storing notes.
1217 Used by the hooks for remember.el. This can be a string, or nil to mean
1218 the value of `remember-data-file'.
1219 You can set this on a per-template basis with the variable
1220 `org-remember-templates'."
1221 :group 'org-refile
1222 :group 'org-remember
1223 :type '(choice
1224 (const :tag "Default from remember-data-file" nil)
1225 file))
1227 (defcustom org-goto-interface 'outline
1228 "The default interface to be used for `org-goto'.
1229 Allowed vaues are:
1230 outline The interface shows an outline of the relevant file
1231 and the correct heading is found by moving through
1232 the outline or by searching with incremental search.
1233 outline-path-completion Headlines in the current buffer are offered via
1234 completion."
1235 :group 'org-refile
1236 :type '(choice
1237 (const :tag "Outline" outline)
1238 (const :tag "Outline-path-completion" outline-path-completion)))
1240 (defcustom org-reverse-note-order nil
1241 "Non-nil means, store new notes at the beginning of a file or entry.
1242 When nil, new notes will be filed to the end of a file or entry.
1243 This can also be a list with cons cells of regular expressions that
1244 are matched against file names, and values."
1245 :group 'org-remember
1246 :type '(choice
1247 (const :tag "Reverse always" t)
1248 (const :tag "Reverse never" nil)
1249 (repeat :tag "By file name regexp"
1250 (cons regexp boolean))))
1252 (defcustom org-refile-targets nil
1253 "Targets for refiling entries with \\[org-refile].
1254 This is list of cons cells. Each cell contains:
1255 - a specification of the files to be considered, either a list of files,
1256 or a symbol whose function or variable value will be used to retrieve
1257 a file name or a list of file names. Nil means, refile to a different
1258 heading in the current buffer.
1259 - A specification of how to find candidate refile targets. This may be
1260 any of
1261 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1262 This tag has to be present in all target headlines, inheritance will
1263 not be considered.
1264 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1265 todo keyword.
1266 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1267 headlines that are refiling targets.
1268 - a cons cell (:level . N). Any headline of level N is considered a target.
1269 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1271 When this variable is nil, all top-level headlines in the current buffer
1272 are used, equivalent to the vlaue `((nil . (:level . 1))'."
1273 :group 'org-remember
1274 :type '(repeat
1275 (cons
1276 (choice :value org-agenda-files
1277 (const :tag "All agenda files" org-agenda-files)
1278 (const :tag "Current buffer" nil)
1279 (function) (variable) (file))
1280 (choice :tag "Identify target headline by"
1281 (cons :tag "Specific tag" (const :tag) (string))
1282 (cons :tag "TODO keyword" (const :todo) (string))
1283 (cons :tag "Regular expression" (const :regexp) (regexp))
1284 (cons :tag "Level number" (const :level) (integer))
1285 (cons :tag "Max Level number" (const :maxlevel) (integer))))))
1287 (defcustom org-refile-use-outline-path nil
1288 "Non-nil means, provide refile targets as paths.
1289 So a level 3 headline will be available as level1/level2/level3.
1290 When the value is `file', also include the file name (without directory)
1291 into the path. When `full-file-path', include the full file path."
1292 :group 'org-remember
1293 :type '(choice
1294 (const :tag "Not" nil)
1295 (const :tag "Yes" t)
1296 (const :tag "Start with file name" file)
1297 (const :tag "Start with full file path" full-file-path)))
1299 (defgroup org-todo nil
1300 "Options concerning TODO items in Org-mode."
1301 :tag "Org TODO"
1302 :group 'org)
1304 (defgroup org-progress nil
1305 "Options concerning Progress logging in Org-mode."
1306 :tag "Org Progress"
1307 :group 'org-time)
1309 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1310 "List of TODO entry keyword sequences and their interpretation.
1311 \\<org-mode-map>This is a list of sequences.
1313 Each sequence starts with a symbol, either `sequence' or `type',
1314 indicating if the keywords should be interpreted as a sequence of
1315 action steps, or as different types of TODO items. The first
1316 keywords are states requiring action - these states will select a headline
1317 for inclusion into the global TODO list Org-mode produces. If one of
1318 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1319 signify that no further action is necessary. If \"|\" is not found,
1320 the last keyword is treated as the only DONE state of the sequence.
1322 The command \\[org-todo] cycles an entry through these states, and one
1323 additional state where no keyword is present. For details about this
1324 cycling, see the manual.
1326 TODO keywords and interpretation can also be set on a per-file basis with
1327 the special #+SEQ_TODO and #+TYP_TODO lines.
1329 Each keyword can optionally specify a character for fast state selection
1330 \(in combination with the variable `org-use-fast-todo-selection')
1331 and specifiers for state change logging, using the same syntax
1332 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1333 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1334 indicates to record a time stamp each time this state is selected.
1336 Each keyword may also specify if a timestamp or a note should be
1337 recorded when entering or leaving the state, by adding additional
1338 characters in the parenthesis after the keyword. This looks like this:
1339 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1340 record only the time of the state change. With X and Y being either
1341 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1342 Y when leaving the state if and only if the *target* state does not
1343 define X. You may omit any of the fast-selection key or X or /Y,
1344 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1346 For backward compatibility, this variable may also be just a list
1347 of keywords - in this case the interptetation (sequence or type) will be
1348 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1349 :group 'org-todo
1350 :group 'org-keywords
1351 :type '(choice
1352 (repeat :tag "Old syntax, just keywords"
1353 (string :tag "Keyword"))
1354 (repeat :tag "New syntax"
1355 (cons
1356 (choice
1357 :tag "Interpretation"
1358 (const :tag "Sequence (cycling hits every state)" sequence)
1359 (const :tag "Type (cycling directly to DONE)" type))
1360 (repeat
1361 (string :tag "Keyword"))))))
1363 (defvar org-todo-keywords-1 nil
1364 "All TODO and DONE keywords active in a buffer.")
1365 (make-variable-buffer-local 'org-todo-keywords-1)
1366 (defvar org-todo-keywords-for-agenda nil)
1367 (defvar org-done-keywords-for-agenda nil)
1368 (defvar org-todo-keyword-alist-for-agenda nil)
1369 (defvar org-tag-alist-for-agenda nil)
1370 (defvar org-agenda-contributing-files nil)
1371 (defvar org-not-done-keywords nil)
1372 (make-variable-buffer-local 'org-not-done-keywords)
1373 (defvar org-done-keywords nil)
1374 (make-variable-buffer-local 'org-done-keywords)
1375 (defvar org-todo-heads nil)
1376 (make-variable-buffer-local 'org-todo-heads)
1377 (defvar org-todo-sets nil)
1378 (make-variable-buffer-local 'org-todo-sets)
1379 (defvar org-todo-log-states nil)
1380 (make-variable-buffer-local 'org-todo-log-states)
1381 (defvar org-todo-kwd-alist nil)
1382 (make-variable-buffer-local 'org-todo-kwd-alist)
1383 (defvar org-todo-key-alist nil)
1384 (make-variable-buffer-local 'org-todo-key-alist)
1385 (defvar org-todo-key-trigger nil)
1386 (make-variable-buffer-local 'org-todo-key-trigger)
1388 (defcustom org-todo-interpretation 'sequence
1389 "Controls how TODO keywords are interpreted.
1390 This variable is in principle obsolete and is only used for
1391 backward compatibility, if the interpretation of todo keywords is
1392 not given already in `org-todo-keywords'. See that variable for
1393 more information."
1394 :group 'org-todo
1395 :group 'org-keywords
1396 :type '(choice (const sequence)
1397 (const type)))
1399 (defcustom org-use-fast-todo-selection 'prefix
1400 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1401 This variable describes if and under what circumstances the cycling
1402 mechanism for TODO keywords will be replaced by a single-key, direct
1403 selection scheme.
1405 When nil, fast selection is never used.
1407 When the symbol `prefix', it will be used when `org-todo' is called with
1408 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1409 in an agenda buffer.
1411 When t, fast selection is used by default. In this case, the prefix
1412 argument forces cycling instead.
1414 In all cases, the special interface is only used if access keys have actually
1415 been assigned by the user, i.e. if keywords in the configuration are followed
1416 by a letter in parenthesis, like TODO(t)."
1417 :group 'org-todo
1418 :type '(choice
1419 (const :tag "Never" nil)
1420 (const :tag "By default" t)
1421 (const :tag "Only with C-u C-c C-t" prefix)))
1423 (defcustom org-provide-todo-statistics t
1424 "Non-nil means, update todo statistics after insert and toggle.
1425 When this is set, todo statistics is updated in the parent of the current
1426 entry each time a todo state is changed."
1427 :group 'org-todo
1428 :type 'boolean)
1430 (defcustom org-after-todo-state-change-hook nil
1431 "Hook which is run after the state of a TODO item was changed.
1432 The new state (a string with a TODO keyword, or nil) is available in the
1433 Lisp variable `state'."
1434 :group 'org-todo
1435 :type 'hook)
1437 (defcustom org-todo-state-tags-triggers nil
1438 "Tag changes that should be triggered by TODO state changes.
1439 This is a list. Each entry is
1441 (state-change (tag . flag) .......)
1443 State-change can be a string with a state, and empty string to indicate the
1444 state that has no TODO keyword, or it can be one of the symbols `todo'
1445 or `done', meaning any not-done or done state, respectively."
1446 :group 'org-todo
1447 :group 'org-tags
1448 :type '(repeat
1449 (cons (choice :tag "When changing to"
1450 (const :tag "Not-done state" todo)
1451 (const :tag "Done state" done)
1452 (string :tag "State"))
1453 (repeat
1454 (cons :tag "Tag action"
1455 (string :tag "Tag")
1456 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1458 (defcustom org-log-done nil
1459 "Non-nil means, record a CLOSED timestamp when moving an entry to DONE.
1460 When equal to the list (done), also prompt for a closing note.
1461 This can also be configured on a per-file basis by adding one of
1462 the following lines anywhere in the buffer:
1464 #+STARTUP: logdone
1465 #+STARTUP: lognotedone
1466 #+STARTUP: nologdone"
1467 :group 'org-todo
1468 :group 'org-progress
1469 :type '(choice
1470 (const :tag "No logging" nil)
1471 (const :tag "Record CLOSED timestamp" time)
1472 (const :tag "Record CLOSED timestamp with closing note." note)))
1474 ;; Normalize old uses of org-log-done.
1475 (cond
1476 ((eq org-log-done t) (setq org-log-done 'time))
1477 ((and (listp org-log-done) (memq 'done org-log-done))
1478 (setq org-log-done 'note)))
1480 (defcustom org-log-note-clock-out nil
1481 "Non-nil means, record a note when clocking out of an item.
1482 This can also be configured on a per-file basis by adding one of
1483 the following lines anywhere in the buffer:
1485 #+STARTUP: lognoteclock-out
1486 #+STARTUP: nolognoteclock-out"
1487 :group 'org-todo
1488 :group 'org-progress
1489 :type 'boolean)
1491 (defcustom org-log-done-with-time t
1492 "Non-nil means, the CLOSED time stamp will contain date and time.
1493 When nil, only the date will be recorded."
1494 :group 'org-progress
1495 :type 'boolean)
1497 (defcustom org-log-note-headings
1498 '((done . "CLOSING NOTE %t")
1499 (state . "State %-12s %t")
1500 (note . "Note taken on %t")
1501 (clock-out . ""))
1502 "Headings for notes added to entries.
1503 The value is an alist, with the car being a symbol indicating the note
1504 context, and the cdr is the heading to be used. The heading may also be the
1505 empty string.
1506 %t in the heading will be replaced by a time stamp.
1507 %s will be replaced by the new TODO state, in double quotes.
1508 %u will be replaced by the user name.
1509 %U will be replaced by the full user name."
1510 :group 'org-todo
1511 :group 'org-progress
1512 :type '(list :greedy t
1513 (cons (const :tag "Heading when closing an item" done) string)
1514 (cons (const :tag
1515 "Heading when changing todo state (todo sequence only)"
1516 state) string)
1517 (cons (const :tag "Heading when just taking a note" note) string)
1518 (cons (const :tag "Heading when clocking out" clock-out) string)))
1520 (unless (assq 'note org-log-note-headings)
1521 (push '(note . "%t") org-log-note-headings))
1523 (defcustom org-log-state-notes-insert-after-drawers nil
1524 "Non-nil means, insert state change notes after any drawers in entry.
1525 Only the drawers that *immediately* follow the headline and the
1526 deadline/scheduled line are skipped.
1527 When nil, insert notes right after the heading and perhaps the line
1528 with deadline/scheduling if present."
1529 :group 'org-todo
1530 :group 'org-progress
1531 :type 'boolean)
1533 (defcustom org-log-states-order-reversed t
1534 "Non-nil means, the latest state change note will be directly after heading.
1535 When nil, the notes will be orderer according to time."
1536 :group 'org-todo
1537 :group 'org-progress
1538 :type 'boolean)
1540 (defcustom org-log-repeat 'time
1541 "Non-nil means, record moving through the DONE state when triggering repeat.
1542 An auto-repeating tasks is immediately switched back to TODO when marked
1543 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1544 the TODO keyword definition, or recording a closing note by setting
1545 `org-log-done', there will be no record of the task moving through DONE.
1546 This variable forces taking a note anyway. Possible values are:
1548 nil Don't force a record
1549 time Record a time stamp
1550 note Record a note
1552 This option can also be set with on a per-file-basis with
1554 #+STARTUP: logrepeat
1555 #+STARTUP: lognoterepeat
1556 #+STARTUP: nologrepeat
1558 You can have local logging settings for a subtree by setting the LOGGING
1559 property to one or more of these keywords."
1560 :group 'org-todo
1561 :group 'org-progress
1562 :type '(choice
1563 (const :tag "Don't force a record" nil)
1564 (const :tag "Force recording the DONE state" time)
1565 (const :tag "Force recording a note with the DONE state" note)))
1568 (defgroup org-priorities nil
1569 "Priorities in Org-mode."
1570 :tag "Org Priorities"
1571 :group 'org-todo)
1573 (defcustom org-highest-priority ?A
1574 "The highest priority of TODO items. A character like ?A, ?B etc.
1575 Must have a smaller ASCII number than `org-lowest-priority'."
1576 :group 'org-priorities
1577 :type 'character)
1579 (defcustom org-lowest-priority ?C
1580 "The lowest priority of TODO items. A character like ?A, ?B etc.
1581 Must have a larger ASCII number than `org-highest-priority'."
1582 :group 'org-priorities
1583 :type 'character)
1585 (defcustom org-default-priority ?B
1586 "The default priority of TODO items.
1587 This is the priority an item get if no explicit priority is given."
1588 :group 'org-priorities
1589 :type 'character)
1591 (defcustom org-priority-start-cycle-with-default t
1592 "Non-nil means, start with default priority when starting to cycle.
1593 When this is nil, the first step in the cycle will be (depending on the
1594 command used) one higher or lower that the default priority."
1595 :group 'org-priorities
1596 :type 'boolean)
1598 (defgroup org-time nil
1599 "Options concerning time stamps and deadlines in Org-mode."
1600 :tag "Org Time"
1601 :group 'org)
1603 (defcustom org-insert-labeled-timestamps-at-point nil
1604 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1605 When nil, these labeled time stamps are forces into the second line of an
1606 entry, just after the headline. When scheduling from the global TODO list,
1607 the time stamp will always be forced into the second line."
1608 :group 'org-time
1609 :type 'boolean)
1611 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1612 "Formats for `format-time-string' which are used for time stamps.
1613 It is not recommended to change this constant.")
1615 (defcustom org-time-stamp-rounding-minutes '(0 5)
1616 "Number of minutes to round time stamps to.
1617 These are two values, the first applies when first creating a time stamp.
1618 The second applies when changing it with the commands `S-up' and `S-down'.
1619 When changing the time stamp, this means that it will change in steps
1620 of N minutes, as given by the second value.
1622 When a setting is 0 or 1, insert the time unmodified. Useful rounding
1623 numbers should be factors of 60, so for example 5, 10, 15.
1625 When this is larger than 1, you can still force an exact time-stamp by using
1626 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
1627 and by using a prefix arg to `S-up/down' to specify the exact number
1628 of minutes to shift."
1629 :group 'org-time
1630 :get '(lambda (var) ; Make sure all entries have 5 elements
1631 (if (integerp (default-value var))
1632 (list (default-value var) 5)
1633 (default-value var)))
1634 :type '(list
1635 (integer :tag "when inserting times")
1636 (integer :tag "when modifying times")))
1638 ;; Normalize old customizations of this variable.
1639 (when (integerp org-time-stamp-rounding-minutes)
1640 (setq org-time-stamp-rounding-minutes
1641 (list org-time-stamp-rounding-minutes
1642 org-time-stamp-rounding-minutes)))
1644 (defcustom org-display-custom-times nil
1645 "Non-nil means, overlay custom formats over all time stamps.
1646 The formats are defined through the variable `org-time-stamp-custom-formats'.
1647 To turn this on on a per-file basis, insert anywhere in the file:
1648 #+STARTUP: customtime"
1649 :group 'org-time
1650 :set 'set-default
1651 :type 'sexp)
1652 (make-variable-buffer-local 'org-display-custom-times)
1654 (defcustom org-time-stamp-custom-formats
1655 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1656 "Custom formats for time stamps. See `format-time-string' for the syntax.
1657 These are overlayed over the default ISO format if the variable
1658 `org-display-custom-times' is set. Time like %H:%M should be at the
1659 end of the second format."
1660 :group 'org-time
1661 :type 'sexp)
1663 (defun org-time-stamp-format (&optional long inactive)
1664 "Get the right format for a time string."
1665 (let ((f (if long (cdr org-time-stamp-formats)
1666 (car org-time-stamp-formats))))
1667 (if inactive
1668 (concat "[" (substring f 1 -1) "]")
1669 f)))
1671 (defcustom org-time-clocksum-format "%d:%02d"
1672 "The format string used when creating CLOCKSUM lines, or when
1673 org-mode generates a time duration."
1674 :group 'org-time
1675 :type 'string)
1677 (defcustom org-deadline-warning-days 14
1678 "No. of days before expiration during which a deadline becomes active.
1679 This variable governs the display in sparse trees and in the agenda.
1680 When 0 or negative, it means use this number (the absolute value of it)
1681 even if a deadline has a different individual lead time specified."
1682 :group 'org-time
1683 :group 'org-agenda-daily/weekly
1684 :type 'number)
1686 (defcustom org-read-date-prefer-future t
1687 "Non-nil means, assume future for incomplete date input from user.
1688 This affects the following situations:
1689 1. The user gives a day, but no month.
1690 For example, if today is the 15th, and you enter \"3\", Org-mode will
1691 read this as the third of *next* month. However, if you enter \"17\",
1692 it will be considered as *this* month.
1693 2. The user gives a month but not a year.
1694 For example, if it is april and you enter \"feb 2\", this will be read
1695 as feb 2, *next* year. \"May 5\", however, will be this year.
1697 Currently this does not work for ISO week specifications.
1699 When this option is nil, the current month and year will always be used
1700 as defaults."
1701 :group 'org-time
1702 :type 'boolean)
1704 (defcustom org-read-date-display-live t
1705 "Non-nil means, display current interpretation of date prompt live.
1706 This display will be in an overlay, in the minibuffer."
1707 :group 'org-time
1708 :type 'boolean)
1710 (defcustom org-read-date-popup-calendar t
1711 "Non-nil means, pop up a calendar when prompting for a date.
1712 In the calendar, the date can be selected with mouse-1. However, the
1713 minibuffer will also be active, and you can simply enter the date as well.
1714 When nil, only the minibuffer will be available."
1715 :group 'org-time
1716 :type 'boolean)
1717 (if (fboundp 'defvaralias)
1718 (defvaralias 'org-popup-calendar-for-date-prompt
1719 'org-read-date-popup-calendar))
1721 (defcustom org-extend-today-until 0
1722 "The hour when your day really ends. Must be an integer.
1723 This has influence for the following applications:
1724 - When switching the agenda to \"today\". It it is still earlier than
1725 the time given here, the day recognized as TODAY is actually yesterday.
1726 - When a date is read from the user and it is still before the time given
1727 here, the current date and time will be assumed to be yesterday, 23:59.
1728 Also, timestamps inserted in remember templates follow this rule.
1730 IMPORTANT: This is a feature whose implementation is and likely will
1731 remain incomplete. Really, it is only here because past midnight seems to
1732 be the favorite working time of John Wiegley :-)"
1733 :group 'org-time
1734 :type 'number)
1736 (defcustom org-edit-timestamp-down-means-later nil
1737 "Non-nil means, S-down will increase the time in a time stamp.
1738 When nil, S-up will increase."
1739 :group 'org-time
1740 :type 'boolean)
1742 (defcustom org-calendar-follow-timestamp-change t
1743 "Non-nil means, make the calendar window follow timestamp changes.
1744 When a timestamp is modified and the calendar window is visible, it will be
1745 moved to the new date."
1746 :group 'org-time
1747 :type 'boolean)
1749 (defgroup org-tags nil
1750 "Options concerning tags in Org-mode."
1751 :tag "Org Tags"
1752 :group 'org)
1754 (defcustom org-tag-alist nil
1755 "List of tags allowed in Org-mode files.
1756 When this list is nil, Org-mode will base TAG input on what is already in the
1757 buffer.
1758 The value of this variable is an alist, the car of each entry must be a
1759 keyword as a string, the cdr may be a character that is used to select
1760 that tag through the fast-tag-selection interface.
1761 See the manual for details."
1762 :group 'org-tags
1763 :type '(repeat
1764 (choice
1765 (cons (string :tag "Tag name")
1766 (character :tag "Access char"))
1767 (const :tag "Start radio group" (:startgroup))
1768 (const :tag "End radio group" (:endgroup)))))
1770 (defvar org-file-tags nil
1771 "List of tags that can be inherited by all entries in the file.
1772 The tags will be inherited if the variable `org-use-tag-inheritance'
1773 says they should be.
1774 This variable is populated from #+TAG lines.")
1776 (defcustom org-use-fast-tag-selection 'auto
1777 "Non-nil means, use fast tag selection scheme.
1778 This is a special interface to select and deselect tags with single keys.
1779 When nil, fast selection is never used.
1780 When the symbol `auto', fast selection is used if and only if selection
1781 characters for tags have been configured, either through the variable
1782 `org-tag-alist' or through a #+TAGS line in the buffer.
1783 When t, fast selection is always used and selection keys are assigned
1784 automatically if necessary."
1785 :group 'org-tags
1786 :type '(choice
1787 (const :tag "Always" t)
1788 (const :tag "Never" nil)
1789 (const :tag "When selection characters are configured" 'auto)))
1791 (defcustom org-fast-tag-selection-single-key nil
1792 "Non-nil means, fast tag selection exits after first change.
1793 When nil, you have to press RET to exit it.
1794 During fast tag selection, you can toggle this flag with `C-c'.
1795 This variable can also have the value `expert'. In this case, the window
1796 displaying the tags menu is not even shown, until you press C-c again."
1797 :group 'org-tags
1798 :type '(choice
1799 (const :tag "No" nil)
1800 (const :tag "Yes" t)
1801 (const :tag "Expert" expert)))
1803 (defvar org-fast-tag-selection-include-todo nil
1804 "Non-nil means, fast tags selection interface will also offer TODO states.
1805 This is an undocumented feature, you should not rely on it.")
1807 (defcustom org-tags-column (if (featurep 'xemacs) -79 -80)
1808 "The column to which tags should be indented in a headline.
1809 If this number is positive, it specifies the column. If it is negative,
1810 it means that the tags should be flushright to that column. For example,
1811 -80 works well for a normal 80 character screen."
1812 :group 'org-tags
1813 :type 'integer)
1815 (defcustom org-auto-align-tags t
1816 "Non-nil means, realign tags after pro/demotion of TODO state change.
1817 These operations change the length of a headline and therefore shift
1818 the tags around. With this options turned on, after each such operation
1819 the tags are again aligned to `org-tags-column'."
1820 :group 'org-tags
1821 :type 'boolean)
1823 (defcustom org-use-tag-inheritance t
1824 "Non-nil means, tags in levels apply also for sublevels.
1825 When nil, only the tags directly given in a specific line apply there.
1826 If this option is t, a match early-on in a tree can lead to a large
1827 number of matches in the subtree. If you only want to see the first
1828 match in a tree during a search, check out the variable
1829 `org-tags-match-list-sublevels'.
1831 This may also be a list of tags that should be inherited, or a regexp that
1832 matches tags that should be inherited."
1833 :group 'org-tags
1834 :type '(choice
1835 (const :tag "Not" nil)
1836 (const :tag "Always" t)
1837 (repeat :tag "Specific tags" (string :tag "Tag"))
1838 (regexp :tag "Tags matched by regexp")))
1840 (defun org-tag-inherit-p (tag)
1841 "Check if TAG is one that should be inherited."
1842 (cond
1843 ((eq org-use-tag-inheritance t) t)
1844 ((not org-use-tag-inheritance) nil)
1845 ((stringp org-use-tag-inheritance)
1846 (string-match org-use-tag-inheritance tag))
1847 ((listp org-use-tag-inheritance)
1848 (member tag org-use-tag-inheritance))
1849 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
1851 (defcustom org-tags-match-list-sublevels t
1852 "Non-nil means list also sublevels of headlines matching tag search.
1853 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1854 the sublevels of a headline matching a tag search often also match
1855 the same search. Listing all of them can create very long lists.
1856 Setting this variable to nil causes subtrees of a match to be skipped.
1857 This option is off by default, because inheritance in on. If you turn
1858 inheritance off, you very likely want to turn this option on.
1860 As a special case, if the tag search is restricted to TODO items, the
1861 value of this variable is ignored and sublevels are always checked, to
1862 make sure all corresponding TODO items find their way into the list."
1863 :group 'org-tags
1864 :type 'boolean)
1866 (defvar org-tags-history nil
1867 "History of minibuffer reads for tags.")
1868 (defvar org-last-tags-completion-table nil
1869 "The last used completion table for tags.")
1870 (defvar org-after-tags-change-hook nil
1871 "Hook that is run after the tags in a line have changed.")
1873 (defgroup org-properties nil
1874 "Options concerning properties in Org-mode."
1875 :tag "Org Properties"
1876 :group 'org)
1878 (defcustom org-property-format "%-10s %s"
1879 "How property key/value pairs should be formatted by `indent-line'.
1880 When `indent-line' hits a property definition, it will format the line
1881 according to this format, mainly to make sure that the values are
1882 lined-up with respect to each other."
1883 :group 'org-properties
1884 :type 'string)
1886 (defcustom org-use-property-inheritance nil
1887 "Non-nil means, properties apply also for sublevels.
1889 This setting is chiefly used during property searches. Turning it on can
1890 cause significant overhead when doing a search, which is why it is not
1891 on by default.
1893 When nil, only the properties directly given in the current entry count.
1894 When t, every property is inherited. The value may also be a list of
1895 properties that should have inheritance, or a regular expression matching
1896 properties that should be inherited.
1898 However, note that some special properties use inheritance under special
1899 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
1900 and the properties ending in \"_ALL\" when they are used as descriptor
1901 for valid values of a property.
1903 Note for programmers:
1904 When querying an entry with `org-entry-get', you can control if inheritance
1905 should be used. By default, `org-entry-get' looks only at the local
1906 properties. You can request inheritance by setting the inherit argument
1907 to t (to force inheritance) or to `selective' (to respect the setting
1908 in this variable)."
1909 :group 'org-properties
1910 :type '(choice
1911 (const :tag "Not" nil)
1912 (const :tag "Always" t)
1913 (repeat :tag "Specific properties" (string :tag "Property"))
1914 (regexp :tag "Properties matched by regexp")))
1916 (defun org-property-inherit-p (property)
1917 "Check if PROPERTY is one that should be inherited."
1918 (cond
1919 ((eq org-use-property-inheritance t) t)
1920 ((not org-use-property-inheritance) nil)
1921 ((stringp org-use-property-inheritance)
1922 (string-match org-use-property-inheritance property))
1923 ((listp org-use-property-inheritance)
1924 (member property org-use-property-inheritance))
1925 (t (error "Invalid setting of `org-use-property-inheritance'"))))
1927 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
1928 "The default column format, if no other format has been defined.
1929 This variable can be set on the per-file basis by inserting a line
1931 #+COLUMNS: %25ITEM ....."
1932 :group 'org-properties
1933 :type 'string)
1935 (defcustom org-columns-ellipses ".."
1936 "The ellipses to be used when a field in column view is truncated.
1937 When this is the empty string, as many characters as possible are shown,
1938 but then there will be no visual indication that the field has been truncated.
1939 When this is a string of length N, the last N characters of a truncated
1940 field are replaced by this string. If the column is narrower than the
1941 ellipses string, only part of the ellipses string will be shown."
1942 :group 'org-properties
1943 :type 'string)
1945 (defcustom org-columns-modify-value-for-display-function nil
1946 "Function that modifies values for display in column view.
1947 For example, it can be used to cut out a certain part from a time stamp.
1948 The function must take 2 argments:
1950 column-title The tite of the column (*not* the property name)
1951 value The value that should be modified.
1953 The function should return the value that should be displayed,
1954 or nil if the normal value should be used."
1955 :group 'org-properties
1956 :type 'function)
1958 (defcustom org-effort-property "Effort"
1959 "The property that is being used to keep track of effort estimates.
1960 Effort estimates given in this property need to have the format H:MM."
1961 :group 'org-properties
1962 :group 'org-progress
1963 :type '(string :tag "Property"))
1965 (defconst org-global-properties-fixed
1966 '(("VISIBILITY_ALL" . "folded children content all"))
1967 "List of property/value pairs that can be inherited by any entry.
1968 These are fixed values, for the preset properties.")
1971 (defcustom org-global-properties nil
1972 "List of property/value pairs that can be inherited by any entry.
1973 You can set buffer-local values for this by adding lines like
1975 #+PROPERTY: NAME VALUE"
1976 :group 'org-properties
1977 :type '(repeat
1978 (cons (string :tag "Property")
1979 (string :tag "Value"))))
1981 (defvar org-file-properties nil
1982 "List of property/value pairs that can be inherited by any entry.
1983 Valid for the current buffer.
1984 This variable is populated from #+PROPERTY lines.")
1985 (make-variable-buffer-local 'org-file-properties)
1987 (defgroup org-agenda nil
1988 "Options concerning agenda views in Org-mode."
1989 :tag "Org Agenda"
1990 :group 'org)
1992 (defvar org-category nil
1993 "Variable used by org files to set a category for agenda display.
1994 Such files should use a file variable to set it, for example
1996 # -*- mode: org; org-category: \"ELisp\"
1998 or contain a special line
2000 #+CATEGORY: ELisp
2002 If the file does not specify a category, then file's base name
2003 is used instead.")
2004 (make-variable-buffer-local 'org-category)
2005 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2007 (defcustom org-agenda-files nil
2008 "The files to be used for agenda display.
2009 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2010 \\[org-remove-file]. You can also use customize to edit the list.
2012 If an entry is a directory, all files in that directory that are matched by
2013 `org-agenda-file-regexp' will be part of the file list.
2015 If the value of the variable is not a list but a single file name, then
2016 the list of agenda files is actually stored and maintained in that file, one
2017 agenda file per line."
2018 :group 'org-agenda
2019 :type '(choice
2020 (repeat :tag "List of files and directories" file)
2021 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2023 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2024 "Regular expression to match files for `org-agenda-files'.
2025 If any element in the list in that variable contains a directory instead
2026 of a normal file, all files in that directory that are matched by this
2027 regular expression will be included."
2028 :group 'org-agenda
2029 :type 'regexp)
2031 (defcustom org-agenda-text-search-extra-files nil
2032 "List of extra files to be searched by text search commands.
2033 These files will be search in addition to the agenda files by the
2034 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2035 Note that these files will only be searched for text search commands,
2036 not for the other agenda views like todo lists, tag searches or the weekly
2037 agenda. This variable is intended to list notes and possibly archive files
2038 that should also be searched by these two commands.
2039 In fact, if the first element in the list is the symbol `agenda-archives',
2040 than all archive files of all agenda files will be added to the search
2041 scope."
2042 :group 'org-agenda
2043 :type '(set :greedy t
2044 (const :tag "Agenda Archives" agenda-archives)
2045 (repeat :inline t (file))))
2047 (if (fboundp 'defvaralias)
2048 (defvaralias 'org-agenda-multi-occur-extra-files
2049 'org-agenda-text-search-extra-files))
2051 (defcustom org-agenda-skip-unavailable-files nil
2052 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2053 A nil value means to remove them, after a query, from the list."
2054 :group 'org-agenda
2055 :type 'boolean)
2057 (defcustom org-calendar-to-agenda-key [?c]
2058 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2059 The command `org-calendar-goto-agenda' will be bound to this key. The
2060 default is the character `c' because then `c' can be used to switch back and
2061 forth between agenda and calendar."
2062 :group 'org-agenda
2063 :type 'sexp)
2065 (defcustom org-calendar-agenda-action-key [?k]
2066 "The key to be installed in `calendar-mode-map' for agenda-action.
2067 The command `org-agenda-action' will be bound to this key. The
2068 default is the character `k' because we use the same key in the agenda."
2069 :group 'org-agenda
2070 :type 'sexp)
2072 (eval-after-load "calendar"
2073 '(progn
2074 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2075 'org-calendar-goto-agenda)
2076 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2077 'org-agenda-action)))
2079 (defgroup org-latex nil
2080 "Options for embedding LaTeX code into Org-mode."
2081 :tag "Org LaTeX"
2082 :group 'org)
2084 (defcustom org-format-latex-options
2085 '(:foreground default :background default :scale 1.0
2086 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2087 :matchers ("begin" "$" "$$" "\\(" "\\["))
2088 "Options for creating images from LaTeX fragments.
2089 This is a property list with the following properties:
2090 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2091 `default' means use the foreground of the default face.
2092 :background the background color, or \"Transparent\".
2093 `default' means use the background of the default face.
2094 :scale a scaling factor for the size of the images.
2095 :html-foreground, :html-background, :html-scale
2096 the same numbers for HTML export.
2097 :matchers a list indicating which matchers should be used to
2098 find LaTeX fragments. Valid members of this list are:
2099 \"begin\" find environments
2100 \"$\" find math expressions surrounded by $...$
2101 \"$$\" find math expressions surrounded by $$....$$
2102 \"\\(\" find math expressions surrounded by \\(...\\)
2103 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2104 :group 'org-latex
2105 :type 'plist)
2107 (defcustom org-format-latex-header "\\documentclass{article}
2108 \\usepackage{fullpage} % do not remove
2109 \\usepackage{amssymb}
2110 \\usepackage[usenames]{color}
2111 \\usepackage{amsmath}
2112 \\usepackage{latexsym}
2113 \\usepackage[mathscr]{eucal}
2114 \\pagestyle{empty} % do not remove"
2115 "The document header used for processing LaTeX fragments."
2116 :group 'org-latex
2117 :type 'string)
2120 (defgroup org-font-lock nil
2121 "Font-lock settings for highlighting in Org-mode."
2122 :tag "Org Font Lock"
2123 :group 'org)
2125 (defcustom org-level-color-stars-only nil
2126 "Non-nil means fontify only the stars in each headline.
2127 When nil, the entire headline is fontified.
2128 Changing it requires restart of `font-lock-mode' to become effective
2129 also in regions already fontified."
2130 :group 'org-font-lock
2131 :type 'boolean)
2133 (defcustom org-hide-leading-stars nil
2134 "Non-nil means, hide the first N-1 stars in a headline.
2135 This works by using the face `org-hide' for these stars. This
2136 face is white for a light background, and black for a dark
2137 background. You may have to customize the face `org-hide' to
2138 make this work.
2139 Changing it requires restart of `font-lock-mode' to become effective
2140 also in regions already fontified.
2141 You may also set this on a per-file basis by adding one of the following
2142 lines to the buffer:
2144 #+STARTUP: hidestars
2145 #+STARTUP: showstars"
2146 :group 'org-font-lock
2147 :type 'boolean)
2149 (defcustom org-fontify-done-headline nil
2150 "Non-nil means, change the face of a headline if it is marked DONE.
2151 Normally, only the TODO/DONE keyword indicates the state of a headline.
2152 When this is non-nil, the headline after the keyword is set to the
2153 `org-headline-done' as an additional indication."
2154 :group 'org-font-lock
2155 :type 'boolean)
2157 (defcustom org-fontify-emphasized-text t
2158 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2159 Changing this variable requires a restart of Emacs to take effect."
2160 :group 'org-font-lock
2161 :type 'boolean)
2163 (defcustom org-highlight-latex-fragments-and-specials nil
2164 "Non-nil means, fontify what is treated specially by the exporters."
2165 :group 'org-font-lock
2166 :type 'boolean)
2168 (defcustom org-hide-emphasis-markers nil
2169 "Non-nil mean font-lock should hide the emphasis marker characters."
2170 :group 'org-font-lock
2171 :type 'boolean)
2173 (defvar org-emph-re nil
2174 "Regular expression for matching emphasis.")
2175 (defvar org-verbatim-re nil
2176 "Regular expression for matching verbatim text.")
2177 (defvar org-emphasis-regexp-components) ; defined just below
2178 (defvar org-emphasis-alist) ; defined just below
2179 (defun org-set-emph-re (var val)
2180 "Set variable and compute the emphasis regular expression."
2181 (set var val)
2182 (when (and (boundp 'org-emphasis-alist)
2183 (boundp 'org-emphasis-regexp-components)
2184 org-emphasis-alist org-emphasis-regexp-components)
2185 (let* ((e org-emphasis-regexp-components)
2186 (pre (car e))
2187 (post (nth 1 e))
2188 (border (nth 2 e))
2189 (body (nth 3 e))
2190 (nl (nth 4 e))
2191 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
2192 (body1 (concat body "*?"))
2193 (markers (mapconcat 'car org-emphasis-alist ""))
2194 (vmarkers (mapconcat
2195 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2196 org-emphasis-alist "")))
2197 ;; make sure special characters appear at the right position in the class
2198 (if (string-match "\\^" markers)
2199 (setq markers (concat (replace-match "" t t markers) "^")))
2200 (if (string-match "-" markers)
2201 (setq markers (concat (replace-match "" t t markers) "-")))
2202 (if (string-match "\\^" vmarkers)
2203 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2204 (if (string-match "-" vmarkers)
2205 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2206 (if (> nl 0)
2207 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2208 (int-to-string nl) "\\}")))
2209 ;; Make the regexp
2210 (setq org-emph-re
2211 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
2212 "\\("
2213 "\\([" markers "]\\)"
2214 "\\("
2215 "[^" border "]\\|"
2216 "[^" border (if (and nil stacked) markers) "]"
2217 body1
2218 "[^" border (if (and nil stacked) markers) "]"
2219 "\\)"
2220 "\\3\\)"
2221 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
2222 (setq org-verbatim-re
2223 (concat "\\([" pre "]\\|^\\)"
2224 "\\("
2225 "\\([" vmarkers "]\\)"
2226 "\\("
2227 "[^" border "]\\|"
2228 "[^" border "]"
2229 body1
2230 "[^" border "]"
2231 "\\)"
2232 "\\3\\)"
2233 "\\([" post "]\\|$\\)")))))
2235 (defcustom org-emphasis-regexp-components
2236 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
2237 "Components used to build the regular expression for emphasis.
2238 This is a list with 6 entries. Terminology: In an emphasis string
2239 like \" *strong word* \", we call the initial space PREMATCH, the final
2240 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2241 and \"trong wor\" is the body. The different components in this variable
2242 specify what is allowed/forbidden in each part:
2244 pre Chars allowed as prematch. Beginning of line will be allowed too.
2245 post Chars allowed as postmatch. End of line will be allowed too.
2246 border The chars *forbidden* as border characters.
2247 body-regexp A regexp like \".\" to match a body character. Don't use
2248 non-shy groups here, and don't allow newline here.
2249 newline The maximum number of newlines allowed in an emphasis exp.
2251 Use customize to modify this, or restart Emacs after changing it."
2252 :group 'org-font-lock
2253 :set 'org-set-emph-re
2254 :type '(list
2255 (sexp :tag "Allowed chars in pre ")
2256 (sexp :tag "Allowed chars in post ")
2257 (sexp :tag "Forbidden chars in border ")
2258 (sexp :tag "Regexp for body ")
2259 (integer :tag "number of newlines allowed")
2260 (option (boolean :tag "Please ignore this button"))))
2262 (defcustom org-emphasis-alist
2263 `(("*" bold "<b>" "</b>")
2264 ("/" italic "<i>" "</i>")
2265 ("_" underline "<u>" "</u>")
2266 ("=" org-code "<code>" "</code>" verbatim)
2267 ("~" org-verbatim "" "" verbatim)
2268 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2269 "<del>" "</del>")
2271 "Special syntax for emphasized text.
2272 Text starting and ending with a special character will be emphasized, for
2273 example *bold*, _underlined_ and /italic/. This variable sets the marker
2274 characters, the face to be used by font-lock for highlighting in Org-mode
2275 Emacs buffers, and the HTML tags to be used for this.
2276 Use customize to modify this, or restart Emacs after changing it."
2277 :group 'org-font-lock
2278 :set 'org-set-emph-re
2279 :type '(repeat
2280 (list
2281 (string :tag "Marker character")
2282 (choice
2283 (face :tag "Font-lock-face")
2284 (plist :tag "Face property list"))
2285 (string :tag "HTML start tag")
2286 (string :tag "HTML end tag")
2287 (option (const verbatim)))))
2289 ;;; Miscellaneous options
2291 (defgroup org-completion nil
2292 "Completion in Org-mode."
2293 :tag "Org Completion"
2294 :group 'org)
2296 (defcustom org-completion-fallback-command 'hippie-expand
2297 "The expansion command called by \\[org-complete] in normal context.
2298 Normal means, no org-mode-specific context."
2299 :group 'org-completion
2300 :type 'function)
2302 ;;; Functions and variables from ther packages
2303 ;; Declared here to avoid compiler warnings
2305 ;; XEmacs only
2306 (defvar outline-mode-menu-heading)
2307 (defvar outline-mode-menu-show)
2308 (defvar outline-mode-menu-hide)
2309 (defvar zmacs-regions) ; XEmacs regions
2311 ;; Emacs only
2312 (defvar mark-active)
2314 ;; Various packages
2315 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2316 (declare-function calendar-forward-day "cal-move" (arg))
2317 (declare-function calendar-goto-date "cal-move" (date))
2318 (declare-function calendar-goto-today "cal-move" ())
2319 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2320 (defvar calc-embedded-close-formula)
2321 (defvar calc-embedded-open-formula)
2322 (declare-function cdlatex-tab "ext:cdlatex" ())
2323 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2324 (defvar font-lock-unfontify-region-function)
2325 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2326 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2327 (defvar iswitchb-temp-buflist)
2328 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2329 (declare-function org-agenda-skip "org-agenda" ())
2330 (declare-function org-format-agenda-item "org-agenda"
2331 (extra txt &optional category tags dotime noprefix remove-re))
2332 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2333 (declare-function org-agenda-change-all-lines "org-agenda"
2334 (newhead hdmarker &optional fixface))
2335 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2336 (declare-function org-agenda-maybe-redo "org-agenda" ())
2337 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2338 (beg end))
2339 (declare-function parse-time-string "parse-time" (string))
2340 (declare-function remember "remember" (&optional initial))
2341 (declare-function remember-buffer-desc "remember" ())
2342 (declare-function remember-finalize "remember" ())
2343 (defvar remember-save-after-remembering)
2344 (defvar remember-data-file)
2345 (defvar remember-register)
2346 (defvar remember-buffer)
2347 (defvar remember-handler-functions)
2348 (defvar remember-annotation-functions)
2349 (defvar texmathp-why)
2350 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2351 (declare-function table--at-cell-p "table" (position &optional object at-column))
2353 (defvar w3m-current-url)
2354 (defvar w3m-current-title)
2356 (defvar org-latex-regexps)
2358 ;;; Autoload and prepare some org modules
2360 ;; Some table stuff that needs to be defined here, because it is used
2361 ;; by the functions setting up org-mode or checking for table context.
2363 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2364 "Detects an org-type or table-type table.")
2365 (defconst org-table-line-regexp "^[ \t]*|"
2366 "Detects an org-type table line.")
2367 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2368 "Detects an org-type table line.")
2369 (defconst org-table-hline-regexp "^[ \t]*|-"
2370 "Detects an org-type table hline.")
2371 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2372 "Detects a table-type table hline.")
2373 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2374 "Searching from within a table (any type) this finds the first line
2375 outside the table.")
2377 ;; Autoload the functions in org-table.el that are needed by functions here.
2379 (eval-and-compile
2380 (org-autoload "org-table"
2381 '(org-table-align org-table-begin org-table-blank-field
2382 org-table-convert org-table-convert-region org-table-copy-down
2383 org-table-copy-region org-table-create
2384 org-table-create-or-convert-from-region
2385 org-table-create-with-table.el org-table-current-dline
2386 org-table-cut-region org-table-delete-column org-table-edit-field
2387 org-table-edit-formulas org-table-end org-table-eval-formula
2388 org-table-export org-table-field-info
2389 org-table-get-stored-formulas org-table-goto-column
2390 org-table-hline-and-move org-table-import org-table-insert-column
2391 org-table-insert-hline org-table-insert-row org-table-iterate
2392 org-table-justify-field-maybe org-table-kill-row
2393 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2394 org-table-move-column org-table-move-column-left
2395 org-table-move-column-right org-table-move-row
2396 org-table-move-row-down org-table-move-row-up
2397 org-table-next-field org-table-next-row org-table-paste-rectangle
2398 org-table-previous-field org-table-recalculate
2399 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2400 org-table-toggle-coordinate-overlays
2401 org-table-toggle-formula-debugger org-table-wrap-region
2402 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
2404 (defun org-at-table-p (&optional table-type)
2405 "Return t if the cursor is inside an org-type table.
2406 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2407 (if org-enable-table-editor
2408 (save-excursion
2409 (beginning-of-line 1)
2410 (looking-at (if table-type org-table-any-line-regexp
2411 org-table-line-regexp)))
2412 nil))
2413 (defsubst org-table-p () (org-at-table-p))
2415 (defun org-at-table.el-p ()
2416 "Return t if and only if we are at a table.el table."
2417 (and (org-at-table-p 'any)
2418 (save-excursion
2419 (goto-char (org-table-begin 'any))
2420 (looking-at org-table1-hline-regexp))))
2421 (defun org-table-recognize-table.el ()
2422 "If there is a table.el table nearby, recognize it and move into it."
2423 (if org-table-tab-recognizes-table.el
2424 (if (org-at-table.el-p)
2425 (progn
2426 (beginning-of-line 1)
2427 (if (looking-at org-table-dataline-regexp)
2429 (if (looking-at org-table1-hline-regexp)
2430 (progn
2431 (beginning-of-line 2)
2432 (if (looking-at org-table-any-border-regexp)
2433 (beginning-of-line -1)))))
2434 (if (re-search-forward "|" (org-table-end t) t)
2435 (progn
2436 (require 'table)
2437 (if (table--at-cell-p (point))
2439 (message "recognizing table.el table...")
2440 (table-recognize-table)
2441 (message "recognizing table.el table...done")))
2442 (error "This should not happen..."))
2444 nil)
2445 nil))
2447 (defun org-at-table-hline-p ()
2448 "Return t if the cursor is inside a hline in a table."
2449 (if org-enable-table-editor
2450 (save-excursion
2451 (beginning-of-line 1)
2452 (looking-at org-table-hline-regexp))
2453 nil))
2455 (defvar org-table-clean-did-remove-column nil)
2457 (defun org-table-map-tables (function)
2458 "Apply FUNCTION to the start of all tables in the buffer."
2459 (save-excursion
2460 (save-restriction
2461 (widen)
2462 (goto-char (point-min))
2463 (while (re-search-forward org-table-any-line-regexp nil t)
2464 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2465 (beginning-of-line 1)
2466 (if (looking-at org-table-line-regexp)
2467 (save-excursion (funcall function)))
2468 (re-search-forward org-table-any-border-regexp nil 1))))
2469 (message "Mapping tables: done"))
2471 ;; Declare and autoload functions from org-exp.el
2473 (declare-function org-default-export-plist "org-exp")
2474 (declare-function org-infile-export-plist "org-exp")
2475 (declare-function org-get-current-options "org-exp")
2476 (eval-and-compile
2477 (org-autoload "org-exp"
2478 '(org-export org-export-as-ascii org-export-visible
2479 org-insert-export-options-template org-export-as-html-and-open
2480 org-export-as-html-batch org-export-as-html-to-buffer
2481 org-replace-region-by-html org-export-region-as-html
2482 org-export-as-html org-export-icalendar-this-file
2483 org-export-icalendar-all-agenda-files
2484 org-table-clean-before-export
2485 org-export-icalendar-combine-agenda-files org-export-as-xoxo)))
2487 ;; Declare and autoload functions from org-agenda.el
2489 (eval-and-compile
2490 (org-autoload "org-agenda"
2491 '(org-agenda org-agenda-list org-search-view
2492 org-todo-list org-tags-view org-agenda-list-stuck-projects
2493 org-diary org-agenda-to-appt)))
2495 ;; Autoload org-remember
2497 (eval-and-compile
2498 (org-autoload "org-remember"
2499 '(org-remember-insinuate org-remember-annotation
2500 org-remember-apply-template org-remember org-remember-handler)))
2502 ;; Autoload org-clock.el
2505 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
2506 (beg end))
2507 (declare-function org-update-mode-line "org-clock" ())
2508 (defvar org-clock-start-time)
2509 (defvar org-clock-marker (make-marker)
2510 "Marker recording the last clock-in.")
2512 (eval-and-compile
2513 (org-autoload
2514 "org-clock"
2515 '(org-clock-in org-clock-out org-clock-cancel
2516 org-clock-goto org-clock-sum org-clock-display
2517 org-remove-clock-overlays org-clock-report
2518 org-clocktable-shift org-dblock-write:clocktable
2519 org-get-clocktable)))
2521 (defun org-clock-update-time-maybe ()
2522 "If this is a CLOCK line, update it and return t.
2523 Otherwise, return nil."
2524 (interactive)
2525 (save-excursion
2526 (beginning-of-line 1)
2527 (skip-chars-forward " \t")
2528 (when (looking-at org-clock-string)
2529 (let ((re (concat "[ \t]*" org-clock-string
2530 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
2531 "\\([ \t]*=>.*\\)?\\)?"))
2532 ts te h m s neg)
2533 (cond
2534 ((not (looking-at re))
2535 nil)
2536 ((not (match-end 2))
2537 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2538 (> org-clock-marker (point))
2539 (<= org-clock-marker (point-at-eol)))
2540 ;; The clock is running here
2541 (setq org-clock-start-time
2542 (apply 'encode-time
2543 (org-parse-time-string (match-string 1))))
2544 (org-update-mode-line)))
2546 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
2547 (end-of-line 1)
2548 (setq ts (match-string 1)
2549 te (match-string 3))
2550 (setq s (- (time-to-seconds
2551 (apply 'encode-time (org-parse-time-string te)))
2552 (time-to-seconds
2553 (apply 'encode-time (org-parse-time-string ts))))
2554 neg (< s 0)
2555 s (abs s)
2556 h (floor (/ s 3600))
2557 s (- s (* 3600 h))
2558 m (floor (/ s 60))
2559 s (- s (* 60 s)))
2560 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
2561 t))))))
2563 (defun org-check-running-clock ()
2564 "Check if the current buffer contains the running clock.
2565 If yes, offer to stop it and to save the buffer with the changes."
2566 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2567 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
2568 (buffer-name))))
2569 (org-clock-out)
2570 (when (y-or-n-p "Save changed buffer?")
2571 (save-buffer))))
2573 (defun org-clocktable-try-shift (dir n)
2574 "Check if this line starts a clock table, if yes, shift the time block."
2575 (when (org-match-line "#\\+BEGIN: clocktable\\>")
2576 (org-clocktable-shift dir n)))
2578 ;; Autoload archiving code
2579 ;; The stuff that is needed for cycling and tags has to be defined here.
2581 (defgroup org-archive nil
2582 "Options concerning archiving in Org-mode."
2583 :tag "Org Archive"
2584 :group 'org-structure)
2586 (defcustom org-archive-location "%s_archive::"
2587 "The location where subtrees should be archived.
2589 Otherwise, the value of this variable is a string, consisting of two
2590 parts, separated by a double-colon.
2592 The first part is a file name - when omitted, archiving happens in the same
2593 file. %s will be replaced by the current file name (without directory part).
2594 Archiving to a different file is useful to keep archived entries from
2595 contributing to the Org-mode Agenda.
2597 The part after the double colon is a headline. The archived entries will be
2598 filed under that headline. When omitted, the subtrees are simply filed away
2599 at the end of the file, as top-level entries.
2601 Here are a few examples:
2602 \"%s_archive::\"
2603 If the current file is Projects.org, archive in file
2604 Projects.org_archive, as top-level trees. This is the default.
2606 \"::* Archived Tasks\"
2607 Archive in the current file, under the top-level headline
2608 \"* Archived Tasks\".
2610 \"~/org/archive.org::\"
2611 Archive in file ~/org/archive.org (absolute path), as top-level trees.
2613 \"basement::** Finished Tasks\"
2614 Archive in file ./basement (relative path), as level 3 trees
2615 below the level 2 heading \"** Finished Tasks\".
2617 You may set this option on a per-file basis by adding to the buffer a
2618 line like
2620 #+ARCHIVE: basement::** Finished Tasks
2622 You may also define it locally for a subtree by setting an ARCHIVE property
2623 in the entry. If such a property is found in an entry, or anywhere up
2624 the hierarchy, it will be used."
2625 :group 'org-archive
2626 :type 'string)
2628 (defcustom org-archive-tag "ARCHIVE"
2629 "The tag that marks a subtree as archived.
2630 An archived subtree does not open during visibility cycling, and does
2631 not contribute to the agenda listings.
2632 After changing this, font-lock must be restarted in the relevant buffers to
2633 get the proper fontification."
2634 :group 'org-archive
2635 :group 'org-keywords
2636 :type 'string)
2638 (defcustom org-agenda-skip-archived-trees t
2639 "Non-nil means, the agenda will skip any items located in archived trees.
2640 An archived tree is a tree marked with the tag ARCHIVE. The use of this
2641 variable is no longer recommended, you should leave it at the value t.
2642 Instead, use the key `v' to cycle the archives-mode in the agenda."
2643 :group 'org-archive
2644 :group 'org-agenda-skip
2645 :type 'boolean)
2647 (defcustom org-cycle-open-archived-trees nil
2648 "Non-nil means, `org-cycle' will open archived trees.
2649 An archived tree is a tree marked with the tag ARCHIVE.
2650 When nil, archived trees will stay folded. You can still open them with
2651 normal outline commands like `show-all', but not with the cycling commands."
2652 :group 'org-archive
2653 :group 'org-cycle
2654 :type 'boolean)
2656 (defcustom org-sparse-tree-open-archived-trees nil
2657 "Non-nil means sparse tree construction shows matches in archived trees.
2658 When nil, matches in these trees are highlighted, but the trees are kept in
2659 collapsed state."
2660 :group 'org-archive
2661 :group 'org-sparse-trees
2662 :type 'boolean)
2664 (defun org-cycle-hide-archived-subtrees (state)
2665 "Re-hide all archived subtrees after a visibility state change."
2666 (when (and (not org-cycle-open-archived-trees)
2667 (not (memq state '(overview folded))))
2668 (save-excursion
2669 (let* ((globalp (memq state '(contents all)))
2670 (beg (if globalp (point-min) (point)))
2671 (end (if globalp (point-max) (org-end-of-subtree t))))
2672 (org-hide-archived-subtrees beg end)
2673 (goto-char beg)
2674 (if (looking-at (concat ".*:" org-archive-tag ":"))
2675 (message "%s" (substitute-command-keys
2676 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
2678 (defun org-force-cycle-archived ()
2679 "Cycle subtree even if it is archived."
2680 (interactive)
2681 (setq this-command 'org-cycle)
2682 (let ((org-cycle-open-archived-trees t))
2683 (call-interactively 'org-cycle)))
2685 (defun org-hide-archived-subtrees (beg end)
2686 "Re-hide all archived subtrees after a visibility state change."
2687 (save-excursion
2688 (let* ((re (concat ":" org-archive-tag ":")))
2689 (goto-char beg)
2690 (while (re-search-forward re end t)
2691 (and (org-on-heading-p) (hide-subtree))
2692 (org-end-of-subtree t)))))
2694 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
2696 (eval-and-compile
2697 (org-autoload "org-archive"
2698 '(org-add-archive-files org-archive-subtree
2699 org-archive-to-archive-sibling org-toggle-archive-tag)))
2701 ;; Autoload Column View Code
2703 (declare-function org-columns-number-to-string "org-colview")
2704 (declare-function org-columns-get-format-and-top-level "org-colview")
2705 (declare-function org-columns-compute "org-colview")
2707 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
2708 '(org-columns-number-to-string org-columns-get-format-and-top-level
2709 org-columns-compute org-agenda-columns org-columns-remove-overlays
2710 org-columns org-insert-columns-dblock org-dblock-write:columnview))
2712 ;; Autoload ID code
2714 (org-autoload "org-id"
2715 '(org-id-get-create org-id-new org-id-copy org-id-get
2716 org-id-get-with-outline-path-completion
2717 org-id-get-with-outline-drilling
2718 org-id-goto org-id-find))
2720 ;;; Variables for pre-computed regular expressions, all buffer local
2722 (defvar org-drawer-regexp nil
2723 "Matches first line of a hidden block.")
2724 (make-variable-buffer-local 'org-drawer-regexp)
2725 (defvar org-todo-regexp nil
2726 "Matches any of the TODO state keywords.")
2727 (make-variable-buffer-local 'org-todo-regexp)
2728 (defvar org-not-done-regexp nil
2729 "Matches any of the TODO state keywords except the last one.")
2730 (make-variable-buffer-local 'org-not-done-regexp)
2731 (defvar org-todo-line-regexp nil
2732 "Matches a headline and puts TODO state into group 2 if present.")
2733 (make-variable-buffer-local 'org-todo-line-regexp)
2734 (defvar org-complex-heading-regexp nil
2735 "Matches a headline and puts everything into groups:
2736 group 1: the stars
2737 group 2: The todo keyword, maybe
2738 group 3: Priority cookie
2739 group 4: True headline
2740 group 5: Tags")
2741 (make-variable-buffer-local 'org-complex-heading-regexp)
2742 (defvar org-todo-line-tags-regexp nil
2743 "Matches a headline and puts TODO state into group 2 if present.
2744 Also put tags into group 4 if tags are present.")
2745 (make-variable-buffer-local 'org-todo-line-tags-regexp)
2746 (defvar org-nl-done-regexp nil
2747 "Matches newline followed by a headline with the DONE keyword.")
2748 (make-variable-buffer-local 'org-nl-done-regexp)
2749 (defvar org-looking-at-done-regexp nil
2750 "Matches the DONE keyword a point.")
2751 (make-variable-buffer-local 'org-looking-at-done-regexp)
2752 (defvar org-ds-keyword-length 12
2753 "Maximum length of the Deadline and SCHEDULED keywords.")
2754 (make-variable-buffer-local 'org-ds-keyword-length)
2755 (defvar org-deadline-regexp nil
2756 "Matches the DEADLINE keyword.")
2757 (make-variable-buffer-local 'org-deadline-regexp)
2758 (defvar org-deadline-time-regexp nil
2759 "Matches the DEADLINE keyword together with a time stamp.")
2760 (make-variable-buffer-local 'org-deadline-time-regexp)
2761 (defvar org-deadline-line-regexp nil
2762 "Matches the DEADLINE keyword and the rest of the line.")
2763 (make-variable-buffer-local 'org-deadline-line-regexp)
2764 (defvar org-scheduled-regexp nil
2765 "Matches the SCHEDULED keyword.")
2766 (make-variable-buffer-local 'org-scheduled-regexp)
2767 (defvar org-scheduled-time-regexp nil
2768 "Matches the SCHEDULED keyword together with a time stamp.")
2769 (make-variable-buffer-local 'org-scheduled-time-regexp)
2770 (defvar org-closed-time-regexp nil
2771 "Matches the CLOSED keyword together with a time stamp.")
2772 (make-variable-buffer-local 'org-closed-time-regexp)
2774 (defvar org-keyword-time-regexp nil
2775 "Matches any of the 4 keywords, together with the time stamp.")
2776 (make-variable-buffer-local 'org-keyword-time-regexp)
2777 (defvar org-keyword-time-not-clock-regexp nil
2778 "Matches any of the 3 keywords, together with the time stamp.")
2779 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
2780 (defvar org-maybe-keyword-time-regexp nil
2781 "Matches a timestamp, possibly preceeded by a keyword.")
2782 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
2783 (defvar org-planning-or-clock-line-re nil
2784 "Matches a line with planning or clock info.")
2785 (make-variable-buffer-local 'org-planning-or-clock-line-re)
2787 (defconst org-plain-time-of-day-regexp
2788 (concat
2789 "\\(\\<[012]?[0-9]"
2790 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2791 "\\(--?"
2792 "\\(\\<[012]?[0-9]"
2793 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2794 "\\)?")
2795 "Regular expression to match a plain time or time range.
2796 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2797 groups carry important information:
2798 0 the full match
2799 1 the first time, range or not
2800 8 the second time, if it is a range.")
2802 (defconst org-plain-time-extension-regexp
2803 (concat
2804 "\\(\\<[012]?[0-9]"
2805 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2806 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
2807 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
2808 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2809 groups carry important information:
2810 0 the full match
2811 7 hours of duration
2812 9 minutes of duration")
2814 (defconst org-stamp-time-of-day-regexp
2815 (concat
2816 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
2817 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
2818 "\\(--?"
2819 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
2820 "Regular expression to match a timestamp time or time range.
2821 After a match, the following groups carry important information:
2822 0 the full match
2823 1 date plus weekday, for backreferencing to make sure both times on same day
2824 2 the first time, range or not
2825 4 the second time, if it is a range.")
2827 (defconst org-startup-options
2828 '(("fold" org-startup-folded t)
2829 ("overview" org-startup-folded t)
2830 ("nofold" org-startup-folded nil)
2831 ("showall" org-startup-folded nil)
2832 ("content" org-startup-folded content)
2833 ("hidestars" org-hide-leading-stars t)
2834 ("showstars" org-hide-leading-stars nil)
2835 ("odd" org-odd-levels-only t)
2836 ("oddeven" org-odd-levels-only nil)
2837 ("align" org-startup-align-all-tables t)
2838 ("noalign" org-startup-align-all-tables nil)
2839 ("customtime" org-display-custom-times t)
2840 ("logdone" org-log-done time)
2841 ("lognotedone" org-log-done note)
2842 ("nologdone" org-log-done nil)
2843 ("lognoteclock-out" org-log-note-clock-out t)
2844 ("nolognoteclock-out" org-log-note-clock-out nil)
2845 ("logrepeat" org-log-repeat state)
2846 ("lognoterepeat" org-log-repeat note)
2847 ("nologrepeat" org-log-repeat nil)
2848 ("constcgs" constants-unit-system cgs)
2849 ("constSI" constants-unit-system SI))
2850 "Variable associated with STARTUP options for org-mode.
2851 Each element is a list of three items: The startup options as written
2852 in the #+STARTUP line, the corresponding variable, and the value to
2853 set this variable to if the option is found. An optional forth element PUSH
2854 means to push this value onto the list in the variable.")
2856 (defun org-set-regexps-and-options ()
2857 "Precompute regular expressions for current buffer."
2858 (when (org-mode-p)
2859 (org-set-local 'org-todo-kwd-alist nil)
2860 (org-set-local 'org-todo-key-alist nil)
2861 (org-set-local 'org-todo-key-trigger nil)
2862 (org-set-local 'org-todo-keywords-1 nil)
2863 (org-set-local 'org-done-keywords nil)
2864 (org-set-local 'org-todo-heads nil)
2865 (org-set-local 'org-todo-sets nil)
2866 (org-set-local 'org-todo-log-states nil)
2867 (org-set-local 'org-file-properties nil)
2868 (org-set-local 'org-file-tags nil)
2869 (let ((re (org-make-options-regexp
2870 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
2871 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
2872 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")))
2873 (splitre "[ \t]+")
2874 kwds kws0 kwsa key log value cat arch tags const links hw dws
2875 tail sep kws1 prio props ftags drawers
2876 ext-setup-or-nil setup-contents (start 0))
2877 (save-excursion
2878 (save-restriction
2879 (widen)
2880 (goto-char (point-min))
2881 (while (or (and ext-setup-or-nil
2882 (string-match re ext-setup-or-nil start)
2883 (setq start (match-end 0)))
2884 (and (setq ext-setup-or-nil nil start 0)
2885 (re-search-forward re nil t)))
2886 (setq key (upcase (match-string 1 ext-setup-or-nil))
2887 value (org-match-string-no-properties 2 ext-setup-or-nil))
2888 (cond
2889 ((equal key "CATEGORY")
2890 (if (string-match "[ \t]+$" value)
2891 (setq value (replace-match "" t t value)))
2892 (setq cat value))
2893 ((member key '("SEQ_TODO" "TODO"))
2894 (push (cons 'sequence (org-split-string value splitre)) kwds))
2895 ((equal key "TYP_TODO")
2896 (push (cons 'type (org-split-string value splitre)) kwds))
2897 ((equal key "TAGS")
2898 (setq tags (append tags (org-split-string value splitre))))
2899 ((equal key "COLUMNS")
2900 (org-set-local 'org-columns-default-format value))
2901 ((equal key "LINK")
2902 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
2903 (push (cons (match-string 1 value)
2904 (org-trim (match-string 2 value)))
2905 links)))
2906 ((equal key "PRIORITIES")
2907 (setq prio (org-split-string value " +")))
2908 ((equal key "PROPERTY")
2909 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
2910 (push (cons (match-string 1 value) (match-string 2 value))
2911 props)))
2912 ((equal key "FILETAGS")
2913 (when (string-match "\\S-" value)
2914 (setq ftags
2915 (append
2916 ftags
2917 (apply 'append
2918 (mapcar (lambda (x) (org-split-string x ":"))
2919 (org-split-string value)))))))
2920 ((equal key "DRAWERS")
2921 (setq drawers (org-split-string value splitre)))
2922 ((equal key "CONSTANTS")
2923 (setq const (append const (org-split-string value splitre))))
2924 ((equal key "STARTUP")
2925 (let ((opts (org-split-string value splitre))
2926 l var val)
2927 (while (setq l (pop opts))
2928 (when (setq l (assoc l org-startup-options))
2929 (setq var (nth 1 l) val (nth 2 l))
2930 (if (not (nth 3 l))
2931 (set (make-local-variable var) val)
2932 (if (not (listp (symbol-value var)))
2933 (set (make-local-variable var) nil))
2934 (set (make-local-variable var) (symbol-value var))
2935 (add-to-list var val))))))
2936 ((equal key "ARCHIVE")
2937 (string-match " *$" value)
2938 (setq arch (replace-match "" t t value))
2939 (remove-text-properties 0 (length arch)
2940 '(face t fontified t) arch))
2941 ((equal key "SETUPFILE")
2942 (setq setup-contents (org-file-contents
2943 (expand-file-name
2944 (org-remove-double-quotes value))
2945 'noerror))
2946 (if (not ext-setup-or-nil)
2947 (setq ext-setup-or-nil setup-contents start 0)
2948 (setq ext-setup-or-nil
2949 (concat (substring ext-setup-or-nil 0 start)
2950 "\n" setup-contents "\n"
2951 (substring ext-setup-or-nil start)))))
2952 ))))
2953 (when cat
2954 (org-set-local 'org-category (intern cat))
2955 (push (cons "CATEGORY" cat) props))
2956 (when prio
2957 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
2958 (setq prio (mapcar 'string-to-char prio))
2959 (org-set-local 'org-highest-priority (nth 0 prio))
2960 (org-set-local 'org-lowest-priority (nth 1 prio))
2961 (org-set-local 'org-default-priority (nth 2 prio)))
2962 (and props (org-set-local 'org-file-properties (nreverse props)))
2963 (and ftags (org-set-local 'org-file-tags ftags))
2964 (and drawers (org-set-local 'org-drawers drawers))
2965 (and arch (org-set-local 'org-archive-location arch))
2966 (and links (setq org-link-abbrev-alist-local (nreverse links)))
2967 ;; Process the TODO keywords
2968 (unless kwds
2969 ;; Use the global values as if they had been given locally.
2970 (setq kwds (default-value 'org-todo-keywords))
2971 (if (stringp (car kwds))
2972 (setq kwds (list (cons org-todo-interpretation
2973 (default-value 'org-todo-keywords)))))
2974 (setq kwds (reverse kwds)))
2975 (setq kwds (nreverse kwds))
2976 (let (inter kws kw)
2977 (while (setq kws (pop kwds))
2978 (setq inter (pop kws) sep (member "|" kws)
2979 kws0 (delete "|" (copy-sequence kws))
2980 kwsa nil
2981 kws1 (mapcar
2982 (lambda (x)
2983 ;; 1 2
2984 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
2985 (progn
2986 (setq kw (match-string 1 x)
2987 key (and (match-end 2) (match-string 2 x))
2988 log (org-extract-log-state-settings x))
2989 (push (cons kw (and key (string-to-char key))) kwsa)
2990 (and log (push log org-todo-log-states))
2992 (error "Invalid TODO keyword %s" x)))
2993 kws0)
2994 kwsa (if kwsa (append '((:startgroup))
2995 (nreverse kwsa)
2996 '((:endgroup))))
2997 hw (car kws1)
2998 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
2999 tail (list inter hw (car dws) (org-last dws)))
3000 (add-to-list 'org-todo-heads hw 'append)
3001 (push kws1 org-todo-sets)
3002 (setq org-done-keywords (append org-done-keywords dws nil))
3003 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3004 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3005 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3006 (setq org-todo-sets (nreverse org-todo-sets)
3007 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3008 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3009 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3010 ;; Process the constants
3011 (when const
3012 (let (e cst)
3013 (while (setq e (pop const))
3014 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3015 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3016 (setq org-table-formula-constants-local cst)))
3018 ;; Process the tags.
3019 (when tags
3020 (let (e tgs)
3021 (while (setq e (pop tags))
3022 (cond
3023 ((equal e "{") (push '(:startgroup) tgs))
3024 ((equal e "}") (push '(:endgroup) tgs))
3025 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3026 (push (cons (match-string 1 e)
3027 (string-to-char (match-string 2 e)))
3028 tgs))
3029 (t (push (list e) tgs))))
3030 (org-set-local 'org-tag-alist nil)
3031 (while (setq e (pop tgs))
3032 (or (and (stringp (car e))
3033 (assoc (car e) org-tag-alist))
3034 (push e org-tag-alist)))))
3036 ;; Compute the regular expressions and other local variables
3037 (if (not org-done-keywords)
3038 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
3039 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3040 (length org-scheduled-string)
3041 (length org-clock-string)
3042 (length org-closed-string)))
3043 org-drawer-regexp
3044 (concat "^[ \t]*:\\("
3045 (mapconcat 'regexp-quote org-drawers "\\|")
3046 "\\):[ \t]*$")
3047 org-not-done-keywords
3048 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3049 org-todo-regexp
3050 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3051 "\\|") "\\)\\>")
3052 org-not-done-regexp
3053 (concat "\\<\\("
3054 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3055 "\\)\\>")
3056 org-todo-line-regexp
3057 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3058 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3059 "\\)\\>\\)?[ \t]*\\(.*\\)")
3060 org-complex-heading-regexp
3061 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
3062 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3063 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3064 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3065 org-nl-done-regexp
3066 (concat "\n\\*+[ \t]+"
3067 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3068 "\\)" "\\>")
3069 org-todo-line-tags-regexp
3070 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3071 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3072 (org-re
3073 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3074 org-looking-at-done-regexp
3075 (concat "^" "\\(?:"
3076 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3077 "\\>")
3078 org-deadline-regexp (concat "\\<" org-deadline-string)
3079 org-deadline-time-regexp
3080 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3081 org-deadline-line-regexp
3082 (concat "\\<\\(" org-deadline-string "\\).*")
3083 org-scheduled-regexp
3084 (concat "\\<" org-scheduled-string)
3085 org-scheduled-time-regexp
3086 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3087 org-closed-time-regexp
3088 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3089 org-keyword-time-regexp
3090 (concat "\\<\\(" org-scheduled-string
3091 "\\|" org-deadline-string
3092 "\\|" org-closed-string
3093 "\\|" org-clock-string "\\)"
3094 " *[[<]\\([^]>]+\\)[]>]")
3095 org-keyword-time-not-clock-regexp
3096 (concat "\\<\\(" org-scheduled-string
3097 "\\|" org-deadline-string
3098 "\\|" org-closed-string
3099 "\\)"
3100 " *[[<]\\([^]>]+\\)[]>]")
3101 org-maybe-keyword-time-regexp
3102 (concat "\\(\\<\\(" org-scheduled-string
3103 "\\|" org-deadline-string
3104 "\\|" org-closed-string
3105 "\\|" org-clock-string "\\)\\)?"
3106 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3107 org-planning-or-clock-line-re
3108 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3109 "\\|" org-deadline-string
3110 "\\|" org-closed-string "\\|" org-clock-string
3111 "\\)\\>\\)")
3113 (org-compute-latex-and-specials-regexp)
3114 (org-set-font-lock-defaults))))
3116 (defun org-file-contents (file &optional noerror)
3117 "Return the contents of FILE, as a string."
3118 (if (or (not file)
3119 (not (file-readable-p file)))
3120 (if noerror
3121 (progn
3122 (message "Cannot read file %s" file)
3123 (ding) (sit-for 2)
3125 (error "Cannot read file %s" file))
3126 (with-temp-buffer
3127 (insert-file-contents file)
3128 (buffer-string))))
3130 (defun org-extract-log-state-settings (x)
3131 "Extract the log state setting from a TODO keyword string.
3132 This will extract info from a string like \"WAIT(w@/!)\"."
3133 (let (kw key log1 log2)
3134 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3135 (setq kw (match-string 1 x)
3136 key (and (match-end 2) (match-string 2 x))
3137 log1 (and (match-end 3) (match-string 3 x))
3138 log2 (and (match-end 4) (match-string 4 x)))
3139 (and (or log1 log2)
3140 (list kw
3141 (and log1 (if (equal log1 "!") 'time 'note))
3142 (and log2 (if (equal log2 "!") 'time 'note)))))))
3144 (defun org-remove-keyword-keys (list)
3145 "Remove a pair of parenthesis at the end of each string in LIST."
3146 (mapcar (lambda (x)
3147 (if (string-match "(.*)$" x)
3148 (substring x 0 (match-beginning 0))
3150 list))
3152 ;; FIXME: this could be done much better, using second characters etc.
3153 (defun org-assign-fast-keys (alist)
3154 "Assign fast keys to a keyword-key alist.
3155 Respect keys that are already there."
3156 (let (new e k c c1 c2 (char ?a))
3157 (while (setq e (pop alist))
3158 (cond
3159 ((equal e '(:startgroup)) (push e new))
3160 ((equal e '(:endgroup)) (push e new))
3162 (setq k (car e) c2 nil)
3163 (if (cdr e)
3164 (setq c (cdr e))
3165 ;; automatically assign a character.
3166 (setq c1 (string-to-char
3167 (downcase (substring
3168 k (if (= (string-to-char k) ?@) 1 0)))))
3169 (if (or (rassoc c1 new) (rassoc c1 alist))
3170 (while (or (rassoc char new) (rassoc char alist))
3171 (setq char (1+ char)))
3172 (setq c2 c1))
3173 (setq c (or c2 char)))
3174 (push (cons k c) new))))
3175 (nreverse new)))
3177 ;;; Some variables used in various places
3179 (defvar org-window-configuration nil
3180 "Used in various places to store a window configuration.")
3181 (defvar org-finish-function nil
3182 "Function to be called when `C-c C-c' is used.
3183 This is for getting out of special buffers like remember.")
3186 ;; FIXME: Occasionally check by commenting these, to make sure
3187 ;; no other functions uses these, forgetting to let-bind them.
3188 (defvar entry)
3189 (defvar state)
3190 (defvar last-state)
3191 (defvar date)
3192 (defvar description)
3194 ;; Defined somewhere in this file, but used before definition.
3195 (defvar org-html-entities)
3196 (defvar org-struct-menu)
3197 (defvar org-org-menu)
3198 (defvar org-tbl-menu)
3199 (defvar org-agenda-keymap)
3201 ;;;; Define the Org-mode
3203 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3204 (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."))
3207 ;; We use a before-change function to check if a table might need
3208 ;; an update.
3209 (defvar org-table-may-need-update t
3210 "Indicates that a table might need an update.
3211 This variable is set by `org-before-change-function'.
3212 `org-table-align' sets it back to nil.")
3213 (defun org-before-change-function (beg end)
3214 "Every change indicates that a table might need an update."
3215 (setq org-table-may-need-update t))
3216 (defvar org-mode-map)
3217 (defvar org-mode-hook nil)
3218 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3219 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3220 (defvar org-table-buffer-is-an nil)
3221 (defconst org-outline-regexp "\\*+ ")
3223 ;;;###autoload
3224 (define-derived-mode org-mode outline-mode "Org"
3225 "Outline-based notes management and organizer, alias
3226 \"Carsten's outline-mode for keeping track of everything.\"
3228 Org-mode develops organizational tasks around a NOTES file which
3229 contains information about projects as plain text. Org-mode is
3230 implemented on top of outline-mode, which is ideal to keep the content
3231 of large files well structured. It supports ToDo items, deadlines and
3232 time stamps, which magically appear in the diary listing of the Emacs
3233 calendar. Tables are easily created with a built-in table editor.
3234 Plain text URL-like links connect to websites, emails (VM), Usenet
3235 messages (Gnus), BBDB entries, and any files related to the project.
3236 For printing and sharing of notes, an Org-mode file (or a part of it)
3237 can be exported as a structured ASCII or HTML file.
3239 The following commands are available:
3241 \\{org-mode-map}"
3243 ;; Get rid of Outline menus, they are not needed
3244 ;; Need to do this here because define-derived-mode sets up
3245 ;; the keymap so late. Still, it is a waste to call this each time
3246 ;; we switch another buffer into org-mode.
3247 (if (featurep 'xemacs)
3248 (when (boundp 'outline-mode-menu-heading)
3249 ;; Assume this is Greg's port, it used easymenu
3250 (easy-menu-remove outline-mode-menu-heading)
3251 (easy-menu-remove outline-mode-menu-show)
3252 (easy-menu-remove outline-mode-menu-hide))
3253 (define-key org-mode-map [menu-bar headings] 'undefined)
3254 (define-key org-mode-map [menu-bar hide] 'undefined)
3255 (define-key org-mode-map [menu-bar show] 'undefined))
3257 (org-load-modules-maybe)
3258 (easy-menu-add org-org-menu)
3259 (easy-menu-add org-tbl-menu)
3260 (org-install-agenda-files-menu)
3261 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3262 (org-add-to-invisibility-spec '(org-cwidth))
3263 (when (featurep 'xemacs)
3264 (org-set-local 'line-move-ignore-invisible t))
3265 (org-set-local 'outline-regexp org-outline-regexp)
3266 (org-set-local 'outline-level 'org-outline-level)
3267 (when (and org-ellipsis
3268 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3269 (fboundp 'make-glyph-code))
3270 (unless org-display-table
3271 (setq org-display-table (make-display-table)))
3272 (set-display-table-slot
3273 org-display-table 4
3274 (vconcat (mapcar
3275 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3276 org-ellipsis)))
3277 (if (stringp org-ellipsis) org-ellipsis "..."))))
3278 (setq buffer-display-table org-display-table))
3279 (org-set-regexps-and-options)
3280 ;; Calc embedded
3281 (org-set-local 'calc-embedded-open-mode "# ")
3282 (modify-syntax-entry ?# "<")
3283 (modify-syntax-entry ?@ "w")
3284 (if org-startup-truncated (setq truncate-lines t))
3285 (org-set-local 'font-lock-unfontify-region-function
3286 'org-unfontify-region)
3287 ;; Activate before-change-function
3288 (org-set-local 'org-table-may-need-update t)
3289 (org-add-hook 'before-change-functions 'org-before-change-function nil
3290 'local)
3291 ;; Check for running clock before killing a buffer
3292 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3293 ;; Paragraphs and auto-filling
3294 (org-set-autofill-regexps)
3295 (setq indent-line-function 'org-indent-line-function)
3296 (org-update-radio-target-regexp)
3298 ;; Comment characters
3299 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3300 (org-set-local 'comment-padding " ")
3302 ;; Align options lines
3303 (org-set-local
3304 'align-mode-rules-list
3305 '((org-in-buffer-settings
3306 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3307 (modes . '(org-mode)))))
3309 ;; Imenu
3310 (org-set-local 'imenu-create-index-function
3311 'org-imenu-get-tree)
3313 ;; Make isearch reveal context
3314 (if (or (featurep 'xemacs)
3315 (not (boundp 'outline-isearch-open-invisible-function)))
3316 ;; Emacs 21 and XEmacs make use of the hook
3317 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3318 ;; Emacs 22 deals with this through a special variable
3319 (org-set-local 'outline-isearch-open-invisible-function
3320 (lambda (&rest ignore) (org-show-context 'isearch))))
3322 ;; If empty file that did not turn on org-mode automatically, make it to.
3323 (if (and org-insert-mode-line-in-empty-file
3324 (interactive-p)
3325 (= (point-min) (point-max)))
3326 (insert "# -*- mode: org -*-\n\n"))
3328 (unless org-inhibit-startup
3329 (when org-startup-align-all-tables
3330 (let ((bmp (buffer-modified-p)))
3331 (org-table-map-tables 'org-table-align)
3332 (set-buffer-modified-p bmp)))
3333 (org-set-startup-visibility)))
3335 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3337 (defun org-current-time ()
3338 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3339 (if (> (car org-time-stamp-rounding-minutes) 1)
3340 (let ((r (car org-time-stamp-rounding-minutes))
3341 (time (decode-time)))
3342 (apply 'encode-time
3343 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3344 (nthcdr 2 time))))
3345 (current-time)))
3347 ;;;; Font-Lock stuff, including the activators
3349 (defvar org-mouse-map (make-sparse-keymap))
3350 (org-defkey org-mouse-map
3351 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3352 (org-defkey org-mouse-map
3353 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3354 (when org-mouse-1-follows-link
3355 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3356 (when org-tab-follows-link
3357 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3358 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3359 (when org-return-follows-link
3360 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
3361 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
3363 (require 'font-lock)
3365 (defconst org-non-link-chars "]\t\n\r<>")
3366 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3367 "shell" "elisp"))
3368 (defvar org-link-types-re nil
3369 "Matches a link that has a url-like prefix like \"http:\"")
3370 (defvar org-link-re-with-space nil
3371 "Matches a link with spaces, optional angular brackets around it.")
3372 (defvar org-link-re-with-space2 nil
3373 "Matches a link with spaces, optional angular brackets around it.")
3374 (defvar org-angle-link-re nil
3375 "Matches link with angular brackets, spaces are allowed.")
3376 (defvar org-plain-link-re nil
3377 "Matches plain link, without spaces.")
3378 (defvar org-bracket-link-regexp nil
3379 "Matches a link in double brackets.")
3380 (defvar org-bracket-link-analytic-regexp nil
3381 "Regular expression used to analyze links.
3382 Here is what the match groups contain after a match:
3383 1: http:
3384 2: http
3385 3: path
3386 4: [desc]
3387 5: desc")
3388 (defvar org-any-link-re nil
3389 "Regular expression matching any link.")
3391 (defun org-make-link-regexps ()
3392 "Update the link regular expressions.
3393 This should be called after the variable `org-link-types' has changed."
3394 (setq org-link-types-re
3395 (concat
3396 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3397 org-link-re-with-space
3398 (concat
3399 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3400 "\\([^" org-non-link-chars " ]"
3401 "[^" org-non-link-chars "]*"
3402 "[^" org-non-link-chars " ]\\)>?")
3403 org-link-re-with-space2
3404 (concat
3405 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3406 "\\([^" org-non-link-chars " ]"
3407 "[^]\t\n\r]*"
3408 "[^" org-non-link-chars " ]\\)>?")
3409 org-angle-link-re
3410 (concat
3411 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3412 "\\([^" org-non-link-chars " ]"
3413 "[^" org-non-link-chars "]*"
3414 "\\)>")
3415 org-plain-link-re
3416 (concat
3417 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3418 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3419 org-bracket-link-regexp
3420 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3421 org-bracket-link-analytic-regexp
3422 (concat
3423 "\\[\\["
3424 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3425 "\\([^]]+\\)"
3426 "\\]"
3427 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3428 "\\]")
3429 org-any-link-re
3430 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3431 org-angle-link-re "\\)\\|\\("
3432 org-plain-link-re "\\)")))
3434 (org-make-link-regexps)
3436 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
3437 "Regular expression for fast time stamp matching.")
3438 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
3439 "Regular expression for fast time stamp matching.")
3440 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3441 "Regular expression matching time strings for analysis.
3442 This one does not require the space after the date, so it can be used
3443 on a string that terminates immediately after the date.")
3444 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3445 "Regular expression matching time strings for analysis.")
3446 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
3447 "Regular expression matching time stamps, with groups.")
3448 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
3449 "Regular expression matching time stamps (also [..]), with groups.")
3450 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3451 "Regular expression matching a time stamp range.")
3452 (defconst org-tr-regexp-both
3453 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3454 "Regular expression matching a time stamp range.")
3455 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3456 org-ts-regexp "\\)?")
3457 "Regular expression matching a time stamp or time stamp range.")
3458 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3459 org-ts-regexp-both "\\)?")
3460 "Regular expression matching a time stamp or time stamp range.
3461 The time stamps may be either active or inactive.")
3463 (defvar org-emph-face nil)
3465 (defun org-do-emphasis-faces (limit)
3466 "Run through the buffer and add overlays to links."
3467 (let (rtn)
3468 (while (and (not rtn) (re-search-forward org-emph-re limit t))
3469 (if (not (= (char-after (match-beginning 3))
3470 (char-after (match-beginning 4))))
3471 (progn
3472 (setq rtn t)
3473 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3474 'face
3475 (nth 1 (assoc (match-string 3)
3476 org-emphasis-alist)))
3477 (add-text-properties (match-beginning 2) (match-end 2)
3478 '(font-lock-multiline t))
3479 (when org-hide-emphasis-markers
3480 (add-text-properties (match-end 4) (match-beginning 5)
3481 '(invisible org-link))
3482 (add-text-properties (match-beginning 3) (match-end 3)
3483 '(invisible org-link)))))
3484 (backward-char 1))
3485 rtn))
3487 (defun org-emphasize (&optional char)
3488 "Insert or change an emphasis, i.e. a font like bold or italic.
3489 If there is an active region, change that region to a new emphasis.
3490 If there is no region, just insert the marker characters and position
3491 the cursor between them.
3492 CHAR should be either the marker character, or the first character of the
3493 HTML tag associated with that emphasis. If CHAR is a space, the means
3494 to remove the emphasis of the selected region.
3495 If char is not given (for example in an interactive call) it
3496 will be prompted for."
3497 (interactive)
3498 (let ((eal org-emphasis-alist) e det
3499 (erc org-emphasis-regexp-components)
3500 (prompt "")
3501 (string "") beg end move tag c s)
3502 (if (org-region-active-p)
3503 (setq beg (region-beginning) end (region-end)
3504 string (buffer-substring beg end))
3505 (setq move t))
3507 (while (setq e (pop eal))
3508 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
3509 c (aref tag 0))
3510 (push (cons c (string-to-char (car e))) det)
3511 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
3512 (substring tag 1)))))
3513 (unless char
3514 (message "%s" (concat "Emphasis marker or tag:" prompt))
3515 (setq char (read-char-exclusive)))
3516 (setq char (or (cdr (assoc char det)) char))
3517 (if (equal char ?\ )
3518 (setq s "" move nil)
3519 (unless (assoc (char-to-string char) org-emphasis-alist)
3520 (error "No such emphasis marker: \"%c\"" char))
3521 (setq s (char-to-string char)))
3522 (while (and (> (length string) 1)
3523 (equal (substring string 0 1) (substring string -1))
3524 (assoc (substring string 0 1) org-emphasis-alist))
3525 (setq string (substring string 1 -1)))
3526 (setq string (concat s string s))
3527 (if beg (delete-region beg end))
3528 (unless (or (bolp)
3529 (string-match (concat "[" (nth 0 erc) "\n]")
3530 (char-to-string (char-before (point)))))
3531 (insert " "))
3532 (unless (string-match (concat "[" (nth 1 erc) "\n]")
3533 (char-to-string (char-after (point))))
3534 (insert " ") (backward-char 1))
3535 (insert string)
3536 (and move (backward-char 1))))
3538 (defconst org-nonsticky-props
3539 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
3542 (defun org-activate-plain-links (limit)
3543 "Run through the buffer and add overlays to links."
3544 (catch 'exit
3545 (let (f)
3546 (while (re-search-forward org-plain-link-re limit t)
3547 (setq f (get-text-property (match-beginning 0) 'face))
3548 (if (or (eq f 'org-tag)
3549 (and (listp f) (memq 'org-tag f)))
3551 (add-text-properties (match-beginning 0) (match-end 0)
3552 (list 'mouse-face 'highlight
3553 'rear-nonsticky org-nonsticky-props
3554 'keymap org-mouse-map
3556 (throw 'exit t))))))
3558 (defun org-activate-code (limit)
3559 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
3560 (progn
3561 (remove-text-properties (match-beginning 0) (match-end 0)
3562 '(display t invisible t intangible t))
3563 t)))
3565 (defun org-activate-angle-links (limit)
3566 "Run through the buffer and add overlays to links."
3567 (if (re-search-forward org-angle-link-re limit t)
3568 (progn
3569 (add-text-properties (match-beginning 0) (match-end 0)
3570 (list 'mouse-face 'highlight
3571 'rear-nonsticky org-nonsticky-props
3572 'keymap org-mouse-map
3574 t)))
3576 (defun org-activate-bracket-links (limit)
3577 "Run through the buffer and add overlays to bracketed links."
3578 (if (re-search-forward org-bracket-link-regexp limit t)
3579 (let* ((help (concat "LINK: "
3580 (org-match-string-no-properties 1)))
3581 ;; FIXME: above we should remove the escapes.
3582 ;; but that requires another match, protecting match data,
3583 ;; a lot of overhead for font-lock.
3584 (ip (org-maybe-intangible
3585 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
3586 'keymap org-mouse-map 'mouse-face 'highlight
3587 'font-lock-multiline t 'help-echo help)))
3588 (vp (list 'rear-nonsticky org-nonsticky-props
3589 'keymap org-mouse-map 'mouse-face 'highlight
3590 ' font-lock-multiline t 'help-echo help)))
3591 ;; We need to remove the invisible property here. Table narrowing
3592 ;; may have made some of this invisible.
3593 (remove-text-properties (match-beginning 0) (match-end 0)
3594 '(invisible nil))
3595 (if (match-end 3)
3596 (progn
3597 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3598 (add-text-properties (match-beginning 3) (match-end 3) vp)
3599 (add-text-properties (match-end 3) (match-end 0) ip))
3600 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3601 (add-text-properties (match-beginning 1) (match-end 1) vp)
3602 (add-text-properties (match-end 1) (match-end 0) ip))
3603 t)))
3605 (defun org-activate-dates (limit)
3606 "Run through the buffer and add overlays to dates."
3607 (if (re-search-forward org-tsr-regexp-both limit t)
3608 (progn
3609 (add-text-properties (match-beginning 0) (match-end 0)
3610 (list 'mouse-face 'highlight
3611 'rear-nonsticky org-nonsticky-props
3612 'keymap org-mouse-map))
3613 (when org-display-custom-times
3614 (if (match-end 3)
3615 (org-display-custom-time (match-beginning 3) (match-end 3)))
3616 (org-display-custom-time (match-beginning 1) (match-end 1)))
3617 t)))
3619 (defvar org-target-link-regexp nil
3620 "Regular expression matching radio targets in plain text.")
3621 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3622 "Regular expression matching a link target.")
3623 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3624 "Regular expression matching a radio target.")
3625 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
3626 "Regular expression matching any target.")
3628 (defun org-activate-target-links (limit)
3629 "Run through the buffer and add overlays to target matches."
3630 (when org-target-link-regexp
3631 (let ((case-fold-search t))
3632 (if (re-search-forward org-target-link-regexp limit t)
3633 (progn
3634 (add-text-properties (match-beginning 0) (match-end 0)
3635 (list 'mouse-face 'highlight
3636 'rear-nonsticky org-nonsticky-props
3637 'keymap org-mouse-map
3638 'help-echo "Radio target link"
3639 'org-linked-text t))
3640 t)))))
3642 (defun org-update-radio-target-regexp ()
3643 "Find all radio targets in this file and update the regular expression."
3644 (interactive)
3645 (when (memq 'radio org-activate-links)
3646 (setq org-target-link-regexp
3647 (org-make-target-link-regexp (org-all-targets 'radio)))
3648 (org-restart-font-lock)))
3650 (defun org-hide-wide-columns (limit)
3651 (let (s e)
3652 (setq s (text-property-any (point) (or limit (point-max))
3653 'org-cwidth t))
3654 (when s
3655 (setq e (next-single-property-change s 'org-cwidth))
3656 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
3657 (goto-char e)
3658 t)))
3660 (defvar org-latex-and-specials-regexp nil
3661 "Regular expression for highlighting export special stuff.")
3662 (defvar org-match-substring-regexp)
3663 (defvar org-match-substring-with-braces-regexp)
3664 (defvar org-export-html-special-string-regexps)
3666 (defun org-compute-latex-and-specials-regexp ()
3667 "Compute regular expression for stuff treated specially by exporters."
3668 (if (not org-highlight-latex-fragments-and-specials)
3669 (org-set-local 'org-latex-and-specials-regexp nil)
3670 (require 'org-exp)
3671 (let*
3672 ((matchers (plist-get org-format-latex-options :matchers))
3673 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
3674 org-latex-regexps)))
3675 (options (org-combine-plists (org-default-export-plist)
3676 (org-infile-export-plist)))
3677 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
3678 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
3679 (org-export-with-TeX-macros (plist-get options :TeX-macros))
3680 (org-export-html-expand (plist-get options :expand-quoted-html))
3681 (org-export-with-special-strings (plist-get options :special-strings))
3682 (re-sub
3683 (cond
3684 ((equal org-export-with-sub-superscripts '{})
3685 (list org-match-substring-with-braces-regexp))
3686 (org-export-with-sub-superscripts
3687 (list org-match-substring-regexp))
3688 (t nil)))
3689 (re-latex
3690 (if org-export-with-LaTeX-fragments
3691 (mapcar (lambda (x) (nth 1 x)) latexs)))
3692 (re-macros
3693 (if org-export-with-TeX-macros
3694 (list (concat "\\\\"
3695 (regexp-opt
3696 (append (mapcar 'car org-html-entities)
3697 (if (boundp 'org-latex-entities)
3698 org-latex-entities nil))
3699 'words))) ; FIXME
3701 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
3702 (re-special (if org-export-with-special-strings
3703 (mapcar (lambda (x) (car x))
3704 org-export-html-special-string-regexps)))
3705 (re-rest
3706 (delq nil
3707 (list
3708 (if org-export-html-expand "@<[^>\n]+>")
3709 ))))
3710 (org-set-local
3711 'org-latex-and-specials-regexp
3712 (mapconcat 'identity (append re-latex re-sub re-macros re-special
3713 re-rest) "\\|")))))
3715 (defun org-do-latex-and-special-faces (limit)
3716 "Run through the buffer and add overlays to links."
3717 (when org-latex-and-specials-regexp
3718 (let (rtn d)
3719 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
3720 limit t))
3721 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
3722 'face))
3723 '(org-code org-verbatim underline)))
3724 (progn
3725 (setq rtn t
3726 d (cond ((member (char-after (1+ (match-beginning 0)))
3727 '(?_ ?^)) 1)
3728 (t 0)))
3729 (font-lock-prepend-text-property
3730 (+ d (match-beginning 0)) (match-end 0)
3731 'face 'org-latex-and-export-specials)
3732 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
3733 '(font-lock-multiline t)))))
3734 rtn)))
3736 (defun org-restart-font-lock ()
3737 "Restart font-lock-mode, to force refontification."
3738 (when (and (boundp 'font-lock-mode) font-lock-mode)
3739 (font-lock-mode -1)
3740 (font-lock-mode 1)))
3742 (defun org-all-targets (&optional radio)
3743 "Return a list of all targets in this file.
3744 With optional argument RADIO, only find radio targets."
3745 (let ((re (if radio org-radio-target-regexp org-target-regexp))
3746 rtn)
3747 (save-excursion
3748 (goto-char (point-min))
3749 (while (re-search-forward re nil t)
3750 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
3751 rtn)))
3753 (defun org-make-target-link-regexp (targets)
3754 "Make regular expression matching all strings in TARGETS.
3755 The regular expression finds the targets also if there is a line break
3756 between words."
3757 (and targets
3758 (concat
3759 "\\<\\("
3760 (mapconcat
3761 (lambda (x)
3762 (while (string-match " +" x)
3763 (setq x (replace-match "\\s-+" t t x)))
3765 targets
3766 "\\|")
3767 "\\)\\>")))
3769 (defun org-activate-tags (limit)
3770 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
3771 (progn
3772 (add-text-properties (match-beginning 1) (match-end 1)
3773 (list 'mouse-face 'highlight
3774 'rear-nonsticky org-nonsticky-props
3775 'keymap org-mouse-map))
3776 t)))
3778 (defun org-outline-level ()
3779 (save-excursion
3780 (looking-at outline-regexp)
3781 (if (match-beginning 1)
3782 (+ (org-get-string-indentation (match-string 1)) 1000)
3783 (1- (- (match-end 0) (match-beginning 0))))))
3785 (defvar org-font-lock-keywords nil)
3787 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
3788 "Regular expression matching a property line.")
3790 (defvar org-font-lock-hook nil
3791 "Functions to be called for special font lock stuff.")
3793 (defun org-font-lock-hook (limit)
3794 (run-hook-with-args 'org-font-lock-hook limit))
3796 (defun org-set-font-lock-defaults ()
3797 (let* ((em org-fontify-emphasized-text)
3798 (lk org-activate-links)
3799 (org-font-lock-extra-keywords
3800 (list
3801 ;; Call the hook
3802 '(org-font-lock-hook)
3803 ;; Headlines
3804 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
3805 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
3806 ;; Table lines
3807 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
3808 (1 'org-table t))
3809 ;; Table internals
3810 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
3811 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
3812 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
3813 ;; Drawers
3814 (list org-drawer-regexp '(0 'org-special-keyword t))
3815 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
3816 ;; Properties
3817 (list org-property-re
3818 '(1 'org-special-keyword t)
3819 '(3 'org-property-value t))
3820 (if org-format-transports-properties-p
3821 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
3822 ;; Links
3823 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
3824 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
3825 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
3826 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
3827 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
3828 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
3829 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
3830 '(org-hide-wide-columns (0 nil append))
3831 ;; TODO lines
3832 (list (concat "^\\*+[ \t]+" org-todo-regexp)
3833 '(1 (org-get-todo-face 1) t))
3834 ;; DONE
3835 (if org-fontify-done-headline
3836 (list (concat "^[*]+ +\\<\\("
3837 (mapconcat 'regexp-quote org-done-keywords "\\|")
3838 "\\)\\(.*\\)")
3839 '(2 'org-headline-done t))
3840 nil)
3841 ;; Priorities
3842 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
3843 ;; Special keywords
3844 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
3845 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
3846 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
3847 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
3848 ;; Emphasis
3849 (if em
3850 (if (featurep 'xemacs)
3851 '(org-do-emphasis-faces (0 nil append))
3852 '(org-do-emphasis-faces)))
3853 ;; Checkboxes
3854 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
3855 2 'bold prepend)
3856 (if org-provide-checkbox-statistics
3857 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
3858 (0 (org-get-checkbox-statistics-face) t)))
3859 ;; Description list items
3860 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
3861 2 'bold prepend)
3862 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
3863 '(1 'org-archived prepend))
3864 ;; Specials
3865 '(org-do-latex-and-special-faces)
3866 ;; Code
3867 '(org-activate-code (1 'org-code t))
3868 ;; COMMENT
3869 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
3870 "\\|" org-quote-string "\\)\\>")
3871 '(1 'org-special-keyword t))
3872 '("^#.*" (0 'font-lock-comment-face t))
3874 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
3875 ;; Now set the full font-lock-keywords
3876 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
3877 (org-set-local 'font-lock-defaults
3878 '(org-font-lock-keywords t nil nil backward-paragraph))
3879 (kill-local-variable 'font-lock-keywords) nil))
3881 (defvar org-m nil)
3882 (defvar org-l nil)
3883 (defvar org-f nil)
3884 (defun org-get-level-face (n)
3885 "Get the right face for match N in font-lock matching of healdines."
3886 (setq org-l (- (match-end 2) (match-beginning 1) 1))
3887 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
3888 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
3889 (cond
3890 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
3891 ((eq n 2) org-f)
3892 (t (if org-level-color-stars-only nil org-f))))
3894 (defun org-get-todo-face (kwd)
3895 "Get the right face for a TODO keyword KWD.
3896 If KWD is a number, get the corresponding match group."
3897 (if (numberp kwd) (setq kwd (match-string kwd)))
3898 (or (cdr (assoc kwd org-todo-keyword-faces))
3899 (and (member kwd org-done-keywords) 'org-done)
3900 'org-todo))
3902 (defun org-unfontify-region (beg end &optional maybe_loudly)
3903 "Remove fontification and activation overlays from links."
3904 (font-lock-default-unfontify-region beg end)
3905 (let* ((buffer-undo-list t)
3906 (inhibit-read-only t) (inhibit-point-motion-hooks t)
3907 (inhibit-modification-hooks t)
3908 deactivate-mark buffer-file-name buffer-file-truename)
3909 (remove-text-properties beg end
3910 '(mouse-face t keymap t org-linked-text t
3911 invisible t intangible t))))
3913 ;;;; Visibility cycling, including org-goto and indirect buffer
3915 ;;; Cycling
3917 (defvar org-cycle-global-status nil)
3918 (make-variable-buffer-local 'org-cycle-global-status)
3919 (defvar org-cycle-subtree-status nil)
3920 (make-variable-buffer-local 'org-cycle-subtree-status)
3922 ;;;###autoload
3923 (defun org-cycle (&optional arg)
3924 "Visibility cycling for Org-mode.
3926 - When this function is called with a prefix argument, rotate the entire
3927 buffer through 3 states (global cycling)
3928 1. OVERVIEW: Show only top-level headlines.
3929 2. CONTENTS: Show all headlines of all levels, but no body text.
3930 3. SHOW ALL: Show everything.
3931 When called with two C-u C-u prefixes, switch to the startup visibility,
3932 determined by the variable `org-startup-folded', and by any VISIBILITY
3933 properties in the buffer.
3934 When called with three C-u C-u C-u prefixed, show the entire buffer,
3935 including drawers.
3937 - When point is at the beginning of a headline, rotate the subtree started
3938 by this line through 3 different states (local cycling)
3939 1. FOLDED: Only the main headline is shown.
3940 2. CHILDREN: The main headline and the direct children are shown.
3941 From this state, you can move to one of the children
3942 and zoom in further.
3943 3. SUBTREE: Show the entire subtree, including body text.
3945 - When there is a numeric prefix, go up to a heading with level ARG, do
3946 a `show-subtree' and return to the previous cursor position. If ARG
3947 is negative, go up that many levels.
3949 - When point is not at the beginning of a headline, execute the global
3950 binding for TAB, which is re-indenting the line. See the option
3951 `org-cycle-emulate-tab' for details.
3953 - Special case: if point is at the beginning of the buffer and there is
3954 no headline in line 1, this function will act as if called with prefix arg.
3955 But only if also the variable `org-cycle-global-at-bob' is t."
3956 (interactive "P")
3957 (org-load-modules-maybe)
3958 (let* ((outline-regexp
3959 (if (and (org-mode-p) org-cycle-include-plain-lists)
3960 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
3961 outline-regexp))
3962 (bob-special (and org-cycle-global-at-bob (bobp)
3963 (not (looking-at outline-regexp))))
3964 (org-cycle-hook
3965 (if bob-special
3966 (delq 'org-optimize-window-after-visibility-change
3967 (copy-sequence org-cycle-hook))
3968 org-cycle-hook))
3969 (pos (point)))
3971 (if (or bob-special (equal arg '(4)))
3972 ;; special case: use global cycling
3973 (setq arg t))
3975 (cond
3977 ((equal arg '(16))
3978 (org-set-startup-visibility)
3979 (message "Startup visibility, plus VISIBILITY properties"))
3981 ((equal arg '(64))
3982 (show-all)
3983 (message "Entire buffer visible, including drawers"))
3985 ((org-at-table-p 'any)
3986 ;; Enter the table or move to the next field in the table
3987 (or (org-table-recognize-table.el)
3988 (progn
3989 (if arg (org-table-edit-field t)
3990 (org-table-justify-field-maybe)
3991 (call-interactively 'org-table-next-field)))))
3993 ((eq arg t) ;; Global cycling
3995 (cond
3996 ((and (eq last-command this-command)
3997 (eq org-cycle-global-status 'overview))
3998 ;; We just created the overview - now do table of contents
3999 ;; This can be slow in very large buffers, so indicate action
4000 (message "CONTENTS...")
4001 (org-content)
4002 (message "CONTENTS...done")
4003 (setq org-cycle-global-status 'contents)
4004 (run-hook-with-args 'org-cycle-hook 'contents))
4006 ((and (eq last-command this-command)
4007 (eq org-cycle-global-status 'contents))
4008 ;; We just showed the table of contents - now show everything
4009 (show-all)
4010 (message "SHOW ALL")
4011 (setq org-cycle-global-status 'all)
4012 (run-hook-with-args 'org-cycle-hook 'all))
4015 ;; Default action: go to overview
4016 (org-overview)
4017 (message "OVERVIEW")
4018 (setq org-cycle-global-status 'overview)
4019 (run-hook-with-args 'org-cycle-hook 'overview))))
4021 ((and org-drawers org-drawer-regexp
4022 (save-excursion
4023 (beginning-of-line 1)
4024 (looking-at org-drawer-regexp)))
4025 ;; Toggle block visibility
4026 (org-flag-drawer
4027 (not (get-char-property (match-end 0) 'invisible))))
4029 ((integerp arg)
4030 ;; Show-subtree, ARG levels up from here.
4031 (save-excursion
4032 (org-back-to-heading)
4033 (outline-up-heading (if (< arg 0) (- arg)
4034 (- (funcall outline-level) arg)))
4035 (org-show-subtree)))
4037 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4038 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4039 ;; At a heading: rotate between three different views
4040 (org-back-to-heading)
4041 (let ((goal-column 0) eoh eol eos)
4042 ;; First, some boundaries
4043 (save-excursion
4044 (org-back-to-heading)
4045 (save-excursion
4046 (beginning-of-line 2)
4047 (while (and (not (eobp)) ;; this is like `next-line'
4048 (get-char-property (1- (point)) 'invisible))
4049 (beginning-of-line 2)) (setq eol (point)))
4050 (outline-end-of-heading) (setq eoh (point))
4051 (org-end-of-subtree t)
4052 (unless (eobp)
4053 (skip-chars-forward " \t\n")
4054 (beginning-of-line 1) ; in case this is an item
4056 (setq eos (1- (point))))
4057 ;; Find out what to do next and set `this-command'
4058 (cond
4059 ((= eos eoh)
4060 ;; Nothing is hidden behind this heading
4061 (message "EMPTY ENTRY")
4062 (setq org-cycle-subtree-status nil)
4063 (save-excursion
4064 (goto-char eos)
4065 (outline-next-heading)
4066 (if (org-invisible-p) (org-flag-heading nil))))
4067 ((or (>= eol eos)
4068 (not (string-match "\\S-" (buffer-substring eol eos))))
4069 ;; Entire subtree is hidden in one line: open it
4070 (org-show-entry)
4071 (show-children)
4072 (message "CHILDREN")
4073 (save-excursion
4074 (goto-char eos)
4075 (outline-next-heading)
4076 (if (org-invisible-p) (org-flag-heading nil)))
4077 (setq org-cycle-subtree-status 'children)
4078 (run-hook-with-args 'org-cycle-hook 'children))
4079 ((and (eq last-command this-command)
4080 (eq org-cycle-subtree-status 'children))
4081 ;; We just showed the children, now show everything.
4082 (org-show-subtree)
4083 (message "SUBTREE")
4084 (setq org-cycle-subtree-status 'subtree)
4085 (run-hook-with-args 'org-cycle-hook 'subtree))
4087 ;; Default action: hide the subtree.
4088 (hide-subtree)
4089 (message "FOLDED")
4090 (setq org-cycle-subtree-status 'folded)
4091 (run-hook-with-args 'org-cycle-hook 'folded)))))
4093 ;; TAB emulation and template completion
4094 (buffer-read-only (org-back-to-heading))
4096 ((org-try-structure-completion))
4098 ((org-try-cdlatex-tab))
4100 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4101 (or (not (bolp))
4102 (not (looking-at outline-regexp))))
4103 (call-interactively (global-key-binding "\t")))
4105 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4106 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4107 (or (and (eq org-cycle-emulate-tab 'white)
4108 (= (match-end 0) (point-at-eol)))
4109 (and (eq org-cycle-emulate-tab 'whitestart)
4110 (>= (match-end 0) pos))))
4112 (eq org-cycle-emulate-tab t))
4113 (call-interactively (global-key-binding "\t")))
4115 (t (save-excursion
4116 (org-back-to-heading)
4117 (org-cycle))))))
4119 ;;;###autoload
4120 (defun org-global-cycle (&optional arg)
4121 "Cycle the global visibility. For details see `org-cycle'.
4122 With C-u prefix arg, switch to startup visibility.
4123 With a numeric prefix, show all headlines up to that level."
4124 (interactive "P")
4125 (let ((org-cycle-include-plain-lists
4126 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4127 (cond
4128 ((integerp arg)
4129 (show-all)
4130 (hide-sublevels arg)
4131 (setq org-cycle-global-status 'contents))
4132 ((equal arg '(4))
4133 (org-set-startup-visibility)
4134 (message "Startup visibility, plus VISIBILITY properties."))
4136 (org-cycle '(4))))))
4138 (defun org-set-startup-visibility ()
4139 "Set the visibility required by startup options and properties."
4140 (cond
4141 ((eq org-startup-folded t)
4142 (org-cycle '(4)))
4143 ((eq org-startup-folded 'content)
4144 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4145 (org-cycle '(4)) (org-cycle '(4)))))
4146 (org-set-visibility-according-to-property 'no-cleanup)
4147 (org-cycle-hide-archived-subtrees 'all)
4148 (org-cycle-hide-drawers 'all)
4149 (org-cycle-show-empty-lines 'all))
4151 (defun org-set-visibility-according-to-property (&optional no-cleanup)
4152 "Switch subtree visibilities according to :VISIBILITY: property."
4153 (interactive)
4154 (let (state)
4155 (save-excursion
4156 (goto-char (point-min))
4157 (while (re-search-forward
4158 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
4159 nil t)
4160 (setq state (match-string 1))
4161 (save-excursion
4162 (org-back-to-heading t)
4163 (hide-subtree)
4164 (org-reveal)
4165 (cond
4166 ((equal state '("fold" "folded"))
4167 (hide-subtree))
4168 ((equal state "children")
4169 (org-show-hidden-entry)
4170 (show-children))
4171 ((equal state "content")
4172 (save-excursion
4173 (save-restriction
4174 (org-narrow-to-subtree)
4175 (org-content))))
4176 ((member state '("all" "showall"))
4177 (show-subtree)))))
4178 (unless no-cleanup
4179 (org-cycle-hide-archived-subtrees 'all)
4180 (org-cycle-hide-drawers 'all)
4181 (org-cycle-show-empty-lines 'all)))))
4183 (defun org-overview ()
4184 "Switch to overview mode, shoing only top-level headlines.
4185 Really, this shows all headlines with level equal or greater than the level
4186 of the first headline in the buffer. This is important, because if the
4187 first headline is not level one, then (hide-sublevels 1) gives confusing
4188 results."
4189 (interactive)
4190 (let ((level (save-excursion
4191 (goto-char (point-min))
4192 (if (re-search-forward (concat "^" outline-regexp) nil t)
4193 (progn
4194 (goto-char (match-beginning 0))
4195 (funcall outline-level))))))
4196 (and level (hide-sublevels level))))
4198 (defun org-content (&optional arg)
4199 "Show all headlines in the buffer, like a table of contents.
4200 With numerical argument N, show content up to level N."
4201 (interactive "P")
4202 (save-excursion
4203 ;; Visit all headings and show their offspring
4204 (and (integerp arg) (org-overview))
4205 (goto-char (point-max))
4206 (catch 'exit
4207 (while (and (progn (condition-case nil
4208 (outline-previous-visible-heading 1)
4209 (error (goto-char (point-min))))
4211 (looking-at outline-regexp))
4212 (if (integerp arg)
4213 (show-children (1- arg))
4214 (show-branches))
4215 (if (bobp) (throw 'exit nil))))))
4218 (defun org-optimize-window-after-visibility-change (state)
4219 "Adjust the window after a change in outline visibility.
4220 This function is the default value of the hook `org-cycle-hook'."
4221 (when (get-buffer-window (current-buffer))
4222 (cond
4223 ; ((eq state 'overview) (org-first-headline-recenter 1))
4224 ; ((eq state 'overview) (org-beginning-of-line))
4225 ((eq state 'content) nil)
4226 ((eq state 'all) nil)
4227 ((eq state 'folded) nil)
4228 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4229 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4231 (defun org-compact-display-after-subtree-move ()
4232 (let (beg end)
4233 (save-excursion
4234 (if (org-up-heading-safe)
4235 (progn
4236 (hide-subtree)
4237 (show-entry)
4238 (show-children)
4239 (org-cycle-show-empty-lines 'children)
4240 (org-cycle-hide-drawers 'children))
4241 (org-overview)))))
4243 (defun org-cycle-show-empty-lines (state)
4244 "Show empty lines above all visible headlines.
4245 The region to be covered depends on STATE when called through
4246 `org-cycle-hook'. Lisp program can use t for STATE to get the
4247 entire buffer covered. Note that an empty line is only shown if there
4248 are at least `org-cycle-separator-lines' empty lines before the headeline."
4249 (when (> org-cycle-separator-lines 0)
4250 (save-excursion
4251 (let* ((n org-cycle-separator-lines)
4252 (re (cond
4253 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
4254 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
4255 (t (let ((ns (number-to-string (- n 2))))
4256 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
4257 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
4258 beg end)
4259 (cond
4260 ((memq state '(overview contents t))
4261 (setq beg (point-min) end (point-max)))
4262 ((memq state '(children folded))
4263 (setq beg (point) end (progn (org-end-of-subtree t t)
4264 (beginning-of-line 2)
4265 (point)))))
4266 (when beg
4267 (goto-char beg)
4268 (while (re-search-forward re end t)
4269 (if (not (get-char-property (match-end 1) 'invisible))
4270 (outline-flag-region
4271 (match-beginning 1) (match-end 1) nil)))))))
4272 ;; Never hide empty lines at the end of the file.
4273 (save-excursion
4274 (goto-char (point-max))
4275 (outline-previous-heading)
4276 (outline-end-of-heading)
4277 (if (and (looking-at "[ \t\n]+")
4278 (= (match-end 0) (point-max)))
4279 (outline-flag-region (point) (match-end 0) nil))))
4281 (defun org-show-empty-lines-in-parent ()
4282 "Move to the parent and re-show empty lines before visible headlines."
4283 (save-excursion
4284 (let ((context (if (org-up-heading-safe) 'children 'overview)))
4285 (org-cycle-show-empty-lines context))))
4287 (defun org-cycle-hide-drawers (state)
4288 "Re-hide all drawers after a visibility state change."
4289 (when (and (org-mode-p)
4290 (not (memq state '(overview folded))))
4291 (save-excursion
4292 (let* ((globalp (memq state '(contents all)))
4293 (beg (if globalp (point-min) (point)))
4294 (end (if globalp (point-max) (org-end-of-subtree t))))
4295 (goto-char beg)
4296 (while (re-search-forward org-drawer-regexp end t)
4297 (org-flag-drawer t))))))
4299 (defun org-flag-drawer (flag)
4300 (save-excursion
4301 (beginning-of-line 1)
4302 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
4303 (let ((b (match-end 0))
4304 (outline-regexp org-outline-regexp))
4305 (if (re-search-forward
4306 "^[ \t]*:END:"
4307 (save-excursion (outline-next-heading) (point)) t)
4308 (outline-flag-region b (point-at-eol) flag)
4309 (error ":END: line missing"))))))
4311 (defun org-subtree-end-visible-p ()
4312 "Is the end of the current subtree visible?"
4313 (pos-visible-in-window-p
4314 (save-excursion (org-end-of-subtree t) (point))))
4316 (defun org-first-headline-recenter (&optional N)
4317 "Move cursor to the first headline and recenter the headline.
4318 Optional argument N means, put the headline into the Nth line of the window."
4319 (goto-char (point-min))
4320 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4321 (beginning-of-line)
4322 (recenter (prefix-numeric-value N))))
4324 ;;; Org-goto
4326 (defvar org-goto-window-configuration nil)
4327 (defvar org-goto-marker nil)
4328 (defvar org-goto-map
4329 (let ((map (make-sparse-keymap)))
4330 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
4331 (while (setq cmd (pop cmds))
4332 (substitute-key-definition cmd cmd map global-map)))
4333 (suppress-keymap map)
4334 (org-defkey map "\C-m" 'org-goto-ret)
4335 (org-defkey map [(return)] 'org-goto-ret)
4336 (org-defkey map [(left)] 'org-goto-left)
4337 (org-defkey map [(right)] 'org-goto-right)
4338 (org-defkey map [(control ?g)] 'org-goto-quit)
4339 (org-defkey map "\C-i" 'org-cycle)
4340 (org-defkey map [(tab)] 'org-cycle)
4341 (org-defkey map [(down)] 'outline-next-visible-heading)
4342 (org-defkey map [(up)] 'outline-previous-visible-heading)
4343 (if org-goto-auto-isearch
4344 (if (fboundp 'define-key-after)
4345 (define-key-after map [t] 'org-goto-local-auto-isearch)
4346 nil)
4347 (org-defkey map "q" 'org-goto-quit)
4348 (org-defkey map "n" 'outline-next-visible-heading)
4349 (org-defkey map "p" 'outline-previous-visible-heading)
4350 (org-defkey map "f" 'outline-forward-same-level)
4351 (org-defkey map "b" 'outline-backward-same-level)
4352 (org-defkey map "u" 'outline-up-heading))
4353 (org-defkey map "/" 'org-occur)
4354 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4355 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4356 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
4357 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
4358 (org-defkey map "\C-c\C-u" 'outline-up-heading)
4359 map))
4361 (defconst org-goto-help
4362 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4363 RET=jump to location [Q]uit and return to previous location
4364 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4366 (defvar org-goto-start-pos) ; dynamically scoped parameter
4368 ;; FIXME: Docstring doe not mention both interfaces
4369 (defun org-goto (&optional alternative-interface)
4370 "Look up a different location in the current file, keeping current visibility.
4372 When you want look-up or go to a different location in a document, the
4373 fastest way is often to fold the entire buffer and then dive into the tree.
4374 This method has the disadvantage, that the previous location will be folded,
4375 which may not be what you want.
4377 This command works around this by showing a copy of the current buffer
4378 in an indirect buffer, in overview mode. You can dive into the tree in
4379 that copy, use org-occur and incremental search to find a location.
4380 When pressing RET or `Q', the command returns to the original buffer in
4381 which the visibility is still unchanged. After RET is will also jump to
4382 the location selected in the indirect buffer and expose the
4383 the headline hierarchy above."
4384 (interactive "P")
4385 (let* ((org-refile-targets '((nil . (:maxlevel . 10))))
4386 (org-refile-use-outline-path t)
4387 (interface
4388 (if (not alternative-interface)
4389 org-goto-interface
4390 (if (eq org-goto-interface 'outline)
4391 'outline-path-completion
4392 'outline)))
4393 (org-goto-start-pos (point))
4394 (selected-point
4395 (if (eq interface 'outline)
4396 (car (org-get-location (current-buffer) org-goto-help))
4397 (nth 3 (org-refile-get-location "Goto: ")))))
4398 (if selected-point
4399 (progn
4400 (org-mark-ring-push org-goto-start-pos)
4401 (goto-char selected-point)
4402 (if (or (org-invisible-p) (org-invisible-p2))
4403 (org-show-context 'org-goto)))
4404 (message "Quit"))))
4406 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
4407 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
4408 (defvar org-goto-local-auto-isearch-map) ; defined below
4410 (defun org-get-location (buf help)
4411 "Let the user select a location in the Org-mode buffer BUF.
4412 This function uses a recursive edit. It returns the selected position
4413 or nil."
4414 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
4415 (isearch-hide-immediately nil)
4416 (isearch-search-fun-function
4417 (lambda () 'org-goto-local-search-headings))
4418 (org-goto-selected-point org-goto-exit-command))
4419 (save-excursion
4420 (save-window-excursion
4421 (delete-other-windows)
4422 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
4423 (switch-to-buffer
4424 (condition-case nil
4425 (make-indirect-buffer (current-buffer) "*org-goto*")
4426 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
4427 (with-output-to-temp-buffer "*Help*"
4428 (princ help))
4429 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
4430 (setq buffer-read-only nil)
4431 (let ((org-startup-truncated t)
4432 (org-startup-folded nil)
4433 (org-startup-align-all-tables nil))
4434 (org-mode)
4435 (org-overview))
4436 (setq buffer-read-only t)
4437 (if (and (boundp 'org-goto-start-pos)
4438 (integer-or-marker-p org-goto-start-pos))
4439 (let ((org-show-hierarchy-above t)
4440 (org-show-siblings t)
4441 (org-show-following-heading t))
4442 (goto-char org-goto-start-pos)
4443 (and (org-invisible-p) (org-show-context)))
4444 (goto-char (point-min)))
4445 (org-beginning-of-line)
4446 (message "Select location and press RET")
4447 (use-local-map org-goto-map)
4448 (recursive-edit)
4450 (kill-buffer "*org-goto*")
4451 (cons org-goto-selected-point org-goto-exit-command)))
4453 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
4454 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
4455 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
4456 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
4458 (defun org-goto-local-search-headings (string bound noerror)
4459 "Search and make sure that any matches are in headlines."
4460 (catch 'return
4461 (while (if isearch-forward
4462 (search-forward string bound noerror)
4463 (search-backward string bound noerror))
4464 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
4465 (and (member :headline context)
4466 (not (member :tags context))))
4467 (throw 'return (point))))))
4469 (defun org-goto-local-auto-isearch ()
4470 "Start isearch."
4471 (interactive)
4472 (goto-char (point-min))
4473 (let ((keys (this-command-keys)))
4474 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
4475 (isearch-mode t)
4476 (isearch-process-search-char (string-to-char keys)))))
4478 (defun org-goto-ret (&optional arg)
4479 "Finish `org-goto' by going to the new location."
4480 (interactive "P")
4481 (setq org-goto-selected-point (point)
4482 org-goto-exit-command 'return)
4483 (throw 'exit nil))
4485 (defun org-goto-left ()
4486 "Finish `org-goto' by going to the new location."
4487 (interactive)
4488 (if (org-on-heading-p)
4489 (progn
4490 (beginning-of-line 1)
4491 (setq org-goto-selected-point (point)
4492 org-goto-exit-command 'left)
4493 (throw 'exit nil))
4494 (error "Not on a heading")))
4496 (defun org-goto-right ()
4497 "Finish `org-goto' by going to the new location."
4498 (interactive)
4499 (if (org-on-heading-p)
4500 (progn
4501 (setq org-goto-selected-point (point)
4502 org-goto-exit-command 'right)
4503 (throw 'exit nil))
4504 (error "Not on a heading")))
4506 (defun org-goto-quit ()
4507 "Finish `org-goto' without cursor motion."
4508 (interactive)
4509 (setq org-goto-selected-point nil)
4510 (setq org-goto-exit-command 'quit)
4511 (throw 'exit nil))
4513 ;;; Indirect buffer display of subtrees
4515 (defvar org-indirect-dedicated-frame nil
4516 "This is the frame being used for indirect tree display.")
4517 (defvar org-last-indirect-buffer nil)
4519 (defun org-tree-to-indirect-buffer (&optional arg)
4520 "Create indirect buffer and narrow it to current subtree.
4521 With numerical prefix ARG, go up to this level and then take that tree.
4522 If ARG is negative, go up that many levels.
4523 If `org-indirect-buffer-display' is not `new-frame', the command removes the
4524 indirect buffer previously made with this command, to avoid proliferation of
4525 indirect buffers. However, when you call the command with a `C-u' prefix, or
4526 when `org-indirect-buffer-display' is `new-frame', the last buffer
4527 is kept so that you can work with several indirect buffers at the same time.
4528 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
4529 requests that a new frame be made for the new buffer, so that the dedicated
4530 frame is not changed."
4531 (interactive "P")
4532 (let ((cbuf (current-buffer))
4533 (cwin (selected-window))
4534 (pos (point))
4535 beg end level heading ibuf)
4536 (save-excursion
4537 (org-back-to-heading t)
4538 (when (numberp arg)
4539 (setq level (org-outline-level))
4540 (if (< arg 0) (setq arg (+ level arg)))
4541 (while (> (setq level (org-outline-level)) arg)
4542 (outline-up-heading 1 t)))
4543 (setq beg (point)
4544 heading (org-get-heading))
4545 (org-end-of-subtree t) (setq end (point)))
4546 (if (and (buffer-live-p org-last-indirect-buffer)
4547 (not (eq org-indirect-buffer-display 'new-frame))
4548 (not arg))
4549 (kill-buffer org-last-indirect-buffer))
4550 (setq ibuf (org-get-indirect-buffer cbuf)
4551 org-last-indirect-buffer ibuf)
4552 (cond
4553 ((or (eq org-indirect-buffer-display 'new-frame)
4554 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
4555 (select-frame (make-frame))
4556 (delete-other-windows)
4557 (switch-to-buffer ibuf)
4558 (org-set-frame-title heading))
4559 ((eq org-indirect-buffer-display 'dedicated-frame)
4560 (raise-frame
4561 (select-frame (or (and org-indirect-dedicated-frame
4562 (frame-live-p org-indirect-dedicated-frame)
4563 org-indirect-dedicated-frame)
4564 (setq org-indirect-dedicated-frame (make-frame)))))
4565 (delete-other-windows)
4566 (switch-to-buffer ibuf)
4567 (org-set-frame-title (concat "Indirect: " heading)))
4568 ((eq org-indirect-buffer-display 'current-window)
4569 (switch-to-buffer ibuf))
4570 ((eq org-indirect-buffer-display 'other-window)
4571 (pop-to-buffer ibuf))
4572 (t (error "Invalid value.")))
4573 (if (featurep 'xemacs)
4574 (save-excursion (org-mode) (turn-on-font-lock)))
4575 (narrow-to-region beg end)
4576 (show-all)
4577 (goto-char pos)
4578 (and (window-live-p cwin) (select-window cwin))))
4580 (defun org-get-indirect-buffer (&optional buffer)
4581 (setq buffer (or buffer (current-buffer)))
4582 (let ((n 1) (base (buffer-name buffer)) bname)
4583 (while (buffer-live-p
4584 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
4585 (setq n (1+ n)))
4586 (condition-case nil
4587 (make-indirect-buffer buffer bname 'clone)
4588 (error (make-indirect-buffer buffer bname)))))
4590 (defun org-set-frame-title (title)
4591 "Set the title of the current frame to the string TITLE."
4592 ;; FIXME: how to name a single frame in XEmacs???
4593 (unless (featurep 'xemacs)
4594 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
4596 ;;;; Structure editing
4598 ;;; Inserting headlines
4600 (defun org-insert-heading (&optional force-heading)
4601 "Insert a new heading or item with same depth at point.
4602 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
4603 If point is at the beginning of a headline, insert a sibling before the
4604 current headline. If point is not at the beginning, do not split the line,
4605 but create the new hedline after the current line."
4606 (interactive "P")
4607 (if (= (buffer-size) 0)
4608 (insert "\n* ")
4609 (when (or force-heading (not (org-insert-item)))
4610 (let* ((head (save-excursion
4611 (condition-case nil
4612 (progn
4613 (org-back-to-heading)
4614 (match-string 0))
4615 (error "*"))))
4616 (blank (cdr (assq 'heading org-blank-before-new-entry)))
4617 pos hide-previous)
4618 (cond
4619 ((and (org-on-heading-p) (bolp)
4620 (or (bobp)
4621 (save-excursion (backward-char 1) (not (org-invisible-p)))))
4622 ;; insert before the current line
4623 (open-line (if blank 2 1)))
4624 ((and (bolp)
4625 (or (bobp)
4626 (save-excursion
4627 (backward-char 1) (not (org-invisible-p)))))
4628 ;; insert right here
4629 nil)
4631 ;; in the middle of the line
4632 (save-excursion
4633 (end-of-line)
4634 (setq hide-previous (org-invisible-p)))
4635 (org-show-entry)
4636 (let ((split
4637 (org-get-alist-option org-M-RET-may-split-line 'headline))
4638 tags pos)
4639 (cond
4640 (org-insert-heading-respect-content
4641 (org-end-of-subtree nil t)
4642 (open-line 1))
4643 ((org-on-heading-p)
4644 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4645 (setq tags (and (match-end 2) (match-string 2)))
4646 (and (match-end 1)
4647 (delete-region (match-beginning 1) (match-end 1)))
4648 (setq pos (point-at-bol))
4649 (or split (end-of-line 1))
4650 (delete-horizontal-space)
4651 (newline (if blank 2 1))
4652 (when tags
4653 (save-excursion
4654 (goto-char pos)
4655 (end-of-line 1)
4656 (insert " " tags)
4657 (org-set-tags nil 'align))))
4659 (or split (end-of-line 1))
4660 (newline (if blank 2 1)))))))
4661 (insert head) (just-one-space)
4662 (setq pos (point))
4663 (end-of-line 1)
4664 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
4665 (when (and org-insert-heading-respect-content hide-previous)
4666 (save-excursion
4667 (outline-previous-visible-heading 1)
4668 (hide-entry)))
4669 (run-hooks 'org-insert-heading-hook)))))
4671 (defun org-get-heading (&optional no-tags)
4672 "Return the heading of the current entry, without the stars."
4673 (save-excursion
4674 (org-back-to-heading t)
4675 (if (looking-at
4676 (if no-tags
4677 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
4678 "\\*+[ \t]+\\([^\r\n]*\\)"))
4679 (match-string 1) "")))
4681 (defun org-insert-heading-after-current ()
4682 "Insert a new heading with same level as current, after current subtree."
4683 (interactive)
4684 (org-back-to-heading)
4685 (org-insert-heading)
4686 (org-move-subtree-down)
4687 (end-of-line 1))
4689 (defun org-insert-heading-respect-content ()
4690 (interactive)
4691 (let ((org-insert-heading-respect-content t))
4692 (org-insert-heading t)))
4694 (defun org-insert-todo-heading-respect-content (&optional force-state)
4695 (interactive "P")
4696 (let ((org-insert-heading-respect-content t))
4697 (org-insert-todo-heading force-state t)))
4699 (defun org-insert-todo-heading (arg &optional force-heading)
4700 "Insert a new heading with the same level and TODO state as current heading.
4701 If the heading has no TODO state, or if the state is DONE, use the first
4702 state (TODO by default). Also with prefix arg, force first state."
4703 (interactive "P")
4704 (when (or force-heading (not (org-insert-item 'checkbox)))
4705 (org-insert-heading force-heading)
4706 (save-excursion
4707 (org-back-to-heading)
4708 (outline-previous-heading)
4709 (looking-at org-todo-line-regexp))
4710 (if (or arg
4711 (not (match-beginning 2))
4712 (member (match-string 2) org-done-keywords))
4713 (insert (car org-todo-keywords-1) " ")
4714 (insert (match-string 2) " "))
4715 (when org-provide-todo-statistics
4716 (org-update-parent-todo-statistics))))
4718 (defun org-insert-subheading (arg)
4719 "Insert a new subheading and demote it.
4720 Works for outline headings and for plain lists alike."
4721 (interactive "P")
4722 (org-insert-heading arg)
4723 (cond
4724 ((org-on-heading-p) (org-do-demote))
4725 ((org-at-item-p) (org-indent-item 1))))
4727 (defun org-insert-todo-subheading (arg)
4728 "Insert a new subheading with TODO keyword or checkbox and demote it.
4729 Works for outline headings and for plain lists alike."
4730 (interactive "P")
4731 (org-insert-todo-heading arg)
4732 (cond
4733 ((org-on-heading-p) (org-do-demote))
4734 ((org-at-item-p) (org-indent-item 1))))
4736 ;;; Promotion and Demotion
4738 (defun org-promote-subtree ()
4739 "Promote the entire subtree.
4740 See also `org-promote'."
4741 (interactive)
4742 (save-excursion
4743 (org-map-tree 'org-promote))
4744 (org-fix-position-after-promote))
4746 (defun org-demote-subtree ()
4747 "Demote the entire subtree. See `org-demote'.
4748 See also `org-promote'."
4749 (interactive)
4750 (save-excursion
4751 (org-map-tree 'org-demote))
4752 (org-fix-position-after-promote))
4755 (defun org-do-promote ()
4756 "Promote the current heading higher up the tree.
4757 If the region is active in `transient-mark-mode', promote all headings
4758 in the region."
4759 (interactive)
4760 (save-excursion
4761 (if (org-region-active-p)
4762 (org-map-region 'org-promote (region-beginning) (region-end))
4763 (org-promote)))
4764 (org-fix-position-after-promote))
4766 (defun org-do-demote ()
4767 "Demote the current heading lower down the tree.
4768 If the region is active in `transient-mark-mode', demote all headings
4769 in the region."
4770 (interactive)
4771 (save-excursion
4772 (if (org-region-active-p)
4773 (org-map-region 'org-demote (region-beginning) (region-end))
4774 (org-demote)))
4775 (org-fix-position-after-promote))
4777 (defun org-fix-position-after-promote ()
4778 "Make sure that after pro/demotion cursor position is right."
4779 (let ((pos (point)))
4780 (when (save-excursion
4781 (beginning-of-line 1)
4782 (looking-at org-todo-line-regexp)
4783 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
4784 (cond ((eobp) (insert " "))
4785 ((eolp) (insert " "))
4786 ((equal (char-after) ?\ ) (forward-char 1))))))
4788 (defun org-reduced-level (l)
4789 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
4791 (defun org-get-valid-level (level &optional change)
4792 "Rectify a level change under the influence of `org-odd-levels-only'
4793 LEVEL is a current level, CHANGE is by how much the level should be
4794 modified. Even if CHANGE is nil, LEVEL may be returned modified because
4795 even level numbers will become the next higher odd number."
4796 (if org-odd-levels-only
4797 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
4798 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
4799 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
4800 (max 1 (+ level change))))
4802 (if (boundp 'define-obsolete-function-alias)
4803 (if (or (featurep 'xemacs) (< emacs-major-version 23))
4804 (define-obsolete-function-alias 'org-get-legal-level
4805 'org-get-valid-level)
4806 (define-obsolete-function-alias 'org-get-legal-level
4807 'org-get-valid-level "23.1")))
4809 (defun org-promote ()
4810 "Promote the current heading higher up the tree.
4811 If the region is active in `transient-mark-mode', promote all headings
4812 in the region."
4813 (org-back-to-heading t)
4814 (let* ((level (save-match-data (funcall outline-level)))
4815 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
4816 (diff (abs (- level (length up-head) -1))))
4817 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
4818 (replace-match up-head nil t)
4819 ;; Fixup tag positioning
4820 (and org-auto-align-tags (org-set-tags nil t))
4821 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
4823 (defun org-demote ()
4824 "Demote the current heading lower down the tree.
4825 If the region is active in `transient-mark-mode', demote all headings
4826 in the region."
4827 (org-back-to-heading t)
4828 (let* ((level (save-match-data (funcall outline-level)))
4829 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
4830 (diff (abs (- level (length down-head) -1))))
4831 (replace-match down-head nil t)
4832 ;; Fixup tag positioning
4833 (and org-auto-align-tags (org-set-tags nil t))
4834 (if org-adapt-indentation (org-fixup-indentation diff))))
4836 (defun org-map-tree (fun)
4837 "Call FUN for every heading underneath the current one."
4838 (org-back-to-heading)
4839 (let ((level (funcall outline-level)))
4840 (save-excursion
4841 (funcall fun)
4842 (while (and (progn
4843 (outline-next-heading)
4844 (> (funcall outline-level) level))
4845 (not (eobp)))
4846 (funcall fun)))))
4848 (defun org-map-region (fun beg end)
4849 "Call FUN for every heading between BEG and END."
4850 (let ((org-ignore-region t))
4851 (save-excursion
4852 (setq end (copy-marker end))
4853 (goto-char beg)
4854 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
4855 (< (point) end))
4856 (funcall fun))
4857 (while (and (progn
4858 (outline-next-heading)
4859 (< (point) end))
4860 (not (eobp)))
4861 (funcall fun)))))
4863 (defun org-fixup-indentation (diff)
4864 "Change the indentation in the current entry by DIFF
4865 However, if any line in the current entry has no indentation, or if it
4866 would end up with no indentation after the change, nothing at all is done."
4867 (save-excursion
4868 (let ((end (save-excursion (outline-next-heading)
4869 (point-marker)))
4870 (prohibit (if (> diff 0)
4871 "^\\S-"
4872 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
4873 col)
4874 (unless (save-excursion (end-of-line 1)
4875 (re-search-forward prohibit end t))
4876 (while (and (< (point) end)
4877 (re-search-forward "^[ \t]+" end t))
4878 (goto-char (match-end 0))
4879 (setq col (current-column))
4880 (if (< diff 0) (replace-match ""))
4881 (indent-to (+ diff col))))
4882 (move-marker end nil))))
4884 (defun org-convert-to-odd-levels ()
4885 "Convert an org-mode file with all levels allowed to one with odd levels.
4886 This will leave level 1 alone, convert level 2 to level 3, level 3 to
4887 level 5 etc."
4888 (interactive)
4889 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
4890 (let ((org-odd-levels-only nil) n)
4891 (save-excursion
4892 (goto-char (point-min))
4893 (while (re-search-forward "^\\*\\*+ " nil t)
4894 (setq n (- (length (match-string 0)) 2))
4895 (while (>= (setq n (1- n)) 0)
4896 (org-demote))
4897 (end-of-line 1))))))
4900 (defun org-convert-to-oddeven-levels ()
4901 "Convert an org-mode file with only odd levels to one with odd and even levels.
4902 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
4903 section with an even level, conversion would destroy the structure of the file. An error
4904 is signaled in this case."
4905 (interactive)
4906 (goto-char (point-min))
4907 ;; First check if there are no even levels
4908 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
4909 (org-show-context t)
4910 (error "Not all levels are odd in this file. Conversion not possible."))
4911 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
4912 (let ((org-odd-levels-only nil) n)
4913 (save-excursion
4914 (goto-char (point-min))
4915 (while (re-search-forward "^\\*\\*+ " nil t)
4916 (setq n (/ (1- (length (match-string 0))) 2))
4917 (while (>= (setq n (1- n)) 0)
4918 (org-promote))
4919 (end-of-line 1))))))
4921 (defun org-tr-level (n)
4922 "Make N odd if required."
4923 (if org-odd-levels-only (1+ (/ n 2)) n))
4925 ;;; Vertical tree motion, cutting and pasting of subtrees
4927 (defun org-move-subtree-up (&optional arg)
4928 "Move the current subtree up past ARG headlines of the same level."
4929 (interactive "p")
4930 (org-move-subtree-down (- (prefix-numeric-value arg))))
4932 (defun org-move-subtree-down (&optional arg)
4933 "Move the current subtree down past ARG headlines of the same level."
4934 (interactive "p")
4935 (setq arg (prefix-numeric-value arg))
4936 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
4937 'outline-get-last-sibling))
4938 (ins-point (make-marker))
4939 (cnt (abs arg))
4940 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
4941 ;; Select the tree
4942 (org-back-to-heading)
4943 (setq beg0 (point))
4944 (save-excursion
4945 (setq ne-beg (org-back-over-empty-lines))
4946 (setq beg (point)))
4947 (save-match-data
4948 (save-excursion (outline-end-of-heading)
4949 (setq folded (org-invisible-p)))
4950 (outline-end-of-subtree))
4951 (outline-next-heading)
4952 (setq ne-end (org-back-over-empty-lines))
4953 (setq end (point))
4954 (goto-char beg0)
4955 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
4956 ;; include less whitespace
4957 (save-excursion
4958 (goto-char beg)
4959 (forward-line (- ne-beg ne-end))
4960 (setq beg (point))))
4961 ;; Find insertion point, with error handling
4962 (while (> cnt 0)
4963 (or (and (funcall movfunc) (looking-at outline-regexp))
4964 (progn (goto-char beg0)
4965 (error "Cannot move past superior level or buffer limit")))
4966 (setq cnt (1- cnt)))
4967 (if (> arg 0)
4968 ;; Moving forward - still need to move over subtree
4969 (progn (org-end-of-subtree t t)
4970 (save-excursion
4971 (org-back-over-empty-lines)
4972 (or (bolp) (newline)))))
4973 (setq ne-ins (org-back-over-empty-lines))
4974 (move-marker ins-point (point))
4975 (setq txt (buffer-substring beg end))
4976 (org-save-markers-in-region beg end)
4977 (delete-region beg end)
4978 (outline-flag-region (1- beg) beg nil)
4979 (outline-flag-region (1- (point)) (point) nil)
4980 (let ((bbb (point)))
4981 (insert-before-markers txt)
4982 (org-reinstall-markers-in-region bbb)
4983 (move-marker ins-point bbb))
4984 (or (bolp) (insert "\n"))
4985 (setq ins-end (point))
4986 (goto-char ins-point)
4987 (org-skip-whitespace)
4988 (when (and (< arg 0)
4989 (org-first-sibling-p)
4990 (> ne-ins ne-beg))
4991 ;; Move whitespace back to beginning
4992 (save-excursion
4993 (goto-char ins-end)
4994 (let ((kill-whole-line t))
4995 (kill-line (- ne-ins ne-beg)) (point)))
4996 (insert (make-string (- ne-ins ne-beg) ?\n)))
4997 (move-marker ins-point nil)
4998 (org-compact-display-after-subtree-move)
4999 (org-show-empty-lines-in-parent)
5000 (unless folded
5001 (org-show-entry)
5002 (show-children)
5003 (org-cycle-hide-drawers 'children))))
5005 (defvar org-subtree-clip ""
5006 "Clipboard for cut and paste of subtrees.
5007 This is actually only a copy of the kill, because we use the normal kill
5008 ring. We need it to check if the kill was created by `org-copy-subtree'.")
5010 (defvar org-subtree-clip-folded nil
5011 "Was the last copied subtree folded?
5012 This is used to fold the tree back after pasting.")
5014 (defun org-cut-subtree (&optional n)
5015 "Cut the current subtree into the clipboard.
5016 With prefix arg N, cut this many sequential subtrees.
5017 This is a short-hand for marking the subtree and then cutting it."
5018 (interactive "p")
5019 (org-copy-subtree n 'cut))
5021 (defun org-copy-subtree (&optional n cut force-store-markers)
5022 "Cut the current subtree into the clipboard.
5023 With prefix arg N, cut this many sequential subtrees.
5024 This is a short-hand for marking the subtree and then copying it.
5025 If CUT is non-nil, actually cut the subtree.
5026 If FORCE-STORE-MARKERS is non-nil, store the relative locations
5027 of some markers in the region, even if CUT is non-nil. This is
5028 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
5029 (interactive "p")
5030 (let (beg end folded (beg0 (point)))
5031 (if (interactive-p)
5032 (org-back-to-heading nil) ; take what looks like a subtree
5033 (org-back-to-heading t)) ; take what is really there
5034 (org-back-over-empty-lines)
5035 (setq beg (point))
5036 (skip-chars-forward " \t\r\n")
5037 (save-match-data
5038 (save-excursion (outline-end-of-heading)
5039 (setq folded (org-invisible-p)))
5040 (condition-case nil
5041 (outline-forward-same-level (1- n))
5042 (error nil))
5043 (org-end-of-subtree t t))
5044 (org-back-over-empty-lines)
5045 (setq end (point))
5046 (goto-char beg0)
5047 (when (> end beg)
5048 (setq org-subtree-clip-folded folded)
5049 (when (or cut force-store-markers)
5050 (org-save-markers-in-region beg end))
5051 (if cut (kill-region beg end) (copy-region-as-kill beg end))
5052 (setq org-subtree-clip (current-kill 0))
5053 (message "%s: Subtree(s) with %d characters"
5054 (if cut "Cut" "Copied")
5055 (length org-subtree-clip)))))
5057 (defun org-paste-subtree (&optional level tree for-yank)
5058 "Paste the clipboard as a subtree, with modification of headline level.
5059 The entire subtree is promoted or demoted in order to match a new headline
5060 level. By default, the new level is derived from the *visible* headings
5061 before and after the insertion point, and taken to be the inferior headline
5062 level of the two. So if the previous visible heading is level 3 and the
5063 next is level 4 (or vice versa), level 4 will be used for insertion.
5064 This makes sure that the subtree remains an independent subtree and does
5065 not swallow low level entries.
5067 You can also force a different level, either by using a numeric prefix
5068 argument, or by inserting the heading marker by hand. For example, if the
5069 cursor is after \"*****\", then the tree will be shifted to level 5.
5071 If you want to insert the tree as is, just use \\[yank].
5073 If optional TREE is given, use this text instead of the kill ring.
5075 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
5076 move back over whitespace before inserting, and move point to the end of
5077 the inserted text when done."
5078 (interactive "P")
5079 (unless (org-kill-is-subtree-p tree)
5080 (error "%s"
5081 (substitute-command-keys
5082 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
5083 (let* ((visp (not (org-invisible-p)))
5084 (txt (or tree (and kill-ring (current-kill 0))))
5085 (^re (concat "^\\(" outline-regexp "\\)"))
5086 (re (concat "\\(" outline-regexp "\\)"))
5087 (^re_ (concat "\\(\\*+\\)[ \t]*"))
5089 (old-level (if (string-match ^re txt)
5090 (- (match-end 0) (match-beginning 0) 1)
5091 -1))
5092 (force-level (cond (level (prefix-numeric-value level))
5093 ((string-match
5094 ^re_ (buffer-substring (point-at-bol) (point)))
5095 (- (match-end 1) (match-beginning 1)))
5096 (t nil)))
5097 (previous-level (save-excursion
5098 (condition-case nil
5099 (progn
5100 (outline-previous-visible-heading 1)
5101 (if (looking-at re)
5102 (- (match-end 0) (match-beginning 0) 1)
5104 (error 1))))
5105 (next-level (save-excursion
5106 (condition-case nil
5107 (progn
5108 (or (looking-at outline-regexp)
5109 (outline-next-visible-heading 1))
5110 (if (looking-at re)
5111 (- (match-end 0) (match-beginning 0) 1)
5113 (error 1))))
5114 (new-level (or force-level (max previous-level next-level)))
5115 (shift (if (or (= old-level -1)
5116 (= new-level -1)
5117 (= old-level new-level))
5119 (- new-level old-level)))
5120 (delta (if (> shift 0) -1 1))
5121 (func (if (> shift 0) 'org-demote 'org-promote))
5122 (org-odd-levels-only nil)
5123 beg end newend)
5124 ;; Remove the forced level indicator
5125 (if force-level
5126 (delete-region (point-at-bol) (point)))
5127 ;; Paste
5128 (beginning-of-line 1)
5129 (unless for-yank (org-back-over-empty-lines))
5130 (setq beg (point))
5131 (insert-before-markers txt)
5132 (unless (string-match "\n\\'" txt) (insert "\n"))
5133 (setq newend (point))
5134 (org-reinstall-markers-in-region beg)
5135 (setq end (point))
5136 (goto-char beg)
5137 (skip-chars-forward " \t\n\r")
5138 (setq beg (point))
5139 (if (and (org-invisible-p) visp)
5140 (save-excursion (outline-show-heading)))
5141 ;; Shift if necessary
5142 (unless (= shift 0)
5143 (save-restriction
5144 (narrow-to-region beg end)
5145 (while (not (= shift 0))
5146 (org-map-region func (point-min) (point-max))
5147 (setq shift (+ delta shift)))
5148 (goto-char (point-min))
5149 (setq newend (point-max))))
5150 (when (interactive-p)
5151 (message "Clipboard pasted as level %d subtree" new-level))
5152 (if (and kill-ring
5153 (eq org-subtree-clip (current-kill 0))
5154 org-subtree-clip-folded)
5155 ;; The tree was folded before it was killed/copied
5156 (hide-subtree))
5157 (and for-yank (goto-char newend))))
5159 (defun org-kill-is-subtree-p (&optional txt)
5160 "Check if the current kill is an outline subtree, or a set of trees.
5161 Returns nil if kill does not start with a headline, or if the first
5162 headline level is not the largest headline level in the tree.
5163 So this will actually accept several entries of equal levels as well,
5164 which is OK for `org-paste-subtree'.
5165 If optional TXT is given, check this string instead of the current kill."
5166 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
5167 (start-level (and kill
5168 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
5169 org-outline-regexp "\\)")
5170 kill)
5171 (- (match-end 2) (match-beginning 2) 1)))
5172 (re (concat "^" org-outline-regexp))
5173 (start (1+ (or (match-beginning 2) -1))))
5174 (if (not start-level)
5175 (progn
5176 nil) ;; does not even start with a heading
5177 (catch 'exit
5178 (while (setq start (string-match re kill (1+ start)))
5179 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
5180 (throw 'exit nil)))
5181 t))))
5183 (defvar org-markers-to-move nil
5184 "Markers that should be moved with a cut-and-paste operation.
5185 Those markers are stored together with their positions relative to
5186 the start of the region.")
5188 (defun org-save-markers-in-region (beg end)
5189 "Check markers in region.
5190 If these markers are between BEG and END, record their position relative
5191 to BEG, so that after moving the block of text, we can put the markers back
5192 into place.
5193 This function gets called just before an entry or tree gets cut from the
5194 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
5195 called immediately, to move the markers with the entries."
5196 (setq org-markers-to-move nil)
5197 (when (featurep 'org-clock)
5198 (org-clock-save-markers-for-cut-and-paste beg end))
5199 (when (featurep 'org-agenda)
5200 (org-agenda-save-markers-for-cut-and-paste beg end)))
5202 (defun org-check-and-save-marker (marker beg end)
5203 "Check if MARKER is between BEG and END.
5204 If yes, remember the marker and the distance to BEG."
5205 (when (and (marker-buffer marker)
5206 (equal (marker-buffer marker) (current-buffer)))
5207 (if (and (>= marker beg) (< marker end))
5208 (push (cons marker (- marker beg)) org-markers-to-move))))
5210 (defun org-reinstall-markers-in-region (beg)
5211 "Move all remembered markers to their position relative to BEG."
5212 (mapc (lambda (x)
5213 (move-marker (car x) (+ beg (cdr x))))
5214 org-markers-to-move)
5215 (setq org-markers-to-move nil))
5217 (defun org-narrow-to-subtree ()
5218 "Narrow buffer to the current subtree."
5219 (interactive)
5220 (save-excursion
5221 (save-match-data
5222 (narrow-to-region
5223 (progn (org-back-to-heading) (point))
5224 (progn (org-end-of-subtree t) (point))))))
5227 ;;; Outline Sorting
5229 (defun org-sort (with-case)
5230 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
5231 Optional argument WITH-CASE means sort case-sensitively."
5232 (interactive "P")
5233 (if (org-at-table-p)
5234 (org-call-with-arg 'org-table-sort-lines with-case)
5235 (org-call-with-arg 'org-sort-entries-or-items with-case)))
5237 (defun org-sort-remove-invisible (s)
5238 (remove-text-properties 0 (length s) org-rm-props s)
5239 (while (string-match org-bracket-link-regexp s)
5240 (setq s (replace-match (if (match-end 2)
5241 (match-string 3 s)
5242 (match-string 1 s)) t t s)))
5245 (defvar org-priority-regexp) ; defined later in the file
5247 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
5248 "Sort entries on a certain level of an outline tree.
5249 If there is an active region, the entries in the region are sorted.
5250 Else, if the cursor is before the first entry, sort the top-level items.
5251 Else, the children of the entry at point are sorted.
5253 Sorting can be alphabetically, numerically, and by date/time as given by
5254 the first time stamp in the entry. The command prompts for the sorting
5255 type unless it has been given to the function through the SORTING-TYPE
5256 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
5257 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
5258 called with point at the beginning of the record. It must return either
5259 a string or a number that should serve as the sorting key for that record.
5261 Comparing entries ignores case by default. However, with an optional argument
5262 WITH-CASE, the sorting considers case as well."
5263 (interactive "P")
5264 (let ((case-func (if with-case 'identity 'downcase))
5265 start beg end stars re re2
5266 txt what tmp plain-list-p)
5267 ;; Find beginning and end of region to sort
5268 (cond
5269 ((org-region-active-p)
5270 ;; we will sort the region
5271 (setq end (region-end)
5272 what "region")
5273 (goto-char (region-beginning))
5274 (if (not (org-on-heading-p)) (outline-next-heading))
5275 (setq start (point)))
5276 ((org-at-item-p)
5277 ;; we will sort this plain list
5278 (org-beginning-of-item-list) (setq start (point))
5279 (org-end-of-item-list) (setq end (point))
5280 (goto-char start)
5281 (setq plain-list-p t
5282 what "plain list"))
5283 ((or (org-on-heading-p)
5284 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
5285 ;; we will sort the children of the current headline
5286 (org-back-to-heading)
5287 (setq start (point)
5288 end (progn (org-end-of-subtree t t)
5289 (org-back-over-empty-lines)
5290 (point))
5291 what "children")
5292 (goto-char start)
5293 (show-subtree)
5294 (outline-next-heading))
5296 ;; we will sort the top-level entries in this file
5297 (goto-char (point-min))
5298 (or (org-on-heading-p) (outline-next-heading))
5299 (setq start (point) end (point-max) what "top-level")
5300 (goto-char start)
5301 (show-all)))
5303 (setq beg (point))
5304 (if (>= beg end) (error "Nothing to sort"))
5306 (unless plain-list-p
5307 (looking-at "\\(\\*+\\)")
5308 (setq stars (match-string 1)
5309 re (concat "^" (regexp-quote stars) " +")
5310 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
5311 txt (buffer-substring beg end))
5312 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
5313 (if (and (not (equal stars "*")) (string-match re2 txt))
5314 (error "Region to sort contains a level above the first entry")))
5316 (unless sorting-type
5317 (message
5318 (if plain-list-p
5319 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
5320 "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:")
5321 what)
5322 (setq sorting-type (read-char-exclusive))
5324 (and (= (downcase sorting-type) ?f)
5325 (setq getkey-func
5326 (completing-read "Sort using function: "
5327 obarray 'fboundp t nil nil))
5328 (setq getkey-func (intern getkey-func)))
5330 (and (= (downcase sorting-type) ?r)
5331 (setq property
5332 (completing-read "Property: "
5333 (mapcar 'list (org-buffer-property-keys t))
5334 nil t))))
5336 (message "Sorting entries...")
5338 (save-restriction
5339 (narrow-to-region start end)
5341 (let ((dcst (downcase sorting-type))
5342 (now (current-time)))
5343 (sort-subr
5344 (/= dcst sorting-type)
5345 ;; This function moves to the beginning character of the "record" to
5346 ;; be sorted.
5347 (if plain-list-p
5348 (lambda nil
5349 (if (org-at-item-p) t (goto-char (point-max))))
5350 (lambda nil
5351 (if (re-search-forward re nil t)
5352 (goto-char (match-beginning 0))
5353 (goto-char (point-max)))))
5354 ;; This function moves to the last character of the "record" being
5355 ;; sorted.
5356 (if plain-list-p
5357 'org-end-of-item
5358 (lambda nil
5359 (save-match-data
5360 (condition-case nil
5361 (outline-forward-same-level 1)
5362 (error
5363 (goto-char (point-max)))))))
5365 ;; This function returns the value that gets sorted against.
5366 (if plain-list-p
5367 (lambda nil
5368 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
5369 (cond
5370 ((= dcst ?n)
5371 (string-to-number (buffer-substring (match-end 0)
5372 (point-at-eol))))
5373 ((= dcst ?a)
5374 (buffer-substring (match-end 0) (point-at-eol)))
5375 ((= dcst ?t)
5376 (if (re-search-forward org-ts-regexp
5377 (point-at-eol) t)
5378 (org-time-string-to-time (match-string 0))
5379 now))
5380 ((= dcst ?f)
5381 (if getkey-func
5382 (progn
5383 (setq tmp (funcall getkey-func))
5384 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5385 tmp)
5386 (error "Invalid key function `%s'" getkey-func)))
5387 (t (error "Invalid sorting type `%c'" sorting-type)))))
5388 (lambda nil
5389 (cond
5390 ((= dcst ?n)
5391 (if (looking-at org-complex-heading-regexp)
5392 (string-to-number (match-string 4))
5393 nil))
5394 ((= dcst ?a)
5395 (if (looking-at org-complex-heading-regexp)
5396 (funcall case-func (match-string 4))
5397 nil))
5398 ((= dcst ?t)
5399 (if (re-search-forward org-ts-regexp
5400 (save-excursion
5401 (forward-line 2)
5402 (point)) t)
5403 (org-time-string-to-time (match-string 0))
5404 now))
5405 ((= dcst ?p)
5406 (if (re-search-forward org-priority-regexp (point-at-eol) t)
5407 (string-to-char (match-string 2))
5408 org-default-priority))
5409 ((= dcst ?r)
5410 (or (org-entry-get nil property) ""))
5411 ((= dcst ?o)
5412 (if (looking-at org-complex-heading-regexp)
5413 (- 9999 (length (member (match-string 2)
5414 org-todo-keywords-1)))))
5415 ((= dcst ?f)
5416 (if getkey-func
5417 (progn
5418 (setq tmp (funcall getkey-func))
5419 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5420 tmp)
5421 (error "Invalid key function `%s'" getkey-func)))
5422 (t (error "Invalid sorting type `%c'" sorting-type)))))
5424 (cond
5425 ((= dcst ?a) 'string<)
5426 ((= dcst ?t) 'time-less-p)
5427 (t nil)))))
5428 (message "Sorting entries...done")))
5430 (defun org-do-sort (table what &optional with-case sorting-type)
5431 "Sort TABLE of WHAT according to SORTING-TYPE.
5432 The user will be prompted for the SORTING-TYPE if the call to this
5433 function does not specify it. WHAT is only for the prompt, to indicate
5434 what is being sorted. The sorting key will be extracted from
5435 the car of the elements of the table.
5436 If WITH-CASE is non-nil, the sorting will be case-sensitive."
5437 (unless sorting-type
5438 (message
5439 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
5440 what)
5441 (setq sorting-type (read-char-exclusive)))
5442 (let ((dcst (downcase sorting-type))
5443 extractfun comparefun)
5444 ;; Define the appropriate functions
5445 (cond
5446 ((= dcst ?n)
5447 (setq extractfun 'string-to-number
5448 comparefun (if (= dcst sorting-type) '< '>)))
5449 ((= dcst ?a)
5450 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
5451 (lambda(x) (downcase (org-sort-remove-invisible x))))
5452 comparefun (if (= dcst sorting-type)
5453 'string<
5454 (lambda (a b) (and (not (string< a b))
5455 (not (string= a b)))))))
5456 ((= dcst ?t)
5457 (setq extractfun
5458 (lambda (x)
5459 (if (string-match org-ts-regexp x)
5460 (time-to-seconds
5461 (org-time-string-to-time (match-string 0 x)))
5463 comparefun (if (= dcst sorting-type) '< '>)))
5464 (t (error "Invalid sorting type `%c'" sorting-type)))
5466 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5467 table)
5468 (lambda (a b) (funcall comparefun (car a) (car b))))))
5470 ;;; Editing source examples
5472 (defvar org-exit-edit-mode-map (make-sparse-keymap))
5473 (define-key org-exit-edit-mode-map "\C-c'" 'org-edit-src-exit)
5474 (defvar org-edit-src-force-single-line nil)
5475 (defvar org-edit-src-from-org-mode nil)
5476 (defvar org-edit-src-picture nil)
5478 (define-minor-mode org-exit-edit-mode
5479 "Minor mode installing a single key binding, \"C-c '\" to exit special edit.")
5481 (defun org-edit-src-code ()
5482 "Edit the source code example at point.
5483 An indirect buffer is created, and that buffer is then narrowed to the
5484 example at point and switched to the correct language mode. When done,
5485 exit by killing the buffer with \\[org-edit-src-exit]."
5486 (interactive)
5487 (let ((line (org-current-line))
5488 (case-fold-search t)
5489 (msg (substitute-command-keys
5490 "Edit, then exit with C-c ' (C-c and single quote)"))
5491 (info (org-edit-src-find-region-and-lang))
5492 (org-mode-p (eq major-mode 'org-mode))
5493 beg end lang lang-f single)
5494 (if (not info)
5496 (setq beg (nth 0 info)
5497 end (nth 1 info)
5498 lang (nth 2 info)
5499 single (nth 3 info)
5500 lang-f (intern (concat lang "-mode")))
5501 (unless (functionp lang-f)
5502 (error "No such language mode: %s" lang-f))
5503 (goto-line line)
5504 (if (get-buffer "*Org Edit Src Example*")
5505 (kill-buffer "*Org Edit Src Example*"))
5506 (switch-to-buffer (make-indirect-buffer (current-buffer)
5507 "*Org Edit Src Example*"))
5508 (narrow-to-region beg end)
5509 (remove-text-properties beg end '(display nil invisible nil
5510 intangible nil))
5511 (let ((org-inhibit-startup t))
5512 (funcall lang-f))
5513 (set (make-local-variable 'org-edit-src-force-single-line) single)
5514 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5515 (when org-mode-p
5516 (goto-char (point-min))
5517 (while (re-search-forward "^," nil t)
5518 (replace-match "")))
5519 (goto-line line)
5520 (org-exit-edit-mode)
5521 (org-set-local 'header-line-format msg)
5522 (message "%s" msg)
5523 t)))
5525 (defun org-edit-fixed-width-region ()
5526 "Edit the fixed-width ascii drawing at point.
5527 This must be a region where each line starts with ca colon followed by
5528 a space character.
5529 An indirect buffer is created, and that buffer is then narrowed to the
5530 example at point and switched to artist-mode. When done,
5531 exit by killing the buffer with \\[org-edit-src-exit]."
5532 (interactive)
5533 (let ((line (org-current-line))
5534 (case-fold-search t)
5535 (msg (substitute-command-keys
5536 "Edit, then exit with C-c ' (C-c and single quote)"))
5537 (org-mode-p (eq major-mode 'org-mode))
5538 beg end lang lang-f)
5539 (beginning-of-line 1)
5540 (if (looking-at "[ \t]*[^:\n \t]")
5542 (if (looking-at "[ \t]*\\(\n\\|\\'\\)]")
5543 (setq beg (point) end (match-end 0))
5544 (save-excursion
5545 (if (re-search-backward "^[ \t]*[^:]" nil 'move)
5546 (setq beg (point-at-bol 2))
5547 (setq beg (point))))
5548 (save-excursion
5549 (if (re-search-forward "^[ \t]*[^:]" nil 'move)
5550 (setq end (1- (match-beginning 0)))
5551 (setq end (point))))
5552 (goto-line line)
5553 (if (get-buffer "*Org Edit Picture*")
5554 (kill-buffer "*Org Edit Picture*"))
5555 (switch-to-buffer (make-indirect-buffer (current-buffer)
5556 "*Org Edit Picture*"))
5557 (narrow-to-region beg end)
5558 (remove-text-properties beg end '(display nil invisible nil
5559 intangible nil))
5560 (when (fboundp 'font-lock-unfontify-region)
5561 (font-lock-unfontify-region (point-min) (point-max)))
5562 (cond
5563 ((eq org-edit-fixed-width-region-mode 'artist-mode)
5564 (fundamental-mode)
5565 (artist-mode 1))
5566 (t (funcall org-edit-fixed-width-region-mode)))
5567 (set (make-local-variable 'org-edit-src-force-single-line) nil)
5568 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5569 (set (make-local-variable 'org-edit-src-picture) t)
5570 (goto-char (point-min))
5571 (while (re-search-forward "^[ \t]*: " nil t)
5572 (replace-match ""))
5573 (goto-line line)
5574 (org-exit-edit-mode)
5575 (org-set-local 'header-line-format msg)
5576 (message "%s" msg)
5577 t))))
5580 (defun org-edit-src-find-region-and-lang ()
5581 "Find the region and language for a local edit.
5582 Return a list with beginning and end of the region, a string representing
5583 the language, a switch telling of the content should be in a single line."
5584 (let ((re-list
5585 (append
5586 org-edit-src-region-extra
5588 ("<src\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</src>" lang)
5589 ("<literal\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</literal>" style)
5590 ("<example>[ \t]*\n?" "\n?[ \t]*</example>" "fundamental")
5591 ("<lisp>[ \t]*\n?" "\n?[ \t]*</lisp>" "emacs-lisp")
5592 ("<perl>[ \t]*\n?" "\n?[ \t]*</perl>" "perl")
5593 ("<python>[ \t]*\n?" "\n?[ \t]*</python>" "python")
5594 ("<ruby>[ \t]*\n?" "\n?[ \t]*</ruby>" "ruby")
5595 ("^#\\+begin_src\\( \\([^ \t\n]+\\)\\)?.*\n" "\n#\\+end_src" 2)
5596 ("^#\\+begin_example.*\n" "\n#\\+end_example" "fundamental")
5597 ("^#\\+html:" "\n" "html" single-line)
5598 ("^#\\+begin_html.*\n" "\n#\\+end_html" "html")
5599 ("^#\\+begin_latex.*\n" "\n#\\+end_latex" "latex")
5600 ("^#\\+latex:" "\n" "latex" single-line)
5601 ("^#\\+begin_ascii.*\n" "\n#\\+end_ascii" "fundamental")
5602 ("^#\\+ascii:" "\n" "ascii" single-line)
5604 (pos (point))
5605 re re1 re2 single beg end lang)
5606 (catch 'exit
5607 (while (setq entry (pop re-list))
5608 (setq re1 (car entry) re2 (nth 1 entry) lang (nth 2 entry)
5609 single (nth 3 entry))
5610 (save-excursion
5611 (if (or (looking-at re1)
5612 (re-search-backward re1 nil t))
5613 (progn
5614 (setq beg (match-end 0) lang (org-edit-src-get-lang lang))
5615 (if (and (re-search-forward re2 nil t)
5616 (>= (match-end 0) pos))
5617 (throw 'exit (list beg (match-beginning 0) lang single))))
5618 (if (or (looking-at re2)
5619 (re-search-forward re2 nil t))
5620 (progn
5621 (setq end (match-beginning 0))
5622 (if (and (re-search-backward re1 nil t)
5623 (<= (match-beginning 0) pos))
5624 (throw 'exit
5625 (list (match-end 0) end
5626 (org-edit-src-get-lang lang) single)))))))))))
5628 (defun org-edit-src-get-lang (lang)
5629 "Extract the src language."
5630 (let ((m (match-string 0)))
5631 (cond
5632 ((stringp lang) lang)
5633 ((integerp lang) (match-string lang))
5634 ((and (eq lang 'lang)
5635 (string-match "\\<lang=\"\\([^ \t\n\"]+\\)\"" m))
5636 (match-string 1 m))
5637 ((and (eq lang 'style)
5638 (string-match "\\<style=\"\\([^ \t\n\"]+\\)\"" m))
5639 (match-string 1 m))
5640 (t "fundamental"))))
5642 (defun org-edit-src-exit ()
5643 "Exit special edit and protect problematic lines."
5644 (interactive)
5645 (unless (buffer-base-buffer (current-buffer))
5646 (error "This is not an indirect buffer, something is wrong..."))
5647 (unless (> (point-min) 1)
5648 (error "This buffer is not narrowed, something is wrong..."))
5649 (goto-char (point-min))
5650 (if (looking-at "[ \t\n]*\n") (replace-match ""))
5651 (if (re-search-forward "\n[ \t\n]*\\'" nil t) (replace-match ""))
5652 (when (org-bound-and-true-p org-edit-src-force-single-line)
5653 (goto-char (point-min))
5654 (while (re-search-forward "\n" nil t)
5655 (replace-match " "))
5656 (goto-char (point-min))
5657 (if (looking-at "\\s-*") (replace-match " "))
5658 (if (re-search-forward "\\s-+\\'" nil t)
5659 (replace-match "")))
5660 (when (org-bound-and-true-p org-edit-src-from-org-mode)
5661 (goto-char (point-min))
5662 (while (re-search-forward (if (org-mode-p) "^\\(.\\)" "^\\([*#]\\)") nil t)
5663 (replace-match ",\\1"))
5664 (when font-lock-mode
5665 (font-lock-unfontify-region (point-min) (point-max)))
5666 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
5667 (when (org-bound-and-true-p org-edit-src-picture)
5668 (goto-char (point-min))
5669 (while (re-search-forward "^" nil t)
5670 (replace-match ": "))
5671 (when font-lock-mode
5672 (font-lock-unfontify-region (point-min) (point-max)))
5673 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
5674 (kill-buffer (current-buffer))
5675 (and (org-mode-p) (org-restart-font-lock)))
5678 ;;; The orgstruct minor mode
5680 ;; Define a minor mode which can be used in other modes in order to
5681 ;; integrate the org-mode structure editing commands.
5683 ;; This is really a hack, because the org-mode structure commands use
5684 ;; keys which normally belong to the major mode. Here is how it
5685 ;; works: The minor mode defines all the keys necessary to operate the
5686 ;; structure commands, but wraps the commands into a function which
5687 ;; tests if the cursor is currently at a headline or a plain list
5688 ;; item. If that is the case, the structure command is used,
5689 ;; temporarily setting many Org-mode variables like regular
5690 ;; expressions for filling etc. However, when any of those keys is
5691 ;; used at a different location, function uses `key-binding' to look
5692 ;; up if the key has an associated command in another currently active
5693 ;; keymap (minor modes, major mode, global), and executes that
5694 ;; command. There might be problems if any of the keys is otherwise
5695 ;; used as a prefix key.
5697 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
5698 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
5699 ;; addresses this by checking explicitly for both bindings.
5701 (defvar orgstruct-mode-map (make-sparse-keymap)
5702 "Keymap for the minor `orgstruct-mode'.")
5704 (defvar org-local-vars nil
5705 "List of local variables, for use by `orgstruct-mode'")
5707 ;;;###autoload
5708 (define-minor-mode orgstruct-mode
5709 "Toggle the minor more `orgstruct-mode'.
5710 This mode is for using Org-mode structure commands in other modes.
5711 The following key behave as if Org-mode was active, if the cursor
5712 is on a headline, or on a plain list item (both in the definition
5713 of Org-mode).
5715 M-up Move entry/item up
5716 M-down Move entry/item down
5717 M-left Promote
5718 M-right Demote
5719 M-S-up Move entry/item up
5720 M-S-down Move entry/item down
5721 M-S-left Promote subtree
5722 M-S-right Demote subtree
5723 M-q Fill paragraph and items like in Org-mode
5724 C-c ^ Sort entries
5725 C-c - Cycle list bullet
5726 TAB Cycle item visibility
5727 M-RET Insert new heading/item
5728 S-M-RET Insert new TODO heading / Chekbox item
5729 C-c C-c Set tags / toggle checkbox"
5730 nil " OrgStruct" nil
5731 (org-load-modules-maybe)
5732 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
5734 ;;;###autoload
5735 (defun turn-on-orgstruct ()
5736 "Unconditionally turn on `orgstruct-mode'."
5737 (orgstruct-mode 1))
5739 ;;;###autoload
5740 (defun turn-on-orgstruct++ ()
5741 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
5742 In addition to setting orgstruct-mode, this also exports all indentation and
5743 autofilling variables from org-mode into the buffer. Note that turning
5744 off orgstruct-mode will *not* remove these additional settings."
5745 (orgstruct-mode 1)
5746 (let (var val)
5747 (mapc
5748 (lambda (x)
5749 (when (string-match
5750 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
5751 (symbol-name (car x)))
5752 (setq var (car x) val (nth 1 x))
5753 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
5754 org-local-vars)))
5756 (defun orgstruct-error ()
5757 "Error when there is no default binding for a structure key."
5758 (interactive)
5759 (error "This key has no function outside structure elements"))
5761 (defun orgstruct-setup ()
5762 "Setup orgstruct keymaps."
5763 (let ((nfunc 0)
5764 (bindings
5765 (list
5766 '([(meta up)] org-metaup)
5767 '([(meta down)] org-metadown)
5768 '([(meta left)] org-metaleft)
5769 '([(meta right)] org-metaright)
5770 '([(meta shift up)] org-shiftmetaup)
5771 '([(meta shift down)] org-shiftmetadown)
5772 '([(meta shift left)] org-shiftmetaleft)
5773 '([(meta shift right)] org-shiftmetaright)
5774 '([(shift up)] org-shiftup)
5775 '([(shift down)] org-shiftdown)
5776 '("\C-c\C-c" org-ctrl-c-ctrl-c)
5777 '("\M-q" fill-paragraph)
5778 '("\C-c^" org-sort)
5779 '("\C-c-" org-cycle-list-bullet)))
5780 elt key fun cmd)
5781 (while (setq elt (pop bindings))
5782 (setq nfunc (1+ nfunc))
5783 (setq key (org-key (car elt))
5784 fun (nth 1 elt)
5785 cmd (orgstruct-make-binding fun nfunc key))
5786 (org-defkey orgstruct-mode-map key cmd))
5788 ;; Special treatment needed for TAB and RET
5789 (org-defkey orgstruct-mode-map [(tab)]
5790 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
5791 (org-defkey orgstruct-mode-map "\C-i"
5792 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
5794 (org-defkey orgstruct-mode-map "\M-\C-m"
5795 (orgstruct-make-binding 'org-insert-heading 105
5796 "\M-\C-m" [(meta return)]))
5797 (org-defkey orgstruct-mode-map [(meta return)]
5798 (orgstruct-make-binding 'org-insert-heading 106
5799 [(meta return)] "\M-\C-m"))
5801 (org-defkey orgstruct-mode-map [(shift meta return)]
5802 (orgstruct-make-binding 'org-insert-todo-heading 107
5803 [(meta return)] "\M-\C-m"))
5805 (unless org-local-vars
5806 (setq org-local-vars (org-get-local-variables)))
5810 (defun orgstruct-make-binding (fun n &rest keys)
5811 "Create a function for binding in the structure minor mode.
5812 FUN is the command to call inside a table. N is used to create a unique
5813 command name. KEYS are keys that should be checked in for a command
5814 to execute outside of tables."
5815 (eval
5816 (list 'defun
5817 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
5818 '(arg)
5819 (concat "In Structure, run `" (symbol-name fun) "'.\n"
5820 "Outside of structure, run the binding of `"
5821 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
5822 "'.")
5823 '(interactive "p")
5824 (list 'if
5825 '(org-context-p 'headline 'item)
5826 (list 'org-run-like-in-org-mode (list 'quote fun))
5827 (list 'let '(orgstruct-mode)
5828 (list 'call-interactively
5829 (append '(or)
5830 (mapcar (lambda (k)
5831 (list 'key-binding k))
5832 keys)
5833 '('orgstruct-error))))))))
5835 (defun org-context-p (&rest contexts)
5836 "Check if local context is any of CONTEXTS.
5837 Possible values in the list of contexts are `table', `headline', and `item'."
5838 (let ((pos (point)))
5839 (goto-char (point-at-bol))
5840 (prog1 (or (and (memq 'table contexts)
5841 (looking-at "[ \t]*|"))
5842 (and (memq 'headline contexts)
5843 ;;????????? (looking-at "\\*+"))
5844 (looking-at outline-regexp))
5845 (and (memq 'item contexts)
5846 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
5847 (goto-char pos))))
5849 (defun org-get-local-variables ()
5850 "Return a list of all local variables in an org-mode buffer."
5851 (let (varlist)
5852 (with-current-buffer (get-buffer-create "*Org tmp*")
5853 (erase-buffer)
5854 (org-mode)
5855 (setq varlist (buffer-local-variables)))
5856 (kill-buffer "*Org tmp*")
5857 (delq nil
5858 (mapcar
5859 (lambda (x)
5860 (setq x
5861 (if (symbolp x)
5862 (list x)
5863 (list (car x) (list 'quote (cdr x)))))
5864 (if (string-match
5865 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
5866 (symbol-name (car x)))
5867 x nil))
5868 varlist))))
5870 ;;;###autoload
5871 (defun org-run-like-in-org-mode (cmd)
5872 (org-load-modules-maybe)
5873 (unless org-local-vars
5874 (setq org-local-vars (org-get-local-variables)))
5875 (eval (list 'let org-local-vars
5876 (list 'call-interactively (list 'quote cmd)))))
5878 ;;;; Archiving
5880 (defun org-get-category (&optional pos)
5881 "Get the category applying to position POS."
5882 (get-text-property (or pos (point)) 'org-category))
5884 (defun org-refresh-category-properties ()
5885 "Refresh category text properties in the buffer."
5886 (let ((def-cat (cond
5887 ((null org-category)
5888 (if buffer-file-name
5889 (file-name-sans-extension
5890 (file-name-nondirectory buffer-file-name))
5891 "???"))
5892 ((symbolp org-category) (symbol-name org-category))
5893 (t org-category)))
5894 beg end cat pos optionp)
5895 (org-unmodified
5896 (save-excursion
5897 (save-restriction
5898 (widen)
5899 (goto-char (point-min))
5900 (put-text-property (point) (point-max) 'org-category def-cat)
5901 (while (re-search-forward
5902 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
5903 (setq pos (match-end 0)
5904 optionp (equal (char-after (match-beginning 0)) ?#)
5905 cat (org-trim (match-string 2)))
5906 (if optionp
5907 (setq beg (point-at-bol) end (point-max))
5908 (org-back-to-heading t)
5909 (setq beg (point) end (org-end-of-subtree t t)))
5910 (put-text-property beg end 'org-category cat)
5911 (goto-char pos)))))))
5914 ;;;; Link Stuff
5916 ;;; Link abbreviations
5918 (defun org-link-expand-abbrev (link)
5919 "Apply replacements as defined in `org-link-abbrev-alist."
5920 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
5921 (let* ((key (match-string 1 link))
5922 (as (or (assoc key org-link-abbrev-alist-local)
5923 (assoc key org-link-abbrev-alist)))
5924 (tag (and (match-end 2) (match-string 3 link)))
5925 rpl)
5926 (if (not as)
5927 link
5928 (setq rpl (cdr as))
5929 (cond
5930 ((symbolp rpl) (funcall rpl tag))
5931 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
5932 (t (concat rpl tag)))))
5933 link))
5935 ;;; Storing and inserting links
5937 (defvar org-insert-link-history nil
5938 "Minibuffer history for links inserted with `org-insert-link'.")
5940 (defvar org-stored-links nil
5941 "Contains the links stored with `org-store-link'.")
5943 (defvar org-store-link-plist nil
5944 "Plist with info about the most recently link created with `org-store-link'.")
5946 (defvar org-link-protocols nil
5947 "Link protocols added to Org-mode using `org-add-link-type'.")
5949 (defvar org-store-link-functions nil
5950 "List of functions that are called to create and store a link.
5951 Each function will be called in turn until one returns a non-nil
5952 value. Each function should check if it is responsible for creating
5953 this link (for example by looking at the major mode).
5954 If not, it must exit and return nil.
5955 If yes, it should return a non-nil value after a calling
5956 `org-store-link-props' with a list of properties and values.
5957 Special properties are:
5959 :type The link prefix. like \"http\". This must be given.
5960 :link The link, like \"http://www.astro.uva.nl/~dominik\".
5961 This is obligatory as well.
5962 :description Optional default description for the second pair
5963 of brackets in an Org-mode link. The user can still change
5964 this when inserting this link into an Org-mode buffer.
5966 In addition to these, any additional properties can be specified
5967 and then used in remember templates.")
5969 (defun org-add-link-type (type &optional follow export)
5970 "Add TYPE to the list of `org-link-types'.
5971 Re-compute all regular expressions depending on `org-link-types'
5973 FOLLOW and EXPORT are two functions.
5975 FOLLOW should take the link path as the single argument and do whatever
5976 is necessary to follow the link, for example find a file or display
5977 a mail message.
5979 EXPORT should format the link path for export to one of the export formats.
5980 It should be a function accepting three arguments:
5982 path the path of the link, the text after the prefix (like \"http:\")
5983 desc the description of the link, if any, nil if there was no descripton
5984 format the export format, a symbol like `html' or `latex'.
5986 The function may use the FORMAT information to return different values
5987 depending on the format. The return value will be put literally into
5988 the exported file.
5989 Org-mode has a built-in default for exporting links. If you are happy with
5990 this default, there is no need to define an export function for the link
5991 type. For a simple example of an export function, see `org-bbdb.el'."
5992 (add-to-list 'org-link-types type t)
5993 (org-make-link-regexps)
5994 (if (assoc type org-link-protocols)
5995 (setcdr (assoc type org-link-protocols) (list follow export))
5996 (push (list type follow export) org-link-protocols)))
5999 ;;;###autoload
6000 (defun org-store-link (arg)
6001 "\\<org-mode-map>Store an org-link to the current location.
6002 This link is added to `org-stored-links' and can later be inserted
6003 into an org-buffer with \\[org-insert-link].
6005 For some link types, a prefix arg is interpreted:
6006 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
6007 For file links, arg negates `org-context-in-file-links'."
6008 (interactive "P")
6009 (org-load-modules-maybe)
6010 (setq org-store-link-plist nil) ; reset
6011 (let (link cpltxt desc description search txt)
6012 (cond
6014 ((run-hook-with-args-until-success 'org-store-link-functions)
6015 (setq link (plist-get org-store-link-plist :link)
6016 desc (or (plist-get org-store-link-plist :description) link)))
6018 ((eq major-mode 'calendar-mode)
6019 (let ((cd (calendar-cursor-to-date)))
6020 (setq link
6021 (format-time-string
6022 (car org-time-stamp-formats)
6023 (apply 'encode-time
6024 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6025 nil nil nil))))
6026 (org-store-link-props :type "calendar" :date cd)))
6028 ((eq major-mode 'w3-mode)
6029 (setq cpltxt (url-view-url t)
6030 link (org-make-link cpltxt))
6031 (org-store-link-props :type "w3" :url (url-view-url t)))
6033 ((eq major-mode 'w3m-mode)
6034 (setq cpltxt (or w3m-current-title w3m-current-url)
6035 link (org-make-link w3m-current-url))
6036 (org-store-link-props :type "w3m" :url (url-view-url t)))
6038 ((setq search (run-hook-with-args-until-success
6039 'org-create-file-search-functions))
6040 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6041 "::" search))
6042 (setq cpltxt (or description link)))
6044 ((eq major-mode 'image-mode)
6045 (setq cpltxt (concat "file:"
6046 (abbreviate-file-name buffer-file-name))
6047 link (org-make-link cpltxt))
6048 (org-store-link-props :type "image" :file buffer-file-name))
6050 ((eq major-mode 'dired-mode)
6051 ;; link to the file in the current line
6052 (setq cpltxt (concat "file:"
6053 (abbreviate-file-name
6054 (expand-file-name
6055 (dired-get-filename nil t))))
6056 link (org-make-link cpltxt)))
6058 ((and buffer-file-name (org-mode-p))
6059 ;; Just link to current headline
6060 (setq cpltxt (concat "file:"
6061 (abbreviate-file-name buffer-file-name)))
6062 ;; Add a context search string
6063 (when (org-xor org-context-in-file-links arg)
6064 ;; Check if we are on a target
6065 (if (org-in-regexp "<<\\(.*?\\)>>")
6066 (setq cpltxt (concat cpltxt "::" (match-string 1)))
6067 (setq txt (cond
6068 ((org-on-heading-p) nil)
6069 ((org-region-active-p)
6070 (buffer-substring (region-beginning) (region-end)))
6071 (t nil)))
6072 (when (or (null txt) (string-match "\\S-" txt))
6073 (setq cpltxt
6074 (concat cpltxt "::"
6075 (condition-case nil
6076 (org-make-org-heading-search-string txt)
6077 (error "")))
6078 desc "NONE"))))
6079 (if (string-match "::\\'" cpltxt)
6080 (setq cpltxt (substring cpltxt 0 -2)))
6081 (setq link (org-make-link cpltxt)))
6083 ((buffer-file-name (buffer-base-buffer))
6084 ;; Just link to this file here.
6085 (setq cpltxt (concat "file:"
6086 (abbreviate-file-name
6087 (buffer-file-name (buffer-base-buffer)))))
6088 ;; Add a context string
6089 (when (org-xor org-context-in-file-links arg)
6090 (setq txt (if (org-region-active-p)
6091 (buffer-substring (region-beginning) (region-end))
6092 (buffer-substring (point-at-bol) (point-at-eol))))
6093 ;; Only use search option if there is some text.
6094 (when (string-match "\\S-" txt)
6095 (setq cpltxt
6096 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6097 desc "NONE")))
6098 (setq link (org-make-link cpltxt)))
6100 ((interactive-p)
6101 (error "Cannot link to a buffer which is not visiting a file"))
6103 (t (setq link nil)))
6105 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6106 (setq link (or link cpltxt)
6107 desc (or desc cpltxt))
6108 (if (equal desc "NONE") (setq desc nil))
6110 (if (and (interactive-p) link)
6111 (progn
6112 (setq org-stored-links
6113 (cons (list link desc) org-stored-links))
6114 (message "Stored: %s" (or desc link)))
6115 (and link (org-make-link-string link desc)))))
6117 (defun org-store-link-props (&rest plist)
6118 "Store link properties, extract names and addresses."
6119 (let (x adr)
6120 (when (setq x (plist-get plist :from))
6121 (setq adr (mail-extract-address-components x))
6122 (plist-put plist :fromname (car adr))
6123 (plist-put plist :fromaddress (nth 1 adr)))
6124 (when (setq x (plist-get plist :to))
6125 (setq adr (mail-extract-address-components x))
6126 (plist-put plist :toname (car adr))
6127 (plist-put plist :toaddress (nth 1 adr))))
6128 (let ((from (plist-get plist :from))
6129 (to (plist-get plist :to)))
6130 (when (and from to org-from-is-user-regexp)
6131 (plist-put plist :fromto
6132 (if (string-match org-from-is-user-regexp from)
6133 (concat "to %t")
6134 (concat "from %f")))))
6135 (setq org-store-link-plist plist))
6137 (defun org-add-link-props (&rest plist)
6138 "Add these properties to the link property list."
6139 (let (key value)
6140 (while plist
6141 (setq key (pop plist) value (pop plist))
6142 (setq org-store-link-plist
6143 (plist-put org-store-link-plist key value)))))
6145 (defun org-email-link-description (&optional fmt)
6146 "Return the description part of an email link.
6147 This takes information from `org-store-link-plist' and formats it
6148 according to FMT (default from `org-email-link-description-format')."
6149 (setq fmt (or fmt org-email-link-description-format))
6150 (let* ((p org-store-link-plist)
6151 (to (plist-get p :toaddress))
6152 (from (plist-get p :fromaddress))
6153 (table
6154 (list
6155 (cons "%c" (plist-get p :fromto))
6156 (cons "%F" (plist-get p :from))
6157 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
6158 (cons "%T" (plist-get p :to))
6159 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
6160 (cons "%s" (plist-get p :subject))
6161 (cons "%m" (plist-get p :message-id)))))
6162 (when (string-match "%c" fmt)
6163 ;; Check if the user wrote this message
6164 (if (and org-from-is-user-regexp from to
6165 (save-match-data (string-match org-from-is-user-regexp from)))
6166 (setq fmt (replace-match "to %t" t t fmt))
6167 (setq fmt (replace-match "from %f" t t fmt))))
6168 (org-replace-escapes fmt table)))
6170 (defun org-make-org-heading-search-string (&optional string heading)
6171 "Make search string for STRING or current headline."
6172 (interactive)
6173 (let ((s (or string (org-get-heading))))
6174 (unless (and string (not heading))
6175 ;; We are using a headline, clean up garbage in there.
6176 (if (string-match org-todo-regexp s)
6177 (setq s (replace-match "" t t s)))
6178 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
6179 (setq s (replace-match "" t t s)))
6180 (setq s (org-trim s))
6181 (if (string-match (concat "^\\(" org-quote-string "\\|"
6182 org-comment-string "\\)") s)
6183 (setq s (replace-match "" t t s)))
6184 (while (string-match org-ts-regexp s)
6185 (setq s (replace-match "" t t s))))
6186 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
6187 (setq s (replace-match " " t t s)))
6188 (or string (setq s (concat "*" s))) ; Add * for headlines
6189 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
6191 (defun org-make-link (&rest strings)
6192 "Concatenate STRINGS."
6193 (apply 'concat strings))
6195 (defun org-make-link-string (link &optional description)
6196 "Make a link with brackets, consisting of LINK and DESCRIPTION."
6197 (unless (string-match "\\S-" link)
6198 (error "Empty link"))
6199 (when (stringp description)
6200 ;; Remove brackets from the description, they are fatal.
6201 (while (string-match "\\[" description)
6202 (setq description (replace-match "{" t t description)))
6203 (while (string-match "\\]" description)
6204 (setq description (replace-match "}" t t description))))
6205 (when (equal (org-link-escape link) description)
6206 ;; No description needed, it is identical
6207 (setq description nil))
6208 (when (and (not description)
6209 (not (equal link (org-link-escape link))))
6210 (setq description (org-extract-attributes link)))
6211 (concat "[[" (org-link-escape link) "]"
6212 (if description (concat "[" description "]") "")
6213 "]"))
6215 (defconst org-link-escape-chars
6216 '((?\ . "%20")
6217 (?\[ . "%5B")
6218 (?\] . "%5D")
6219 (?\340 . "%E0") ; `a
6220 (?\342 . "%E2") ; ^a
6221 (?\347 . "%E7") ; ,c
6222 (?\350 . "%E8") ; `e
6223 (?\351 . "%E9") ; 'e
6224 (?\352 . "%EA") ; ^e
6225 (?\356 . "%EE") ; ^i
6226 (?\364 . "%F4") ; ^o
6227 (?\371 . "%F9") ; `u
6228 (?\373 . "%FB") ; ^u
6229 (?\; . "%3B")
6230 (?? . "%3F")
6231 (?= . "%3D")
6232 (?+ . "%2B")
6234 "Association list of escapes for some characters problematic in links.
6235 This is the list that is used for internal purposes.")
6237 (defconst org-link-escape-chars-browser
6238 '((?\ . "%20")) ; 32 for the SPC char
6239 "Association list of escapes for some characters problematic in links.
6240 This is the list that is used before handing over to the browser.")
6242 (defun org-link-escape (text &optional table)
6243 "Escape charaters in TEXT that are problematic for links."
6244 (setq table (or table org-link-escape-chars))
6245 (when text
6246 (let ((re (mapconcat (lambda (x) (regexp-quote
6247 (char-to-string (car x))))
6248 table "\\|")))
6249 (while (string-match re text)
6250 (setq text
6251 (replace-match
6252 (cdr (assoc (string-to-char (match-string 0 text))
6253 table))
6254 t t text)))
6255 text)))
6257 (defun org-link-unescape (text &optional table)
6258 "Reverse the action of `org-link-escape'."
6259 (setq table (or table org-link-escape-chars))
6260 (when text
6261 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
6262 table "\\|")))
6263 (while (string-match re text)
6264 (setq text
6265 (replace-match
6266 (char-to-string (car (rassoc (match-string 0 text) table)))
6267 t t text)))
6268 text)))
6270 (defun org-xor (a b)
6271 "Exclusive or."
6272 (if a (not b) b))
6274 (defun org-get-header (header)
6275 "Find a header field in the current buffer."
6276 (save-excursion
6277 (goto-char (point-min))
6278 (let ((case-fold-search t) s)
6279 (cond
6280 ((eq header 'from)
6281 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
6282 (setq s (match-string 1)))
6283 (while (string-match "\"" s)
6284 (setq s (replace-match "" t t s)))
6285 (if (string-match "[<(].*" s)
6286 (setq s (replace-match "" t t s))))
6287 ((eq header 'message-id)
6288 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
6289 (setq s (match-string 1))))
6290 ((eq header 'subject)
6291 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
6292 (setq s (match-string 1)))))
6293 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
6294 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
6295 s)))
6298 (defun org-fixup-message-id-for-http (s)
6299 "Replace special characters in a message id, so it can be used in an http query."
6300 (while (string-match "<" s)
6301 (setq s (replace-match "%3C" t t s)))
6302 (while (string-match ">" s)
6303 (setq s (replace-match "%3E" t t s)))
6304 (while (string-match "@" s)
6305 (setq s (replace-match "%40" t t s)))
6308 ;;;###autoload
6309 (defun org-insert-link-global ()
6310 "Insert a link like Org-mode does.
6311 This command can be called in any mode to insert a link in Org-mode syntax."
6312 (interactive)
6313 (org-load-modules-maybe)
6314 (org-run-like-in-org-mode 'org-insert-link))
6316 (defun org-insert-link (&optional complete-file link-location)
6317 "Insert a link. At the prompt, enter the link.
6319 Completion can be used to select a link previously stored with
6320 `org-store-link'. When the empty string is entered (i.e. if you just
6321 press RET at the prompt), the link defaults to the most recently
6322 stored link. As SPC triggers completion in the minibuffer, you need to
6323 use M-SPC or C-q SPC to force the insertion of a space character.
6325 You will also be prompted for a description, and if one is given, it will
6326 be displayed in the buffer instead of the link.
6328 If there is already a link at point, this command will allow you to edit link
6329 and description parts.
6331 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
6332 be selected using completion. The path to the file will be relative to the
6333 current directory if the file is in the current directory or a subdirectory.
6334 Otherwise, the link will be the absolute path as completed in the minibuffer
6335 \(i.e. normally ~/path/to/file).
6337 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
6338 the current directory or below. With three \\[universal-argument] prefixes, negate the meaning
6339 of `org-keep-stored-link-after-insertion'.
6341 If `org-make-link-description-function' is non-nil, this function will be
6342 called with the link target, and the result will be the default
6343 link description.
6345 If the LINK-LOCATION parameter is non-nil, this value will be
6346 used as the link location instead of reading one interactively."
6347 (interactive "P")
6348 (let* ((wcf (current-window-configuration))
6349 (region (if (org-region-active-p)
6350 (buffer-substring (region-beginning) (region-end))))
6351 (remove (and region (list (region-beginning) (region-end))))
6352 (desc region)
6353 tmphist ; byte-compile incorrectly complains about this
6354 (link link-location)
6355 entry file)
6356 (cond
6357 (link-location) ; specified by arg, just use it.
6358 ((org-in-regexp org-bracket-link-regexp 1)
6359 ;; We do have a link at point, and we are going to edit it.
6360 (setq remove (list (match-beginning 0) (match-end 0)))
6361 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
6362 (setq link (read-string "Link: "
6363 (org-link-unescape
6364 (org-match-string-no-properties 1)))))
6365 ((or (org-in-regexp org-angle-link-re)
6366 (org-in-regexp org-plain-link-re))
6367 ;; Convert to bracket link
6368 (setq remove (list (match-beginning 0) (match-end 0))
6369 link (read-string "Link: "
6370 (org-remove-angle-brackets (match-string 0)))))
6371 ((equal complete-file '(4))
6372 ;; Completing read for file names.
6373 (setq file (read-file-name "File: "))
6374 (let ((pwd (file-name-as-directory (expand-file-name ".")))
6375 (pwd1 (file-name-as-directory (abbreviate-file-name
6376 (expand-file-name ".")))))
6377 (cond
6378 ((equal complete-file '(16))
6379 (setq link (org-make-link
6380 "file:"
6381 (abbreviate-file-name (expand-file-name file)))))
6382 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
6383 (setq link (org-make-link "file:" (match-string 1 file))))
6384 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
6385 (expand-file-name file))
6386 (setq link (org-make-link
6387 "file:" (match-string 1 (expand-file-name file)))))
6388 (t (setq link (org-make-link "file:" file))))))
6390 ;; Read link, with completion for stored links.
6391 (with-output-to-temp-buffer "*Org Links*"
6392 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
6393 (when org-stored-links
6394 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
6395 (princ (mapconcat
6396 (lambda (x)
6397 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
6398 (reverse org-stored-links) "\n"))))
6399 (let ((cw (selected-window)))
6400 (select-window (get-buffer-window "*Org Links*"))
6401 (shrink-window-if-larger-than-buffer)
6402 (setq truncate-lines t)
6403 (select-window cw))
6404 ;; Fake a link history, containing the stored links.
6405 (setq tmphist (append (mapcar 'car org-stored-links)
6406 org-insert-link-history))
6407 (unwind-protect
6408 (setq link (org-completing-read
6409 "Link: "
6410 (append
6411 (mapcar (lambda (x) (list (concat (car x) ":")))
6412 (append org-link-abbrev-alist-local org-link-abbrev-alist))
6413 (mapcar (lambda (x) (list (concat x ":")))
6414 org-link-types))
6415 nil nil nil
6416 'tmphist
6417 (or (car (car org-stored-links)))))
6418 (set-window-configuration wcf)
6419 (kill-buffer "*Org Links*"))
6420 (setq entry (assoc link org-stored-links))
6421 (or entry (push link org-insert-link-history))
6422 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
6423 (not org-keep-stored-link-after-insertion))
6424 (setq org-stored-links (delq (assoc link org-stored-links)
6425 org-stored-links)))
6426 (setq desc (or desc (nth 1 entry)))))
6428 (if (string-match org-plain-link-re link)
6429 ;; URL-like link, normalize the use of angular brackets.
6430 (setq link (org-make-link (org-remove-angle-brackets link))))
6432 ;; Check if we are linking to the current file with a search option
6433 ;; If yes, simplify the link by using only the search option.
6434 (when (and buffer-file-name
6435 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
6436 (let* ((path (match-string 1 link))
6437 (case-fold-search nil)
6438 (search (match-string 2 link)))
6439 (save-match-data
6440 (if (equal (file-truename buffer-file-name) (file-truename path))
6441 ;; We are linking to this same file, with a search option
6442 (setq link search)))))
6444 ;; Check if we can/should use a relative path. If yes, simplify the link
6445 (when (string-match "\\<file:\\(.*\\)" link)
6446 (let* ((path (match-string 1 link))
6447 (origpath path)
6448 (case-fold-search nil))
6449 (cond
6450 ((eq org-link-file-path-type 'absolute)
6451 (setq path (abbreviate-file-name (expand-file-name path))))
6452 ((eq org-link-file-path-type 'noabbrev)
6453 (setq path (expand-file-name path)))
6454 ((eq org-link-file-path-type 'relative)
6455 (setq path (file-relative-name path)))
6457 (save-match-data
6458 (if (string-match (concat "^" (regexp-quote
6459 (file-name-as-directory
6460 (expand-file-name "."))))
6461 (expand-file-name path))
6462 ;; We are linking a file with relative path name.
6463 (setq path (substring (expand-file-name path)
6464 (match-end 0)))))))
6465 (setq link (concat "file:" path))
6466 (if (equal desc origpath)
6467 (setq desc path))))
6469 (if org-make-link-description-function
6470 (setq desc (funcall org-make-link-description-function link desc)))
6472 (setq desc (read-string "Description: " desc))
6473 (unless (string-match "\\S-" desc) (setq desc nil))
6474 (if remove (apply 'delete-region remove))
6475 (insert (org-make-link-string link desc))))
6477 (defun org-completing-read (&rest args)
6478 (let ((minibuffer-local-completion-map
6479 (copy-keymap minibuffer-local-completion-map)))
6480 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
6481 (apply 'completing-read args)))
6483 (defun org-extract-attributes (s)
6484 "Extract the attributes cookie from a string and set as text property."
6485 (let (a attr (start 0) key value)
6486 (save-match-data
6487 (when (string-match "{{\\([^}]+\\)}}$" s)
6488 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
6489 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
6490 (setq key (match-string 1 a) value (match-string 2 a)
6491 start (match-end 0)
6492 attr (plist-put attr (intern key) value))))
6493 (org-add-props s nil 'org-attributes attr))
6496 (defun org-attributes-to-string (plist)
6497 "Format a property list into an HTML attribute list."
6498 (let ((s "") key value)
6499 (while plist
6500 (setq key (pop plist) value (pop plist))
6501 (setq s (concat s " "(symbol-name key) "=\"" value "\"")))
6504 ;;; Opening/following a link
6506 (defvar org-link-search-failed nil)
6508 (defun org-next-link ()
6509 "Move forward to the next link.
6510 If the link is in hidden text, expose it."
6511 (interactive)
6512 (when (and org-link-search-failed (eq this-command last-command))
6513 (goto-char (point-min))
6514 (message "Link search wrapped back to beginning of buffer"))
6515 (setq org-link-search-failed nil)
6516 (let* ((pos (point))
6517 (ct (org-context))
6518 (a (assoc :link ct)))
6519 (if a (goto-char (nth 2 a)))
6520 (if (re-search-forward org-any-link-re nil t)
6521 (progn
6522 (goto-char (match-beginning 0))
6523 (if (org-invisible-p) (org-show-context)))
6524 (goto-char pos)
6525 (setq org-link-search-failed t)
6526 (error "No further link found"))))
6528 (defun org-previous-link ()
6529 "Move backward to the previous link.
6530 If the link is in hidden text, expose it."
6531 (interactive)
6532 (when (and org-link-search-failed (eq this-command last-command))
6533 (goto-char (point-max))
6534 (message "Link search wrapped back to end of buffer"))
6535 (setq org-link-search-failed nil)
6536 (let* ((pos (point))
6537 (ct (org-context))
6538 (a (assoc :link ct)))
6539 (if a (goto-char (nth 1 a)))
6540 (if (re-search-backward org-any-link-re nil t)
6541 (progn
6542 (goto-char (match-beginning 0))
6543 (if (org-invisible-p) (org-show-context)))
6544 (goto-char pos)
6545 (setq org-link-search-failed t)
6546 (error "No further link found"))))
6548 (defun org-find-file-at-mouse (ev)
6549 "Open file link or URL at mouse."
6550 (interactive "e")
6551 (mouse-set-point ev)
6552 (org-open-at-point 'in-emacs))
6554 (defun org-open-at-mouse (ev)
6555 "Open file link or URL at mouse."
6556 (interactive "e")
6557 (mouse-set-point ev)
6558 (org-open-at-point))
6560 (defvar org-window-config-before-follow-link nil
6561 "The window configuration before following a link.
6562 This is saved in case the need arises to restore it.")
6564 (defvar org-open-link-marker (make-marker)
6565 "Marker pointing to the location where `org-open-at-point; was called.")
6567 ;;;###autoload
6568 (defun org-open-at-point-global ()
6569 "Follow a link like Org-mode does.
6570 This command can be called in any mode to follow a link that has
6571 Org-mode syntax."
6572 (interactive)
6573 (org-run-like-in-org-mode 'org-open-at-point))
6575 ;;;###autoload
6576 (defun org-open-link-from-string (s &optional arg)
6577 "Open a link in the string S, as if it was in Org-mode."
6578 (interactive "sLink: \nP")
6579 (with-temp-buffer
6580 (let ((org-inhibit-startup t))
6581 (org-mode)
6582 (insert s)
6583 (goto-char (point-min))
6584 (org-open-at-point arg))))
6586 (defun org-open-at-point (&optional in-emacs)
6587 "Open link at or after point.
6588 If there is no link at point, this function will search forward up to
6589 the end of the current subtree.
6590 Normally, files will be opened by an appropriate application. If the
6591 optional argument IN-EMACS is non-nil, Emacs will visit the file."
6592 (interactive "P")
6593 (org-load-modules-maybe)
6594 (move-marker org-open-link-marker (point))
6595 (setq org-window-config-before-follow-link (current-window-configuration))
6596 (org-remove-occur-highlights nil nil t)
6597 (if (org-at-timestamp-p t)
6598 (org-follow-timestamp-link)
6599 (let (type path link line search (pos (point)))
6600 (catch 'match
6601 (save-excursion
6602 (skip-chars-forward "^]\n\r")
6603 (when (org-in-regexp org-bracket-link-regexp)
6604 (setq link (org-extract-attributes
6605 (org-link-unescape (org-match-string-no-properties 1))))
6606 (while (string-match " *\n *" link)
6607 (setq link (replace-match " " t t link)))
6608 (setq link (org-link-expand-abbrev link))
6609 (cond
6610 ((or (file-name-absolute-p link)
6611 (string-match "^\\.\\.?/" link))
6612 (setq type "file" path link))
6613 ((string-match org-link-re-with-space2 link)
6614 (setq type (match-string 1 link) path (match-string 2 link)))
6615 (t (setq type "thisfile" path link)))
6616 (throw 'match t)))
6618 (when (get-text-property (point) 'org-linked-text)
6619 (setq type "thisfile"
6620 pos (if (get-text-property (1+ (point)) 'org-linked-text)
6621 (1+ (point)) (point))
6622 path (buffer-substring
6623 (previous-single-property-change pos 'org-linked-text)
6624 (next-single-property-change pos 'org-linked-text)))
6625 (throw 'match t))
6627 (save-excursion
6628 (when (or (org-in-regexp org-angle-link-re)
6629 (org-in-regexp org-plain-link-re))
6630 (setq type (match-string 1) path (match-string 2))
6631 (throw 'match t)))
6632 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
6633 (setq type "tree-match"
6634 path (match-string 1))
6635 (throw 'match t))
6636 (save-excursion
6637 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
6638 (setq type "tags"
6639 path (match-string 1))
6640 (while (string-match ":" path)
6641 (setq path (replace-match "+" t t path)))
6642 (throw 'match t))))
6643 (unless path
6644 (error "No link found"))
6645 ;; Remove any trailing spaces in path
6646 (if (string-match " +\\'" path)
6647 (setq path (replace-match "" t t path)))
6649 (cond
6651 ((assoc type org-link-protocols)
6652 (funcall (nth 1 (assoc type org-link-protocols)) path))
6654 ((equal type "mailto")
6655 (let ((cmd (car org-link-mailto-program))
6656 (args (cdr org-link-mailto-program)) args1
6657 (address path) (subject "") a)
6658 (if (string-match "\\(.*\\)::\\(.*\\)" path)
6659 (setq address (match-string 1 path)
6660 subject (org-link-escape (match-string 2 path))))
6661 (while args
6662 (cond
6663 ((not (stringp (car args))) (push (pop args) args1))
6664 (t (setq a (pop args))
6665 (if (string-match "%a" a)
6666 (setq a (replace-match address t t a)))
6667 (if (string-match "%s" a)
6668 (setq a (replace-match subject t t a)))
6669 (push a args1))))
6670 (apply cmd (nreverse args1))))
6672 ((member type '("http" "https" "ftp" "news"))
6673 (browse-url (concat type ":" (org-link-escape
6674 path org-link-escape-chars-browser))))
6676 ((member type '("message"))
6677 (browse-url (concat type ":" path)))
6679 ((string= type "tags")
6680 (org-tags-view in-emacs path))
6681 ((string= type "thisfile")
6682 (if in-emacs
6683 (switch-to-buffer-other-window
6684 (org-get-buffer-for-internal-link (current-buffer)))
6685 (org-mark-ring-push))
6686 (let ((cmd `(org-link-search
6687 ,path
6688 ,(cond ((equal in-emacs '(4)) 'occur)
6689 ((equal in-emacs '(16)) 'org-occur)
6690 (t nil))
6691 ,pos)))
6692 (condition-case nil (eval cmd)
6693 (error (progn (widen) (eval cmd))))))
6695 ((string= type "tree-match")
6696 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
6698 ((string= type "file")
6699 (if (string-match "::\\([0-9]+\\)\\'" path)
6700 (setq line (string-to-number (match-string 1 path))
6701 path (substring path 0 (match-beginning 0)))
6702 (if (string-match "::\\(.+\\)\\'" path)
6703 (setq search (match-string 1 path)
6704 path (substring path 0 (match-beginning 0)))))
6705 (if (string-match "[*?{]" (file-name-nondirectory path))
6706 (dired path)
6707 (org-open-file path in-emacs line search)))
6709 ((string= type "news")
6710 (require 'org-gnus)
6711 (org-gnus-follow-link path))
6713 ((string= type "shell")
6714 (let ((cmd path))
6715 (if (or (not org-confirm-shell-link-function)
6716 (funcall org-confirm-shell-link-function
6717 (format "Execute \"%s\" in shell? "
6718 (org-add-props cmd nil
6719 'face 'org-warning))))
6720 (progn
6721 (message "Executing %s" cmd)
6722 (shell-command cmd))
6723 (error "Abort"))))
6725 ((string= type "elisp")
6726 (let ((cmd path))
6727 (if (or (not org-confirm-elisp-link-function)
6728 (funcall org-confirm-elisp-link-function
6729 (format "Execute \"%s\" as elisp? "
6730 (org-add-props cmd nil
6731 'face 'org-warning))))
6732 (message "%s => %s" cmd (eval (read cmd)))
6733 (error "Abort"))))
6736 (browse-url-at-point)))))
6737 (move-marker org-open-link-marker nil)
6738 (run-hook-with-args 'org-follow-link-hook))
6740 ;;;; Time estimates
6742 (defun org-get-effort (&optional pom)
6743 "Get the effort estimate for the current entry."
6744 (org-entry-get pom org-effort-property))
6746 ;;; File search
6748 (defvar org-create-file-search-functions nil
6749 "List of functions to construct the right search string for a file link.
6750 These functions are called in turn with point at the location to
6751 which the link should point.
6753 A function in the hook should first test if it would like to
6754 handle this file type, for example by checking the major-mode or
6755 the file extension. If it decides not to handle this file, it
6756 should just return nil to give other functions a chance. If it
6757 does handle the file, it must return the search string to be used
6758 when following the link. The search string will be part of the
6759 file link, given after a double colon, and `org-open-at-point'
6760 will automatically search for it. If special measures must be
6761 taken to make the search successful, another function should be
6762 added to the companion hook `org-execute-file-search-functions',
6763 which see.
6765 A function in this hook may also use `setq' to set the variable
6766 `description' to provide a suggestion for the descriptive text to
6767 be used for this link when it gets inserted into an Org-mode
6768 buffer with \\[org-insert-link].")
6770 (defvar org-execute-file-search-functions nil
6771 "List of functions to execute a file search triggered by a link.
6773 Functions added to this hook must accept a single argument, the
6774 search string that was part of the file link, the part after the
6775 double colon. The function must first check if it would like to
6776 handle this search, for example by checking the major-mode or the
6777 file extension. If it decides not to handle this search, it
6778 should just return nil to give other functions a chance. If it
6779 does handle the search, it must return a non-nil value to keep
6780 other functions from trying.
6782 Each function can access the current prefix argument through the
6783 variable `current-prefix-argument'. Note that a single prefix is
6784 used to force opening a link in Emacs, so it may be good to only
6785 use a numeric or double prefix to guide the search function.
6787 In case this is needed, a function in this hook can also restore
6788 the window configuration before `org-open-at-point' was called using:
6790 (set-window-configuration org-window-config-before-follow-link)")
6792 (defun org-link-search (s &optional type avoid-pos)
6793 "Search for a link search option.
6794 If S is surrounded by forward slashes, it is interpreted as a
6795 regular expression. In org-mode files, this will create an `org-occur'
6796 sparse tree. In ordinary files, `occur' will be used to list matches.
6797 If the current buffer is in `dired-mode', grep will be used to search
6798 in all files. If AVOID-POS is given, ignore matches near that position."
6799 (let ((case-fold-search t)
6800 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
6801 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
6802 (append '(("") (" ") ("\t") ("\n"))
6803 org-emphasis-alist)
6804 "\\|") "\\)"))
6805 (pos (point))
6806 (pre nil) (post nil)
6807 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
6808 (cond
6809 ;; First check if there are any special
6810 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
6811 ;; Now try the builtin stuff
6812 ((save-excursion
6813 (goto-char (point-min))
6814 (and
6815 (re-search-forward
6816 (concat "<<" (regexp-quote s0) ">>") nil t)
6817 (setq type 'dedicated
6818 pos (match-beginning 0))))
6819 ;; There is an exact target for this
6820 (goto-char pos))
6821 ((string-match "^/\\(.*\\)/$" s)
6822 ;; A regular expression
6823 (cond
6824 ((org-mode-p)
6825 (org-occur (match-string 1 s)))
6826 ;;((eq major-mode 'dired-mode)
6827 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
6828 (t (org-do-occur (match-string 1 s)))))
6830 ;; A normal search strings
6831 (when (equal (string-to-char s) ?*)
6832 ;; Anchor on headlines, post may include tags.
6833 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
6834 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
6835 s (substring s 1)))
6836 (remove-text-properties
6837 0 (length s)
6838 '(face nil mouse-face nil keymap nil fontified nil) s)
6839 ;; Make a series of regular expressions to find a match
6840 (setq words (org-split-string s "[ \n\r\t]+")
6842 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
6843 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
6844 "\\)" markers)
6845 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
6846 re2a (concat "[ \t\r\n]" re2a_)
6847 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
6848 re4 (concat "[^a-zA-Z_]" re4_)
6850 re1 (concat pre re2 post)
6851 re3 (concat pre (if pre re4_ re4) post)
6852 re5 (concat pre ".*" re4)
6853 re2 (concat pre re2)
6854 re2a (concat pre (if pre re2a_ re2a))
6855 re4 (concat pre (if pre re4_ re4))
6856 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
6857 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
6858 re5 "\\)"
6860 (cond
6861 ((eq type 'org-occur) (org-occur reall))
6862 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
6863 (t (goto-char (point-min))
6864 (setq type 'fuzzy)
6865 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
6866 (org-search-not-self 1 re1 nil t)
6867 (org-search-not-self 1 re2 nil t)
6868 (org-search-not-self 1 re2a nil t)
6869 (org-search-not-self 1 re3 nil t)
6870 (org-search-not-self 1 re4 nil t)
6871 (org-search-not-self 1 re5 nil t)
6873 (goto-char (match-beginning 1))
6874 (goto-char pos)
6875 (error "No match")))))
6877 ;; Normal string-search
6878 (goto-char (point-min))
6879 (if (search-forward s nil t)
6880 (goto-char (match-beginning 0))
6881 (error "No match"))))
6882 (and (org-mode-p) (org-show-context 'link-search))
6883 type))
6885 (defun org-search-not-self (group &rest args)
6886 "Execute `re-search-forward', but only accept matches that do not
6887 enclose the position of `org-open-link-marker'."
6888 (let ((m org-open-link-marker))
6889 (catch 'exit
6890 (while (apply 're-search-forward args)
6891 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
6892 (goto-char (match-end group))
6893 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
6894 (> (match-beginning 0) (marker-position m))
6895 (< (match-end 0) (marker-position m)))
6896 (save-match-data
6897 (or (not (org-in-regexp
6898 org-bracket-link-analytic-regexp 1))
6899 (not (match-end 4)) ; no description
6900 (and (<= (match-beginning 4) (point))
6901 (>= (match-end 4) (point))))))
6902 (throw 'exit (point))))))))
6904 (defun org-get-buffer-for-internal-link (buffer)
6905 "Return a buffer to be used for displaying the link target of internal links."
6906 (cond
6907 ((not org-display-internal-link-with-indirect-buffer)
6908 buffer)
6909 ((string-match "(Clone)$" (buffer-name buffer))
6910 (message "Buffer is already a clone, not making another one")
6911 ;; we also do not modify visibility in this case
6912 buffer)
6913 (t ; make a new indirect buffer for displaying the link
6914 (let* ((bn (buffer-name buffer))
6915 (ibn (concat bn "(Clone)"))
6916 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
6917 (with-current-buffer ib (org-overview))
6918 ib))))
6920 (defun org-do-occur (regexp &optional cleanup)
6921 "Call the Emacs command `occur'.
6922 If CLEANUP is non-nil, remove the printout of the regular expression
6923 in the *Occur* buffer. This is useful if the regex is long and not useful
6924 to read."
6925 (occur regexp)
6926 (when cleanup
6927 (let ((cwin (selected-window)) win beg end)
6928 (when (setq win (get-buffer-window "*Occur*"))
6929 (select-window win))
6930 (goto-char (point-min))
6931 (when (re-search-forward "match[a-z]+" nil t)
6932 (setq beg (match-end 0))
6933 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
6934 (setq end (1- (match-beginning 0)))))
6935 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
6936 (goto-char (point-min))
6937 (select-window cwin))))
6939 ;;; The mark ring for links jumps
6941 (defvar org-mark-ring nil
6942 "Mark ring for positions before jumps in Org-mode.")
6943 (defvar org-mark-ring-last-goto nil
6944 "Last position in the mark ring used to go back.")
6945 ;; Fill and close the ring
6946 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
6947 (loop for i from 1 to org-mark-ring-length do
6948 (push (make-marker) org-mark-ring))
6949 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
6950 org-mark-ring)
6952 (defun org-mark-ring-push (&optional pos buffer)
6953 "Put the current position or POS into the mark ring and rotate it."
6954 (interactive)
6955 (setq pos (or pos (point)))
6956 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
6957 (move-marker (car org-mark-ring)
6958 (or pos (point))
6959 (or buffer (current-buffer)))
6960 (message "%s"
6961 (substitute-command-keys
6962 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
6964 (defun org-mark-ring-goto (&optional n)
6965 "Jump to the previous position in the mark ring.
6966 With prefix arg N, jump back that many stored positions. When
6967 called several times in succession, walk through the entire ring.
6968 Org-mode commands jumping to a different position in the current file,
6969 or to another Org-mode file, automatically push the old position
6970 onto the ring."
6971 (interactive "p")
6972 (let (p m)
6973 (if (eq last-command this-command)
6974 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
6975 (setq p org-mark-ring))
6976 (setq org-mark-ring-last-goto p)
6977 (setq m (car p))
6978 (switch-to-buffer (marker-buffer m))
6979 (goto-char m)
6980 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
6982 (defun org-remove-angle-brackets (s)
6983 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
6984 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
6986 (defun org-add-angle-brackets (s)
6987 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
6988 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
6990 (defun org-remove-double-quotes (s)
6991 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
6992 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
6995 ;;; Following specific links
6997 (defun org-follow-timestamp-link ()
6998 (cond
6999 ((org-at-date-range-p t)
7000 (let ((org-agenda-start-on-weekday)
7001 (t1 (match-string 1))
7002 (t2 (match-string 2)))
7003 (setq t1 (time-to-days (org-time-string-to-time t1))
7004 t2 (time-to-days (org-time-string-to-time t2)))
7005 (org-agenda-list nil t1 (1+ (- t2 t1)))))
7006 ((org-at-timestamp-p t)
7007 (org-agenda-list nil (time-to-days (org-time-string-to-time
7008 (substring (match-string 1) 0 10)))
7010 (t (error "This should not happen"))))
7013 ;;; Following file links
7014 (defvar org-wait nil)
7015 (defun org-open-file (path &optional in-emacs line search)
7016 "Open the file at PATH.
7017 First, this expands any special file name abbreviations. Then the
7018 configuration variable `org-file-apps' is checked if it contains an
7019 entry for this file type, and if yes, the corresponding command is launched.
7020 If no application is found, Emacs simply visits the file.
7021 With optional argument IN-EMACS, Emacs will visit the file.
7022 Optional LINE specifies a line to go to, optional SEARCH a string to
7023 search for. If LINE or SEARCH is given, the file will always be
7024 opened in Emacs.
7025 If the file does not exist, an error is thrown."
7026 (setq in-emacs (or in-emacs line search))
7027 (let* ((file (if (equal path "")
7028 buffer-file-name
7029 (substitute-in-file-name (expand-file-name path))))
7030 (apps (append org-file-apps (org-default-apps)))
7031 (remp (and (assq 'remote apps) (org-file-remote-p file)))
7032 (dirp (if remp nil (file-directory-p file)))
7033 (file (if (and dirp org-open-directory-means-index-dot-org)
7034 (concat (file-name-as-directory file) "index.org")
7035 file))
7036 (a-m-a-p (assq 'auto-mode apps))
7037 (dfile (downcase file))
7038 (old-buffer (current-buffer))
7039 (old-pos (point))
7040 (old-mode major-mode)
7041 ext cmd)
7042 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7043 (setq ext (match-string 1 dfile))
7044 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7045 (setq ext (match-string 1 dfile))))
7046 (if in-emacs
7047 (setq cmd 'emacs)
7048 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
7049 (and dirp (cdr (assoc 'directory apps)))
7050 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
7051 'string-match)
7052 (cdr (assoc ext apps))
7053 (cdr (assoc t apps)))))
7054 (when (eq cmd 'default)
7055 (setq cmd (cdr (assoc t apps))))
7056 (when (eq cmd 'mailcap)
7057 (require 'mailcap)
7058 (mailcap-parse-mailcaps)
7059 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7060 (command (mailcap-mime-info mime-type)))
7061 (if (stringp command)
7062 (setq cmd command)
7063 (setq cmd 'emacs))))
7064 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
7065 (not (file-exists-p file))
7066 (not org-open-non-existing-files))
7067 (error "No such file: %s" file))
7068 (cond
7069 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7070 ;; Remove quotes around the file name - we'll use shell-quote-argument.
7071 (while (string-match "['\"]%s['\"]" cmd)
7072 (setq cmd (replace-match "%s" t t cmd)))
7073 (while (string-match "%s" cmd)
7074 (setq cmd (replace-match
7075 (save-match-data
7076 (shell-quote-argument
7077 (convert-standard-filename file)))
7078 t t cmd)))
7079 (save-window-excursion
7080 (start-process-shell-command cmd nil cmd)
7081 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
7083 ((or (stringp cmd)
7084 (eq cmd 'emacs))
7085 (funcall (cdr (assq 'file org-link-frame-setup)) file)
7086 (widen)
7087 (if line (goto-line line)
7088 (if search (org-link-search search))))
7089 ((consp cmd)
7090 (let ((file (convert-standard-filename file)))
7091 (eval cmd)))
7092 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7093 (and (org-mode-p) (eq old-mode 'org-mode)
7094 (or (not (equal old-buffer (current-buffer)))
7095 (not (equal old-pos (point))))
7096 (org-mark-ring-push old-pos old-buffer))))
7098 (defun org-default-apps ()
7099 "Return the default applications for this operating system."
7100 (cond
7101 ((eq system-type 'darwin)
7102 org-file-apps-defaults-macosx)
7103 ((eq system-type 'windows-nt)
7104 org-file-apps-defaults-windowsnt)
7105 (t org-file-apps-defaults-gnu)))
7107 (defun org-apps-regexp-alist (list &optional add-auto-mode)
7108 "Convert extensions to regular expressions in the cars of LIST.
7109 Also, weed out any non-string entries, because the return value is used
7110 only for regexp matching.
7111 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
7112 point to the symbol `emacs', indicating that the file should
7113 be opened in Emacs."
7114 (append
7115 (delq nil
7116 (mapcar (lambda (x)
7117 (if (not (stringp (car x)))
7119 (if (string-match "\\W" (car x))
7121 (cons (concat "\\." (car x) "\\'") (cdr x)))))
7122 list))
7123 (if add-auto-mode
7124 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
7126 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
7127 (defun org-file-remote-p (file)
7128 "Test whether FILE specifies a location on a remote system.
7129 Return non-nil if the location is indeed remote.
7131 For example, the filename \"/user@host:/foo\" specifies a location
7132 on the system \"/user@host:\"."
7133 (cond ((fboundp 'file-remote-p)
7134 (file-remote-p file))
7135 ((fboundp 'tramp-handle-file-remote-p)
7136 (tramp-handle-file-remote-p file))
7137 ((and (boundp 'ange-ftp-name-format)
7138 (string-match (car ange-ftp-name-format) file))
7140 (t nil)))
7143 ;;;; Refiling
7145 (defun org-get-org-file ()
7146 "Read a filename, with default directory `org-directory'."
7147 (let ((default (or org-default-notes-file remember-data-file)))
7148 (read-file-name (format "File name [%s]: " default)
7149 (file-name-as-directory org-directory)
7150 default)))
7152 (defun org-notes-order-reversed-p ()
7153 "Check if the current file should receive notes in reversed order."
7154 (cond
7155 ((not org-reverse-note-order) nil)
7156 ((eq t org-reverse-note-order) t)
7157 ((not (listp org-reverse-note-order)) nil)
7158 (t (catch 'exit
7159 (let ((all org-reverse-note-order)
7160 entry)
7161 (while (setq entry (pop all))
7162 (if (string-match (car entry) buffer-file-name)
7163 (throw 'exit (cdr entry))))
7164 nil)))))
7166 (defvar org-refile-target-table nil
7167 "The list of refile targets, created by `org-refile'.")
7169 (defvar org-agenda-new-buffers nil
7170 "Buffers created to visit agenda files.")
7172 (defun org-get-refile-targets (&optional default-buffer)
7173 "Produce a table with refile targets."
7174 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
7175 targets txt re files f desc descre)
7176 (with-current-buffer (or default-buffer (current-buffer))
7177 (while (setq entry (pop entries))
7178 (setq files (car entry) desc (cdr entry))
7179 (cond
7180 ((null files) (setq files (list (current-buffer))))
7181 ((eq files 'org-agenda-files)
7182 (setq files (org-agenda-files 'unrestricted)))
7183 ((and (symbolp files) (fboundp files))
7184 (setq files (funcall files)))
7185 ((and (symbolp files) (boundp files))
7186 (setq files (symbol-value files))))
7187 (if (stringp files) (setq files (list files)))
7188 (cond
7189 ((eq (car desc) :tag)
7190 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
7191 ((eq (car desc) :todo)
7192 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
7193 ((eq (car desc) :regexp)
7194 (setq descre (cdr desc)))
7195 ((eq (car desc) :level)
7196 (setq descre (concat "^\\*\\{" (number-to-string
7197 (if org-odd-levels-only
7198 (1- (* 2 (cdr desc)))
7199 (cdr desc)))
7200 "\\}[ \t]")))
7201 ((eq (car desc) :maxlevel)
7202 (setq descre (concat "^\\*\\{1," (number-to-string
7203 (if org-odd-levels-only
7204 (1- (* 2 (cdr desc)))
7205 (cdr desc)))
7206 "\\}[ \t]")))
7207 (t (error "Bad refiling target description %s" desc)))
7208 (while (setq f (pop files))
7209 (save-excursion
7210 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
7211 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
7212 (save-excursion
7213 (save-restriction
7214 (widen)
7215 (goto-char (point-min))
7216 (while (re-search-forward descre nil t)
7217 (goto-char (point-at-bol))
7218 (when (looking-at org-complex-heading-regexp)
7219 (setq txt (org-link-display-format (match-string 4))
7220 re (concat "^" (regexp-quote
7221 (buffer-substring (match-beginning 1)
7222 (match-end 4)))))
7223 (if (match-end 5) (setq re (concat re "[ \t]+"
7224 (regexp-quote
7225 (match-string 5)))))
7226 (setq re (concat re "[ \t]*$"))
7227 (when org-refile-use-outline-path
7228 (setq txt (mapconcat 'org-protect-slash
7229 (append
7230 (if (eq org-refile-use-outline-path 'file)
7231 (list (file-name-nondirectory
7232 (buffer-file-name (buffer-base-buffer))))
7233 (if (eq org-refile-use-outline-path 'full-file-path)
7234 (list (buffer-file-name (buffer-base-buffer)))))
7235 (org-get-outline-path)
7236 (list txt))
7237 "/")))
7238 (push (list txt f re (point)) targets))
7239 (goto-char (point-at-eol))))))))
7240 (nreverse targets))))
7242 (defun org-protect-slash (s)
7243 (while (string-match "/" s)
7244 (setq s (replace-match "\\" t t s)))
7247 (defun org-get-outline-path ()
7248 "Return the outline path to the current entry, as a list."
7249 (let (rtn)
7250 (save-excursion
7251 (while (org-up-heading-safe)
7252 (when (looking-at org-complex-heading-regexp)
7253 (push (org-match-string-no-properties 4) rtn)))
7254 rtn)))
7256 (defvar org-refile-history nil
7257 "History for refiling operations.")
7259 (defun org-refile (&optional goto default-buffer)
7260 "Move the entry at point to another heading.
7261 The list of target headings is compiled using the information in
7262 `org-refile-targets', which see. This list is created before each use
7263 and will therefore always be up-to-date.
7265 At the target location, the entry is filed as a subitem of the target heading.
7266 Depending on `org-reverse-note-order', the new subitem will either be the
7267 first or the last subitem.
7269 With prefix arg GOTO, the command will only visit the target location,
7270 not actually move anything.
7271 With a double prefix `C-u C-u', go to the location where the last refiling
7272 operation has put the subtree."
7273 (interactive "P")
7274 (let* ((cbuf (current-buffer))
7275 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7276 pos it nbuf file re level reversed)
7277 (if (equal goto '(16))
7278 (org-refile-goto-last-stored)
7279 (when (setq it (org-refile-get-location
7280 (if goto "Goto: " "Refile to: ") default-buffer))
7281 (setq file (nth 1 it)
7282 re (nth 2 it)
7283 pos (nth 3 it))
7284 (setq nbuf (or (find-buffer-visiting file)
7285 (find-file-noselect file)))
7286 (if goto
7287 (progn
7288 (switch-to-buffer nbuf)
7289 (goto-char pos)
7290 (org-show-context 'org-goto))
7291 (org-copy-subtree 1 nil t)
7292 (save-excursion
7293 (set-buffer (setq nbuf (or (find-buffer-visiting file)
7294 (find-file-noselect file))))
7295 (setq reversed (org-notes-order-reversed-p))
7296 (save-excursion
7297 (save-restriction
7298 (widen)
7299 (goto-char pos)
7300 (looking-at outline-regexp)
7301 (setq level (org-get-valid-level (funcall outline-level) 1))
7302 (goto-char
7303 (if reversed
7304 (or (outline-next-heading) (point-max))
7305 (or (save-excursion (outline-get-next-sibling))
7306 (org-end-of-subtree t t)
7307 (point-max))))
7308 (if (not (bolp)) (newline))
7309 (bookmark-set "org-refile-last-stored")
7310 (org-paste-subtree level))))
7311 (org-cut-subtree)
7312 (setq org-markers-to-move nil)
7313 (message "Entry refiled to \"%s\"" (car it)))))))
7315 (defun org-refile-goto-last-stored ()
7316 "Go to the location where the last refile was stored."
7317 (interactive)
7318 (bookmark-jump "org-refile-last-stored")
7319 (message "This is the location of the last refile"))
7321 (defun org-refile-get-location (&optional prompt default-buffer)
7322 "Prompt the user for a refile location, using PROMPT."
7323 (let ((org-refile-targets org-refile-targets)
7324 (org-refile-use-outline-path org-refile-use-outline-path))
7325 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
7326 (unless org-refile-target-table
7327 (error "No refile targets"))
7328 (let* ((cbuf (current-buffer))
7329 (cfunc (if org-refile-use-outline-path
7330 'org-olpath-completing-read
7331 'completing-read))
7332 (extra (if org-refile-use-outline-path "/" ""))
7333 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7334 (fname (and filename (file-truename filename)))
7335 (tbl (mapcar
7336 (lambda (x)
7337 (if (not (equal fname (file-truename (nth 1 x))))
7338 (cons (concat (car x) extra " ("
7339 (file-name-nondirectory (nth 1 x)) ")")
7340 (cdr x))
7341 (cons (concat (car x) extra) (cdr x))))
7342 org-refile-target-table))
7343 (completion-ignore-case t))
7344 (assoc (funcall cfunc prompt tbl nil t nil 'org-refile-history)
7345 tbl)))
7347 (defun org-olpath-completing-read (prompt collection &rest args)
7348 "Read an outline path like a file name."
7349 (let ((thetable collection))
7350 (apply
7351 'completing-read prompt
7352 (lambda (string predicate &optional flag)
7353 (let (rtn r s f (l (length string)))
7354 (cond
7355 ((eq flag nil)
7356 ;; try completion
7357 (try-completion string thetable))
7358 ((eq flag t)
7359 ;; all-completions
7360 (setq rtn (all-completions string thetable predicate))
7361 (mapcar
7362 (lambda (x)
7363 (setq r (substring x l))
7364 (if (string-match " ([^)]*)$" x)
7365 (setq f (match-string 0 x))
7366 (setq f ""))
7367 (if (string-match "/" r)
7368 (concat string (substring r 0 (match-end 0)) f)
7370 rtn))
7371 ((eq flag 'lambda)
7372 ;; exact match?
7373 (assoc string thetable)))
7375 args)))
7377 ;;;; Dynamic blocks
7379 (defun org-find-dblock (name)
7380 "Find the first dynamic block with name NAME in the buffer.
7381 If not found, stay at current position and return nil."
7382 (let (pos)
7383 (save-excursion
7384 (goto-char (point-min))
7385 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
7386 nil t)
7387 (match-beginning 0))))
7388 (if pos (goto-char pos))
7389 pos))
7391 (defconst org-dblock-start-re
7392 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
7393 "Matches the startline of a dynamic block, with parameters.")
7395 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
7396 "Matches the end of a dyhamic block.")
7398 (defun org-create-dblock (plist)
7399 "Create a dynamic block section, with parameters taken from PLIST.
7400 PLIST must containe a :name entry which is used as name of the block."
7401 (unless (bolp) (newline))
7402 (let ((name (plist-get plist :name)))
7403 (insert "#+BEGIN: " name)
7404 (while plist
7405 (if (eq (car plist) :name)
7406 (setq plist (cddr plist))
7407 (insert " " (prin1-to-string (pop plist)))))
7408 (insert "\n\n#+END:\n")
7409 (beginning-of-line -2)))
7411 (defun org-prepare-dblock ()
7412 "Prepare dynamic block for refresh.
7413 This empties the block, puts the cursor at the insert position and returns
7414 the property list including an extra property :name with the block name."
7415 (unless (looking-at org-dblock-start-re)
7416 (error "Not at a dynamic block"))
7417 (let* ((begdel (1+ (match-end 0)))
7418 (name (org-no-properties (match-string 1)))
7419 (params (append (list :name name)
7420 (read (concat "(" (match-string 3) ")")))))
7421 (unless (re-search-forward org-dblock-end-re nil t)
7422 (error "Dynamic block not terminated"))
7423 (setq params
7424 (append params
7425 (list :content (buffer-substring
7426 begdel (match-beginning 0)))))
7427 (delete-region begdel (match-beginning 0))
7428 (goto-char begdel)
7429 (open-line 1)
7430 params))
7432 (defun org-map-dblocks (&optional command)
7433 "Apply COMMAND to all dynamic blocks in the current buffer.
7434 If COMMAND is not given, use `org-update-dblock'."
7435 (let ((cmd (or command 'org-update-dblock))
7436 pos)
7437 (save-excursion
7438 (goto-char (point-min))
7439 (while (re-search-forward org-dblock-start-re nil t)
7440 (goto-char (setq pos (match-beginning 0)))
7441 (condition-case nil
7442 (funcall cmd)
7443 (error (message "Error during update of dynamic block")))
7444 (goto-char pos)
7445 (unless (re-search-forward org-dblock-end-re nil t)
7446 (error "Dynamic block not terminated"))))))
7448 (defun org-dblock-update (&optional arg)
7449 "User command for updating dynamic blocks.
7450 Update the dynamic block at point. With prefix ARG, update all dynamic
7451 blocks in the buffer."
7452 (interactive "P")
7453 (if arg
7454 (org-update-all-dblocks)
7455 (or (looking-at org-dblock-start-re)
7456 (org-beginning-of-dblock))
7457 (org-update-dblock)))
7459 (defun org-update-dblock ()
7460 "Update the dynamic block at point
7461 This means to empty the block, parse for parameters and then call
7462 the correct writing function."
7463 (save-window-excursion
7464 (let* ((pos (point))
7465 (line (org-current-line))
7466 (params (org-prepare-dblock))
7467 (name (plist-get params :name))
7468 (cmd (intern (concat "org-dblock-write:" name))))
7469 (message "Updating dynamic block `%s' at line %d..." name line)
7470 (funcall cmd params)
7471 (message "Updating dynamic block `%s' at line %d...done" name line)
7472 (goto-char pos))))
7474 (defun org-beginning-of-dblock ()
7475 "Find the beginning of the dynamic block at point.
7476 Error if there is no scuh block at point."
7477 (let ((pos (point))
7478 beg)
7479 (end-of-line 1)
7480 (if (and (re-search-backward org-dblock-start-re nil t)
7481 (setq beg (match-beginning 0))
7482 (re-search-forward org-dblock-end-re nil t)
7483 (> (match-end 0) pos))
7484 (goto-char beg)
7485 (goto-char pos)
7486 (error "Not in a dynamic block"))))
7488 (defun org-update-all-dblocks ()
7489 "Update all dynamic blocks in the buffer.
7490 This function can be used in a hook."
7491 (when (org-mode-p)
7492 (org-map-dblocks 'org-update-dblock)))
7495 ;;;; Completion
7497 (defconst org-additional-option-like-keywords
7498 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
7499 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
7500 "BEGIN_EXAMPLE" "END_EXAMPLE"
7501 "BEGIN_QUOTE" "END_QUOTE"
7502 "BEGIN_VERSE" "END_VERSE"
7503 "BEGIN_SRC" "END_SRC"))
7505 (defcustom org-structure-template-alist
7507 ("s" "#+begin_src ?\n\n#+end_src"
7508 "<src lang=\"?\">\n\n</src>")
7509 ("e" "#+begin_example\n?\n#+end_example"
7510 "<example>\n?\n</example>")
7511 ("q" "#+begin_quote\n?\n#+end_quote"
7512 "<quote>\n?\n</quote>")
7513 ("v" "#+begin_verse\n?\n#+end_verse"
7514 "<verse>\n?\n/verse>")
7515 ("l" "#+begin_latex\n?\n#+end_latex"
7516 "<literal style=\"latex\">\n?\n</literal>")
7517 ("L" "#+latex: "
7518 "<literal style=\"latex\">?</literal>")
7519 ("h" "#+begin_html\n?\n#+end_html"
7520 "<literal style=\"html\">\n?\n</literal>")
7521 ("H" "#+html: "
7522 "<literal style=\"html\">?</literal>")
7523 ("a" "#+begin_ascii\n?\n#+end_ascii")
7524 ("A" "#+ascii: ")
7525 ("i" "#+include %file ?"
7526 "<include file=%file markup=\"?\">")
7528 "Structure completion elements.
7529 This is a list of abbreviation keys and values. The value gets inserted
7530 it you type @samp{.} followed by the key and then the completion key,
7531 usually `M-TAB'. %file will be replaced by a file name after prompting
7532 for the file uning completion.
7533 There are two templates for each key, the first uses the original Org syntax,
7534 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
7535 the default when the /org-mtags.el/ module has been loaded. See also the
7536 variable `org-mtags-prefere-muse-templates'.
7537 This is an experimental feature, it is undecided if it is going to stay in."
7538 :group 'org-completion
7539 :type '(repeat
7540 (string :tag "Key")
7541 (string :tag "Template")
7542 (string :tag "Muse Template")))
7544 (defun org-try-structure-completion ()
7545 "Try to complete a structure template before point.
7546 This looks for strings like \"<e\" on an otherwise empty line and
7547 expands them."
7548 (let ((l (buffer-substring (point-at-bol) (point)))
7550 (when (and (looking-at "[ \t]*$")
7551 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
7552 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
7553 (org-complete-expand-structure-template (+ -1 (point-at-bol)
7554 (match-beginning 1)) a)
7555 t)))
7557 (defun org-complete-expand-structure-template (start cell)
7558 "Expand a structure template."
7559 (let* ((musep (org-bound-and-true-p org-mtags-prefere-muse-templates))
7560 (rpl (nth (if musep 2 1) cell)))
7561 (delete-region start (point))
7562 (when (string-match "\\`#\\+" rpl)
7563 (cond
7564 ((bolp))
7565 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
7566 (delete-region (point-at-bol) (point)))
7567 (t (newline))))
7568 (setq start (point))
7569 (if (string-match "%file" rpl)
7570 (setq rpl (replace-match
7571 (concat
7572 "\""
7573 (save-match-data
7574 (abbreviate-file-name (read-file-name "Include file: ")))
7575 "\"")
7576 t t rpl)))
7577 (insert rpl)
7578 (if (re-search-backward "\\?" start t) (delete-char 1))))
7581 (defun org-complete (&optional arg)
7582 "Perform completion on word at point.
7583 At the beginning of a headline, this completes TODO keywords as given in
7584 `org-todo-keywords'.
7585 If the current word is preceded by a backslash, completes the TeX symbols
7586 that are supported for HTML support.
7587 If the current word is preceded by \"#+\", completes special words for
7588 setting file options.
7589 In the line after \"#+STARTUP:, complete valid keywords.\"
7590 At all other locations, this simply calls the value of
7591 `org-completion-fallback-command'."
7592 (interactive "P")
7593 (org-without-partial-completion
7594 (catch 'exit
7595 (let* ((a nil)
7596 (end (point))
7597 (beg1 (save-excursion
7598 (skip-chars-backward (org-re "[:alnum:]_@"))
7599 (point)))
7600 (beg (save-excursion
7601 (skip-chars-backward "a-zA-Z0-9_:$")
7602 (point)))
7603 (confirm (lambda (x) (stringp (car x))))
7604 (searchhead (equal (char-before beg) ?*))
7605 (struct
7606 (when (and (member (char-before beg1) '(?. ?<))
7607 (setq a (assoc (buffer-substring beg1 (point))
7608 org-structure-template-alist)))
7609 (org-complete-expand-structure-template (1- beg1) a)
7610 (throw 'exit t)))
7611 (tag (and (equal (char-before beg1) ?:)
7612 (equal (char-after (point-at-bol)) ?*)))
7613 (prop (and (equal (char-before beg1) ?:)
7614 (not (equal (char-after (point-at-bol)) ?*))))
7615 (texp (equal (char-before beg) ?\\))
7616 (link (equal (char-before beg) ?\[))
7617 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
7618 beg)
7619 "#+"))
7620 (startup (string-match "^#\\+STARTUP:.*"
7621 (buffer-substring (point-at-bol) (point))))
7622 (completion-ignore-case opt)
7623 (type nil)
7624 (tbl nil)
7625 (table (cond
7626 (opt
7627 (setq type :opt)
7628 (require 'org-exp)
7629 (append
7630 (mapcar
7631 (lambda (x)
7632 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
7633 (cons (match-string 2 x) (match-string 1 x)))
7634 (org-split-string (org-get-current-options) "\n"))
7635 (mapcar 'list org-additional-option-like-keywords)))
7636 (startup
7637 (setq type :startup)
7638 org-startup-options)
7639 (link (append org-link-abbrev-alist-local
7640 org-link-abbrev-alist))
7641 (texp
7642 (setq type :tex)
7643 org-html-entities)
7644 ((string-match "\\`\\*+[ \t]+\\'"
7645 (buffer-substring (point-at-bol) beg))
7646 (setq type :todo)
7647 (mapcar 'list org-todo-keywords-1))
7648 (searchhead
7649 (setq type :searchhead)
7650 (save-excursion
7651 (goto-char (point-min))
7652 (while (re-search-forward org-todo-line-regexp nil t)
7653 (push (list
7654 (org-make-org-heading-search-string
7655 (match-string 3) t))
7656 tbl)))
7657 tbl)
7658 (tag (setq type :tag beg beg1)
7659 (or org-tag-alist (org-get-buffer-tags)))
7660 (prop (setq type :prop beg beg1)
7661 (mapcar 'list (org-buffer-property-keys nil t t)))
7662 (t (progn
7663 (call-interactively org-completion-fallback-command)
7664 (throw 'exit nil)))))
7665 (pattern (buffer-substring-no-properties beg end))
7666 (completion (try-completion pattern table confirm)))
7667 (cond ((eq completion t)
7668 (if (not (assoc (upcase pattern) table))
7669 (message "Already complete")
7670 (if (and (equal type :opt)
7671 (not (member (car (assoc (upcase pattern) table))
7672 org-additional-option-like-keywords)))
7673 (insert (substring (cdr (assoc (upcase pattern) table))
7674 (length pattern)))
7675 (if (memq type '(:tag :prop)) (insert ":")))))
7676 ((null completion)
7677 (message "Can't find completion for \"%s\"" pattern)
7678 (ding))
7679 ((not (string= pattern completion))
7680 (delete-region beg end)
7681 (if (string-match " +$" completion)
7682 (setq completion (replace-match "" t t completion)))
7683 (insert completion)
7684 (if (get-buffer-window "*Completions*")
7685 (delete-window (get-buffer-window "*Completions*")))
7686 (if (assoc completion table)
7687 (if (eq type :todo) (insert " ")
7688 (if (memq type '(:tag :prop)) (insert ":"))))
7689 (if (and (equal type :opt) (assoc completion table))
7690 (message "%s" (substitute-command-keys
7691 "Press \\[org-complete] again to insert example settings"))))
7693 (message "Making completion list...")
7694 (let ((list (sort (all-completions pattern table confirm)
7695 'string<)))
7696 (with-output-to-temp-buffer "*Completions*"
7697 (condition-case nil
7698 ;; Protection needed for XEmacs and emacs 21
7699 (display-completion-list list pattern)
7700 (error (display-completion-list list)))))
7701 (message "Making completion list...%s" "done")))))))
7703 ;;;; TODO, DEADLINE, Comments
7705 (defun org-toggle-comment ()
7706 "Change the COMMENT state of an entry."
7707 (interactive)
7708 (save-excursion
7709 (org-back-to-heading)
7710 (let (case-fold-search)
7711 (if (looking-at (concat outline-regexp
7712 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
7713 (replace-match "" t t nil 1)
7714 (if (looking-at outline-regexp)
7715 (progn
7716 (goto-char (match-end 0))
7717 (insert org-comment-string " ")))))))
7719 (defvar org-last-todo-state-is-todo nil
7720 "This is non-nil when the last TODO state change led to a TODO state.
7721 If the last change removed the TODO tag or switched to DONE, then
7722 this is nil.")
7724 (defvar org-setting-tags nil) ; dynamically skiped
7726 (defun org-parse-local-options (string var)
7727 "Parse STRING for startup setting relevant for variable VAR."
7728 (let ((rtn (symbol-value var))
7729 e opts)
7730 (save-match-data
7731 (if (or (not string) (not (string-match "\\S-" string)))
7733 (setq opts (delq nil (mapcar (lambda (x)
7734 (setq e (assoc x org-startup-options))
7735 (if (eq (nth 1 e) var) e nil))
7736 (org-split-string string "[ \t]+"))))
7737 (if (not opts)
7739 (setq rtn nil)
7740 (while (setq e (pop opts))
7741 (if (not (nth 3 e))
7742 (setq rtn (nth 2 e))
7743 (if (not (listp rtn)) (setq rtn nil))
7744 (push (nth 2 e) rtn)))
7745 rtn)))))
7747 (defvar org-blocker-hook nil
7748 "Hook for functions that are allowed to block a state change.
7750 Each function gets as its single argument a property list, see
7751 `org-trigger-hook' for more information about this list.
7753 If any of the functions in this hook returns nil, the state change
7754 is blocked.")
7756 (defvar org-trigger-hook nil
7757 "Hook for functions that are triggered by a state change.
7759 Each function gets as its single argument a property list with at least
7760 the following elements:
7762 (:type type-of-change :position pos-at-entry-start
7763 :from old-state :to new-state)
7765 Depending on the type, more properties may be present.
7767 This mechanism is currently implemented for:
7769 TODO state changes
7770 ------------------
7771 :type todo-state-change
7772 :from previous state (keyword as a string), or nil
7773 :to new state (keyword as a string), or nil")
7776 (defun org-todo (&optional arg)
7777 "Change the TODO state of an item.
7778 The state of an item is given by a keyword at the start of the heading,
7779 like
7780 *** TODO Write paper
7781 *** DONE Call mom
7783 The different keywords are specified in the variable `org-todo-keywords'.
7784 By default the available states are \"TODO\" and \"DONE\".
7785 So for this example: when the item starts with TODO, it is changed to DONE.
7786 When it starts with DONE, the DONE is removed. And when neither TODO nor
7787 DONE are present, add TODO at the beginning of the heading.
7789 With C-u prefix arg, use completion to determine the new state.
7790 With numeric prefix arg, switch to that state.
7792 For calling through lisp, arg is also interpreted in the following way:
7793 'none -> empty state
7794 \"\"(empty string) -> switch to empty state
7795 'done -> switch to DONE
7796 'nextset -> switch to the next set of keywords
7797 'previousset -> switch to the previous set of keywords
7798 \"WAITING\" -> switch to the specified keyword, but only if it
7799 really is a member of `org-todo-keywords'."
7800 (interactive "P")
7801 (save-excursion
7802 (catch 'exit
7803 (org-back-to-heading)
7804 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
7805 (or (looking-at (concat " +" org-todo-regexp " *"))
7806 (looking-at " *"))
7807 (let* ((match-data (match-data))
7808 (startpos (point-at-bol))
7809 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
7810 (org-log-done org-log-done)
7811 (org-log-repeat org-log-repeat)
7812 (org-todo-log-states org-todo-log-states)
7813 (this (match-string 1))
7814 (hl-pos (match-beginning 0))
7815 (head (org-get-todo-sequence-head this))
7816 (ass (assoc head org-todo-kwd-alist))
7817 (interpret (nth 1 ass))
7818 (done-word (nth 3 ass))
7819 (final-done-word (nth 4 ass))
7820 (last-state (or this ""))
7821 (completion-ignore-case t)
7822 (member (member this org-todo-keywords-1))
7823 (tail (cdr member))
7824 (state (cond
7825 ((and org-todo-key-trigger
7826 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
7827 (and (not arg) org-use-fast-todo-selection
7828 (not (eq org-use-fast-todo-selection 'prefix)))))
7829 ;; Use fast selection
7830 (org-fast-todo-selection))
7831 ((and (equal arg '(4))
7832 (or (not org-use-fast-todo-selection)
7833 (not org-todo-key-trigger)))
7834 ;; Read a state with completion
7835 (completing-read "State: " (mapcar (lambda(x) (list x))
7836 org-todo-keywords-1)
7837 nil t))
7838 ((eq arg 'right)
7839 (if this
7840 (if tail (car tail) nil)
7841 (car org-todo-keywords-1)))
7842 ((eq arg 'left)
7843 (if (equal member org-todo-keywords-1)
7845 (if this
7846 (nth (- (length org-todo-keywords-1) (length tail) 2)
7847 org-todo-keywords-1)
7848 (org-last org-todo-keywords-1))))
7849 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
7850 (setq arg nil))) ; hack to fall back to cycling
7851 (arg
7852 ;; user or caller requests a specific state
7853 (cond
7854 ((equal arg "") nil)
7855 ((eq arg 'none) nil)
7856 ((eq arg 'done) (or done-word (car org-done-keywords)))
7857 ((eq arg 'nextset)
7858 (or (car (cdr (member head org-todo-heads)))
7859 (car org-todo-heads)))
7860 ((eq arg 'previousset)
7861 (let ((org-todo-heads (reverse org-todo-heads)))
7862 (or (car (cdr (member head org-todo-heads)))
7863 (car org-todo-heads))))
7864 ((car (member arg org-todo-keywords-1)))
7865 ((nth (1- (prefix-numeric-value arg))
7866 org-todo-keywords-1))))
7867 ((null member) (or head (car org-todo-keywords-1)))
7868 ((equal this final-done-word) nil) ;; -> make empty
7869 ((null tail) nil) ;; -> first entry
7870 ((eq interpret 'sequence)
7871 (car tail))
7872 ((memq interpret '(type priority))
7873 (if (eq this-command last-command)
7874 (car tail)
7875 (if (> (length tail) 0)
7876 (or done-word (car org-done-keywords))
7877 nil)))
7878 (t nil)))
7879 (next (if state (concat " " state " ") " "))
7880 (change-plist (list :type 'todo-state-change :from this :to state
7881 :position startpos))
7882 dolog now-done-p)
7883 (when org-blocker-hook
7884 (unless (save-excursion
7885 (save-match-data
7886 (run-hook-with-args-until-failure
7887 'org-blocker-hook change-plist)))
7888 (if (interactive-p)
7889 (error "TODO state change from %s to %s blocked" this state)
7890 ;; fail silently
7891 (message "TODO state change from %s to %s blocked" this state)
7892 (throw 'exit nil))))
7893 (store-match-data match-data)
7894 (replace-match next t t)
7895 (unless (pos-visible-in-window-p hl-pos)
7896 (message "TODO state changed to %s" (org-trim next)))
7897 (unless head
7898 (setq head (org-get-todo-sequence-head state)
7899 ass (assoc head org-todo-kwd-alist)
7900 interpret (nth 1 ass)
7901 done-word (nth 3 ass)
7902 final-done-word (nth 4 ass)))
7903 (when (memq arg '(nextset previousset))
7904 (message "Keyword-Set %d/%d: %s"
7905 (- (length org-todo-sets) -1
7906 (length (memq (assoc state org-todo-sets) org-todo-sets)))
7907 (length org-todo-sets)
7908 (mapconcat 'identity (assoc state org-todo-sets) " ")))
7909 (setq org-last-todo-state-is-todo
7910 (not (member state org-done-keywords)))
7911 (setq now-done-p (and (member state org-done-keywords)
7912 (not (member this org-done-keywords))))
7913 (and logging (org-local-logging logging))
7914 (when (and (or org-todo-log-states org-log-done)
7915 (not (memq arg '(nextset previousset))))
7916 ;; we need to look at recording a time and note
7917 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
7918 (nth 2 (assoc this org-todo-log-states))))
7919 (when (and state
7920 (member state org-not-done-keywords)
7921 (not (member this org-not-done-keywords)))
7922 ;; This is now a todo state and was not one before
7923 ;; If there was a CLOSED time stamp, get rid of it.
7924 (org-add-planning-info nil nil 'closed))
7925 (when (and now-done-p org-log-done)
7926 ;; It is now done, and it was not done before
7927 (org-add-planning-info 'closed (org-current-time))
7928 (if (and (not dolog) (eq 'note org-log-done))
7929 (org-add-log-setup 'done state 'findpos 'note)))
7930 (when (and state dolog)
7931 ;; This is a non-nil state, and we need to log it
7932 (org-add-log-setup 'state state 'findpos dolog)))
7933 ;; Fixup tag positioning
7934 (org-todo-trigger-tag-changes state)
7935 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
7936 (when org-provide-todo-statistics
7937 (org-update-parent-todo-statistics))
7938 (run-hooks 'org-after-todo-state-change-hook)
7939 (if (and arg (not (member state org-done-keywords)))
7940 (setq head (org-get-todo-sequence-head state)))
7941 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
7942 ;; Do we need to trigger a repeat?
7943 (when now-done-p (org-auto-repeat-maybe state))
7944 ;; Fixup cursor location if close to the keyword
7945 (if (and (outline-on-heading-p)
7946 (not (bolp))
7947 (save-excursion (beginning-of-line 1)
7948 (looking-at org-todo-line-regexp))
7949 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
7950 (progn
7951 (goto-char (or (match-end 2) (match-end 1)))
7952 (just-one-space)))
7953 (when org-trigger-hook
7954 (save-excursion
7955 (run-hook-with-args 'org-trigger-hook change-plist)))))))
7957 (defun org-update-parent-todo-statistics ()
7958 "Update any statistics cookie in the parent of the current headline."
7959 (interactive)
7960 (let ((box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
7961 level (cnt-all 0) (cnt-done 0) is-percent kwd)
7962 (catch 'exit
7963 (save-excursion
7964 (setq level (org-up-heading-safe))
7965 (unless (and level
7966 (re-search-forward box-re (point-at-eol) t))
7967 (throw 'exit nil))
7968 (setq is-percent (match-end 2))
7969 (save-match-data
7970 (unless (outline-next-heading) (throw 'exit nil))
7971 (while (looking-at org-todo-line-regexp)
7972 (setq kwd (match-string 2))
7973 (and kwd (setq cnt-all (1+ cnt-all)))
7974 (and (member kwd org-done-keywords)
7975 (setq cnt-done (1+ cnt-done)))
7976 (condition-case nil
7977 (org-forward-same-level 1)
7978 (error (end-of-line 1)))))
7979 (replace-match
7980 (if is-percent
7981 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
7982 (format "[%d/%d]" cnt-done cnt-all)))
7983 (run-hook-with-args 'org-after-todo-statistics-hook
7984 cnt-done (- cnt-all cnt-done))))))
7986 (defvar org-after-todo-statistics-hook nil
7987 "Hook that is called after a TODO statistics cookie has been updated.
7988 Each function is called with two arguments: the number of not-done entries
7989 and the number of done entries.
7991 For example, the following function, when added to this hook, will switch
7992 an entry to DONE when all children are done, and back to TODO when new
7993 entries are set to a TODO status. Note that this hook is only called
7994 when there is a statistics cookie in the headline!
7996 (defun org-summary-todo (n-done n-not-done)
7997 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
7998 (let (org-log-done org-log-states) ; turn off logging
7999 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
8002 (defun org-todo-trigger-tag-changes (state)
8003 "Apply the changes defined in `org-todo-state-tags-triggers'."
8004 (let ((l org-todo-state-tags-triggers)
8005 changes)
8006 (when (or (not state) (equal state ""))
8007 (setq changes (append changes (cdr (assoc "" l)))))
8008 (when (and (stringp state) (> (length state) 0))
8009 (setq changes (append changes (cdr (assoc state l)))))
8010 (when (member state org-not-done-keywords)
8011 (setq changes (append changes (cdr (assoc 'todo l)))))
8012 (when (member state org-done-keywords)
8013 (setq changes (append changes (cdr (assoc 'done l)))))
8014 (dolist (c changes)
8015 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
8017 (defun org-local-logging (value)
8018 "Get logging settings from a property VALUE."
8019 (let* (words w a)
8020 ;; directly set the variables, they are already local.
8021 (setq org-log-done nil
8022 org-log-repeat nil
8023 org-todo-log-states nil)
8024 (setq words (org-split-string value))
8025 (while (setq w (pop words))
8026 (cond
8027 ((setq a (assoc w org-startup-options))
8028 (and (member (nth 1 a) '(org-log-done org-log-repeat))
8029 (set (nth 1 a) (nth 2 a))))
8030 ((setq a (org-extract-log-state-settings w))
8031 (and (member (car a) org-todo-keywords-1)
8032 (push a org-todo-log-states)))))))
8034 (defun org-get-todo-sequence-head (kwd)
8035 "Return the head of the TODO sequence to which KWD belongs.
8036 If KWD is not set, check if there is a text property remembering the
8037 right sequence."
8038 (let (p)
8039 (cond
8040 ((not kwd)
8041 (or (get-text-property (point-at-bol) 'org-todo-head)
8042 (progn
8043 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
8044 nil (point-at-eol)))
8045 (get-text-property p 'org-todo-head))))
8046 ((not (member kwd org-todo-keywords-1))
8047 (car org-todo-keywords-1))
8048 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
8050 (defun org-fast-todo-selection ()
8051 "Fast TODO keyword selection with single keys.
8052 Returns the new TODO keyword, or nil if no state change should occur."
8053 (let* ((fulltable org-todo-key-alist)
8054 (done-keywords org-done-keywords) ;; needed for the faces.
8055 (maxlen (apply 'max (mapcar
8056 (lambda (x)
8057 (if (stringp (car x)) (string-width (car x)) 0))
8058 fulltable)))
8059 (expert nil)
8060 (fwidth (+ maxlen 3 1 3))
8061 (ncol (/ (- (window-width) 4) fwidth))
8062 tg cnt e c tbl
8063 groups ingroup)
8064 (save-window-excursion
8065 (if expert
8066 (set-buffer (get-buffer-create " *Org todo*"))
8067 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
8068 (erase-buffer)
8069 (org-set-local 'org-done-keywords done-keywords)
8070 (setq tbl fulltable cnt 0)
8071 (while (setq e (pop tbl))
8072 (cond
8073 ((equal e '(:startgroup))
8074 (push '() groups) (setq ingroup t)
8075 (when (not (= cnt 0))
8076 (setq cnt 0)
8077 (insert "\n"))
8078 (insert "{ "))
8079 ((equal e '(:endgroup))
8080 (setq ingroup nil cnt 0)
8081 (insert "}\n"))
8083 (setq tg (car e) c (cdr e))
8084 (if ingroup (push tg (car groups)))
8085 (setq tg (org-add-props tg nil 'face
8086 (org-get-todo-face tg)))
8087 (if (and (= cnt 0) (not ingroup)) (insert " "))
8088 (insert "[" c "] " tg (make-string
8089 (- fwidth 4 (length tg)) ?\ ))
8090 (when (= (setq cnt (1+ cnt)) ncol)
8091 (insert "\n")
8092 (if ingroup (insert " "))
8093 (setq cnt 0)))))
8094 (insert "\n")
8095 (goto-char (point-min))
8096 (if (and (not expert) (fboundp 'fit-window-to-buffer))
8097 (fit-window-to-buffer))
8098 (message "[a-z..]:Set [SPC]:clear")
8099 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
8100 (cond
8101 ((or (= c ?\C-g)
8102 (and (= c ?q) (not (rassoc c fulltable))))
8103 (setq quit-flag t))
8104 ((= c ?\ ) nil)
8105 ((setq e (rassoc c fulltable) tg (car e))
8107 (t (setq quit-flag t))))))
8109 (defun org-entry-is-todo-p ()
8110 (member (org-get-todo-state) org-not-done-keywords))
8112 (defun org-entry-is-done-p ()
8113 (member (org-get-todo-state) org-done-keywords))
8115 (defun org-get-todo-state ()
8116 (save-excursion
8117 (org-back-to-heading t)
8118 (and (looking-at org-todo-line-regexp)
8119 (match-end 2)
8120 (match-string 2))))
8122 (defun org-at-date-range-p (&optional inactive-ok)
8123 "Is the cursor inside a date range?"
8124 (interactive)
8125 (save-excursion
8126 (catch 'exit
8127 (let ((pos (point)))
8128 (skip-chars-backward "^[<\r\n")
8129 (skip-chars-backward "<[")
8130 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8131 (>= (match-end 0) pos)
8132 (throw 'exit t))
8133 (skip-chars-backward "^<[\r\n")
8134 (skip-chars-backward "<[")
8135 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8136 (>= (match-end 0) pos)
8137 (throw 'exit t)))
8138 nil)))
8140 (defun org-get-repeat ()
8141 "Check if there is a deadline/schedule with repeater in this entry."
8142 (save-match-data
8143 (save-excursion
8144 (org-back-to-heading t)
8145 (if (re-search-forward
8146 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
8147 (match-string 1)))))
8149 (defvar org-last-changed-timestamp)
8150 (defvar org-last-inserted-timestamp)
8151 (defvar org-log-post-message)
8152 (defvar org-log-note-purpose)
8153 (defvar org-log-note-how)
8154 (defvar org-log-note-extra)
8155 (defun org-auto-repeat-maybe (done-word)
8156 "Check if the current headline contains a repeated deadline/schedule.
8157 If yes, set TODO state back to what it was and change the base date
8158 of repeating deadline/scheduled time stamps to new date.
8159 This function is run automatically after each state change to a DONE state."
8160 ;; last-state is dynamically scoped into this function
8161 (let* ((repeat (org-get-repeat))
8162 (aa (assoc last-state org-todo-kwd-alist))
8163 (interpret (nth 1 aa))
8164 (head (nth 2 aa))
8165 (whata '(("d" . day) ("m" . month) ("y" . year)))
8166 (msg "Entry repeats: ")
8167 (org-log-done nil)
8168 (org-todo-log-states nil)
8169 (nshiftmax 10) (nshift 0)
8170 re type n what ts mb0 time)
8171 (when repeat
8172 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
8173 (org-todo (if (eq interpret 'type) last-state head))
8174 (when org-log-repeat
8175 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
8176 (memq 'org-add-log-note post-command-hook))
8177 ;; OK, we are already setup for some record
8178 (if (eq org-log-repeat 'note)
8179 ;; make sure we take a note, not only a time stamp
8180 (setq org-log-note-how 'note))
8181 ;; Set up for taking a record
8182 (org-add-log-setup 'state (or done-word (car org-done-keywords))
8183 'findpos org-log-repeat)))
8184 (org-back-to-heading t)
8185 (org-add-planning-info nil nil 'closed)
8186 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
8187 org-deadline-time-regexp "\\)\\|\\("
8188 org-ts-regexp "\\)"))
8189 (while (re-search-forward
8190 re (save-excursion (outline-next-heading) (point)) t)
8191 (setq type (if (match-end 1) org-scheduled-string
8192 (if (match-end 3) org-deadline-string "Plain:"))
8193 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0)))
8194 mb0 (match-beginning 0))
8195 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
8196 (setq n (string-to-number (match-string 2 ts))
8197 what (match-string 3 ts))
8198 (if (equal what "w") (setq n (* n 7) what "d"))
8199 ;; Preparation, see if we need to modify the start date for the change
8200 (when (match-end 1)
8201 (setq time (save-match-data (org-time-string-to-time ts)))
8202 (cond
8203 ((equal (match-string 1 ts) ".")
8204 ;; Shift starting date to today
8205 (org-timestamp-change
8206 (- (time-to-days (current-time)) (time-to-days time))
8207 'day))
8208 ((equal (match-string 1 ts) "+")
8209 (while (or (= nshift 0)
8210 (<= (time-to-days time) (time-to-days (current-time))))
8211 (when (= (incf nshift) nshiftmax)
8212 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
8213 (error "Abort")))
8214 (org-timestamp-change n (cdr (assoc what whata)))
8215 (org-at-timestamp-p t)
8216 (setq ts (match-string 1))
8217 (setq time (save-match-data (org-time-string-to-time ts))))
8218 (org-timestamp-change (- n) (cdr (assoc what whata)))
8219 ;; rematch, so that we have everything in place for the real shift
8220 (org-at-timestamp-p t)
8221 (setq ts (match-string 1))
8222 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
8223 (org-timestamp-change n (cdr (assoc what whata)))
8224 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
8225 (setq org-log-post-message msg)
8226 (message "%s" msg))))
8228 (defun org-show-todo-tree (arg)
8229 "Make a compact tree which shows all headlines marked with TODO.
8230 The tree will show the lines where the regexp matches, and all higher
8231 headlines above the match.
8232 With a \\[universal-argument] prefix, also show the DONE entries.
8233 With a numeric prefix N, construct a sparse tree for the Nth element
8234 of `org-todo-keywords-1'."
8235 (interactive "P")
8236 (let ((case-fold-search nil)
8237 (kwd-re
8238 (cond ((null arg) org-not-done-regexp)
8239 ((equal arg '(4))
8240 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
8241 (mapcar 'list org-todo-keywords-1))))
8242 (concat "\\("
8243 (mapconcat 'identity (org-split-string kwd "|") "\\|")
8244 "\\)\\>")))
8245 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
8246 (regexp-quote (nth (1- (prefix-numeric-value arg))
8247 org-todo-keywords-1)))
8248 (t (error "Invalid prefix argument: %s" arg)))))
8249 (message "%d TODO entries found"
8250 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
8252 (defun org-deadline (&optional remove time)
8253 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
8254 With argument REMOVE, remove any deadline from the item.
8255 When TIME is set, it should be an internal time specification, and the
8256 scheduling will use the corresponding date."
8257 (interactive "P")
8258 (if remove
8259 (progn
8260 (org-remove-timestamp-with-keyword org-deadline-string)
8261 (message "Item no longer has a deadline."))
8262 (if (org-get-repeat)
8263 (error "Cannot change deadline on task with repeater, please do that by hand")
8264 (org-add-planning-info 'deadline time 'closed)
8265 (message "Deadline on %s" org-last-inserted-timestamp))))
8267 (defun org-schedule (&optional remove time)
8268 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
8269 With argument REMOVE, remove any scheduling date from the item.
8270 When TIME is set, it should be an internal time specification, and the
8271 scheduling will use the corresponding date."
8272 (interactive "P")
8273 (if remove
8274 (progn
8275 (org-remove-timestamp-with-keyword org-scheduled-string)
8276 (message "Item is no longer scheduled."))
8277 (if (org-get-repeat)
8278 (error "Cannot reschedule task with repeater, please do that by hand")
8279 (org-add-planning-info 'scheduled time 'closed)
8280 (message "Scheduled to %s" org-last-inserted-timestamp))))
8282 (defun org-remove-timestamp-with-keyword (keyword)
8283 "Remove all time stamps with KEYWORD in the current entry."
8284 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
8285 beg)
8286 (save-excursion
8287 (org-back-to-heading t)
8288 (setq beg (point))
8289 (org-end-of-subtree t t)
8290 (while (re-search-backward re beg t)
8291 (replace-match "")
8292 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
8293 (equal (char-before) ?\ ))
8294 (backward-delete-char 1)
8295 (if (string-match "^[ \t]*$" (buffer-substring
8296 (point-at-bol) (point-at-eol)))
8297 (delete-region (point-at-bol)
8298 (min (point-max) (1+ (point-at-eol))))))))))
8300 (defun org-add-planning-info (what &optional time &rest remove)
8301 "Insert new timestamp with keyword in the line directly after the headline.
8302 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
8303 If non is given, the user is prompted for a date.
8304 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
8305 be removed."
8306 (interactive)
8307 (let (org-time-was-given org-end-time-was-given ts
8308 end default-time default-input)
8310 (when (and (not time) (memq what '(scheduled deadline)))
8311 ;; Try to get a default date/time from existing timestamp
8312 (save-excursion
8313 (org-back-to-heading t)
8314 (setq end (save-excursion (outline-next-heading) (point)))
8315 (when (re-search-forward (if (eq what 'scheduled)
8316 org-scheduled-time-regexp
8317 org-deadline-time-regexp)
8318 end t)
8319 (setq ts (match-string 1)
8320 default-time
8321 (apply 'encode-time (org-parse-time-string ts))
8322 default-input (and ts (org-get-compact-tod ts))))))
8323 (when what
8324 ;; If necessary, get the time from the user
8325 (setq time (or time (org-read-date nil 'to-time nil nil
8326 default-time default-input))))
8328 (when (and org-insert-labeled-timestamps-at-point
8329 (member what '(scheduled deadline)))
8330 (insert
8331 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
8332 (org-insert-time-stamp time org-time-was-given
8333 nil nil nil (list org-end-time-was-given))
8334 (setq what nil))
8335 (save-excursion
8336 (save-restriction
8337 (let (col list elt ts buffer-invisibility-spec)
8338 (org-back-to-heading t)
8339 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
8340 (goto-char (match-end 1))
8341 (setq col (current-column))
8342 (goto-char (match-end 0))
8343 (if (eobp) (insert "\n") (forward-char 1))
8344 (if (and (not (looking-at outline-regexp))
8345 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
8346 "[^\r\n]*"))
8347 (not (equal (match-string 1) org-clock-string)))
8348 (narrow-to-region (match-beginning 0) (match-end 0))
8349 (insert-before-markers "\n")
8350 (backward-char 1)
8351 (narrow-to-region (point) (point))
8352 (and org-adapt-indentation (org-indent-to-column col)))
8353 ;; Check if we have to remove something.
8354 (setq list (cons what remove))
8355 (while list
8356 (setq elt (pop list))
8357 (goto-char (point-min))
8358 (when (or (and (eq elt 'scheduled)
8359 (re-search-forward org-scheduled-time-regexp nil t))
8360 (and (eq elt 'deadline)
8361 (re-search-forward org-deadline-time-regexp nil t))
8362 (and (eq elt 'closed)
8363 (re-search-forward org-closed-time-regexp nil t)))
8364 (replace-match "")
8365 (if (looking-at "--+<[^>]+>") (replace-match ""))
8366 (if (looking-at " +") (replace-match ""))))
8367 (goto-char (point-max))
8368 (when what
8369 (insert
8370 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
8371 (cond ((eq what 'scheduled) org-scheduled-string)
8372 ((eq what 'deadline) org-deadline-string)
8373 ((eq what 'closed) org-closed-string))
8374 " ")
8375 (setq ts (org-insert-time-stamp
8376 time
8377 (or org-time-was-given
8378 (and (eq what 'closed) org-log-done-with-time))
8379 (eq what 'closed)
8380 nil nil (list org-end-time-was-given)))
8381 (end-of-line 1))
8382 (goto-char (point-min))
8383 (widen)
8384 (if (and (looking-at "[ \t]+\n")
8385 (equal (char-before) ?\n))
8386 (delete-region (1- (point)) (point-at-eol)))
8387 ts)))))
8389 (defvar org-log-note-marker (make-marker))
8390 (defvar org-log-note-purpose nil)
8391 (defvar org-log-note-state nil)
8392 (defvar org-log-note-how nil)
8393 (defvar org-log-note-extra nil)
8394 (defvar org-log-note-window-configuration nil)
8395 (defvar org-log-note-return-to (make-marker))
8396 (defvar org-log-post-message nil
8397 "Message to be displayed after a log note has been stored.
8398 The auto-repeater uses this.")
8400 (defun org-add-note ()
8401 "Add a note to the current entry.
8402 This is done in the same way as adding a state change note."
8403 (interactive)
8404 (org-add-log-setup 'note nil 'findpos nil))
8406 (defvar org-property-end-re)
8407 (defun org-add-log-setup (&optional purpose state findpos how &optional extra)
8408 "Set up the post command hook to take a note.
8409 If this is about to TODO state change, the new state is expected in STATE.
8410 When FINDPOS is non-nil, find the correct position for the note in
8411 the current entry. If not, assume that it can be inserted at point.
8412 HOW is an indicator what kind of note should be created.
8413 EXTRA is additional text that will be inserted into the notes buffer."
8414 (save-restriction
8415 (save-excursion
8416 (when findpos
8417 (org-back-to-heading t)
8418 (narrow-to-region (point) (save-excursion
8419 (outline-next-heading) (point)))
8420 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
8421 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
8422 "[^\r\n]*\\)?"))
8423 (goto-char (match-end 0))
8424 (when (and org-log-state-notes-insert-after-drawers
8425 (save-excursion
8426 (forward-line) (looking-at org-drawer-regexp)))
8427 (progn (forward-line)
8428 (while (looking-at org-drawer-regexp)
8429 (goto-char (match-end 0))
8430 (re-search-forward org-property-end-re (point-max) t)
8431 (forward-line))
8432 (forward-line -1)))
8433 (unless org-log-states-order-reversed
8434 (and (= (char-after) ?\n) (forward-char 1))
8435 (org-skip-over-state-notes)
8436 (skip-chars-backward " \t\n\r")))
8437 (move-marker org-log-note-marker (point))
8438 (setq org-log-note-purpose purpose
8439 org-log-note-state state
8440 org-log-note-how how
8441 org-log-note-extra extra)
8442 (add-hook 'post-command-hook 'org-add-log-note 'append))))
8444 (defun org-skip-over-state-notes ()
8445 "Skip past the list of State notes in an entry."
8446 (if (looking-at "\n[ \t]*- State") (forward-char 1))
8447 (while (looking-at "[ \t]*- State")
8448 (condition-case nil
8449 (org-next-item)
8450 (error (org-end-of-item)))))
8452 (defun org-add-log-note (&optional purpose)
8453 "Pop up a window for taking a note, and add this note later at point."
8454 (remove-hook 'post-command-hook 'org-add-log-note)
8455 (setq org-log-note-window-configuration (current-window-configuration))
8456 (delete-other-windows)
8457 (move-marker org-log-note-return-to (point))
8458 (switch-to-buffer (marker-buffer org-log-note-marker))
8459 (goto-char org-log-note-marker)
8460 (org-switch-to-buffer-other-window "*Org Note*")
8461 (erase-buffer)
8462 (if (memq org-log-note-how '(time state))
8463 (let (current-prefix-arg) (org-store-log-note))
8464 (let ((org-inhibit-startup t)) (org-mode))
8465 (insert (format "# Insert note for %s.
8466 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
8467 (cond
8468 ((eq org-log-note-purpose 'clock-out) "stopped clock")
8469 ((eq org-log-note-purpose 'done) "closed todo item")
8470 ((eq org-log-note-purpose 'state)
8471 (format "state change to \"%s\"" org-log-note-state))
8472 ((eq org-log-note-purpose 'note)
8473 "this entry")
8474 (t (error "This should not happen")))))
8475 (if org-log-note-extra (insert org-log-note-extra))
8476 (org-set-local 'org-finish-function 'org-store-log-note)))
8478 (defvar org-note-abort nil) ; dynamically scoped
8479 (defun org-store-log-note ()
8480 "Finish taking a log note, and insert it to where it belongs."
8481 (let ((txt (buffer-string))
8482 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
8483 lines ind)
8484 (kill-buffer (current-buffer))
8485 (while (string-match "\\`#.*\n[ \t\n]*" txt)
8486 (setq txt (replace-match "" t t txt)))
8487 (if (string-match "\\s-+\\'" txt)
8488 (setq txt (replace-match "" t t txt)))
8489 (setq lines (org-split-string txt "\n"))
8490 (when (and note (string-match "\\S-" note))
8491 (setq note
8492 (org-replace-escapes
8493 note
8494 (list (cons "%u" (user-login-name))
8495 (cons "%U" user-full-name)
8496 (cons "%t" (format-time-string
8497 (org-time-stamp-format 'long 'inactive)
8498 (current-time)))
8499 (cons "%s" (if org-log-note-state
8500 (concat "\"" org-log-note-state "\"")
8501 "")))))
8502 (if lines (setq note (concat note " \\\\")))
8503 (push note lines))
8504 (when (or current-prefix-arg org-note-abort) (setq lines nil))
8505 (when lines
8506 (save-excursion
8507 (set-buffer (marker-buffer org-log-note-marker))
8508 (save-excursion
8509 (goto-char org-log-note-marker)
8510 (move-marker org-log-note-marker nil)
8511 (end-of-line 1)
8512 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
8513 (indent-relative nil)
8514 (insert "- " (pop lines))
8515 (org-indent-line-function)
8516 (beginning-of-line 1)
8517 (looking-at "[ \t]*")
8518 (setq ind (concat (match-string 0) " "))
8519 (end-of-line 1)
8520 (while lines (insert "\n" ind (pop lines)))))))
8521 (set-window-configuration org-log-note-window-configuration)
8522 (with-current-buffer (marker-buffer org-log-note-return-to)
8523 (goto-char org-log-note-return-to))
8524 (move-marker org-log-note-return-to nil)
8525 (and org-log-post-message (message "%s" org-log-post-message)))
8527 (defun org-sparse-tree (&optional arg)
8528 "Create a sparse tree, prompt for the details.
8529 This command can create sparse trees. You first need to select the type
8530 of match used to create the tree:
8532 t Show entries with a specific TODO keyword.
8533 T Show entries selected by a tags match.
8534 p Enter a property name and its value (both with completion on existing
8535 names/values) and show entries with that property.
8536 r Show entries matching a regular expression
8537 d Show deadlines due within `org-deadline-warning-days'."
8538 (interactive "P")
8539 (let (ans kwd value)
8540 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
8541 (setq ans (read-char-exclusive))
8542 (cond
8543 ((equal ans ?d)
8544 (call-interactively 'org-check-deadlines))
8545 ((equal ans ?b)
8546 (call-interactively 'org-check-before-date))
8547 ((equal ans ?t)
8548 (org-show-todo-tree '(4)))
8549 ((equal ans ?T)
8550 (call-interactively 'org-tags-sparse-tree))
8551 ((member ans '(?p ?P))
8552 (setq kwd (completing-read "Property: "
8553 (mapcar 'list (org-buffer-property-keys))))
8554 (setq value (completing-read "Value: "
8555 (mapcar 'list (org-property-values kwd))))
8556 (unless (string-match "\\`{.*}\\'" value)
8557 (setq value (concat "\"" value "\"")))
8558 (org-tags-sparse-tree arg (concat kwd "=" value)))
8559 ((member ans '(?r ?R ?/))
8560 (call-interactively 'org-occur))
8561 (t (error "No such sparse tree command \"%c\"" ans)))))
8563 (defvar org-occur-highlights nil
8564 "List of overlays used for occur matches.")
8565 (make-variable-buffer-local 'org-occur-highlights)
8566 (defvar org-occur-parameters nil
8567 "Parameters of the active org-occur calls.
8568 This is a list, each call to org-occur pushes as cons cell,
8569 containing the regular expression and the callback, onto the list.
8570 The list can contain several entries if `org-occur' has been called
8571 several time with the KEEP-PREVIOUS argument. Otherwise, this list
8572 will only contain one set of parameters. When the highlights are
8573 removed (for example with `C-c C-c', or with the next edit (depending
8574 on `org-remove-highlights-with-change'), this variable is emptied
8575 as well.")
8576 (make-variable-buffer-local 'org-occur-parameters)
8578 (defun org-occur (regexp &optional keep-previous callback)
8579 "Make a compact tree which shows all matches of REGEXP.
8580 The tree will show the lines where the regexp matches, and all higher
8581 headlines above the match. It will also show the heading after the match,
8582 to make sure editing the matching entry is easy.
8583 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
8584 call to `org-occur' will be kept, to allow stacking of calls to this
8585 command.
8586 If CALLBACK is non-nil, it is a function which is called to confirm
8587 that the match should indeed be shown."
8588 (interactive "sRegexp: \nP")
8589 (unless keep-previous
8590 (org-remove-occur-highlights nil nil t))
8591 (push (cons regexp callback) org-occur-parameters)
8592 (let ((cnt 0))
8593 (save-excursion
8594 (goto-char (point-min))
8595 (if (or (not keep-previous) ; do not want to keep
8596 (not org-occur-highlights)) ; no previous matches
8597 ;; hide everything
8598 (org-overview))
8599 (while (re-search-forward regexp nil t)
8600 (when (or (not callback)
8601 (save-match-data (funcall callback)))
8602 (setq cnt (1+ cnt))
8603 (when org-highlight-sparse-tree-matches
8604 (org-highlight-new-match (match-beginning 0) (match-end 0)))
8605 (org-show-context 'occur-tree))))
8606 (when org-remove-highlights-with-change
8607 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
8608 nil 'local))
8609 (unless org-sparse-tree-open-archived-trees
8610 (org-hide-archived-subtrees (point-min) (point-max)))
8611 (run-hooks 'org-occur-hook)
8612 (if (interactive-p)
8613 (message "%d match(es) for regexp %s" cnt regexp))
8614 cnt))
8616 (defun org-show-context (&optional key)
8617 "Make sure point and context and visible.
8618 How much context is shown depends upon the variables
8619 `org-show-hierarchy-above', `org-show-following-heading'. and
8620 `org-show-siblings'."
8621 (let ((heading-p (org-on-heading-p t))
8622 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
8623 (following-p (org-get-alist-option org-show-following-heading key))
8624 (entry-p (org-get-alist-option org-show-entry-below key))
8625 (siblings-p (org-get-alist-option org-show-siblings key)))
8626 (catch 'exit
8627 ;; Show heading or entry text
8628 (if (and heading-p (not entry-p))
8629 (org-flag-heading nil) ; only show the heading
8630 (and (or entry-p (org-invisible-p) (org-invisible-p2))
8631 (org-show-hidden-entry))) ; show entire entry
8632 (when following-p
8633 ;; Show next sibling, or heading below text
8634 (save-excursion
8635 (and (if heading-p (org-goto-sibling) (outline-next-heading))
8636 (org-flag-heading nil))))
8637 (when siblings-p (org-show-siblings))
8638 (when hierarchy-p
8639 ;; show all higher headings, possibly with siblings
8640 (save-excursion
8641 (while (and (condition-case nil
8642 (progn (org-up-heading-all 1) t)
8643 (error nil))
8644 (not (bobp)))
8645 (org-flag-heading nil)
8646 (when siblings-p (org-show-siblings))))))))
8648 (defun org-reveal (&optional siblings)
8649 "Show current entry, hierarchy above it, and the following headline.
8650 This can be used to show a consistent set of context around locations
8651 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
8652 not t for the search context.
8654 With optional argument SIBLINGS, on each level of the hierarchy all
8655 siblings are shown. This repairs the tree structure to what it would
8656 look like when opened with hierarchical calls to `org-cycle'."
8657 (interactive "P")
8658 (let ((org-show-hierarchy-above t)
8659 (org-show-following-heading t)
8660 (org-show-siblings (if siblings t org-show-siblings)))
8661 (org-show-context nil)))
8663 (defun org-highlight-new-match (beg end)
8664 "Highlight from BEG to END and mark the highlight is an occur headline."
8665 (let ((ov (org-make-overlay beg end)))
8666 (org-overlay-put ov 'face 'secondary-selection)
8667 (push ov org-occur-highlights)))
8669 (defun org-remove-occur-highlights (&optional beg end noremove)
8670 "Remove the occur highlights from the buffer.
8671 BEG and END are ignored. If NOREMOVE is nil, remove this function
8672 from the `before-change-functions' in the current buffer."
8673 (interactive)
8674 (unless org-inhibit-highlight-removal
8675 (mapc 'org-delete-overlay org-occur-highlights)
8676 (setq org-occur-highlights nil)
8677 (setq org-occur-parameters nil)
8678 (unless noremove
8679 (remove-hook 'before-change-functions
8680 'org-remove-occur-highlights 'local))))
8682 ;;;; Priorities
8684 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
8685 "Regular expression matching the priority indicator.")
8687 (defvar org-remove-priority-next-time nil)
8689 (defun org-priority-up ()
8690 "Increase the priority of the current item."
8691 (interactive)
8692 (org-priority 'up))
8694 (defun org-priority-down ()
8695 "Decrease the priority of the current item."
8696 (interactive)
8697 (org-priority 'down))
8699 (defun org-priority (&optional action)
8700 "Change the priority of an item by ARG.
8701 ACTION can be `set', `up', `down', or a character."
8702 (interactive)
8703 (setq action (or action 'set))
8704 (let (current new news have remove)
8705 (save-excursion
8706 (org-back-to-heading)
8707 (if (looking-at org-priority-regexp)
8708 (setq current (string-to-char (match-string 2))
8709 have t)
8710 (setq current org-default-priority))
8711 (cond
8712 ((or (eq action 'set)
8713 (if (featurep 'xemacs) (characterp action) (integerp action)))
8714 (if (not (eq action 'set))
8715 (setq new action)
8716 (message "Priority %c-%c, SPC to remove: "
8717 org-highest-priority org-lowest-priority)
8718 (setq new (read-char-exclusive)))
8719 (if (and (= (upcase org-highest-priority) org-highest-priority)
8720 (= (upcase org-lowest-priority) org-lowest-priority))
8721 (setq new (upcase new)))
8722 (cond ((equal new ?\ ) (setq remove t))
8723 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
8724 (error "Priority must be between `%c' and `%c'"
8725 org-highest-priority org-lowest-priority))))
8726 ((eq action 'up)
8727 (if (and (not have) (eq last-command this-command))
8728 (setq new org-lowest-priority)
8729 (setq new (if (and org-priority-start-cycle-with-default (not have))
8730 org-default-priority (1- current)))))
8731 ((eq action 'down)
8732 (if (and (not have) (eq last-command this-command))
8733 (setq new org-highest-priority)
8734 (setq new (if (and org-priority-start-cycle-with-default (not have))
8735 org-default-priority (1+ current)))))
8736 (t (error "Invalid action")))
8737 (if (or (< (upcase new) org-highest-priority)
8738 (> (upcase new) org-lowest-priority))
8739 (setq remove t))
8740 (setq news (format "%c" new))
8741 (if have
8742 (if remove
8743 (replace-match "" t t nil 1)
8744 (replace-match news t t nil 2))
8745 (if remove
8746 (error "No priority cookie found in line")
8747 (looking-at org-todo-line-regexp)
8748 (if (match-end 2)
8749 (progn
8750 (goto-char (match-end 2))
8751 (insert " [#" news "]"))
8752 (goto-char (match-beginning 3))
8753 (insert "[#" news "] ")))))
8754 (org-preserve-lc (org-set-tags nil 'align))
8755 (if remove
8756 (message "Priority removed")
8757 (message "Priority of current item set to %s" news))))
8760 (defun org-get-priority (s)
8761 "Find priority cookie and return priority."
8762 (save-match-data
8763 (if (not (string-match org-priority-regexp s))
8764 (* 1000 (- org-lowest-priority org-default-priority))
8765 (* 1000 (- org-lowest-priority
8766 (string-to-char (match-string 2 s)))))))
8768 ;;;; Tags
8770 (defvar org-agenda-archives-mode)
8771 (defun org-scan-tags (action matcher &optional todo-only)
8772 "Scan headline tags with inheritance and produce output ACTION.
8774 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
8775 or `agenda' to produce an entry list for an agenda view. It can also be
8776 a Lisp form or a function that should be called at each matched headline, in
8777 this case the return value is a list of all return values from these calls.
8779 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
8780 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
8781 only lines with a TODO keyword are included in the output."
8782 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
8783 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
8784 (org-re
8785 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
8786 (props (list 'face 'default
8787 'done-face 'org-done
8788 'undone-face 'default
8789 'mouse-face 'highlight
8790 'org-not-done-regexp org-not-done-regexp
8791 'org-todo-regexp org-todo-regexp
8792 'keymap org-agenda-keymap
8793 'help-echo
8794 (format "mouse-2 or RET jump to org file %s"
8795 (abbreviate-file-name
8796 (or (buffer-file-name (buffer-base-buffer))
8797 (buffer-name (buffer-base-buffer)))))))
8798 (case-fold-search nil)
8799 lspos tags tags-list
8800 (tags-alist (list (cons 0 (mapcar 'downcase org-file-tags))))
8801 (llast 0) rtn rtn1 level category i txt
8802 todo marker entry priority)
8803 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
8804 (setq action (list 'lambda nil action)))
8805 (save-excursion
8806 (goto-char (point-min))
8807 (when (eq action 'sparse-tree)
8808 (org-overview)
8809 (org-remove-occur-highlights))
8810 (while (re-search-forward re nil t)
8811 (catch :skip
8812 (setq todo (if (match-end 1) (match-string 2))
8813 tags (if (match-end 4) (match-string 4)))
8814 (goto-char (setq lspos (1+ (match-beginning 0))))
8815 (setq level (org-reduced-level (funcall outline-level))
8816 category (org-get-category))
8817 (setq i llast llast level)
8818 ;; remove tag lists from same and sublevels
8819 (while (>= i level)
8820 (when (setq entry (assoc i tags-alist))
8821 (setq tags-alist (delete entry tags-alist)))
8822 (setq i (1- i)))
8823 ;; add the next tags
8824 (when tags
8825 (setq tags (mapcar 'downcase (org-split-string tags ":"))
8826 tags-alist
8827 (cons (cons level tags) tags-alist)))
8828 ;; compile tags for current headline
8829 (setq tags-list
8830 (if org-use-tag-inheritance
8831 (apply 'append (mapcar 'cdr tags-alist))
8832 tags))
8833 (when (and tags org-use-tag-inheritance
8834 (not (eq t org-use-tag-inheritance)))
8835 ;; selective inheritance, remove uninherited ones
8836 (setcdr (car tags-alist)
8837 (org-remove-uniherited-tags (cdar tags-alist))))
8838 (when (and (or (not todo-only) (member todo org-not-done-keywords))
8839 (let ((case-fold-search t)) (eval matcher))
8841 (not (member org-archive-tag tags-list))
8842 ;; we have an archive tag, should we use this anyway?
8843 (or (not org-agenda-skip-archived-trees)
8844 (and (eq action 'agenda) org-agenda-archives-mode))))
8845 (unless (eq action 'sparse-tree) (org-agenda-skip))
8847 ;; select this headline
8849 (cond
8850 ((eq action 'sparse-tree)
8851 (and org-highlight-sparse-tree-matches
8852 (org-get-heading) (match-end 0)
8853 (org-highlight-new-match
8854 (match-beginning 0) (match-beginning 1)))
8855 (org-show-context 'tags-tree))
8856 ((eq action 'agenda)
8857 (setq txt (org-format-agenda-item
8859 (concat
8860 (if org-tags-match-list-sublevels
8861 (make-string (1- level) ?.) "")
8862 (org-get-heading))
8863 category tags-list)
8864 priority (org-get-priority txt))
8865 (goto-char lspos)
8866 (setq marker (org-agenda-new-marker))
8867 (org-add-props txt props
8868 'org-marker marker 'org-hd-marker marker 'org-category category
8869 'priority priority 'type "tagsmatch")
8870 (push txt rtn))
8871 ((functionp action)
8872 (save-excursion
8873 (setq rtn1 (funcall action))
8874 (push rtn1 rtn))
8875 (goto-char (point-at-eol)))
8876 (t (error "Invalid action")))
8878 ;; if we are to skip sublevels, jump to end of subtree
8879 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
8880 (when (and (eq action 'sparse-tree)
8881 (not org-sparse-tree-open-archived-trees))
8882 (org-hide-archived-subtrees (point-min) (point-max)))
8883 (nreverse rtn)))
8885 (defun org-remove-uniherited-tags (tags)
8886 "Remove all tags that are not inherited from the list TAGS."
8887 (cond
8888 ((eq org-use-tag-inheritance t) tags)
8889 ((not org-use-tag-inheritance) nil)
8890 ((stringp org-use-tag-inheritance)
8891 (delq nil (mapcar
8892 (lambda (x) (if (string-match org-use-tag-inheritance x) x nil))
8893 tags)))
8894 ((listp org-use-tag-inheritance)
8895 (delq nil (mapcar
8896 (lambda (x) (if (member x org-use-tag-inheritance) x nil))
8897 tags)))))
8899 (defvar todo-only) ;; dynamically scoped
8901 (defun org-tags-sparse-tree (&optional todo-only match)
8902 "Create a sparse tree according to tags string MATCH.
8903 MATCH can contain positive and negative selection of tags, like
8904 \"+WORK+URGENT-WITHBOSS\".
8905 If optional argument TODO_ONLY is non-nil, only select lines that are
8906 also TODO lines."
8907 (interactive "P")
8908 (org-prepare-agenda-buffers (list (current-buffer)))
8909 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
8911 (defvar org-cached-props nil)
8912 (defun org-cached-entry-get (pom property)
8913 (if (or (eq t org-use-property-inheritance)
8914 (and (stringp org-use-property-inheritance)
8915 (string-match org-use-property-inheritance property))
8916 (and (listp org-use-property-inheritance)
8917 (member property org-use-property-inheritance)))
8918 ;; Caching is not possible, check it directly
8919 (org-entry-get pom property 'inherit)
8920 ;; Get all properties, so that we can do complicated checks easily
8921 (cdr (assoc property (or org-cached-props
8922 (setq org-cached-props
8923 (org-entry-properties pom)))))))
8925 (defun org-global-tags-completion-table (&optional files)
8926 "Return the list of all tags in all agenda buffer/files."
8927 (save-excursion
8928 (org-uniquify
8929 (delq nil
8930 (apply 'append
8931 (mapcar
8932 (lambda (file)
8933 (set-buffer (find-file-noselect file))
8934 (append (org-get-buffer-tags)
8935 (mapcar (lambda (x) (if (stringp (car-safe x))
8936 (list (car-safe x)) nil))
8937 org-tag-alist)))
8938 (if (and files (car files))
8939 files
8940 (org-agenda-files))))))))
8942 (defun org-make-tags-matcher (match)
8943 "Create the TAGS//TODO matcher form for the selection string MATCH."
8944 ;; todo-only is scoped dynamically into this function, and the function
8945 ;; may change it it the matcher asksk for it.
8946 (unless match
8947 ;; Get a new match request, with completion
8948 (let ((org-last-tags-completion-table
8949 (org-global-tags-completion-table)))
8950 (setq match (completing-read
8951 "Match: " 'org-tags-completion-function nil nil nil
8952 'org-tags-history))))
8954 ;; Parse the string and create a lisp form
8955 (let ((match0 match)
8956 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
8957 minus tag mm
8958 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
8959 orterms term orlist re-p str-p level-p level-op time-p
8960 prop-p pn pv po cat-p gv)
8961 (if (string-match "/+" match)
8962 ;; match contains also a todo-matching request
8963 (progn
8964 (setq tagsmatch (substring match 0 (match-beginning 0))
8965 todomatch (substring match (match-end 0)))
8966 (if (string-match "^!" todomatch)
8967 (setq todo-only t todomatch (substring todomatch 1)))
8968 (if (string-match "^\\s-*$" todomatch)
8969 (setq todomatch nil)))
8970 ;; only matching tags
8971 (setq tagsmatch match todomatch nil))
8973 ;; Make the tags matcher
8974 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
8975 (setq tagsmatcher t)
8976 (setq orterms (org-split-string tagsmatch "|") orlist nil)
8977 (while (setq term (pop orterms))
8978 (while (and (equal (substring term -1) "\\") orterms)
8979 (setq term (concat term "|" (pop orterms)))) ; repair bad split
8980 (while (string-match re term)
8981 (setq minus (and (match-end 1)
8982 (equal (match-string 1 term) "-"))
8983 tag (match-string 2 term)
8984 re-p (equal (string-to-char tag) ?{)
8985 level-p (match-end 4)
8986 prop-p (match-end 5)
8987 mm (cond
8988 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
8989 (level-p
8990 (setq level-op (org-op-to-function (match-string 3 term)))
8991 `(,level-op level ,(string-to-number
8992 (match-string 4 term))))
8993 (prop-p
8994 (setq pn (match-string 5 term)
8995 po (match-string 6 term)
8996 pv (match-string 7 term)
8997 cat-p (equal pn "CATEGORY")
8998 re-p (equal (string-to-char pv) ?{)
8999 str-p (equal (string-to-char pv) ?\")
9000 time-p (save-match-data
9001 (string-match "^\"[[<].*[]>]\"$" pv))
9002 pv (if (or re-p str-p) (substring pv 1 -1) pv))
9003 (if time-p (setq pv (org-matcher-time pv)))
9004 (setq po (org-op-to-function po (if time-p 'time str-p)))
9005 (if (equal pn "CATEGORY")
9006 (setq gv '(get-text-property (point) 'org-category))
9007 (setq gv `(org-cached-entry-get nil ,pn)))
9008 (if re-p
9009 (if (eq po 'org<>)
9010 `(not (string-match ,pv (or ,gv "")))
9011 `(string-match ,pv (or ,gv "")))
9012 (if str-p
9013 `(,po (or ,gv "") ,pv)
9014 `(,po (string-to-number (or ,gv ""))
9015 ,(string-to-number pv) ))))
9016 (t `(member ,(downcase tag) tags-list)))
9017 mm (if minus (list 'not mm) mm)
9018 term (substring term (match-end 0)))
9019 (push mm tagsmatcher))
9020 (push (if (> (length tagsmatcher) 1)
9021 (cons 'and tagsmatcher)
9022 (car tagsmatcher))
9023 orlist)
9024 (setq tagsmatcher nil))
9025 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
9026 (setq tagsmatcher
9027 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
9028 ;; Make the todo matcher
9029 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
9030 (setq todomatcher t)
9031 (setq orterms (org-split-string todomatch "|") orlist nil)
9032 (while (setq term (pop orterms))
9033 (while (string-match re term)
9034 (setq minus (and (match-end 1)
9035 (equal (match-string 1 term) "-"))
9036 kwd (match-string 2 term)
9037 re-p (equal (string-to-char kwd) ?{)
9038 term (substring term (match-end 0))
9039 mm (if re-p
9040 `(string-match ,(substring kwd 1 -1) todo)
9041 (list 'equal 'todo kwd))
9042 mm (if minus (list 'not mm) mm))
9043 (push mm todomatcher))
9044 (push (if (> (length todomatcher) 1)
9045 (cons 'and todomatcher)
9046 (car todomatcher))
9047 orlist)
9048 (setq todomatcher nil))
9049 (setq todomatcher (if (> (length orlist) 1)
9050 (cons 'or orlist) (car orlist))))
9052 ;; Return the string and lisp forms of the matcher
9053 (setq matcher (if todomatcher
9054 (list 'and tagsmatcher todomatcher)
9055 tagsmatcher))
9056 (cons match0 matcher)))
9058 (defun org-op-to-function (op &optional stringp)
9059 "Turn an operator into the appropriate function."
9060 (setq op
9061 (cond
9062 ((equal op "<" ) '(< string< org-time<))
9063 ((equal op ">" ) '(> org-string> org-time>))
9064 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
9065 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
9066 ((member op '("=" "==")) '(= string= org-time=))
9067 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
9068 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
9070 (defun org<> (a b) (not (= a b)))
9071 (defun org-string<= (a b) (or (string= a b) (string< a b)))
9072 (defun org-string>= (a b) (not (string< a b)))
9073 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
9074 (defun org-string<> (a b) (not (string= a b)))
9075 (defun org-time= (a b) (= (org-2ft a) (org-2ft b)))
9076 (defun org-time< (a b) (< (org-2ft a) (org-2ft b)))
9077 (defun org-time<= (a b) (<= (org-2ft a) (org-2ft b)))
9078 (defun org-time> (a b) (> (org-2ft a) (org-2ft b)))
9079 (defun org-time>= (a b) (>= (org-2ft a) (org-2ft b)))
9080 (defun org-time<> (a b) (org<> (org-2ft a) (org-2ft b)))
9081 (defun org-2ft (s)
9082 "Convert S to a floating point time.
9083 If S is already a number, just return it. If it is a string, parse
9084 it as a time string and apply `float-time' to it. f S is nil, just return 0."
9085 (cond
9086 ((numberp s) s)
9087 ((stringp s)
9088 (condition-case nil
9089 (float-time (apply 'encode-time (org-parse-time-string s)))
9090 (error 0.)))
9091 (t 0.)))
9093 (defun org-matcher-time (s)
9094 (cond
9095 ((equal s "<now>") (float-time))
9096 ((equal s "<today>")
9097 (float-time (append '(0 0 0) (nthcdr 3 (decode-time)))))
9098 (t (org-2ft s))))
9100 (defun org-match-any-p (re list)
9101 "Does re match any element of list?"
9102 (setq list (mapcar (lambda (x) (string-match re x)) list))
9103 (delq nil list))
9105 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
9106 (defvar org-tags-overlay (org-make-overlay 1 1))
9107 (org-detach-overlay org-tags-overlay)
9109 (defun org-get-local-tags-at (&optional pos)
9110 "Get a list of tags defined in the current headline."
9111 (org-get-tags-at pos 'local))
9113 (defun org-get-local-tags ()
9114 "Get a list of tags defined in the current headline."
9115 (org-get-tags-at nil 'local))
9117 (defun org-get-tags-at (&optional pos local)
9118 "Get a list of all headline tags applicable at POS.
9119 POS defaults to point. If tags are inherited, the list contains
9120 the targets in the same sequence as the headlines appear, i.e.
9121 the tags of the current headline come last.
9122 When LOCAL is non-nil, only return tags from the current headline,
9123 ignore inherited ones."
9124 (interactive)
9125 (let (tags ltags lastpos parent)
9126 (save-excursion
9127 (save-restriction
9128 (widen)
9129 (goto-char (or pos (point)))
9130 (save-match-data
9131 (catch 'done
9132 (condition-case nil
9133 (progn
9134 (org-back-to-heading t)
9135 (while (not (equal lastpos (point)))
9136 (setq lastpos (point))
9137 (when (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
9138 (setq ltags (org-split-string
9139 (org-match-string-no-properties 1) ":"))
9140 (setq tags (append
9141 (if parent
9142 (org-remove-uniherited-tags ltags)
9143 ltags)
9144 tags)))
9145 (or org-use-tag-inheritance (throw 'done t))
9146 (if local (throw 'done t))
9147 (org-up-heading-all 1)
9148 (setq parent t)))
9149 (error nil)))))
9150 (append (org-remove-uniherited-tags org-file-tags) tags))))
9152 (defun org-toggle-tag (tag &optional onoff)
9153 "Toggle the tag TAG for the current line.
9154 If ONOFF is `on' or `off', don't toggle but set to this state."
9155 (unless (org-on-heading-p t) (error "Not on headling"))
9156 (let (res current)
9157 (save-excursion
9158 (beginning-of-line)
9159 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
9160 (point-at-eol) t)
9161 (progn
9162 (setq current (match-string 1))
9163 (replace-match ""))
9164 (setq current ""))
9165 (setq current (nreverse (org-split-string current ":")))
9166 (cond
9167 ((eq onoff 'on)
9168 (setq res t)
9169 (or (member tag current) (push tag current)))
9170 ((eq onoff 'off)
9171 (or (not (member tag current)) (setq current (delete tag current))))
9172 (t (if (member tag current)
9173 (setq current (delete tag current))
9174 (setq res t)
9175 (push tag current))))
9176 (end-of-line 1)
9177 (if current
9178 (progn
9179 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
9180 (org-set-tags nil t))
9181 (delete-horizontal-space))
9182 (run-hooks 'org-after-tags-change-hook))
9183 res))
9185 (defun org-align-tags-here (to-col)
9186 ;; Assumes that this is a headline
9187 (let ((pos (point)) (col (current-column)) ncol tags-l p)
9188 (beginning-of-line 1)
9189 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9190 (< pos (match-beginning 2)))
9191 (progn
9192 (setq tags-l (- (match-end 2) (match-beginning 2)))
9193 (goto-char (match-beginning 1))
9194 (insert " ")
9195 (delete-region (point) (1+ (match-beginning 2)))
9196 (setq ncol (max (1+ (current-column))
9197 (1+ col)
9198 (if (> to-col 0)
9199 to-col
9200 (- (abs to-col) tags-l))))
9201 (setq p (point))
9202 (insert (make-string (- ncol (current-column)) ?\ ))
9203 (setq ncol (current-column))
9204 (when indent-tabs-mode (tabify p (point-at-eol)))
9205 (org-move-to-column (min ncol col) t))
9206 (goto-char pos))))
9208 (defun org-set-tags-command (&optional arg just-align)
9209 "Call the set-tags command for the current entry."
9210 (interactive "P")
9211 (if (org-on-heading-p)
9212 (org-set-tags arg just-align)
9213 (save-excursion
9214 (org-back-to-heading t)
9215 (org-set-tags arg just-align))))
9217 (defun org-set-tags (&optional arg just-align)
9218 "Set the tags for the current headline.
9219 With prefix ARG, realign all tags in headings in the current buffer."
9220 (interactive "P")
9221 (let* ((re (concat "^" outline-regexp))
9222 (current (org-get-tags-string))
9223 (col (current-column))
9224 (org-setting-tags t)
9225 table current-tags inherited-tags ; computed below when needed
9226 tags p0 c0 c1 rpl)
9227 (if arg
9228 (save-excursion
9229 (goto-char (point-min))
9230 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
9231 (while (re-search-forward re nil t)
9232 (org-set-tags nil t)
9233 (end-of-line 1)))
9234 (message "All tags realigned to column %d" org-tags-column))
9235 (if just-align
9236 (setq tags current)
9237 ;; Get a new set of tags from the user
9238 (save-excursion
9239 (setq table (or org-tag-alist (org-get-buffer-tags))
9240 org-last-tags-completion-table table
9241 current-tags (org-split-string current ":")
9242 inherited-tags (nreverse
9243 (nthcdr (length current-tags)
9244 (nreverse (org-get-tags-at))))
9245 tags
9246 (if (or (eq t org-use-fast-tag-selection)
9247 (and org-use-fast-tag-selection
9248 (delq nil (mapcar 'cdr table))))
9249 (org-fast-tag-selection
9250 current-tags inherited-tags table
9251 (if org-fast-tag-selection-include-todo org-todo-key-alist))
9252 (let ((org-add-colon-after-tag-completion t))
9253 (org-trim
9254 (org-without-partial-completion
9255 (completing-read "Tags: " 'org-tags-completion-function
9256 nil nil current 'org-tags-history)))))))
9257 (while (string-match "[-+&]+" tags)
9258 ;; No boolean logic, just a list
9259 (setq tags (replace-match ":" t t tags))))
9261 (if (string-match "\\`[\t ]*\\'" tags)
9262 (setq tags "")
9263 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
9264 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
9266 ;; Insert new tags at the correct column
9267 (beginning-of-line 1)
9268 (cond
9269 ((and (equal current "") (equal tags "")))
9270 ((re-search-forward
9271 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
9272 (point-at-eol) t)
9273 (if (equal tags "")
9274 (setq rpl "")
9275 (goto-char (match-beginning 0))
9276 (setq c0 (current-column) p0 (point)
9277 c1 (max (1+ c0) (if (> org-tags-column 0)
9278 org-tags-column
9279 (- (- org-tags-column) (length tags))))
9280 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
9281 (replace-match rpl t t)
9282 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
9283 tags)
9284 (t (error "Tags alignment failed")))
9285 (org-move-to-column col)
9286 (unless just-align
9287 (run-hooks 'org-after-tags-change-hook)))))
9289 (defun org-change-tag-in-region (beg end tag off)
9290 "Add or remove TAG for each entry in the region.
9291 This works in the agenda, and also in an org-mode buffer."
9292 (interactive
9293 (list (region-beginning) (region-end)
9294 (let ((org-last-tags-completion-table
9295 (if (org-mode-p)
9296 (org-get-buffer-tags)
9297 (org-global-tags-completion-table))))
9298 (completing-read
9299 "Tag: " 'org-tags-completion-function nil nil nil
9300 'org-tags-history))
9301 (progn
9302 (message "[s]et or [r]emove? ")
9303 (equal (read-char-exclusive) ?r))))
9304 (if (fboundp 'deactivate-mark) (deactivate-mark))
9305 (let ((agendap (equal major-mode 'org-agenda-mode))
9306 l1 l2 m buf pos newhead (cnt 0))
9307 (goto-char end)
9308 (setq l2 (1- (org-current-line)))
9309 (goto-char beg)
9310 (setq l1 (org-current-line))
9311 (loop for l from l1 to l2 do
9312 (goto-line l)
9313 (setq m (get-text-property (point) 'org-hd-marker))
9314 (when (or (and (org-mode-p) (org-on-heading-p))
9315 (and agendap m))
9316 (setq buf (if agendap (marker-buffer m) (current-buffer))
9317 pos (if agendap m (point)))
9318 (with-current-buffer buf
9319 (save-excursion
9320 (save-restriction
9321 (goto-char pos)
9322 (setq cnt (1+ cnt))
9323 (org-toggle-tag tag (if off 'off 'on))
9324 (setq newhead (org-get-heading)))))
9325 (and agendap (org-agenda-change-all-lines newhead m))))
9326 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
9328 (defun org-tags-completion-function (string predicate &optional flag)
9329 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
9330 (confirm (lambda (x) (stringp (car x)))))
9331 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
9332 (setq s1 (match-string 1 string)
9333 s2 (match-string 2 string))
9334 (setq s1 "" s2 string))
9335 (cond
9336 ((eq flag nil)
9337 ;; try completion
9338 (setq rtn (try-completion s2 ctable confirm))
9339 (if (stringp rtn)
9340 (setq rtn
9341 (concat s1 s2 (substring rtn (length s2))
9342 (if (and org-add-colon-after-tag-completion
9343 (assoc rtn ctable))
9344 ":" ""))))
9345 rtn)
9346 ((eq flag t)
9347 ;; all-completions
9348 (all-completions s2 ctable confirm)
9350 ((eq flag 'lambda)
9351 ;; exact match?
9352 (assoc s2 ctable)))
9355 (defun org-fast-tag-insert (kwd tags face &optional end)
9356 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
9357 (insert (format "%-12s" (concat kwd ":"))
9358 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
9359 (or end "")))
9361 (defun org-fast-tag-show-exit (flag)
9362 (save-excursion
9363 (goto-line 3)
9364 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
9365 (replace-match ""))
9366 (when flag
9367 (end-of-line 1)
9368 (org-move-to-column (- (window-width) 19) t)
9369 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
9371 (defun org-set-current-tags-overlay (current prefix)
9372 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
9373 (if (featurep 'xemacs)
9374 (org-overlay-display org-tags-overlay (concat prefix s)
9375 'secondary-selection)
9376 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
9377 (org-overlay-display org-tags-overlay (concat prefix s)))))
9379 (defun org-fast-tag-selection (current inherited table &optional todo-table)
9380 "Fast tag selection with single keys.
9381 CURRENT is the current list of tags in the headline, INHERITED is the
9382 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
9383 possibly with grouping information. TODO-TABLE is a similar table with
9384 TODO keywords, should these have keys assigned to them.
9385 If the keys are nil, a-z are automatically assigned.
9386 Returns the new tags string, or nil to not change the current settings."
9387 (let* ((fulltable (append table todo-table))
9388 (maxlen (apply 'max (mapcar
9389 (lambda (x)
9390 (if (stringp (car x)) (string-width (car x)) 0))
9391 fulltable)))
9392 (buf (current-buffer))
9393 (expert (eq org-fast-tag-selection-single-key 'expert))
9394 (buffer-tags nil)
9395 (fwidth (+ maxlen 3 1 3))
9396 (ncol (/ (- (window-width) 4) fwidth))
9397 (i-face 'org-done)
9398 (c-face 'org-todo)
9399 tg cnt e c char c1 c2 ntable tbl rtn
9400 ov-start ov-end ov-prefix
9401 (exit-after-next org-fast-tag-selection-single-key)
9402 (done-keywords org-done-keywords)
9403 groups ingroup)
9404 (save-excursion
9405 (beginning-of-line 1)
9406 (if (looking-at
9407 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9408 (setq ov-start (match-beginning 1)
9409 ov-end (match-end 1)
9410 ov-prefix "")
9411 (setq ov-start (1- (point-at-eol))
9412 ov-end (1+ ov-start))
9413 (skip-chars-forward "^\n\r")
9414 (setq ov-prefix
9415 (concat
9416 (buffer-substring (1- (point)) (point))
9417 (if (> (current-column) org-tags-column)
9419 (make-string (- org-tags-column (current-column)) ?\ ))))))
9420 (org-move-overlay org-tags-overlay ov-start ov-end)
9421 (save-window-excursion
9422 (if expert
9423 (set-buffer (get-buffer-create " *Org tags*"))
9424 (delete-other-windows)
9425 (split-window-vertically)
9426 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
9427 (erase-buffer)
9428 (org-set-local 'org-done-keywords done-keywords)
9429 (org-fast-tag-insert "Inherited" inherited i-face "\n")
9430 (org-fast-tag-insert "Current" current c-face "\n\n")
9431 (org-fast-tag-show-exit exit-after-next)
9432 (org-set-current-tags-overlay current ov-prefix)
9433 (setq tbl fulltable char ?a cnt 0)
9434 (while (setq e (pop tbl))
9435 (cond
9436 ((equal e '(:startgroup))
9437 (push '() groups) (setq ingroup t)
9438 (when (not (= cnt 0))
9439 (setq cnt 0)
9440 (insert "\n"))
9441 (insert "{ "))
9442 ((equal e '(:endgroup))
9443 (setq ingroup nil cnt 0)
9444 (insert "}\n"))
9446 (setq tg (car e) c2 nil)
9447 (if (cdr e)
9448 (setq c (cdr e))
9449 ;; automatically assign a character.
9450 (setq c1 (string-to-char
9451 (downcase (substring
9452 tg (if (= (string-to-char tg) ?@) 1 0)))))
9453 (if (or (rassoc c1 ntable) (rassoc c1 table))
9454 (while (or (rassoc char ntable) (rassoc char table))
9455 (setq char (1+ char)))
9456 (setq c2 c1))
9457 (setq c (or c2 char)))
9458 (if ingroup (push tg (car groups)))
9459 (setq tg (org-add-props tg nil 'face
9460 (cond
9461 ((not (assoc tg table))
9462 (org-get-todo-face tg))
9463 ((member tg current) c-face)
9464 ((member tg inherited) i-face)
9465 (t nil))))
9466 (if (and (= cnt 0) (not ingroup)) (insert " "))
9467 (insert "[" c "] " tg (make-string
9468 (- fwidth 4 (length tg)) ?\ ))
9469 (push (cons tg c) ntable)
9470 (when (= (setq cnt (1+ cnt)) ncol)
9471 (insert "\n")
9472 (if ingroup (insert " "))
9473 (setq cnt 0)))))
9474 (setq ntable (nreverse ntable))
9475 (insert "\n")
9476 (goto-char (point-min))
9477 (if (and (not expert) (fboundp 'fit-window-to-buffer))
9478 (fit-window-to-buffer))
9479 (setq rtn
9480 (catch 'exit
9481 (while t
9482 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
9483 (if groups " [!] no groups" " [!]groups")
9484 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
9485 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9486 (cond
9487 ((= c ?\r) (throw 'exit t))
9488 ((= c ?!)
9489 (setq groups (not groups))
9490 (goto-char (point-min))
9491 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
9492 ((= c ?\C-c)
9493 (if (not expert)
9494 (org-fast-tag-show-exit
9495 (setq exit-after-next (not exit-after-next)))
9496 (setq expert nil)
9497 (delete-other-windows)
9498 (split-window-vertically)
9499 (org-switch-to-buffer-other-window " *Org tags*")
9500 (and (fboundp 'fit-window-to-buffer)
9501 (fit-window-to-buffer))))
9502 ((or (= c ?\C-g)
9503 (and (= c ?q) (not (rassoc c ntable))))
9504 (org-detach-overlay org-tags-overlay)
9505 (setq quit-flag t))
9506 ((= c ?\ )
9507 (setq current nil)
9508 (if exit-after-next (setq exit-after-next 'now)))
9509 ((= c ?\t)
9510 (condition-case nil
9511 (setq tg (completing-read
9512 "Tag: "
9513 (or buffer-tags
9514 (with-current-buffer buf
9515 (org-get-buffer-tags)))))
9516 (quit (setq tg "")))
9517 (when (string-match "\\S-" tg)
9518 (add-to-list 'buffer-tags (list tg))
9519 (if (member tg current)
9520 (setq current (delete tg current))
9521 (push tg current)))
9522 (if exit-after-next (setq exit-after-next 'now)))
9523 ((setq e (rassoc c todo-table) tg (car e))
9524 (with-current-buffer buf
9525 (save-excursion (org-todo tg)))
9526 (if exit-after-next (setq exit-after-next 'now)))
9527 ((setq e (rassoc c ntable) tg (car e))
9528 (if (member tg current)
9529 (setq current (delete tg current))
9530 (loop for g in groups do
9531 (if (member tg g)
9532 (mapc (lambda (x)
9533 (setq current (delete x current)))
9534 g)))
9535 (push tg current))
9536 (if exit-after-next (setq exit-after-next 'now))))
9538 ;; Create a sorted list
9539 (setq current
9540 (sort current
9541 (lambda (a b)
9542 (assoc b (cdr (memq (assoc a ntable) ntable))))))
9543 (if (eq exit-after-next 'now) (throw 'exit t))
9544 (goto-char (point-min))
9545 (beginning-of-line 2)
9546 (delete-region (point) (point-at-eol))
9547 (org-fast-tag-insert "Current" current c-face)
9548 (org-set-current-tags-overlay current ov-prefix)
9549 (while (re-search-forward
9550 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
9551 (setq tg (match-string 1))
9552 (add-text-properties
9553 (match-beginning 1) (match-end 1)
9554 (list 'face
9555 (cond
9556 ((member tg current) c-face)
9557 ((member tg inherited) i-face)
9558 (t (get-text-property (match-beginning 1) 'face))))))
9559 (goto-char (point-min)))))
9560 (org-detach-overlay org-tags-overlay)
9561 (if rtn
9562 (mapconcat 'identity current ":")
9563 nil))))
9565 (defun org-get-tags-string ()
9566 "Get the TAGS string in the current headline."
9567 (unless (org-on-heading-p t)
9568 (error "Not on a heading"))
9569 (save-excursion
9570 (beginning-of-line 1)
9571 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9572 (org-match-string-no-properties 1)
9573 "")))
9575 (defun org-get-tags ()
9576 "Get the list of tags specified in the current headline."
9577 (org-split-string (org-get-tags-string) ":"))
9579 (defun org-get-buffer-tags ()
9580 "Get a table of all tags used in the buffer, for completion."
9581 (let (tags)
9582 (save-excursion
9583 (goto-char (point-min))
9584 (while (re-search-forward
9585 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
9586 (when (equal (char-after (point-at-bol 0)) ?*)
9587 (mapc (lambda (x) (add-to-list 'tags x))
9588 (org-split-string (org-match-string-no-properties 1) ":")))))
9589 (mapcar 'list tags)))
9591 ;;;; The mapping API
9593 ;;;###autoload
9594 (defun org-map-entries (func &optional match scope &rest skip)
9595 "Call FUNC at each headline selected by MATCH in SCOPE.
9597 FUNC is a function or a lisp form. The function will be called without
9598 arguments, with the cursor positioned at the beginning of the headline.
9599 The return values of all calls to the function will be collected and
9600 returned as a list.
9602 MATCH is a tags/property/todo match as it is used in the agenda tags view.
9603 Only headlines that are matched by this query will be considered during
9604 the iteration. When MATCH is nil or t, all headlines will be
9605 visited by the iteration.
9607 SCOPE determines the scope of this command. It can be any of:
9609 nil The current buffer, respecting the restriction if any
9610 tree The subtree started with the entry at point
9611 file The current buffer, without restriction
9612 file-with-archives
9613 The current buffer, and any archives associated with it
9614 agenda All agenda files
9615 agenda-with-archives
9616 All agenda files with any archive files associated with them
9617 \(file1 file2 ...)
9618 If this is a list, all files in the list will be scanned
9620 The remaining args are treated as settings for the skipping facilities of
9621 the scanner. The following items can be given here:
9623 archive skip trees with the archive tag.
9624 comment skip trees with the COMMENT keyword
9625 function or Emacs Lisp form:
9626 will be used as value for `org-agenda-skip-function', so whenever
9627 the the function returns t, FUNC will not be called for that
9628 entry and search will continue from the point where the
9629 function leaves it."
9630 (let* ((org-agenda-archives-mode nil) ; just to make sure
9631 (org-agenda-skip-archived-trees (memq 'archive skip))
9632 (org-agenda-skip-comment-trees (memq 'comment skip))
9633 (org-agenda-skip-function
9634 (car (org-delete-all '(comment archive) skip)))
9635 (org-tags-match-list-sublevels t)
9636 matcher pos file
9637 org-todo-keywords-for-agenda
9638 org-done-keywords-for-agenda
9639 org-todo-keyword-alist-for-agenda
9640 org-tag-alist-for-agenda)
9642 (cond
9643 ((eq match t) (setq matcher t))
9644 ((eq match nil) (setq matcher t))
9645 (t (setq matcher (if match (org-make-tags-matcher match) t))))
9647 (when (eq scope 'tree)
9648 (org-back-to-heading t)
9649 (org-narrow-to-subtree)
9650 (setq scope nil))
9652 (if (not scope)
9653 (progn
9654 (org-prepare-agenda-buffers
9655 (list (buffer-file-name (current-buffer))))
9656 (org-scan-tags func matcher))
9657 ;; Get the right scope
9658 (setq pos (point))
9659 (cond
9660 ((and scope (listp scope) (symbolp (car scope)))
9661 (setq scope (eval scope)))
9662 ((eq scope 'agenda)
9663 (setq scope (org-agenda-files t)))
9664 ((eq scope 'agenda-with-archives)
9665 (setq scope (org-agenda-files t))
9666 (setq scope (org-add-archive-files scope)))
9667 ((eq scope 'file)
9668 (setq scope (list (buffer-file-name))))
9669 ((eq scope 'file-with-archives)
9670 (setq scope (org-add-archive-files (list (buffer-file-name))))))
9671 (org-prepare-agenda-buffers scope)
9672 (while (setq file (pop scope))
9673 (with-current-buffer (org-find-base-buffer-visiting file)
9674 (save-excursion
9675 (save-restriction
9676 (widen)
9677 (goto-char (point-min))
9678 (org-scan-tags func matcher))))))))
9680 ;;;; Properties
9682 ;;; Setting and retrieving properties
9684 (defconst org-special-properties
9685 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "PRIORITY"
9686 "TIMESTAMP" "TIMESTAMP_IA")
9687 "The special properties valid in Org-mode.
9689 These are properties that are not defined in the property drawer,
9690 but in some other way.")
9692 (defconst org-default-properties
9693 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
9694 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
9695 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
9696 "EXPORT_FILE_NAME" "EXPORT_TITLE")
9697 "Some properties that are used by Org-mode for various purposes.
9698 Being in this list makes sure that they are offered for completion.")
9700 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
9701 "Regular expression matching the first line of a property drawer.")
9703 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
9704 "Regular expression matching the first line of a property drawer.")
9706 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
9707 "Regular expression matching the first line of a property drawer.")
9709 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
9710 "Regular expression matching the first line of a property drawer.")
9712 (defconst org-property-drawer-re
9713 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
9714 org-property-end-re "\\)\n?")
9715 "Matches an entire property drawer.")
9717 (defconst org-clock-drawer-re
9718 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
9719 org-property-end-re "\\)\n?")
9720 "Matches an entire clock drawer.")
9722 (defun org-property-action ()
9723 "Do an action on properties."
9724 (interactive)
9725 (let (c)
9726 (org-at-property-p)
9727 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
9728 (setq c (read-char-exclusive))
9729 (cond
9730 ((equal c ?s)
9731 (call-interactively 'org-set-property))
9732 ((equal c ?d)
9733 (call-interactively 'org-delete-property))
9734 ((equal c ?D)
9735 (call-interactively 'org-delete-property-globally))
9736 ((equal c ?c)
9737 (call-interactively 'org-compute-property-at-point))
9738 (t (error "No such property action %c" c)))))
9740 (defun org-at-property-p ()
9741 "Is the cursor in a property line?"
9742 ;; FIXME: Does not check if we are actually in the drawer.
9743 ;; FIXME: also returns true on any drawers.....
9744 ;; This is used by C-c C-c for property action.
9745 (save-excursion
9746 (beginning-of-line 1)
9747 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
9749 (defun org-get-property-block (&optional beg end force)
9750 "Return the (beg . end) range of the body of the property drawer.
9751 BEG and END can be beginning and end of subtree, if not given
9752 they will be found.
9753 If the drawer does not exist and FORCE is non-nil, create the drawer."
9754 (catch 'exit
9755 (save-excursion
9756 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
9757 (end (or end (progn (outline-next-heading) (point)))))
9758 (goto-char beg)
9759 (if (re-search-forward org-property-start-re end t)
9760 (setq beg (1+ (match-end 0)))
9761 (if force
9762 (save-excursion
9763 (org-insert-property-drawer)
9764 (setq end (progn (outline-next-heading) (point))))
9765 (throw 'exit nil))
9766 (goto-char beg)
9767 (if (re-search-forward org-property-start-re end t)
9768 (setq beg (1+ (match-end 0)))))
9769 (if (re-search-forward org-property-end-re end t)
9770 (setq end (match-beginning 0))
9771 (or force (throw 'exit nil))
9772 (goto-char beg)
9773 (setq end beg)
9774 (org-indent-line-function)
9775 (insert ":END:\n"))
9776 (cons beg end)))))
9778 (defun org-entry-properties (&optional pom which)
9779 "Get all properties of the entry at point-or-marker POM.
9780 This includes the TODO keyword, the tags, time strings for deadline,
9781 scheduled, and clocking, and any additional properties defined in the
9782 entry. The return value is an alist, keys may occur multiple times
9783 if the property key was used several times.
9784 POM may also be nil, in which case the current entry is used.
9785 If WHICH is nil or `all', get all properties. If WHICH is
9786 `special' or `standard', only get that subclass."
9787 (setq which (or which 'all))
9788 (org-with-point-at pom
9789 (let ((clockstr (substring org-clock-string 0 -1))
9790 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
9791 beg end range props sum-props key value string clocksum)
9792 (save-excursion
9793 (when (condition-case nil (org-back-to-heading t) (error nil))
9794 (setq beg (point))
9795 (setq sum-props (get-text-property (point) 'org-summaries))
9796 (setq clocksum (get-text-property (point) :org-clock-minutes))
9797 (outline-next-heading)
9798 (setq end (point))
9799 (when (memq which '(all special))
9800 ;; Get the special properties, like TODO and tags
9801 (goto-char beg)
9802 (when (and (looking-at org-todo-line-regexp) (match-end 2))
9803 (push (cons "TODO" (org-match-string-no-properties 2)) props))
9804 (when (looking-at org-priority-regexp)
9805 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
9806 (when (and (setq value (org-get-tags-string))
9807 (string-match "\\S-" value))
9808 (push (cons "TAGS" value) props))
9809 (when (setq value (org-get-tags-at))
9810 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
9811 props))
9812 (while (re-search-forward org-maybe-keyword-time-regexp end t)
9813 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
9814 string (if (equal key clockstr)
9815 (org-no-properties
9816 (org-trim
9817 (buffer-substring
9818 (match-beginning 3) (goto-char (point-at-eol)))))
9819 (substring (org-match-string-no-properties 3) 1 -1)))
9820 (unless key
9821 (if (= (char-after (match-beginning 3)) ?\[)
9822 (setq key "TIMESTAMP_IA")
9823 (setq key "TIMESTAMP")))
9824 (when (or (equal key clockstr) (not (assoc key props)))
9825 (push (cons key string) props)))
9829 (when (memq which '(all standard))
9830 ;; Get the standard properties, like :PORP: ...
9831 (setq range (org-get-property-block beg end))
9832 (when range
9833 (goto-char (car range))
9834 (while (re-search-forward
9835 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
9836 (cdr range) t)
9837 (setq key (org-match-string-no-properties 1)
9838 value (org-trim (or (org-match-string-no-properties 2) "")))
9839 (unless (member key excluded)
9840 (push (cons key (or value "")) props)))))
9841 (if clocksum
9842 (push (cons "CLOCKSUM"
9843 (org-columns-number-to-string (/ (float clocksum) 60.)
9844 'add_times))
9845 props))
9846 (unless (assoc "CATEGORY" props)
9847 (setq value (or (org-get-category)
9848 (progn (org-refresh-category-properties)
9849 (org-get-category))))
9850 (push (cons "CATEGORY" value) props))
9851 (append sum-props (nreverse props)))))))
9853 (defun org-entry-get (pom property &optional inherit)
9854 "Get value of PROPERTY for entry at point-or-marker POM.
9855 If INHERIT is non-nil and the entry does not have the property,
9856 then also check higher levels of the hierarchy.
9857 If INHERIT is the symbol `selective', use inheritance only if the setting
9858 in `org-use-property-inheritance' selects PROPERTY for inheritance.
9859 If the property is present but empty, the return value is the empty string.
9860 If the property is not present at all, nil is returned."
9861 (org-with-point-at pom
9862 (if (and inherit (if (eq inherit 'selective)
9863 (org-property-inherit-p property)
9865 (org-entry-get-with-inheritance property)
9866 (if (member property org-special-properties)
9867 ;; We need a special property. Use brute force, get all properties.
9868 (cdr (assoc property (org-entry-properties nil 'special)))
9869 (let ((range (org-get-property-block)))
9870 (if (and range
9871 (goto-char (car range))
9872 (re-search-forward
9873 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
9874 (cdr range) t))
9875 ;; Found the property, return it.
9876 (if (match-end 1)
9877 (org-match-string-no-properties 1)
9878 "")))))))
9880 (defun org-property-or-variable-value (var &optional inherit)
9881 "Check if there is a property fixing the value of VAR.
9882 If yes, return this value. If not, return the current value of the variable."
9883 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
9884 (if (and prop (stringp prop) (string-match "\\S-" prop))
9885 (read prop)
9886 (symbol-value var))))
9888 (defun org-entry-delete (pom property)
9889 "Delete the property PROPERTY from entry at point-or-marker POM."
9890 (org-with-point-at pom
9891 (if (member property org-special-properties)
9892 nil ; cannot delete these properties.
9893 (let ((range (org-get-property-block)))
9894 (if (and range
9895 (goto-char (car range))
9896 (re-search-forward
9897 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
9898 (cdr range) t))
9899 (progn
9900 (delete-region (match-beginning 0) (1+ (point-at-eol)))
9902 nil)))))
9904 ;; Multi-values properties are properties that contain multiple values
9905 ;; These values are assumed to be single words, separated by whitespace.
9906 (defun org-entry-add-to-multivalued-property (pom property value)
9907 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
9908 (let* ((old (org-entry-get pom property))
9909 (values (and old (org-split-string old "[ \t]"))))
9910 (setq value (org-entry-protect-space value))
9911 (unless (member value values)
9912 (setq values (cons value values))
9913 (org-entry-put pom property
9914 (mapconcat 'identity values " ")))))
9916 (defun org-entry-remove-from-multivalued-property (pom property value)
9917 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
9918 (let* ((old (org-entry-get pom property))
9919 (values (and old (org-split-string old "[ \t]"))))
9920 (setq value (org-entry-protect-space value))
9921 (when (member value values)
9922 (setq values (delete value values))
9923 (org-entry-put pom property
9924 (mapconcat 'identity values " ")))))
9926 (defun org-entry-member-in-multivalued-property (pom property value)
9927 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
9928 (let* ((old (org-entry-get pom property))
9929 (values (and old (org-split-string old "[ \t]"))))
9930 (setq value (org-entry-protect-space value))
9931 (member value values)))
9933 (defun org-entry-get-multivalued-property (pom property)
9934 "Return a list of values in a multivalued property."
9935 (let* ((value (org-entry-get pom property))
9936 (values (and value (org-split-string value "[ \t]"))))
9937 (mapcar 'org-entry-restore-space values)))
9939 (defun org-entry-put-multivalued-property (pom property &rest values)
9940 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
9941 VALUES should be a list of strings. Spaces will be protected."
9942 (org-entry-put pom property
9943 (mapconcat 'org-entry-protect-space values " "))
9944 (let* ((value (org-entry-get pom property))
9945 (values (and value (org-split-string value "[ \t]"))))
9946 (mapcar 'org-entry-restore-space values)))
9948 (defun org-entry-protect-space (s)
9949 "Protect spaces and newline in string S."
9950 (while (string-match " " s)
9951 (setq s (replace-match "%20" t t s)))
9952 (while (string-match "\n" s)
9953 (setq s (replace-match "%0A" t t s)))
9956 (defun org-entry-restore-space (s)
9957 "Restore spaces and newline in string S."
9958 (while (string-match "%20" s)
9959 (setq s (replace-match " " t t s)))
9960 (while (string-match "%0A" s)
9961 (setq s (replace-match "\n" t t s)))
9964 (defvar org-entry-property-inherited-from (make-marker)
9965 "Marker pointing to the entry from where a proerty was inherited.
9966 Each call to `org-entry-get-with-inheritance' will set this marker to the
9967 location of the entry where the inheriance search matched. If there was
9968 no match, the marker will point nowhere.
9969 Note that also `org-entry-get' calls this function, if the INHERIT flag
9970 is set.")
9972 (defun org-entry-get-with-inheritance (property)
9973 "Get entry property, and search higher levels if not present."
9974 (move-marker org-entry-property-inherited-from nil)
9975 (let (tmp)
9976 (save-excursion
9977 (save-restriction
9978 (widen)
9979 (catch 'ex
9980 (while t
9981 (when (setq tmp (org-entry-get nil property))
9982 (org-back-to-heading t)
9983 (move-marker org-entry-property-inherited-from (point))
9984 (throw 'ex tmp))
9985 (or (org-up-heading-safe) (throw 'ex nil)))))
9986 (or tmp
9987 (cdr (assoc property org-file-properties))
9988 (cdr (assoc property org-global-properties))
9989 (cdr (assoc property org-global-properties-fixed))))))
9991 (defun org-entry-put (pom property value)
9992 "Set PROPERTY to VALUE for entry at point-or-marker POM."
9993 (org-with-point-at pom
9994 (org-back-to-heading t)
9995 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
9996 range)
9997 (cond
9998 ((equal property "TODO")
9999 (when (and (stringp value) (string-match "\\S-" value)
10000 (not (member value org-todo-keywords-1)))
10001 (error "\"%s\" is not a valid TODO state" value))
10002 (if (or (not value)
10003 (not (string-match "\\S-" value)))
10004 (setq value 'none))
10005 (org-todo value)
10006 (org-set-tags nil 'align))
10007 ((equal property "PRIORITY")
10008 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
10009 (string-to-char value) ?\ ))
10010 (org-set-tags nil 'align))
10011 ((equal property "SCHEDULED")
10012 (if (re-search-forward org-scheduled-time-regexp end t)
10013 (cond
10014 ((eq value 'earlier) (org-timestamp-change -1 'day))
10015 ((eq value 'later) (org-timestamp-change 1 'day))
10016 (t (call-interactively 'org-schedule)))
10017 (call-interactively 'org-schedule)))
10018 ((equal property "DEADLINE")
10019 (if (re-search-forward org-deadline-time-regexp end t)
10020 (cond
10021 ((eq value 'earlier) (org-timestamp-change -1 'day))
10022 ((eq value 'later) (org-timestamp-change 1 'day))
10023 (t (call-interactively 'org-deadline)))
10024 (call-interactively 'org-deadline)))
10025 ((member property org-special-properties)
10026 (error "The %s property can not yet be set with `org-entry-put'"
10027 property))
10028 (t ; a non-special property
10029 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
10030 (setq range (org-get-property-block beg end 'force))
10031 (goto-char (car range))
10032 (if (re-search-forward
10033 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
10034 (progn
10035 (delete-region (match-beginning 1) (match-end 1))
10036 (goto-char (match-beginning 1)))
10037 (goto-char (cdr range))
10038 (insert "\n")
10039 (backward-char 1)
10040 (org-indent-line-function)
10041 (insert ":" property ":"))
10042 (and value (insert " " value))
10043 (org-indent-line-function)))))))
10045 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
10046 "Get all property keys in the current buffer.
10047 With INCLUDE-SPECIALS, also list the special properties that relect things
10048 like tags and TODO state.
10049 With INCLUDE-DEFAULTS, also include properties that has special meaning
10050 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
10051 With INCLUDE-COLUMNS, also include property names given in COLUMN
10052 formats in the current buffer."
10053 (let (rtn range cfmt cols s p)
10054 (save-excursion
10055 (save-restriction
10056 (widen)
10057 (goto-char (point-min))
10058 (while (re-search-forward org-property-start-re nil t)
10059 (setq range (org-get-property-block))
10060 (goto-char (car range))
10061 (while (re-search-forward
10062 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
10063 (cdr range) t)
10064 (add-to-list 'rtn (org-match-string-no-properties 1)))
10065 (outline-next-heading))))
10067 (when include-specials
10068 (setq rtn (append org-special-properties rtn)))
10070 (when include-defaults
10071 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
10073 (when include-columns
10074 (save-excursion
10075 (save-restriction
10076 (widen)
10077 (goto-char (point-min))
10078 (while (re-search-forward
10079 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
10080 nil t)
10081 (setq cfmt (match-string 2) s 0)
10082 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
10083 cfmt s)
10084 (setq s (match-end 0)
10085 p (match-string 1 cfmt))
10086 (unless (or (equal p "ITEM")
10087 (member p org-special-properties))
10088 (add-to-list 'rtn (match-string 1 cfmt))))))))
10090 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
10092 (defun org-property-values (key)
10093 "Return a list of all values of property KEY."
10094 (save-excursion
10095 (save-restriction
10096 (widen)
10097 (goto-char (point-min))
10098 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
10099 values)
10100 (while (re-search-forward re nil t)
10101 (add-to-list 'values (org-trim (match-string 1))))
10102 (delete "" values)))))
10104 (defun org-insert-property-drawer ()
10105 "Insert a property drawer into the current entry."
10106 (interactive)
10107 (org-back-to-heading t)
10108 (looking-at outline-regexp)
10109 (let ((indent (- (match-end 0)(match-beginning 0)))
10110 (beg (point))
10111 (re (concat "^[ \t]*" org-keyword-time-regexp))
10112 end hiddenp)
10113 (outline-next-heading)
10114 (setq end (point))
10115 (goto-char beg)
10116 (while (re-search-forward re end t))
10117 (setq hiddenp (org-invisible-p))
10118 (end-of-line 1)
10119 (and (equal (char-after) ?\n) (forward-char 1))
10120 (while (looking-at "^[ \t]*\\(:CLOCK:\\|CLOCK\\|:END:\\)")
10121 (beginning-of-line 2))
10122 (org-skip-over-state-notes)
10123 (skip-chars-backward " \t\n\r")
10124 (if (eq (char-before) ?*) (forward-char 1))
10125 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
10126 (beginning-of-line 0)
10127 (org-indent-to-column indent)
10128 (beginning-of-line 2)
10129 (org-indent-to-column indent)
10130 (beginning-of-line 0)
10131 (if hiddenp
10132 (save-excursion
10133 (org-back-to-heading t)
10134 (hide-entry))
10135 (org-flag-drawer t))))
10137 (defun org-set-property (property value)
10138 "In the current entry, set PROPERTY to VALUE.
10139 When called interactively, this will prompt for a property name, offering
10140 completion on existing and default properties. And then it will prompt
10141 for a value, offering competion either on allowed values (via an inherited
10142 xxx_ALL property) or on existing values in other instances of this property
10143 in the current file."
10144 (interactive
10145 (let* ((completion-ignore-case t)
10146 (keys (org-buffer-property-keys nil t t))
10147 (prop0 (completing-read "Property: " (mapcar 'list keys)))
10148 (prop (if (member prop0 keys)
10149 prop0
10150 (or (cdr (assoc (downcase prop0)
10151 (mapcar (lambda (x) (cons (downcase x) x))
10152 keys)))
10153 prop0)))
10154 (cur (org-entry-get nil prop))
10155 (allowed (org-property-get-allowed-values nil prop 'table))
10156 (existing (mapcar 'list (org-property-values prop)))
10157 (val (if allowed
10158 (org-completing-read "Value: " allowed nil 'req-match)
10159 (org-completing-read
10160 (concat "Value" (if (and cur (string-match "\\S-" cur))
10161 (concat "[" cur "]") "")
10162 ": ")
10163 existing nil nil "" nil cur))))
10164 (list prop (if (equal val "") cur val))))
10165 (unless (equal (org-entry-get nil property) value)
10166 (org-entry-put nil property value)))
10168 (defun org-delete-property (property)
10169 "In the current entry, delete PROPERTY."
10170 (interactive
10171 (let* ((completion-ignore-case t)
10172 (prop (completing-read
10173 "Property: " (org-entry-properties nil 'standard))))
10174 (list prop)))
10175 (message "Property %s %s" property
10176 (if (org-entry-delete nil property)
10177 "deleted"
10178 "was not present in the entry")))
10180 (defun org-delete-property-globally (property)
10181 "Remove PROPERTY globally, from all entries."
10182 (interactive
10183 (let* ((completion-ignore-case t)
10184 (prop (completing-read
10185 "Globally remove property: "
10186 (mapcar 'list (org-buffer-property-keys)))))
10187 (list prop)))
10188 (save-excursion
10189 (save-restriction
10190 (widen)
10191 (goto-char (point-min))
10192 (let ((cnt 0))
10193 (while (re-search-forward
10194 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
10195 nil t)
10196 (setq cnt (1+ cnt))
10197 (replace-match ""))
10198 (message "Property \"%s\" removed from %d entries" property cnt)))))
10200 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
10202 (defun org-compute-property-at-point ()
10203 "Compute the property at point.
10204 This looks for an enclosing column format, extracts the operator and
10205 then applies it to the proerty in the column format's scope."
10206 (interactive)
10207 (unless (org-at-property-p)
10208 (error "Not at a property"))
10209 (let ((prop (org-match-string-no-properties 2)))
10210 (org-columns-get-format-and-top-level)
10211 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
10212 (error "No operator defined for property %s" prop))
10213 (org-columns-compute prop)))
10215 (defun org-property-get-allowed-values (pom property &optional table)
10216 "Get allowed values for the property PROPERTY.
10217 When TABLE is non-nil, return an alist that can directly be used for
10218 completion."
10219 (let (vals)
10220 (cond
10221 ((equal property "TODO")
10222 (setq vals (org-with-point-at pom
10223 (append org-todo-keywords-1 '("")))))
10224 ((equal property "PRIORITY")
10225 (let ((n org-lowest-priority))
10226 (while (>= n org-highest-priority)
10227 (push (char-to-string n) vals)
10228 (setq n (1- n)))))
10229 ((member property org-special-properties))
10231 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
10233 (when (and vals (string-match "\\S-" vals))
10234 (setq vals (car (read-from-string (concat "(" vals ")"))))
10235 (setq vals (mapcar (lambda (x)
10236 (cond ((stringp x) x)
10237 ((numberp x) (number-to-string x))
10238 ((symbolp x) (symbol-name x))
10239 (t "???")))
10240 vals)))))
10241 (if table (mapcar 'list vals) vals)))
10243 (defun org-property-previous-allowed-value (&optional previous)
10244 "Switch to the next allowed value for this property."
10245 (interactive)
10246 (org-property-next-allowed-value t))
10248 (defun org-property-next-allowed-value (&optional previous)
10249 "Switch to the next allowed value for this property."
10250 (interactive)
10251 (unless (org-at-property-p)
10252 (error "Not at a property"))
10253 (let* ((key (match-string 2))
10254 (value (match-string 3))
10255 (allowed (or (org-property-get-allowed-values (point) key)
10256 (and (member value '("[ ]" "[-]" "[X]"))
10257 '("[ ]" "[X]"))))
10258 nval)
10259 (unless allowed
10260 (error "Allowed values for this property have not been defined"))
10261 (if previous (setq allowed (reverse allowed)))
10262 (if (member value allowed)
10263 (setq nval (car (cdr (member value allowed)))))
10264 (setq nval (or nval (car allowed)))
10265 (if (equal nval value)
10266 (error "Only one allowed value for this property"))
10267 (org-at-property-p)
10268 (replace-match (concat " :" key ": " nval) t t)
10269 (org-indent-line-function)
10270 (beginning-of-line 1)
10271 (skip-chars-forward " \t")))
10273 (defun org-find-entry-with-id (ident)
10274 "Locate the entry that contains the ID property with exact value IDENT.
10275 IDENT can be a string, a symbol or a number, this function will search for
10276 the string representation of it.
10277 Return the position where this entry starts, or nil if there is no such entry."
10278 (let ((id (cond
10279 ((stringp ident) ident)
10280 ((symbol-name ident) (symbol-name ident))
10281 ((numberp ident) (number-to-string ident))
10282 (t (error "IDENT %s must be a string, symbol or number" ident))))
10283 (case-fold-search nil))
10284 (save-excursion
10285 (save-restriction
10286 (widen)
10287 (goto-char (point-min))
10288 (when (re-search-forward
10289 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
10290 nil t)
10291 (org-back-to-heading)
10292 (point))))))
10294 ;;;; Timestamps
10296 (defvar org-last-changed-timestamp nil)
10297 (defvar org-last-inserted-timestamp nil
10298 "The last time stamp inserted with `org-insert-time-stamp'.")
10299 (defvar org-time-was-given) ; dynamically scoped parameter
10300 (defvar org-end-time-was-given) ; dynamically scoped parameter
10301 (defvar org-ts-what) ; dynamically scoped parameter
10303 (defun org-time-stamp (arg &optional inactive)
10304 "Prompt for a date/time and insert a time stamp.
10305 If the user specifies a time like HH:MM, or if this command is called
10306 with a prefix argument, the time stamp will contain date and time.
10307 Otherwise, only the date will be included. All parts of a date not
10308 specified by the user will be filled in from the current date/time.
10309 So if you press just return without typing anything, the time stamp
10310 will represent the current date/time. If there is already a timestamp
10311 at the cursor, it will be modified."
10312 (interactive "P")
10313 (let* ((ts nil)
10314 (default-time
10315 ;; Default time is either today, or, when entering a range,
10316 ;; the range start.
10317 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
10318 (save-excursion
10319 (re-search-backward
10320 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
10321 (- (point) 20) t)))
10322 (apply 'encode-time (org-parse-time-string (match-string 1)))
10323 (current-time)))
10324 (default-input (and ts (org-get-compact-tod ts)))
10325 org-time-was-given org-end-time-was-given time)
10326 (cond
10327 ((and (org-at-timestamp-p t)
10328 (memq last-command '(org-time-stamp org-time-stamp-inactive))
10329 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
10330 (insert "--")
10331 (setq time (let ((this-command this-command))
10332 (org-read-date arg 'totime nil nil
10333 default-time default-input)))
10334 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
10335 ((org-at-timestamp-p t)
10336 (setq time (let ((this-command this-command))
10337 (org-read-date arg 'totime nil nil default-time default-input)))
10338 (when (org-at-timestamp-p t) ; just to get the match data
10339 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
10340 (replace-match "")
10341 (setq org-last-changed-timestamp
10342 (org-insert-time-stamp
10343 time (or org-time-was-given arg)
10344 inactive nil nil (list org-end-time-was-given))))
10345 (message "Timestamp updated"))
10347 (setq time (let ((this-command this-command))
10348 (org-read-date arg 'totime nil nil default-time default-input)))
10349 (org-insert-time-stamp time (or org-time-was-given arg) inactive
10350 nil nil (list org-end-time-was-given))))))
10352 ;; FIXME: can we use this for something else, like computing time differences?
10353 (defun org-get-compact-tod (s)
10354 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
10355 (let* ((t1 (match-string 1 s))
10356 (h1 (string-to-number (match-string 2 s)))
10357 (m1 (string-to-number (match-string 3 s)))
10358 (t2 (and (match-end 4) (match-string 5 s)))
10359 (h2 (and t2 (string-to-number (match-string 6 s))))
10360 (m2 (and t2 (string-to-number (match-string 7 s))))
10361 dh dm)
10362 (if (not t2)
10364 (setq dh (- h2 h1) dm (- m2 m1))
10365 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
10366 (concat t1 "+" (number-to-string dh)
10367 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
10369 (defun org-time-stamp-inactive (&optional arg)
10370 "Insert an inactive time stamp.
10371 An inactive time stamp is enclosed in square brackets instead of angle
10372 brackets. It is inactive in the sense that it does not trigger agenda entries,
10373 does not link to the calendar and cannot be changed with the S-cursor keys.
10374 So these are more for recording a certain time/date."
10375 (interactive "P")
10376 (org-time-stamp arg 'inactive))
10378 (defvar org-date-ovl (org-make-overlay 1 1))
10379 (org-overlay-put org-date-ovl 'face 'org-warning)
10380 (org-detach-overlay org-date-ovl)
10382 (defvar org-ans1) ; dynamically scoped parameter
10383 (defvar org-ans2) ; dynamically scoped parameter
10385 (defvar org-plain-time-of-day-regexp) ; defined below
10387 (defvar org-overriding-default-time nil) ; dynamically scoped
10388 (defvar org-read-date-overlay nil)
10389 (defvar org-dcst nil) ; dynamically scoped
10391 (defun org-read-date (&optional with-time to-time from-string prompt
10392 default-time default-input)
10393 "Read a date, possibly a time, and make things smooth for the user.
10394 The prompt will suggest to enter an ISO date, but you can also enter anything
10395 which will at least partially be understood by `parse-time-string'.
10396 Unrecognized parts of the date will default to the current day, month, year,
10397 hour and minute. If this command is called to replace a timestamp at point,
10398 of to enter the second timestamp of a range, the default time is taken from the
10399 existing stamp. For example,
10400 3-2-5 --> 2003-02-05
10401 feb 15 --> currentyear-02-15
10402 sep 12 9 --> 2009-09-12
10403 12:45 --> today 12:45
10404 22 sept 0:34 --> currentyear-09-22 0:34
10405 12 --> currentyear-currentmonth-12
10406 Fri --> nearest Friday (today or later)
10407 etc.
10409 Furthermore you can specify a relative date by giving, as the *first* thing
10410 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
10411 change in days weeks, months, years.
10412 With a single plus or minus, the date is relative to today. With a double
10413 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
10414 +4d --> four days from today
10415 +4 --> same as above
10416 +2w --> two weeks from today
10417 ++5 --> five days from default date
10419 The function understands only English month and weekday abbreviations,
10420 but this can be configured with the variables `parse-time-months' and
10421 `parse-time-weekdays'.
10423 While prompting, a calendar is popped up - you can also select the
10424 date with the mouse (button 1). The calendar shows a period of three
10425 months. To scroll it to other months, use the keys `>' and `<'.
10426 If you don't like the calendar, turn it off with
10427 \(setq org-read-date-popup-calendar nil)
10429 With optional argument TO-TIME, the date will immediately be converted
10430 to an internal time.
10431 With an optional argument WITH-TIME, the prompt will suggest to also
10432 insert a time. Note that when WITH-TIME is not set, you can still
10433 enter a time, and this function will inform the calling routine about
10434 this change. The calling routine may then choose to change the format
10435 used to insert the time stamp into the buffer to include the time.
10436 With optional argument FROM-STRING, read from this string instead from
10437 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
10438 the time/date that is used for everything that is not specified by the
10439 user."
10440 (require 'parse-time)
10441 (let* ((org-time-stamp-rounding-minutes
10442 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
10443 (org-dcst org-display-custom-times)
10444 (ct (org-current-time))
10445 (def (or org-overriding-default-time default-time ct))
10446 (defdecode (decode-time def))
10447 (dummy (progn
10448 (when (< (nth 2 defdecode) org-extend-today-until)
10449 (setcar (nthcdr 2 defdecode) -1)
10450 (setcar (nthcdr 1 defdecode) 59)
10451 (setq def (apply 'encode-time defdecode)
10452 defdecode (decode-time def)))))
10453 (calendar-move-hook nil)
10454 (calendar-view-diary-initially-flag nil)
10455 (view-diary-entries-initially nil)
10456 (calendar-view-holidays-initially-flag nil)
10457 (view-calendar-holidays-initially nil)
10458 (timestr (format-time-string
10459 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
10460 (prompt (concat (if prompt (concat prompt " ") "")
10461 (format "Date+time [%s]: " timestr)))
10462 ans (org-ans0 "") org-ans1 org-ans2 final)
10464 (cond
10465 (from-string (setq ans from-string))
10466 (org-read-date-popup-calendar
10467 (save-excursion
10468 (save-window-excursion
10469 (calendar)
10470 (calendar-forward-day (- (time-to-days def)
10471 (calendar-absolute-from-gregorian
10472 (calendar-current-date))))
10473 (org-eval-in-calendar nil t)
10474 (let* ((old-map (current-local-map))
10475 (map (copy-keymap calendar-mode-map))
10476 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
10477 (org-defkey map (kbd "RET") 'org-calendar-select)
10478 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
10479 'org-calendar-select-mouse)
10480 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
10481 'org-calendar-select-mouse)
10482 (org-defkey minibuffer-local-map [(meta shift left)]
10483 (lambda () (interactive)
10484 (org-eval-in-calendar '(calendar-backward-month 1))))
10485 (org-defkey minibuffer-local-map [(meta shift right)]
10486 (lambda () (interactive)
10487 (org-eval-in-calendar '(calendar-forward-month 1))))
10488 (org-defkey minibuffer-local-map [(meta shift up)]
10489 (lambda () (interactive)
10490 (org-eval-in-calendar '(calendar-backward-year 1))))
10491 (org-defkey minibuffer-local-map [(meta shift down)]
10492 (lambda () (interactive)
10493 (org-eval-in-calendar '(calendar-forward-year 1))))
10494 (org-defkey minibuffer-local-map [(shift up)]
10495 (lambda () (interactive)
10496 (org-eval-in-calendar '(calendar-backward-week 1))))
10497 (org-defkey minibuffer-local-map [(shift down)]
10498 (lambda () (interactive)
10499 (org-eval-in-calendar '(calendar-forward-week 1))))
10500 (org-defkey minibuffer-local-map [(shift left)]
10501 (lambda () (interactive)
10502 (org-eval-in-calendar '(calendar-backward-day 1))))
10503 (org-defkey minibuffer-local-map [(shift right)]
10504 (lambda () (interactive)
10505 (org-eval-in-calendar '(calendar-forward-day 1))))
10506 (org-defkey minibuffer-local-map ">"
10507 (lambda () (interactive)
10508 (org-eval-in-calendar '(scroll-calendar-left 1))))
10509 (org-defkey minibuffer-local-map "<"
10510 (lambda () (interactive)
10511 (org-eval-in-calendar '(scroll-calendar-right 1))))
10512 (unwind-protect
10513 (progn
10514 (use-local-map map)
10515 (add-hook 'post-command-hook 'org-read-date-display)
10516 (setq org-ans0 (read-string prompt default-input nil nil))
10517 ;; org-ans0: from prompt
10518 ;; org-ans1: from mouse click
10519 ;; org-ans2: from calendar motion
10520 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
10521 (remove-hook 'post-command-hook 'org-read-date-display)
10522 (use-local-map old-map)
10523 (when org-read-date-overlay
10524 (org-delete-overlay org-read-date-overlay)
10525 (setq org-read-date-overlay nil)))))))
10527 (t ; Naked prompt only
10528 (unwind-protect
10529 (setq ans (read-string prompt default-input nil timestr))
10530 (when org-read-date-overlay
10531 (org-delete-overlay org-read-date-overlay)
10532 (setq org-read-date-overlay nil)))))
10534 (setq final (org-read-date-analyze ans def defdecode))
10536 (if to-time
10537 (apply 'encode-time final)
10538 (if (and (boundp 'org-time-was-given) org-time-was-given)
10539 (format "%04d-%02d-%02d %02d:%02d"
10540 (nth 5 final) (nth 4 final) (nth 3 final)
10541 (nth 2 final) (nth 1 final))
10542 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
10543 (defvar def)
10544 (defvar defdecode)
10545 (defvar with-time)
10546 (defun org-read-date-display ()
10547 "Display the currrent date prompt interpretation in the minibuffer."
10548 (when org-read-date-display-live
10549 (when org-read-date-overlay
10550 (org-delete-overlay org-read-date-overlay))
10551 (let ((p (point)))
10552 (end-of-line 1)
10553 (while (not (equal (buffer-substring
10554 (max (point-min) (- (point) 4)) (point))
10555 " "))
10556 (insert " "))
10557 (goto-char p))
10558 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
10559 " " (or org-ans1 org-ans2)))
10560 (org-end-time-was-given nil)
10561 (f (org-read-date-analyze ans def defdecode))
10562 (fmts (if org-dcst
10563 org-time-stamp-custom-formats
10564 org-time-stamp-formats))
10565 (fmt (if (or with-time
10566 (and (boundp 'org-time-was-given) org-time-was-given))
10567 (cdr fmts)
10568 (car fmts)))
10569 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
10570 (when (and org-end-time-was-given
10571 (string-match org-plain-time-of-day-regexp txt))
10572 (setq txt (concat (substring txt 0 (match-end 0)) "-"
10573 org-end-time-was-given
10574 (substring txt (match-end 0)))))
10575 (setq org-read-date-overlay
10576 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
10577 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
10579 (defun org-read-date-analyze (ans def defdecode)
10580 "Analyze the combined answer of the date prompt."
10581 ;; FIXME: cleanup and comment
10582 (let (delta deltan deltaw deltadef year month day
10583 hour minute second wday pm h2 m2 tl wday1
10584 iso-year iso-weekday iso-week iso-year iso-date)
10586 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
10587 (setq ans "+0"))
10589 (when (setq delta (org-read-date-get-relative ans (current-time) def))
10590 (setq ans (replace-match "" t t ans)
10591 deltan (car delta)
10592 deltaw (nth 1 delta)
10593 deltadef (nth 2 delta)))
10595 ;; Check if there is an iso week date in there
10596 ;; If yes, sore the info and ostpone interpreting it until the rest
10597 ;; of the parsing is done
10598 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
10599 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
10600 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
10601 iso-week (string-to-number (match-string 2 ans)))
10602 (setq ans (replace-match "" t t ans)))
10604 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
10605 (when (string-match
10606 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
10607 (setq year (if (match-end 2)
10608 (string-to-number (match-string 2 ans))
10609 (string-to-number (format-time-string "%Y")))
10610 month (string-to-number (match-string 3 ans))
10611 day (string-to-number (match-string 4 ans)))
10612 (if (< year 100) (setq year (+ 2000 year)))
10613 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
10614 t nil ans)))
10615 ;; Help matching am/pm times, because `parse-time-string' does not do that.
10616 ;; If there is a time with am/pm, and *no* time without it, we convert
10617 ;; so that matching will be successful.
10618 (loop for i from 1 to 2 do ; twice, for end time as well
10619 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
10620 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
10621 (setq hour (string-to-number (match-string 1 ans))
10622 minute (if (match-end 3)
10623 (string-to-number (match-string 3 ans))
10625 pm (equal ?p
10626 (string-to-char (downcase (match-string 4 ans)))))
10627 (if (and (= hour 12) (not pm))
10628 (setq hour 0)
10629 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
10630 (setq ans (replace-match (format "%02d:%02d" hour minute)
10631 t t ans))))
10633 ;; Check if a time range is given as a duration
10634 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
10635 (setq hour (string-to-number (match-string 1 ans))
10636 h2 (+ hour (string-to-number (match-string 3 ans)))
10637 minute (string-to-number (match-string 2 ans))
10638 m2 (+ minute (if (match-end 5) (string-to-number
10639 (match-string 5 ans))0)))
10640 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
10641 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
10642 t t ans)))
10644 ;; Check if there is a time range
10645 (when (boundp 'org-end-time-was-given)
10646 (setq org-time-was-given nil)
10647 (when (and (string-match org-plain-time-of-day-regexp ans)
10648 (match-end 8))
10649 (setq org-end-time-was-given (match-string 8 ans))
10650 (setq ans (concat (substring ans 0 (match-beginning 7))
10651 (substring ans (match-end 7))))))
10653 (setq tl (parse-time-string ans)
10654 day (or (nth 3 tl) (nth 3 defdecode))
10655 month (or (nth 4 tl)
10656 (if (and org-read-date-prefer-future
10657 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
10658 (1+ (nth 4 defdecode))
10659 (nth 4 defdecode)))
10660 year (or (nth 5 tl)
10661 (if (and org-read-date-prefer-future
10662 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
10663 (1+ (nth 5 defdecode))
10664 (nth 5 defdecode)))
10665 hour (or (nth 2 tl) (nth 2 defdecode))
10666 minute (or (nth 1 tl) (nth 1 defdecode))
10667 second (or (nth 0 tl) 0)
10668 wday (nth 6 tl))
10670 ;; Special date definitions below
10671 (cond
10672 (iso-week
10673 ;; There was an iso week
10674 (setq year (or iso-year year)
10675 day (or iso-weekday wday 1)
10676 wday nil ; to make sure that the trigger below does not match
10677 iso-date (calendar-gregorian-from-absolute
10678 (calendar-absolute-from-iso
10679 (list iso-week day year))))
10680 ; FIXME: Should we also push ISO weeks into the future?
10681 ; (when (and org-read-date-prefer-future
10682 ; (not iso-year)
10683 ; (< (calendar-absolute-from-gregorian iso-date)
10684 ; (time-to-days (current-time))))
10685 ; (setq year (1+ year)
10686 ; iso-date (calendar-gregorian-from-absolute
10687 ; (calendar-absolute-from-iso
10688 ; (list iso-week day year)))))
10689 (setq month (car iso-date)
10690 year (nth 2 iso-date)
10691 day (nth 1 iso-date)))
10692 (deltan
10693 (unless deltadef
10694 (let ((now (decode-time (current-time))))
10695 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
10696 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
10697 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
10698 ((equal deltaw "m") (setq month (+ month deltan)))
10699 ((equal deltaw "y") (setq year (+ year deltan)))))
10700 ((and wday (not (nth 3 tl)))
10701 ;; Weekday was given, but no day, so pick that day in the week
10702 ;; on or after the derived date.
10703 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
10704 (unless (equal wday wday1)
10705 (setq day (+ day (% (- wday wday1 -7) 7))))))
10706 (if (and (boundp 'org-time-was-given)
10707 (nth 2 tl))
10708 (setq org-time-was-given t))
10709 (if (< year 100) (setq year (+ 2000 year)))
10710 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
10711 (list second minute hour day month year)))
10713 (defvar parse-time-weekdays)
10715 (defun org-read-date-get-relative (s today default)
10716 "Check string S for special relative date string.
10717 TODAY and DEFAULT are internal times, for today and for a default.
10718 Return shift list (N what def-flag)
10719 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
10720 N is the number of WHATs to shift.
10721 DEF-FLAG is t when a double ++ or -- indicates shift relative to
10722 the DEFAULT date rather than TODAY."
10723 (when (and
10724 (string-match
10725 (concat
10726 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
10727 "\\([0-9]+\\)?"
10728 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
10729 "\\([ \t]\\|$\\)") s)
10730 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
10731 (let* ((dir (if (> (match-end 1) (match-beginning 1))
10732 (string-to-char (substring (match-string 1 s) -1))
10733 ?+))
10734 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
10735 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
10736 (what (if (match-end 3) (match-string 3 s) "d"))
10737 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
10738 (date (if rel default today))
10739 (wday (nth 6 (decode-time date)))
10740 delta)
10741 (if wday1
10742 (progn
10743 (setq delta (mod (+ 7 (- wday1 wday)) 7))
10744 (if (= dir ?-) (setq delta (- delta 7)))
10745 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
10746 (list delta "d" rel))
10747 (list (* n (if (= dir ?-) -1 1)) what rel)))))
10749 (defun org-eval-in-calendar (form &optional keepdate)
10750 "Eval FORM in the calendar window and return to current window.
10751 Also, store the cursor date in variable org-ans2."
10752 (let ((sw (selected-window)))
10753 (select-window (get-buffer-window "*Calendar*"))
10754 (eval form)
10755 (when (and (not keepdate) (calendar-cursor-to-date))
10756 (let* ((date (calendar-cursor-to-date))
10757 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10758 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
10759 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
10760 (select-window sw)))
10762 (defun org-calendar-select ()
10763 "Return to `org-read-date' with the date currently selected.
10764 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
10765 (interactive)
10766 (when (calendar-cursor-to-date)
10767 (let* ((date (calendar-cursor-to-date))
10768 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10769 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
10770 (if (active-minibuffer-window) (exit-minibuffer))))
10772 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
10773 "Insert a date stamp for the date given by the internal TIME.
10774 WITH-HM means, use the stamp format that includes the time of the day.
10775 INACTIVE means use square brackets instead of angular ones, so that the
10776 stamp will not contribute to the agenda.
10777 PRE and POST are optional strings to be inserted before and after the
10778 stamp.
10779 The command returns the inserted time stamp."
10780 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
10781 stamp)
10782 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
10783 (insert-before-markers (or pre ""))
10784 (insert-before-markers (setq stamp (format-time-string fmt time)))
10785 (when (listp extra)
10786 (setq extra (car extra))
10787 (if (and (stringp extra)
10788 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
10789 (setq extra (format "-%02d:%02d"
10790 (string-to-number (match-string 1 extra))
10791 (string-to-number (match-string 2 extra))))
10792 (setq extra nil)))
10793 (when extra
10794 (backward-char 1)
10795 (insert-before-markers extra)
10796 (forward-char 1))
10797 (insert-before-markers (or post ""))
10798 (setq org-last-inserted-timestamp stamp)))
10800 (defun org-toggle-time-stamp-overlays ()
10801 "Toggle the use of custom time stamp formats."
10802 (interactive)
10803 (setq org-display-custom-times (not org-display-custom-times))
10804 (unless org-display-custom-times
10805 (let ((p (point-min)) (bmp (buffer-modified-p)))
10806 (while (setq p (next-single-property-change p 'display))
10807 (if (and (get-text-property p 'display)
10808 (eq (get-text-property p 'face) 'org-date))
10809 (remove-text-properties
10810 p (setq p (next-single-property-change p 'display))
10811 '(display t))))
10812 (set-buffer-modified-p bmp)))
10813 (if (featurep 'xemacs)
10814 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
10815 (org-restart-font-lock)
10816 (setq org-table-may-need-update t)
10817 (if org-display-custom-times
10818 (message "Time stamps are overlayed with custom format")
10819 (message "Time stamp overlays removed")))
10821 (defun org-display-custom-time (beg end)
10822 "Overlay modified time stamp format over timestamp between BEG and END."
10823 (let* ((ts (buffer-substring beg end))
10824 t1 w1 with-hm tf time str w2 (off 0))
10825 (save-match-data
10826 (setq t1 (org-parse-time-string ts t))
10827 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
10828 (setq off (- (match-end 0) (match-beginning 0)))))
10829 (setq end (- end off))
10830 (setq w1 (- end beg)
10831 with-hm (and (nth 1 t1) (nth 2 t1))
10832 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
10833 time (org-fix-decoded-time t1)
10834 str (org-add-props
10835 (format-time-string
10836 (substring tf 1 -1) (apply 'encode-time time))
10837 nil 'mouse-face 'highlight)
10838 w2 (length str))
10839 (if (not (= w2 w1))
10840 (add-text-properties (1+ beg) (+ 2 beg)
10841 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
10842 (if (featurep 'xemacs)
10843 (progn
10844 (put-text-property beg end 'invisible t)
10845 (put-text-property beg end 'end-glyph (make-glyph str)))
10846 (put-text-property beg end 'display str))))
10848 (defun org-translate-time (string)
10849 "Translate all timestamps in STRING to custom format.
10850 But do this only if the variable `org-display-custom-times' is set."
10851 (when org-display-custom-times
10852 (save-match-data
10853 (let* ((start 0)
10854 (re org-ts-regexp-both)
10855 t1 with-hm inactive tf time str beg end)
10856 (while (setq start (string-match re string start))
10857 (setq beg (match-beginning 0)
10858 end (match-end 0)
10859 t1 (save-match-data
10860 (org-parse-time-string (substring string beg end) t))
10861 with-hm (and (nth 1 t1) (nth 2 t1))
10862 inactive (equal (substring string beg (1+ beg)) "[")
10863 tf (funcall (if with-hm 'cdr 'car)
10864 org-time-stamp-custom-formats)
10865 time (org-fix-decoded-time t1)
10866 str (format-time-string
10867 (concat
10868 (if inactive "[" "<") (substring tf 1 -1)
10869 (if inactive "]" ">"))
10870 (apply 'encode-time time))
10871 string (replace-match str t t string)
10872 start (+ start (length str)))))))
10873 string)
10875 (defun org-fix-decoded-time (time)
10876 "Set 0 instead of nil for the first 6 elements of time.
10877 Don't touch the rest."
10878 (let ((n 0))
10879 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
10881 (defun org-days-to-time (timestamp-string)
10882 "Difference between TIMESTAMP-STRING and now in days."
10883 (- (time-to-days (org-time-string-to-time timestamp-string))
10884 (time-to-days (current-time))))
10886 (defun org-deadline-close (timestamp-string &optional ndays)
10887 "Is the time in TIMESTAMP-STRING close to the current date?"
10888 (setq ndays (or ndays (org-get-wdays timestamp-string)))
10889 (and (< (org-days-to-time timestamp-string) ndays)
10890 (not (org-entry-is-done-p))))
10892 (defun org-get-wdays (ts)
10893 "Get the deadline lead time appropriate for timestring TS."
10894 (cond
10895 ((<= org-deadline-warning-days 0)
10896 ;; 0 or negative, enforce this value no matter what
10897 (- org-deadline-warning-days))
10898 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
10899 ;; lead time is specified.
10900 (floor (* (string-to-number (match-string 1 ts))
10901 (cdr (assoc (match-string 2 ts)
10902 '(("d" . 1) ("w" . 7)
10903 ("m" . 30.4) ("y" . 365.25)))))))
10904 ;; go for the default.
10905 (t org-deadline-warning-days)))
10907 (defun org-calendar-select-mouse (ev)
10908 "Return to `org-read-date' with the date currently selected.
10909 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
10910 (interactive "e")
10911 (mouse-set-point ev)
10912 (when (calendar-cursor-to-date)
10913 (let* ((date (calendar-cursor-to-date))
10914 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10915 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
10916 (if (active-minibuffer-window) (exit-minibuffer))))
10918 (defun org-check-deadlines (ndays)
10919 "Check if there are any deadlines due or past due.
10920 A deadline is considered due if it happens within `org-deadline-warning-days'
10921 days from today's date. If the deadline appears in an entry marked DONE,
10922 it is not shown. The prefix arg NDAYS can be used to test that many
10923 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
10924 (interactive "P")
10925 (let* ((org-warn-days
10926 (cond
10927 ((equal ndays '(4)) 100000)
10928 (ndays (prefix-numeric-value ndays))
10929 (t (abs org-deadline-warning-days))))
10930 (case-fold-search nil)
10931 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
10932 (callback
10933 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
10935 (message "%d deadlines past-due or due within %d days"
10936 (org-occur regexp nil callback)
10937 org-warn-days)))
10939 (defun org-check-before-date (date)
10940 "Check if there are deadlines or scheduled entries before DATE."
10941 (interactive (list (org-read-date)))
10942 (let ((case-fold-search nil)
10943 (regexp (concat "\\<\\(" org-deadline-string
10944 "\\|" org-scheduled-string
10945 "\\) *<\\([^>]+\\)>"))
10946 (callback
10947 (lambda () (time-less-p
10948 (org-time-string-to-time (match-string 2))
10949 (org-time-string-to-time date)))))
10950 (message "%d entries before %s"
10951 (org-occur regexp nil callback) date)))
10953 (defun org-evaluate-time-range (&optional to-buffer)
10954 "Evaluate a time range by computing the difference between start and end.
10955 Normally the result is just printed in the echo area, but with prefix arg
10956 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
10957 If the time range is actually in a table, the result is inserted into the
10958 next column.
10959 For time difference computation, a year is assumed to be exactly 365
10960 days in order to avoid rounding problems."
10961 (interactive "P")
10963 (org-clock-update-time-maybe)
10964 (save-excursion
10965 (unless (org-at-date-range-p t)
10966 (goto-char (point-at-bol))
10967 (re-search-forward org-tr-regexp-both (point-at-eol) t))
10968 (if (not (org-at-date-range-p t))
10969 (error "Not at a time-stamp range, and none found in current line")))
10970 (let* ((ts1 (match-string 1))
10971 (ts2 (match-string 2))
10972 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
10973 (match-end (match-end 0))
10974 (time1 (org-time-string-to-time ts1))
10975 (time2 (org-time-string-to-time ts2))
10976 (t1 (time-to-seconds time1))
10977 (t2 (time-to-seconds time2))
10978 (diff (abs (- t2 t1)))
10979 (negative (< (- t2 t1) 0))
10980 ;; (ys (floor (* 365 24 60 60)))
10981 (ds (* 24 60 60))
10982 (hs (* 60 60))
10983 (fy "%dy %dd %02d:%02d")
10984 (fy1 "%dy %dd")
10985 (fd "%dd %02d:%02d")
10986 (fd1 "%dd")
10987 (fh "%02d:%02d")
10988 y d h m align)
10989 (if havetime
10990 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
10992 d (floor (/ diff ds)) diff (mod diff ds)
10993 h (floor (/ diff hs)) diff (mod diff hs)
10994 m (floor (/ diff 60)))
10995 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
10997 d (floor (+ (/ diff ds) 0.5))
10998 h 0 m 0))
10999 (if (not to-buffer)
11000 (message "%s" (org-make-tdiff-string y d h m))
11001 (if (org-at-table-p)
11002 (progn
11003 (goto-char match-end)
11004 (setq align t)
11005 (and (looking-at " *|") (goto-char (match-end 0))))
11006 (goto-char match-end))
11007 (if (looking-at
11008 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
11009 (replace-match ""))
11010 (if negative (insert " -"))
11011 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
11012 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
11013 (insert " " (format fh h m))))
11014 (if align (org-table-align))
11015 (message "Time difference inserted")))))
11017 (defun org-make-tdiff-string (y d h m)
11018 (let ((fmt "")
11019 (l nil))
11020 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
11021 l (push y l)))
11022 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
11023 l (push d l)))
11024 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
11025 l (push h l)))
11026 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
11027 l (push m l)))
11028 (apply 'format fmt (nreverse l))))
11030 (defun org-time-string-to-time (s)
11031 (apply 'encode-time (org-parse-time-string s)))
11033 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
11034 "Convert a time stamp to an absolute day number.
11035 If there is a specifyer for a cyclic time stamp, get the closest date to
11036 DAYNR.
11037 PREFER and SHOW_ALL are passed through to `org-closest-date'."
11038 (cond
11039 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
11040 (if (org-diary-sexp-entry (match-string 1 s) "" date)
11041 daynr
11042 (+ daynr 1000)))
11043 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
11044 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
11045 (time-to-days (current-time))) (match-string 0 s)
11046 prefer show-all))
11047 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
11049 (defun org-days-to-iso-week (days)
11050 "Return the iso week number."
11051 (require 'cal-iso)
11052 (car (calendar-iso-from-absolute days)))
11054 (defun org-small-year-to-year (year)
11055 "Convert 2-digit years into 4-digit years.
11056 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
11057 The year 2000 cannot be abbreviated. Any year lager than 99
11058 is retrned unchanged."
11059 (if (< year 38)
11060 (setq year (+ 2000 year))
11061 (if (< year 100)
11062 (setq year (+ 1900 year))))
11063 year)
11065 (defun org-time-from-absolute (d)
11066 "Return the time corresponding to date D.
11067 D may be an absolute day number, or a calendar-type list (month day year)."
11068 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
11069 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
11071 (defun org-calendar-holiday ()
11072 "List of holidays, for Diary display in Org-mode."
11073 (require 'holidays)
11074 (let ((hl (funcall
11075 (if (fboundp 'calendar-check-holidays)
11076 'calendar-check-holidays 'check-calendar-holidays) date)))
11077 (if hl (mapconcat 'identity hl "; "))))
11079 (defun org-diary-sexp-entry (sexp entry date)
11080 "Process a SEXP diary ENTRY for DATE."
11081 (require 'diary-lib)
11082 (let ((result (if calendar-debug-sexp
11083 (let ((stack-trace-on-error t))
11084 (eval (car (read-from-string sexp))))
11085 (condition-case nil
11086 (eval (car (read-from-string sexp)))
11087 (error
11088 (beep)
11089 (message "Bad sexp at line %d in %s: %s"
11090 (org-current-line)
11091 (buffer-file-name) sexp)
11092 (sleep-for 2))))))
11093 (cond ((stringp result) result)
11094 ((and (consp result)
11095 (stringp (cdr result))) (cdr result))
11096 (result entry)
11097 (t nil))))
11099 (defun org-diary-to-ical-string (frombuf)
11100 "Get iCalendar entries from diary entries in buffer FROMBUF.
11101 This uses the icalendar.el library."
11102 (let* ((tmpdir (if (featurep 'xemacs)
11103 (temp-directory)
11104 temporary-file-directory))
11105 (tmpfile (make-temp-name
11106 (expand-file-name "orgics" tmpdir)))
11107 buf rtn b e)
11108 (save-excursion
11109 (set-buffer frombuf)
11110 (icalendar-export-region (point-min) (point-max) tmpfile)
11111 (setq buf (find-buffer-visiting tmpfile))
11112 (set-buffer buf)
11113 (goto-char (point-min))
11114 (if (re-search-forward "^BEGIN:VEVENT" nil t)
11115 (setq b (match-beginning 0)))
11116 (goto-char (point-max))
11117 (if (re-search-backward "^END:VEVENT" nil t)
11118 (setq e (match-end 0)))
11119 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
11120 (kill-buffer buf)
11121 (delete-file tmpfile)
11122 rtn))
11124 (defun org-closest-date (start current change prefer show-all)
11125 "Find the date closest to CURRENT that is consistent with START and CHANGE.
11126 When PREFER is `past' return a date that is either CURRENT or past.
11127 When PREFER is `future', return a date that is either CURRENT or future.
11128 When SHOW-ALL is nil, only return the current occurence of a time stamp."
11129 ;; Make the proper lists from the dates
11130 (catch 'exit
11131 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
11132 dn dw sday cday n1 n2
11133 d m y y1 y2 date1 date2 nmonths nm ny m2)
11135 (setq start (org-date-to-gregorian start)
11136 current (org-date-to-gregorian
11137 (if show-all
11138 current
11139 (time-to-days (current-time))))
11140 sday (calendar-absolute-from-gregorian start)
11141 cday (calendar-absolute-from-gregorian current))
11143 (if (<= cday sday) (throw 'exit sday))
11145 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
11146 (setq dn (string-to-number (match-string 1 change))
11147 dw (cdr (assoc (match-string 2 change) a1)))
11148 (error "Invalid change specifyer: %s" change))
11149 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
11150 (cond
11151 ((eq dw 'day)
11152 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
11153 n2 (+ n1 dn)))
11154 ((eq dw 'year)
11155 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
11156 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
11157 (setq date1 (list m d y1)
11158 n1 (calendar-absolute-from-gregorian date1)
11159 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
11160 n2 (calendar-absolute-from-gregorian date2)))
11161 ((eq dw 'month)
11162 ;; approx number of month between the two dates
11163 (setq nmonths (floor (/ (- cday sday) 30.436875)))
11164 ;; How often does dn fit in there?
11165 (setq d (nth 1 start) m (car start) y (nth 2 start)
11166 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
11167 m (+ m nm)
11168 ny (floor (/ m 12))
11169 y (+ y ny)
11170 m (- m (* ny 12)))
11171 (while (> m 12) (setq m (- m 12) y (1+ y)))
11172 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
11173 (setq m2 (+ m dn) y2 y)
11174 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11175 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
11176 (while (<= n2 cday)
11177 (setq n1 n2 m m2 y y2)
11178 (setq m2 (+ m dn) y2 y)
11179 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11180 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
11181 (if show-all
11182 (cond
11183 ((eq prefer 'past) n1)
11184 ((eq prefer 'future) (if (= cday n1) n1 n2))
11185 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
11186 (cond
11187 ((eq prefer 'past) n1)
11188 ((eq prefer 'future) (if (= cday n1) n1 n2))
11189 (t (if (= cday n1) n1 n2)))))))
11191 (defun org-date-to-gregorian (date)
11192 "Turn any specification of DATE into a gregorian date for the calendar."
11193 (cond ((integerp date) (calendar-gregorian-from-absolute date))
11194 ((and (listp date) (= (length date) 3)) date)
11195 ((stringp date)
11196 (setq date (org-parse-time-string date))
11197 (list (nth 4 date) (nth 3 date) (nth 5 date)))
11198 ((listp date)
11199 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
11201 (defun org-parse-time-string (s &optional nodefault)
11202 "Parse the standard Org-mode time string.
11203 This should be a lot faster than the normal `parse-time-string'.
11204 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
11205 hour and minute fields will be nil if not given."
11206 (if (string-match org-ts-regexp0 s)
11207 (list 0
11208 (if (or (match-beginning 8) (not nodefault))
11209 (string-to-number (or (match-string 8 s) "0")))
11210 (if (or (match-beginning 7) (not nodefault))
11211 (string-to-number (or (match-string 7 s) "0")))
11212 (string-to-number (match-string 4 s))
11213 (string-to-number (match-string 3 s))
11214 (string-to-number (match-string 2 s))
11215 nil nil nil)
11216 (make-list 9 0)))
11218 (defun org-timestamp-up (&optional arg)
11219 "Increase the date item at the cursor by one.
11220 If the cursor is on the year, change the year. If it is on the month or
11221 the day, change that.
11222 With prefix ARG, change by that many units."
11223 (interactive "p")
11224 (org-timestamp-change (prefix-numeric-value arg)))
11226 (defun org-timestamp-down (&optional arg)
11227 "Decrease the date item at the cursor by one.
11228 If the cursor is on the year, change the year. If it is on the month or
11229 the day, change that.
11230 With prefix ARG, change by that many units."
11231 (interactive "p")
11232 (org-timestamp-change (- (prefix-numeric-value arg))))
11234 (defun org-timestamp-up-day (&optional arg)
11235 "Increase the date in the time stamp by one day.
11236 With prefix ARG, change that many days."
11237 (interactive "p")
11238 (if (and (not (org-at-timestamp-p t))
11239 (org-on-heading-p))
11240 (org-todo 'up)
11241 (org-timestamp-change (prefix-numeric-value arg) 'day)))
11243 (defun org-timestamp-down-day (&optional arg)
11244 "Decrease the date in the time stamp by one day.
11245 With prefix ARG, change that many days."
11246 (interactive "p")
11247 (if (and (not (org-at-timestamp-p t))
11248 (org-on-heading-p))
11249 (org-todo 'down)
11250 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
11252 (defun org-at-timestamp-p (&optional inactive-ok)
11253 "Determine if the cursor is in or at a timestamp."
11254 (interactive)
11255 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
11256 (pos (point))
11257 (ans (or (looking-at tsr)
11258 (save-excursion
11259 (skip-chars-backward "^[<\n\r\t")
11260 (if (> (point) (point-min)) (backward-char 1))
11261 (and (looking-at tsr)
11262 (> (- (match-end 0) pos) -1))))))
11263 (and ans
11264 (boundp 'org-ts-what)
11265 (setq org-ts-what
11266 (cond
11267 ((= pos (match-beginning 0)) 'bracket)
11268 ((= pos (1- (match-end 0))) 'bracket)
11269 ((org-pos-in-match-range pos 2) 'year)
11270 ((org-pos-in-match-range pos 3) 'month)
11271 ((org-pos-in-match-range pos 7) 'hour)
11272 ((org-pos-in-match-range pos 8) 'minute)
11273 ((or (org-pos-in-match-range pos 4)
11274 (org-pos-in-match-range pos 5)) 'day)
11275 ((and (> pos (or (match-end 8) (match-end 5)))
11276 (< pos (match-end 0)))
11277 (- pos (or (match-end 8) (match-end 5))))
11278 (t 'day))))
11279 ans))
11281 (defun org-toggle-timestamp-type ()
11282 "Toggle the type (<active> or [inactive]) of a time stamp."
11283 (interactive)
11284 (when (org-at-timestamp-p t)
11285 (save-excursion
11286 (goto-char (match-beginning 0))
11287 (insert (if (equal (char-after) ?<) "[" "<")) (delete-char 1)
11288 (goto-char (1- (match-end 0)))
11289 (insert (if (equal (char-after) ?>) "]" ">")) (delete-char 1))
11290 (message "Timestamp is now %sactive"
11291 (if (equal (char-before) ?>) "in" ""))))
11293 (defun org-timestamp-change (n &optional what)
11294 "Change the date in the time stamp at point.
11295 The date will be changed by N times WHAT. WHAT can be `day', `month',
11296 `year', `minute', `second'. If WHAT is not given, the cursor position
11297 in the timestamp determines what will be changed."
11298 (let ((pos (point))
11299 with-hm inactive
11300 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
11301 org-ts-what
11302 extra rem
11303 ts time time0)
11304 (if (not (org-at-timestamp-p t))
11305 (error "Not at a timestamp"))
11306 (if (and (not what) (eq org-ts-what 'bracket))
11307 (org-toggle-timestamp-type)
11308 (if (and (not what) (not (eq org-ts-what 'day))
11309 org-display-custom-times
11310 (get-text-property (point) 'display)
11311 (not (get-text-property (1- (point)) 'display)))
11312 (setq org-ts-what 'day))
11313 (setq org-ts-what (or what org-ts-what)
11314 inactive (= (char-after (match-beginning 0)) ?\[)
11315 ts (match-string 0))
11316 (replace-match "")
11317 (if (string-match
11318 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
11320 (setq extra (match-string 1 ts)))
11321 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
11322 (setq with-hm t))
11323 (setq time0 (org-parse-time-string ts))
11324 (when (and (eq org-ts-what 'minute)
11325 (eq current-prefix-arg nil))
11326 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
11327 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
11328 (setcar (cdr time0) (+ (nth 1 time0)
11329 (if (> n 0) (- rem) (- dm rem))))))
11330 (setq time
11331 (encode-time (or (car time0) 0)
11332 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
11333 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
11334 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
11335 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
11336 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
11337 (nthcdr 6 time0)))
11338 (when (integerp org-ts-what)
11339 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
11340 (if (eq what 'calendar)
11341 (let ((cal-date (org-get-date-from-calendar)))
11342 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
11343 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
11344 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
11345 (setcar time0 (or (car time0) 0))
11346 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
11347 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
11348 (setq time (apply 'encode-time time0))))
11349 (setq org-last-changed-timestamp
11350 (org-insert-time-stamp time with-hm inactive nil nil extra))
11351 (org-clock-update-time-maybe)
11352 (goto-char pos)
11353 ;; Try to recenter the calendar window, if any
11354 (if (and org-calendar-follow-timestamp-change
11355 (get-buffer-window "*Calendar*" t)
11356 (memq org-ts-what '(day month year)))
11357 (org-recenter-calendar (time-to-days time))))))
11359 (defun org-modify-ts-extra (s pos n dm)
11360 "Change the different parts of the lead-time and repeat fields in timestamp."
11361 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
11362 ng h m new rem)
11363 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
11364 (cond
11365 ((or (org-pos-in-match-range pos 2)
11366 (org-pos-in-match-range pos 3))
11367 (setq m (string-to-number (match-string 3 s))
11368 h (string-to-number (match-string 2 s)))
11369 (if (org-pos-in-match-range pos 2)
11370 (setq h (+ h n))
11371 (setq n (* dm (org-no-warnings (signum n))))
11372 (when (not (= 0 (setq rem (% m dm))))
11373 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
11374 (setq m (+ m n)))
11375 (if (< m 0) (setq m (+ m 60) h (1- h)))
11376 (if (> m 59) (setq m (- m 60) h (1+ h)))
11377 (setq h (min 24 (max 0 h)))
11378 (setq ng 1 new (format "-%02d:%02d" h m)))
11379 ((org-pos-in-match-range pos 6)
11380 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
11381 ((org-pos-in-match-range pos 5)
11382 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
11384 ((org-pos-in-match-range pos 9)
11385 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
11386 ((org-pos-in-match-range pos 8)
11387 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
11389 (when ng
11390 (setq s (concat
11391 (substring s 0 (match-beginning ng))
11393 (substring s (match-end ng))))))
11396 (defun org-recenter-calendar (date)
11397 "If the calendar is visible, recenter it to DATE."
11398 (let* ((win (selected-window))
11399 (cwin (get-buffer-window "*Calendar*" t))
11400 (calendar-move-hook nil))
11401 (when cwin
11402 (select-window cwin)
11403 (calendar-goto-date (if (listp date) date
11404 (calendar-gregorian-from-absolute date)))
11405 (select-window win))))
11407 (defun org-goto-calendar (&optional arg)
11408 "Go to the Emacs calendar at the current date.
11409 If there is a time stamp in the current line, go to that date.
11410 A prefix ARG can be used to force the current date."
11411 (interactive "P")
11412 (let ((tsr org-ts-regexp) diff
11413 (calendar-move-hook nil)
11414 (calendar-view-holidays-initially-flag nil)
11415 (view-calendar-holidays-initially nil)
11416 (calendar-view-diary-initially-flag nil)
11417 (view-diary-entries-initially nil))
11418 (if (or (org-at-timestamp-p)
11419 (save-excursion
11420 (beginning-of-line 1)
11421 (looking-at (concat ".*" tsr))))
11422 (let ((d1 (time-to-days (current-time)))
11423 (d2 (time-to-days
11424 (org-time-string-to-time (match-string 1)))))
11425 (setq diff (- d2 d1))))
11426 (calendar)
11427 (calendar-goto-today)
11428 (if (and diff (not arg)) (calendar-forward-day diff))))
11430 (defun org-get-date-from-calendar ()
11431 "Return a list (month day year) of date at point in calendar."
11432 (with-current-buffer "*Calendar*"
11433 (save-match-data
11434 (calendar-cursor-to-date))))
11436 (defun org-date-from-calendar ()
11437 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
11438 If there is already a time stamp at the cursor position, update it."
11439 (interactive)
11440 (if (org-at-timestamp-p t)
11441 (org-timestamp-change 0 'calendar)
11442 (let ((cal-date (org-get-date-from-calendar)))
11443 (org-insert-time-stamp
11444 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
11446 (defun org-minutes-to-hh:mm-string (m)
11447 "Compute H:MM from a number of minutes."
11448 (let ((h (/ m 60)))
11449 (setq m (- m (* 60 h)))
11450 (format org-time-clocksum-format h m)))
11452 (defun org-hh:mm-string-to-minutes (s)
11453 "Convert a string H:MM to a number of minutes."
11454 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
11455 (+ (* (string-to-number (match-string 1 s)) 60)
11456 (string-to-number (match-string 2 s)))
11459 ;;;; Agenda files
11461 ;;;###autoload
11462 (defun org-iswitchb (&optional arg)
11463 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
11464 With a prefix argument, restrict available to files.
11465 With two prefix arguments, restrict available buffers to agenda files.
11467 Due to some yet unresolved reason, the global function
11468 `iswitchb-mode' needs to be active for this function to work."
11469 (interactive "P")
11470 (require 'iswitchb)
11471 (let ((enabled iswitchb-mode) blist)
11472 (or enabled (iswitchb-mode 1))
11473 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
11474 ((equal arg '(16)) (org-buffer-list 'agenda))
11475 (t (org-buffer-list))))
11476 (unwind-protect
11477 (let ((iswitchb-make-buflist-hook
11478 (lambda ()
11479 (setq iswitchb-temp-buflist
11480 (mapcar 'buffer-name blist)))))
11481 (switch-to-buffer
11482 (iswitchb-read-buffer
11483 "Switch-to: " nil t))
11484 (or enabled (iswitchb-mode -1))))))
11486 (defun org-buffer-list (&optional predicate exclude-tmp)
11487 "Return a list of Org buffers.
11488 PREDICATE can be `export', `files' or `agenda'.
11490 export restrict the list to Export buffers.
11491 files restrict the list to buffers visiting Org files.
11492 agenda restrict the list to buffers visiting agenda files.
11494 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
11495 (let* ((bfn nil)
11496 (agenda-files (and (eq predicate 'agenda)
11497 (mapcar 'file-truename (org-agenda-files t))))
11498 (filter
11499 (cond
11500 ((eq predicate 'files)
11501 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
11502 ((eq predicate 'export)
11503 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
11504 ((eq predicate 'agenda)
11505 (lambda (b)
11506 (with-current-buffer b
11507 (and (eq major-mode 'org-mode)
11508 (setq bfn (buffer-file-name b))
11509 (member (file-truename bfn) agenda-files)))))
11510 (t (lambda (b) (with-current-buffer b
11511 (or (eq major-mode 'org-mode)
11512 (string-match "\*Org .*Export"
11513 (buffer-name b)))))))))
11514 (delq nil
11515 (mapcar
11516 (lambda(b)
11517 (if (and (funcall filter b)
11518 (or (not exclude-tmp)
11519 (not (string-match "tmp" (buffer-name b)))))
11521 nil))
11522 (buffer-list)))))
11524 (defun org-agenda-files (&optional unrestricted archives)
11525 "Get the list of agenda files.
11526 Optional UNRESTRICTED means return the full list even if a restriction
11527 is currently in place.
11528 When ARCHIVES is t, include all archive files hat are really being
11529 used by the agenda files. If ARCHIVE is `ifmode', do this only if
11530 `org-agenda-archives-mode' is t."
11531 (let ((files
11532 (cond
11533 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
11534 ((stringp org-agenda-files) (org-read-agenda-file-list))
11535 ((listp org-agenda-files) org-agenda-files)
11536 (t (error "Invalid value of `org-agenda-files'")))))
11537 (setq files (apply 'append
11538 (mapcar (lambda (f)
11539 (if (file-directory-p f)
11540 (directory-files
11541 f t org-agenda-file-regexp)
11542 (list f)))
11543 files)))
11544 (when org-agenda-skip-unavailable-files
11545 (setq files (delq nil
11546 (mapcar (function
11547 (lambda (file)
11548 (and (file-readable-p file) file)))
11549 files))))
11550 (when (or (eq archives t)
11551 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
11552 (setq files (org-add-archive-files files)))
11553 files))
11555 (defun org-edit-agenda-file-list ()
11556 "Edit the list of agenda files.
11557 Depending on setup, this either uses customize to edit the variable
11558 `org-agenda-files', or it visits the file that is holding the list. In the
11559 latter case, the buffer is set up in a way that saving it automatically kills
11560 the buffer and restores the previous window configuration."
11561 (interactive)
11562 (if (stringp org-agenda-files)
11563 (let ((cw (current-window-configuration)))
11564 (find-file org-agenda-files)
11565 (org-set-local 'org-window-configuration cw)
11566 (org-add-hook 'after-save-hook
11567 (lambda ()
11568 (set-window-configuration
11569 (prog1 org-window-configuration
11570 (kill-buffer (current-buffer))))
11571 (org-install-agenda-files-menu)
11572 (message "New agenda file list installed"))
11573 nil 'local)
11574 (message "%s" (substitute-command-keys
11575 "Edit list and finish with \\[save-buffer]")))
11576 (customize-variable 'org-agenda-files)))
11578 (defun org-store-new-agenda-file-list (list)
11579 "Set new value for the agenda file list and save it correcly."
11580 (if (stringp org-agenda-files)
11581 (let ((f org-agenda-files) b)
11582 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
11583 (with-temp-file f
11584 (insert (mapconcat 'identity list "\n") "\n")))
11585 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
11586 (setq org-agenda-files list)
11587 (customize-save-variable 'org-agenda-files org-agenda-files))))
11589 (defun org-read-agenda-file-list ()
11590 "Read the list of agenda files from a file."
11591 (when (file-directory-p org-agenda-files)
11592 (error "`org-agenda-files' cannot be a single directory"))
11593 (when (stringp org-agenda-files)
11594 (with-temp-buffer
11595 (insert-file-contents org-agenda-files)
11596 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
11599 ;;;###autoload
11600 (defun org-cycle-agenda-files ()
11601 "Cycle through the files in `org-agenda-files'.
11602 If the current buffer visits an agenda file, find the next one in the list.
11603 If the current buffer does not, find the first agenda file."
11604 (interactive)
11605 (let* ((fs (org-agenda-files t))
11606 (files (append fs (list (car fs))))
11607 (tcf (if buffer-file-name (file-truename buffer-file-name)))
11608 file)
11609 (unless files (error "No agenda files"))
11610 (catch 'exit
11611 (while (setq file (pop files))
11612 (if (equal (file-truename file) tcf)
11613 (when (car files)
11614 (find-file (car files))
11615 (throw 'exit t))))
11616 (find-file (car fs)))
11617 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
11619 (defun org-agenda-file-to-front (&optional to-end)
11620 "Move/add the current file to the top of the agenda file list.
11621 If the file is not present in the list, it is added to the front. If it is
11622 present, it is moved there. With optional argument TO-END, add/move to the
11623 end of the list."
11624 (interactive "P")
11625 (let ((org-agenda-skip-unavailable-files nil)
11626 (file-alist (mapcar (lambda (x)
11627 (cons (file-truename x) x))
11628 (org-agenda-files t)))
11629 (ctf (file-truename buffer-file-name))
11630 x had)
11631 (setq x (assoc ctf file-alist) had x)
11633 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
11634 (if to-end
11635 (setq file-alist (append (delq x file-alist) (list x)))
11636 (setq file-alist (cons x (delq x file-alist))))
11637 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
11638 (org-install-agenda-files-menu)
11639 (message "File %s to %s of agenda file list"
11640 (if had "moved" "added") (if to-end "end" "front"))))
11642 (defun org-remove-file (&optional file)
11643 "Remove current file from the list of files in variable `org-agenda-files'.
11644 These are the files which are being checked for agenda entries.
11645 Optional argument FILE means, use this file instead of the current."
11646 (interactive)
11647 (let* ((org-agenda-skip-unavailable-files nil)
11648 (file (or file buffer-file-name))
11649 (true-file (file-truename file))
11650 (afile (abbreviate-file-name file))
11651 (files (delq nil (mapcar
11652 (lambda (x)
11653 (if (equal true-file
11654 (file-truename x))
11655 nil x))
11656 (org-agenda-files t)))))
11657 (if (not (= (length files) (length (org-agenda-files t))))
11658 (progn
11659 (org-store-new-agenda-file-list files)
11660 (org-install-agenda-files-menu)
11661 (message "Removed file: %s" afile))
11662 (message "File was not in list: %s (not removed)" afile))))
11664 (defun org-file-menu-entry (file)
11665 (vector file (list 'find-file file) t))
11667 (defun org-check-agenda-file (file)
11668 "Make sure FILE exists. If not, ask user what to do."
11669 (when (not (file-exists-p file))
11670 (message "non-existent file %s. [R]emove from list or [A]bort?"
11671 (abbreviate-file-name file))
11672 (let ((r (downcase (read-char-exclusive))))
11673 (cond
11674 ((equal r ?r)
11675 (org-remove-file file)
11676 (throw 'nextfile t))
11677 (t (error "Abort"))))))
11679 (defun org-get-agenda-file-buffer (file)
11680 "Get a buffer visiting FILE. If the buffer needs to be created, add
11681 it to the list of buffers which might be released later."
11682 (let ((buf (org-find-base-buffer-visiting file)))
11683 (if buf
11684 buf ; just return it
11685 ;; Make a new buffer and remember it
11686 (setq buf (find-file-noselect file))
11687 (if buf (push buf org-agenda-new-buffers))
11688 buf)))
11690 (defun org-release-buffers (blist)
11691 "Release all buffers in list, asking the user for confirmation when needed.
11692 When a buffer is unmodified, it is just killed. When modified, it is saved
11693 \(if the user agrees) and then killed."
11694 (let (buf file)
11695 (while (setq buf (pop blist))
11696 (setq file (buffer-file-name buf))
11697 (when (and (buffer-modified-p buf)
11698 file
11699 (y-or-n-p (format "Save file %s? " file)))
11700 (with-current-buffer buf (save-buffer)))
11701 (kill-buffer buf))))
11703 (defun org-prepare-agenda-buffers (files)
11704 "Create buffers for all agenda files, protect archived trees and comments."
11705 (interactive)
11706 (let ((pa '(:org-archived t))
11707 (pc '(:org-comment t))
11708 (pall '(:org-archived t :org-comment t))
11709 (inhibit-read-only t)
11710 (rea (concat ":" org-archive-tag ":"))
11711 bmp file re)
11712 (save-excursion
11713 (save-restriction
11714 (while (setq file (pop files))
11715 (if (bufferp file)
11716 (set-buffer file)
11717 (org-check-agenda-file file)
11718 (set-buffer (org-get-agenda-file-buffer file)))
11719 (widen)
11720 (setq bmp (buffer-modified-p))
11721 (org-refresh-category-properties)
11722 (setq org-todo-keywords-for-agenda
11723 (append org-todo-keywords-for-agenda org-todo-keywords-1))
11724 (setq org-done-keywords-for-agenda
11725 (append org-done-keywords-for-agenda org-done-keywords))
11726 (setq org-todo-keyword-alist-for-agenda
11727 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
11728 (setq org-tag-alist-for-agenda
11729 (append org-tag-alist-for-agenda org-tag-alist))
11731 (save-excursion
11732 (remove-text-properties (point-min) (point-max) pall)
11733 (when org-agenda-skip-archived-trees
11734 (goto-char (point-min))
11735 (while (re-search-forward rea nil t)
11736 (if (org-on-heading-p t)
11737 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
11738 (goto-char (point-min))
11739 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
11740 (while (re-search-forward re nil t)
11741 (add-text-properties
11742 (match-beginning 0) (org-end-of-subtree t) pc)))
11743 (set-buffer-modified-p bmp))))
11744 (setq org-todo-keyword-alist-for-agenda
11745 (org-uniquify org-todo-keyword-alist-for-agenda)
11746 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
11748 ;;;; Embedded LaTeX
11750 (defvar org-cdlatex-mode-map (make-sparse-keymap)
11751 "Keymap for the minor `org-cdlatex-mode'.")
11753 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
11754 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
11755 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
11756 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
11757 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
11759 (defvar org-cdlatex-texmathp-advice-is-done nil
11760 "Flag remembering if we have applied the advice to texmathp already.")
11762 (define-minor-mode org-cdlatex-mode
11763 "Toggle the minor `org-cdlatex-mode'.
11764 This mode supports entering LaTeX environment and math in LaTeX fragments
11765 in Org-mode.
11766 \\{org-cdlatex-mode-map}"
11767 nil " OCDL" nil
11768 (when org-cdlatex-mode (require 'cdlatex))
11769 (unless org-cdlatex-texmathp-advice-is-done
11770 (setq org-cdlatex-texmathp-advice-is-done t)
11771 (defadvice texmathp (around org-math-always-on activate)
11772 "Always return t in org-mode buffers.
11773 This is because we want to insert math symbols without dollars even outside
11774 the LaTeX math segments. If Orgmode thinks that point is actually inside
11775 en embedded LaTeX fragement, let texmathp do its job.
11776 \\[org-cdlatex-mode-map]"
11777 (interactive)
11778 (let (p)
11779 (cond
11780 ((not (org-mode-p)) ad-do-it)
11781 ((eq this-command 'cdlatex-math-symbol)
11782 (setq ad-return-value t
11783 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
11785 (let ((p (org-inside-LaTeX-fragment-p)))
11786 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
11787 (setq ad-return-value t
11788 texmathp-why '("Org-mode embedded math" . 0))
11789 (if p ad-do-it)))))))))
11791 (defun turn-on-org-cdlatex ()
11792 "Unconditionally turn on `org-cdlatex-mode'."
11793 (org-cdlatex-mode 1))
11795 (defun org-inside-LaTeX-fragment-p ()
11796 "Test if point is inside a LaTeX fragment.
11797 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
11798 sequence appearing also before point.
11799 Even though the matchers for math are configurable, this function assumes
11800 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
11801 delimiters are skipped when they have been removed by customization.
11802 The return value is nil, or a cons cell with the delimiter and
11803 and the position of this delimiter.
11805 This function does a reasonably good job, but can locally be fooled by
11806 for example currency specifications. For example it will assume being in
11807 inline math after \"$22.34\". The LaTeX fragment formatter will only format
11808 fragments that are properly closed, but during editing, we have to live
11809 with the uncertainty caused by missing closing delimiters. This function
11810 looks only before point, not after."
11811 (catch 'exit
11812 (let ((pos (point))
11813 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
11814 (lim (progn
11815 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
11816 (point)))
11817 dd-on str (start 0) m re)
11818 (goto-char pos)
11819 (when dodollar
11820 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
11821 re (nth 1 (assoc "$" org-latex-regexps)))
11822 (while (string-match re str start)
11823 (cond
11824 ((= (match-end 0) (length str))
11825 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
11826 ((= (match-end 0) (- (length str) 5))
11827 (throw 'exit nil))
11828 (t (setq start (match-end 0))))))
11829 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
11830 (goto-char pos)
11831 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
11832 (and (match-beginning 2) (throw 'exit nil))
11833 ;; count $$
11834 (while (re-search-backward "\\$\\$" lim t)
11835 (setq dd-on (not dd-on)))
11836 (goto-char pos)
11837 (if dd-on (cons "$$" m))))))
11840 (defun org-try-cdlatex-tab ()
11841 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
11842 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
11843 - inside a LaTeX fragment, or
11844 - after the first word in a line, where an abbreviation expansion could
11845 insert a LaTeX environment."
11846 (when org-cdlatex-mode
11847 (cond
11848 ((save-excursion
11849 (skip-chars-backward "a-zA-Z0-9*")
11850 (skip-chars-backward " \t")
11851 (bolp))
11852 (cdlatex-tab) t)
11853 ((org-inside-LaTeX-fragment-p)
11854 (cdlatex-tab) t)
11855 (t nil))))
11857 (defun org-cdlatex-underscore-caret (&optional arg)
11858 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
11859 Revert to the normal definition outside of these fragments."
11860 (interactive "P")
11861 (if (org-inside-LaTeX-fragment-p)
11862 (call-interactively 'cdlatex-sub-superscript)
11863 (let (org-cdlatex-mode)
11864 (call-interactively (key-binding (vector last-input-event))))))
11866 (defun org-cdlatex-math-modify (&optional arg)
11867 "Execute `cdlatex-math-modify' in LaTeX fragments.
11868 Revert to the normal definition outside of these fragments."
11869 (interactive "P")
11870 (if (org-inside-LaTeX-fragment-p)
11871 (call-interactively 'cdlatex-math-modify)
11872 (let (org-cdlatex-mode)
11873 (call-interactively (key-binding (vector last-input-event))))))
11875 (defvar org-latex-fragment-image-overlays nil
11876 "List of overlays carrying the images of latex fragments.")
11877 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
11879 (defun org-remove-latex-fragment-image-overlays ()
11880 "Remove all overlays with LaTeX fragment images in current buffer."
11881 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
11882 (setq org-latex-fragment-image-overlays nil))
11884 (defun org-preview-latex-fragment (&optional subtree)
11885 "Preview the LaTeX fragment at point, or all locally or globally.
11886 If the cursor is in a LaTeX fragment, create the image and overlay
11887 it over the source code. If there is no fragment at point, display
11888 all fragments in the current text, from one headline to the next. With
11889 prefix SUBTREE, display all fragments in the current subtree. With a
11890 double prefix `C-u C-u', or when the cursor is before the first headline,
11891 display all fragments in the buffer.
11892 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
11893 (interactive "P")
11894 (org-remove-latex-fragment-image-overlays)
11895 (save-excursion
11896 (save-restriction
11897 (let (beg end at msg)
11898 (cond
11899 ((or (equal subtree '(16))
11900 (not (save-excursion
11901 (re-search-backward (concat "^" outline-regexp) nil t))))
11902 (setq beg (point-min) end (point-max)
11903 msg "Creating images for buffer...%s"))
11904 ((equal subtree '(4))
11905 (org-back-to-heading)
11906 (setq beg (point) end (org-end-of-subtree t)
11907 msg "Creating images for subtree...%s"))
11909 (if (setq at (org-inside-LaTeX-fragment-p))
11910 (goto-char (max (point-min) (- (cdr at) 2)))
11911 (org-back-to-heading))
11912 (setq beg (point) end (progn (outline-next-heading) (point))
11913 msg (if at "Creating image...%s"
11914 "Creating images for entry...%s"))))
11915 (message msg "")
11916 (narrow-to-region beg end)
11917 (goto-char beg)
11918 (org-format-latex
11919 (concat "ltxpng/" (file-name-sans-extension
11920 (file-name-nondirectory
11921 buffer-file-name)))
11922 default-directory 'overlays msg at 'forbuffer)
11923 (message msg "done. Use `C-c C-c' to remove images.")))))
11925 (defvar org-latex-regexps
11926 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
11927 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
11928 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
11929 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
11930 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
11931 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
11932 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
11933 "Regular expressions for matching embedded LaTeX.")
11935 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
11936 "Replace LaTeX fragments with links to an image, and produce images."
11937 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
11938 (let* ((prefixnodir (file-name-nondirectory prefix))
11939 (absprefix (expand-file-name prefix dir))
11940 (todir (file-name-directory absprefix))
11941 (opt org-format-latex-options)
11942 (matchers (plist-get opt :matchers))
11943 (re-list org-latex-regexps)
11944 (cnt 0) txt link beg end re e checkdir
11945 m n block linkfile movefile ov)
11946 ;; Check if there are old images files with this prefix, and remove them
11947 (when (file-directory-p todir)
11948 (mapc 'delete-file
11949 (directory-files
11950 todir 'full
11951 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
11952 ;; Check the different regular expressions
11953 (while (setq e (pop re-list))
11954 (setq m (car e) re (nth 1 e) n (nth 2 e)
11955 block (if (nth 3 e) "\n\n" ""))
11956 (when (member m matchers)
11957 (goto-char (point-min))
11958 (while (re-search-forward re nil t)
11959 (when (or (not at) (equal (cdr at) (match-beginning n)))
11960 (setq txt (match-string n)
11961 beg (match-beginning n) end (match-end n)
11962 cnt (1+ cnt)
11963 linkfile (format "%s_%04d.png" prefix cnt)
11964 movefile (format "%s_%04d.png" absprefix cnt)
11965 link (concat block "[[file:" linkfile "]]" block))
11966 (if msg (message msg cnt))
11967 (goto-char beg)
11968 (unless checkdir ; make sure the directory exists
11969 (setq checkdir t)
11970 (or (file-directory-p todir) (make-directory todir)))
11971 (org-create-formula-image
11972 txt movefile opt forbuffer)
11973 (if overlays
11974 (progn
11975 (setq ov (org-make-overlay beg end))
11976 (if (featurep 'xemacs)
11977 (progn
11978 (org-overlay-put ov 'invisible t)
11979 (org-overlay-put
11980 ov 'end-glyph
11981 (make-glyph (vector 'png :file movefile))))
11982 (org-overlay-put
11983 ov 'display
11984 (list 'image :type 'png :file movefile :ascent 'center)))
11985 (push ov org-latex-fragment-image-overlays)
11986 (goto-char end))
11987 (delete-region beg end)
11988 (insert link))))))))
11990 ;; This function borrows from Ganesh Swami's latex2png.el
11991 (defun org-create-formula-image (string tofile options buffer)
11992 (let* ((tmpdir (if (featurep 'xemacs)
11993 (temp-directory)
11994 temporary-file-directory))
11995 (texfilebase (make-temp-name
11996 (expand-file-name "orgtex" tmpdir)))
11997 (texfile (concat texfilebase ".tex"))
11998 (dvifile (concat texfilebase ".dvi"))
11999 (pngfile (concat texfilebase ".png"))
12000 (fnh (if (featurep 'xemacs)
12001 (font-height (get-face-font 'default))
12002 (face-attribute 'default :height nil)))
12003 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
12004 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
12005 (fg (or (plist-get options (if buffer :foreground :html-foreground))
12006 "Black"))
12007 (bg (or (plist-get options (if buffer :background :html-background))
12008 "Transparent")))
12009 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
12010 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
12011 (with-temp-file texfile
12012 (insert org-format-latex-header
12013 "\n\\begin{document}\n" string "\n\\end{document}\n"))
12014 (let ((dir default-directory))
12015 (condition-case nil
12016 (progn
12017 (cd tmpdir)
12018 (call-process "latex" nil nil nil texfile))
12019 (error nil))
12020 (cd dir))
12021 (if (not (file-exists-p dvifile))
12022 (progn (message "Failed to create dvi file from %s" texfile) nil)
12023 (condition-case nil
12024 (call-process "dvipng" nil nil nil
12025 "-E" "-fg" fg "-bg" bg
12026 "-D" dpi
12027 ;;"-x" scale "-y" scale
12028 "-T" "tight"
12029 "-o" pngfile
12030 dvifile)
12031 (error nil))
12032 (if (not (file-exists-p pngfile))
12033 (progn (message "Failed to create png file from %s" texfile) nil)
12034 ;; Use the requested file name and clean up
12035 (copy-file pngfile tofile 'replace)
12036 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
12037 (delete-file (concat texfilebase e)))
12038 pngfile))))
12040 (defun org-dvipng-color (attr)
12041 "Return an rgb color specification for dvipng."
12042 (apply 'format "rgb %s %s %s"
12043 (mapcar 'org-normalize-color
12044 (color-values (face-attribute 'default attr nil)))))
12046 (defun org-normalize-color (value)
12047 "Return string to be used as color value for an RGB component."
12048 (format "%g" (/ value 65535.0)))
12051 ;;;; Key bindings
12053 ;; Make `C-c C-x' a prefix key
12054 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
12056 ;; TAB key with modifiers
12057 (org-defkey org-mode-map "\C-i" 'org-cycle)
12058 (org-defkey org-mode-map [(tab)] 'org-cycle)
12059 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
12060 (org-defkey org-mode-map [(meta tab)] 'org-complete)
12061 (org-defkey org-mode-map "\M-\t" 'org-complete)
12062 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
12063 ;; The following line is necessary under Suse GNU/Linux
12064 (unless (featurep 'xemacs)
12065 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
12066 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
12067 (define-key org-mode-map [backtab] 'org-shifttab)
12069 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
12070 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
12071 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
12073 ;; Cursor keys with modifiers
12074 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
12075 (org-defkey org-mode-map [(meta right)] 'org-metaright)
12076 (org-defkey org-mode-map [(meta up)] 'org-metaup)
12077 (org-defkey org-mode-map [(meta down)] 'org-metadown)
12079 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
12080 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
12081 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
12082 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
12084 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
12085 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
12086 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
12087 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
12089 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
12090 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
12092 ;;; Extra keys for tty access.
12093 ;; We only set them when really needed because otherwise the
12094 ;; menus don't show the simple keys
12096 (when (or org-use-extra-keys
12097 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
12098 (not window-system))
12099 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
12100 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
12101 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
12102 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
12103 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
12104 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
12105 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
12106 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
12107 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
12108 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
12109 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
12110 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
12111 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
12112 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
12113 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
12114 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
12115 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
12116 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
12117 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
12118 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
12119 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
12120 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
12122 ;; All the other keys
12124 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
12125 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
12126 (if (boundp 'narrow-map)
12127 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
12128 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
12129 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
12130 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
12131 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
12132 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
12133 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
12134 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
12135 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
12136 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
12137 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
12138 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
12139 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
12140 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
12141 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
12142 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
12143 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
12144 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
12145 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
12146 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
12147 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
12148 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
12149 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
12150 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
12151 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
12152 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
12153 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
12154 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
12155 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
12156 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
12157 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
12158 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
12159 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
12160 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
12161 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
12162 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
12163 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
12164 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
12165 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
12166 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
12167 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
12168 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
12169 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
12170 (org-defkey org-mode-map "\C-c^" 'org-sort)
12171 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
12172 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
12173 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
12174 (org-defkey org-mode-map "\C-m" 'org-return)
12175 (org-defkey org-mode-map "\C-j" 'org-return-indent)
12176 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
12177 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
12178 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
12179 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
12180 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
12181 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
12182 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
12183 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
12184 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
12185 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
12186 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
12187 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
12188 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
12189 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
12190 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
12192 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
12193 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
12194 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
12195 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
12197 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
12198 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
12199 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
12200 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
12201 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
12202 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
12203 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
12204 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
12205 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
12206 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
12207 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
12208 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
12210 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
12212 (when (featurep 'xemacs)
12213 (org-defkey org-mode-map 'button3 'popup-mode-menu))
12215 (defvar org-table-auto-blank-field) ; defined in org-table.el
12216 (defun org-self-insert-command (N)
12217 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
12218 If the cursor is in a table looking at whitespace, the whitespace is
12219 overwritten, and the table is not marked as requiring realignment."
12220 (interactive "p")
12221 (if (and (org-table-p)
12222 (progn
12223 ;; check if we blank the field, and if that triggers align
12224 (and (featurep 'org-table) org-table-auto-blank-field
12225 (member last-command
12226 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
12227 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
12228 ;; got extra space, this field does not determine column width
12229 (let (org-table-may-need-update) (org-table-blank-field))
12230 ;; no extra space, this field may determine column width
12231 (org-table-blank-field)))
12233 (eq N 1)
12234 (looking-at "[^|\n]* |"))
12235 (let (org-table-may-need-update)
12236 (goto-char (1- (match-end 0)))
12237 (delete-backward-char 1)
12238 (goto-char (match-beginning 0))
12239 (self-insert-command N))
12240 (setq org-table-may-need-update t)
12241 (self-insert-command N)
12242 (org-fix-tags-on-the-fly)))
12244 (defun org-fix-tags-on-the-fly ()
12245 (when (and (equal (char-after (point-at-bol)) ?*)
12246 (org-on-heading-p))
12247 (org-align-tags-here org-tags-column)))
12249 (defun org-delete-backward-char (N)
12250 "Like `delete-backward-char', insert whitespace at field end in tables.
12251 When deleting backwards, in tables this function will insert whitespace in
12252 front of the next \"|\" separator, to keep the table aligned. The table will
12253 still be marked for re-alignment if the field did fill the entire column,
12254 because, in this case the deletion might narrow the column."
12255 (interactive "p")
12256 (if (and (org-table-p)
12257 (eq N 1)
12258 (string-match "|" (buffer-substring (point-at-bol) (point)))
12259 (looking-at ".*?|"))
12260 (let ((pos (point))
12261 (noalign (looking-at "[^|\n\r]* |"))
12262 (c org-table-may-need-update))
12263 (backward-delete-char N)
12264 (skip-chars-forward "^|")
12265 (insert " ")
12266 (goto-char (1- pos))
12267 ;; noalign: if there were two spaces at the end, this field
12268 ;; does not determine the width of the column.
12269 (if noalign (setq org-table-may-need-update c)))
12270 (backward-delete-char N)
12271 (org-fix-tags-on-the-fly)))
12273 (defun org-delete-char (N)
12274 "Like `delete-char', but insert whitespace at field end in tables.
12275 When deleting characters, in tables this function will insert whitespace in
12276 front of the next \"|\" separator, to keep the table aligned. The table will
12277 still be marked for re-alignment if the field did fill the entire column,
12278 because, in this case the deletion might narrow the column."
12279 (interactive "p")
12280 (if (and (org-table-p)
12281 (not (bolp))
12282 (not (= (char-after) ?|))
12283 (eq N 1))
12284 (if (looking-at ".*?|")
12285 (let ((pos (point))
12286 (noalign (looking-at "[^|\n\r]* |"))
12287 (c org-table-may-need-update))
12288 (replace-match (concat
12289 (substring (match-string 0) 1 -1)
12290 " |"))
12291 (goto-char pos)
12292 ;; noalign: if there were two spaces at the end, this field
12293 ;; does not determine the width of the column.
12294 (if noalign (setq org-table-may-need-update c)))
12295 (delete-char N))
12296 (delete-char N)
12297 (org-fix-tags-on-the-fly)))
12299 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
12300 (put 'org-self-insert-command 'delete-selection t)
12301 (put 'orgtbl-self-insert-command 'delete-selection t)
12302 (put 'org-delete-char 'delete-selection 'supersede)
12303 (put 'org-delete-backward-char 'delete-selection 'supersede)
12305 ;; Make `flyspell-mode' delay after some commands
12306 (put 'org-self-insert-command 'flyspell-delayed t)
12307 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
12308 (put 'org-delete-char 'flyspell-delayed t)
12309 (put 'org-delete-backward-char 'flyspell-delayed t)
12311 ;; Make pabbrev-mode expand after org-mode commands
12312 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
12313 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
12315 ;; How to do this: Measure non-white length of current string
12316 ;; If equal to column width, we should realign.
12318 (defun org-remap (map &rest commands)
12319 "In MAP, remap the functions given in COMMANDS.
12320 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
12321 (let (new old)
12322 (while commands
12323 (setq old (pop commands) new (pop commands))
12324 (if (fboundp 'command-remapping)
12325 (org-defkey map (vector 'remap old) new)
12326 (substitute-key-definition old new map global-map)))))
12328 (when (eq org-enable-table-editor 'optimized)
12329 ;; If the user wants maximum table support, we need to hijack
12330 ;; some standard editing functions
12331 (org-remap org-mode-map
12332 'self-insert-command 'org-self-insert-command
12333 'delete-char 'org-delete-char
12334 'delete-backward-char 'org-delete-backward-char)
12335 (org-defkey org-mode-map "|" 'org-force-self-insert))
12337 (defun org-shiftcursor-error ()
12338 "Throw an error because Shift-Cursor command was applied in wrong context."
12339 (error "This command is active in special context like tables, headlines or timestamps"))
12341 (defun org-shifttab (&optional arg)
12342 "Global visibility cycling or move to previous table field.
12343 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
12344 on context.
12345 See the individual commands for more information."
12346 (interactive "P")
12347 (cond
12348 ((org-at-table-p) (call-interactively 'org-table-previous-field))
12349 ((integerp arg)
12350 (message "Content view to level: %d" arg)
12351 (org-content (prefix-numeric-value arg))
12352 (setq org-cycle-global-status 'overview))
12353 (t (call-interactively 'org-global-cycle))))
12355 (defun org-shiftmetaleft ()
12356 "Promote subtree or delete table column.
12357 Calls `org-promote-subtree', `org-outdent-item',
12358 or `org-table-delete-column', depending on context.
12359 See the individual commands for more information."
12360 (interactive)
12361 (cond
12362 ((org-at-table-p) (call-interactively 'org-table-delete-column))
12363 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
12364 ((org-at-item-p) (call-interactively 'org-outdent-item))
12365 (t (org-shiftcursor-error))))
12367 (defun org-shiftmetaright ()
12368 "Demote subtree or insert table column.
12369 Calls `org-demote-subtree', `org-indent-item',
12370 or `org-table-insert-column', depending on context.
12371 See the individual commands for more information."
12372 (interactive)
12373 (cond
12374 ((org-at-table-p) (call-interactively 'org-table-insert-column))
12375 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
12376 ((org-at-item-p) (call-interactively 'org-indent-item))
12377 (t (org-shiftcursor-error))))
12379 (defun org-shiftmetaup (&optional arg)
12380 "Move subtree up or kill table row.
12381 Calls `org-move-subtree-up' or `org-table-kill-row' or
12382 `org-move-item-up' depending on context. See the individual commands
12383 for more information."
12384 (interactive "P")
12385 (cond
12386 ((org-at-table-p) (call-interactively 'org-table-kill-row))
12387 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12388 ((org-at-item-p) (call-interactively 'org-move-item-up))
12389 (t (org-shiftcursor-error))))
12390 (defun org-shiftmetadown (&optional arg)
12391 "Move subtree down or insert table row.
12392 Calls `org-move-subtree-down' or `org-table-insert-row' or
12393 `org-move-item-down', depending on context. See the individual
12394 commands for more information."
12395 (interactive "P")
12396 (cond
12397 ((org-at-table-p) (call-interactively 'org-table-insert-row))
12398 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12399 ((org-at-item-p) (call-interactively 'org-move-item-down))
12400 (t (org-shiftcursor-error))))
12402 (defun org-metaleft (&optional arg)
12403 "Promote heading or move table column to left.
12404 Calls `org-do-promote' or `org-table-move-column', depending on context.
12405 With no specific context, calls the Emacs default `backward-word'.
12406 See the individual commands for more information."
12407 (interactive "P")
12408 (cond
12409 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
12410 ((or (org-on-heading-p) (org-region-active-p))
12411 (call-interactively 'org-do-promote))
12412 ((org-at-item-p) (call-interactively 'org-outdent-item))
12413 (t (call-interactively 'backward-word))))
12415 (defun org-metaright (&optional arg)
12416 "Demote subtree or move table column to right.
12417 Calls `org-do-demote' or `org-table-move-column', depending on context.
12418 With no specific context, calls the Emacs default `forward-word'.
12419 See the individual commands for more information."
12420 (interactive "P")
12421 (cond
12422 ((org-at-table-p) (call-interactively 'org-table-move-column))
12423 ((or (org-on-heading-p) (org-region-active-p))
12424 (call-interactively 'org-do-demote))
12425 ((org-at-item-p) (call-interactively 'org-indent-item))
12426 (t (call-interactively 'forward-word))))
12428 (defun org-metaup (&optional arg)
12429 "Move subtree up or move table row up.
12430 Calls `org-move-subtree-up' or `org-table-move-row' or
12431 `org-move-item-up', depending on context. See the individual commands
12432 for more information."
12433 (interactive "P")
12434 (cond
12435 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
12436 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12437 ((org-at-item-p) (call-interactively 'org-move-item-up))
12438 (t (transpose-lines 1) (beginning-of-line -1))))
12440 (defun org-metadown (&optional arg)
12441 "Move subtree down or move table row down.
12442 Calls `org-move-subtree-down' or `org-table-move-row' or
12443 `org-move-item-down', depending on context. See the individual
12444 commands for more information."
12445 (interactive "P")
12446 (cond
12447 ((org-at-table-p) (call-interactively 'org-table-move-row))
12448 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12449 ((org-at-item-p) (call-interactively 'org-move-item-down))
12450 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
12452 (defun org-shiftup (&optional arg)
12453 "Increase item in timestamp or increase priority of current headline.
12454 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
12455 depending on context. See the individual commands for more information."
12456 (interactive "P")
12457 (cond
12458 ((org-at-timestamp-p t)
12459 (call-interactively (if org-edit-timestamp-down-means-later
12460 'org-timestamp-down 'org-timestamp-up)))
12461 ((org-on-heading-p) (call-interactively 'org-priority-up))
12462 ((org-at-item-p) (call-interactively 'org-previous-item))
12463 ((org-clocktable-try-shift 'up arg))
12464 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
12466 (defun org-shiftdown (&optional arg)
12467 "Decrease item in timestamp or decrease priority of current headline.
12468 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
12469 depending on context. See the individual commands for more information."
12470 (interactive "P")
12471 (cond
12472 ((org-at-timestamp-p t)
12473 (call-interactively (if org-edit-timestamp-down-means-later
12474 'org-timestamp-up 'org-timestamp-down)))
12475 ((org-on-heading-p) (call-interactively 'org-priority-down))
12476 ((org-clocktable-try-shift 'down arg))
12477 (t (call-interactively 'org-next-item))))
12479 (defun org-shiftright (&optional arg)
12480 "Next TODO keyword or timestamp one day later, depending on context."
12481 (interactive "P")
12482 (cond
12483 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
12484 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
12485 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
12486 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
12487 ((org-clocktable-try-shift 'right arg))
12488 (t (org-shiftcursor-error))))
12490 (defun org-shiftleft (&optional arg)
12491 "Previous TODO keyword or timestamp one day earlier, depending on context."
12492 (interactive "P")
12493 (cond
12494 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
12495 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
12496 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
12497 ((org-at-property-p)
12498 (call-interactively 'org-property-previous-allowed-value))
12499 ((org-clocktable-try-shift 'left arg))
12500 (t (org-shiftcursor-error))))
12502 (defun org-shiftcontrolright ()
12503 "Switch to next TODO set."
12504 (interactive)
12505 (cond
12506 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
12507 (t (org-shiftcursor-error))))
12509 (defun org-shiftcontrolleft ()
12510 "Switch to previous TODO set."
12511 (interactive)
12512 (cond
12513 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
12514 (t (org-shiftcursor-error))))
12516 (defun org-ctrl-c-ret ()
12517 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
12518 (interactive)
12519 (cond
12520 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
12521 (t (call-interactively 'org-insert-heading))))
12523 (defun org-copy-special ()
12524 "Copy region in table or copy current subtree.
12525 Calls `org-table-copy' or `org-copy-subtree', depending on context.
12526 See the individual commands for more information."
12527 (interactive)
12528 (call-interactively
12529 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
12531 (defun org-cut-special ()
12532 "Cut region in table or cut current subtree.
12533 Calls `org-table-copy' or `org-cut-subtree', depending on context.
12534 See the individual commands for more information."
12535 (interactive)
12536 (call-interactively
12537 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
12539 (defun org-paste-special (arg)
12540 "Paste rectangular region into table, or past subtree relative to level.
12541 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
12542 See the individual commands for more information."
12543 (interactive "P")
12544 (if (org-at-table-p)
12545 (org-table-paste-rectangle)
12546 (org-paste-subtree arg)))
12548 (defun org-edit-special ()
12549 "Call a special editor for the stuff at point.
12550 When at a table, call the formula editor with `org-table-edit-formulas'.
12551 When at the first line of an src example, call `org-edit-src-code'.
12552 When in an #+include line, visit the include file. Otherwise call
12553 `ffap' to visit the file at point."
12554 (interactive)
12555 (cond
12556 ((org-at-table-p)
12557 (call-interactively 'org-table-edit-formulas))
12558 ((save-excursion
12559 (beginning-of-line 1)
12560 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
12561 (find-file (org-trim (match-string 1))))
12562 ((org-edit-src-code))
12563 ((org-edit-fixed-width-region))
12564 (t (call-interactively 'ffap))))
12566 (defun org-ctrl-c-ctrl-c (&optional arg)
12567 "Set tags in headline, or update according to changed information at point.
12569 This command does many different things, depending on context:
12571 - If the cursor is in a headline, prompt for tags and insert them
12572 into the current line, aligned to `org-tags-column'. When called
12573 with prefix arg, realign all tags in the current buffer.
12575 - If the cursor is in one of the special #+KEYWORD lines, this
12576 triggers scanning the buffer for these lines and updating the
12577 information.
12579 - If the cursor is inside a table, realign the table. This command
12580 works even if the automatic table editor has been turned off.
12582 - If the cursor is on a #+TBLFM line, re-apply the formulas to
12583 the entire table.
12585 - If the cursor is a the beginning of a dynamic block, update it.
12587 - If the cursor is inside a table created by the table.el package,
12588 activate that table.
12590 - If the current buffer is a remember buffer, close note and file it.
12591 with a prefix argument, file it without further interaction to the default
12592 location.
12594 - If the cursor is on a <<<target>>>, update radio targets and corresponding
12595 links in this buffer.
12597 - If the cursor is on a numbered item in a plain list, renumber the
12598 ordered list.
12600 - If the cursor is on a checkbox, toggle it."
12601 (interactive "P")
12602 (let ((org-enable-table-editor t))
12603 (cond
12604 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
12605 org-occur-highlights
12606 org-latex-fragment-image-overlays)
12607 (and (boundp 'org-clock-overlays) (org-remove-clock-overlays))
12608 (org-remove-occur-highlights)
12609 (org-remove-latex-fragment-image-overlays)
12610 (message "Temporary highlights/overlays removed from current buffer"))
12611 ((and (local-variable-p 'org-finish-function (current-buffer))
12612 (fboundp org-finish-function))
12613 (funcall org-finish-function))
12614 ((org-at-property-p)
12615 (call-interactively 'org-property-action))
12616 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
12617 ((org-on-heading-p) (call-interactively 'org-set-tags))
12618 ((org-at-table.el-p)
12619 (require 'table)
12620 (beginning-of-line 1)
12621 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
12622 (call-interactively 'table-recognize-table))
12623 ((org-at-table-p)
12624 (org-table-maybe-eval-formula)
12625 (if arg
12626 (call-interactively 'org-table-recalculate)
12627 (org-table-maybe-recalculate-line))
12628 (call-interactively 'org-table-align))
12629 ((org-at-item-checkbox-p)
12630 (call-interactively 'org-toggle-checkbox))
12631 ((org-at-item-p)
12632 (call-interactively 'org-maybe-renumber-ordered-list))
12633 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
12634 ;; Dynamic block
12635 (beginning-of-line 1)
12636 (save-excursion (org-update-dblock)))
12637 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
12638 (cond
12639 ((equal (match-string 1) "TBLFM")
12640 ;; Recalculate the table before this line
12641 (save-excursion
12642 (beginning-of-line 1)
12643 (skip-chars-backward " \r\n\t")
12644 (if (org-at-table-p)
12645 (org-call-with-arg 'org-table-recalculate t))))
12647 ; (org-set-regexps-and-options)
12648 ; (org-restart-font-lock)
12649 (let ((org-inhibit-startup t)) (org-mode-restart))
12650 (message "Local setup has been refreshed"))))
12651 (t (error "C-c C-c can do nothing useful at this location.")))))
12653 (defun org-mode-restart ()
12654 "Restart Org-mode, to scan again for special lines.
12655 Also updates the keyword regular expressions."
12656 (interactive)
12657 (org-mode)
12658 (message "Org-mode restarted"))
12660 (defun org-kill-note-or-show-branches ()
12661 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
12662 (interactive)
12663 (if (not org-finish-function)
12664 (call-interactively 'show-branches)
12665 (let ((org-note-abort t))
12666 (funcall org-finish-function))))
12668 (defun org-return (&optional indent)
12669 "Goto next table row or insert a newline.
12670 Calls `org-table-next-row' or `newline', depending on context.
12671 See the individual commands for more information."
12672 (interactive)
12673 (cond
12674 ((bobp) (if indent (newline-and-indent) (newline)))
12675 ((and (org-at-heading-p)
12676 (looking-at
12677 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
12678 (org-show-entry)
12679 (end-of-line 1)
12680 (newline))
12681 ((org-at-table-p)
12682 (org-table-justify-field-maybe)
12683 (call-interactively 'org-table-next-row))
12684 (t (if indent (newline-and-indent) (newline)))))
12686 (defun org-return-indent ()
12687 "Goto next table row or insert a newline and indent.
12688 Calls `org-table-next-row' or `newline-and-indent', depending on
12689 context. See the individual commands for more information."
12690 (interactive)
12691 (org-return t))
12693 (defun org-ctrl-c-star ()
12694 "Compute table, or change heading status of lines.
12695 Calls `org-table-recalculate' or `org-toggle-region-headings',
12696 depending on context. This will also turn a plain list item or a normal
12697 line into a subheading."
12698 (interactive)
12699 (cond
12700 ((org-at-table-p)
12701 (call-interactively 'org-table-recalculate))
12702 ((org-region-active-p)
12703 ;; Convert all lines in region to list items
12704 (call-interactively 'org-toggle-region-headings))
12705 ((org-on-heading-p)
12706 (org-toggle-region-headings (point-at-bol)
12707 (min (1+ (point-at-eol)) (point-max))))
12708 ((org-at-item-p)
12709 ;; Convert to heading
12710 (let ((level (save-match-data
12711 (save-excursion
12712 (condition-case nil
12713 (progn
12714 (org-back-to-heading t)
12715 (funcall outline-level))
12716 (error 0))))))
12717 (replace-match
12718 (concat (make-string (org-get-valid-level level 1) ?*) " ") t t)))
12719 (t (org-toggle-region-headings (point-at-bol)
12720 (min (1+ (point-at-eol)) (point-max))))))
12722 (defun org-ctrl-c-minus ()
12723 "Insert separator line in table or modify bullet status of line.
12724 Also turns a plain line or a region of lines into list items.
12725 Calls `org-table-insert-hline', `org-toggle-region-items', or
12726 `org-cycle-list-bullet', depending on context."
12727 (interactive)
12728 (cond
12729 ((org-at-table-p)
12730 (call-interactively 'org-table-insert-hline))
12731 ((org-on-heading-p)
12732 ;; Convert to item
12733 (save-excursion
12734 (beginning-of-line 1)
12735 (if (looking-at "\\*+ ")
12736 (replace-match (concat (make-string (- (match-end 0) (point) 1) ?\ ) "- ")))))
12737 ((org-region-active-p)
12738 ;; Convert all lines in region to list items
12739 (call-interactively 'org-toggle-region-items))
12740 ((org-in-item-p)
12741 (call-interactively 'org-cycle-list-bullet))
12742 (t (org-toggle-region-items (point-at-bol)
12743 (min (1+ (point-at-eol)) (point-max))))))
12745 (defun org-toggle-region-items (beg end)
12746 "Convert all lines in region to list items.
12747 If the first line is already an item, convert all list items in the region
12748 to normal lines."
12749 (interactive "r")
12750 (let (l2 l)
12751 (save-excursion
12752 (goto-char end)
12753 (setq l2 (org-current-line))
12754 (goto-char beg)
12755 (beginning-of-line 1)
12756 (setq l (1- (org-current-line)))
12757 (if (org-at-item-p)
12758 ;; We already have items, de-itemize
12759 (while (< (setq l (1+ l)) l2)
12760 (when (org-at-item-p)
12761 (goto-char (match-beginning 2))
12762 (delete-region (match-beginning 2) (match-end 2))
12763 (and (looking-at "[ \t]+") (replace-match "")))
12764 (beginning-of-line 2))
12765 (while (< (setq l (1+ l)) l2)
12766 (unless (org-at-item-p)
12767 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
12768 (replace-match "\\1- \\2")))
12769 (beginning-of-line 2))))))
12771 (defun org-toggle-region-headings (beg end)
12772 "Convert all lines in region to list items.
12773 If the first line is already an item, convert all list items in the region
12774 to normal lines."
12775 (interactive "r")
12776 (let (l2 l)
12777 (save-excursion
12778 (goto-char end)
12779 (setq l2 (org-current-line))
12780 (goto-char beg)
12781 (beginning-of-line 1)
12782 (setq l (1- (org-current-line)))
12783 (if (org-on-heading-p)
12784 ;; We already have headlines, de-star them
12785 (while (< (setq l (1+ l)) l2)
12786 (when (org-on-heading-p t)
12787 (and (looking-at outline-regexp) (replace-match "")))
12788 (beginning-of-line 2))
12789 (let* ((stars (save-excursion
12790 (re-search-backward org-complex-heading-regexp nil t)
12791 (or (match-string 1) "*")))
12792 (add-stars (if org-odd-levels-only "**" "*"))
12793 (rpl (concat stars add-stars " \\2")))
12794 (while (< (setq l (1+ l)) l2)
12795 (unless (org-on-heading-p)
12796 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
12797 (replace-match rpl)))
12798 (beginning-of-line 2)))))))
12800 (defun org-meta-return (&optional arg)
12801 "Insert a new heading or wrap a region in a table.
12802 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
12803 See the individual commands for more information."
12804 (interactive "P")
12805 (cond
12806 ((org-at-table-p)
12807 (call-interactively 'org-table-wrap-region))
12808 (t (call-interactively 'org-insert-heading))))
12810 ;;; Menu entries
12812 ;; Define the Org-mode menus
12813 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
12814 '("Tbl"
12815 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
12816 ["Next Field" org-cycle (org-at-table-p)]
12817 ["Previous Field" org-shifttab (org-at-table-p)]
12818 ["Next Row" org-return (org-at-table-p)]
12819 "--"
12820 ["Blank Field" org-table-blank-field (org-at-table-p)]
12821 ["Edit Field" org-table-edit-field (org-at-table-p)]
12822 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
12823 "--"
12824 ("Column"
12825 ["Move Column Left" org-metaleft (org-at-table-p)]
12826 ["Move Column Right" org-metaright (org-at-table-p)]
12827 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
12828 ["Insert Column" org-shiftmetaright (org-at-table-p)])
12829 ("Row"
12830 ["Move Row Up" org-metaup (org-at-table-p)]
12831 ["Move Row Down" org-metadown (org-at-table-p)]
12832 ["Delete Row" org-shiftmetaup (org-at-table-p)]
12833 ["Insert Row" org-shiftmetadown (org-at-table-p)]
12834 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
12835 "--"
12836 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
12837 ("Rectangle"
12838 ["Copy Rectangle" org-copy-special (org-at-table-p)]
12839 ["Cut Rectangle" org-cut-special (org-at-table-p)]
12840 ["Paste Rectangle" org-paste-special (org-at-table-p)]
12841 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
12842 "--"
12843 ("Calculate"
12844 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
12845 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
12846 ["Edit Formulas" org-edit-special (org-at-table-p)]
12847 "--"
12848 ["Recalculate line" org-table-recalculate (org-at-table-p)]
12849 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
12850 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
12851 "--"
12852 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
12853 "--"
12854 ["Sum Column/Rectangle" org-table-sum
12855 (or (org-at-table-p) (org-region-active-p))]
12856 ["Which Column?" org-table-current-column (org-at-table-p)])
12857 ["Debug Formulas"
12858 org-table-toggle-formula-debugger
12859 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
12860 ["Show Col/Row Numbers"
12861 org-table-toggle-coordinate-overlays
12862 :style toggle
12863 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
12864 "--"
12865 ["Create" org-table-create (and (not (org-at-table-p))
12866 org-enable-table-editor)]
12867 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
12868 ["Import from File" org-table-import (not (org-at-table-p))]
12869 ["Export to File" org-table-export (org-at-table-p)]
12870 "--"
12871 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
12873 (easy-menu-define org-org-menu org-mode-map "Org menu"
12874 '("Org"
12875 ("Show/Hide"
12876 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
12877 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
12878 ["Sparse Tree..." org-sparse-tree t]
12879 ["Reveal Context" org-reveal t]
12880 ["Show All" show-all t]
12881 "--"
12882 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
12883 "--"
12884 ["New Heading" org-insert-heading t]
12885 ("Navigate Headings"
12886 ["Up" outline-up-heading t]
12887 ["Next" outline-next-visible-heading t]
12888 ["Previous" outline-previous-visible-heading t]
12889 ["Next Same Level" outline-forward-same-level t]
12890 ["Previous Same Level" outline-backward-same-level t]
12891 "--"
12892 ["Jump" org-goto t])
12893 ("Edit Structure"
12894 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
12895 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
12896 "--"
12897 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
12898 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
12899 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
12900 "--"
12901 ["Promote Heading" org-metaleft (not (org-at-table-p))]
12902 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
12903 ["Demote Heading" org-metaright (not (org-at-table-p))]
12904 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
12905 "--"
12906 ["Sort Region/Children" org-sort (not (org-at-table-p))]
12907 "--"
12908 ["Convert to odd levels" org-convert-to-odd-levels t]
12909 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
12910 ("Editing"
12911 ["Emphasis..." org-emphasize t]
12912 ["Edit Source Example" org-edit-special t])
12913 ("Archive"
12914 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
12915 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
12916 ; :active t :keys "C-u C-c C-x C-a"]
12917 ["Sparse trees open ARCHIVE trees"
12918 (setq org-sparse-tree-open-archived-trees
12919 (not org-sparse-tree-open-archived-trees))
12920 :style toggle :selected org-sparse-tree-open-archived-trees]
12921 ["Cycling opens ARCHIVE trees"
12922 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
12923 :style toggle :selected org-cycle-open-archived-trees]
12924 "--"
12925 ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
12926 ["Move Subtree to Archive" org-advertized-archive-subtree t]
12927 ; ["Check and Move Children" (org-archive-subtree '(4))
12928 ; :active t :keys "C-u C-c C-x C-s"]
12930 "--"
12931 ("TODO Lists"
12932 ["TODO/DONE/-" org-todo t]
12933 ("Select keyword"
12934 ["Next keyword" org-shiftright (org-on-heading-p)]
12935 ["Previous keyword" org-shiftleft (org-on-heading-p)]
12936 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
12937 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
12938 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
12939 ["Show TODO Tree" org-show-todo-tree t]
12940 ["Global TODO list" org-todo-list t]
12941 "--"
12942 ["Set Priority" org-priority t]
12943 ["Priority Up" org-shiftup t]
12944 ["Priority Down" org-shiftdown t])
12945 ("TAGS and Properties"
12946 ["Set Tags" 'org-set-tags-command t]
12947 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
12948 "--"
12949 ["Set property" 'org-set-property t]
12950 ["Column view of properties" org-columns t]
12951 ["Insert Column View DBlock" org-insert-columns-dblock t])
12952 ("Dates and Scheduling"
12953 ["Timestamp" org-time-stamp t]
12954 ["Timestamp (inactive)" org-time-stamp-inactive t]
12955 ("Change Date"
12956 ["1 Day Later" org-shiftright t]
12957 ["1 Day Earlier" org-shiftleft t]
12958 ["1 ... Later" org-shiftup t]
12959 ["1 ... Earlier" org-shiftdown t])
12960 ["Compute Time Range" org-evaluate-time-range t]
12961 ["Schedule Item" org-schedule t]
12962 ["Deadline" org-deadline t]
12963 "--"
12964 ["Custom time format" org-toggle-time-stamp-overlays
12965 :style radio :selected org-display-custom-times]
12966 "--"
12967 ["Goto Calendar" org-goto-calendar t]
12968 ["Date from Calendar" org-date-from-calendar t])
12969 ("Logging work"
12970 ["Clock in" org-clock-in t]
12971 ["Clock out" org-clock-out t]
12972 ["Clock cancel" org-clock-cancel t]
12973 ["Goto running clock" org-clock-goto t]
12974 ["Display times" org-clock-display t]
12975 ["Create clock table" org-clock-report t]
12976 "--"
12977 ["Record DONE time"
12978 (progn (setq org-log-done (not org-log-done))
12979 (message "Switching to %s will %s record a timestamp"
12980 (car org-done-keywords)
12981 (if org-log-done "automatically" "not")))
12982 :style toggle :selected org-log-done])
12983 "--"
12984 ["Agenda Command..." org-agenda t]
12985 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
12986 ("File List for Agenda")
12987 ("Special views current file"
12988 ["TODO Tree" org-show-todo-tree t]
12989 ["Check Deadlines" org-check-deadlines t]
12990 ["Timeline" org-timeline t]
12991 ["Tags Tree" org-tags-sparse-tree t])
12992 "--"
12993 ("Hyperlinks"
12994 ["Store Link (Global)" org-store-link t]
12995 ["Insert Link" org-insert-link t]
12996 ["Follow Link" org-open-at-point t]
12997 "--"
12998 ["Next link" org-next-link t]
12999 ["Previous link" org-previous-link t]
13000 "--"
13001 ["Descriptive Links"
13002 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
13003 :style radio
13004 :selected (member '(org-link) buffer-invisibility-spec)]
13005 ["Literal Links"
13006 (progn
13007 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
13008 :style radio
13009 :selected (not (member '(org-link) buffer-invisibility-spec))])
13010 "--"
13011 ["Export/Publish..." org-export t]
13012 ("LaTeX"
13013 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
13014 :selected org-cdlatex-mode]
13015 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
13016 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
13017 ["Modify math symbol" org-cdlatex-math-modify
13018 (org-inside-LaTeX-fragment-p)]
13019 ["Export LaTeX fragments as images"
13020 (if (featurep 'org-exp)
13021 (setq org-export-with-LaTeX-fragments
13022 (not org-export-with-LaTeX-fragments))
13023 (require 'org-exp))
13024 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
13025 org-export-with-LaTeX-fragments)])
13026 "--"
13027 ("Documentation"
13028 ["Show Version" org-version t]
13029 ["Info Documentation" org-info t])
13030 ("Customize"
13031 ["Browse Org Group" org-customize t]
13032 "--"
13033 ["Expand This Menu" org-create-customize-menu
13034 (fboundp 'customize-menu-create)])
13035 "--"
13036 ["Refresh setup" org-mode-restart t]
13039 (defun org-info (&optional node)
13040 "Read documentation for Org-mode in the info system.
13041 With optional NODE, go directly to that node."
13042 (interactive)
13043 (info (format "(org)%s" (or node ""))))
13045 (defun org-install-agenda-files-menu ()
13046 (let ((bl (buffer-list)))
13047 (save-excursion
13048 (while bl
13049 (set-buffer (pop bl))
13050 (if (org-mode-p) (setq bl nil)))
13051 (when (org-mode-p)
13052 (easy-menu-change
13053 '("Org") "File List for Agenda"
13054 (append
13055 (list
13056 ["Edit File List" (org-edit-agenda-file-list) t]
13057 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
13058 ["Remove Current File from List" org-remove-file t]
13059 ["Cycle through agenda files" org-cycle-agenda-files t]
13060 ["Occur in all agenda files" org-occur-in-agenda-files t]
13061 "--")
13062 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
13064 ;;;; Documentation
13066 ;;;###autoload
13067 (defun org-require-autoloaded-modules ()
13068 (interactive)
13069 (mapc 'require
13070 '(org-agenda org-archive org-clock org-colview
13071 org-exp org-id org-export-latex org-publish
13072 org-remember org-table)))
13074 ;;;###autoload
13075 (defun org-customize ()
13076 "Call the customize function with org as argument."
13077 (interactive)
13078 (org-load-modules-maybe)
13079 (org-require-autoloaded-modules)
13080 (customize-browse 'org))
13082 (defun org-create-customize-menu ()
13083 "Create a full customization menu for Org-mode, insert it into the menu."
13084 (interactive)
13085 (org-load-modules-maybe)
13086 (org-require-autoloaded-modules)
13087 (if (fboundp 'customize-menu-create)
13088 (progn
13089 (easy-menu-change
13090 '("Org") "Customize"
13091 `(["Browse Org group" org-customize t]
13092 "--"
13093 ,(customize-menu-create 'org)
13094 ["Set" Custom-set t]
13095 ["Save" Custom-save t]
13096 ["Reset to Current" Custom-reset-current t]
13097 ["Reset to Saved" Custom-reset-saved t]
13098 ["Reset to Standard Settings" Custom-reset-standard t]))
13099 (message "\"Org\"-menu now contains full customization menu"))
13100 (error "Cannot expand menu (outdated version of cus-edit.el)")))
13102 ;;;; Miscellaneous stuff
13104 ;;; Generally useful functions
13106 (defun org-display-warning (message) ;; Copied from Emacs-Muse
13107 "Display the given MESSAGE as a warning."
13108 (if (fboundp 'display-warning)
13109 (display-warning 'org message
13110 (if (featurep 'xemacs)
13111 'warning
13112 :warning))
13113 (let ((buf (get-buffer-create "*Org warnings*")))
13114 (with-current-buffer buf
13115 (goto-char (point-max))
13116 (insert "Warning (Org): " message)
13117 (unless (bolp)
13118 (newline)))
13119 (display-buffer buf)
13120 (sit-for 0))))
13122 (defun org-goto-marker-or-bmk (marker &optional bookmark)
13123 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
13124 (if (and marker (marker-buffer marker)
13125 (buffer-live-p (marker-buffer marker)))
13126 (progn
13127 (switch-to-buffer (marker-buffer marker))
13128 (if (or (> marker (point-max)) (< marker (point-min)))
13129 (widen))
13130 (goto-char marker))
13131 (if bookmark
13132 (bookmark-jump bookmark)
13133 (error "Cannot find location"))))
13135 (defun org-quote-csv-field (s)
13136 "Quote field for inclusion in CSV material."
13137 (if (string-match "[\",]" s)
13138 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
13141 (defun org-plist-delete (plist property)
13142 "Delete PROPERTY from PLIST.
13143 This is in contrast to merely setting it to 0."
13144 (let (p)
13145 (while plist
13146 (if (not (eq property (car plist)))
13147 (setq p (plist-put p (car plist) (nth 1 plist))))
13148 (setq plist (cddr plist)))
13151 (defun org-force-self-insert (N)
13152 "Needed to enforce self-insert under remapping."
13153 (interactive "p")
13154 (self-insert-command N))
13156 (defun org-string-width (s)
13157 "Compute width of string, ignoring invisible characters.
13158 This ignores character with invisibility property `org-link', and also
13159 characters with property `org-cwidth', because these will become invisible
13160 upon the next fontification round."
13161 (let (b l)
13162 (when (or (eq t buffer-invisibility-spec)
13163 (assq 'org-link buffer-invisibility-spec))
13164 (while (setq b (text-property-any 0 (length s)
13165 'invisible 'org-link s))
13166 (setq s (concat (substring s 0 b)
13167 (substring s (or (next-single-property-change
13168 b 'invisible s) (length s)))))))
13169 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
13170 (setq s (concat (substring s 0 b)
13171 (substring s (or (next-single-property-change
13172 b 'org-cwidth s) (length s))))))
13173 (setq l (string-width s) b -1)
13174 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
13175 (setq l (- l (get-text-property b 'org-dwidth-n s))))
13178 (defun org-get-indentation (&optional line)
13179 "Get the indentation of the current line, interpreting tabs.
13180 When LINE is given, assume it represents a line and compute its indentation."
13181 (if line
13182 (if (string-match "^ *" (org-remove-tabs line))
13183 (match-end 0))
13184 (save-excursion
13185 (beginning-of-line 1)
13186 (skip-chars-forward " \t")
13187 (current-column))))
13189 (defun org-remove-tabs (s &optional width)
13190 "Replace tabulators in S with spaces.
13191 Assumes that s is a single line, starting in column 0."
13192 (setq width (or width tab-width))
13193 (while (string-match "\t" s)
13194 (setq s (replace-match
13195 (make-string
13196 (- (* width (/ (+ (match-beginning 0) width) width))
13197 (match-beginning 0)) ?\ )
13198 t t s)))
13201 (defun org-fix-indentation (line ind)
13202 "Fix indentation in LINE.
13203 IND is a cons cell with target and minimum indentation.
13204 If the current indenation in LINE is smaller than the minimum,
13205 leave it alone. If it is larger than ind, set it to the target."
13206 (let* ((l (org-remove-tabs line))
13207 (i (org-get-indentation l))
13208 (i1 (car ind)) (i2 (cdr ind)))
13209 (if (>= i i2) (setq l (substring line i2)))
13210 (if (> i1 0)
13211 (concat (make-string i1 ?\ ) l)
13212 l)))
13214 (defun org-base-buffer (buffer)
13215 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
13216 (if (not buffer)
13217 buffer
13218 (or (buffer-base-buffer buffer)
13219 buffer)))
13221 (defun org-trim (s)
13222 "Remove whitespace at beginning and end of string."
13223 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
13224 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
13227 (defun org-wrap (string &optional width lines)
13228 "Wrap string to either a number of lines, or a width in characters.
13229 If WIDTH is non-nil, the string is wrapped to that width, however many lines
13230 that costs. If there is a word longer than WIDTH, the text is actually
13231 wrapped to the length of that word.
13232 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
13233 many lines, whatever width that takes.
13234 The return value is a list of lines, without newlines at the end."
13235 (let* ((words (org-split-string string "[ \t\n]+"))
13236 (maxword (apply 'max (mapcar 'org-string-width words)))
13237 w ll)
13238 (cond (width
13239 (org-do-wrap words (max maxword width)))
13240 (lines
13241 (setq w maxword)
13242 (setq ll (org-do-wrap words maxword))
13243 (if (<= (length ll) lines)
13245 (setq ll words)
13246 (while (> (length ll) lines)
13247 (setq w (1+ w))
13248 (setq ll (org-do-wrap words w)))
13249 ll))
13250 (t (error "Cannot wrap this")))))
13252 (defun org-do-wrap (words width)
13253 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
13254 (let (lines line)
13255 (while words
13256 (setq line (pop words))
13257 (while (and words (< (+ (length line) (length (car words))) width))
13258 (setq line (concat line " " (pop words))))
13259 (setq lines (push line lines)))
13260 (nreverse lines)))
13262 (defun org-split-string (string &optional separators)
13263 "Splits STRING into substrings at SEPARATORS.
13264 No empty strings are returned if there are matches at the beginning
13265 and end of string."
13266 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
13267 (start 0)
13268 notfirst
13269 (list nil))
13270 (while (and (string-match rexp string
13271 (if (and notfirst
13272 (= start (match-beginning 0))
13273 (< start (length string)))
13274 (1+ start) start))
13275 (< (match-beginning 0) (length string)))
13276 (setq notfirst t)
13277 (or (eq (match-beginning 0) 0)
13278 (and (eq (match-beginning 0) (match-end 0))
13279 (eq (match-beginning 0) start))
13280 (setq list
13281 (cons (substring string start (match-beginning 0))
13282 list)))
13283 (setq start (match-end 0)))
13284 (or (eq start (length string))
13285 (setq list
13286 (cons (substring string start)
13287 list)))
13288 (nreverse list)))
13290 (defun org-context ()
13291 "Return a list of contexts of the current cursor position.
13292 If several contexts apply, all are returned.
13293 Each context entry is a list with a symbol naming the context, and
13294 two positions indicating start and end of the context. Possible
13295 contexts are:
13297 :headline anywhere in a headline
13298 :headline-stars on the leading stars in a headline
13299 :todo-keyword on a TODO keyword (including DONE) in a headline
13300 :tags on the TAGS in a headline
13301 :priority on the priority cookie in a headline
13302 :item on the first line of a plain list item
13303 :item-bullet on the bullet/number of a plain list item
13304 :checkbox on the checkbox in a plain list item
13305 :table in an org-mode table
13306 :table-special on a special filed in a table
13307 :table-table in a table.el table
13308 :link on a hyperlink
13309 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
13310 :target on a <<target>>
13311 :radio-target on a <<<radio-target>>>
13312 :latex-fragment on a LaTeX fragment
13313 :latex-preview on a LaTeX fragment with overlayed preview image
13315 This function expects the position to be visible because it uses font-lock
13316 faces as a help to recognize the following contexts: :table-special, :link,
13317 and :keyword."
13318 (let* ((f (get-text-property (point) 'face))
13319 (faces (if (listp f) f (list f)))
13320 (p (point)) clist o)
13321 ;; First the large context
13322 (cond
13323 ((org-on-heading-p t)
13324 (push (list :headline (point-at-bol) (point-at-eol)) clist)
13325 (when (progn
13326 (beginning-of-line 1)
13327 (looking-at org-todo-line-tags-regexp))
13328 (push (org-point-in-group p 1 :headline-stars) clist)
13329 (push (org-point-in-group p 2 :todo-keyword) clist)
13330 (push (org-point-in-group p 4 :tags) clist))
13331 (goto-char p)
13332 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
13333 (if (looking-at "\\[#[A-Z0-9]\\]")
13334 (push (org-point-in-group p 0 :priority) clist)))
13336 ((org-at-item-p)
13337 (push (org-point-in-group p 2 :item-bullet) clist)
13338 (push (list :item (point-at-bol)
13339 (save-excursion (org-end-of-item) (point)))
13340 clist)
13341 (and (org-at-item-checkbox-p)
13342 (push (org-point-in-group p 0 :checkbox) clist)))
13344 ((org-at-table-p)
13345 (push (list :table (org-table-begin) (org-table-end)) clist)
13346 (if (memq 'org-formula faces)
13347 (push (list :table-special
13348 (previous-single-property-change p 'face)
13349 (next-single-property-change p 'face)) clist)))
13350 ((org-at-table-p 'any)
13351 (push (list :table-table) clist)))
13352 (goto-char p)
13354 ;; Now the small context
13355 (cond
13356 ((org-at-timestamp-p)
13357 (push (org-point-in-group p 0 :timestamp) clist))
13358 ((memq 'org-link faces)
13359 (push (list :link
13360 (previous-single-property-change p 'face)
13361 (next-single-property-change p 'face)) clist))
13362 ((memq 'org-special-keyword faces)
13363 (push (list :keyword
13364 (previous-single-property-change p 'face)
13365 (next-single-property-change p 'face)) clist))
13366 ((org-on-target-p)
13367 (push (org-point-in-group p 0 :target) clist)
13368 (goto-char (1- (match-beginning 0)))
13369 (if (looking-at org-radio-target-regexp)
13370 (push (org-point-in-group p 0 :radio-target) clist))
13371 (goto-char p))
13372 ((setq o (car (delq nil
13373 (mapcar
13374 (lambda (x)
13375 (if (memq x org-latex-fragment-image-overlays) x))
13376 (org-overlays-at (point))))))
13377 (push (list :latex-fragment
13378 (org-overlay-start o) (org-overlay-end o)) clist)
13379 (push (list :latex-preview
13380 (org-overlay-start o) (org-overlay-end o)) clist))
13381 ((org-inside-LaTeX-fragment-p)
13382 ;; FIXME: positions wrong.
13383 (push (list :latex-fragment (point) (point)) clist)))
13385 (setq clist (nreverse (delq nil clist)))
13386 clist))
13388 ;; FIXME: Compare with at-regexp-p Do we need both?
13389 (defun org-in-regexp (re &optional nlines visually)
13390 "Check if point is inside a match of regexp.
13391 Normally only the current line is checked, but you can include NLINES extra
13392 lines both before and after point into the search.
13393 If VISUALLY is set, require that the cursor is not after the match but
13394 really on, so that the block visually is on the match."
13395 (catch 'exit
13396 (let ((pos (point))
13397 (eol (point-at-eol (+ 1 (or nlines 0))))
13398 (inc (if visually 1 0)))
13399 (save-excursion
13400 (beginning-of-line (- 1 (or nlines 0)))
13401 (while (re-search-forward re eol t)
13402 (if (and (<= (match-beginning 0) pos)
13403 (>= (+ inc (match-end 0)) pos))
13404 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
13406 (defun org-at-regexp-p (regexp)
13407 "Is point inside a match of REGEXP in the current line?"
13408 (catch 'exit
13409 (save-excursion
13410 (let ((pos (point)) (end (point-at-eol)))
13411 (beginning-of-line 1)
13412 (while (re-search-forward regexp end t)
13413 (if (and (<= (match-beginning 0) pos)
13414 (>= (match-end 0) pos))
13415 (throw 'exit t)))
13416 nil))))
13418 (defun org-occur-in-agenda-files (regexp &optional nlines)
13419 "Call `multi-occur' with buffers for all agenda files."
13420 (interactive "sOrg-files matching: \np")
13421 (let* ((files (org-agenda-files))
13422 (tnames (mapcar 'file-truename files))
13423 (extra org-agenda-text-search-extra-files)
13425 (when (eq (car extra) 'agenda-archives)
13426 (setq extra (cdr extra))
13427 (setq files (org-add-archive-files files)))
13428 (while (setq f (pop extra))
13429 (unless (member (file-truename f) tnames)
13430 (add-to-list 'files f 'append)
13431 (add-to-list 'tnames (file-truename f) 'append)))
13432 (multi-occur
13433 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
13434 regexp)))
13436 (if (boundp 'occur-mode-find-occurrence-hook)
13437 ;; Emacs 23
13438 (add-hook 'occur-mode-find-occurrence-hook
13439 (lambda ()
13440 (when (org-mode-p)
13441 (org-reveal))))
13442 ;; Emacs 22
13443 (defadvice occur-mode-goto-occurrence
13444 (after org-occur-reveal activate)
13445 (and (org-mode-p) (org-reveal)))
13446 (defadvice occur-mode-goto-occurrence-other-window
13447 (after org-occur-reveal activate)
13448 (and (org-mode-p) (org-reveal)))
13449 (defadvice occur-mode-display-occurrence
13450 (after org-occur-reveal activate)
13451 (when (org-mode-p)
13452 (let ((pos (occur-mode-find-occurrence)))
13453 (with-current-buffer (marker-buffer pos)
13454 (save-excursion
13455 (goto-char pos)
13456 (org-reveal)))))))
13458 (defun org-uniquify (list)
13459 "Remove duplicate elements from LIST."
13460 (let (res)
13461 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
13462 res))
13464 (defun org-delete-all (elts list)
13465 "Remove all elements in ELTS from LIST."
13466 (while elts
13467 (setq list (delete (pop elts) list)))
13468 list)
13470 (defun org-back-over-empty-lines ()
13471 "Move backwards over witespace, to the beginning of the first empty line.
13472 Returns the number of empty lines passed."
13473 (let ((pos (point)))
13474 (skip-chars-backward " \t\n\r")
13475 (beginning-of-line 2)
13476 (goto-char (min (point) pos))
13477 (count-lines (point) pos)))
13479 (defun org-skip-whitespace ()
13480 (skip-chars-forward " \t\n\r"))
13482 (defun org-point-in-group (point group &optional context)
13483 "Check if POINT is in match-group GROUP.
13484 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
13485 match. If the match group does ot exist or point is not inside it,
13486 return nil."
13487 (and (match-beginning group)
13488 (>= point (match-beginning group))
13489 (<= point (match-end group))
13490 (if context
13491 (list context (match-beginning group) (match-end group))
13492 t)))
13494 (defun org-switch-to-buffer-other-window (&rest args)
13495 "Switch to buffer in a second window on the current frame.
13496 In particular, do not allow pop-up frames."
13497 (let (pop-up-frames special-display-buffer-names special-display-regexps
13498 special-display-function)
13499 (apply 'switch-to-buffer-other-window args)))
13501 (defun org-combine-plists (&rest plists)
13502 "Create a single property list from all plists in PLISTS.
13503 The process starts by copying the first list, and then setting properties
13504 from the other lists. Settings in the last list are the most significant
13505 ones and overrule settings in the other lists."
13506 (let ((rtn (copy-sequence (pop plists)))
13507 p v ls)
13508 (while plists
13509 (setq ls (pop plists))
13510 (while ls
13511 (setq p (pop ls) v (pop ls))
13512 (setq rtn (plist-put rtn p v))))
13513 rtn))
13515 (defun org-move-line-down (arg)
13516 "Move the current line down. With prefix argument, move it past ARG lines."
13517 (interactive "p")
13518 (let ((col (current-column))
13519 beg end pos)
13520 (beginning-of-line 1) (setq beg (point))
13521 (beginning-of-line 2) (setq end (point))
13522 (beginning-of-line (+ 1 arg))
13523 (setq pos (move-marker (make-marker) (point)))
13524 (insert (delete-and-extract-region beg end))
13525 (goto-char pos)
13526 (org-move-to-column col)))
13528 (defun org-move-line-up (arg)
13529 "Move the current line up. With prefix argument, move it past ARG lines."
13530 (interactive "p")
13531 (let ((col (current-column))
13532 beg end pos)
13533 (beginning-of-line 1) (setq beg (point))
13534 (beginning-of-line 2) (setq end (point))
13535 (beginning-of-line (- arg))
13536 (setq pos (move-marker (make-marker) (point)))
13537 (insert (delete-and-extract-region beg end))
13538 (goto-char pos)
13539 (org-move-to-column col)))
13541 (defun org-replace-escapes (string table)
13542 "Replace %-escapes in STRING with values in TABLE.
13543 TABLE is an association list with keys like \"%a\" and string values.
13544 The sequences in STRING may contain normal field width and padding information,
13545 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
13546 so values can contain further %-escapes if they are define later in TABLE."
13547 (let ((case-fold-search nil)
13548 e re rpl)
13549 (while (setq e (pop table))
13550 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
13551 (while (string-match re string)
13552 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
13553 (cdr e)))
13554 (setq string (replace-match rpl t t string))))
13555 string))
13558 (defun org-sublist (list start end)
13559 "Return a section of LIST, from START to END.
13560 Counting starts at 1."
13561 (let (rtn (c start))
13562 (setq list (nthcdr (1- start) list))
13563 (while (and list (<= c end))
13564 (push (pop list) rtn)
13565 (setq c (1+ c)))
13566 (nreverse rtn)))
13568 (defun org-find-base-buffer-visiting (file)
13569 "Like `find-buffer-visiting' but alway return the base buffer and
13570 not an indirect buffer."
13571 (let ((buf (find-buffer-visiting file)))
13572 (if buf
13573 (or (buffer-base-buffer buf) buf)
13574 nil)))
13576 (defun org-image-file-name-regexp ()
13577 "Return regexp matching the file names of images."
13578 (if (fboundp 'image-file-name-regexp)
13579 (image-file-name-regexp)
13580 (let ((image-file-name-extensions
13581 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
13582 "xbm" "xpm" "pbm" "pgm" "ppm")))
13583 (concat "\\."
13584 (regexp-opt (nconc (mapcar 'upcase
13585 image-file-name-extensions)
13586 image-file-name-extensions)
13588 "\\'"))))
13590 (defun org-file-image-p (file)
13591 "Return non-nil if FILE is an image."
13592 (save-match-data
13593 (string-match (org-image-file-name-regexp) file)))
13595 (defun org-get-cursor-date ()
13596 "Return the date at cursor in as a time.
13597 This works in the calendar and in the agenda, anywhere else it just
13598 returns the current time."
13599 (let (date day defd)
13600 (cond
13601 ((eq major-mode 'calendar-mode)
13602 (setq date (calendar-cursor-to-date)
13603 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13604 ((eq major-mode 'org-agenda-mode)
13605 (setq day (get-text-property (point) 'day))
13606 (if day
13607 (setq date (calendar-gregorian-from-absolute day)
13608 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
13609 (nth 2 date))))))
13610 (or defd (current-time))))
13612 (defvar org-agenda-action-marker (make-marker)
13613 "Marker pointing to the entry for the next agenda action.")
13615 (defun org-mark-entry-for-agenda-action ()
13616 "Mark the current entry as target of an agenda action.
13617 Agenda actions are actions executed from the agenda with the key `k',
13618 which make use of the date at the cursor."
13619 (interactive)
13620 (move-marker org-agenda-action-marker
13621 (save-excursion (org-back-to-heading t) (point))
13622 (current-buffer))
13623 (message
13624 "Entry marked for action; press `k' at desired date in agenda or calendar"))
13626 ;;; Paragraph filling stuff.
13627 ;; We want this to be just right, so use the full arsenal.
13629 (defun org-indent-line-function ()
13630 "Indent line like previous, but further if previous was headline or item."
13631 (interactive)
13632 (let* ((pos (point))
13633 (itemp (org-at-item-p))
13634 column bpos bcol tpos tcol bullet btype bullet-type)
13635 ;; Find the previous relevant line
13636 (beginning-of-line 1)
13637 (cond
13638 ((looking-at "#") (setq column 0))
13639 ((looking-at "\\*+ ") (setq column 0))
13641 (beginning-of-line 0)
13642 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
13643 (beginning-of-line 0))
13644 (cond
13645 ((looking-at "\\*+[ \t]+")
13646 (if (not org-adapt-indentation)
13647 (setq column 0)
13648 (goto-char (match-end 0))
13649 (setq column (current-column))))
13650 ((org-in-item-p)
13651 (org-beginning-of-item)
13652 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
13653 (setq bpos (match-beginning 1) tpos (match-end 0)
13654 bcol (progn (goto-char bpos) (current-column))
13655 tcol (progn (goto-char tpos) (current-column))
13656 bullet (match-string 1)
13657 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
13658 (if (> tcol (+ bcol org-description-max-indent))
13659 (setq tcol (+ bcol 5)))
13660 (if (not itemp)
13661 (setq column tcol)
13662 (goto-char pos)
13663 (beginning-of-line 1)
13664 (if (looking-at "\\S-")
13665 (progn
13666 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
13667 (setq bullet (match-string 1)
13668 btype (if (string-match "[0-9]" bullet) "n" bullet))
13669 (setq column (if (equal btype bullet-type) bcol tcol)))
13670 (setq column (org-get-indentation)))))
13671 (t (setq column (org-get-indentation))))))
13672 (goto-char pos)
13673 (if (<= (current-column) (current-indentation))
13674 (org-indent-line-to column)
13675 (save-excursion (org-indent-line-to column)))
13676 (setq column (current-column))
13677 (beginning-of-line 1)
13678 (if (looking-at
13679 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
13680 (replace-match (concat "\\1" (format org-property-format
13681 (match-string 2) (match-string 3)))
13682 t nil))
13683 (org-move-to-column column)))
13685 (defun org-set-autofill-regexps ()
13686 (interactive)
13687 ;; In the paragraph separator we include headlines, because filling
13688 ;; text in a line directly attached to a headline would otherwise
13689 ;; fill the headline as well.
13690 (org-set-local 'comment-start-skip "^#+[ \t]*")
13691 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
13692 ;; The paragraph starter includes hand-formatted lists.
13693 (org-set-local 'paragraph-start
13694 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
13695 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
13696 ;; But only if the user has not turned off tables or fixed-width regions
13697 (org-set-local
13698 'auto-fill-inhibit-regexp
13699 (concat "\\*+ \\|#\\+"
13700 "\\|[ \t]*" org-keyword-time-regexp
13701 (if (or org-enable-table-editor org-enable-fixed-width-editor)
13702 (concat
13703 "\\|[ \t]*["
13704 (if org-enable-table-editor "|" "")
13705 (if org-enable-fixed-width-editor ":" "")
13706 "]"))))
13707 ;; We use our own fill-paragraph function, to make sure that tables
13708 ;; and fixed-width regions are not wrapped. That function will pass
13709 ;; through to `fill-paragraph' when appropriate.
13710 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
13711 ; Adaptive filling: To get full control, first make sure that
13712 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
13713 (org-set-local 'adaptive-fill-regexp "\000")
13714 (org-set-local 'adaptive-fill-function
13715 'org-adaptive-fill-function)
13716 (org-set-local
13717 'align-mode-rules-list
13718 '((org-in-buffer-settings
13719 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
13720 (modes . '(org-mode))))))
13722 (defun org-fill-paragraph (&optional justify)
13723 "Re-align a table, pass through to fill-paragraph if no table."
13724 (let ((table-p (org-at-table-p))
13725 (table.el-p (org-at-table.el-p)))
13726 (cond ((and (equal (char-after (point-at-bol)) ?*)
13727 (save-excursion (goto-char (point-at-bol))
13728 (looking-at outline-regexp)))
13729 t) ; skip headlines
13730 (table.el-p t) ; skip table.el tables
13731 (table-p (org-table-align) t) ; align org-mode tables
13732 (t nil)))) ; call paragraph-fill
13734 ;; For reference, this is the default value of adaptive-fill-regexp
13735 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
13737 (defun org-adaptive-fill-function ()
13738 "Return a fill prefix for org-mode files.
13739 In particular, this makes sure hanging paragraphs for hand-formatted lists
13740 work correctly."
13741 (cond ((looking-at "#[ \t]+")
13742 (match-string 0))
13743 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
13744 (save-excursion
13745 (if (> (match-end 1) (+ (match-beginning 1)
13746 org-description-max-indent))
13747 (goto-char (+ (match-beginning 1) 5))
13748 (goto-char (match-end 0)))
13749 (make-string (current-column) ?\ )))
13750 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
13751 (save-excursion
13752 (goto-char (match-end 0))
13753 (make-string (current-column) ?\ )))
13754 (t nil)))
13756 ;;; Other stuff.
13758 (defun org-toggle-fixed-width-section (arg)
13759 "Toggle the fixed-width export.
13760 If there is no active region, the QUOTE keyword at the current headline is
13761 inserted or removed. When present, it causes the text between this headline
13762 and the next to be exported as fixed-width text, and unmodified.
13763 If there is an active region, this command adds or removes a colon as the
13764 first character of this line. If the first character of a line is a colon,
13765 this line is also exported in fixed-width font."
13766 (interactive "P")
13767 (let* ((cc 0)
13768 (regionp (org-region-active-p))
13769 (beg (if regionp (region-beginning) (point)))
13770 (end (if regionp (region-end)))
13771 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
13772 (case-fold-search nil)
13773 (re "[ \t]*\\(:\\)")
13774 off)
13775 (if regionp
13776 (save-excursion
13777 (goto-char beg)
13778 (setq cc (current-column))
13779 (beginning-of-line 1)
13780 (setq off (looking-at re))
13781 (while (> nlines 0)
13782 (setq nlines (1- nlines))
13783 (beginning-of-line 1)
13784 (cond
13785 (arg
13786 (org-move-to-column cc t)
13787 (insert ":\n")
13788 (forward-line -1))
13789 ((and off (looking-at re))
13790 (replace-match "" t t nil 1))
13791 ((not off) (org-move-to-column cc t) (insert ":")))
13792 (forward-line 1)))
13793 (save-excursion
13794 (org-back-to-heading)
13795 (if (looking-at (concat outline-regexp
13796 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
13797 (replace-match "" t t nil 1)
13798 (if (looking-at outline-regexp)
13799 (progn
13800 (goto-char (match-end 0))
13801 (insert org-quote-string " "))))))))
13803 ;;;; Functions extending outline functionality
13805 (defun org-beginning-of-line (&optional arg)
13806 "Go to the beginning of the current line. If that is invisible, continue
13807 to a visible line beginning. This makes the function of C-a more intuitive.
13808 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
13809 first attempt, and only move to after the tags when the cursor is already
13810 beyond the end of the headline."
13811 (interactive "P")
13812 (let ((pos (point)) refpos)
13813 (beginning-of-line 1)
13814 (if (bobp)
13816 (backward-char 1)
13817 (if (org-invisible-p)
13818 (while (and (not (bobp)) (org-invisible-p))
13819 (backward-char 1)
13820 (beginning-of-line 1))
13821 (forward-char 1)))
13822 (when org-special-ctrl-a/e
13823 (cond
13824 ((and (looking-at org-complex-heading-regexp)
13825 (= (char-after (match-end 1)) ?\ ))
13826 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
13827 (point-at-eol)))
13828 (goto-char
13829 (if (eq org-special-ctrl-a/e t)
13830 (cond ((> pos refpos) refpos)
13831 ((= pos (point)) refpos)
13832 (t (point)))
13833 (cond ((> pos (point)) (point))
13834 ((not (eq last-command this-command)) (point))
13835 (t refpos)))))
13836 ((org-at-item-p)
13837 (goto-char
13838 (if (eq org-special-ctrl-a/e t)
13839 (cond ((> pos (match-end 4)) (match-end 4))
13840 ((= pos (point)) (match-end 4))
13841 (t (point)))
13842 (cond ((> pos (point)) (point))
13843 ((not (eq last-command this-command)) (point))
13844 (t (match-end 4))))))))
13845 (org-no-warnings
13846 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
13848 (defun org-end-of-line (&optional arg)
13849 "Go to the end of the line.
13850 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
13851 first attempt, and only move to after the tags when the cursor is already
13852 beyond the end of the headline."
13853 (interactive "P")
13854 (if (or (not org-special-ctrl-a/e)
13855 (not (org-on-heading-p)))
13856 (end-of-line arg)
13857 (let ((pos (point)))
13858 (beginning-of-line 1)
13859 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
13860 (if (eq org-special-ctrl-a/e t)
13861 (if (or (< pos (match-beginning 1))
13862 (= pos (match-end 0)))
13863 (goto-char (match-beginning 1))
13864 (goto-char (match-end 0)))
13865 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
13866 (goto-char (match-end 0))
13867 (goto-char (match-beginning 1))))
13868 (end-of-line arg))))
13869 (org-no-warnings
13870 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
13873 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
13874 (define-key org-mode-map "\C-e" 'org-end-of-line)
13876 (defun org-kill-line (&optional arg)
13877 "Kill line, to tags or end of line."
13878 (interactive "P")
13879 (cond
13880 ((or (not org-special-ctrl-k)
13881 (bolp)
13882 (not (org-on-heading-p)))
13883 (call-interactively 'kill-line))
13884 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
13885 (kill-region (point) (match-beginning 1))
13886 (org-set-tags nil t))
13887 (t (kill-region (point) (point-at-eol)))))
13889 (define-key org-mode-map "\C-k" 'org-kill-line)
13891 (defun org-yank ()
13892 "Yank. If the kill is a subtree, treat it specially.
13893 This command will look at the current kill and check it is a single
13894 subtree, or a series of subtrees[1]. If it passes the test, it is
13895 treated specially, depending on the value of the following variables, both
13896 set by default.
13898 org-yank-folded-subtrees
13899 When set, the subree(s) wiil be folded after insertion.
13901 org-yank-adjusted-subtrees
13902 When set, the subtree will be promoted or demoted in order to
13903 fit into the local outline tree structure.
13906 \[1] Basically, the test checks if the first non-white line is a heading
13907 and if there are no other headings with fewer stars."
13908 (interactive)
13909 (if org-yank-folded-subtrees
13910 (let ((beg (point))
13911 (subtreep (org-kill-is-subtree-p))
13912 end)
13913 (if (and subtreep org-yank-adjusted-subtrees)
13914 (org-paste-subtree nil nil 'for-yank)
13915 (call-interactively 'yank))
13916 (setq end (point))
13917 (goto-char beg)
13918 (when (and (bolp) subtreep)
13919 (or (looking-at outline-regexp)
13920 (re-search-forward (concat "^" outline-regexp) end t))
13921 (while (and (< (point) end) (looking-at outline-regexp))
13922 (hide-subtree)
13923 (org-cycle-show-empty-lines 'folded)
13924 (condition-case nil
13925 (outline-forward-same-level 1)
13926 (error (goto-char end)))))
13927 (goto-char end)
13928 (skip-chars-forward " \t\n\r"))
13929 (if (and subtreep org-yank-adjusted-subtrees)
13930 (org-paste-subtree nil nil 'for-yank)
13931 (call-interactively 'yank))))
13933 (define-key org-mode-map "\C-y" 'org-yank)
13935 (defun org-invisible-p ()
13936 "Check if point is at a character currently not visible."
13937 ;; Early versions of noutline don't have `outline-invisible-p'.
13938 (if (fboundp 'outline-invisible-p)
13939 (outline-invisible-p)
13940 (get-char-property (point) 'invisible)))
13942 (defun org-invisible-p2 ()
13943 "Check if point is at a character currently not visible."
13944 (save-excursion
13945 (if (and (eolp) (not (bobp))) (backward-char 1))
13946 ;; Early versions of noutline don't have `outline-invisible-p'.
13947 (if (fboundp 'outline-invisible-p)
13948 (outline-invisible-p)
13949 (get-char-property (point) 'invisible))))
13951 (defalias 'org-back-to-heading 'outline-back-to-heading)
13952 (defalias 'org-on-heading-p 'outline-on-heading-p)
13953 (defalias 'org-at-heading-p 'outline-on-heading-p)
13954 (defun org-at-heading-or-item-p ()
13955 (or (org-on-heading-p) (org-at-item-p)))
13957 (defun org-on-target-p ()
13958 (or (org-in-regexp org-radio-target-regexp)
13959 (org-in-regexp org-target-regexp)))
13961 (defun org-up-heading-all (arg)
13962 "Move to the heading line of which the present line is a subheading.
13963 This function considers both visible and invisible heading lines.
13964 With argument, move up ARG levels."
13965 (if (fboundp 'outline-up-heading-all)
13966 (outline-up-heading-all arg) ; emacs 21 version of outline.el
13967 (outline-up-heading arg t))) ; emacs 22 version of outline.el
13969 (defun org-up-heading-safe ()
13970 "Move to the heading line of which the present line is a subheading.
13971 This version will not throw an error. It will return the level of the
13972 headline found, or nil if no higher level is found."
13973 (let ((pos (point)) start-level level
13974 (re (concat "^" outline-regexp)))
13975 (catch 'exit
13976 (outline-back-to-heading t)
13977 (setq start-level (funcall outline-level))
13978 (if (equal start-level 1) (throw 'exit nil))
13979 (while (re-search-backward re nil t)
13980 (setq level (funcall outline-level))
13981 (if (< level start-level) (throw 'exit level)))
13982 nil)))
13984 (defun org-first-sibling-p ()
13985 "Is this heading the first child of its parents?"
13986 (interactive)
13987 (let ((re (concat "^" outline-regexp))
13988 level l)
13989 (unless (org-at-heading-p t)
13990 (error "Not at a heading"))
13991 (setq level (funcall outline-level))
13992 (save-excursion
13993 (if (not (re-search-backward re nil t))
13995 (setq l (funcall outline-level))
13996 (< l level)))))
13998 (defun org-goto-sibling (&optional previous)
13999 "Goto the next sibling, even if it is invisible.
14000 When PREVIOUS is set, go to the previous sibling instead. Returns t
14001 when a sibling was found. When none is found, return nil and don't
14002 move point."
14003 (let ((fun (if previous 're-search-backward 're-search-forward))
14004 (pos (point))
14005 (re (concat "^" outline-regexp))
14006 level l)
14007 (when (condition-case nil (org-back-to-heading t) (error nil))
14008 (setq level (funcall outline-level))
14009 (catch 'exit
14010 (or previous (forward-char 1))
14011 (while (funcall fun re nil t)
14012 (setq l (funcall outline-level))
14013 (when (< l level) (goto-char pos) (throw 'exit nil))
14014 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
14015 (goto-char pos)
14016 nil))))
14018 (defun org-show-siblings ()
14019 "Show all siblings of the current headline."
14020 (save-excursion
14021 (while (org-goto-sibling) (org-flag-heading nil)))
14022 (save-excursion
14023 (while (org-goto-sibling 'previous)
14024 (org-flag-heading nil))))
14026 (defun org-show-hidden-entry ()
14027 "Show an entry where even the heading is hidden."
14028 (save-excursion
14029 (org-show-entry)))
14031 (defun org-flag-heading (flag &optional entry)
14032 "Flag the current heading. FLAG non-nil means make invisible.
14033 When ENTRY is non-nil, show the entire entry."
14034 (save-excursion
14035 (org-back-to-heading t)
14036 ;; Check if we should show the entire entry
14037 (if entry
14038 (progn
14039 (org-show-entry)
14040 (save-excursion
14041 (and (outline-next-heading)
14042 (org-flag-heading nil))))
14043 (outline-flag-region (max (point-min) (1- (point)))
14044 (save-excursion (outline-end-of-heading) (point))
14045 flag))))
14047 (defun org-forward-same-level (arg)
14048 "Move forward to the ARG'th subheading at same level as this one.
14049 Stop at the first and last subheadings of a superior heading.
14050 This is like outline-forward-same-level, but invisible headings are ok."
14051 (interactive "p")
14052 (outline-back-to-heading t)
14053 (while (> arg 0)
14054 (let ((point-to-move-to (save-excursion
14055 (org-get-next-sibling))))
14056 (if point-to-move-to
14057 (progn
14058 (goto-char point-to-move-to)
14059 (setq arg (1- arg)))
14060 (progn
14061 (setq arg 0)
14062 (error "No following same-level heading"))))))
14064 (defun org-get-next-sibling ()
14065 "Move to next heading of the same level, and return point.
14066 If there is no such heading, return nil.
14067 This is like outline-next-sibling, but invisible headings are ok."
14068 (let ((level (funcall outline-level)))
14069 (outline-next-heading)
14070 (while (and (not (eobp)) (> (funcall outline-level) level))
14071 (outline-next-heading))
14072 (if (or (eobp) (< (funcall outline-level) level))
14074 (point))))
14076 (defun org-end-of-subtree (&optional invisible-OK to-heading)
14077 ;; This is an exact copy of the original function, but it uses
14078 ;; `org-back-to-heading', to make it work also in invisible
14079 ;; trees. And is uses an invisible-OK argument.
14080 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
14081 (org-back-to-heading invisible-OK)
14082 (let ((first t)
14083 (level (funcall outline-level)))
14084 (while (and (not (eobp))
14085 (or first (> (funcall outline-level) level)))
14086 (setq first nil)
14087 (outline-next-heading))
14088 (unless to-heading
14089 (if (memq (preceding-char) '(?\n ?\^M))
14090 (progn
14091 ;; Go to end of line before heading
14092 (forward-char -1)
14093 (if (memq (preceding-char) '(?\n ?\^M))
14094 ;; leave blank line before heading
14095 (forward-char -1))))))
14096 (point))
14098 (defun org-show-subtree ()
14099 "Show everything after this heading at deeper levels."
14100 (outline-flag-region
14101 (point)
14102 (save-excursion
14103 (outline-end-of-subtree) (outline-next-heading) (point))
14104 nil))
14106 (defun org-show-entry ()
14107 "Show the body directly following this heading.
14108 Show the heading too, if it is currently invisible."
14109 (interactive)
14110 (save-excursion
14111 (condition-case nil
14112 (progn
14113 (org-back-to-heading t)
14114 (outline-flag-region
14115 (max (point-min) (1- (point)))
14116 (save-excursion
14117 (re-search-forward
14118 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
14119 (or (match-beginning 1) (point-max)))
14120 nil))
14121 (error nil))))
14123 (defun org-make-options-regexp (kwds)
14124 "Make a regular expression for keyword lines."
14125 (concat
14127 "#?[ \t]*\\+\\("
14128 (mapconcat 'regexp-quote kwds "\\|")
14129 "\\):[ \t]*"
14130 "\\(.+\\)"))
14132 ;; Make isearch reveal the necessary context
14133 (defun org-isearch-end ()
14134 "Reveal context after isearch exits."
14135 (when isearch-success ; only if search was successful
14136 (if (featurep 'xemacs)
14137 ;; Under XEmacs, the hook is run in the correct place,
14138 ;; we directly show the context.
14139 (org-show-context 'isearch)
14140 ;; In Emacs the hook runs *before* restoring the overlays.
14141 ;; So we have to use a one-time post-command-hook to do this.
14142 ;; (Emacs 22 has a special variable, see function `org-mode')
14143 (unless (and (boundp 'isearch-mode-end-hook-quit)
14144 isearch-mode-end-hook-quit)
14145 ;; Only when the isearch was not quitted.
14146 (org-add-hook 'post-command-hook 'org-isearch-post-command
14147 'append 'local)))))
14149 (defun org-isearch-post-command ()
14150 "Remove self from hook, and show context."
14151 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
14152 (org-show-context 'isearch))
14155 ;;;; Integration with and fixes for other packages
14157 ;;; Imenu support
14159 (defvar org-imenu-markers nil
14160 "All markers currently used by Imenu.")
14161 (make-variable-buffer-local 'org-imenu-markers)
14163 (defun org-imenu-new-marker (&optional pos)
14164 "Return a new marker for use by Imenu, and remember the marker."
14165 (let ((m (make-marker)))
14166 (move-marker m (or pos (point)))
14167 (push m org-imenu-markers)
14170 (defun org-imenu-get-tree ()
14171 "Produce the index for Imenu."
14172 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
14173 (setq org-imenu-markers nil)
14174 (let* ((n org-imenu-depth)
14175 (re (concat "^" outline-regexp))
14176 (subs (make-vector (1+ n) nil))
14177 (last-level 0)
14178 m tree level head)
14179 (save-excursion
14180 (save-restriction
14181 (widen)
14182 (goto-char (point-max))
14183 (while (re-search-backward re nil t)
14184 (setq level (org-reduced-level (funcall outline-level)))
14185 (when (<= level n)
14186 (looking-at org-complex-heading-regexp)
14187 (setq head (org-link-display-format
14188 (org-match-string-no-properties 4))
14189 m (org-imenu-new-marker))
14190 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
14191 (if (>= level last-level)
14192 (push (cons head m) (aref subs level))
14193 (push (cons head (aref subs (1+ level))) (aref subs level))
14194 (loop for i from (1+ level) to n do (aset subs i nil)))
14195 (setq last-level level)))))
14196 (aref subs 1)))
14198 (eval-after-load "imenu"
14199 '(progn
14200 (add-hook 'imenu-after-jump-hook
14201 (lambda ()
14202 (if (eq major-mode 'org-mode)
14203 (org-show-context 'org-goto))))))
14205 (defun org-link-display-format (link)
14206 "Replace a link with either the description, or the link target
14207 if no description is present"
14208 (save-match-data
14209 (if (string-match org-bracket-link-analytic-regexp link)
14210 (replace-match (or (match-string 5 link)
14211 (concat (match-string 1 link)
14212 (match-string 3 link)))
14213 nil nil link)
14214 link)))
14216 ;; Speedbar support
14218 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
14219 "Overlay marking the agenda restriction line in speedbar.")
14220 (org-overlay-put org-speedbar-restriction-lock-overlay
14221 'face 'org-agenda-restriction-lock)
14222 (org-overlay-put org-speedbar-restriction-lock-overlay
14223 'help-echo "Agendas are currently limited to this item.")
14224 (org-detach-overlay org-speedbar-restriction-lock-overlay)
14226 (defun org-speedbar-set-agenda-restriction ()
14227 "Restrict future agenda commands to the location at point in speedbar.
14228 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
14229 (interactive)
14230 (require 'org-agenda)
14231 (let (p m tp np dir txt w)
14232 (cond
14233 ((setq p (text-property-any (point-at-bol) (point-at-eol)
14234 'org-imenu t))
14235 (setq m (get-text-property p 'org-imenu-marker))
14236 (save-excursion
14237 (save-restriction
14238 (set-buffer (marker-buffer m))
14239 (goto-char m)
14240 (org-agenda-set-restriction-lock 'subtree))))
14241 ((setq p (text-property-any (point-at-bol) (point-at-eol)
14242 'speedbar-function 'speedbar-find-file))
14243 (setq tp (previous-single-property-change
14244 (1+ p) 'speedbar-function)
14245 np (next-single-property-change
14246 tp 'speedbar-function)
14247 dir (speedbar-line-directory)
14248 txt (buffer-substring-no-properties (or tp (point-min))
14249 (or np (point-max))))
14250 (save-excursion
14251 (save-restriction
14252 (set-buffer (find-file-noselect
14253 (let ((default-directory dir))
14254 (expand-file-name txt))))
14255 (unless (org-mode-p)
14256 (error "Cannot restrict to non-Org-mode file"))
14257 (org-agenda-set-restriction-lock 'file))))
14258 (t (error "Don't know how to restrict Org-mode's agenda")))
14259 (org-move-overlay org-speedbar-restriction-lock-overlay
14260 (point-at-bol) (point-at-eol))
14261 (setq current-prefix-arg nil)
14262 (org-agenda-maybe-redo)))
14264 (eval-after-load "speedbar"
14265 '(progn
14266 (speedbar-add-supported-extension ".org")
14267 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
14268 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
14269 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
14270 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
14271 (add-hook 'speedbar-visiting-tag-hook
14272 (lambda () (org-show-context 'org-goto)))))
14275 ;;; Fixes and Hacks for problems with other packages
14277 ;; Make flyspell not check words in links, to not mess up our keymap
14278 (defun org-mode-flyspell-verify ()
14279 "Don't let flyspell put overlays at active buttons."
14280 (not (get-text-property (point) 'keymap)))
14282 ;; Make `bookmark-jump' show the jump location if it was hidden.
14283 (eval-after-load "bookmark"
14284 '(if (boundp 'bookmark-after-jump-hook)
14285 ;; We can use the hook
14286 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
14287 ;; Hook not available, use advice
14288 (defadvice bookmark-jump (after org-make-visible activate)
14289 "Make the position visible."
14290 (org-bookmark-jump-unhide))))
14292 ;; Make sure saveplace show the location if it was hidden
14293 (eval-after-load "saveplace"
14294 '(defadvice save-place-find-file-hook (after org-make-visible activate)
14295 "Make the position visible."
14296 (org-bookmark-jump-unhide)))
14298 (defun org-bookmark-jump-unhide ()
14299 "Unhide the current position, to show the bookmark location."
14300 (and (org-mode-p)
14301 (or (org-invisible-p)
14302 (save-excursion (goto-char (max (point-min) (1- (point))))
14303 (org-invisible-p)))
14304 (org-show-context 'bookmark-jump)))
14306 ;; Make session.el ignore our circular variable
14307 (eval-after-load "session"
14308 '(add-to-list 'session-globals-exclude 'org-mark-ring))
14310 ;;;; Experimental code
14312 (defun org-closed-in-range ()
14313 "Sparse tree of items closed in a certain time range.
14314 Still experimental, may disappear in the future."
14315 (interactive)
14316 ;; Get the time interval from the user.
14317 (let* ((time1 (time-to-seconds
14318 (org-read-date nil 'to-time nil "Starting date: ")))
14319 (time2 (time-to-seconds
14320 (org-read-date nil 'to-time nil "End date:")))
14321 ;; callback function
14322 (callback (lambda ()
14323 (let ((time
14324 (time-to-seconds
14325 (apply 'encode-time
14326 (org-parse-time-string
14327 (match-string 1))))))
14328 ;; check if time in interval
14329 (and (>= time time1) (<= time time2))))))
14330 ;; make tree, check each match with the callback
14331 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
14334 ;;;; Finish up
14336 (provide 'org)
14338 (run-hooks 'org-load-hook)
14340 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
14342 ;;; org.el ends here