Bug fixes.
[org-mode.git] / lisp / org.el
blobd59706b4cb89a429d00727296d113742ed35094f
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.
5062 If the cursor is at the beginning of a headline, the same level as
5063 that headline is used to paste the tree
5065 If not, the new level is derived from the *visible* headings
5066 before and after the insertion point, and taken to be the inferior headline
5067 level of the two. So if the previous visible heading is level 3 and the
5068 next is level 4 (or vice versa), level 4 will be used for insertion.
5069 This makes sure that the subtree remains an independent subtree and does
5070 not swallow low level entries.
5072 You can also force a different level, either by using a numeric prefix
5073 argument, or by inserting the heading marker by hand. For example, if the
5074 cursor is after \"*****\", then the tree will be shifted to level 5.
5076 If optional TREE is given, use this text instead of the kill ring.
5078 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
5079 move back over whitespace before inserting, and move point to the end of
5080 the inserted text when done."
5081 (interactive "P")
5082 (unless (org-kill-is-subtree-p tree)
5083 (error "%s"
5084 (substitute-command-keys
5085 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
5086 (let* ((visp (not (org-invisible-p)))
5087 (txt (or tree (and kill-ring (current-kill 0))))
5088 (^re (concat "^\\(" outline-regexp "\\)"))
5089 (re (concat "\\(" outline-regexp "\\)"))
5090 (^re_ (concat "\\(\\*+\\)[ \t]*"))
5092 (old-level (if (string-match ^re txt)
5093 (- (match-end 0) (match-beginning 0) 1)
5094 -1))
5095 (force-level (cond (level (prefix-numeric-value level))
5096 ((and (looking-at "[ \t]*$")
5097 (string-match
5098 ^re_ (buffer-substring
5099 (point-at-bol) (point))))
5100 (- (match-end 1) (match-beginning 1)))
5101 ((and (bolp)
5102 (looking-at org-outline-regexp))
5103 (- (match-end 0) (point) 1))
5104 (t nil)))
5105 (previous-level (save-excursion
5106 (condition-case nil
5107 (progn
5108 (outline-previous-visible-heading 1)
5109 (if (looking-at re)
5110 (- (match-end 0) (match-beginning 0) 1)
5112 (error 1))))
5113 (next-level (save-excursion
5114 (condition-case nil
5115 (progn
5116 (or (looking-at outline-regexp)
5117 (outline-next-visible-heading 1))
5118 (if (looking-at re)
5119 (- (match-end 0) (match-beginning 0) 1)
5121 (error 1))))
5122 (new-level (or force-level (max previous-level next-level)))
5123 (shift (if (or (= old-level -1)
5124 (= new-level -1)
5125 (= old-level new-level))
5127 (- new-level old-level)))
5128 (delta (if (> shift 0) -1 1))
5129 (func (if (> shift 0) 'org-demote 'org-promote))
5130 (org-odd-levels-only nil)
5131 beg end newend)
5132 ;; Remove the forced level indicator
5133 (if force-level
5134 (delete-region (point-at-bol) (point)))
5135 ;; Paste
5136 (beginning-of-line 1)
5137 (unless for-yank (org-back-over-empty-lines))
5138 (setq beg (point))
5139 (insert-before-markers txt)
5140 (unless (string-match "\n\\'" txt) (insert "\n"))
5141 (setq newend (point))
5142 (org-reinstall-markers-in-region beg)
5143 (setq end (point))
5144 (goto-char beg)
5145 (skip-chars-forward " \t\n\r")
5146 (setq beg (point))
5147 (if (and (org-invisible-p) visp)
5148 (save-excursion (outline-show-heading)))
5149 ;; Shift if necessary
5150 (unless (= shift 0)
5151 (save-restriction
5152 (narrow-to-region beg end)
5153 (while (not (= shift 0))
5154 (org-map-region func (point-min) (point-max))
5155 (setq shift (+ delta shift)))
5156 (goto-char (point-min))
5157 (setq newend (point-max))))
5158 (when (or (interactive-p) for-yank)
5159 (message "Clipboard pasted as level %d subtree" new-level))
5160 (if (and (not for-yank) ; in this case, org-yank will decide about folding
5161 kill-ring
5162 (eq org-subtree-clip (current-kill 0))
5163 org-subtree-clip-folded)
5164 ;; The tree was folded before it was killed/copied
5165 (hide-subtree))
5166 (and for-yank (goto-char newend))))
5168 (defun org-kill-is-subtree-p (&optional txt)
5169 "Check if the current kill is an outline subtree, or a set of trees.
5170 Returns nil if kill does not start with a headline, or if the first
5171 headline level is not the largest headline level in the tree.
5172 So this will actually accept several entries of equal levels as well,
5173 which is OK for `org-paste-subtree'.
5174 If optional TXT is given, check this string instead of the current kill."
5175 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
5176 (start-level (and kill
5177 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
5178 org-outline-regexp "\\)")
5179 kill)
5180 (- (match-end 2) (match-beginning 2) 1)))
5181 (re (concat "^" org-outline-regexp))
5182 (start (1+ (or (match-beginning 2) -1))))
5183 (if (not start-level)
5184 (progn
5185 nil) ;; does not even start with a heading
5186 (catch 'exit
5187 (while (setq start (string-match re kill (1+ start)))
5188 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
5189 (throw 'exit nil)))
5190 t))))
5192 (defvar org-markers-to-move nil
5193 "Markers that should be moved with a cut-and-paste operation.
5194 Those markers are stored together with their positions relative to
5195 the start of the region.")
5197 (defun org-save-markers-in-region (beg end)
5198 "Check markers in region.
5199 If these markers are between BEG and END, record their position relative
5200 to BEG, so that after moving the block of text, we can put the markers back
5201 into place.
5202 This function gets called just before an entry or tree gets cut from the
5203 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
5204 called immediately, to move the markers with the entries."
5205 (setq org-markers-to-move nil)
5206 (when (featurep 'org-clock)
5207 (org-clock-save-markers-for-cut-and-paste beg end))
5208 (when (featurep 'org-agenda)
5209 (org-agenda-save-markers-for-cut-and-paste beg end)))
5211 (defun org-check-and-save-marker (marker beg end)
5212 "Check if MARKER is between BEG and END.
5213 If yes, remember the marker and the distance to BEG."
5214 (when (and (marker-buffer marker)
5215 (equal (marker-buffer marker) (current-buffer)))
5216 (if (and (>= marker beg) (< marker end))
5217 (push (cons marker (- marker beg)) org-markers-to-move))))
5219 (defun org-reinstall-markers-in-region (beg)
5220 "Move all remembered markers to their position relative to BEG."
5221 (mapc (lambda (x)
5222 (move-marker (car x) (+ beg (cdr x))))
5223 org-markers-to-move)
5224 (setq org-markers-to-move nil))
5226 (defun org-narrow-to-subtree ()
5227 "Narrow buffer to the current subtree."
5228 (interactive)
5229 (save-excursion
5230 (save-match-data
5231 (narrow-to-region
5232 (progn (org-back-to-heading) (point))
5233 (progn (org-end-of-subtree t) (point))))))
5236 ;;; Outline Sorting
5238 (defun org-sort (with-case)
5239 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
5240 Optional argument WITH-CASE means sort case-sensitively."
5241 (interactive "P")
5242 (if (org-at-table-p)
5243 (org-call-with-arg 'org-table-sort-lines with-case)
5244 (org-call-with-arg 'org-sort-entries-or-items with-case)))
5246 (defun org-sort-remove-invisible (s)
5247 (remove-text-properties 0 (length s) org-rm-props s)
5248 (while (string-match org-bracket-link-regexp s)
5249 (setq s (replace-match (if (match-end 2)
5250 (match-string 3 s)
5251 (match-string 1 s)) t t s)))
5254 (defvar org-priority-regexp) ; defined later in the file
5256 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
5257 "Sort entries on a certain level of an outline tree.
5258 If there is an active region, the entries in the region are sorted.
5259 Else, if the cursor is before the first entry, sort the top-level items.
5260 Else, the children of the entry at point are sorted.
5262 Sorting can be alphabetically, numerically, and by date/time as given by
5263 the first time stamp in the entry. The command prompts for the sorting
5264 type unless it has been given to the function through the SORTING-TYPE
5265 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
5266 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
5267 called with point at the beginning of the record. It must return either
5268 a string or a number that should serve as the sorting key for that record.
5270 Comparing entries ignores case by default. However, with an optional argument
5271 WITH-CASE, the sorting considers case as well."
5272 (interactive "P")
5273 (let ((case-func (if with-case 'identity 'downcase))
5274 start beg end stars re re2
5275 txt what tmp plain-list-p)
5276 ;; Find beginning and end of region to sort
5277 (cond
5278 ((org-region-active-p)
5279 ;; we will sort the region
5280 (setq end (region-end)
5281 what "region")
5282 (goto-char (region-beginning))
5283 (if (not (org-on-heading-p)) (outline-next-heading))
5284 (setq start (point)))
5285 ((org-at-item-p)
5286 ;; we will sort this plain list
5287 (org-beginning-of-item-list) (setq start (point))
5288 (org-end-of-item-list) (setq end (point))
5289 (goto-char start)
5290 (setq plain-list-p t
5291 what "plain list"))
5292 ((or (org-on-heading-p)
5293 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
5294 ;; we will sort the children of the current headline
5295 (org-back-to-heading)
5296 (setq start (point)
5297 end (progn (org-end-of-subtree t t)
5298 (org-back-over-empty-lines)
5299 (point))
5300 what "children")
5301 (goto-char start)
5302 (show-subtree)
5303 (outline-next-heading))
5305 ;; we will sort the top-level entries in this file
5306 (goto-char (point-min))
5307 (or (org-on-heading-p) (outline-next-heading))
5308 (setq start (point) end (point-max) what "top-level")
5309 (goto-char start)
5310 (show-all)))
5312 (setq beg (point))
5313 (if (>= beg end) (error "Nothing to sort"))
5315 (unless plain-list-p
5316 (looking-at "\\(\\*+\\)")
5317 (setq stars (match-string 1)
5318 re (concat "^" (regexp-quote stars) " +")
5319 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
5320 txt (buffer-substring beg end))
5321 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
5322 (if (and (not (equal stars "*")) (string-match re2 txt))
5323 (error "Region to sort contains a level above the first entry")))
5325 (unless sorting-type
5326 (message
5327 (if plain-list-p
5328 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
5329 "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:")
5330 what)
5331 (setq sorting-type (read-char-exclusive))
5333 (and (= (downcase sorting-type) ?f)
5334 (setq getkey-func
5335 (completing-read "Sort using function: "
5336 obarray 'fboundp t nil nil))
5337 (setq getkey-func (intern getkey-func)))
5339 (and (= (downcase sorting-type) ?r)
5340 (setq property
5341 (completing-read "Property: "
5342 (mapcar 'list (org-buffer-property-keys t))
5343 nil t))))
5345 (message "Sorting entries...")
5347 (save-restriction
5348 (narrow-to-region start end)
5350 (let ((dcst (downcase sorting-type))
5351 (now (current-time)))
5352 (sort-subr
5353 (/= dcst sorting-type)
5354 ;; This function moves to the beginning character of the "record" to
5355 ;; be sorted.
5356 (if plain-list-p
5357 (lambda nil
5358 (if (org-at-item-p) t (goto-char (point-max))))
5359 (lambda nil
5360 (if (re-search-forward re nil t)
5361 (goto-char (match-beginning 0))
5362 (goto-char (point-max)))))
5363 ;; This function moves to the last character of the "record" being
5364 ;; sorted.
5365 (if plain-list-p
5366 'org-end-of-item
5367 (lambda nil
5368 (save-match-data
5369 (condition-case nil
5370 (outline-forward-same-level 1)
5371 (error
5372 (goto-char (point-max)))))))
5374 ;; This function returns the value that gets sorted against.
5375 (if plain-list-p
5376 (lambda nil
5377 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
5378 (cond
5379 ((= dcst ?n)
5380 (string-to-number (buffer-substring (match-end 0)
5381 (point-at-eol))))
5382 ((= dcst ?a)
5383 (buffer-substring (match-end 0) (point-at-eol)))
5384 ((= dcst ?t)
5385 (if (re-search-forward org-ts-regexp
5386 (point-at-eol) t)
5387 (org-time-string-to-time (match-string 0))
5388 now))
5389 ((= dcst ?f)
5390 (if getkey-func
5391 (progn
5392 (setq tmp (funcall getkey-func))
5393 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5394 tmp)
5395 (error "Invalid key function `%s'" getkey-func)))
5396 (t (error "Invalid sorting type `%c'" sorting-type)))))
5397 (lambda nil
5398 (cond
5399 ((= dcst ?n)
5400 (if (looking-at org-complex-heading-regexp)
5401 (string-to-number (match-string 4))
5402 nil))
5403 ((= dcst ?a)
5404 (if (looking-at org-complex-heading-regexp)
5405 (funcall case-func (match-string 4))
5406 nil))
5407 ((= dcst ?t)
5408 (if (re-search-forward org-ts-regexp
5409 (save-excursion
5410 (forward-line 2)
5411 (point)) t)
5412 (org-time-string-to-time (match-string 0))
5413 now))
5414 ((= dcst ?p)
5415 (if (re-search-forward org-priority-regexp (point-at-eol) t)
5416 (string-to-char (match-string 2))
5417 org-default-priority))
5418 ((= dcst ?r)
5419 (or (org-entry-get nil property) ""))
5420 ((= dcst ?o)
5421 (if (looking-at org-complex-heading-regexp)
5422 (- 9999 (length (member (match-string 2)
5423 org-todo-keywords-1)))))
5424 ((= dcst ?f)
5425 (if getkey-func
5426 (progn
5427 (setq tmp (funcall getkey-func))
5428 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5429 tmp)
5430 (error "Invalid key function `%s'" getkey-func)))
5431 (t (error "Invalid sorting type `%c'" sorting-type)))))
5433 (cond
5434 ((= dcst ?a) 'string<)
5435 ((= dcst ?t) 'time-less-p)
5436 (t nil)))))
5437 (message "Sorting entries...done")))
5439 (defun org-do-sort (table what &optional with-case sorting-type)
5440 "Sort TABLE of WHAT according to SORTING-TYPE.
5441 The user will be prompted for the SORTING-TYPE if the call to this
5442 function does not specify it. WHAT is only for the prompt, to indicate
5443 what is being sorted. The sorting key will be extracted from
5444 the car of the elements of the table.
5445 If WITH-CASE is non-nil, the sorting will be case-sensitive."
5446 (unless sorting-type
5447 (message
5448 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
5449 what)
5450 (setq sorting-type (read-char-exclusive)))
5451 (let ((dcst (downcase sorting-type))
5452 extractfun comparefun)
5453 ;; Define the appropriate functions
5454 (cond
5455 ((= dcst ?n)
5456 (setq extractfun 'string-to-number
5457 comparefun (if (= dcst sorting-type) '< '>)))
5458 ((= dcst ?a)
5459 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
5460 (lambda(x) (downcase (org-sort-remove-invisible x))))
5461 comparefun (if (= dcst sorting-type)
5462 'string<
5463 (lambda (a b) (and (not (string< a b))
5464 (not (string= a b)))))))
5465 ((= dcst ?t)
5466 (setq extractfun
5467 (lambda (x)
5468 (if (string-match org-ts-regexp x)
5469 (time-to-seconds
5470 (org-time-string-to-time (match-string 0 x)))
5472 comparefun (if (= dcst sorting-type) '< '>)))
5473 (t (error "Invalid sorting type `%c'" sorting-type)))
5475 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5476 table)
5477 (lambda (a b) (funcall comparefun (car a) (car b))))))
5479 ;;; Editing source examples
5481 (defvar org-exit-edit-mode-map (make-sparse-keymap))
5482 (define-key org-exit-edit-mode-map "\C-c'" 'org-edit-src-exit)
5483 (defvar org-edit-src-force-single-line nil)
5484 (defvar org-edit-src-from-org-mode nil)
5485 (defvar org-edit-src-picture nil)
5487 (define-minor-mode org-exit-edit-mode
5488 "Minor mode installing a single key binding, \"C-c '\" to exit special edit.")
5490 (defun org-edit-src-code ()
5491 "Edit the source code example at point.
5492 An indirect buffer is created, and that buffer is then narrowed to the
5493 example at point and switched to the correct language mode. When done,
5494 exit by killing the buffer with \\[org-edit-src-exit]."
5495 (interactive)
5496 (let ((line (org-current-line))
5497 (case-fold-search t)
5498 (msg (substitute-command-keys
5499 "Edit, then exit with C-c ' (C-c and single quote)"))
5500 (info (org-edit-src-find-region-and-lang))
5501 (org-mode-p (eq major-mode 'org-mode))
5502 beg end lang lang-f single)
5503 (if (not info)
5505 (setq beg (nth 0 info)
5506 end (nth 1 info)
5507 lang (nth 2 info)
5508 single (nth 3 info)
5509 lang-f (intern (concat lang "-mode")))
5510 (unless (functionp lang-f)
5511 (error "No such language mode: %s" lang-f))
5512 (goto-line line)
5513 (if (get-buffer "*Org Edit Src Example*")
5514 (kill-buffer "*Org Edit Src Example*"))
5515 (switch-to-buffer (make-indirect-buffer (current-buffer)
5516 "*Org Edit Src Example*"))
5517 (narrow-to-region beg end)
5518 (remove-text-properties beg end '(display nil invisible nil
5519 intangible nil))
5520 (let ((org-inhibit-startup t))
5521 (funcall lang-f))
5522 (set (make-local-variable 'org-edit-src-force-single-line) single)
5523 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5524 (when org-mode-p
5525 (goto-char (point-min))
5526 (while (re-search-forward "^," nil t)
5527 (replace-match "")))
5528 (goto-line line)
5529 (org-exit-edit-mode)
5530 (org-set-local 'header-line-format msg)
5531 (message "%s" msg)
5532 t)))
5534 (defun org-edit-fixed-width-region ()
5535 "Edit the fixed-width ascii drawing at point.
5536 This must be a region where each line starts with ca colon followed by
5537 a space character.
5538 An indirect buffer is created, and that buffer is then narrowed to the
5539 example at point and switched to artist-mode. When done,
5540 exit by killing the buffer with \\[org-edit-src-exit]."
5541 (interactive)
5542 (let ((line (org-current-line))
5543 (case-fold-search t)
5544 (msg (substitute-command-keys
5545 "Edit, then exit with C-c ' (C-c and single quote)"))
5546 (org-mode-p (eq major-mode 'org-mode))
5547 beg end lang lang-f)
5548 (beginning-of-line 1)
5549 (if (looking-at "[ \t]*[^:\n \t]")
5551 (if (looking-at "[ \t]*\\(\n\\|\\'\\)]")
5552 (setq beg (point) end (match-end 0))
5553 (save-excursion
5554 (if (re-search-backward "^[ \t]*[^:]" nil 'move)
5555 (setq beg (point-at-bol 2))
5556 (setq beg (point))))
5557 (save-excursion
5558 (if (re-search-forward "^[ \t]*[^:]" nil 'move)
5559 (setq end (1- (match-beginning 0)))
5560 (setq end (point))))
5561 (goto-line line)
5562 (if (get-buffer "*Org Edit Picture*")
5563 (kill-buffer "*Org Edit Picture*"))
5564 (switch-to-buffer (make-indirect-buffer (current-buffer)
5565 "*Org Edit Picture*"))
5566 (narrow-to-region beg end)
5567 (remove-text-properties beg end '(display nil invisible nil
5568 intangible nil))
5569 (when (fboundp 'font-lock-unfontify-region)
5570 (font-lock-unfontify-region (point-min) (point-max)))
5571 (cond
5572 ((eq org-edit-fixed-width-region-mode 'artist-mode)
5573 (fundamental-mode)
5574 (artist-mode 1))
5575 (t (funcall org-edit-fixed-width-region-mode)))
5576 (set (make-local-variable 'org-edit-src-force-single-line) nil)
5577 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5578 (set (make-local-variable 'org-edit-src-picture) t)
5579 (goto-char (point-min))
5580 (while (re-search-forward "^[ \t]*: " nil t)
5581 (replace-match ""))
5582 (goto-line line)
5583 (org-exit-edit-mode)
5584 (org-set-local 'header-line-format msg)
5585 (message "%s" msg)
5586 t))))
5589 (defun org-edit-src-find-region-and-lang ()
5590 "Find the region and language for a local edit.
5591 Return a list with beginning and end of the region, a string representing
5592 the language, a switch telling of the content should be in a single line."
5593 (let ((re-list
5594 (append
5595 org-edit-src-region-extra
5597 ("<src\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</src>" lang)
5598 ("<literal\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</literal>" style)
5599 ("<example>[ \t]*\n?" "\n?[ \t]*</example>" "fundamental")
5600 ("<lisp>[ \t]*\n?" "\n?[ \t]*</lisp>" "emacs-lisp")
5601 ("<perl>[ \t]*\n?" "\n?[ \t]*</perl>" "perl")
5602 ("<python>[ \t]*\n?" "\n?[ \t]*</python>" "python")
5603 ("<ruby>[ \t]*\n?" "\n?[ \t]*</ruby>" "ruby")
5604 ("^#\\+begin_src\\( \\([^ \t\n]+\\)\\)?.*\n" "\n#\\+end_src" 2)
5605 ("^#\\+begin_example.*\n" "\n#\\+end_example" "fundamental")
5606 ("^#\\+html:" "\n" "html" single-line)
5607 ("^#\\+begin_html.*\n" "\n#\\+end_html" "html")
5608 ("^#\\+begin_latex.*\n" "\n#\\+end_latex" "latex")
5609 ("^#\\+latex:" "\n" "latex" single-line)
5610 ("^#\\+begin_ascii.*\n" "\n#\\+end_ascii" "fundamental")
5611 ("^#\\+ascii:" "\n" "ascii" single-line)
5613 (pos (point))
5614 re re1 re2 single beg end lang)
5615 (catch 'exit
5616 (while (setq entry (pop re-list))
5617 (setq re1 (car entry) re2 (nth 1 entry) lang (nth 2 entry)
5618 single (nth 3 entry))
5619 (save-excursion
5620 (if (or (looking-at re1)
5621 (re-search-backward re1 nil t))
5622 (progn
5623 (setq beg (match-end 0) lang (org-edit-src-get-lang lang))
5624 (if (and (re-search-forward re2 nil t)
5625 (>= (match-end 0) pos))
5626 (throw 'exit (list beg (match-beginning 0) lang single))))
5627 (if (or (looking-at re2)
5628 (re-search-forward re2 nil t))
5629 (progn
5630 (setq end (match-beginning 0))
5631 (if (and (re-search-backward re1 nil t)
5632 (<= (match-beginning 0) pos))
5633 (throw 'exit
5634 (list (match-end 0) end
5635 (org-edit-src-get-lang lang) single)))))))))))
5637 (defun org-edit-src-get-lang (lang)
5638 "Extract the src language."
5639 (let ((m (match-string 0)))
5640 (cond
5641 ((stringp lang) lang)
5642 ((integerp lang) (match-string lang))
5643 ((and (eq lang 'lang)
5644 (string-match "\\<lang=\"\\([^ \t\n\"]+\\)\"" m))
5645 (match-string 1 m))
5646 ((and (eq lang 'style)
5647 (string-match "\\<style=\"\\([^ \t\n\"]+\\)\"" m))
5648 (match-string 1 m))
5649 (t "fundamental"))))
5651 (defun org-edit-src-exit ()
5652 "Exit special edit and protect problematic lines."
5653 (interactive)
5654 (unless (buffer-base-buffer (current-buffer))
5655 (error "This is not an indirect buffer, something is wrong..."))
5656 (unless (> (point-min) 1)
5657 (error "This buffer is not narrowed, something is wrong..."))
5658 (goto-char (point-min))
5659 (if (looking-at "[ \t\n]*\n") (replace-match ""))
5660 (if (re-search-forward "\n[ \t\n]*\\'" nil t) (replace-match ""))
5661 (when (org-bound-and-true-p org-edit-src-force-single-line)
5662 (goto-char (point-min))
5663 (while (re-search-forward "\n" nil t)
5664 (replace-match " "))
5665 (goto-char (point-min))
5666 (if (looking-at "\\s-*") (replace-match " "))
5667 (if (re-search-forward "\\s-+\\'" nil t)
5668 (replace-match "")))
5669 (when (org-bound-and-true-p org-edit-src-from-org-mode)
5670 (goto-char (point-min))
5671 (while (re-search-forward (if (org-mode-p) "^\\(.\\)" "^\\([*#]\\)") nil t)
5672 (replace-match ",\\1"))
5673 (when font-lock-mode
5674 (font-lock-unfontify-region (point-min) (point-max)))
5675 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
5676 (when (org-bound-and-true-p org-edit-src-picture)
5677 (goto-char (point-min))
5678 (while (re-search-forward "^" nil t)
5679 (replace-match ": "))
5680 (when font-lock-mode
5681 (font-lock-unfontify-region (point-min) (point-max)))
5682 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
5683 (kill-buffer (current-buffer))
5684 (and (org-mode-p) (org-restart-font-lock)))
5687 ;;; The orgstruct minor mode
5689 ;; Define a minor mode which can be used in other modes in order to
5690 ;; integrate the org-mode structure editing commands.
5692 ;; This is really a hack, because the org-mode structure commands use
5693 ;; keys which normally belong to the major mode. Here is how it
5694 ;; works: The minor mode defines all the keys necessary to operate the
5695 ;; structure commands, but wraps the commands into a function which
5696 ;; tests if the cursor is currently at a headline or a plain list
5697 ;; item. If that is the case, the structure command is used,
5698 ;; temporarily setting many Org-mode variables like regular
5699 ;; expressions for filling etc. However, when any of those keys is
5700 ;; used at a different location, function uses `key-binding' to look
5701 ;; up if the key has an associated command in another currently active
5702 ;; keymap (minor modes, major mode, global), and executes that
5703 ;; command. There might be problems if any of the keys is otherwise
5704 ;; used as a prefix key.
5706 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
5707 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
5708 ;; addresses this by checking explicitly for both bindings.
5710 (defvar orgstruct-mode-map (make-sparse-keymap)
5711 "Keymap for the minor `orgstruct-mode'.")
5713 (defvar org-local-vars nil
5714 "List of local variables, for use by `orgstruct-mode'")
5716 ;;;###autoload
5717 (define-minor-mode orgstruct-mode
5718 "Toggle the minor more `orgstruct-mode'.
5719 This mode is for using Org-mode structure commands in other modes.
5720 The following key behave as if Org-mode was active, if the cursor
5721 is on a headline, or on a plain list item (both in the definition
5722 of Org-mode).
5724 M-up Move entry/item up
5725 M-down Move entry/item down
5726 M-left Promote
5727 M-right Demote
5728 M-S-up Move entry/item up
5729 M-S-down Move entry/item down
5730 M-S-left Promote subtree
5731 M-S-right Demote subtree
5732 M-q Fill paragraph and items like in Org-mode
5733 C-c ^ Sort entries
5734 C-c - Cycle list bullet
5735 TAB Cycle item visibility
5736 M-RET Insert new heading/item
5737 S-M-RET Insert new TODO heading / Chekbox item
5738 C-c C-c Set tags / toggle checkbox"
5739 nil " OrgStruct" nil
5740 (org-load-modules-maybe)
5741 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
5743 ;;;###autoload
5744 (defun turn-on-orgstruct ()
5745 "Unconditionally turn on `orgstruct-mode'."
5746 (orgstruct-mode 1))
5748 ;;;###autoload
5749 (defun turn-on-orgstruct++ ()
5750 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
5751 In addition to setting orgstruct-mode, this also exports all indentation and
5752 autofilling variables from org-mode into the buffer. Note that turning
5753 off orgstruct-mode will *not* remove these additional settings."
5754 (orgstruct-mode 1)
5755 (let (var val)
5756 (mapc
5757 (lambda (x)
5758 (when (string-match
5759 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
5760 (symbol-name (car x)))
5761 (setq var (car x) val (nth 1 x))
5762 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
5763 org-local-vars)))
5765 (defun orgstruct-error ()
5766 "Error when there is no default binding for a structure key."
5767 (interactive)
5768 (error "This key has no function outside structure elements"))
5770 (defun orgstruct-setup ()
5771 "Setup orgstruct keymaps."
5772 (let ((nfunc 0)
5773 (bindings
5774 (list
5775 '([(meta up)] org-metaup)
5776 '([(meta down)] org-metadown)
5777 '([(meta left)] org-metaleft)
5778 '([(meta right)] org-metaright)
5779 '([(meta shift up)] org-shiftmetaup)
5780 '([(meta shift down)] org-shiftmetadown)
5781 '([(meta shift left)] org-shiftmetaleft)
5782 '([(meta shift right)] org-shiftmetaright)
5783 '([(shift up)] org-shiftup)
5784 '([(shift down)] org-shiftdown)
5785 '("\C-c\C-c" org-ctrl-c-ctrl-c)
5786 '("\M-q" fill-paragraph)
5787 '("\C-c^" org-sort)
5788 '("\C-c-" org-cycle-list-bullet)))
5789 elt key fun cmd)
5790 (while (setq elt (pop bindings))
5791 (setq nfunc (1+ nfunc))
5792 (setq key (org-key (car elt))
5793 fun (nth 1 elt)
5794 cmd (orgstruct-make-binding fun nfunc key))
5795 (org-defkey orgstruct-mode-map key cmd))
5797 ;; Special treatment needed for TAB and RET
5798 (org-defkey orgstruct-mode-map [(tab)]
5799 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
5800 (org-defkey orgstruct-mode-map "\C-i"
5801 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
5803 (org-defkey orgstruct-mode-map "\M-\C-m"
5804 (orgstruct-make-binding 'org-insert-heading 105
5805 "\M-\C-m" [(meta return)]))
5806 (org-defkey orgstruct-mode-map [(meta return)]
5807 (orgstruct-make-binding 'org-insert-heading 106
5808 [(meta return)] "\M-\C-m"))
5810 (org-defkey orgstruct-mode-map [(shift meta return)]
5811 (orgstruct-make-binding 'org-insert-todo-heading 107
5812 [(meta return)] "\M-\C-m"))
5814 (unless org-local-vars
5815 (setq org-local-vars (org-get-local-variables)))
5819 (defun orgstruct-make-binding (fun n &rest keys)
5820 "Create a function for binding in the structure minor mode.
5821 FUN is the command to call inside a table. N is used to create a unique
5822 command name. KEYS are keys that should be checked in for a command
5823 to execute outside of tables."
5824 (eval
5825 (list 'defun
5826 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
5827 '(arg)
5828 (concat "In Structure, run `" (symbol-name fun) "'.\n"
5829 "Outside of structure, run the binding of `"
5830 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
5831 "'.")
5832 '(interactive "p")
5833 (list 'if
5834 '(org-context-p 'headline 'item)
5835 (list 'org-run-like-in-org-mode (list 'quote fun))
5836 (list 'let '(orgstruct-mode)
5837 (list 'call-interactively
5838 (append '(or)
5839 (mapcar (lambda (k)
5840 (list 'key-binding k))
5841 keys)
5842 '('orgstruct-error))))))))
5844 (defun org-context-p (&rest contexts)
5845 "Check if local context is any of CONTEXTS.
5846 Possible values in the list of contexts are `table', `headline', and `item'."
5847 (let ((pos (point)))
5848 (goto-char (point-at-bol))
5849 (prog1 (or (and (memq 'table contexts)
5850 (looking-at "[ \t]*|"))
5851 (and (memq 'headline contexts)
5852 ;;????????? (looking-at "\\*+"))
5853 (looking-at outline-regexp))
5854 (and (memq 'item contexts)
5855 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
5856 (goto-char pos))))
5858 (defun org-get-local-variables ()
5859 "Return a list of all local variables in an org-mode buffer."
5860 (let (varlist)
5861 (with-current-buffer (get-buffer-create "*Org tmp*")
5862 (erase-buffer)
5863 (org-mode)
5864 (setq varlist (buffer-local-variables)))
5865 (kill-buffer "*Org tmp*")
5866 (delq nil
5867 (mapcar
5868 (lambda (x)
5869 (setq x
5870 (if (symbolp x)
5871 (list x)
5872 (list (car x) (list 'quote (cdr x)))))
5873 (if (string-match
5874 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
5875 (symbol-name (car x)))
5876 x nil))
5877 varlist))))
5879 ;;;###autoload
5880 (defun org-run-like-in-org-mode (cmd)
5881 (org-load-modules-maybe)
5882 (unless org-local-vars
5883 (setq org-local-vars (org-get-local-variables)))
5884 (eval (list 'let org-local-vars
5885 (list 'call-interactively (list 'quote cmd)))))
5887 ;;;; Archiving
5889 (defun org-get-category (&optional pos)
5890 "Get the category applying to position POS."
5891 (get-text-property (or pos (point)) 'org-category))
5893 (defun org-refresh-category-properties ()
5894 "Refresh category text properties in the buffer."
5895 (let ((def-cat (cond
5896 ((null org-category)
5897 (if buffer-file-name
5898 (file-name-sans-extension
5899 (file-name-nondirectory buffer-file-name))
5900 "???"))
5901 ((symbolp org-category) (symbol-name org-category))
5902 (t org-category)))
5903 beg end cat pos optionp)
5904 (org-unmodified
5905 (save-excursion
5906 (save-restriction
5907 (widen)
5908 (goto-char (point-min))
5909 (put-text-property (point) (point-max) 'org-category def-cat)
5910 (while (re-search-forward
5911 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
5912 (setq pos (match-end 0)
5913 optionp (equal (char-after (match-beginning 0)) ?#)
5914 cat (org-trim (match-string 2)))
5915 (if optionp
5916 (setq beg (point-at-bol) end (point-max))
5917 (org-back-to-heading t)
5918 (setq beg (point) end (org-end-of-subtree t t)))
5919 (put-text-property beg end 'org-category cat)
5920 (goto-char pos)))))))
5923 ;;;; Link Stuff
5925 ;;; Link abbreviations
5927 (defun org-link-expand-abbrev (link)
5928 "Apply replacements as defined in `org-link-abbrev-alist."
5929 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
5930 (let* ((key (match-string 1 link))
5931 (as (or (assoc key org-link-abbrev-alist-local)
5932 (assoc key org-link-abbrev-alist)))
5933 (tag (and (match-end 2) (match-string 3 link)))
5934 rpl)
5935 (if (not as)
5936 link
5937 (setq rpl (cdr as))
5938 (cond
5939 ((symbolp rpl) (funcall rpl tag))
5940 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
5941 (t (concat rpl tag)))))
5942 link))
5944 ;;; Storing and inserting links
5946 (defvar org-insert-link-history nil
5947 "Minibuffer history for links inserted with `org-insert-link'.")
5949 (defvar org-stored-links nil
5950 "Contains the links stored with `org-store-link'.")
5952 (defvar org-store-link-plist nil
5953 "Plist with info about the most recently link created with `org-store-link'.")
5955 (defvar org-link-protocols nil
5956 "Link protocols added to Org-mode using `org-add-link-type'.")
5958 (defvar org-store-link-functions nil
5959 "List of functions that are called to create and store a link.
5960 Each function will be called in turn until one returns a non-nil
5961 value. Each function should check if it is responsible for creating
5962 this link (for example by looking at the major mode).
5963 If not, it must exit and return nil.
5964 If yes, it should return a non-nil value after a calling
5965 `org-store-link-props' with a list of properties and values.
5966 Special properties are:
5968 :type The link prefix. like \"http\". This must be given.
5969 :link The link, like \"http://www.astro.uva.nl/~dominik\".
5970 This is obligatory as well.
5971 :description Optional default description for the second pair
5972 of brackets in an Org-mode link. The user can still change
5973 this when inserting this link into an Org-mode buffer.
5975 In addition to these, any additional properties can be specified
5976 and then used in remember templates.")
5978 (defun org-add-link-type (type &optional follow export)
5979 "Add TYPE to the list of `org-link-types'.
5980 Re-compute all regular expressions depending on `org-link-types'
5982 FOLLOW and EXPORT are two functions.
5984 FOLLOW should take the link path as the single argument and do whatever
5985 is necessary to follow the link, for example find a file or display
5986 a mail message.
5988 EXPORT should format the link path for export to one of the export formats.
5989 It should be a function accepting three arguments:
5991 path the path of the link, the text after the prefix (like \"http:\")
5992 desc the description of the link, if any, nil if there was no descripton
5993 format the export format, a symbol like `html' or `latex'.
5995 The function may use the FORMAT information to return different values
5996 depending on the format. The return value will be put literally into
5997 the exported file.
5998 Org-mode has a built-in default for exporting links. If you are happy with
5999 this default, there is no need to define an export function for the link
6000 type. For a simple example of an export function, see `org-bbdb.el'."
6001 (add-to-list 'org-link-types type t)
6002 (org-make-link-regexps)
6003 (if (assoc type org-link-protocols)
6004 (setcdr (assoc type org-link-protocols) (list follow export))
6005 (push (list type follow export) org-link-protocols)))
6008 ;;;###autoload
6009 (defun org-store-link (arg)
6010 "\\<org-mode-map>Store an org-link to the current location.
6011 This link is added to `org-stored-links' and can later be inserted
6012 into an org-buffer with \\[org-insert-link].
6014 For some link types, a prefix arg is interpreted:
6015 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
6016 For file links, arg negates `org-context-in-file-links'."
6017 (interactive "P")
6018 (org-load-modules-maybe)
6019 (setq org-store-link-plist nil) ; reset
6020 (let (link cpltxt desc description search txt)
6021 (cond
6023 ((run-hook-with-args-until-success 'org-store-link-functions)
6024 (setq link (plist-get org-store-link-plist :link)
6025 desc (or (plist-get org-store-link-plist :description) link)))
6027 ((eq major-mode 'calendar-mode)
6028 (let ((cd (calendar-cursor-to-date)))
6029 (setq link
6030 (format-time-string
6031 (car org-time-stamp-formats)
6032 (apply 'encode-time
6033 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6034 nil nil nil))))
6035 (org-store-link-props :type "calendar" :date cd)))
6037 ((eq major-mode 'w3-mode)
6038 (setq cpltxt (url-view-url t)
6039 link (org-make-link cpltxt))
6040 (org-store-link-props :type "w3" :url (url-view-url t)))
6042 ((eq major-mode 'w3m-mode)
6043 (setq cpltxt (or w3m-current-title w3m-current-url)
6044 link (org-make-link w3m-current-url))
6045 (org-store-link-props :type "w3m" :url (url-view-url t)))
6047 ((setq search (run-hook-with-args-until-success
6048 'org-create-file-search-functions))
6049 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6050 "::" search))
6051 (setq cpltxt (or description link)))
6053 ((eq major-mode 'image-mode)
6054 (setq cpltxt (concat "file:"
6055 (abbreviate-file-name buffer-file-name))
6056 link (org-make-link cpltxt))
6057 (org-store-link-props :type "image" :file buffer-file-name))
6059 ((eq major-mode 'dired-mode)
6060 ;; link to the file in the current line
6061 (setq cpltxt (concat "file:"
6062 (abbreviate-file-name
6063 (expand-file-name
6064 (dired-get-filename nil t))))
6065 link (org-make-link cpltxt)))
6067 ((and buffer-file-name (org-mode-p))
6068 ;; Just link to current headline
6069 (setq cpltxt (concat "file:"
6070 (abbreviate-file-name buffer-file-name)))
6071 ;; Add a context search string
6072 (when (org-xor org-context-in-file-links arg)
6073 ;; Check if we are on a target
6074 (if (org-in-regexp "<<\\(.*?\\)>>")
6075 (setq cpltxt (concat cpltxt "::" (match-string 1)))
6076 (setq txt (cond
6077 ((org-on-heading-p) nil)
6078 ((org-region-active-p)
6079 (buffer-substring (region-beginning) (region-end)))
6080 (t nil)))
6081 (when (or (null txt) (string-match "\\S-" txt))
6082 (setq cpltxt
6083 (concat cpltxt "::"
6084 (condition-case nil
6085 (org-make-org-heading-search-string txt)
6086 (error "")))
6087 desc "NONE"))))
6088 (if (string-match "::\\'" cpltxt)
6089 (setq cpltxt (substring cpltxt 0 -2)))
6090 (setq link (org-make-link cpltxt)))
6092 ((buffer-file-name (buffer-base-buffer))
6093 ;; Just link to this file here.
6094 (setq cpltxt (concat "file:"
6095 (abbreviate-file-name
6096 (buffer-file-name (buffer-base-buffer)))))
6097 ;; Add a context string
6098 (when (org-xor org-context-in-file-links arg)
6099 (setq txt (if (org-region-active-p)
6100 (buffer-substring (region-beginning) (region-end))
6101 (buffer-substring (point-at-bol) (point-at-eol))))
6102 ;; Only use search option if there is some text.
6103 (when (string-match "\\S-" txt)
6104 (setq cpltxt
6105 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6106 desc "NONE")))
6107 (setq link (org-make-link cpltxt)))
6109 ((interactive-p)
6110 (error "Cannot link to a buffer which is not visiting a file"))
6112 (t (setq link nil)))
6114 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6115 (setq link (or link cpltxt)
6116 desc (or desc cpltxt))
6117 (if (equal desc "NONE") (setq desc nil))
6119 (if (and (interactive-p) link)
6120 (progn
6121 (setq org-stored-links
6122 (cons (list link desc) org-stored-links))
6123 (message "Stored: %s" (or desc link)))
6124 (and link (org-make-link-string link desc)))))
6126 (defun org-store-link-props (&rest plist)
6127 "Store link properties, extract names and addresses."
6128 (let (x adr)
6129 (when (setq x (plist-get plist :from))
6130 (setq adr (mail-extract-address-components x))
6131 (plist-put plist :fromname (car adr))
6132 (plist-put plist :fromaddress (nth 1 adr)))
6133 (when (setq x (plist-get plist :to))
6134 (setq adr (mail-extract-address-components x))
6135 (plist-put plist :toname (car adr))
6136 (plist-put plist :toaddress (nth 1 adr))))
6137 (let ((from (plist-get plist :from))
6138 (to (plist-get plist :to)))
6139 (when (and from to org-from-is-user-regexp)
6140 (plist-put plist :fromto
6141 (if (string-match org-from-is-user-regexp from)
6142 (concat "to %t")
6143 (concat "from %f")))))
6144 (setq org-store-link-plist plist))
6146 (defun org-add-link-props (&rest plist)
6147 "Add these properties to the link property list."
6148 (let (key value)
6149 (while plist
6150 (setq key (pop plist) value (pop plist))
6151 (setq org-store-link-plist
6152 (plist-put org-store-link-plist key value)))))
6154 (defun org-email-link-description (&optional fmt)
6155 "Return the description part of an email link.
6156 This takes information from `org-store-link-plist' and formats it
6157 according to FMT (default from `org-email-link-description-format')."
6158 (setq fmt (or fmt org-email-link-description-format))
6159 (let* ((p org-store-link-plist)
6160 (to (plist-get p :toaddress))
6161 (from (plist-get p :fromaddress))
6162 (table
6163 (list
6164 (cons "%c" (plist-get p :fromto))
6165 (cons "%F" (plist-get p :from))
6166 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
6167 (cons "%T" (plist-get p :to))
6168 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
6169 (cons "%s" (plist-get p :subject))
6170 (cons "%m" (plist-get p :message-id)))))
6171 (when (string-match "%c" fmt)
6172 ;; Check if the user wrote this message
6173 (if (and org-from-is-user-regexp from to
6174 (save-match-data (string-match org-from-is-user-regexp from)))
6175 (setq fmt (replace-match "to %t" t t fmt))
6176 (setq fmt (replace-match "from %f" t t fmt))))
6177 (org-replace-escapes fmt table)))
6179 (defun org-make-org-heading-search-string (&optional string heading)
6180 "Make search string for STRING or current headline."
6181 (interactive)
6182 (let ((s (or string (org-get-heading))))
6183 (unless (and string (not heading))
6184 ;; We are using a headline, clean up garbage in there.
6185 (if (string-match org-todo-regexp s)
6186 (setq s (replace-match "" t t s)))
6187 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
6188 (setq s (replace-match "" t t s)))
6189 (setq s (org-trim s))
6190 (if (string-match (concat "^\\(" org-quote-string "\\|"
6191 org-comment-string "\\)") s)
6192 (setq s (replace-match "" t t s)))
6193 (while (string-match org-ts-regexp s)
6194 (setq s (replace-match "" t t s))))
6195 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
6196 (setq s (replace-match " " t t s)))
6197 (or string (setq s (concat "*" s))) ; Add * for headlines
6198 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
6200 (defun org-make-link (&rest strings)
6201 "Concatenate STRINGS."
6202 (apply 'concat strings))
6204 (defun org-make-link-string (link &optional description)
6205 "Make a link with brackets, consisting of LINK and DESCRIPTION."
6206 (unless (string-match "\\S-" link)
6207 (error "Empty link"))
6208 (when (stringp description)
6209 ;; Remove brackets from the description, they are fatal.
6210 (while (string-match "\\[" description)
6211 (setq description (replace-match "{" t t description)))
6212 (while (string-match "\\]" description)
6213 (setq description (replace-match "}" t t description))))
6214 (when (equal (org-link-escape link) description)
6215 ;; No description needed, it is identical
6216 (setq description nil))
6217 (when (and (not description)
6218 (not (equal link (org-link-escape link))))
6219 (setq description (org-extract-attributes link)))
6220 (concat "[[" (org-link-escape link) "]"
6221 (if description (concat "[" description "]") "")
6222 "]"))
6224 (defconst org-link-escape-chars
6225 '((?\ . "%20")
6226 (?\[ . "%5B")
6227 (?\] . "%5D")
6228 (?\340 . "%E0") ; `a
6229 (?\342 . "%E2") ; ^a
6230 (?\347 . "%E7") ; ,c
6231 (?\350 . "%E8") ; `e
6232 (?\351 . "%E9") ; 'e
6233 (?\352 . "%EA") ; ^e
6234 (?\356 . "%EE") ; ^i
6235 (?\364 . "%F4") ; ^o
6236 (?\371 . "%F9") ; `u
6237 (?\373 . "%FB") ; ^u
6238 (?\; . "%3B")
6239 (?? . "%3F")
6240 (?= . "%3D")
6241 (?+ . "%2B")
6243 "Association list of escapes for some characters problematic in links.
6244 This is the list that is used for internal purposes.")
6246 (defconst org-link-escape-chars-browser
6247 '((?\ . "%20")) ; 32 for the SPC char
6248 "Association list of escapes for some characters problematic in links.
6249 This is the list that is used before handing over to the browser.")
6251 (defun org-link-escape (text &optional table)
6252 "Escape charaters in TEXT that are problematic for links."
6253 (setq table (or table org-link-escape-chars))
6254 (when text
6255 (let ((re (mapconcat (lambda (x) (regexp-quote
6256 (char-to-string (car x))))
6257 table "\\|")))
6258 (while (string-match re text)
6259 (setq text
6260 (replace-match
6261 (cdr (assoc (string-to-char (match-string 0 text))
6262 table))
6263 t t text)))
6264 text)))
6266 (defun org-link-unescape (text &optional table)
6267 "Reverse the action of `org-link-escape'."
6268 (setq table (or table org-link-escape-chars))
6269 (when text
6270 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
6271 table "\\|")))
6272 (while (string-match re text)
6273 (setq text
6274 (replace-match
6275 (char-to-string (car (rassoc (match-string 0 text) table)))
6276 t t text)))
6277 text)))
6279 (defun org-xor (a b)
6280 "Exclusive or."
6281 (if a (not b) b))
6283 (defun org-get-header (header)
6284 "Find a header field in the current buffer."
6285 (save-excursion
6286 (goto-char (point-min))
6287 (let ((case-fold-search t) s)
6288 (cond
6289 ((eq header 'from)
6290 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
6291 (setq s (match-string 1)))
6292 (while (string-match "\"" s)
6293 (setq s (replace-match "" t t s)))
6294 (if (string-match "[<(].*" s)
6295 (setq s (replace-match "" t t s))))
6296 ((eq header 'message-id)
6297 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
6298 (setq s (match-string 1))))
6299 ((eq header 'subject)
6300 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
6301 (setq s (match-string 1)))))
6302 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
6303 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
6304 s)))
6307 (defun org-fixup-message-id-for-http (s)
6308 "Replace special characters in a message id, so it can be used in an http query."
6309 (while (string-match "<" s)
6310 (setq s (replace-match "%3C" t t s)))
6311 (while (string-match ">" s)
6312 (setq s (replace-match "%3E" t t s)))
6313 (while (string-match "@" s)
6314 (setq s (replace-match "%40" t t s)))
6317 ;;;###autoload
6318 (defun org-insert-link-global ()
6319 "Insert a link like Org-mode does.
6320 This command can be called in any mode to insert a link in Org-mode syntax."
6321 (interactive)
6322 (org-load-modules-maybe)
6323 (org-run-like-in-org-mode 'org-insert-link))
6325 (defun org-insert-link (&optional complete-file link-location)
6326 "Insert a link. At the prompt, enter the link.
6328 Completion can be used to select a link previously stored with
6329 `org-store-link'. When the empty string is entered (i.e. if you just
6330 press RET at the prompt), the link defaults to the most recently
6331 stored link. As SPC triggers completion in the minibuffer, you need to
6332 use M-SPC or C-q SPC to force the insertion of a space character.
6334 You will also be prompted for a description, and if one is given, it will
6335 be displayed in the buffer instead of the link.
6337 If there is already a link at point, this command will allow you to edit link
6338 and description parts.
6340 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
6341 be selected using completion. The path to the file will be relative to the
6342 current directory if the file is in the current directory or a subdirectory.
6343 Otherwise, the link will be the absolute path as completed in the minibuffer
6344 \(i.e. normally ~/path/to/file).
6346 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
6347 the current directory or below. With three \\[universal-argument] prefixes, negate the meaning
6348 of `org-keep-stored-link-after-insertion'.
6350 If `org-make-link-description-function' is non-nil, this function will be
6351 called with the link target, and the result will be the default
6352 link description.
6354 If the LINK-LOCATION parameter is non-nil, this value will be
6355 used as the link location instead of reading one interactively."
6356 (interactive "P")
6357 (let* ((wcf (current-window-configuration))
6358 (region (if (org-region-active-p)
6359 (buffer-substring (region-beginning) (region-end))))
6360 (remove (and region (list (region-beginning) (region-end))))
6361 (desc region)
6362 tmphist ; byte-compile incorrectly complains about this
6363 (link link-location)
6364 entry file)
6365 (cond
6366 (link-location) ; specified by arg, just use it.
6367 ((org-in-regexp org-bracket-link-regexp 1)
6368 ;; We do have a link at point, and we are going to edit it.
6369 (setq remove (list (match-beginning 0) (match-end 0)))
6370 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
6371 (setq link (read-string "Link: "
6372 (org-link-unescape
6373 (org-match-string-no-properties 1)))))
6374 ((or (org-in-regexp org-angle-link-re)
6375 (org-in-regexp org-plain-link-re))
6376 ;; Convert to bracket link
6377 (setq remove (list (match-beginning 0) (match-end 0))
6378 link (read-string "Link: "
6379 (org-remove-angle-brackets (match-string 0)))))
6380 ((equal complete-file '(4))
6381 ;; Completing read for file names.
6382 (setq file (read-file-name "File: "))
6383 (let ((pwd (file-name-as-directory (expand-file-name ".")))
6384 (pwd1 (file-name-as-directory (abbreviate-file-name
6385 (expand-file-name ".")))))
6386 (cond
6387 ((equal complete-file '(16))
6388 (setq link (org-make-link
6389 "file:"
6390 (abbreviate-file-name (expand-file-name file)))))
6391 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
6392 (setq link (org-make-link "file:" (match-string 1 file))))
6393 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
6394 (expand-file-name file))
6395 (setq link (org-make-link
6396 "file:" (match-string 1 (expand-file-name file)))))
6397 (t (setq link (org-make-link "file:" file))))))
6399 ;; Read link, with completion for stored links.
6400 (with-output-to-temp-buffer "*Org Links*"
6401 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
6402 (when org-stored-links
6403 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
6404 (princ (mapconcat
6405 (lambda (x)
6406 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
6407 (reverse org-stored-links) "\n"))))
6408 (let ((cw (selected-window)))
6409 (select-window (get-buffer-window "*Org Links*"))
6410 (shrink-window-if-larger-than-buffer)
6411 (setq truncate-lines t)
6412 (select-window cw))
6413 ;; Fake a link history, containing the stored links.
6414 (setq tmphist (append (mapcar 'car org-stored-links)
6415 org-insert-link-history))
6416 (unwind-protect
6417 (setq link (org-completing-read
6418 "Link: "
6419 (append
6420 (mapcar (lambda (x) (list (concat (car x) ":")))
6421 (append org-link-abbrev-alist-local org-link-abbrev-alist))
6422 (mapcar (lambda (x) (list (concat x ":")))
6423 org-link-types))
6424 nil nil nil
6425 'tmphist
6426 (or (car (car org-stored-links)))))
6427 (set-window-configuration wcf)
6428 (kill-buffer "*Org Links*"))
6429 (setq entry (assoc link org-stored-links))
6430 (or entry (push link org-insert-link-history))
6431 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
6432 (not org-keep-stored-link-after-insertion))
6433 (setq org-stored-links (delq (assoc link org-stored-links)
6434 org-stored-links)))
6435 (setq desc (or desc (nth 1 entry)))))
6437 (if (string-match org-plain-link-re link)
6438 ;; URL-like link, normalize the use of angular brackets.
6439 (setq link (org-make-link (org-remove-angle-brackets link))))
6441 ;; Check if we are linking to the current file with a search option
6442 ;; If yes, simplify the link by using only the search option.
6443 (when (and buffer-file-name
6444 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
6445 (let* ((path (match-string 1 link))
6446 (case-fold-search nil)
6447 (search (match-string 2 link)))
6448 (save-match-data
6449 (if (equal (file-truename buffer-file-name) (file-truename path))
6450 ;; We are linking to this same file, with a search option
6451 (setq link search)))))
6453 ;; Check if we can/should use a relative path. If yes, simplify the link
6454 (when (string-match "\\<file:\\(.*\\)" link)
6455 (let* ((path (match-string 1 link))
6456 (origpath path)
6457 (case-fold-search nil))
6458 (cond
6459 ((eq org-link-file-path-type 'absolute)
6460 (setq path (abbreviate-file-name (expand-file-name path))))
6461 ((eq org-link-file-path-type 'noabbrev)
6462 (setq path (expand-file-name path)))
6463 ((eq org-link-file-path-type 'relative)
6464 (setq path (file-relative-name path)))
6466 (save-match-data
6467 (if (string-match (concat "^" (regexp-quote
6468 (file-name-as-directory
6469 (expand-file-name "."))))
6470 (expand-file-name path))
6471 ;; We are linking a file with relative path name.
6472 (setq path (substring (expand-file-name path)
6473 (match-end 0)))))))
6474 (setq link (concat "file:" path))
6475 (if (equal desc origpath)
6476 (setq desc path))))
6478 (if org-make-link-description-function
6479 (setq desc (funcall org-make-link-description-function link desc)))
6481 (setq desc (read-string "Description: " desc))
6482 (unless (string-match "\\S-" desc) (setq desc nil))
6483 (if remove (apply 'delete-region remove))
6484 (insert (org-make-link-string link desc))))
6486 (defun org-completing-read (&rest args)
6487 (let ((minibuffer-local-completion-map
6488 (copy-keymap minibuffer-local-completion-map)))
6489 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
6490 (apply 'completing-read args)))
6492 (defun org-extract-attributes (s)
6493 "Extract the attributes cookie from a string and set as text property."
6494 (let (a attr (start 0) key value)
6495 (save-match-data
6496 (when (string-match "{{\\([^}]+\\)}}$" s)
6497 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
6498 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
6499 (setq key (match-string 1 a) value (match-string 2 a)
6500 start (match-end 0)
6501 attr (plist-put attr (intern key) value))))
6502 (org-add-props s nil 'org-attributes attr))
6505 (defun org-attributes-to-string (plist)
6506 "Format a property list into an HTML attribute list."
6507 (let ((s "") key value)
6508 (while plist
6509 (setq key (pop plist) value (pop plist))
6510 (setq s (concat s " "(symbol-name key) "=\"" value "\"")))
6513 ;;; Opening/following a link
6515 (defvar org-link-search-failed nil)
6517 (defun org-next-link ()
6518 "Move forward to the next link.
6519 If the link is in hidden text, expose it."
6520 (interactive)
6521 (when (and org-link-search-failed (eq this-command last-command))
6522 (goto-char (point-min))
6523 (message "Link search wrapped back to beginning of buffer"))
6524 (setq org-link-search-failed nil)
6525 (let* ((pos (point))
6526 (ct (org-context))
6527 (a (assoc :link ct)))
6528 (if a (goto-char (nth 2 a)))
6529 (if (re-search-forward org-any-link-re nil t)
6530 (progn
6531 (goto-char (match-beginning 0))
6532 (if (org-invisible-p) (org-show-context)))
6533 (goto-char pos)
6534 (setq org-link-search-failed t)
6535 (error "No further link found"))))
6537 (defun org-previous-link ()
6538 "Move backward to the previous link.
6539 If the link is in hidden text, expose it."
6540 (interactive)
6541 (when (and org-link-search-failed (eq this-command last-command))
6542 (goto-char (point-max))
6543 (message "Link search wrapped back to end of buffer"))
6544 (setq org-link-search-failed nil)
6545 (let* ((pos (point))
6546 (ct (org-context))
6547 (a (assoc :link ct)))
6548 (if a (goto-char (nth 1 a)))
6549 (if (re-search-backward org-any-link-re nil t)
6550 (progn
6551 (goto-char (match-beginning 0))
6552 (if (org-invisible-p) (org-show-context)))
6553 (goto-char pos)
6554 (setq org-link-search-failed t)
6555 (error "No further link found"))))
6557 (defun org-find-file-at-mouse (ev)
6558 "Open file link or URL at mouse."
6559 (interactive "e")
6560 (mouse-set-point ev)
6561 (org-open-at-point 'in-emacs))
6563 (defun org-open-at-mouse (ev)
6564 "Open file link or URL at mouse."
6565 (interactive "e")
6566 (mouse-set-point ev)
6567 (org-open-at-point))
6569 (defvar org-window-config-before-follow-link nil
6570 "The window configuration before following a link.
6571 This is saved in case the need arises to restore it.")
6573 (defvar org-open-link-marker (make-marker)
6574 "Marker pointing to the location where `org-open-at-point; was called.")
6576 ;;;###autoload
6577 (defun org-open-at-point-global ()
6578 "Follow a link like Org-mode does.
6579 This command can be called in any mode to follow a link that has
6580 Org-mode syntax."
6581 (interactive)
6582 (org-run-like-in-org-mode 'org-open-at-point))
6584 ;;;###autoload
6585 (defun org-open-link-from-string (s &optional arg)
6586 "Open a link in the string S, as if it was in Org-mode."
6587 (interactive "sLink: \nP")
6588 (with-temp-buffer
6589 (let ((org-inhibit-startup t))
6590 (org-mode)
6591 (insert s)
6592 (goto-char (point-min))
6593 (org-open-at-point arg))))
6595 (defun org-open-at-point (&optional in-emacs)
6596 "Open link at or after point.
6597 If there is no link at point, this function will search forward up to
6598 the end of the current subtree.
6599 Normally, files will be opened by an appropriate application. If the
6600 optional argument IN-EMACS is non-nil, Emacs will visit the file."
6601 (interactive "P")
6602 (org-load-modules-maybe)
6603 (move-marker org-open-link-marker (point))
6604 (setq org-window-config-before-follow-link (current-window-configuration))
6605 (org-remove-occur-highlights nil nil t)
6606 (if (org-at-timestamp-p t)
6607 (org-follow-timestamp-link)
6608 (let (type path link line search (pos (point)))
6609 (catch 'match
6610 (save-excursion
6611 (skip-chars-forward "^]\n\r")
6612 (when (org-in-regexp org-bracket-link-regexp)
6613 (setq link (org-extract-attributes
6614 (org-link-unescape (org-match-string-no-properties 1))))
6615 (while (string-match " *\n *" link)
6616 (setq link (replace-match " " t t link)))
6617 (setq link (org-link-expand-abbrev link))
6618 (cond
6619 ((or (file-name-absolute-p link)
6620 (string-match "^\\.\\.?/" link))
6621 (setq type "file" path link))
6622 ((string-match org-link-re-with-space2 link)
6623 (setq type (match-string 1 link) path (match-string 2 link)))
6624 (t (setq type "thisfile" path link)))
6625 (throw 'match t)))
6627 (when (get-text-property (point) 'org-linked-text)
6628 (setq type "thisfile"
6629 pos (if (get-text-property (1+ (point)) 'org-linked-text)
6630 (1+ (point)) (point))
6631 path (buffer-substring
6632 (previous-single-property-change pos 'org-linked-text)
6633 (next-single-property-change pos 'org-linked-text)))
6634 (throw 'match t))
6636 (save-excursion
6637 (when (or (org-in-regexp org-angle-link-re)
6638 (org-in-regexp org-plain-link-re))
6639 (setq type (match-string 1) path (match-string 2))
6640 (throw 'match t)))
6641 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
6642 (setq type "tree-match"
6643 path (match-string 1))
6644 (throw 'match t))
6645 (save-excursion
6646 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
6647 (setq type "tags"
6648 path (match-string 1))
6649 (while (string-match ":" path)
6650 (setq path (replace-match "+" t t path)))
6651 (throw 'match t))))
6652 (unless path
6653 (error "No link found"))
6654 ;; Remove any trailing spaces in path
6655 (if (string-match " +\\'" path)
6656 (setq path (replace-match "" t t path)))
6658 (cond
6660 ((assoc type org-link-protocols)
6661 (funcall (nth 1 (assoc type org-link-protocols)) path))
6663 ((equal type "mailto")
6664 (let ((cmd (car org-link-mailto-program))
6665 (args (cdr org-link-mailto-program)) args1
6666 (address path) (subject "") a)
6667 (if (string-match "\\(.*\\)::\\(.*\\)" path)
6668 (setq address (match-string 1 path)
6669 subject (org-link-escape (match-string 2 path))))
6670 (while args
6671 (cond
6672 ((not (stringp (car args))) (push (pop args) args1))
6673 (t (setq a (pop args))
6674 (if (string-match "%a" a)
6675 (setq a (replace-match address t t a)))
6676 (if (string-match "%s" a)
6677 (setq a (replace-match subject t t a)))
6678 (push a args1))))
6679 (apply cmd (nreverse args1))))
6681 ((member type '("http" "https" "ftp" "news"))
6682 (browse-url (concat type ":" (org-link-escape
6683 path org-link-escape-chars-browser))))
6685 ((member type '("message"))
6686 (browse-url (concat type ":" path)))
6688 ((string= type "tags")
6689 (org-tags-view in-emacs path))
6690 ((string= type "thisfile")
6691 (if in-emacs
6692 (switch-to-buffer-other-window
6693 (org-get-buffer-for-internal-link (current-buffer)))
6694 (org-mark-ring-push))
6695 (let ((cmd `(org-link-search
6696 ,path
6697 ,(cond ((equal in-emacs '(4)) 'occur)
6698 ((equal in-emacs '(16)) 'org-occur)
6699 (t nil))
6700 ,pos)))
6701 (condition-case nil (eval cmd)
6702 (error (progn (widen) (eval cmd))))))
6704 ((string= type "tree-match")
6705 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
6707 ((string= type "file")
6708 (if (string-match "::\\([0-9]+\\)\\'" path)
6709 (setq line (string-to-number (match-string 1 path))
6710 path (substring path 0 (match-beginning 0)))
6711 (if (string-match "::\\(.+\\)\\'" path)
6712 (setq search (match-string 1 path)
6713 path (substring path 0 (match-beginning 0)))))
6714 (if (string-match "[*?{]" (file-name-nondirectory path))
6715 (dired path)
6716 (org-open-file path in-emacs line search)))
6718 ((string= type "news")
6719 (require 'org-gnus)
6720 (org-gnus-follow-link path))
6722 ((string= type "shell")
6723 (let ((cmd path))
6724 (if (or (not org-confirm-shell-link-function)
6725 (funcall org-confirm-shell-link-function
6726 (format "Execute \"%s\" in shell? "
6727 (org-add-props cmd nil
6728 'face 'org-warning))))
6729 (progn
6730 (message "Executing %s" cmd)
6731 (shell-command cmd))
6732 (error "Abort"))))
6734 ((string= type "elisp")
6735 (let ((cmd path))
6736 (if (or (not org-confirm-elisp-link-function)
6737 (funcall org-confirm-elisp-link-function
6738 (format "Execute \"%s\" as elisp? "
6739 (org-add-props cmd nil
6740 'face 'org-warning))))
6741 (message "%s => %s" cmd (eval (read cmd)))
6742 (error "Abort"))))
6745 (browse-url-at-point)))))
6746 (move-marker org-open-link-marker nil)
6747 (run-hook-with-args 'org-follow-link-hook))
6749 ;;;; Time estimates
6751 (defun org-get-effort (&optional pom)
6752 "Get the effort estimate for the current entry."
6753 (org-entry-get pom org-effort-property))
6755 ;;; File search
6757 (defvar org-create-file-search-functions nil
6758 "List of functions to construct the right search string for a file link.
6759 These functions are called in turn with point at the location to
6760 which the link should point.
6762 A function in the hook should first test if it would like to
6763 handle this file type, for example by checking the major-mode or
6764 the file extension. If it decides not to handle this file, it
6765 should just return nil to give other functions a chance. If it
6766 does handle the file, it must return the search string to be used
6767 when following the link. The search string will be part of the
6768 file link, given after a double colon, and `org-open-at-point'
6769 will automatically search for it. If special measures must be
6770 taken to make the search successful, another function should be
6771 added to the companion hook `org-execute-file-search-functions',
6772 which see.
6774 A function in this hook may also use `setq' to set the variable
6775 `description' to provide a suggestion for the descriptive text to
6776 be used for this link when it gets inserted into an Org-mode
6777 buffer with \\[org-insert-link].")
6779 (defvar org-execute-file-search-functions nil
6780 "List of functions to execute a file search triggered by a link.
6782 Functions added to this hook must accept a single argument, the
6783 search string that was part of the file link, the part after the
6784 double colon. The function must first check if it would like to
6785 handle this search, for example by checking the major-mode or the
6786 file extension. If it decides not to handle this search, it
6787 should just return nil to give other functions a chance. If it
6788 does handle the search, it must return a non-nil value to keep
6789 other functions from trying.
6791 Each function can access the current prefix argument through the
6792 variable `current-prefix-argument'. Note that a single prefix is
6793 used to force opening a link in Emacs, so it may be good to only
6794 use a numeric or double prefix to guide the search function.
6796 In case this is needed, a function in this hook can also restore
6797 the window configuration before `org-open-at-point' was called using:
6799 (set-window-configuration org-window-config-before-follow-link)")
6801 (defun org-link-search (s &optional type avoid-pos)
6802 "Search for a link search option.
6803 If S is surrounded by forward slashes, it is interpreted as a
6804 regular expression. In org-mode files, this will create an `org-occur'
6805 sparse tree. In ordinary files, `occur' will be used to list matches.
6806 If the current buffer is in `dired-mode', grep will be used to search
6807 in all files. If AVOID-POS is given, ignore matches near that position."
6808 (let ((case-fold-search t)
6809 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
6810 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
6811 (append '(("") (" ") ("\t") ("\n"))
6812 org-emphasis-alist)
6813 "\\|") "\\)"))
6814 (pos (point))
6815 (pre nil) (post nil)
6816 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
6817 (cond
6818 ;; First check if there are any special
6819 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
6820 ;; Now try the builtin stuff
6821 ((save-excursion
6822 (goto-char (point-min))
6823 (and
6824 (re-search-forward
6825 (concat "<<" (regexp-quote s0) ">>") nil t)
6826 (setq type 'dedicated
6827 pos (match-beginning 0))))
6828 ;; There is an exact target for this
6829 (goto-char pos))
6830 ((string-match "^/\\(.*\\)/$" s)
6831 ;; A regular expression
6832 (cond
6833 ((org-mode-p)
6834 (org-occur (match-string 1 s)))
6835 ;;((eq major-mode 'dired-mode)
6836 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
6837 (t (org-do-occur (match-string 1 s)))))
6839 ;; A normal search strings
6840 (when (equal (string-to-char s) ?*)
6841 ;; Anchor on headlines, post may include tags.
6842 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
6843 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
6844 s (substring s 1)))
6845 (remove-text-properties
6846 0 (length s)
6847 '(face nil mouse-face nil keymap nil fontified nil) s)
6848 ;; Make a series of regular expressions to find a match
6849 (setq words (org-split-string s "[ \n\r\t]+")
6851 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
6852 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
6853 "\\)" markers)
6854 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
6855 re2a (concat "[ \t\r\n]" re2a_)
6856 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
6857 re4 (concat "[^a-zA-Z_]" re4_)
6859 re1 (concat pre re2 post)
6860 re3 (concat pre (if pre re4_ re4) post)
6861 re5 (concat pre ".*" re4)
6862 re2 (concat pre re2)
6863 re2a (concat pre (if pre re2a_ re2a))
6864 re4 (concat pre (if pre re4_ re4))
6865 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
6866 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
6867 re5 "\\)"
6869 (cond
6870 ((eq type 'org-occur) (org-occur reall))
6871 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
6872 (t (goto-char (point-min))
6873 (setq type 'fuzzy)
6874 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
6875 (org-search-not-self 1 re1 nil t)
6876 (org-search-not-self 1 re2 nil t)
6877 (org-search-not-self 1 re2a nil t)
6878 (org-search-not-self 1 re3 nil t)
6879 (org-search-not-self 1 re4 nil t)
6880 (org-search-not-self 1 re5 nil t)
6882 (goto-char (match-beginning 1))
6883 (goto-char pos)
6884 (error "No match")))))
6886 ;; Normal string-search
6887 (goto-char (point-min))
6888 (if (search-forward s nil t)
6889 (goto-char (match-beginning 0))
6890 (error "No match"))))
6891 (and (org-mode-p) (org-show-context 'link-search))
6892 type))
6894 (defun org-search-not-self (group &rest args)
6895 "Execute `re-search-forward', but only accept matches that do not
6896 enclose the position of `org-open-link-marker'."
6897 (let ((m org-open-link-marker))
6898 (catch 'exit
6899 (while (apply 're-search-forward args)
6900 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
6901 (goto-char (match-end group))
6902 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
6903 (> (match-beginning 0) (marker-position m))
6904 (< (match-end 0) (marker-position m)))
6905 (save-match-data
6906 (or (not (org-in-regexp
6907 org-bracket-link-analytic-regexp 1))
6908 (not (match-end 4)) ; no description
6909 (and (<= (match-beginning 4) (point))
6910 (>= (match-end 4) (point))))))
6911 (throw 'exit (point))))))))
6913 (defun org-get-buffer-for-internal-link (buffer)
6914 "Return a buffer to be used for displaying the link target of internal links."
6915 (cond
6916 ((not org-display-internal-link-with-indirect-buffer)
6917 buffer)
6918 ((string-match "(Clone)$" (buffer-name buffer))
6919 (message "Buffer is already a clone, not making another one")
6920 ;; we also do not modify visibility in this case
6921 buffer)
6922 (t ; make a new indirect buffer for displaying the link
6923 (let* ((bn (buffer-name buffer))
6924 (ibn (concat bn "(Clone)"))
6925 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
6926 (with-current-buffer ib (org-overview))
6927 ib))))
6929 (defun org-do-occur (regexp &optional cleanup)
6930 "Call the Emacs command `occur'.
6931 If CLEANUP is non-nil, remove the printout of the regular expression
6932 in the *Occur* buffer. This is useful if the regex is long and not useful
6933 to read."
6934 (occur regexp)
6935 (when cleanup
6936 (let ((cwin (selected-window)) win beg end)
6937 (when (setq win (get-buffer-window "*Occur*"))
6938 (select-window win))
6939 (goto-char (point-min))
6940 (when (re-search-forward "match[a-z]+" nil t)
6941 (setq beg (match-end 0))
6942 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
6943 (setq end (1- (match-beginning 0)))))
6944 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
6945 (goto-char (point-min))
6946 (select-window cwin))))
6948 ;;; The mark ring for links jumps
6950 (defvar org-mark-ring nil
6951 "Mark ring for positions before jumps in Org-mode.")
6952 (defvar org-mark-ring-last-goto nil
6953 "Last position in the mark ring used to go back.")
6954 ;; Fill and close the ring
6955 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
6956 (loop for i from 1 to org-mark-ring-length do
6957 (push (make-marker) org-mark-ring))
6958 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
6959 org-mark-ring)
6961 (defun org-mark-ring-push (&optional pos buffer)
6962 "Put the current position or POS into the mark ring and rotate it."
6963 (interactive)
6964 (setq pos (or pos (point)))
6965 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
6966 (move-marker (car org-mark-ring)
6967 (or pos (point))
6968 (or buffer (current-buffer)))
6969 (message "%s"
6970 (substitute-command-keys
6971 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
6973 (defun org-mark-ring-goto (&optional n)
6974 "Jump to the previous position in the mark ring.
6975 With prefix arg N, jump back that many stored positions. When
6976 called several times in succession, walk through the entire ring.
6977 Org-mode commands jumping to a different position in the current file,
6978 or to another Org-mode file, automatically push the old position
6979 onto the ring."
6980 (interactive "p")
6981 (let (p m)
6982 (if (eq last-command this-command)
6983 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
6984 (setq p org-mark-ring))
6985 (setq org-mark-ring-last-goto p)
6986 (setq m (car p))
6987 (switch-to-buffer (marker-buffer m))
6988 (goto-char m)
6989 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
6991 (defun org-remove-angle-brackets (s)
6992 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
6993 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
6995 (defun org-add-angle-brackets (s)
6996 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
6997 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
6999 (defun org-remove-double-quotes (s)
7000 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
7001 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
7004 ;;; Following specific links
7006 (defun org-follow-timestamp-link ()
7007 (cond
7008 ((org-at-date-range-p t)
7009 (let ((org-agenda-start-on-weekday)
7010 (t1 (match-string 1))
7011 (t2 (match-string 2)))
7012 (setq t1 (time-to-days (org-time-string-to-time t1))
7013 t2 (time-to-days (org-time-string-to-time t2)))
7014 (org-agenda-list nil t1 (1+ (- t2 t1)))))
7015 ((org-at-timestamp-p t)
7016 (org-agenda-list nil (time-to-days (org-time-string-to-time
7017 (substring (match-string 1) 0 10)))
7019 (t (error "This should not happen"))))
7022 ;;; Following file links
7023 (defvar org-wait nil)
7024 (defun org-open-file (path &optional in-emacs line search)
7025 "Open the file at PATH.
7026 First, this expands any special file name abbreviations. Then the
7027 configuration variable `org-file-apps' is checked if it contains an
7028 entry for this file type, and if yes, the corresponding command is launched.
7029 If no application is found, Emacs simply visits the file.
7030 With optional argument IN-EMACS, Emacs will visit the file.
7031 Optional LINE specifies a line to go to, optional SEARCH a string to
7032 search for. If LINE or SEARCH is given, the file will always be
7033 opened in Emacs.
7034 If the file does not exist, an error is thrown."
7035 (setq in-emacs (or in-emacs line search))
7036 (let* ((file (if (equal path "")
7037 buffer-file-name
7038 (substitute-in-file-name (expand-file-name path))))
7039 (apps (append org-file-apps (org-default-apps)))
7040 (remp (and (assq 'remote apps) (org-file-remote-p file)))
7041 (dirp (if remp nil (file-directory-p file)))
7042 (file (if (and dirp org-open-directory-means-index-dot-org)
7043 (concat (file-name-as-directory file) "index.org")
7044 file))
7045 (a-m-a-p (assq 'auto-mode apps))
7046 (dfile (downcase file))
7047 (old-buffer (current-buffer))
7048 (old-pos (point))
7049 (old-mode major-mode)
7050 ext cmd)
7051 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7052 (setq ext (match-string 1 dfile))
7053 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7054 (setq ext (match-string 1 dfile))))
7055 (if in-emacs
7056 (setq cmd 'emacs)
7057 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
7058 (and dirp (cdr (assoc 'directory apps)))
7059 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
7060 'string-match)
7061 (cdr (assoc ext apps))
7062 (cdr (assoc t apps)))))
7063 (when (eq cmd 'default)
7064 (setq cmd (cdr (assoc t apps))))
7065 (when (eq cmd 'mailcap)
7066 (require 'mailcap)
7067 (mailcap-parse-mailcaps)
7068 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7069 (command (mailcap-mime-info mime-type)))
7070 (if (stringp command)
7071 (setq cmd command)
7072 (setq cmd 'emacs))))
7073 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
7074 (not (file-exists-p file))
7075 (not org-open-non-existing-files))
7076 (error "No such file: %s" file))
7077 (cond
7078 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7079 ;; Remove quotes around the file name - we'll use shell-quote-argument.
7080 (while (string-match "['\"]%s['\"]" cmd)
7081 (setq cmd (replace-match "%s" t t cmd)))
7082 (while (string-match "%s" cmd)
7083 (setq cmd (replace-match
7084 (save-match-data
7085 (shell-quote-argument
7086 (convert-standard-filename file)))
7087 t t cmd)))
7088 (save-window-excursion
7089 (start-process-shell-command cmd nil cmd)
7090 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
7092 ((or (stringp cmd)
7093 (eq cmd 'emacs))
7094 (funcall (cdr (assq 'file org-link-frame-setup)) file)
7095 (widen)
7096 (if line (goto-line line)
7097 (if search (org-link-search search))))
7098 ((consp cmd)
7099 (let ((file (convert-standard-filename file)))
7100 (eval cmd)))
7101 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7102 (and (org-mode-p) (eq old-mode 'org-mode)
7103 (or (not (equal old-buffer (current-buffer)))
7104 (not (equal old-pos (point))))
7105 (org-mark-ring-push old-pos old-buffer))))
7107 (defun org-default-apps ()
7108 "Return the default applications for this operating system."
7109 (cond
7110 ((eq system-type 'darwin)
7111 org-file-apps-defaults-macosx)
7112 ((eq system-type 'windows-nt)
7113 org-file-apps-defaults-windowsnt)
7114 (t org-file-apps-defaults-gnu)))
7116 (defun org-apps-regexp-alist (list &optional add-auto-mode)
7117 "Convert extensions to regular expressions in the cars of LIST.
7118 Also, weed out any non-string entries, because the return value is used
7119 only for regexp matching.
7120 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
7121 point to the symbol `emacs', indicating that the file should
7122 be opened in Emacs."
7123 (append
7124 (delq nil
7125 (mapcar (lambda (x)
7126 (if (not (stringp (car x)))
7128 (if (string-match "\\W" (car x))
7130 (cons (concat "\\." (car x) "\\'") (cdr x)))))
7131 list))
7132 (if add-auto-mode
7133 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
7135 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
7136 (defun org-file-remote-p (file)
7137 "Test whether FILE specifies a location on a remote system.
7138 Return non-nil if the location is indeed remote.
7140 For example, the filename \"/user@host:/foo\" specifies a location
7141 on the system \"/user@host:\"."
7142 (cond ((fboundp 'file-remote-p)
7143 (file-remote-p file))
7144 ((fboundp 'tramp-handle-file-remote-p)
7145 (tramp-handle-file-remote-p file))
7146 ((and (boundp 'ange-ftp-name-format)
7147 (string-match (car ange-ftp-name-format) file))
7149 (t nil)))
7152 ;;;; Refiling
7154 (defun org-get-org-file ()
7155 "Read a filename, with default directory `org-directory'."
7156 (let ((default (or org-default-notes-file remember-data-file)))
7157 (read-file-name (format "File name [%s]: " default)
7158 (file-name-as-directory org-directory)
7159 default)))
7161 (defun org-notes-order-reversed-p ()
7162 "Check if the current file should receive notes in reversed order."
7163 (cond
7164 ((not org-reverse-note-order) nil)
7165 ((eq t org-reverse-note-order) t)
7166 ((not (listp org-reverse-note-order)) nil)
7167 (t (catch 'exit
7168 (let ((all org-reverse-note-order)
7169 entry)
7170 (while (setq entry (pop all))
7171 (if (string-match (car entry) buffer-file-name)
7172 (throw 'exit (cdr entry))))
7173 nil)))))
7175 (defvar org-refile-target-table nil
7176 "The list of refile targets, created by `org-refile'.")
7178 (defvar org-agenda-new-buffers nil
7179 "Buffers created to visit agenda files.")
7181 (defun org-get-refile-targets (&optional default-buffer)
7182 "Produce a table with refile targets."
7183 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
7184 targets txt re files f desc descre)
7185 (with-current-buffer (or default-buffer (current-buffer))
7186 (while (setq entry (pop entries))
7187 (setq files (car entry) desc (cdr entry))
7188 (cond
7189 ((null files) (setq files (list (current-buffer))))
7190 ((eq files 'org-agenda-files)
7191 (setq files (org-agenda-files 'unrestricted)))
7192 ((and (symbolp files) (fboundp files))
7193 (setq files (funcall files)))
7194 ((and (symbolp files) (boundp files))
7195 (setq files (symbol-value files))))
7196 (if (stringp files) (setq files (list files)))
7197 (cond
7198 ((eq (car desc) :tag)
7199 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
7200 ((eq (car desc) :todo)
7201 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
7202 ((eq (car desc) :regexp)
7203 (setq descre (cdr desc)))
7204 ((eq (car desc) :level)
7205 (setq descre (concat "^\\*\\{" (number-to-string
7206 (if org-odd-levels-only
7207 (1- (* 2 (cdr desc)))
7208 (cdr desc)))
7209 "\\}[ \t]")))
7210 ((eq (car desc) :maxlevel)
7211 (setq descre (concat "^\\*\\{1," (number-to-string
7212 (if org-odd-levels-only
7213 (1- (* 2 (cdr desc)))
7214 (cdr desc)))
7215 "\\}[ \t]")))
7216 (t (error "Bad refiling target description %s" desc)))
7217 (while (setq f (pop files))
7218 (save-excursion
7219 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
7220 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
7221 (save-excursion
7222 (save-restriction
7223 (widen)
7224 (goto-char (point-min))
7225 (while (re-search-forward descre nil t)
7226 (goto-char (point-at-bol))
7227 (when (looking-at org-complex-heading-regexp)
7228 (setq txt (org-link-display-format (match-string 4))
7229 re (concat "^" (regexp-quote
7230 (buffer-substring (match-beginning 1)
7231 (match-end 4)))))
7232 (if (match-end 5) (setq re (concat re "[ \t]+"
7233 (regexp-quote
7234 (match-string 5)))))
7235 (setq re (concat re "[ \t]*$"))
7236 (when org-refile-use-outline-path
7237 (setq txt (mapconcat 'org-protect-slash
7238 (append
7239 (if (eq org-refile-use-outline-path 'file)
7240 (list (file-name-nondirectory
7241 (buffer-file-name (buffer-base-buffer))))
7242 (if (eq org-refile-use-outline-path 'full-file-path)
7243 (list (buffer-file-name (buffer-base-buffer)))))
7244 (org-get-outline-path)
7245 (list txt))
7246 "/")))
7247 (push (list txt f re (point)) targets))
7248 (goto-char (point-at-eol))))))))
7249 (nreverse targets))))
7251 (defun org-protect-slash (s)
7252 (while (string-match "/" s)
7253 (setq s (replace-match "\\" t t s)))
7256 (defun org-get-outline-path ()
7257 "Return the outline path to the current entry, as a list."
7258 (let (rtn)
7259 (save-excursion
7260 (while (org-up-heading-safe)
7261 (when (looking-at org-complex-heading-regexp)
7262 (push (org-match-string-no-properties 4) rtn)))
7263 rtn)))
7265 (defvar org-refile-history nil
7266 "History for refiling operations.")
7268 (defun org-refile (&optional goto default-buffer)
7269 "Move the entry at point to another heading.
7270 The list of target headings is compiled using the information in
7271 `org-refile-targets', which see. This list is created before each use
7272 and will therefore always be up-to-date.
7274 At the target location, the entry is filed as a subitem of the target heading.
7275 Depending on `org-reverse-note-order', the new subitem will either be the
7276 first or the last subitem.
7278 With prefix arg GOTO, the command will only visit the target location,
7279 not actually move anything.
7280 With a double prefix `C-u C-u', go to the location where the last refiling
7281 operation has put the subtree."
7282 (interactive "P")
7283 (let* ((cbuf (current-buffer))
7284 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7285 pos it nbuf file re level reversed)
7286 (if (equal goto '(16))
7287 (org-refile-goto-last-stored)
7288 (when (setq it (org-refile-get-location
7289 (if goto "Goto: " "Refile to: ") default-buffer))
7290 (setq file (nth 1 it)
7291 re (nth 2 it)
7292 pos (nth 3 it))
7293 (setq nbuf (or (find-buffer-visiting file)
7294 (find-file-noselect file)))
7295 (if goto
7296 (progn
7297 (switch-to-buffer nbuf)
7298 (goto-char pos)
7299 (org-show-context 'org-goto))
7300 (org-copy-subtree 1 nil t)
7301 (save-excursion
7302 (set-buffer (setq nbuf (or (find-buffer-visiting file)
7303 (find-file-noselect file))))
7304 (setq reversed (org-notes-order-reversed-p))
7305 (save-excursion
7306 (save-restriction
7307 (widen)
7308 (goto-char pos)
7309 (looking-at outline-regexp)
7310 (setq level (org-get-valid-level (funcall outline-level) 1))
7311 (goto-char
7312 (if reversed
7313 (or (outline-next-heading) (point-max))
7314 (or (save-excursion (outline-get-next-sibling))
7315 (org-end-of-subtree t t)
7316 (point-max))))
7317 (if (not (bolp)) (newline))
7318 (bookmark-set "org-refile-last-stored")
7319 (org-paste-subtree level))))
7320 (org-cut-subtree)
7321 (setq org-markers-to-move nil)
7322 (message "Entry refiled to \"%s\"" (car it)))))))
7324 (defun org-refile-goto-last-stored ()
7325 "Go to the location where the last refile was stored."
7326 (interactive)
7327 (bookmark-jump "org-refile-last-stored")
7328 (message "This is the location of the last refile"))
7330 (defun org-refile-get-location (&optional prompt default-buffer)
7331 "Prompt the user for a refile location, using PROMPT."
7332 (let ((org-refile-targets org-refile-targets)
7333 (org-refile-use-outline-path org-refile-use-outline-path))
7334 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
7335 (unless org-refile-target-table
7336 (error "No refile targets"))
7337 (let* ((cbuf (current-buffer))
7338 (cfunc (if org-refile-use-outline-path
7339 'org-olpath-completing-read
7340 'completing-read))
7341 (extra (if org-refile-use-outline-path "/" ""))
7342 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7343 (fname (and filename (file-truename filename)))
7344 (tbl (mapcar
7345 (lambda (x)
7346 (if (not (equal fname (file-truename (nth 1 x))))
7347 (cons (concat (car x) extra " ("
7348 (file-name-nondirectory (nth 1 x)) ")")
7349 (cdr x))
7350 (cons (concat (car x) extra) (cdr x))))
7351 org-refile-target-table))
7352 (completion-ignore-case t))
7353 (assoc (funcall cfunc prompt tbl nil t nil 'org-refile-history)
7354 tbl)))
7356 (defun org-olpath-completing-read (prompt collection &rest args)
7357 "Read an outline path like a file name."
7358 (let ((thetable collection))
7359 (apply
7360 'completing-read prompt
7361 (lambda (string predicate &optional flag)
7362 (let (rtn r s f (l (length string)))
7363 (cond
7364 ((eq flag nil)
7365 ;; try completion
7366 (try-completion string thetable))
7367 ((eq flag t)
7368 ;; all-completions
7369 (setq rtn (all-completions string thetable predicate))
7370 (mapcar
7371 (lambda (x)
7372 (setq r (substring x l))
7373 (if (string-match " ([^)]*)$" x)
7374 (setq f (match-string 0 x))
7375 (setq f ""))
7376 (if (string-match "/" r)
7377 (concat string (substring r 0 (match-end 0)) f)
7379 rtn))
7380 ((eq flag 'lambda)
7381 ;; exact match?
7382 (assoc string thetable)))
7384 args)))
7386 ;;;; Dynamic blocks
7388 (defun org-find-dblock (name)
7389 "Find the first dynamic block with name NAME in the buffer.
7390 If not found, stay at current position and return nil."
7391 (let (pos)
7392 (save-excursion
7393 (goto-char (point-min))
7394 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
7395 nil t)
7396 (match-beginning 0))))
7397 (if pos (goto-char pos))
7398 pos))
7400 (defconst org-dblock-start-re
7401 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
7402 "Matches the startline of a dynamic block, with parameters.")
7404 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
7405 "Matches the end of a dyhamic block.")
7407 (defun org-create-dblock (plist)
7408 "Create a dynamic block section, with parameters taken from PLIST.
7409 PLIST must containe a :name entry which is used as name of the block."
7410 (unless (bolp) (newline))
7411 (let ((name (plist-get plist :name)))
7412 (insert "#+BEGIN: " name)
7413 (while plist
7414 (if (eq (car plist) :name)
7415 (setq plist (cddr plist))
7416 (insert " " (prin1-to-string (pop plist)))))
7417 (insert "\n\n#+END:\n")
7418 (beginning-of-line -2)))
7420 (defun org-prepare-dblock ()
7421 "Prepare dynamic block for refresh.
7422 This empties the block, puts the cursor at the insert position and returns
7423 the property list including an extra property :name with the block name."
7424 (unless (looking-at org-dblock-start-re)
7425 (error "Not at a dynamic block"))
7426 (let* ((begdel (1+ (match-end 0)))
7427 (name (org-no-properties (match-string 1)))
7428 (params (append (list :name name)
7429 (read (concat "(" (match-string 3) ")")))))
7430 (unless (re-search-forward org-dblock-end-re nil t)
7431 (error "Dynamic block not terminated"))
7432 (setq params
7433 (append params
7434 (list :content (buffer-substring
7435 begdel (match-beginning 0)))))
7436 (delete-region begdel (match-beginning 0))
7437 (goto-char begdel)
7438 (open-line 1)
7439 params))
7441 (defun org-map-dblocks (&optional command)
7442 "Apply COMMAND to all dynamic blocks in the current buffer.
7443 If COMMAND is not given, use `org-update-dblock'."
7444 (let ((cmd (or command 'org-update-dblock))
7445 pos)
7446 (save-excursion
7447 (goto-char (point-min))
7448 (while (re-search-forward org-dblock-start-re nil t)
7449 (goto-char (setq pos (match-beginning 0)))
7450 (condition-case nil
7451 (funcall cmd)
7452 (error (message "Error during update of dynamic block")))
7453 (goto-char pos)
7454 (unless (re-search-forward org-dblock-end-re nil t)
7455 (error "Dynamic block not terminated"))))))
7457 (defun org-dblock-update (&optional arg)
7458 "User command for updating dynamic blocks.
7459 Update the dynamic block at point. With prefix ARG, update all dynamic
7460 blocks in the buffer."
7461 (interactive "P")
7462 (if arg
7463 (org-update-all-dblocks)
7464 (or (looking-at org-dblock-start-re)
7465 (org-beginning-of-dblock))
7466 (org-update-dblock)))
7468 (defun org-update-dblock ()
7469 "Update the dynamic block at point
7470 This means to empty the block, parse for parameters and then call
7471 the correct writing function."
7472 (save-window-excursion
7473 (let* ((pos (point))
7474 (line (org-current-line))
7475 (params (org-prepare-dblock))
7476 (name (plist-get params :name))
7477 (cmd (intern (concat "org-dblock-write:" name))))
7478 (message "Updating dynamic block `%s' at line %d..." name line)
7479 (funcall cmd params)
7480 (message "Updating dynamic block `%s' at line %d...done" name line)
7481 (goto-char pos))))
7483 (defun org-beginning-of-dblock ()
7484 "Find the beginning of the dynamic block at point.
7485 Error if there is no scuh block at point."
7486 (let ((pos (point))
7487 beg)
7488 (end-of-line 1)
7489 (if (and (re-search-backward org-dblock-start-re nil t)
7490 (setq beg (match-beginning 0))
7491 (re-search-forward org-dblock-end-re nil t)
7492 (> (match-end 0) pos))
7493 (goto-char beg)
7494 (goto-char pos)
7495 (error "Not in a dynamic block"))))
7497 (defun org-update-all-dblocks ()
7498 "Update all dynamic blocks in the buffer.
7499 This function can be used in a hook."
7500 (when (org-mode-p)
7501 (org-map-dblocks 'org-update-dblock)))
7504 ;;;; Completion
7506 (defconst org-additional-option-like-keywords
7507 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
7508 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
7509 "BEGIN_EXAMPLE" "END_EXAMPLE"
7510 "BEGIN_QUOTE" "END_QUOTE"
7511 "BEGIN_VERSE" "END_VERSE"
7512 "BEGIN_SRC" "END_SRC"))
7514 (defcustom org-structure-template-alist
7516 ("s" "#+begin_src ?\n\n#+end_src"
7517 "<src lang=\"?\">\n\n</src>")
7518 ("e" "#+begin_example\n?\n#+end_example"
7519 "<example>\n?\n</example>")
7520 ("q" "#+begin_quote\n?\n#+end_quote"
7521 "<quote>\n?\n</quote>")
7522 ("v" "#+begin_verse\n?\n#+end_verse"
7523 "<verse>\n?\n/verse>")
7524 ("l" "#+begin_latex\n?\n#+end_latex"
7525 "<literal style=\"latex\">\n?\n</literal>")
7526 ("L" "#+latex: "
7527 "<literal style=\"latex\">?</literal>")
7528 ("h" "#+begin_html\n?\n#+end_html"
7529 "<literal style=\"html\">\n?\n</literal>")
7530 ("H" "#+html: "
7531 "<literal style=\"html\">?</literal>")
7532 ("a" "#+begin_ascii\n?\n#+end_ascii")
7533 ("A" "#+ascii: ")
7534 ("i" "#+include %file ?"
7535 "<include file=%file markup=\"?\">")
7537 "Structure completion elements.
7538 This is a list of abbreviation keys and values. The value gets inserted
7539 it you type @samp{.} followed by the key and then the completion key,
7540 usually `M-TAB'. %file will be replaced by a file name after prompting
7541 for the file uning completion.
7542 There are two templates for each key, the first uses the original Org syntax,
7543 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
7544 the default when the /org-mtags.el/ module has been loaded. See also the
7545 variable `org-mtags-prefere-muse-templates'.
7546 This is an experimental feature, it is undecided if it is going to stay in."
7547 :group 'org-completion
7548 :type '(repeat
7549 (string :tag "Key")
7550 (string :tag "Template")
7551 (string :tag "Muse Template")))
7553 (defun org-try-structure-completion ()
7554 "Try to complete a structure template before point.
7555 This looks for strings like \"<e\" on an otherwise empty line and
7556 expands them."
7557 (let ((l (buffer-substring (point-at-bol) (point)))
7559 (when (and (looking-at "[ \t]*$")
7560 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
7561 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
7562 (org-complete-expand-structure-template (+ -1 (point-at-bol)
7563 (match-beginning 1)) a)
7564 t)))
7566 (defun org-complete-expand-structure-template (start cell)
7567 "Expand a structure template."
7568 (let* ((musep (org-bound-and-true-p org-mtags-prefere-muse-templates))
7569 (rpl (nth (if musep 2 1) cell)))
7570 (delete-region start (point))
7571 (when (string-match "\\`#\\+" rpl)
7572 (cond
7573 ((bolp))
7574 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
7575 (delete-region (point-at-bol) (point)))
7576 (t (newline))))
7577 (setq start (point))
7578 (if (string-match "%file" rpl)
7579 (setq rpl (replace-match
7580 (concat
7581 "\""
7582 (save-match-data
7583 (abbreviate-file-name (read-file-name "Include file: ")))
7584 "\"")
7585 t t rpl)))
7586 (insert rpl)
7587 (if (re-search-backward "\\?" start t) (delete-char 1))))
7590 (defun org-complete (&optional arg)
7591 "Perform completion on word at point.
7592 At the beginning of a headline, this completes TODO keywords as given in
7593 `org-todo-keywords'.
7594 If the current word is preceded by a backslash, completes the TeX symbols
7595 that are supported for HTML support.
7596 If the current word is preceded by \"#+\", completes special words for
7597 setting file options.
7598 In the line after \"#+STARTUP:, complete valid keywords.\"
7599 At all other locations, this simply calls the value of
7600 `org-completion-fallback-command'."
7601 (interactive "P")
7602 (org-without-partial-completion
7603 (catch 'exit
7604 (let* ((a nil)
7605 (end (point))
7606 (beg1 (save-excursion
7607 (skip-chars-backward (org-re "[:alnum:]_@"))
7608 (point)))
7609 (beg (save-excursion
7610 (skip-chars-backward "a-zA-Z0-9_:$")
7611 (point)))
7612 (confirm (lambda (x) (stringp (car x))))
7613 (searchhead (equal (char-before beg) ?*))
7614 (struct
7615 (when (and (member (char-before beg1) '(?. ?<))
7616 (setq a (assoc (buffer-substring beg1 (point))
7617 org-structure-template-alist)))
7618 (org-complete-expand-structure-template (1- beg1) a)
7619 (throw 'exit t)))
7620 (tag (and (equal (char-before beg1) ?:)
7621 (equal (char-after (point-at-bol)) ?*)))
7622 (prop (and (equal (char-before beg1) ?:)
7623 (not (equal (char-after (point-at-bol)) ?*))))
7624 (texp (equal (char-before beg) ?\\))
7625 (link (equal (char-before beg) ?\[))
7626 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
7627 beg)
7628 "#+"))
7629 (startup (string-match "^#\\+STARTUP:.*"
7630 (buffer-substring (point-at-bol) (point))))
7631 (completion-ignore-case opt)
7632 (type nil)
7633 (tbl nil)
7634 (table (cond
7635 (opt
7636 (setq type :opt)
7637 (require 'org-exp)
7638 (append
7639 (mapcar
7640 (lambda (x)
7641 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
7642 (cons (match-string 2 x) (match-string 1 x)))
7643 (org-split-string (org-get-current-options) "\n"))
7644 (mapcar 'list org-additional-option-like-keywords)))
7645 (startup
7646 (setq type :startup)
7647 org-startup-options)
7648 (link (append org-link-abbrev-alist-local
7649 org-link-abbrev-alist))
7650 (texp
7651 (setq type :tex)
7652 org-html-entities)
7653 ((string-match "\\`\\*+[ \t]+\\'"
7654 (buffer-substring (point-at-bol) beg))
7655 (setq type :todo)
7656 (mapcar 'list org-todo-keywords-1))
7657 (searchhead
7658 (setq type :searchhead)
7659 (save-excursion
7660 (goto-char (point-min))
7661 (while (re-search-forward org-todo-line-regexp nil t)
7662 (push (list
7663 (org-make-org-heading-search-string
7664 (match-string 3) t))
7665 tbl)))
7666 tbl)
7667 (tag (setq type :tag beg beg1)
7668 (or org-tag-alist (org-get-buffer-tags)))
7669 (prop (setq type :prop beg beg1)
7670 (mapcar 'list (org-buffer-property-keys nil t t)))
7671 (t (progn
7672 (call-interactively org-completion-fallback-command)
7673 (throw 'exit nil)))))
7674 (pattern (buffer-substring-no-properties beg end))
7675 (completion (try-completion pattern table confirm)))
7676 (cond ((eq completion t)
7677 (if (not (assoc (upcase pattern) table))
7678 (message "Already complete")
7679 (if (and (equal type :opt)
7680 (not (member (car (assoc (upcase pattern) table))
7681 org-additional-option-like-keywords)))
7682 (insert (substring (cdr (assoc (upcase pattern) table))
7683 (length pattern)))
7684 (if (memq type '(:tag :prop)) (insert ":")))))
7685 ((null completion)
7686 (message "Can't find completion for \"%s\"" pattern)
7687 (ding))
7688 ((not (string= pattern completion))
7689 (delete-region beg end)
7690 (if (string-match " +$" completion)
7691 (setq completion (replace-match "" t t completion)))
7692 (insert completion)
7693 (if (get-buffer-window "*Completions*")
7694 (delete-window (get-buffer-window "*Completions*")))
7695 (if (assoc completion table)
7696 (if (eq type :todo) (insert " ")
7697 (if (memq type '(:tag :prop)) (insert ":"))))
7698 (if (and (equal type :opt) (assoc completion table))
7699 (message "%s" (substitute-command-keys
7700 "Press \\[org-complete] again to insert example settings"))))
7702 (message "Making completion list...")
7703 (let ((list (sort (all-completions pattern table confirm)
7704 'string<)))
7705 (with-output-to-temp-buffer "*Completions*"
7706 (condition-case nil
7707 ;; Protection needed for XEmacs and emacs 21
7708 (display-completion-list list pattern)
7709 (error (display-completion-list list)))))
7710 (message "Making completion list...%s" "done")))))))
7712 ;;;; TODO, DEADLINE, Comments
7714 (defun org-toggle-comment ()
7715 "Change the COMMENT state of an entry."
7716 (interactive)
7717 (save-excursion
7718 (org-back-to-heading)
7719 (let (case-fold-search)
7720 (if (looking-at (concat outline-regexp
7721 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
7722 (replace-match "" t t nil 1)
7723 (if (looking-at outline-regexp)
7724 (progn
7725 (goto-char (match-end 0))
7726 (insert org-comment-string " ")))))))
7728 (defvar org-last-todo-state-is-todo nil
7729 "This is non-nil when the last TODO state change led to a TODO state.
7730 If the last change removed the TODO tag or switched to DONE, then
7731 this is nil.")
7733 (defvar org-setting-tags nil) ; dynamically skiped
7735 (defun org-parse-local-options (string var)
7736 "Parse STRING for startup setting relevant for variable VAR."
7737 (let ((rtn (symbol-value var))
7738 e opts)
7739 (save-match-data
7740 (if (or (not string) (not (string-match "\\S-" string)))
7742 (setq opts (delq nil (mapcar (lambda (x)
7743 (setq e (assoc x org-startup-options))
7744 (if (eq (nth 1 e) var) e nil))
7745 (org-split-string string "[ \t]+"))))
7746 (if (not opts)
7748 (setq rtn nil)
7749 (while (setq e (pop opts))
7750 (if (not (nth 3 e))
7751 (setq rtn (nth 2 e))
7752 (if (not (listp rtn)) (setq rtn nil))
7753 (push (nth 2 e) rtn)))
7754 rtn)))))
7756 (defvar org-blocker-hook nil
7757 "Hook for functions that are allowed to block a state change.
7759 Each function gets as its single argument a property list, see
7760 `org-trigger-hook' for more information about this list.
7762 If any of the functions in this hook returns nil, the state change
7763 is blocked.")
7765 (defvar org-trigger-hook nil
7766 "Hook for functions that are triggered by a state change.
7768 Each function gets as its single argument a property list with at least
7769 the following elements:
7771 (:type type-of-change :position pos-at-entry-start
7772 :from old-state :to new-state)
7774 Depending on the type, more properties may be present.
7776 This mechanism is currently implemented for:
7778 TODO state changes
7779 ------------------
7780 :type todo-state-change
7781 :from previous state (keyword as a string), or nil
7782 :to new state (keyword as a string), or nil")
7785 (defun org-todo (&optional arg)
7786 "Change the TODO state of an item.
7787 The state of an item is given by a keyword at the start of the heading,
7788 like
7789 *** TODO Write paper
7790 *** DONE Call mom
7792 The different keywords are specified in the variable `org-todo-keywords'.
7793 By default the available states are \"TODO\" and \"DONE\".
7794 So for this example: when the item starts with TODO, it is changed to DONE.
7795 When it starts with DONE, the DONE is removed. And when neither TODO nor
7796 DONE are present, add TODO at the beginning of the heading.
7798 With C-u prefix arg, use completion to determine the new state.
7799 With numeric prefix arg, switch to that state.
7801 For calling through lisp, arg is also interpreted in the following way:
7802 'none -> empty state
7803 \"\"(empty string) -> switch to empty state
7804 'done -> switch to DONE
7805 'nextset -> switch to the next set of keywords
7806 'previousset -> switch to the previous set of keywords
7807 \"WAITING\" -> switch to the specified keyword, but only if it
7808 really is a member of `org-todo-keywords'."
7809 (interactive "P")
7810 (save-excursion
7811 (catch 'exit
7812 (org-back-to-heading)
7813 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
7814 (or (looking-at (concat " +" org-todo-regexp " *"))
7815 (looking-at " *"))
7816 (let* ((match-data (match-data))
7817 (startpos (point-at-bol))
7818 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
7819 (org-log-done org-log-done)
7820 (org-log-repeat org-log-repeat)
7821 (org-todo-log-states org-todo-log-states)
7822 (this (match-string 1))
7823 (hl-pos (match-beginning 0))
7824 (head (org-get-todo-sequence-head this))
7825 (ass (assoc head org-todo-kwd-alist))
7826 (interpret (nth 1 ass))
7827 (done-word (nth 3 ass))
7828 (final-done-word (nth 4 ass))
7829 (last-state (or this ""))
7830 (completion-ignore-case t)
7831 (member (member this org-todo-keywords-1))
7832 (tail (cdr member))
7833 (state (cond
7834 ((and org-todo-key-trigger
7835 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
7836 (and (not arg) org-use-fast-todo-selection
7837 (not (eq org-use-fast-todo-selection 'prefix)))))
7838 ;; Use fast selection
7839 (org-fast-todo-selection))
7840 ((and (equal arg '(4))
7841 (or (not org-use-fast-todo-selection)
7842 (not org-todo-key-trigger)))
7843 ;; Read a state with completion
7844 (completing-read "State: " (mapcar (lambda(x) (list x))
7845 org-todo-keywords-1)
7846 nil t))
7847 ((eq arg 'right)
7848 (if this
7849 (if tail (car tail) nil)
7850 (car org-todo-keywords-1)))
7851 ((eq arg 'left)
7852 (if (equal member org-todo-keywords-1)
7854 (if this
7855 (nth (- (length org-todo-keywords-1) (length tail) 2)
7856 org-todo-keywords-1)
7857 (org-last org-todo-keywords-1))))
7858 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
7859 (setq arg nil))) ; hack to fall back to cycling
7860 (arg
7861 ;; user or caller requests a specific state
7862 (cond
7863 ((equal arg "") nil)
7864 ((eq arg 'none) nil)
7865 ((eq arg 'done) (or done-word (car org-done-keywords)))
7866 ((eq arg 'nextset)
7867 (or (car (cdr (member head org-todo-heads)))
7868 (car org-todo-heads)))
7869 ((eq arg 'previousset)
7870 (let ((org-todo-heads (reverse org-todo-heads)))
7871 (or (car (cdr (member head org-todo-heads)))
7872 (car org-todo-heads))))
7873 ((car (member arg org-todo-keywords-1)))
7874 ((nth (1- (prefix-numeric-value arg))
7875 org-todo-keywords-1))))
7876 ((null member) (or head (car org-todo-keywords-1)))
7877 ((equal this final-done-word) nil) ;; -> make empty
7878 ((null tail) nil) ;; -> first entry
7879 ((eq interpret 'sequence)
7880 (car tail))
7881 ((memq interpret '(type priority))
7882 (if (eq this-command last-command)
7883 (car tail)
7884 (if (> (length tail) 0)
7885 (or done-word (car org-done-keywords))
7886 nil)))
7887 (t nil)))
7888 (next (if state (concat " " state " ") " "))
7889 (change-plist (list :type 'todo-state-change :from this :to state
7890 :position startpos))
7891 dolog now-done-p)
7892 (when org-blocker-hook
7893 (unless (save-excursion
7894 (save-match-data
7895 (run-hook-with-args-until-failure
7896 'org-blocker-hook change-plist)))
7897 (if (interactive-p)
7898 (error "TODO state change from %s to %s blocked" this state)
7899 ;; fail silently
7900 (message "TODO state change from %s to %s blocked" this state)
7901 (throw 'exit nil))))
7902 (store-match-data match-data)
7903 (replace-match next t t)
7904 (unless (pos-visible-in-window-p hl-pos)
7905 (message "TODO state changed to %s" (org-trim next)))
7906 (unless head
7907 (setq head (org-get-todo-sequence-head state)
7908 ass (assoc head org-todo-kwd-alist)
7909 interpret (nth 1 ass)
7910 done-word (nth 3 ass)
7911 final-done-word (nth 4 ass)))
7912 (when (memq arg '(nextset previousset))
7913 (message "Keyword-Set %d/%d: %s"
7914 (- (length org-todo-sets) -1
7915 (length (memq (assoc state org-todo-sets) org-todo-sets)))
7916 (length org-todo-sets)
7917 (mapconcat 'identity (assoc state org-todo-sets) " ")))
7918 (setq org-last-todo-state-is-todo
7919 (not (member state org-done-keywords)))
7920 (setq now-done-p (and (member state org-done-keywords)
7921 (not (member this org-done-keywords))))
7922 (and logging (org-local-logging logging))
7923 (when (and (or org-todo-log-states org-log-done)
7924 (not (memq arg '(nextset previousset))))
7925 ;; we need to look at recording a time and note
7926 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
7927 (nth 2 (assoc this org-todo-log-states))))
7928 (when (and state
7929 (member state org-not-done-keywords)
7930 (not (member this org-not-done-keywords)))
7931 ;; This is now a todo state and was not one before
7932 ;; If there was a CLOSED time stamp, get rid of it.
7933 (org-add-planning-info nil nil 'closed))
7934 (when (and now-done-p org-log-done)
7935 ;; It is now done, and it was not done before
7936 (org-add-planning-info 'closed (org-current-time))
7937 (if (and (not dolog) (eq 'note org-log-done))
7938 (org-add-log-setup 'done state 'findpos 'note)))
7939 (when (and state dolog)
7940 ;; This is a non-nil state, and we need to log it
7941 (org-add-log-setup 'state state 'findpos dolog)))
7942 ;; Fixup tag positioning
7943 (org-todo-trigger-tag-changes state)
7944 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
7945 (when org-provide-todo-statistics
7946 (org-update-parent-todo-statistics))
7947 (run-hooks 'org-after-todo-state-change-hook)
7948 (if (and arg (not (member state org-done-keywords)))
7949 (setq head (org-get-todo-sequence-head state)))
7950 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
7951 ;; Do we need to trigger a repeat?
7952 (when now-done-p (org-auto-repeat-maybe state))
7953 ;; Fixup cursor location if close to the keyword
7954 (if (and (outline-on-heading-p)
7955 (not (bolp))
7956 (save-excursion (beginning-of-line 1)
7957 (looking-at org-todo-line-regexp))
7958 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
7959 (progn
7960 (goto-char (or (match-end 2) (match-end 1)))
7961 (just-one-space)))
7962 (when org-trigger-hook
7963 (save-excursion
7964 (run-hook-with-args 'org-trigger-hook change-plist)))))))
7966 (defun org-update-parent-todo-statistics ()
7967 "Update any statistics cookie in the parent of the current headline."
7968 (interactive)
7969 (let ((box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
7970 level (cnt-all 0) (cnt-done 0) is-percent kwd)
7971 (catch 'exit
7972 (save-excursion
7973 (setq level (org-up-heading-safe))
7974 (unless (and level
7975 (re-search-forward box-re (point-at-eol) t))
7976 (throw 'exit nil))
7977 (setq is-percent (match-end 2))
7978 (save-match-data
7979 (unless (outline-next-heading) (throw 'exit nil))
7980 (while (looking-at org-todo-line-regexp)
7981 (setq kwd (match-string 2))
7982 (and kwd (setq cnt-all (1+ cnt-all)))
7983 (and (member kwd org-done-keywords)
7984 (setq cnt-done (1+ cnt-done)))
7985 (condition-case nil
7986 (org-forward-same-level 1)
7987 (error (end-of-line 1)))))
7988 (replace-match
7989 (if is-percent
7990 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
7991 (format "[%d/%d]" cnt-done cnt-all)))
7992 (run-hook-with-args 'org-after-todo-statistics-hook
7993 cnt-done (- cnt-all cnt-done))))))
7995 (defvar org-after-todo-statistics-hook nil
7996 "Hook that is called after a TODO statistics cookie has been updated.
7997 Each function is called with two arguments: the number of not-done entries
7998 and the number of done entries.
8000 For example, the following function, when added to this hook, will switch
8001 an entry to DONE when all children are done, and back to TODO when new
8002 entries are set to a TODO status. Note that this hook is only called
8003 when there is a statistics cookie in the headline!
8005 (defun org-summary-todo (n-done n-not-done)
8006 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
8007 (let (org-log-done org-log-states) ; turn off logging
8008 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
8011 (defun org-todo-trigger-tag-changes (state)
8012 "Apply the changes defined in `org-todo-state-tags-triggers'."
8013 (let ((l org-todo-state-tags-triggers)
8014 changes)
8015 (when (or (not state) (equal state ""))
8016 (setq changes (append changes (cdr (assoc "" l)))))
8017 (when (and (stringp state) (> (length state) 0))
8018 (setq changes (append changes (cdr (assoc state l)))))
8019 (when (member state org-not-done-keywords)
8020 (setq changes (append changes (cdr (assoc 'todo l)))))
8021 (when (member state org-done-keywords)
8022 (setq changes (append changes (cdr (assoc 'done l)))))
8023 (dolist (c changes)
8024 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
8026 (defun org-local-logging (value)
8027 "Get logging settings from a property VALUE."
8028 (let* (words w a)
8029 ;; directly set the variables, they are already local.
8030 (setq org-log-done nil
8031 org-log-repeat nil
8032 org-todo-log-states nil)
8033 (setq words (org-split-string value))
8034 (while (setq w (pop words))
8035 (cond
8036 ((setq a (assoc w org-startup-options))
8037 (and (member (nth 1 a) '(org-log-done org-log-repeat))
8038 (set (nth 1 a) (nth 2 a))))
8039 ((setq a (org-extract-log-state-settings w))
8040 (and (member (car a) org-todo-keywords-1)
8041 (push a org-todo-log-states)))))))
8043 (defun org-get-todo-sequence-head (kwd)
8044 "Return the head of the TODO sequence to which KWD belongs.
8045 If KWD is not set, check if there is a text property remembering the
8046 right sequence."
8047 (let (p)
8048 (cond
8049 ((not kwd)
8050 (or (get-text-property (point-at-bol) 'org-todo-head)
8051 (progn
8052 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
8053 nil (point-at-eol)))
8054 (get-text-property p 'org-todo-head))))
8055 ((not (member kwd org-todo-keywords-1))
8056 (car org-todo-keywords-1))
8057 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
8059 (defun org-fast-todo-selection ()
8060 "Fast TODO keyword selection with single keys.
8061 Returns the new TODO keyword, or nil if no state change should occur."
8062 (let* ((fulltable org-todo-key-alist)
8063 (done-keywords org-done-keywords) ;; needed for the faces.
8064 (maxlen (apply 'max (mapcar
8065 (lambda (x)
8066 (if (stringp (car x)) (string-width (car x)) 0))
8067 fulltable)))
8068 (expert nil)
8069 (fwidth (+ maxlen 3 1 3))
8070 (ncol (/ (- (window-width) 4) fwidth))
8071 tg cnt e c tbl
8072 groups ingroup)
8073 (save-window-excursion
8074 (if expert
8075 (set-buffer (get-buffer-create " *Org todo*"))
8076 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
8077 (erase-buffer)
8078 (org-set-local 'org-done-keywords done-keywords)
8079 (setq tbl fulltable cnt 0)
8080 (while (setq e (pop tbl))
8081 (cond
8082 ((equal e '(:startgroup))
8083 (push '() groups) (setq ingroup t)
8084 (when (not (= cnt 0))
8085 (setq cnt 0)
8086 (insert "\n"))
8087 (insert "{ "))
8088 ((equal e '(:endgroup))
8089 (setq ingroup nil cnt 0)
8090 (insert "}\n"))
8092 (setq tg (car e) c (cdr e))
8093 (if ingroup (push tg (car groups)))
8094 (setq tg (org-add-props tg nil 'face
8095 (org-get-todo-face tg)))
8096 (if (and (= cnt 0) (not ingroup)) (insert " "))
8097 (insert "[" c "] " tg (make-string
8098 (- fwidth 4 (length tg)) ?\ ))
8099 (when (= (setq cnt (1+ cnt)) ncol)
8100 (insert "\n")
8101 (if ingroup (insert " "))
8102 (setq cnt 0)))))
8103 (insert "\n")
8104 (goto-char (point-min))
8105 (if (and (not expert) (fboundp 'fit-window-to-buffer))
8106 (fit-window-to-buffer))
8107 (message "[a-z..]:Set [SPC]:clear")
8108 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
8109 (cond
8110 ((or (= c ?\C-g)
8111 (and (= c ?q) (not (rassoc c fulltable))))
8112 (setq quit-flag t))
8113 ((= c ?\ ) nil)
8114 ((setq e (rassoc c fulltable) tg (car e))
8116 (t (setq quit-flag t))))))
8118 (defun org-entry-is-todo-p ()
8119 (member (org-get-todo-state) org-not-done-keywords))
8121 (defun org-entry-is-done-p ()
8122 (member (org-get-todo-state) org-done-keywords))
8124 (defun org-get-todo-state ()
8125 (save-excursion
8126 (org-back-to-heading t)
8127 (and (looking-at org-todo-line-regexp)
8128 (match-end 2)
8129 (match-string 2))))
8131 (defun org-at-date-range-p (&optional inactive-ok)
8132 "Is the cursor inside a date range?"
8133 (interactive)
8134 (save-excursion
8135 (catch 'exit
8136 (let ((pos (point)))
8137 (skip-chars-backward "^[<\r\n")
8138 (skip-chars-backward "<[")
8139 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8140 (>= (match-end 0) pos)
8141 (throw 'exit t))
8142 (skip-chars-backward "^<[\r\n")
8143 (skip-chars-backward "<[")
8144 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8145 (>= (match-end 0) pos)
8146 (throw 'exit t)))
8147 nil)))
8149 (defun org-get-repeat ()
8150 "Check if there is a deadline/schedule with repeater in this entry."
8151 (save-match-data
8152 (save-excursion
8153 (org-back-to-heading t)
8154 (if (re-search-forward
8155 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
8156 (match-string 1)))))
8158 (defvar org-last-changed-timestamp)
8159 (defvar org-last-inserted-timestamp)
8160 (defvar org-log-post-message)
8161 (defvar org-log-note-purpose)
8162 (defvar org-log-note-how)
8163 (defvar org-log-note-extra)
8164 (defun org-auto-repeat-maybe (done-word)
8165 "Check if the current headline contains a repeated deadline/schedule.
8166 If yes, set TODO state back to what it was and change the base date
8167 of repeating deadline/scheduled time stamps to new date.
8168 This function is run automatically after each state change to a DONE state."
8169 ;; last-state is dynamically scoped into this function
8170 (let* ((repeat (org-get-repeat))
8171 (aa (assoc last-state org-todo-kwd-alist))
8172 (interpret (nth 1 aa))
8173 (head (nth 2 aa))
8174 (whata '(("d" . day) ("m" . month) ("y" . year)))
8175 (msg "Entry repeats: ")
8176 (org-log-done nil)
8177 (org-todo-log-states nil)
8178 (nshiftmax 10) (nshift 0)
8179 re type n what ts mb0 time)
8180 (when repeat
8181 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
8182 (org-todo (if (eq interpret 'type) last-state head))
8183 (when org-log-repeat
8184 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
8185 (memq 'org-add-log-note post-command-hook))
8186 ;; OK, we are already setup for some record
8187 (if (eq org-log-repeat 'note)
8188 ;; make sure we take a note, not only a time stamp
8189 (setq org-log-note-how 'note))
8190 ;; Set up for taking a record
8191 (org-add-log-setup 'state (or done-word (car org-done-keywords))
8192 'findpos org-log-repeat)))
8193 (org-back-to-heading t)
8194 (org-add-planning-info nil nil 'closed)
8195 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
8196 org-deadline-time-regexp "\\)\\|\\("
8197 org-ts-regexp "\\)"))
8198 (while (re-search-forward
8199 re (save-excursion (outline-next-heading) (point)) t)
8200 (setq type (if (match-end 1) org-scheduled-string
8201 (if (match-end 3) org-deadline-string "Plain:"))
8202 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0)))
8203 mb0 (match-beginning 0))
8204 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
8205 (setq n (string-to-number (match-string 2 ts))
8206 what (match-string 3 ts))
8207 (if (equal what "w") (setq n (* n 7) what "d"))
8208 ;; Preparation, see if we need to modify the start date for the change
8209 (when (match-end 1)
8210 (setq time (save-match-data (org-time-string-to-time ts)))
8211 (cond
8212 ((equal (match-string 1 ts) ".")
8213 ;; Shift starting date to today
8214 (org-timestamp-change
8215 (- (time-to-days (current-time)) (time-to-days time))
8216 'day))
8217 ((equal (match-string 1 ts) "+")
8218 (while (or (= nshift 0)
8219 (<= (time-to-days time) (time-to-days (current-time))))
8220 (when (= (incf nshift) nshiftmax)
8221 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
8222 (error "Abort")))
8223 (org-timestamp-change n (cdr (assoc what whata)))
8224 (org-at-timestamp-p t)
8225 (setq ts (match-string 1))
8226 (setq time (save-match-data (org-time-string-to-time ts))))
8227 (org-timestamp-change (- n) (cdr (assoc what whata)))
8228 ;; rematch, so that we have everything in place for the real shift
8229 (org-at-timestamp-p t)
8230 (setq ts (match-string 1))
8231 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
8232 (org-timestamp-change n (cdr (assoc what whata)))
8233 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
8234 (setq org-log-post-message msg)
8235 (message "%s" msg))))
8237 (defun org-show-todo-tree (arg)
8238 "Make a compact tree which shows all headlines marked with TODO.
8239 The tree will show the lines where the regexp matches, and all higher
8240 headlines above the match.
8241 With a \\[universal-argument] prefix, also show the DONE entries.
8242 With a numeric prefix N, construct a sparse tree for the Nth element
8243 of `org-todo-keywords-1'."
8244 (interactive "P")
8245 (let ((case-fold-search nil)
8246 (kwd-re
8247 (cond ((null arg) org-not-done-regexp)
8248 ((equal arg '(4))
8249 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
8250 (mapcar 'list org-todo-keywords-1))))
8251 (concat "\\("
8252 (mapconcat 'identity (org-split-string kwd "|") "\\|")
8253 "\\)\\>")))
8254 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
8255 (regexp-quote (nth (1- (prefix-numeric-value arg))
8256 org-todo-keywords-1)))
8257 (t (error "Invalid prefix argument: %s" arg)))))
8258 (message "%d TODO entries found"
8259 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
8261 (defun org-deadline (&optional remove time)
8262 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
8263 With argument REMOVE, remove any deadline from the item.
8264 When TIME is set, it should be an internal time specification, and the
8265 scheduling will use the corresponding date."
8266 (interactive "P")
8267 (if remove
8268 (progn
8269 (org-remove-timestamp-with-keyword org-deadline-string)
8270 (message "Item no longer has a deadline."))
8271 (if (org-get-repeat)
8272 (error "Cannot change deadline on task with repeater, please do that by hand")
8273 (org-add-planning-info 'deadline time 'closed)
8274 (message "Deadline on %s" org-last-inserted-timestamp))))
8276 (defun org-schedule (&optional remove time)
8277 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
8278 With argument REMOVE, remove any scheduling date from the item.
8279 When TIME is set, it should be an internal time specification, and the
8280 scheduling will use the corresponding date."
8281 (interactive "P")
8282 (if remove
8283 (progn
8284 (org-remove-timestamp-with-keyword org-scheduled-string)
8285 (message "Item is no longer scheduled."))
8286 (if (org-get-repeat)
8287 (error "Cannot reschedule task with repeater, please do that by hand")
8288 (org-add-planning-info 'scheduled time 'closed)
8289 (message "Scheduled to %s" org-last-inserted-timestamp))))
8291 (defun org-remove-timestamp-with-keyword (keyword)
8292 "Remove all time stamps with KEYWORD in the current entry."
8293 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
8294 beg)
8295 (save-excursion
8296 (org-back-to-heading t)
8297 (setq beg (point))
8298 (org-end-of-subtree t t)
8299 (while (re-search-backward re beg t)
8300 (replace-match "")
8301 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
8302 (equal (char-before) ?\ ))
8303 (backward-delete-char 1)
8304 (if (string-match "^[ \t]*$" (buffer-substring
8305 (point-at-bol) (point-at-eol)))
8306 (delete-region (point-at-bol)
8307 (min (point-max) (1+ (point-at-eol))))))))))
8309 (defun org-add-planning-info (what &optional time &rest remove)
8310 "Insert new timestamp with keyword in the line directly after the headline.
8311 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
8312 If non is given, the user is prompted for a date.
8313 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
8314 be removed."
8315 (interactive)
8316 (let (org-time-was-given org-end-time-was-given ts
8317 end default-time default-input)
8319 (when (and (not time) (memq what '(scheduled deadline)))
8320 ;; Try to get a default date/time from existing timestamp
8321 (save-excursion
8322 (org-back-to-heading t)
8323 (setq end (save-excursion (outline-next-heading) (point)))
8324 (when (re-search-forward (if (eq what 'scheduled)
8325 org-scheduled-time-regexp
8326 org-deadline-time-regexp)
8327 end t)
8328 (setq ts (match-string 1)
8329 default-time
8330 (apply 'encode-time (org-parse-time-string ts))
8331 default-input (and ts (org-get-compact-tod ts))))))
8332 (when what
8333 ;; If necessary, get the time from the user
8334 (setq time (or time (org-read-date nil 'to-time nil nil
8335 default-time default-input))))
8337 (when (and org-insert-labeled-timestamps-at-point
8338 (member what '(scheduled deadline)))
8339 (insert
8340 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
8341 (org-insert-time-stamp time org-time-was-given
8342 nil nil nil (list org-end-time-was-given))
8343 (setq what nil))
8344 (save-excursion
8345 (save-restriction
8346 (let (col list elt ts buffer-invisibility-spec)
8347 (org-back-to-heading t)
8348 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
8349 (goto-char (match-end 1))
8350 (setq col (current-column))
8351 (goto-char (match-end 0))
8352 (if (eobp) (insert "\n") (forward-char 1))
8353 (if (and (not (looking-at outline-regexp))
8354 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
8355 "[^\r\n]*"))
8356 (not (equal (match-string 1) org-clock-string)))
8357 (narrow-to-region (match-beginning 0) (match-end 0))
8358 (insert-before-markers "\n")
8359 (backward-char 1)
8360 (narrow-to-region (point) (point))
8361 (and org-adapt-indentation (org-indent-to-column col)))
8362 ;; Check if we have to remove something.
8363 (setq list (cons what remove))
8364 (while list
8365 (setq elt (pop list))
8366 (goto-char (point-min))
8367 (when (or (and (eq elt 'scheduled)
8368 (re-search-forward org-scheduled-time-regexp nil t))
8369 (and (eq elt 'deadline)
8370 (re-search-forward org-deadline-time-regexp nil t))
8371 (and (eq elt 'closed)
8372 (re-search-forward org-closed-time-regexp nil t)))
8373 (replace-match "")
8374 (if (looking-at "--+<[^>]+>") (replace-match ""))
8375 (if (looking-at " +") (replace-match ""))))
8376 (goto-char (point-max))
8377 (when what
8378 (insert
8379 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
8380 (cond ((eq what 'scheduled) org-scheduled-string)
8381 ((eq what 'deadline) org-deadline-string)
8382 ((eq what 'closed) org-closed-string))
8383 " ")
8384 (setq ts (org-insert-time-stamp
8385 time
8386 (or org-time-was-given
8387 (and (eq what 'closed) org-log-done-with-time))
8388 (eq what 'closed)
8389 nil nil (list org-end-time-was-given)))
8390 (end-of-line 1))
8391 (goto-char (point-min))
8392 (widen)
8393 (if (and (looking-at "[ \t]+\n")
8394 (equal (char-before) ?\n))
8395 (delete-region (1- (point)) (point-at-eol)))
8396 ts)))))
8398 (defvar org-log-note-marker (make-marker))
8399 (defvar org-log-note-purpose nil)
8400 (defvar org-log-note-state nil)
8401 (defvar org-log-note-how nil)
8402 (defvar org-log-note-extra nil)
8403 (defvar org-log-note-window-configuration nil)
8404 (defvar org-log-note-return-to (make-marker))
8405 (defvar org-log-post-message nil
8406 "Message to be displayed after a log note has been stored.
8407 The auto-repeater uses this.")
8409 (defun org-add-note ()
8410 "Add a note to the current entry.
8411 This is done in the same way as adding a state change note."
8412 (interactive)
8413 (org-add-log-setup 'note nil 'findpos nil))
8415 (defvar org-property-end-re)
8416 (defun org-add-log-setup (&optional purpose state findpos how &optional extra)
8417 "Set up the post command hook to take a note.
8418 If this is about to TODO state change, the new state is expected in STATE.
8419 When FINDPOS is non-nil, find the correct position for the note in
8420 the current entry. If not, assume that it can be inserted at point.
8421 HOW is an indicator what kind of note should be created.
8422 EXTRA is additional text that will be inserted into the notes buffer."
8423 (save-restriction
8424 (save-excursion
8425 (when findpos
8426 (org-back-to-heading t)
8427 (narrow-to-region (point) (save-excursion
8428 (outline-next-heading) (point)))
8429 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
8430 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
8431 "[^\r\n]*\\)?"))
8432 (goto-char (match-end 0))
8433 (when (and org-log-state-notes-insert-after-drawers
8434 (save-excursion
8435 (forward-line) (looking-at org-drawer-regexp)))
8436 (progn (forward-line)
8437 (while (looking-at org-drawer-regexp)
8438 (goto-char (match-end 0))
8439 (re-search-forward org-property-end-re (point-max) t)
8440 (forward-line))
8441 (forward-line -1)))
8442 (unless org-log-states-order-reversed
8443 (and (= (char-after) ?\n) (forward-char 1))
8444 (org-skip-over-state-notes)
8445 (skip-chars-backward " \t\n\r")))
8446 (move-marker org-log-note-marker (point))
8447 (setq org-log-note-purpose purpose
8448 org-log-note-state state
8449 org-log-note-how how
8450 org-log-note-extra extra)
8451 (add-hook 'post-command-hook 'org-add-log-note 'append))))
8453 (defun org-skip-over-state-notes ()
8454 "Skip past the list of State notes in an entry."
8455 (if (looking-at "\n[ \t]*- State") (forward-char 1))
8456 (while (looking-at "[ \t]*- State")
8457 (condition-case nil
8458 (org-next-item)
8459 (error (org-end-of-item)))))
8461 (defun org-add-log-note (&optional purpose)
8462 "Pop up a window for taking a note, and add this note later at point."
8463 (remove-hook 'post-command-hook 'org-add-log-note)
8464 (setq org-log-note-window-configuration (current-window-configuration))
8465 (delete-other-windows)
8466 (move-marker org-log-note-return-to (point))
8467 (switch-to-buffer (marker-buffer org-log-note-marker))
8468 (goto-char org-log-note-marker)
8469 (org-switch-to-buffer-other-window "*Org Note*")
8470 (erase-buffer)
8471 (if (memq org-log-note-how '(time state))
8472 (let (current-prefix-arg) (org-store-log-note))
8473 (let ((org-inhibit-startup t)) (org-mode))
8474 (insert (format "# Insert note for %s.
8475 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
8476 (cond
8477 ((eq org-log-note-purpose 'clock-out) "stopped clock")
8478 ((eq org-log-note-purpose 'done) "closed todo item")
8479 ((eq org-log-note-purpose 'state)
8480 (format "state change to \"%s\"" org-log-note-state))
8481 ((eq org-log-note-purpose 'note)
8482 "this entry")
8483 (t (error "This should not happen")))))
8484 (if org-log-note-extra (insert org-log-note-extra))
8485 (org-set-local 'org-finish-function 'org-store-log-note)))
8487 (defvar org-note-abort nil) ; dynamically scoped
8488 (defun org-store-log-note ()
8489 "Finish taking a log note, and insert it to where it belongs."
8490 (let ((txt (buffer-string))
8491 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
8492 lines ind)
8493 (kill-buffer (current-buffer))
8494 (while (string-match "\\`#.*\n[ \t\n]*" txt)
8495 (setq txt (replace-match "" t t txt)))
8496 (if (string-match "\\s-+\\'" txt)
8497 (setq txt (replace-match "" t t txt)))
8498 (setq lines (org-split-string txt "\n"))
8499 (when (and note (string-match "\\S-" note))
8500 (setq note
8501 (org-replace-escapes
8502 note
8503 (list (cons "%u" (user-login-name))
8504 (cons "%U" user-full-name)
8505 (cons "%t" (format-time-string
8506 (org-time-stamp-format 'long 'inactive)
8507 (current-time)))
8508 (cons "%s" (if org-log-note-state
8509 (concat "\"" org-log-note-state "\"")
8510 "")))))
8511 (if lines (setq note (concat note " \\\\")))
8512 (push note lines))
8513 (when (or current-prefix-arg org-note-abort) (setq lines nil))
8514 (when lines
8515 (save-excursion
8516 (set-buffer (marker-buffer org-log-note-marker))
8517 (save-excursion
8518 (goto-char org-log-note-marker)
8519 (move-marker org-log-note-marker nil)
8520 (end-of-line 1)
8521 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
8522 (indent-relative nil)
8523 (insert "- " (pop lines))
8524 (org-indent-line-function)
8525 (beginning-of-line 1)
8526 (looking-at "[ \t]*")
8527 (setq ind (concat (match-string 0) " "))
8528 (end-of-line 1)
8529 (while lines (insert "\n" ind (pop lines)))))))
8530 (set-window-configuration org-log-note-window-configuration)
8531 (with-current-buffer (marker-buffer org-log-note-return-to)
8532 (goto-char org-log-note-return-to))
8533 (move-marker org-log-note-return-to nil)
8534 (and org-log-post-message (message "%s" org-log-post-message)))
8536 (defun org-sparse-tree (&optional arg)
8537 "Create a sparse tree, prompt for the details.
8538 This command can create sparse trees. You first need to select the type
8539 of match used to create the tree:
8541 t Show entries with a specific TODO keyword.
8542 T Show entries selected by a tags match.
8543 p Enter a property name and its value (both with completion on existing
8544 names/values) and show entries with that property.
8545 r Show entries matching a regular expression
8546 d Show deadlines due within `org-deadline-warning-days'."
8547 (interactive "P")
8548 (let (ans kwd value)
8549 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
8550 (setq ans (read-char-exclusive))
8551 (cond
8552 ((equal ans ?d)
8553 (call-interactively 'org-check-deadlines))
8554 ((equal ans ?b)
8555 (call-interactively 'org-check-before-date))
8556 ((equal ans ?t)
8557 (org-show-todo-tree '(4)))
8558 ((equal ans ?T)
8559 (call-interactively 'org-tags-sparse-tree))
8560 ((member ans '(?p ?P))
8561 (setq kwd (completing-read "Property: "
8562 (mapcar 'list (org-buffer-property-keys))))
8563 (setq value (completing-read "Value: "
8564 (mapcar 'list (org-property-values kwd))))
8565 (unless (string-match "\\`{.*}\\'" value)
8566 (setq value (concat "\"" value "\"")))
8567 (org-tags-sparse-tree arg (concat kwd "=" value)))
8568 ((member ans '(?r ?R ?/))
8569 (call-interactively 'org-occur))
8570 (t (error "No such sparse tree command \"%c\"" ans)))))
8572 (defvar org-occur-highlights nil
8573 "List of overlays used for occur matches.")
8574 (make-variable-buffer-local 'org-occur-highlights)
8575 (defvar org-occur-parameters nil
8576 "Parameters of the active org-occur calls.
8577 This is a list, each call to org-occur pushes as cons cell,
8578 containing the regular expression and the callback, onto the list.
8579 The list can contain several entries if `org-occur' has been called
8580 several time with the KEEP-PREVIOUS argument. Otherwise, this list
8581 will only contain one set of parameters. When the highlights are
8582 removed (for example with `C-c C-c', or with the next edit (depending
8583 on `org-remove-highlights-with-change'), this variable is emptied
8584 as well.")
8585 (make-variable-buffer-local 'org-occur-parameters)
8587 (defun org-occur (regexp &optional keep-previous callback)
8588 "Make a compact tree which shows all matches of REGEXP.
8589 The tree will show the lines where the regexp matches, and all higher
8590 headlines above the match. It will also show the heading after the match,
8591 to make sure editing the matching entry is easy.
8592 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
8593 call to `org-occur' will be kept, to allow stacking of calls to this
8594 command.
8595 If CALLBACK is non-nil, it is a function which is called to confirm
8596 that the match should indeed be shown."
8597 (interactive "sRegexp: \nP")
8598 (unless keep-previous
8599 (org-remove-occur-highlights nil nil t))
8600 (push (cons regexp callback) org-occur-parameters)
8601 (let ((cnt 0))
8602 (save-excursion
8603 (goto-char (point-min))
8604 (if (or (not keep-previous) ; do not want to keep
8605 (not org-occur-highlights)) ; no previous matches
8606 ;; hide everything
8607 (org-overview))
8608 (while (re-search-forward regexp nil t)
8609 (when (or (not callback)
8610 (save-match-data (funcall callback)))
8611 (setq cnt (1+ cnt))
8612 (when org-highlight-sparse-tree-matches
8613 (org-highlight-new-match (match-beginning 0) (match-end 0)))
8614 (org-show-context 'occur-tree))))
8615 (when org-remove-highlights-with-change
8616 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
8617 nil 'local))
8618 (unless org-sparse-tree-open-archived-trees
8619 (org-hide-archived-subtrees (point-min) (point-max)))
8620 (run-hooks 'org-occur-hook)
8621 (if (interactive-p)
8622 (message "%d match(es) for regexp %s" cnt regexp))
8623 cnt))
8625 (defun org-show-context (&optional key)
8626 "Make sure point and context and visible.
8627 How much context is shown depends upon the variables
8628 `org-show-hierarchy-above', `org-show-following-heading'. and
8629 `org-show-siblings'."
8630 (let ((heading-p (org-on-heading-p t))
8631 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
8632 (following-p (org-get-alist-option org-show-following-heading key))
8633 (entry-p (org-get-alist-option org-show-entry-below key))
8634 (siblings-p (org-get-alist-option org-show-siblings key)))
8635 (catch 'exit
8636 ;; Show heading or entry text
8637 (if (and heading-p (not entry-p))
8638 (org-flag-heading nil) ; only show the heading
8639 (and (or entry-p (org-invisible-p) (org-invisible-p2))
8640 (org-show-hidden-entry))) ; show entire entry
8641 (when following-p
8642 ;; Show next sibling, or heading below text
8643 (save-excursion
8644 (and (if heading-p (org-goto-sibling) (outline-next-heading))
8645 (org-flag-heading nil))))
8646 (when siblings-p (org-show-siblings))
8647 (when hierarchy-p
8648 ;; show all higher headings, possibly with siblings
8649 (save-excursion
8650 (while (and (condition-case nil
8651 (progn (org-up-heading-all 1) t)
8652 (error nil))
8653 (not (bobp)))
8654 (org-flag-heading nil)
8655 (when siblings-p (org-show-siblings))))))))
8657 (defun org-reveal (&optional siblings)
8658 "Show current entry, hierarchy above it, and the following headline.
8659 This can be used to show a consistent set of context around locations
8660 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
8661 not t for the search context.
8663 With optional argument SIBLINGS, on each level of the hierarchy all
8664 siblings are shown. This repairs the tree structure to what it would
8665 look like when opened with hierarchical calls to `org-cycle'."
8666 (interactive "P")
8667 (let ((org-show-hierarchy-above t)
8668 (org-show-following-heading t)
8669 (org-show-siblings (if siblings t org-show-siblings)))
8670 (org-show-context nil)))
8672 (defun org-highlight-new-match (beg end)
8673 "Highlight from BEG to END and mark the highlight is an occur headline."
8674 (let ((ov (org-make-overlay beg end)))
8675 (org-overlay-put ov 'face 'secondary-selection)
8676 (push ov org-occur-highlights)))
8678 (defun org-remove-occur-highlights (&optional beg end noremove)
8679 "Remove the occur highlights from the buffer.
8680 BEG and END are ignored. If NOREMOVE is nil, remove this function
8681 from the `before-change-functions' in the current buffer."
8682 (interactive)
8683 (unless org-inhibit-highlight-removal
8684 (mapc 'org-delete-overlay org-occur-highlights)
8685 (setq org-occur-highlights nil)
8686 (setq org-occur-parameters nil)
8687 (unless noremove
8688 (remove-hook 'before-change-functions
8689 'org-remove-occur-highlights 'local))))
8691 ;;;; Priorities
8693 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
8694 "Regular expression matching the priority indicator.")
8696 (defvar org-remove-priority-next-time nil)
8698 (defun org-priority-up ()
8699 "Increase the priority of the current item."
8700 (interactive)
8701 (org-priority 'up))
8703 (defun org-priority-down ()
8704 "Decrease the priority of the current item."
8705 (interactive)
8706 (org-priority 'down))
8708 (defun org-priority (&optional action)
8709 "Change the priority of an item by ARG.
8710 ACTION can be `set', `up', `down', or a character."
8711 (interactive)
8712 (setq action (or action 'set))
8713 (let (current new news have remove)
8714 (save-excursion
8715 (org-back-to-heading)
8716 (if (looking-at org-priority-regexp)
8717 (setq current (string-to-char (match-string 2))
8718 have t)
8719 (setq current org-default-priority))
8720 (cond
8721 ((or (eq action 'set)
8722 (if (featurep 'xemacs) (characterp action) (integerp action)))
8723 (if (not (eq action 'set))
8724 (setq new action)
8725 (message "Priority %c-%c, SPC to remove: "
8726 org-highest-priority org-lowest-priority)
8727 (setq new (read-char-exclusive)))
8728 (if (and (= (upcase org-highest-priority) org-highest-priority)
8729 (= (upcase org-lowest-priority) org-lowest-priority))
8730 (setq new (upcase new)))
8731 (cond ((equal new ?\ ) (setq remove t))
8732 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
8733 (error "Priority must be between `%c' and `%c'"
8734 org-highest-priority org-lowest-priority))))
8735 ((eq action 'up)
8736 (if (and (not have) (eq last-command this-command))
8737 (setq new org-lowest-priority)
8738 (setq new (if (and org-priority-start-cycle-with-default (not have))
8739 org-default-priority (1- current)))))
8740 ((eq action 'down)
8741 (if (and (not have) (eq last-command this-command))
8742 (setq new org-highest-priority)
8743 (setq new (if (and org-priority-start-cycle-with-default (not have))
8744 org-default-priority (1+ current)))))
8745 (t (error "Invalid action")))
8746 (if (or (< (upcase new) org-highest-priority)
8747 (> (upcase new) org-lowest-priority))
8748 (setq remove t))
8749 (setq news (format "%c" new))
8750 (if have
8751 (if remove
8752 (replace-match "" t t nil 1)
8753 (replace-match news t t nil 2))
8754 (if remove
8755 (error "No priority cookie found in line")
8756 (looking-at org-todo-line-regexp)
8757 (if (match-end 2)
8758 (progn
8759 (goto-char (match-end 2))
8760 (insert " [#" news "]"))
8761 (goto-char (match-beginning 3))
8762 (insert "[#" news "] ")))))
8763 (org-preserve-lc (org-set-tags nil 'align))
8764 (if remove
8765 (message "Priority removed")
8766 (message "Priority of current item set to %s" news))))
8769 (defun org-get-priority (s)
8770 "Find priority cookie and return priority."
8771 (save-match-data
8772 (if (not (string-match org-priority-regexp s))
8773 (* 1000 (- org-lowest-priority org-default-priority))
8774 (* 1000 (- org-lowest-priority
8775 (string-to-char (match-string 2 s)))))))
8777 ;;;; Tags
8779 (defvar org-agenda-archives-mode)
8780 (defun org-scan-tags (action matcher &optional todo-only)
8781 "Scan headline tags with inheritance and produce output ACTION.
8783 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
8784 or `agenda' to produce an entry list for an agenda view. It can also be
8785 a Lisp form or a function that should be called at each matched headline, in
8786 this case the return value is a list of all return values from these calls.
8788 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
8789 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
8790 only lines with a TODO keyword are included in the output."
8791 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
8792 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
8793 (org-re
8794 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
8795 (props (list 'face 'default
8796 'done-face 'org-done
8797 'undone-face 'default
8798 'mouse-face 'highlight
8799 'org-not-done-regexp org-not-done-regexp
8800 'org-todo-regexp org-todo-regexp
8801 'keymap org-agenda-keymap
8802 'help-echo
8803 (format "mouse-2 or RET jump to org file %s"
8804 (abbreviate-file-name
8805 (or (buffer-file-name (buffer-base-buffer))
8806 (buffer-name (buffer-base-buffer)))))))
8807 (case-fold-search nil)
8808 lspos tags tags-list
8809 (tags-alist (list (cons 0 (mapcar 'downcase org-file-tags))))
8810 (llast 0) rtn rtn1 level category i txt
8811 todo marker entry priority)
8812 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
8813 (setq action (list 'lambda nil action)))
8814 (save-excursion
8815 (goto-char (point-min))
8816 (when (eq action 'sparse-tree)
8817 (org-overview)
8818 (org-remove-occur-highlights))
8819 (while (re-search-forward re nil t)
8820 (catch :skip
8821 (setq todo (if (match-end 1) (match-string 2))
8822 tags (if (match-end 4) (match-string 4)))
8823 (goto-char (setq lspos (1+ (match-beginning 0))))
8824 (setq level (org-reduced-level (funcall outline-level))
8825 category (org-get-category))
8826 (setq i llast llast level)
8827 ;; remove tag lists from same and sublevels
8828 (while (>= i level)
8829 (when (setq entry (assoc i tags-alist))
8830 (setq tags-alist (delete entry tags-alist)))
8831 (setq i (1- i)))
8832 ;; add the next tags
8833 (when tags
8834 (setq tags (mapcar 'downcase (org-split-string tags ":"))
8835 tags-alist
8836 (cons (cons level tags) tags-alist)))
8837 ;; compile tags for current headline
8838 (setq tags-list
8839 (if org-use-tag-inheritance
8840 (apply 'append (mapcar 'cdr tags-alist))
8841 tags))
8842 (when (and tags org-use-tag-inheritance
8843 (not (eq t org-use-tag-inheritance)))
8844 ;; selective inheritance, remove uninherited ones
8845 (setcdr (car tags-alist)
8846 (org-remove-uniherited-tags (cdar tags-alist))))
8847 (when (and (or (not todo-only) (member todo org-not-done-keywords))
8848 (let ((case-fold-search t)) (eval matcher))
8850 (not (member org-archive-tag tags-list))
8851 ;; we have an archive tag, should we use this anyway?
8852 (or (not org-agenda-skip-archived-trees)
8853 (and (eq action 'agenda) org-agenda-archives-mode))))
8854 (unless (eq action 'sparse-tree) (org-agenda-skip))
8856 ;; select this headline
8858 (cond
8859 ((eq action 'sparse-tree)
8860 (and org-highlight-sparse-tree-matches
8861 (org-get-heading) (match-end 0)
8862 (org-highlight-new-match
8863 (match-beginning 0) (match-beginning 1)))
8864 (org-show-context 'tags-tree))
8865 ((eq action 'agenda)
8866 (setq txt (org-format-agenda-item
8868 (concat
8869 (if org-tags-match-list-sublevels
8870 (make-string (1- level) ?.) "")
8871 (org-get-heading))
8872 category tags-list)
8873 priority (org-get-priority txt))
8874 (goto-char lspos)
8875 (setq marker (org-agenda-new-marker))
8876 (org-add-props txt props
8877 'org-marker marker 'org-hd-marker marker 'org-category category
8878 'priority priority 'type "tagsmatch")
8879 (push txt rtn))
8880 ((functionp action)
8881 (save-excursion
8882 (setq rtn1 (funcall action))
8883 (push rtn1 rtn))
8884 (goto-char (point-at-eol)))
8885 (t (error "Invalid action")))
8887 ;; if we are to skip sublevels, jump to end of subtree
8888 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
8889 (when (and (eq action 'sparse-tree)
8890 (not org-sparse-tree-open-archived-trees))
8891 (org-hide-archived-subtrees (point-min) (point-max)))
8892 (nreverse rtn)))
8894 (defun org-remove-uniherited-tags (tags)
8895 "Remove all tags that are not inherited from the list TAGS."
8896 (cond
8897 ((eq org-use-tag-inheritance t) tags)
8898 ((not org-use-tag-inheritance) nil)
8899 ((stringp org-use-tag-inheritance)
8900 (delq nil (mapcar
8901 (lambda (x) (if (string-match org-use-tag-inheritance x) x nil))
8902 tags)))
8903 ((listp org-use-tag-inheritance)
8904 (delq nil (mapcar
8905 (lambda (x) (if (member x org-use-tag-inheritance) x nil))
8906 tags)))))
8908 (defvar todo-only) ;; dynamically scoped
8910 (defun org-tags-sparse-tree (&optional todo-only match)
8911 "Create a sparse tree according to tags string MATCH.
8912 MATCH can contain positive and negative selection of tags, like
8913 \"+WORK+URGENT-WITHBOSS\".
8914 If optional argument TODO_ONLY is non-nil, only select lines that are
8915 also TODO lines."
8916 (interactive "P")
8917 (org-prepare-agenda-buffers (list (current-buffer)))
8918 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
8920 (defvar org-cached-props nil)
8921 (defun org-cached-entry-get (pom property)
8922 (if (or (eq t org-use-property-inheritance)
8923 (and (stringp org-use-property-inheritance)
8924 (string-match org-use-property-inheritance property))
8925 (and (listp org-use-property-inheritance)
8926 (member property org-use-property-inheritance)))
8927 ;; Caching is not possible, check it directly
8928 (org-entry-get pom property 'inherit)
8929 ;; Get all properties, so that we can do complicated checks easily
8930 (cdr (assoc property (or org-cached-props
8931 (setq org-cached-props
8932 (org-entry-properties pom)))))))
8934 (defun org-global-tags-completion-table (&optional files)
8935 "Return the list of all tags in all agenda buffer/files."
8936 (save-excursion
8937 (org-uniquify
8938 (delq nil
8939 (apply 'append
8940 (mapcar
8941 (lambda (file)
8942 (set-buffer (find-file-noselect file))
8943 (append (org-get-buffer-tags)
8944 (mapcar (lambda (x) (if (stringp (car-safe x))
8945 (list (car-safe x)) nil))
8946 org-tag-alist)))
8947 (if (and files (car files))
8948 files
8949 (org-agenda-files))))))))
8951 (defun org-make-tags-matcher (match)
8952 "Create the TAGS//TODO matcher form for the selection string MATCH."
8953 ;; todo-only is scoped dynamically into this function, and the function
8954 ;; may change it it the matcher asksk for it.
8955 (unless match
8956 ;; Get a new match request, with completion
8957 (let ((org-last-tags-completion-table
8958 (org-global-tags-completion-table)))
8959 (setq match (completing-read
8960 "Match: " 'org-tags-completion-function nil nil nil
8961 'org-tags-history))))
8963 ;; Parse the string and create a lisp form
8964 (let ((match0 match)
8965 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
8966 minus tag mm
8967 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
8968 orterms term orlist re-p str-p level-p level-op time-p
8969 prop-p pn pv po cat-p gv)
8970 (if (string-match "/+" match)
8971 ;; match contains also a todo-matching request
8972 (progn
8973 (setq tagsmatch (substring match 0 (match-beginning 0))
8974 todomatch (substring match (match-end 0)))
8975 (if (string-match "^!" todomatch)
8976 (setq todo-only t todomatch (substring todomatch 1)))
8977 (if (string-match "^\\s-*$" todomatch)
8978 (setq todomatch nil)))
8979 ;; only matching tags
8980 (setq tagsmatch match todomatch nil))
8982 ;; Make the tags matcher
8983 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
8984 (setq tagsmatcher t)
8985 (setq orterms (org-split-string tagsmatch "|") orlist nil)
8986 (while (setq term (pop orterms))
8987 (while (and (equal (substring term -1) "\\") orterms)
8988 (setq term (concat term "|" (pop orterms)))) ; repair bad split
8989 (while (string-match re term)
8990 (setq minus (and (match-end 1)
8991 (equal (match-string 1 term) "-"))
8992 tag (match-string 2 term)
8993 re-p (equal (string-to-char tag) ?{)
8994 level-p (match-end 4)
8995 prop-p (match-end 5)
8996 mm (cond
8997 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
8998 (level-p
8999 (setq level-op (org-op-to-function (match-string 3 term)))
9000 `(,level-op level ,(string-to-number
9001 (match-string 4 term))))
9002 (prop-p
9003 (setq pn (match-string 5 term)
9004 po (match-string 6 term)
9005 pv (match-string 7 term)
9006 cat-p (equal pn "CATEGORY")
9007 re-p (equal (string-to-char pv) ?{)
9008 str-p (equal (string-to-char pv) ?\")
9009 time-p (save-match-data
9010 (string-match "^\"[[<].*[]>]\"$" pv))
9011 pv (if (or re-p str-p) (substring pv 1 -1) pv))
9012 (if time-p (setq pv (org-matcher-time pv)))
9013 (setq po (org-op-to-function po (if time-p 'time str-p)))
9014 (if (equal pn "CATEGORY")
9015 (setq gv '(get-text-property (point) 'org-category))
9016 (setq gv `(org-cached-entry-get nil ,pn)))
9017 (if re-p
9018 (if (eq po 'org<>)
9019 `(not (string-match ,pv (or ,gv "")))
9020 `(string-match ,pv (or ,gv "")))
9021 (if str-p
9022 `(,po (or ,gv "") ,pv)
9023 `(,po (string-to-number (or ,gv ""))
9024 ,(string-to-number pv) ))))
9025 (t `(member ,(downcase tag) tags-list)))
9026 mm (if minus (list 'not mm) mm)
9027 term (substring term (match-end 0)))
9028 (push mm tagsmatcher))
9029 (push (if (> (length tagsmatcher) 1)
9030 (cons 'and tagsmatcher)
9031 (car tagsmatcher))
9032 orlist)
9033 (setq tagsmatcher nil))
9034 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
9035 (setq tagsmatcher
9036 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
9037 ;; Make the todo matcher
9038 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
9039 (setq todomatcher t)
9040 (setq orterms (org-split-string todomatch "|") orlist nil)
9041 (while (setq term (pop orterms))
9042 (while (string-match re term)
9043 (setq minus (and (match-end 1)
9044 (equal (match-string 1 term) "-"))
9045 kwd (match-string 2 term)
9046 re-p (equal (string-to-char kwd) ?{)
9047 term (substring term (match-end 0))
9048 mm (if re-p
9049 `(string-match ,(substring kwd 1 -1) todo)
9050 (list 'equal 'todo kwd))
9051 mm (if minus (list 'not mm) mm))
9052 (push mm todomatcher))
9053 (push (if (> (length todomatcher) 1)
9054 (cons 'and todomatcher)
9055 (car todomatcher))
9056 orlist)
9057 (setq todomatcher nil))
9058 (setq todomatcher (if (> (length orlist) 1)
9059 (cons 'or orlist) (car orlist))))
9061 ;; Return the string and lisp forms of the matcher
9062 (setq matcher (if todomatcher
9063 (list 'and tagsmatcher todomatcher)
9064 tagsmatcher))
9065 (cons match0 matcher)))
9067 (defun org-op-to-function (op &optional stringp)
9068 "Turn an operator into the appropriate function."
9069 (setq op
9070 (cond
9071 ((equal op "<" ) '(< string< org-time<))
9072 ((equal op ">" ) '(> org-string> org-time>))
9073 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
9074 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
9075 ((member op '("=" "==")) '(= string= org-time=))
9076 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
9077 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
9079 (defun org<> (a b) (not (= a b)))
9080 (defun org-string<= (a b) (or (string= a b) (string< a b)))
9081 (defun org-string>= (a b) (not (string< a b)))
9082 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
9083 (defun org-string<> (a b) (not (string= a b)))
9084 (defun org-time= (a b) (= (org-2ft a) (org-2ft b)))
9085 (defun org-time< (a b) (< (org-2ft a) (org-2ft b)))
9086 (defun org-time<= (a b) (<= (org-2ft a) (org-2ft b)))
9087 (defun org-time> (a b) (> (org-2ft a) (org-2ft b)))
9088 (defun org-time>= (a b) (>= (org-2ft a) (org-2ft b)))
9089 (defun org-time<> (a b) (org<> (org-2ft a) (org-2ft b)))
9090 (defun org-2ft (s)
9091 "Convert S to a floating point time.
9092 If S is already a number, just return it. If it is a string, parse
9093 it as a time string and apply `float-time' to it. f S is nil, just return 0."
9094 (cond
9095 ((numberp s) s)
9096 ((stringp s)
9097 (condition-case nil
9098 (float-time (apply 'encode-time (org-parse-time-string s)))
9099 (error 0.)))
9100 (t 0.)))
9102 (defun org-matcher-time (s)
9103 (cond
9104 ((equal s "<now>") (float-time))
9105 ((equal s "<today>")
9106 (float-time (append '(0 0 0) (nthcdr 3 (decode-time)))))
9107 (t (org-2ft s))))
9109 (defun org-match-any-p (re list)
9110 "Does re match any element of list?"
9111 (setq list (mapcar (lambda (x) (string-match re x)) list))
9112 (delq nil list))
9114 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
9115 (defvar org-tags-overlay (org-make-overlay 1 1))
9116 (org-detach-overlay org-tags-overlay)
9118 (defun org-get-local-tags-at (&optional pos)
9119 "Get a list of tags defined in the current headline."
9120 (org-get-tags-at pos 'local))
9122 (defun org-get-local-tags ()
9123 "Get a list of tags defined in the current headline."
9124 (org-get-tags-at nil 'local))
9126 (defun org-get-tags-at (&optional pos local)
9127 "Get a list of all headline tags applicable at POS.
9128 POS defaults to point. If tags are inherited, the list contains
9129 the targets in the same sequence as the headlines appear, i.e.
9130 the tags of the current headline come last.
9131 When LOCAL is non-nil, only return tags from the current headline,
9132 ignore inherited ones."
9133 (interactive)
9134 (let (tags ltags lastpos parent)
9135 (save-excursion
9136 (save-restriction
9137 (widen)
9138 (goto-char (or pos (point)))
9139 (save-match-data
9140 (catch 'done
9141 (condition-case nil
9142 (progn
9143 (org-back-to-heading t)
9144 (while (not (equal lastpos (point)))
9145 (setq lastpos (point))
9146 (when (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
9147 (setq ltags (org-split-string
9148 (org-match-string-no-properties 1) ":"))
9149 (setq tags (append
9150 (if parent
9151 (org-remove-uniherited-tags ltags)
9152 ltags)
9153 tags)))
9154 (or org-use-tag-inheritance (throw 'done t))
9155 (if local (throw 'done t))
9156 (org-up-heading-all 1)
9157 (setq parent t)))
9158 (error nil)))))
9159 (append (org-remove-uniherited-tags org-file-tags) tags))))
9161 (defun org-toggle-tag (tag &optional onoff)
9162 "Toggle the tag TAG for the current line.
9163 If ONOFF is `on' or `off', don't toggle but set to this state."
9164 (unless (org-on-heading-p t) (error "Not on headling"))
9165 (let (res current)
9166 (save-excursion
9167 (beginning-of-line)
9168 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
9169 (point-at-eol) t)
9170 (progn
9171 (setq current (match-string 1))
9172 (replace-match ""))
9173 (setq current ""))
9174 (setq current (nreverse (org-split-string current ":")))
9175 (cond
9176 ((eq onoff 'on)
9177 (setq res t)
9178 (or (member tag current) (push tag current)))
9179 ((eq onoff 'off)
9180 (or (not (member tag current)) (setq current (delete tag current))))
9181 (t (if (member tag current)
9182 (setq current (delete tag current))
9183 (setq res t)
9184 (push tag current))))
9185 (end-of-line 1)
9186 (if current
9187 (progn
9188 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
9189 (org-set-tags nil t))
9190 (delete-horizontal-space))
9191 (run-hooks 'org-after-tags-change-hook))
9192 res))
9194 (defun org-align-tags-here (to-col)
9195 ;; Assumes that this is a headline
9196 (let ((pos (point)) (col (current-column)) ncol tags-l p)
9197 (beginning-of-line 1)
9198 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9199 (< pos (match-beginning 2)))
9200 (progn
9201 (setq tags-l (- (match-end 2) (match-beginning 2)))
9202 (goto-char (match-beginning 1))
9203 (insert " ")
9204 (delete-region (point) (1+ (match-beginning 2)))
9205 (setq ncol (max (1+ (current-column))
9206 (1+ col)
9207 (if (> to-col 0)
9208 to-col
9209 (- (abs to-col) tags-l))))
9210 (setq p (point))
9211 (insert (make-string (- ncol (current-column)) ?\ ))
9212 (setq ncol (current-column))
9213 (when indent-tabs-mode (tabify p (point-at-eol)))
9214 (org-move-to-column (min ncol col) t))
9215 (goto-char pos))))
9217 (defun org-set-tags-command (&optional arg just-align)
9218 "Call the set-tags command for the current entry."
9219 (interactive "P")
9220 (if (org-on-heading-p)
9221 (org-set-tags arg just-align)
9222 (save-excursion
9223 (org-back-to-heading t)
9224 (org-set-tags arg just-align))))
9226 (defun org-set-tags (&optional arg just-align)
9227 "Set the tags for the current headline.
9228 With prefix ARG, realign all tags in headings in the current buffer."
9229 (interactive "P")
9230 (let* ((re (concat "^" outline-regexp))
9231 (current (org-get-tags-string))
9232 (col (current-column))
9233 (org-setting-tags t)
9234 table current-tags inherited-tags ; computed below when needed
9235 tags p0 c0 c1 rpl)
9236 (if arg
9237 (save-excursion
9238 (goto-char (point-min))
9239 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
9240 (while (re-search-forward re nil t)
9241 (org-set-tags nil t)
9242 (end-of-line 1)))
9243 (message "All tags realigned to column %d" org-tags-column))
9244 (if just-align
9245 (setq tags current)
9246 ;; Get a new set of tags from the user
9247 (save-excursion
9248 (setq table (or org-tag-alist (org-get-buffer-tags))
9249 org-last-tags-completion-table table
9250 current-tags (org-split-string current ":")
9251 inherited-tags (nreverse
9252 (nthcdr (length current-tags)
9253 (nreverse (org-get-tags-at))))
9254 tags
9255 (if (or (eq t org-use-fast-tag-selection)
9256 (and org-use-fast-tag-selection
9257 (delq nil (mapcar 'cdr table))))
9258 (org-fast-tag-selection
9259 current-tags inherited-tags table
9260 (if org-fast-tag-selection-include-todo org-todo-key-alist))
9261 (let ((org-add-colon-after-tag-completion t))
9262 (org-trim
9263 (org-without-partial-completion
9264 (completing-read "Tags: " 'org-tags-completion-function
9265 nil nil current 'org-tags-history)))))))
9266 (while (string-match "[-+&]+" tags)
9267 ;; No boolean logic, just a list
9268 (setq tags (replace-match ":" t t tags))))
9270 (if (string-match "\\`[\t ]*\\'" tags)
9271 (setq tags "")
9272 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
9273 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
9275 ;; Insert new tags at the correct column
9276 (beginning-of-line 1)
9277 (cond
9278 ((and (equal current "") (equal tags "")))
9279 ((re-search-forward
9280 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
9281 (point-at-eol) t)
9282 (if (equal tags "")
9283 (setq rpl "")
9284 (goto-char (match-beginning 0))
9285 (setq c0 (current-column) p0 (point)
9286 c1 (max (1+ c0) (if (> org-tags-column 0)
9287 org-tags-column
9288 (- (- org-tags-column) (length tags))))
9289 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
9290 (replace-match rpl t t)
9291 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
9292 tags)
9293 (t (error "Tags alignment failed")))
9294 (org-move-to-column col)
9295 (unless just-align
9296 (run-hooks 'org-after-tags-change-hook)))))
9298 (defun org-change-tag-in-region (beg end tag off)
9299 "Add or remove TAG for each entry in the region.
9300 This works in the agenda, and also in an org-mode buffer."
9301 (interactive
9302 (list (region-beginning) (region-end)
9303 (let ((org-last-tags-completion-table
9304 (if (org-mode-p)
9305 (org-get-buffer-tags)
9306 (org-global-tags-completion-table))))
9307 (completing-read
9308 "Tag: " 'org-tags-completion-function nil nil nil
9309 'org-tags-history))
9310 (progn
9311 (message "[s]et or [r]emove? ")
9312 (equal (read-char-exclusive) ?r))))
9313 (if (fboundp 'deactivate-mark) (deactivate-mark))
9314 (let ((agendap (equal major-mode 'org-agenda-mode))
9315 l1 l2 m buf pos newhead (cnt 0))
9316 (goto-char end)
9317 (setq l2 (1- (org-current-line)))
9318 (goto-char beg)
9319 (setq l1 (org-current-line))
9320 (loop for l from l1 to l2 do
9321 (goto-line l)
9322 (setq m (get-text-property (point) 'org-hd-marker))
9323 (when (or (and (org-mode-p) (org-on-heading-p))
9324 (and agendap m))
9325 (setq buf (if agendap (marker-buffer m) (current-buffer))
9326 pos (if agendap m (point)))
9327 (with-current-buffer buf
9328 (save-excursion
9329 (save-restriction
9330 (goto-char pos)
9331 (setq cnt (1+ cnt))
9332 (org-toggle-tag tag (if off 'off 'on))
9333 (setq newhead (org-get-heading)))))
9334 (and agendap (org-agenda-change-all-lines newhead m))))
9335 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
9337 (defun org-tags-completion-function (string predicate &optional flag)
9338 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
9339 (confirm (lambda (x) (stringp (car x)))))
9340 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
9341 (setq s1 (match-string 1 string)
9342 s2 (match-string 2 string))
9343 (setq s1 "" s2 string))
9344 (cond
9345 ((eq flag nil)
9346 ;; try completion
9347 (setq rtn (try-completion s2 ctable confirm))
9348 (if (stringp rtn)
9349 (setq rtn
9350 (concat s1 s2 (substring rtn (length s2))
9351 (if (and org-add-colon-after-tag-completion
9352 (assoc rtn ctable))
9353 ":" ""))))
9354 rtn)
9355 ((eq flag t)
9356 ;; all-completions
9357 (all-completions s2 ctable confirm)
9359 ((eq flag 'lambda)
9360 ;; exact match?
9361 (assoc s2 ctable)))
9364 (defun org-fast-tag-insert (kwd tags face &optional end)
9365 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
9366 (insert (format "%-12s" (concat kwd ":"))
9367 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
9368 (or end "")))
9370 (defun org-fast-tag-show-exit (flag)
9371 (save-excursion
9372 (goto-line 3)
9373 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
9374 (replace-match ""))
9375 (when flag
9376 (end-of-line 1)
9377 (org-move-to-column (- (window-width) 19) t)
9378 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
9380 (defun org-set-current-tags-overlay (current prefix)
9381 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
9382 (if (featurep 'xemacs)
9383 (org-overlay-display org-tags-overlay (concat prefix s)
9384 'secondary-selection)
9385 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
9386 (org-overlay-display org-tags-overlay (concat prefix s)))))
9388 (defun org-fast-tag-selection (current inherited table &optional todo-table)
9389 "Fast tag selection with single keys.
9390 CURRENT is the current list of tags in the headline, INHERITED is the
9391 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
9392 possibly with grouping information. TODO-TABLE is a similar table with
9393 TODO keywords, should these have keys assigned to them.
9394 If the keys are nil, a-z are automatically assigned.
9395 Returns the new tags string, or nil to not change the current settings."
9396 (let* ((fulltable (append table todo-table))
9397 (maxlen (apply 'max (mapcar
9398 (lambda (x)
9399 (if (stringp (car x)) (string-width (car x)) 0))
9400 fulltable)))
9401 (buf (current-buffer))
9402 (expert (eq org-fast-tag-selection-single-key 'expert))
9403 (buffer-tags nil)
9404 (fwidth (+ maxlen 3 1 3))
9405 (ncol (/ (- (window-width) 4) fwidth))
9406 (i-face 'org-done)
9407 (c-face 'org-todo)
9408 tg cnt e c char c1 c2 ntable tbl rtn
9409 ov-start ov-end ov-prefix
9410 (exit-after-next org-fast-tag-selection-single-key)
9411 (done-keywords org-done-keywords)
9412 groups ingroup)
9413 (save-excursion
9414 (beginning-of-line 1)
9415 (if (looking-at
9416 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9417 (setq ov-start (match-beginning 1)
9418 ov-end (match-end 1)
9419 ov-prefix "")
9420 (setq ov-start (1- (point-at-eol))
9421 ov-end (1+ ov-start))
9422 (skip-chars-forward "^\n\r")
9423 (setq ov-prefix
9424 (concat
9425 (buffer-substring (1- (point)) (point))
9426 (if (> (current-column) org-tags-column)
9428 (make-string (- org-tags-column (current-column)) ?\ ))))))
9429 (org-move-overlay org-tags-overlay ov-start ov-end)
9430 (save-window-excursion
9431 (if expert
9432 (set-buffer (get-buffer-create " *Org tags*"))
9433 (delete-other-windows)
9434 (split-window-vertically)
9435 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
9436 (erase-buffer)
9437 (org-set-local 'org-done-keywords done-keywords)
9438 (org-fast-tag-insert "Inherited" inherited i-face "\n")
9439 (org-fast-tag-insert "Current" current c-face "\n\n")
9440 (org-fast-tag-show-exit exit-after-next)
9441 (org-set-current-tags-overlay current ov-prefix)
9442 (setq tbl fulltable char ?a cnt 0)
9443 (while (setq e (pop tbl))
9444 (cond
9445 ((equal e '(:startgroup))
9446 (push '() groups) (setq ingroup t)
9447 (when (not (= cnt 0))
9448 (setq cnt 0)
9449 (insert "\n"))
9450 (insert "{ "))
9451 ((equal e '(:endgroup))
9452 (setq ingroup nil cnt 0)
9453 (insert "}\n"))
9455 (setq tg (car e) c2 nil)
9456 (if (cdr e)
9457 (setq c (cdr e))
9458 ;; automatically assign a character.
9459 (setq c1 (string-to-char
9460 (downcase (substring
9461 tg (if (= (string-to-char tg) ?@) 1 0)))))
9462 (if (or (rassoc c1 ntable) (rassoc c1 table))
9463 (while (or (rassoc char ntable) (rassoc char table))
9464 (setq char (1+ char)))
9465 (setq c2 c1))
9466 (setq c (or c2 char)))
9467 (if ingroup (push tg (car groups)))
9468 (setq tg (org-add-props tg nil 'face
9469 (cond
9470 ((not (assoc tg table))
9471 (org-get-todo-face tg))
9472 ((member tg current) c-face)
9473 ((member tg inherited) i-face)
9474 (t nil))))
9475 (if (and (= cnt 0) (not ingroup)) (insert " "))
9476 (insert "[" c "] " tg (make-string
9477 (- fwidth 4 (length tg)) ?\ ))
9478 (push (cons tg c) ntable)
9479 (when (= (setq cnt (1+ cnt)) ncol)
9480 (insert "\n")
9481 (if ingroup (insert " "))
9482 (setq cnt 0)))))
9483 (setq ntable (nreverse ntable))
9484 (insert "\n")
9485 (goto-char (point-min))
9486 (if (and (not expert) (fboundp 'fit-window-to-buffer))
9487 (fit-window-to-buffer))
9488 (setq rtn
9489 (catch 'exit
9490 (while t
9491 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
9492 (if groups " [!] no groups" " [!]groups")
9493 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
9494 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9495 (cond
9496 ((= c ?\r) (throw 'exit t))
9497 ((= c ?!)
9498 (setq groups (not groups))
9499 (goto-char (point-min))
9500 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
9501 ((= c ?\C-c)
9502 (if (not expert)
9503 (org-fast-tag-show-exit
9504 (setq exit-after-next (not exit-after-next)))
9505 (setq expert nil)
9506 (delete-other-windows)
9507 (split-window-vertically)
9508 (org-switch-to-buffer-other-window " *Org tags*")
9509 (and (fboundp 'fit-window-to-buffer)
9510 (fit-window-to-buffer))))
9511 ((or (= c ?\C-g)
9512 (and (= c ?q) (not (rassoc c ntable))))
9513 (org-detach-overlay org-tags-overlay)
9514 (setq quit-flag t))
9515 ((= c ?\ )
9516 (setq current nil)
9517 (if exit-after-next (setq exit-after-next 'now)))
9518 ((= c ?\t)
9519 (condition-case nil
9520 (setq tg (completing-read
9521 "Tag: "
9522 (or buffer-tags
9523 (with-current-buffer buf
9524 (org-get-buffer-tags)))))
9525 (quit (setq tg "")))
9526 (when (string-match "\\S-" tg)
9527 (add-to-list 'buffer-tags (list tg))
9528 (if (member tg current)
9529 (setq current (delete tg current))
9530 (push tg current)))
9531 (if exit-after-next (setq exit-after-next 'now)))
9532 ((setq e (rassoc c todo-table) tg (car e))
9533 (with-current-buffer buf
9534 (save-excursion (org-todo tg)))
9535 (if exit-after-next (setq exit-after-next 'now)))
9536 ((setq e (rassoc c ntable) tg (car e))
9537 (if (member tg current)
9538 (setq current (delete tg current))
9539 (loop for g in groups do
9540 (if (member tg g)
9541 (mapc (lambda (x)
9542 (setq current (delete x current)))
9543 g)))
9544 (push tg current))
9545 (if exit-after-next (setq exit-after-next 'now))))
9547 ;; Create a sorted list
9548 (setq current
9549 (sort current
9550 (lambda (a b)
9551 (assoc b (cdr (memq (assoc a ntable) ntable))))))
9552 (if (eq exit-after-next 'now) (throw 'exit t))
9553 (goto-char (point-min))
9554 (beginning-of-line 2)
9555 (delete-region (point) (point-at-eol))
9556 (org-fast-tag-insert "Current" current c-face)
9557 (org-set-current-tags-overlay current ov-prefix)
9558 (while (re-search-forward
9559 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
9560 (setq tg (match-string 1))
9561 (add-text-properties
9562 (match-beginning 1) (match-end 1)
9563 (list 'face
9564 (cond
9565 ((member tg current) c-face)
9566 ((member tg inherited) i-face)
9567 (t (get-text-property (match-beginning 1) 'face))))))
9568 (goto-char (point-min)))))
9569 (org-detach-overlay org-tags-overlay)
9570 (if rtn
9571 (mapconcat 'identity current ":")
9572 nil))))
9574 (defun org-get-tags-string ()
9575 "Get the TAGS string in the current headline."
9576 (unless (org-on-heading-p t)
9577 (error "Not on a heading"))
9578 (save-excursion
9579 (beginning-of-line 1)
9580 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9581 (org-match-string-no-properties 1)
9582 "")))
9584 (defun org-get-tags ()
9585 "Get the list of tags specified in the current headline."
9586 (org-split-string (org-get-tags-string) ":"))
9588 (defun org-get-buffer-tags ()
9589 "Get a table of all tags used in the buffer, for completion."
9590 (let (tags)
9591 (save-excursion
9592 (goto-char (point-min))
9593 (while (re-search-forward
9594 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
9595 (when (equal (char-after (point-at-bol 0)) ?*)
9596 (mapc (lambda (x) (add-to-list 'tags x))
9597 (org-split-string (org-match-string-no-properties 1) ":")))))
9598 (mapcar 'list tags)))
9600 ;;;; The mapping API
9602 ;;;###autoload
9603 (defun org-map-entries (func &optional match scope &rest skip)
9604 "Call FUNC at each headline selected by MATCH in SCOPE.
9606 FUNC is a function or a lisp form. The function will be called without
9607 arguments, with the cursor positioned at the beginning of the headline.
9608 The return values of all calls to the function will be collected and
9609 returned as a list.
9611 MATCH is a tags/property/todo match as it is used in the agenda tags view.
9612 Only headlines that are matched by this query will be considered during
9613 the iteration. When MATCH is nil or t, all headlines will be
9614 visited by the iteration.
9616 SCOPE determines the scope of this command. It can be any of:
9618 nil The current buffer, respecting the restriction if any
9619 tree The subtree started with the entry at point
9620 file The current buffer, without restriction
9621 file-with-archives
9622 The current buffer, and any archives associated with it
9623 agenda All agenda files
9624 agenda-with-archives
9625 All agenda files with any archive files associated with them
9626 \(file1 file2 ...)
9627 If this is a list, all files in the list will be scanned
9629 The remaining args are treated as settings for the skipping facilities of
9630 the scanner. The following items can be given here:
9632 archive skip trees with the archive tag.
9633 comment skip trees with the COMMENT keyword
9634 function or Emacs Lisp form:
9635 will be used as value for `org-agenda-skip-function', so whenever
9636 the the function returns t, FUNC will not be called for that
9637 entry and search will continue from the point where the
9638 function leaves it."
9639 (let* ((org-agenda-archives-mode nil) ; just to make sure
9640 (org-agenda-skip-archived-trees (memq 'archive skip))
9641 (org-agenda-skip-comment-trees (memq 'comment skip))
9642 (org-agenda-skip-function
9643 (car (org-delete-all '(comment archive) skip)))
9644 (org-tags-match-list-sublevels t)
9645 matcher pos file
9646 org-todo-keywords-for-agenda
9647 org-done-keywords-for-agenda
9648 org-todo-keyword-alist-for-agenda
9649 org-tag-alist-for-agenda)
9651 (cond
9652 ((eq match t) (setq matcher t))
9653 ((eq match nil) (setq matcher t))
9654 (t (setq matcher (if match (org-make-tags-matcher match) t))))
9656 (when (eq scope 'tree)
9657 (org-back-to-heading t)
9658 (org-narrow-to-subtree)
9659 (setq scope nil))
9661 (if (not scope)
9662 (progn
9663 (org-prepare-agenda-buffers
9664 (list (buffer-file-name (current-buffer))))
9665 (org-scan-tags func matcher))
9666 ;; Get the right scope
9667 (setq pos (point))
9668 (cond
9669 ((and scope (listp scope) (symbolp (car scope)))
9670 (setq scope (eval scope)))
9671 ((eq scope 'agenda)
9672 (setq scope (org-agenda-files t)))
9673 ((eq scope 'agenda-with-archives)
9674 (setq scope (org-agenda-files t))
9675 (setq scope (org-add-archive-files scope)))
9676 ((eq scope 'file)
9677 (setq scope (list (buffer-file-name))))
9678 ((eq scope 'file-with-archives)
9679 (setq scope (org-add-archive-files (list (buffer-file-name))))))
9680 (org-prepare-agenda-buffers scope)
9681 (while (setq file (pop scope))
9682 (with-current-buffer (org-find-base-buffer-visiting file)
9683 (save-excursion
9684 (save-restriction
9685 (widen)
9686 (goto-char (point-min))
9687 (org-scan-tags func matcher))))))))
9689 ;;;; Properties
9691 ;;; Setting and retrieving properties
9693 (defconst org-special-properties
9694 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "PRIORITY"
9695 "TIMESTAMP" "TIMESTAMP_IA")
9696 "The special properties valid in Org-mode.
9698 These are properties that are not defined in the property drawer,
9699 but in some other way.")
9701 (defconst org-default-properties
9702 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
9703 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
9704 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
9705 "EXPORT_FILE_NAME" "EXPORT_TITLE")
9706 "Some properties that are used by Org-mode for various purposes.
9707 Being in this list makes sure that they are offered for completion.")
9709 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
9710 "Regular expression matching the first line of a property drawer.")
9712 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
9713 "Regular expression matching the first line of a property drawer.")
9715 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
9716 "Regular expression matching the first line of a property drawer.")
9718 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
9719 "Regular expression matching the first line of a property drawer.")
9721 (defconst org-property-drawer-re
9722 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
9723 org-property-end-re "\\)\n?")
9724 "Matches an entire property drawer.")
9726 (defconst org-clock-drawer-re
9727 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
9728 org-property-end-re "\\)\n?")
9729 "Matches an entire clock drawer.")
9731 (defun org-property-action ()
9732 "Do an action on properties."
9733 (interactive)
9734 (let (c)
9735 (org-at-property-p)
9736 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
9737 (setq c (read-char-exclusive))
9738 (cond
9739 ((equal c ?s)
9740 (call-interactively 'org-set-property))
9741 ((equal c ?d)
9742 (call-interactively 'org-delete-property))
9743 ((equal c ?D)
9744 (call-interactively 'org-delete-property-globally))
9745 ((equal c ?c)
9746 (call-interactively 'org-compute-property-at-point))
9747 (t (error "No such property action %c" c)))))
9749 (defun org-at-property-p ()
9750 "Is the cursor in a property line?"
9751 ;; FIXME: Does not check if we are actually in the drawer.
9752 ;; FIXME: also returns true on any drawers.....
9753 ;; This is used by C-c C-c for property action.
9754 (save-excursion
9755 (beginning-of-line 1)
9756 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
9758 (defun org-get-property-block (&optional beg end force)
9759 "Return the (beg . end) range of the body of the property drawer.
9760 BEG and END can be beginning and end of subtree, if not given
9761 they will be found.
9762 If the drawer does not exist and FORCE is non-nil, create the drawer."
9763 (catch 'exit
9764 (save-excursion
9765 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
9766 (end (or end (progn (outline-next-heading) (point)))))
9767 (goto-char beg)
9768 (if (re-search-forward org-property-start-re end t)
9769 (setq beg (1+ (match-end 0)))
9770 (if force
9771 (save-excursion
9772 (org-insert-property-drawer)
9773 (setq end (progn (outline-next-heading) (point))))
9774 (throw 'exit nil))
9775 (goto-char beg)
9776 (if (re-search-forward org-property-start-re end t)
9777 (setq beg (1+ (match-end 0)))))
9778 (if (re-search-forward org-property-end-re end t)
9779 (setq end (match-beginning 0))
9780 (or force (throw 'exit nil))
9781 (goto-char beg)
9782 (setq end beg)
9783 (org-indent-line-function)
9784 (insert ":END:\n"))
9785 (cons beg end)))))
9787 (defun org-entry-properties (&optional pom which)
9788 "Get all properties of the entry at point-or-marker POM.
9789 This includes the TODO keyword, the tags, time strings for deadline,
9790 scheduled, and clocking, and any additional properties defined in the
9791 entry. The return value is an alist, keys may occur multiple times
9792 if the property key was used several times.
9793 POM may also be nil, in which case the current entry is used.
9794 If WHICH is nil or `all', get all properties. If WHICH is
9795 `special' or `standard', only get that subclass."
9796 (setq which (or which 'all))
9797 (org-with-point-at pom
9798 (let ((clockstr (substring org-clock-string 0 -1))
9799 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
9800 beg end range props sum-props key value string clocksum)
9801 (save-excursion
9802 (when (condition-case nil (org-back-to-heading t) (error nil))
9803 (setq beg (point))
9804 (setq sum-props (get-text-property (point) 'org-summaries))
9805 (setq clocksum (get-text-property (point) :org-clock-minutes))
9806 (outline-next-heading)
9807 (setq end (point))
9808 (when (memq which '(all special))
9809 ;; Get the special properties, like TODO and tags
9810 (goto-char beg)
9811 (when (and (looking-at org-todo-line-regexp) (match-end 2))
9812 (push (cons "TODO" (org-match-string-no-properties 2)) props))
9813 (when (looking-at org-priority-regexp)
9814 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
9815 (when (and (setq value (org-get-tags-string))
9816 (string-match "\\S-" value))
9817 (push (cons "TAGS" value) props))
9818 (when (setq value (org-get-tags-at))
9819 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
9820 props))
9821 (while (re-search-forward org-maybe-keyword-time-regexp end t)
9822 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
9823 string (if (equal key clockstr)
9824 (org-no-properties
9825 (org-trim
9826 (buffer-substring
9827 (match-beginning 3) (goto-char (point-at-eol)))))
9828 (substring (org-match-string-no-properties 3) 1 -1)))
9829 (unless key
9830 (if (= (char-after (match-beginning 3)) ?\[)
9831 (setq key "TIMESTAMP_IA")
9832 (setq key "TIMESTAMP")))
9833 (when (or (equal key clockstr) (not (assoc key props)))
9834 (push (cons key string) props)))
9838 (when (memq which '(all standard))
9839 ;; Get the standard properties, like :PORP: ...
9840 (setq range (org-get-property-block beg end))
9841 (when range
9842 (goto-char (car range))
9843 (while (re-search-forward
9844 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
9845 (cdr range) t)
9846 (setq key (org-match-string-no-properties 1)
9847 value (org-trim (or (org-match-string-no-properties 2) "")))
9848 (unless (member key excluded)
9849 (push (cons key (or value "")) props)))))
9850 (if clocksum
9851 (push (cons "CLOCKSUM"
9852 (org-columns-number-to-string (/ (float clocksum) 60.)
9853 'add_times))
9854 props))
9855 (unless (assoc "CATEGORY" props)
9856 (setq value (or (org-get-category)
9857 (progn (org-refresh-category-properties)
9858 (org-get-category))))
9859 (push (cons "CATEGORY" value) props))
9860 (append sum-props (nreverse props)))))))
9862 (defun org-entry-get (pom property &optional inherit)
9863 "Get value of PROPERTY for entry at point-or-marker POM.
9864 If INHERIT is non-nil and the entry does not have the property,
9865 then also check higher levels of the hierarchy.
9866 If INHERIT is the symbol `selective', use inheritance only if the setting
9867 in `org-use-property-inheritance' selects PROPERTY for inheritance.
9868 If the property is present but empty, the return value is the empty string.
9869 If the property is not present at all, nil is returned."
9870 (org-with-point-at pom
9871 (if (and inherit (if (eq inherit 'selective)
9872 (org-property-inherit-p property)
9874 (org-entry-get-with-inheritance property)
9875 (if (member property org-special-properties)
9876 ;; We need a special property. Use brute force, get all properties.
9877 (cdr (assoc property (org-entry-properties nil 'special)))
9878 (let ((range (org-get-property-block)))
9879 (if (and range
9880 (goto-char (car range))
9881 (re-search-forward
9882 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
9883 (cdr range) t))
9884 ;; Found the property, return it.
9885 (if (match-end 1)
9886 (org-match-string-no-properties 1)
9887 "")))))))
9889 (defun org-property-or-variable-value (var &optional inherit)
9890 "Check if there is a property fixing the value of VAR.
9891 If yes, return this value. If not, return the current value of the variable."
9892 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
9893 (if (and prop (stringp prop) (string-match "\\S-" prop))
9894 (read prop)
9895 (symbol-value var))))
9897 (defun org-entry-delete (pom property)
9898 "Delete the property PROPERTY from entry at point-or-marker POM."
9899 (org-with-point-at pom
9900 (if (member property org-special-properties)
9901 nil ; cannot delete these properties.
9902 (let ((range (org-get-property-block)))
9903 (if (and range
9904 (goto-char (car range))
9905 (re-search-forward
9906 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
9907 (cdr range) t))
9908 (progn
9909 (delete-region (match-beginning 0) (1+ (point-at-eol)))
9911 nil)))))
9913 ;; Multi-values properties are properties that contain multiple values
9914 ;; These values are assumed to be single words, separated by whitespace.
9915 (defun org-entry-add-to-multivalued-property (pom property value)
9916 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
9917 (let* ((old (org-entry-get pom property))
9918 (values (and old (org-split-string old "[ \t]"))))
9919 (setq value (org-entry-protect-space value))
9920 (unless (member value values)
9921 (setq values (cons value values))
9922 (org-entry-put pom property
9923 (mapconcat 'identity values " ")))))
9925 (defun org-entry-remove-from-multivalued-property (pom property value)
9926 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
9927 (let* ((old (org-entry-get pom property))
9928 (values (and old (org-split-string old "[ \t]"))))
9929 (setq value (org-entry-protect-space value))
9930 (when (member value values)
9931 (setq values (delete value values))
9932 (org-entry-put pom property
9933 (mapconcat 'identity values " ")))))
9935 (defun org-entry-member-in-multivalued-property (pom property value)
9936 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
9937 (let* ((old (org-entry-get pom property))
9938 (values (and old (org-split-string old "[ \t]"))))
9939 (setq value (org-entry-protect-space value))
9940 (member value values)))
9942 (defun org-entry-get-multivalued-property (pom property)
9943 "Return a list of values in a multivalued property."
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-put-multivalued-property (pom property &rest values)
9949 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
9950 VALUES should be a list of strings. Spaces will be protected."
9951 (org-entry-put pom property
9952 (mapconcat 'org-entry-protect-space values " "))
9953 (let* ((value (org-entry-get pom property))
9954 (values (and value (org-split-string value "[ \t]"))))
9955 (mapcar 'org-entry-restore-space values)))
9957 (defun org-entry-protect-space (s)
9958 "Protect spaces and newline in string S."
9959 (while (string-match " " s)
9960 (setq s (replace-match "%20" t t s)))
9961 (while (string-match "\n" s)
9962 (setq s (replace-match "%0A" t t s)))
9965 (defun org-entry-restore-space (s)
9966 "Restore spaces and newline in string S."
9967 (while (string-match "%20" s)
9968 (setq s (replace-match " " t t s)))
9969 (while (string-match "%0A" s)
9970 (setq s (replace-match "\n" t t s)))
9973 (defvar org-entry-property-inherited-from (make-marker)
9974 "Marker pointing to the entry from where a proerty was inherited.
9975 Each call to `org-entry-get-with-inheritance' will set this marker to the
9976 location of the entry where the inheriance search matched. If there was
9977 no match, the marker will point nowhere.
9978 Note that also `org-entry-get' calls this function, if the INHERIT flag
9979 is set.")
9981 (defun org-entry-get-with-inheritance (property)
9982 "Get entry property, and search higher levels if not present."
9983 (move-marker org-entry-property-inherited-from nil)
9984 (let (tmp)
9985 (save-excursion
9986 (save-restriction
9987 (widen)
9988 (catch 'ex
9989 (while t
9990 (when (setq tmp (org-entry-get nil property))
9991 (org-back-to-heading t)
9992 (move-marker org-entry-property-inherited-from (point))
9993 (throw 'ex tmp))
9994 (or (org-up-heading-safe) (throw 'ex nil)))))
9995 (or tmp
9996 (cdr (assoc property org-file-properties))
9997 (cdr (assoc property org-global-properties))
9998 (cdr (assoc property org-global-properties-fixed))))))
10000 (defun org-entry-put (pom property value)
10001 "Set PROPERTY to VALUE for entry at point-or-marker POM."
10002 (org-with-point-at pom
10003 (org-back-to-heading t)
10004 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
10005 range)
10006 (cond
10007 ((equal property "TODO")
10008 (when (and (stringp value) (string-match "\\S-" value)
10009 (not (member value org-todo-keywords-1)))
10010 (error "\"%s\" is not a valid TODO state" value))
10011 (if (or (not value)
10012 (not (string-match "\\S-" value)))
10013 (setq value 'none))
10014 (org-todo value)
10015 (org-set-tags nil 'align))
10016 ((equal property "PRIORITY")
10017 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
10018 (string-to-char value) ?\ ))
10019 (org-set-tags nil 'align))
10020 ((equal property "SCHEDULED")
10021 (if (re-search-forward org-scheduled-time-regexp end t)
10022 (cond
10023 ((eq value 'earlier) (org-timestamp-change -1 'day))
10024 ((eq value 'later) (org-timestamp-change 1 'day))
10025 (t (call-interactively 'org-schedule)))
10026 (call-interactively 'org-schedule)))
10027 ((equal property "DEADLINE")
10028 (if (re-search-forward org-deadline-time-regexp end t)
10029 (cond
10030 ((eq value 'earlier) (org-timestamp-change -1 'day))
10031 ((eq value 'later) (org-timestamp-change 1 'day))
10032 (t (call-interactively 'org-deadline)))
10033 (call-interactively 'org-deadline)))
10034 ((member property org-special-properties)
10035 (error "The %s property can not yet be set with `org-entry-put'"
10036 property))
10037 (t ; a non-special property
10038 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
10039 (setq range (org-get-property-block beg end 'force))
10040 (goto-char (car range))
10041 (if (re-search-forward
10042 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
10043 (progn
10044 (delete-region (match-beginning 1) (match-end 1))
10045 (goto-char (match-beginning 1)))
10046 (goto-char (cdr range))
10047 (insert "\n")
10048 (backward-char 1)
10049 (org-indent-line-function)
10050 (insert ":" property ":"))
10051 (and value (insert " " value))
10052 (org-indent-line-function)))))))
10054 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
10055 "Get all property keys in the current buffer.
10056 With INCLUDE-SPECIALS, also list the special properties that relect things
10057 like tags and TODO state.
10058 With INCLUDE-DEFAULTS, also include properties that has special meaning
10059 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
10060 With INCLUDE-COLUMNS, also include property names given in COLUMN
10061 formats in the current buffer."
10062 (let (rtn range cfmt cols s p)
10063 (save-excursion
10064 (save-restriction
10065 (widen)
10066 (goto-char (point-min))
10067 (while (re-search-forward org-property-start-re nil t)
10068 (setq range (org-get-property-block))
10069 (goto-char (car range))
10070 (while (re-search-forward
10071 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
10072 (cdr range) t)
10073 (add-to-list 'rtn (org-match-string-no-properties 1)))
10074 (outline-next-heading))))
10076 (when include-specials
10077 (setq rtn (append org-special-properties rtn)))
10079 (when include-defaults
10080 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
10082 (when include-columns
10083 (save-excursion
10084 (save-restriction
10085 (widen)
10086 (goto-char (point-min))
10087 (while (re-search-forward
10088 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
10089 nil t)
10090 (setq cfmt (match-string 2) s 0)
10091 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
10092 cfmt s)
10093 (setq s (match-end 0)
10094 p (match-string 1 cfmt))
10095 (unless (or (equal p "ITEM")
10096 (member p org-special-properties))
10097 (add-to-list 'rtn (match-string 1 cfmt))))))))
10099 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
10101 (defun org-property-values (key)
10102 "Return a list of all values of property KEY."
10103 (save-excursion
10104 (save-restriction
10105 (widen)
10106 (goto-char (point-min))
10107 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
10108 values)
10109 (while (re-search-forward re nil t)
10110 (add-to-list 'values (org-trim (match-string 1))))
10111 (delete "" values)))))
10113 (defun org-insert-property-drawer ()
10114 "Insert a property drawer into the current entry."
10115 (interactive)
10116 (org-back-to-heading t)
10117 (looking-at outline-regexp)
10118 (let ((indent (- (match-end 0)(match-beginning 0)))
10119 (beg (point))
10120 (re (concat "^[ \t]*" org-keyword-time-regexp))
10121 end hiddenp)
10122 (outline-next-heading)
10123 (setq end (point))
10124 (goto-char beg)
10125 (while (re-search-forward re end t))
10126 (setq hiddenp (org-invisible-p))
10127 (end-of-line 1)
10128 (and (equal (char-after) ?\n) (forward-char 1))
10129 (while (looking-at "^[ \t]*\\(:CLOCK:\\|CLOCK\\|:END:\\)")
10130 (beginning-of-line 2))
10131 (org-skip-over-state-notes)
10132 (skip-chars-backward " \t\n\r")
10133 (if (eq (char-before) ?*) (forward-char 1))
10134 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
10135 (beginning-of-line 0)
10136 (org-indent-to-column indent)
10137 (beginning-of-line 2)
10138 (org-indent-to-column indent)
10139 (beginning-of-line 0)
10140 (if hiddenp
10141 (save-excursion
10142 (org-back-to-heading t)
10143 (hide-entry))
10144 (org-flag-drawer t))))
10146 (defun org-set-property (property value)
10147 "In the current entry, set PROPERTY to VALUE.
10148 When called interactively, this will prompt for a property name, offering
10149 completion on existing and default properties. And then it will prompt
10150 for a value, offering competion either on allowed values (via an inherited
10151 xxx_ALL property) or on existing values in other instances of this property
10152 in the current file."
10153 (interactive
10154 (let* ((completion-ignore-case t)
10155 (keys (org-buffer-property-keys nil t t))
10156 (prop0 (completing-read "Property: " (mapcar 'list keys)))
10157 (prop (if (member prop0 keys)
10158 prop0
10159 (or (cdr (assoc (downcase prop0)
10160 (mapcar (lambda (x) (cons (downcase x) x))
10161 keys)))
10162 prop0)))
10163 (cur (org-entry-get nil prop))
10164 (allowed (org-property-get-allowed-values nil prop 'table))
10165 (existing (mapcar 'list (org-property-values prop)))
10166 (val (if allowed
10167 (org-completing-read "Value: " allowed nil 'req-match)
10168 (org-completing-read
10169 (concat "Value" (if (and cur (string-match "\\S-" cur))
10170 (concat "[" cur "]") "")
10171 ": ")
10172 existing nil nil "" nil cur))))
10173 (list prop (if (equal val "") cur val))))
10174 (unless (equal (org-entry-get nil property) value)
10175 (org-entry-put nil property value)))
10177 (defun org-delete-property (property)
10178 "In the current entry, delete PROPERTY."
10179 (interactive
10180 (let* ((completion-ignore-case t)
10181 (prop (completing-read
10182 "Property: " (org-entry-properties nil 'standard))))
10183 (list prop)))
10184 (message "Property %s %s" property
10185 (if (org-entry-delete nil property)
10186 "deleted"
10187 "was not present in the entry")))
10189 (defun org-delete-property-globally (property)
10190 "Remove PROPERTY globally, from all entries."
10191 (interactive
10192 (let* ((completion-ignore-case t)
10193 (prop (completing-read
10194 "Globally remove property: "
10195 (mapcar 'list (org-buffer-property-keys)))))
10196 (list prop)))
10197 (save-excursion
10198 (save-restriction
10199 (widen)
10200 (goto-char (point-min))
10201 (let ((cnt 0))
10202 (while (re-search-forward
10203 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
10204 nil t)
10205 (setq cnt (1+ cnt))
10206 (replace-match ""))
10207 (message "Property \"%s\" removed from %d entries" property cnt)))))
10209 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
10211 (defun org-compute-property-at-point ()
10212 "Compute the property at point.
10213 This looks for an enclosing column format, extracts the operator and
10214 then applies it to the proerty in the column format's scope."
10215 (interactive)
10216 (unless (org-at-property-p)
10217 (error "Not at a property"))
10218 (let ((prop (org-match-string-no-properties 2)))
10219 (org-columns-get-format-and-top-level)
10220 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
10221 (error "No operator defined for property %s" prop))
10222 (org-columns-compute prop)))
10224 (defun org-property-get-allowed-values (pom property &optional table)
10225 "Get allowed values for the property PROPERTY.
10226 When TABLE is non-nil, return an alist that can directly be used for
10227 completion."
10228 (let (vals)
10229 (cond
10230 ((equal property "TODO")
10231 (setq vals (org-with-point-at pom
10232 (append org-todo-keywords-1 '("")))))
10233 ((equal property "PRIORITY")
10234 (let ((n org-lowest-priority))
10235 (while (>= n org-highest-priority)
10236 (push (char-to-string n) vals)
10237 (setq n (1- n)))))
10238 ((member property org-special-properties))
10240 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
10242 (when (and vals (string-match "\\S-" vals))
10243 (setq vals (car (read-from-string (concat "(" vals ")"))))
10244 (setq vals (mapcar (lambda (x)
10245 (cond ((stringp x) x)
10246 ((numberp x) (number-to-string x))
10247 ((symbolp x) (symbol-name x))
10248 (t "???")))
10249 vals)))))
10250 (if table (mapcar 'list vals) vals)))
10252 (defun org-property-previous-allowed-value (&optional previous)
10253 "Switch to the next allowed value for this property."
10254 (interactive)
10255 (org-property-next-allowed-value t))
10257 (defun org-property-next-allowed-value (&optional previous)
10258 "Switch to the next allowed value for this property."
10259 (interactive)
10260 (unless (org-at-property-p)
10261 (error "Not at a property"))
10262 (let* ((key (match-string 2))
10263 (value (match-string 3))
10264 (allowed (or (org-property-get-allowed-values (point) key)
10265 (and (member value '("[ ]" "[-]" "[X]"))
10266 '("[ ]" "[X]"))))
10267 nval)
10268 (unless allowed
10269 (error "Allowed values for this property have not been defined"))
10270 (if previous (setq allowed (reverse allowed)))
10271 (if (member value allowed)
10272 (setq nval (car (cdr (member value allowed)))))
10273 (setq nval (or nval (car allowed)))
10274 (if (equal nval value)
10275 (error "Only one allowed value for this property"))
10276 (org-at-property-p)
10277 (replace-match (concat " :" key ": " nval) t t)
10278 (org-indent-line-function)
10279 (beginning-of-line 1)
10280 (skip-chars-forward " \t")))
10282 (defun org-find-entry-with-id (ident)
10283 "Locate the entry that contains the ID property with exact value IDENT.
10284 IDENT can be a string, a symbol or a number, this function will search for
10285 the string representation of it.
10286 Return the position where this entry starts, or nil if there is no such entry."
10287 (let ((id (cond
10288 ((stringp ident) ident)
10289 ((symbol-name ident) (symbol-name ident))
10290 ((numberp ident) (number-to-string ident))
10291 (t (error "IDENT %s must be a string, symbol or number" ident))))
10292 (case-fold-search nil))
10293 (save-excursion
10294 (save-restriction
10295 (widen)
10296 (goto-char (point-min))
10297 (when (re-search-forward
10298 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
10299 nil t)
10300 (org-back-to-heading)
10301 (point))))))
10303 ;;;; Timestamps
10305 (defvar org-last-changed-timestamp nil)
10306 (defvar org-last-inserted-timestamp nil
10307 "The last time stamp inserted with `org-insert-time-stamp'.")
10308 (defvar org-time-was-given) ; dynamically scoped parameter
10309 (defvar org-end-time-was-given) ; dynamically scoped parameter
10310 (defvar org-ts-what) ; dynamically scoped parameter
10312 (defun org-time-stamp (arg &optional inactive)
10313 "Prompt for a date/time and insert a time stamp.
10314 If the user specifies a time like HH:MM, or if this command is called
10315 with a prefix argument, the time stamp will contain date and time.
10316 Otherwise, only the date will be included. All parts of a date not
10317 specified by the user will be filled in from the current date/time.
10318 So if you press just return without typing anything, the time stamp
10319 will represent the current date/time. If there is already a timestamp
10320 at the cursor, it will be modified."
10321 (interactive "P")
10322 (let* ((ts nil)
10323 (default-time
10324 ;; Default time is either today, or, when entering a range,
10325 ;; the range start.
10326 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
10327 (save-excursion
10328 (re-search-backward
10329 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
10330 (- (point) 20) t)))
10331 (apply 'encode-time (org-parse-time-string (match-string 1)))
10332 (current-time)))
10333 (default-input (and ts (org-get-compact-tod ts)))
10334 org-time-was-given org-end-time-was-given time)
10335 (cond
10336 ((and (org-at-timestamp-p t)
10337 (memq last-command '(org-time-stamp org-time-stamp-inactive))
10338 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
10339 (insert "--")
10340 (setq time (let ((this-command this-command))
10341 (org-read-date arg 'totime nil nil
10342 default-time default-input)))
10343 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
10344 ((org-at-timestamp-p t)
10345 (setq time (let ((this-command this-command))
10346 (org-read-date arg 'totime nil nil default-time default-input)))
10347 (when (org-at-timestamp-p t) ; just to get the match data
10348 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
10349 (replace-match "")
10350 (setq org-last-changed-timestamp
10351 (org-insert-time-stamp
10352 time (or org-time-was-given arg)
10353 inactive nil nil (list org-end-time-was-given))))
10354 (message "Timestamp updated"))
10356 (setq time (let ((this-command this-command))
10357 (org-read-date arg 'totime nil nil default-time default-input)))
10358 (org-insert-time-stamp time (or org-time-was-given arg) inactive
10359 nil nil (list org-end-time-was-given))))))
10361 ;; FIXME: can we use this for something else, like computing time differences?
10362 (defun org-get-compact-tod (s)
10363 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
10364 (let* ((t1 (match-string 1 s))
10365 (h1 (string-to-number (match-string 2 s)))
10366 (m1 (string-to-number (match-string 3 s)))
10367 (t2 (and (match-end 4) (match-string 5 s)))
10368 (h2 (and t2 (string-to-number (match-string 6 s))))
10369 (m2 (and t2 (string-to-number (match-string 7 s))))
10370 dh dm)
10371 (if (not t2)
10373 (setq dh (- h2 h1) dm (- m2 m1))
10374 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
10375 (concat t1 "+" (number-to-string dh)
10376 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
10378 (defun org-time-stamp-inactive (&optional arg)
10379 "Insert an inactive time stamp.
10380 An inactive time stamp is enclosed in square brackets instead of angle
10381 brackets. It is inactive in the sense that it does not trigger agenda entries,
10382 does not link to the calendar and cannot be changed with the S-cursor keys.
10383 So these are more for recording a certain time/date."
10384 (interactive "P")
10385 (org-time-stamp arg 'inactive))
10387 (defvar org-date-ovl (org-make-overlay 1 1))
10388 (org-overlay-put org-date-ovl 'face 'org-warning)
10389 (org-detach-overlay org-date-ovl)
10391 (defvar org-ans1) ; dynamically scoped parameter
10392 (defvar org-ans2) ; dynamically scoped parameter
10394 (defvar org-plain-time-of-day-regexp) ; defined below
10396 (defvar org-overriding-default-time nil) ; dynamically scoped
10397 (defvar org-read-date-overlay nil)
10398 (defvar org-dcst nil) ; dynamically scoped
10400 (defun org-read-date (&optional with-time to-time from-string prompt
10401 default-time default-input)
10402 "Read a date, possibly a time, and make things smooth for the user.
10403 The prompt will suggest to enter an ISO date, but you can also enter anything
10404 which will at least partially be understood by `parse-time-string'.
10405 Unrecognized parts of the date will default to the current day, month, year,
10406 hour and minute. If this command is called to replace a timestamp at point,
10407 of to enter the second timestamp of a range, the default time is taken from the
10408 existing stamp. For example,
10409 3-2-5 --> 2003-02-05
10410 feb 15 --> currentyear-02-15
10411 sep 12 9 --> 2009-09-12
10412 12:45 --> today 12:45
10413 22 sept 0:34 --> currentyear-09-22 0:34
10414 12 --> currentyear-currentmonth-12
10415 Fri --> nearest Friday (today or later)
10416 etc.
10418 Furthermore you can specify a relative date by giving, as the *first* thing
10419 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
10420 change in days weeks, months, years.
10421 With a single plus or minus, the date is relative to today. With a double
10422 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
10423 +4d --> four days from today
10424 +4 --> same as above
10425 +2w --> two weeks from today
10426 ++5 --> five days from default date
10428 The function understands only English month and weekday abbreviations,
10429 but this can be configured with the variables `parse-time-months' and
10430 `parse-time-weekdays'.
10432 While prompting, a calendar is popped up - you can also select the
10433 date with the mouse (button 1). The calendar shows a period of three
10434 months. To scroll it to other months, use the keys `>' and `<'.
10435 If you don't like the calendar, turn it off with
10436 \(setq org-read-date-popup-calendar nil)
10438 With optional argument TO-TIME, the date will immediately be converted
10439 to an internal time.
10440 With an optional argument WITH-TIME, the prompt will suggest to also
10441 insert a time. Note that when WITH-TIME is not set, you can still
10442 enter a time, and this function will inform the calling routine about
10443 this change. The calling routine may then choose to change the format
10444 used to insert the time stamp into the buffer to include the time.
10445 With optional argument FROM-STRING, read from this string instead from
10446 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
10447 the time/date that is used for everything that is not specified by the
10448 user."
10449 (require 'parse-time)
10450 (let* ((org-time-stamp-rounding-minutes
10451 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
10452 (org-dcst org-display-custom-times)
10453 (ct (org-current-time))
10454 (def (or org-overriding-default-time default-time ct))
10455 (defdecode (decode-time def))
10456 (dummy (progn
10457 (when (< (nth 2 defdecode) org-extend-today-until)
10458 (setcar (nthcdr 2 defdecode) -1)
10459 (setcar (nthcdr 1 defdecode) 59)
10460 (setq def (apply 'encode-time defdecode)
10461 defdecode (decode-time def)))))
10462 (calendar-move-hook nil)
10463 (calendar-view-diary-initially-flag nil)
10464 (view-diary-entries-initially nil)
10465 (calendar-view-holidays-initially-flag nil)
10466 (view-calendar-holidays-initially nil)
10467 (timestr (format-time-string
10468 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
10469 (prompt (concat (if prompt (concat prompt " ") "")
10470 (format "Date+time [%s]: " timestr)))
10471 ans (org-ans0 "") org-ans1 org-ans2 final)
10473 (cond
10474 (from-string (setq ans from-string))
10475 (org-read-date-popup-calendar
10476 (save-excursion
10477 (save-window-excursion
10478 (calendar)
10479 (calendar-forward-day (- (time-to-days def)
10480 (calendar-absolute-from-gregorian
10481 (calendar-current-date))))
10482 (org-eval-in-calendar nil t)
10483 (let* ((old-map (current-local-map))
10484 (map (copy-keymap calendar-mode-map))
10485 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
10486 (org-defkey map (kbd "RET") 'org-calendar-select)
10487 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
10488 'org-calendar-select-mouse)
10489 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
10490 'org-calendar-select-mouse)
10491 (org-defkey minibuffer-local-map [(meta shift left)]
10492 (lambda () (interactive)
10493 (org-eval-in-calendar '(calendar-backward-month 1))))
10494 (org-defkey minibuffer-local-map [(meta shift right)]
10495 (lambda () (interactive)
10496 (org-eval-in-calendar '(calendar-forward-month 1))))
10497 (org-defkey minibuffer-local-map [(meta shift up)]
10498 (lambda () (interactive)
10499 (org-eval-in-calendar '(calendar-backward-year 1))))
10500 (org-defkey minibuffer-local-map [(meta shift down)]
10501 (lambda () (interactive)
10502 (org-eval-in-calendar '(calendar-forward-year 1))))
10503 (org-defkey minibuffer-local-map [(shift up)]
10504 (lambda () (interactive)
10505 (org-eval-in-calendar '(calendar-backward-week 1))))
10506 (org-defkey minibuffer-local-map [(shift down)]
10507 (lambda () (interactive)
10508 (org-eval-in-calendar '(calendar-forward-week 1))))
10509 (org-defkey minibuffer-local-map [(shift left)]
10510 (lambda () (interactive)
10511 (org-eval-in-calendar '(calendar-backward-day 1))))
10512 (org-defkey minibuffer-local-map [(shift right)]
10513 (lambda () (interactive)
10514 (org-eval-in-calendar '(calendar-forward-day 1))))
10515 (org-defkey minibuffer-local-map ">"
10516 (lambda () (interactive)
10517 (org-eval-in-calendar '(scroll-calendar-left 1))))
10518 (org-defkey minibuffer-local-map "<"
10519 (lambda () (interactive)
10520 (org-eval-in-calendar '(scroll-calendar-right 1))))
10521 (unwind-protect
10522 (progn
10523 (use-local-map map)
10524 (add-hook 'post-command-hook 'org-read-date-display)
10525 (setq org-ans0 (read-string prompt default-input nil nil))
10526 ;; org-ans0: from prompt
10527 ;; org-ans1: from mouse click
10528 ;; org-ans2: from calendar motion
10529 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
10530 (remove-hook 'post-command-hook 'org-read-date-display)
10531 (use-local-map old-map)
10532 (when org-read-date-overlay
10533 (org-delete-overlay org-read-date-overlay)
10534 (setq org-read-date-overlay nil)))))))
10536 (t ; Naked prompt only
10537 (unwind-protect
10538 (setq ans (read-string prompt default-input nil timestr))
10539 (when org-read-date-overlay
10540 (org-delete-overlay org-read-date-overlay)
10541 (setq org-read-date-overlay nil)))))
10543 (setq final (org-read-date-analyze ans def defdecode))
10545 (if to-time
10546 (apply 'encode-time final)
10547 (if (and (boundp 'org-time-was-given) org-time-was-given)
10548 (format "%04d-%02d-%02d %02d:%02d"
10549 (nth 5 final) (nth 4 final) (nth 3 final)
10550 (nth 2 final) (nth 1 final))
10551 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
10552 (defvar def)
10553 (defvar defdecode)
10554 (defvar with-time)
10555 (defun org-read-date-display ()
10556 "Display the currrent date prompt interpretation in the minibuffer."
10557 (when org-read-date-display-live
10558 (when org-read-date-overlay
10559 (org-delete-overlay org-read-date-overlay))
10560 (let ((p (point)))
10561 (end-of-line 1)
10562 (while (not (equal (buffer-substring
10563 (max (point-min) (- (point) 4)) (point))
10564 " "))
10565 (insert " "))
10566 (goto-char p))
10567 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
10568 " " (or org-ans1 org-ans2)))
10569 (org-end-time-was-given nil)
10570 (f (org-read-date-analyze ans def defdecode))
10571 (fmts (if org-dcst
10572 org-time-stamp-custom-formats
10573 org-time-stamp-formats))
10574 (fmt (if (or with-time
10575 (and (boundp 'org-time-was-given) org-time-was-given))
10576 (cdr fmts)
10577 (car fmts)))
10578 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
10579 (when (and org-end-time-was-given
10580 (string-match org-plain-time-of-day-regexp txt))
10581 (setq txt (concat (substring txt 0 (match-end 0)) "-"
10582 org-end-time-was-given
10583 (substring txt (match-end 0)))))
10584 (setq org-read-date-overlay
10585 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
10586 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
10588 (defun org-read-date-analyze (ans def defdecode)
10589 "Analyze the combined answer of the date prompt."
10590 ;; FIXME: cleanup and comment
10591 (let (delta deltan deltaw deltadef year month day
10592 hour minute second wday pm h2 m2 tl wday1
10593 iso-year iso-weekday iso-week iso-year iso-date)
10595 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
10596 (setq ans "+0"))
10598 (when (setq delta (org-read-date-get-relative ans (current-time) def))
10599 (setq ans (replace-match "" t t ans)
10600 deltan (car delta)
10601 deltaw (nth 1 delta)
10602 deltadef (nth 2 delta)))
10604 ;; Check if there is an iso week date in there
10605 ;; If yes, sore the info and ostpone interpreting it until the rest
10606 ;; of the parsing is done
10607 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
10608 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
10609 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
10610 iso-week (string-to-number (match-string 2 ans)))
10611 (setq ans (replace-match "" t t ans)))
10613 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
10614 (when (string-match
10615 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
10616 (setq year (if (match-end 2)
10617 (string-to-number (match-string 2 ans))
10618 (string-to-number (format-time-string "%Y")))
10619 month (string-to-number (match-string 3 ans))
10620 day (string-to-number (match-string 4 ans)))
10621 (if (< year 100) (setq year (+ 2000 year)))
10622 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
10623 t nil ans)))
10624 ;; Help matching am/pm times, because `parse-time-string' does not do that.
10625 ;; If there is a time with am/pm, and *no* time without it, we convert
10626 ;; so that matching will be successful.
10627 (loop for i from 1 to 2 do ; twice, for end time as well
10628 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
10629 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
10630 (setq hour (string-to-number (match-string 1 ans))
10631 minute (if (match-end 3)
10632 (string-to-number (match-string 3 ans))
10634 pm (equal ?p
10635 (string-to-char (downcase (match-string 4 ans)))))
10636 (if (and (= hour 12) (not pm))
10637 (setq hour 0)
10638 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
10639 (setq ans (replace-match (format "%02d:%02d" hour minute)
10640 t t ans))))
10642 ;; Check if a time range is given as a duration
10643 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
10644 (setq hour (string-to-number (match-string 1 ans))
10645 h2 (+ hour (string-to-number (match-string 3 ans)))
10646 minute (string-to-number (match-string 2 ans))
10647 m2 (+ minute (if (match-end 5) (string-to-number
10648 (match-string 5 ans))0)))
10649 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
10650 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
10651 t t ans)))
10653 ;; Check if there is a time range
10654 (when (boundp 'org-end-time-was-given)
10655 (setq org-time-was-given nil)
10656 (when (and (string-match org-plain-time-of-day-regexp ans)
10657 (match-end 8))
10658 (setq org-end-time-was-given (match-string 8 ans))
10659 (setq ans (concat (substring ans 0 (match-beginning 7))
10660 (substring ans (match-end 7))))))
10662 (setq tl (parse-time-string ans)
10663 day (or (nth 3 tl) (nth 3 defdecode))
10664 month (or (nth 4 tl)
10665 (if (and org-read-date-prefer-future
10666 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
10667 (1+ (nth 4 defdecode))
10668 (nth 4 defdecode)))
10669 year (or (nth 5 tl)
10670 (if (and org-read-date-prefer-future
10671 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
10672 (1+ (nth 5 defdecode))
10673 (nth 5 defdecode)))
10674 hour (or (nth 2 tl) (nth 2 defdecode))
10675 minute (or (nth 1 tl) (nth 1 defdecode))
10676 second (or (nth 0 tl) 0)
10677 wday (nth 6 tl))
10679 ;; Special date definitions below
10680 (cond
10681 (iso-week
10682 ;; There was an iso week
10683 (setq year (or iso-year year)
10684 day (or iso-weekday wday 1)
10685 wday nil ; to make sure that the trigger below does not match
10686 iso-date (calendar-gregorian-from-absolute
10687 (calendar-absolute-from-iso
10688 (list iso-week day year))))
10689 ; FIXME: Should we also push ISO weeks into the future?
10690 ; (when (and org-read-date-prefer-future
10691 ; (not iso-year)
10692 ; (< (calendar-absolute-from-gregorian iso-date)
10693 ; (time-to-days (current-time))))
10694 ; (setq year (1+ year)
10695 ; iso-date (calendar-gregorian-from-absolute
10696 ; (calendar-absolute-from-iso
10697 ; (list iso-week day year)))))
10698 (setq month (car iso-date)
10699 year (nth 2 iso-date)
10700 day (nth 1 iso-date)))
10701 (deltan
10702 (unless deltadef
10703 (let ((now (decode-time (current-time))))
10704 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
10705 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
10706 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
10707 ((equal deltaw "m") (setq month (+ month deltan)))
10708 ((equal deltaw "y") (setq year (+ year deltan)))))
10709 ((and wday (not (nth 3 tl)))
10710 ;; Weekday was given, but no day, so pick that day in the week
10711 ;; on or after the derived date.
10712 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
10713 (unless (equal wday wday1)
10714 (setq day (+ day (% (- wday wday1 -7) 7))))))
10715 (if (and (boundp 'org-time-was-given)
10716 (nth 2 tl))
10717 (setq org-time-was-given t))
10718 (if (< year 100) (setq year (+ 2000 year)))
10719 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
10720 (list second minute hour day month year)))
10722 (defvar parse-time-weekdays)
10724 (defun org-read-date-get-relative (s today default)
10725 "Check string S for special relative date string.
10726 TODAY and DEFAULT are internal times, for today and for a default.
10727 Return shift list (N what def-flag)
10728 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
10729 N is the number of WHATs to shift.
10730 DEF-FLAG is t when a double ++ or -- indicates shift relative to
10731 the DEFAULT date rather than TODAY."
10732 (when (and
10733 (string-match
10734 (concat
10735 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
10736 "\\([0-9]+\\)?"
10737 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
10738 "\\([ \t]\\|$\\)") s)
10739 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
10740 (let* ((dir (if (> (match-end 1) (match-beginning 1))
10741 (string-to-char (substring (match-string 1 s) -1))
10742 ?+))
10743 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
10744 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
10745 (what (if (match-end 3) (match-string 3 s) "d"))
10746 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
10747 (date (if rel default today))
10748 (wday (nth 6 (decode-time date)))
10749 delta)
10750 (if wday1
10751 (progn
10752 (setq delta (mod (+ 7 (- wday1 wday)) 7))
10753 (if (= dir ?-) (setq delta (- delta 7)))
10754 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
10755 (list delta "d" rel))
10756 (list (* n (if (= dir ?-) -1 1)) what rel)))))
10758 (defun org-eval-in-calendar (form &optional keepdate)
10759 "Eval FORM in the calendar window and return to current window.
10760 Also, store the cursor date in variable org-ans2."
10761 (let ((sw (selected-window)))
10762 (select-window (get-buffer-window "*Calendar*"))
10763 (eval form)
10764 (when (and (not keepdate) (calendar-cursor-to-date))
10765 (let* ((date (calendar-cursor-to-date))
10766 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10767 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
10768 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
10769 (select-window sw)))
10771 (defun org-calendar-select ()
10772 "Return to `org-read-date' with the date currently selected.
10773 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
10774 (interactive)
10775 (when (calendar-cursor-to-date)
10776 (let* ((date (calendar-cursor-to-date))
10777 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10778 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
10779 (if (active-minibuffer-window) (exit-minibuffer))))
10781 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
10782 "Insert a date stamp for the date given by the internal TIME.
10783 WITH-HM means, use the stamp format that includes the time of the day.
10784 INACTIVE means use square brackets instead of angular ones, so that the
10785 stamp will not contribute to the agenda.
10786 PRE and POST are optional strings to be inserted before and after the
10787 stamp.
10788 The command returns the inserted time stamp."
10789 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
10790 stamp)
10791 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
10792 (insert-before-markers (or pre ""))
10793 (insert-before-markers (setq stamp (format-time-string fmt time)))
10794 (when (listp extra)
10795 (setq extra (car extra))
10796 (if (and (stringp extra)
10797 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
10798 (setq extra (format "-%02d:%02d"
10799 (string-to-number (match-string 1 extra))
10800 (string-to-number (match-string 2 extra))))
10801 (setq extra nil)))
10802 (when extra
10803 (backward-char 1)
10804 (insert-before-markers extra)
10805 (forward-char 1))
10806 (insert-before-markers (or post ""))
10807 (setq org-last-inserted-timestamp stamp)))
10809 (defun org-toggle-time-stamp-overlays ()
10810 "Toggle the use of custom time stamp formats."
10811 (interactive)
10812 (setq org-display-custom-times (not org-display-custom-times))
10813 (unless org-display-custom-times
10814 (let ((p (point-min)) (bmp (buffer-modified-p)))
10815 (while (setq p (next-single-property-change p 'display))
10816 (if (and (get-text-property p 'display)
10817 (eq (get-text-property p 'face) 'org-date))
10818 (remove-text-properties
10819 p (setq p (next-single-property-change p 'display))
10820 '(display t))))
10821 (set-buffer-modified-p bmp)))
10822 (if (featurep 'xemacs)
10823 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
10824 (org-restart-font-lock)
10825 (setq org-table-may-need-update t)
10826 (if org-display-custom-times
10827 (message "Time stamps are overlayed with custom format")
10828 (message "Time stamp overlays removed")))
10830 (defun org-display-custom-time (beg end)
10831 "Overlay modified time stamp format over timestamp between BEG and END."
10832 (let* ((ts (buffer-substring beg end))
10833 t1 w1 with-hm tf time str w2 (off 0))
10834 (save-match-data
10835 (setq t1 (org-parse-time-string ts t))
10836 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
10837 (setq off (- (match-end 0) (match-beginning 0)))))
10838 (setq end (- end off))
10839 (setq w1 (- end beg)
10840 with-hm (and (nth 1 t1) (nth 2 t1))
10841 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
10842 time (org-fix-decoded-time t1)
10843 str (org-add-props
10844 (format-time-string
10845 (substring tf 1 -1) (apply 'encode-time time))
10846 nil 'mouse-face 'highlight)
10847 w2 (length str))
10848 (if (not (= w2 w1))
10849 (add-text-properties (1+ beg) (+ 2 beg)
10850 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
10851 (if (featurep 'xemacs)
10852 (progn
10853 (put-text-property beg end 'invisible t)
10854 (put-text-property beg end 'end-glyph (make-glyph str)))
10855 (put-text-property beg end 'display str))))
10857 (defun org-translate-time (string)
10858 "Translate all timestamps in STRING to custom format.
10859 But do this only if the variable `org-display-custom-times' is set."
10860 (when org-display-custom-times
10861 (save-match-data
10862 (let* ((start 0)
10863 (re org-ts-regexp-both)
10864 t1 with-hm inactive tf time str beg end)
10865 (while (setq start (string-match re string start))
10866 (setq beg (match-beginning 0)
10867 end (match-end 0)
10868 t1 (save-match-data
10869 (org-parse-time-string (substring string beg end) t))
10870 with-hm (and (nth 1 t1) (nth 2 t1))
10871 inactive (equal (substring string beg (1+ beg)) "[")
10872 tf (funcall (if with-hm 'cdr 'car)
10873 org-time-stamp-custom-formats)
10874 time (org-fix-decoded-time t1)
10875 str (format-time-string
10876 (concat
10877 (if inactive "[" "<") (substring tf 1 -1)
10878 (if inactive "]" ">"))
10879 (apply 'encode-time time))
10880 string (replace-match str t t string)
10881 start (+ start (length str)))))))
10882 string)
10884 (defun org-fix-decoded-time (time)
10885 "Set 0 instead of nil for the first 6 elements of time.
10886 Don't touch the rest."
10887 (let ((n 0))
10888 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
10890 (defun org-days-to-time (timestamp-string)
10891 "Difference between TIMESTAMP-STRING and now in days."
10892 (- (time-to-days (org-time-string-to-time timestamp-string))
10893 (time-to-days (current-time))))
10895 (defun org-deadline-close (timestamp-string &optional ndays)
10896 "Is the time in TIMESTAMP-STRING close to the current date?"
10897 (setq ndays (or ndays (org-get-wdays timestamp-string)))
10898 (and (< (org-days-to-time timestamp-string) ndays)
10899 (not (org-entry-is-done-p))))
10901 (defun org-get-wdays (ts)
10902 "Get the deadline lead time appropriate for timestring TS."
10903 (cond
10904 ((<= org-deadline-warning-days 0)
10905 ;; 0 or negative, enforce this value no matter what
10906 (- org-deadline-warning-days))
10907 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
10908 ;; lead time is specified.
10909 (floor (* (string-to-number (match-string 1 ts))
10910 (cdr (assoc (match-string 2 ts)
10911 '(("d" . 1) ("w" . 7)
10912 ("m" . 30.4) ("y" . 365.25)))))))
10913 ;; go for the default.
10914 (t org-deadline-warning-days)))
10916 (defun org-calendar-select-mouse (ev)
10917 "Return to `org-read-date' with the date currently selected.
10918 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
10919 (interactive "e")
10920 (mouse-set-point ev)
10921 (when (calendar-cursor-to-date)
10922 (let* ((date (calendar-cursor-to-date))
10923 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10924 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
10925 (if (active-minibuffer-window) (exit-minibuffer))))
10927 (defun org-check-deadlines (ndays)
10928 "Check if there are any deadlines due or past due.
10929 A deadline is considered due if it happens within `org-deadline-warning-days'
10930 days from today's date. If the deadline appears in an entry marked DONE,
10931 it is not shown. The prefix arg NDAYS can be used to test that many
10932 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
10933 (interactive "P")
10934 (let* ((org-warn-days
10935 (cond
10936 ((equal ndays '(4)) 100000)
10937 (ndays (prefix-numeric-value ndays))
10938 (t (abs org-deadline-warning-days))))
10939 (case-fold-search nil)
10940 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
10941 (callback
10942 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
10944 (message "%d deadlines past-due or due within %d days"
10945 (org-occur regexp nil callback)
10946 org-warn-days)))
10948 (defun org-check-before-date (date)
10949 "Check if there are deadlines or scheduled entries before DATE."
10950 (interactive (list (org-read-date)))
10951 (let ((case-fold-search nil)
10952 (regexp (concat "\\<\\(" org-deadline-string
10953 "\\|" org-scheduled-string
10954 "\\) *<\\([^>]+\\)>"))
10955 (callback
10956 (lambda () (time-less-p
10957 (org-time-string-to-time (match-string 2))
10958 (org-time-string-to-time date)))))
10959 (message "%d entries before %s"
10960 (org-occur regexp nil callback) date)))
10962 (defun org-evaluate-time-range (&optional to-buffer)
10963 "Evaluate a time range by computing the difference between start and end.
10964 Normally the result is just printed in the echo area, but with prefix arg
10965 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
10966 If the time range is actually in a table, the result is inserted into the
10967 next column.
10968 For time difference computation, a year is assumed to be exactly 365
10969 days in order to avoid rounding problems."
10970 (interactive "P")
10972 (org-clock-update-time-maybe)
10973 (save-excursion
10974 (unless (org-at-date-range-p t)
10975 (goto-char (point-at-bol))
10976 (re-search-forward org-tr-regexp-both (point-at-eol) t))
10977 (if (not (org-at-date-range-p t))
10978 (error "Not at a time-stamp range, and none found in current line")))
10979 (let* ((ts1 (match-string 1))
10980 (ts2 (match-string 2))
10981 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
10982 (match-end (match-end 0))
10983 (time1 (org-time-string-to-time ts1))
10984 (time2 (org-time-string-to-time ts2))
10985 (t1 (time-to-seconds time1))
10986 (t2 (time-to-seconds time2))
10987 (diff (abs (- t2 t1)))
10988 (negative (< (- t2 t1) 0))
10989 ;; (ys (floor (* 365 24 60 60)))
10990 (ds (* 24 60 60))
10991 (hs (* 60 60))
10992 (fy "%dy %dd %02d:%02d")
10993 (fy1 "%dy %dd")
10994 (fd "%dd %02d:%02d")
10995 (fd1 "%dd")
10996 (fh "%02d:%02d")
10997 y d h m align)
10998 (if havetime
10999 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11001 d (floor (/ diff ds)) diff (mod diff ds)
11002 h (floor (/ diff hs)) diff (mod diff hs)
11003 m (floor (/ diff 60)))
11004 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11006 d (floor (+ (/ diff ds) 0.5))
11007 h 0 m 0))
11008 (if (not to-buffer)
11009 (message "%s" (org-make-tdiff-string y d h m))
11010 (if (org-at-table-p)
11011 (progn
11012 (goto-char match-end)
11013 (setq align t)
11014 (and (looking-at " *|") (goto-char (match-end 0))))
11015 (goto-char match-end))
11016 (if (looking-at
11017 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
11018 (replace-match ""))
11019 (if negative (insert " -"))
11020 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
11021 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
11022 (insert " " (format fh h m))))
11023 (if align (org-table-align))
11024 (message "Time difference inserted")))))
11026 (defun org-make-tdiff-string (y d h m)
11027 (let ((fmt "")
11028 (l nil))
11029 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
11030 l (push y l)))
11031 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
11032 l (push d l)))
11033 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
11034 l (push h l)))
11035 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
11036 l (push m l)))
11037 (apply 'format fmt (nreverse l))))
11039 (defun org-time-string-to-time (s)
11040 (apply 'encode-time (org-parse-time-string s)))
11042 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
11043 "Convert a time stamp to an absolute day number.
11044 If there is a specifyer for a cyclic time stamp, get the closest date to
11045 DAYNR.
11046 PREFER and SHOW_ALL are passed through to `org-closest-date'."
11047 (cond
11048 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
11049 (if (org-diary-sexp-entry (match-string 1 s) "" date)
11050 daynr
11051 (+ daynr 1000)))
11052 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
11053 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
11054 (time-to-days (current-time))) (match-string 0 s)
11055 prefer show-all))
11056 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
11058 (defun org-days-to-iso-week (days)
11059 "Return the iso week number."
11060 (require 'cal-iso)
11061 (car (calendar-iso-from-absolute days)))
11063 (defun org-small-year-to-year (year)
11064 "Convert 2-digit years into 4-digit years.
11065 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
11066 The year 2000 cannot be abbreviated. Any year lager than 99
11067 is retrned unchanged."
11068 (if (< year 38)
11069 (setq year (+ 2000 year))
11070 (if (< year 100)
11071 (setq year (+ 1900 year))))
11072 year)
11074 (defun org-time-from-absolute (d)
11075 "Return the time corresponding to date D.
11076 D may be an absolute day number, or a calendar-type list (month day year)."
11077 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
11078 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
11080 (defun org-calendar-holiday ()
11081 "List of holidays, for Diary display in Org-mode."
11082 (require 'holidays)
11083 (let ((hl (funcall
11084 (if (fboundp 'calendar-check-holidays)
11085 'calendar-check-holidays 'check-calendar-holidays) date)))
11086 (if hl (mapconcat 'identity hl "; "))))
11088 (defun org-diary-sexp-entry (sexp entry date)
11089 "Process a SEXP diary ENTRY for DATE."
11090 (require 'diary-lib)
11091 (let ((result (if calendar-debug-sexp
11092 (let ((stack-trace-on-error t))
11093 (eval (car (read-from-string sexp))))
11094 (condition-case nil
11095 (eval (car (read-from-string sexp)))
11096 (error
11097 (beep)
11098 (message "Bad sexp at line %d in %s: %s"
11099 (org-current-line)
11100 (buffer-file-name) sexp)
11101 (sleep-for 2))))))
11102 (cond ((stringp result) result)
11103 ((and (consp result)
11104 (stringp (cdr result))) (cdr result))
11105 (result entry)
11106 (t nil))))
11108 (defun org-diary-to-ical-string (frombuf)
11109 "Get iCalendar entries from diary entries in buffer FROMBUF.
11110 This uses the icalendar.el library."
11111 (let* ((tmpdir (if (featurep 'xemacs)
11112 (temp-directory)
11113 temporary-file-directory))
11114 (tmpfile (make-temp-name
11115 (expand-file-name "orgics" tmpdir)))
11116 buf rtn b e)
11117 (save-excursion
11118 (set-buffer frombuf)
11119 (icalendar-export-region (point-min) (point-max) tmpfile)
11120 (setq buf (find-buffer-visiting tmpfile))
11121 (set-buffer buf)
11122 (goto-char (point-min))
11123 (if (re-search-forward "^BEGIN:VEVENT" nil t)
11124 (setq b (match-beginning 0)))
11125 (goto-char (point-max))
11126 (if (re-search-backward "^END:VEVENT" nil t)
11127 (setq e (match-end 0)))
11128 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
11129 (kill-buffer buf)
11130 (delete-file tmpfile)
11131 rtn))
11133 (defun org-closest-date (start current change prefer show-all)
11134 "Find the date closest to CURRENT that is consistent with START and CHANGE.
11135 When PREFER is `past' return a date that is either CURRENT or past.
11136 When PREFER is `future', return a date that is either CURRENT or future.
11137 When SHOW-ALL is nil, only return the current occurence of a time stamp."
11138 ;; Make the proper lists from the dates
11139 (catch 'exit
11140 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
11141 dn dw sday cday n1 n2
11142 d m y y1 y2 date1 date2 nmonths nm ny m2)
11144 (setq start (org-date-to-gregorian start)
11145 current (org-date-to-gregorian
11146 (if show-all
11147 current
11148 (time-to-days (current-time))))
11149 sday (calendar-absolute-from-gregorian start)
11150 cday (calendar-absolute-from-gregorian current))
11152 (if (<= cday sday) (throw 'exit sday))
11154 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
11155 (setq dn (string-to-number (match-string 1 change))
11156 dw (cdr (assoc (match-string 2 change) a1)))
11157 (error "Invalid change specifyer: %s" change))
11158 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
11159 (cond
11160 ((eq dw 'day)
11161 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
11162 n2 (+ n1 dn)))
11163 ((eq dw 'year)
11164 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
11165 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
11166 (setq date1 (list m d y1)
11167 n1 (calendar-absolute-from-gregorian date1)
11168 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
11169 n2 (calendar-absolute-from-gregorian date2)))
11170 ((eq dw 'month)
11171 ;; approx number of month between the two dates
11172 (setq nmonths (floor (/ (- cday sday) 30.436875)))
11173 ;; How often does dn fit in there?
11174 (setq d (nth 1 start) m (car start) y (nth 2 start)
11175 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
11176 m (+ m nm)
11177 ny (floor (/ m 12))
11178 y (+ y ny)
11179 m (- m (* ny 12)))
11180 (while (> m 12) (setq m (- m 12) y (1+ y)))
11181 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
11182 (setq m2 (+ m dn) y2 y)
11183 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11184 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
11185 (while (<= n2 cday)
11186 (setq n1 n2 m m2 y y2)
11187 (setq m2 (+ m dn) y2 y)
11188 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11189 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
11190 (if show-all
11191 (cond
11192 ((eq prefer 'past) n1)
11193 ((eq prefer 'future) (if (= cday n1) n1 n2))
11194 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
11195 (cond
11196 ((eq prefer 'past) n1)
11197 ((eq prefer 'future) (if (= cday n1) n1 n2))
11198 (t (if (= cday n1) n1 n2)))))))
11200 (defun org-date-to-gregorian (date)
11201 "Turn any specification of DATE into a gregorian date for the calendar."
11202 (cond ((integerp date) (calendar-gregorian-from-absolute date))
11203 ((and (listp date) (= (length date) 3)) date)
11204 ((stringp date)
11205 (setq date (org-parse-time-string date))
11206 (list (nth 4 date) (nth 3 date) (nth 5 date)))
11207 ((listp date)
11208 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
11210 (defun org-parse-time-string (s &optional nodefault)
11211 "Parse the standard Org-mode time string.
11212 This should be a lot faster than the normal `parse-time-string'.
11213 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
11214 hour and minute fields will be nil if not given."
11215 (if (string-match org-ts-regexp0 s)
11216 (list 0
11217 (if (or (match-beginning 8) (not nodefault))
11218 (string-to-number (or (match-string 8 s) "0")))
11219 (if (or (match-beginning 7) (not nodefault))
11220 (string-to-number (or (match-string 7 s) "0")))
11221 (string-to-number (match-string 4 s))
11222 (string-to-number (match-string 3 s))
11223 (string-to-number (match-string 2 s))
11224 nil nil nil)
11225 (make-list 9 0)))
11227 (defun org-timestamp-up (&optional arg)
11228 "Increase the date item at the cursor by one.
11229 If the cursor is on the year, change the year. If it is on the month or
11230 the day, change that.
11231 With prefix ARG, change by that many units."
11232 (interactive "p")
11233 (org-timestamp-change (prefix-numeric-value arg)))
11235 (defun org-timestamp-down (&optional arg)
11236 "Decrease the date item at the cursor by one.
11237 If the cursor is on the year, change the year. If it is on the month or
11238 the day, change that.
11239 With prefix ARG, change by that many units."
11240 (interactive "p")
11241 (org-timestamp-change (- (prefix-numeric-value arg))))
11243 (defun org-timestamp-up-day (&optional arg)
11244 "Increase 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 'up)
11250 (org-timestamp-change (prefix-numeric-value arg) 'day)))
11252 (defun org-timestamp-down-day (&optional arg)
11253 "Decrease the date in the time stamp by one day.
11254 With prefix ARG, change that many days."
11255 (interactive "p")
11256 (if (and (not (org-at-timestamp-p t))
11257 (org-on-heading-p))
11258 (org-todo 'down)
11259 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
11261 (defun org-at-timestamp-p (&optional inactive-ok)
11262 "Determine if the cursor is in or at a timestamp."
11263 (interactive)
11264 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
11265 (pos (point))
11266 (ans (or (looking-at tsr)
11267 (save-excursion
11268 (skip-chars-backward "^[<\n\r\t")
11269 (if (> (point) (point-min)) (backward-char 1))
11270 (and (looking-at tsr)
11271 (> (- (match-end 0) pos) -1))))))
11272 (and ans
11273 (boundp 'org-ts-what)
11274 (setq org-ts-what
11275 (cond
11276 ((= pos (match-beginning 0)) 'bracket)
11277 ((= pos (1- (match-end 0))) 'bracket)
11278 ((org-pos-in-match-range pos 2) 'year)
11279 ((org-pos-in-match-range pos 3) 'month)
11280 ((org-pos-in-match-range pos 7) 'hour)
11281 ((org-pos-in-match-range pos 8) 'minute)
11282 ((or (org-pos-in-match-range pos 4)
11283 (org-pos-in-match-range pos 5)) 'day)
11284 ((and (> pos (or (match-end 8) (match-end 5)))
11285 (< pos (match-end 0)))
11286 (- pos (or (match-end 8) (match-end 5))))
11287 (t 'day))))
11288 ans))
11290 (defun org-toggle-timestamp-type ()
11291 "Toggle the type (<active> or [inactive]) of a time stamp."
11292 (interactive)
11293 (when (org-at-timestamp-p t)
11294 (save-excursion
11295 (goto-char (match-beginning 0))
11296 (insert (if (equal (char-after) ?<) "[" "<")) (delete-char 1)
11297 (goto-char (1- (match-end 0)))
11298 (insert (if (equal (char-after) ?>) "]" ">")) (delete-char 1))
11299 (message "Timestamp is now %sactive"
11300 (if (equal (char-before) ?>) "in" ""))))
11302 (defun org-timestamp-change (n &optional what)
11303 "Change the date in the time stamp at point.
11304 The date will be changed by N times WHAT. WHAT can be `day', `month',
11305 `year', `minute', `second'. If WHAT is not given, the cursor position
11306 in the timestamp determines what will be changed."
11307 (let ((pos (point))
11308 with-hm inactive
11309 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
11310 org-ts-what
11311 extra rem
11312 ts time time0)
11313 (if (not (org-at-timestamp-p t))
11314 (error "Not at a timestamp"))
11315 (if (and (not what) (eq org-ts-what 'bracket))
11316 (org-toggle-timestamp-type)
11317 (if (and (not what) (not (eq org-ts-what 'day))
11318 org-display-custom-times
11319 (get-text-property (point) 'display)
11320 (not (get-text-property (1- (point)) 'display)))
11321 (setq org-ts-what 'day))
11322 (setq org-ts-what (or what org-ts-what)
11323 inactive (= (char-after (match-beginning 0)) ?\[)
11324 ts (match-string 0))
11325 (replace-match "")
11326 (if (string-match
11327 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
11329 (setq extra (match-string 1 ts)))
11330 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
11331 (setq with-hm t))
11332 (setq time0 (org-parse-time-string ts))
11333 (when (and (eq org-ts-what 'minute)
11334 (eq current-prefix-arg nil))
11335 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
11336 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
11337 (setcar (cdr time0) (+ (nth 1 time0)
11338 (if (> n 0) (- rem) (- dm rem))))))
11339 (setq time
11340 (encode-time (or (car time0) 0)
11341 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
11342 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
11343 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
11344 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
11345 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
11346 (nthcdr 6 time0)))
11347 (when (integerp org-ts-what)
11348 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
11349 (if (eq what 'calendar)
11350 (let ((cal-date (org-get-date-from-calendar)))
11351 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
11352 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
11353 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
11354 (setcar time0 (or (car time0) 0))
11355 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
11356 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
11357 (setq time (apply 'encode-time time0))))
11358 (setq org-last-changed-timestamp
11359 (org-insert-time-stamp time with-hm inactive nil nil extra))
11360 (org-clock-update-time-maybe)
11361 (goto-char pos)
11362 ;; Try to recenter the calendar window, if any
11363 (if (and org-calendar-follow-timestamp-change
11364 (get-buffer-window "*Calendar*" t)
11365 (memq org-ts-what '(day month year)))
11366 (org-recenter-calendar (time-to-days time))))))
11368 (defun org-modify-ts-extra (s pos n dm)
11369 "Change the different parts of the lead-time and repeat fields in timestamp."
11370 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
11371 ng h m new rem)
11372 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
11373 (cond
11374 ((or (org-pos-in-match-range pos 2)
11375 (org-pos-in-match-range pos 3))
11376 (setq m (string-to-number (match-string 3 s))
11377 h (string-to-number (match-string 2 s)))
11378 (if (org-pos-in-match-range pos 2)
11379 (setq h (+ h n))
11380 (setq n (* dm (org-no-warnings (signum n))))
11381 (when (not (= 0 (setq rem (% m dm))))
11382 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
11383 (setq m (+ m n)))
11384 (if (< m 0) (setq m (+ m 60) h (1- h)))
11385 (if (> m 59) (setq m (- m 60) h (1+ h)))
11386 (setq h (min 24 (max 0 h)))
11387 (setq ng 1 new (format "-%02d:%02d" h m)))
11388 ((org-pos-in-match-range pos 6)
11389 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
11390 ((org-pos-in-match-range pos 5)
11391 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
11393 ((org-pos-in-match-range pos 9)
11394 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
11395 ((org-pos-in-match-range pos 8)
11396 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
11398 (when ng
11399 (setq s (concat
11400 (substring s 0 (match-beginning ng))
11402 (substring s (match-end ng))))))
11405 (defun org-recenter-calendar (date)
11406 "If the calendar is visible, recenter it to DATE."
11407 (let* ((win (selected-window))
11408 (cwin (get-buffer-window "*Calendar*" t))
11409 (calendar-move-hook nil))
11410 (when cwin
11411 (select-window cwin)
11412 (calendar-goto-date (if (listp date) date
11413 (calendar-gregorian-from-absolute date)))
11414 (select-window win))))
11416 (defun org-goto-calendar (&optional arg)
11417 "Go to the Emacs calendar at the current date.
11418 If there is a time stamp in the current line, go to that date.
11419 A prefix ARG can be used to force the current date."
11420 (interactive "P")
11421 (let ((tsr org-ts-regexp) diff
11422 (calendar-move-hook nil)
11423 (calendar-view-holidays-initially-flag nil)
11424 (view-calendar-holidays-initially nil)
11425 (calendar-view-diary-initially-flag nil)
11426 (view-diary-entries-initially nil))
11427 (if (or (org-at-timestamp-p)
11428 (save-excursion
11429 (beginning-of-line 1)
11430 (looking-at (concat ".*" tsr))))
11431 (let ((d1 (time-to-days (current-time)))
11432 (d2 (time-to-days
11433 (org-time-string-to-time (match-string 1)))))
11434 (setq diff (- d2 d1))))
11435 (calendar)
11436 (calendar-goto-today)
11437 (if (and diff (not arg)) (calendar-forward-day diff))))
11439 (defun org-get-date-from-calendar ()
11440 "Return a list (month day year) of date at point in calendar."
11441 (with-current-buffer "*Calendar*"
11442 (save-match-data
11443 (calendar-cursor-to-date))))
11445 (defun org-date-from-calendar ()
11446 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
11447 If there is already a time stamp at the cursor position, update it."
11448 (interactive)
11449 (if (org-at-timestamp-p t)
11450 (org-timestamp-change 0 'calendar)
11451 (let ((cal-date (org-get-date-from-calendar)))
11452 (org-insert-time-stamp
11453 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
11455 (defun org-minutes-to-hh:mm-string (m)
11456 "Compute H:MM from a number of minutes."
11457 (let ((h (/ m 60)))
11458 (setq m (- m (* 60 h)))
11459 (format org-time-clocksum-format h m)))
11461 (defun org-hh:mm-string-to-minutes (s)
11462 "Convert a string H:MM to a number of minutes."
11463 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
11464 (+ (* (string-to-number (match-string 1 s)) 60)
11465 (string-to-number (match-string 2 s)))
11468 ;;;; Agenda files
11470 ;;;###autoload
11471 (defun org-iswitchb (&optional arg)
11472 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
11473 With a prefix argument, restrict available to files.
11474 With two prefix arguments, restrict available buffers to agenda files.
11476 Due to some yet unresolved reason, the global function
11477 `iswitchb-mode' needs to be active for this function to work."
11478 (interactive "P")
11479 (require 'iswitchb)
11480 (let ((enabled iswitchb-mode) blist)
11481 (or enabled (iswitchb-mode 1))
11482 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
11483 ((equal arg '(16)) (org-buffer-list 'agenda))
11484 (t (org-buffer-list))))
11485 (unwind-protect
11486 (let ((iswitchb-make-buflist-hook
11487 (lambda ()
11488 (setq iswitchb-temp-buflist
11489 (mapcar 'buffer-name blist)))))
11490 (switch-to-buffer
11491 (iswitchb-read-buffer
11492 "Switch-to: " nil t))
11493 (or enabled (iswitchb-mode -1))))))
11495 (defun org-buffer-list (&optional predicate exclude-tmp)
11496 "Return a list of Org buffers.
11497 PREDICATE can be `export', `files' or `agenda'.
11499 export restrict the list to Export buffers.
11500 files restrict the list to buffers visiting Org files.
11501 agenda restrict the list to buffers visiting agenda files.
11503 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
11504 (let* ((bfn nil)
11505 (agenda-files (and (eq predicate 'agenda)
11506 (mapcar 'file-truename (org-agenda-files t))))
11507 (filter
11508 (cond
11509 ((eq predicate 'files)
11510 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
11511 ((eq predicate 'export)
11512 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
11513 ((eq predicate 'agenda)
11514 (lambda (b)
11515 (with-current-buffer b
11516 (and (eq major-mode 'org-mode)
11517 (setq bfn (buffer-file-name b))
11518 (member (file-truename bfn) agenda-files)))))
11519 (t (lambda (b) (with-current-buffer b
11520 (or (eq major-mode 'org-mode)
11521 (string-match "\*Org .*Export"
11522 (buffer-name b)))))))))
11523 (delq nil
11524 (mapcar
11525 (lambda(b)
11526 (if (and (funcall filter b)
11527 (or (not exclude-tmp)
11528 (not (string-match "tmp" (buffer-name b)))))
11530 nil))
11531 (buffer-list)))))
11533 (defun org-agenda-files (&optional unrestricted archives)
11534 "Get the list of agenda files.
11535 Optional UNRESTRICTED means return the full list even if a restriction
11536 is currently in place.
11537 When ARCHIVES is t, include all archive files hat are really being
11538 used by the agenda files. If ARCHIVE is `ifmode', do this only if
11539 `org-agenda-archives-mode' is t."
11540 (let ((files
11541 (cond
11542 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
11543 ((stringp org-agenda-files) (org-read-agenda-file-list))
11544 ((listp org-agenda-files) org-agenda-files)
11545 (t (error "Invalid value of `org-agenda-files'")))))
11546 (setq files (apply 'append
11547 (mapcar (lambda (f)
11548 (if (file-directory-p f)
11549 (directory-files
11550 f t org-agenda-file-regexp)
11551 (list f)))
11552 files)))
11553 (when org-agenda-skip-unavailable-files
11554 (setq files (delq nil
11555 (mapcar (function
11556 (lambda (file)
11557 (and (file-readable-p file) file)))
11558 files))))
11559 (when (or (eq archives t)
11560 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
11561 (setq files (org-add-archive-files files)))
11562 files))
11564 (defun org-edit-agenda-file-list ()
11565 "Edit the list of agenda files.
11566 Depending on setup, this either uses customize to edit the variable
11567 `org-agenda-files', or it visits the file that is holding the list. In the
11568 latter case, the buffer is set up in a way that saving it automatically kills
11569 the buffer and restores the previous window configuration."
11570 (interactive)
11571 (if (stringp org-agenda-files)
11572 (let ((cw (current-window-configuration)))
11573 (find-file org-agenda-files)
11574 (org-set-local 'org-window-configuration cw)
11575 (org-add-hook 'after-save-hook
11576 (lambda ()
11577 (set-window-configuration
11578 (prog1 org-window-configuration
11579 (kill-buffer (current-buffer))))
11580 (org-install-agenda-files-menu)
11581 (message "New agenda file list installed"))
11582 nil 'local)
11583 (message "%s" (substitute-command-keys
11584 "Edit list and finish with \\[save-buffer]")))
11585 (customize-variable 'org-agenda-files)))
11587 (defun org-store-new-agenda-file-list (list)
11588 "Set new value for the agenda file list and save it correcly."
11589 (if (stringp org-agenda-files)
11590 (let ((f org-agenda-files) b)
11591 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
11592 (with-temp-file f
11593 (insert (mapconcat 'identity list "\n") "\n")))
11594 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
11595 (setq org-agenda-files list)
11596 (customize-save-variable 'org-agenda-files org-agenda-files))))
11598 (defun org-read-agenda-file-list ()
11599 "Read the list of agenda files from a file."
11600 (when (file-directory-p org-agenda-files)
11601 (error "`org-agenda-files' cannot be a single directory"))
11602 (when (stringp org-agenda-files)
11603 (with-temp-buffer
11604 (insert-file-contents org-agenda-files)
11605 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
11608 ;;;###autoload
11609 (defun org-cycle-agenda-files ()
11610 "Cycle through the files in `org-agenda-files'.
11611 If the current buffer visits an agenda file, find the next one in the list.
11612 If the current buffer does not, find the first agenda file."
11613 (interactive)
11614 (let* ((fs (org-agenda-files t))
11615 (files (append fs (list (car fs))))
11616 (tcf (if buffer-file-name (file-truename buffer-file-name)))
11617 file)
11618 (unless files (error "No agenda files"))
11619 (catch 'exit
11620 (while (setq file (pop files))
11621 (if (equal (file-truename file) tcf)
11622 (when (car files)
11623 (find-file (car files))
11624 (throw 'exit t))))
11625 (find-file (car fs)))
11626 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
11628 (defun org-agenda-file-to-front (&optional to-end)
11629 "Move/add the current file to the top of the agenda file list.
11630 If the file is not present in the list, it is added to the front. If it is
11631 present, it is moved there. With optional argument TO-END, add/move to the
11632 end of the list."
11633 (interactive "P")
11634 (let ((org-agenda-skip-unavailable-files nil)
11635 (file-alist (mapcar (lambda (x)
11636 (cons (file-truename x) x))
11637 (org-agenda-files t)))
11638 (ctf (file-truename buffer-file-name))
11639 x had)
11640 (setq x (assoc ctf file-alist) had x)
11642 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
11643 (if to-end
11644 (setq file-alist (append (delq x file-alist) (list x)))
11645 (setq file-alist (cons x (delq x file-alist))))
11646 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
11647 (org-install-agenda-files-menu)
11648 (message "File %s to %s of agenda file list"
11649 (if had "moved" "added") (if to-end "end" "front"))))
11651 (defun org-remove-file (&optional file)
11652 "Remove current file from the list of files in variable `org-agenda-files'.
11653 These are the files which are being checked for agenda entries.
11654 Optional argument FILE means, use this file instead of the current."
11655 (interactive)
11656 (let* ((org-agenda-skip-unavailable-files nil)
11657 (file (or file buffer-file-name))
11658 (true-file (file-truename file))
11659 (afile (abbreviate-file-name file))
11660 (files (delq nil (mapcar
11661 (lambda (x)
11662 (if (equal true-file
11663 (file-truename x))
11664 nil x))
11665 (org-agenda-files t)))))
11666 (if (not (= (length files) (length (org-agenda-files t))))
11667 (progn
11668 (org-store-new-agenda-file-list files)
11669 (org-install-agenda-files-menu)
11670 (message "Removed file: %s" afile))
11671 (message "File was not in list: %s (not removed)" afile))))
11673 (defun org-file-menu-entry (file)
11674 (vector file (list 'find-file file) t))
11676 (defun org-check-agenda-file (file)
11677 "Make sure FILE exists. If not, ask user what to do."
11678 (when (not (file-exists-p file))
11679 (message "non-existent file %s. [R]emove from list or [A]bort?"
11680 (abbreviate-file-name file))
11681 (let ((r (downcase (read-char-exclusive))))
11682 (cond
11683 ((equal r ?r)
11684 (org-remove-file file)
11685 (throw 'nextfile t))
11686 (t (error "Abort"))))))
11688 (defun org-get-agenda-file-buffer (file)
11689 "Get a buffer visiting FILE. If the buffer needs to be created, add
11690 it to the list of buffers which might be released later."
11691 (let ((buf (org-find-base-buffer-visiting file)))
11692 (if buf
11693 buf ; just return it
11694 ;; Make a new buffer and remember it
11695 (setq buf (find-file-noselect file))
11696 (if buf (push buf org-agenda-new-buffers))
11697 buf)))
11699 (defun org-release-buffers (blist)
11700 "Release all buffers in list, asking the user for confirmation when needed.
11701 When a buffer is unmodified, it is just killed. When modified, it is saved
11702 \(if the user agrees) and then killed."
11703 (let (buf file)
11704 (while (setq buf (pop blist))
11705 (setq file (buffer-file-name buf))
11706 (when (and (buffer-modified-p buf)
11707 file
11708 (y-or-n-p (format "Save file %s? " file)))
11709 (with-current-buffer buf (save-buffer)))
11710 (kill-buffer buf))))
11712 (defun org-prepare-agenda-buffers (files)
11713 "Create buffers for all agenda files, protect archived trees and comments."
11714 (interactive)
11715 (let ((pa '(:org-archived t))
11716 (pc '(:org-comment t))
11717 (pall '(:org-archived t :org-comment t))
11718 (inhibit-read-only t)
11719 (rea (concat ":" org-archive-tag ":"))
11720 bmp file re)
11721 (save-excursion
11722 (save-restriction
11723 (while (setq file (pop files))
11724 (if (bufferp file)
11725 (set-buffer file)
11726 (org-check-agenda-file file)
11727 (set-buffer (org-get-agenda-file-buffer file)))
11728 (widen)
11729 (setq bmp (buffer-modified-p))
11730 (org-refresh-category-properties)
11731 (setq org-todo-keywords-for-agenda
11732 (append org-todo-keywords-for-agenda org-todo-keywords-1))
11733 (setq org-done-keywords-for-agenda
11734 (append org-done-keywords-for-agenda org-done-keywords))
11735 (setq org-todo-keyword-alist-for-agenda
11736 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
11737 (setq org-tag-alist-for-agenda
11738 (append org-tag-alist-for-agenda org-tag-alist))
11740 (save-excursion
11741 (remove-text-properties (point-min) (point-max) pall)
11742 (when org-agenda-skip-archived-trees
11743 (goto-char (point-min))
11744 (while (re-search-forward rea nil t)
11745 (if (org-on-heading-p t)
11746 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
11747 (goto-char (point-min))
11748 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
11749 (while (re-search-forward re nil t)
11750 (add-text-properties
11751 (match-beginning 0) (org-end-of-subtree t) pc)))
11752 (set-buffer-modified-p bmp))))
11753 (setq org-todo-keyword-alist-for-agenda
11754 (org-uniquify org-todo-keyword-alist-for-agenda)
11755 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
11757 ;;;; Embedded LaTeX
11759 (defvar org-cdlatex-mode-map (make-sparse-keymap)
11760 "Keymap for the minor `org-cdlatex-mode'.")
11762 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
11763 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
11764 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
11765 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
11766 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
11768 (defvar org-cdlatex-texmathp-advice-is-done nil
11769 "Flag remembering if we have applied the advice to texmathp already.")
11771 (define-minor-mode org-cdlatex-mode
11772 "Toggle the minor `org-cdlatex-mode'.
11773 This mode supports entering LaTeX environment and math in LaTeX fragments
11774 in Org-mode.
11775 \\{org-cdlatex-mode-map}"
11776 nil " OCDL" nil
11777 (when org-cdlatex-mode (require 'cdlatex))
11778 (unless org-cdlatex-texmathp-advice-is-done
11779 (setq org-cdlatex-texmathp-advice-is-done t)
11780 (defadvice texmathp (around org-math-always-on activate)
11781 "Always return t in org-mode buffers.
11782 This is because we want to insert math symbols without dollars even outside
11783 the LaTeX math segments. If Orgmode thinks that point is actually inside
11784 en embedded LaTeX fragement, let texmathp do its job.
11785 \\[org-cdlatex-mode-map]"
11786 (interactive)
11787 (let (p)
11788 (cond
11789 ((not (org-mode-p)) ad-do-it)
11790 ((eq this-command 'cdlatex-math-symbol)
11791 (setq ad-return-value t
11792 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
11794 (let ((p (org-inside-LaTeX-fragment-p)))
11795 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
11796 (setq ad-return-value t
11797 texmathp-why '("Org-mode embedded math" . 0))
11798 (if p ad-do-it)))))))))
11800 (defun turn-on-org-cdlatex ()
11801 "Unconditionally turn on `org-cdlatex-mode'."
11802 (org-cdlatex-mode 1))
11804 (defun org-inside-LaTeX-fragment-p ()
11805 "Test if point is inside a LaTeX fragment.
11806 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
11807 sequence appearing also before point.
11808 Even though the matchers for math are configurable, this function assumes
11809 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
11810 delimiters are skipped when they have been removed by customization.
11811 The return value is nil, or a cons cell with the delimiter and
11812 and the position of this delimiter.
11814 This function does a reasonably good job, but can locally be fooled by
11815 for example currency specifications. For example it will assume being in
11816 inline math after \"$22.34\". The LaTeX fragment formatter will only format
11817 fragments that are properly closed, but during editing, we have to live
11818 with the uncertainty caused by missing closing delimiters. This function
11819 looks only before point, not after."
11820 (catch 'exit
11821 (let ((pos (point))
11822 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
11823 (lim (progn
11824 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
11825 (point)))
11826 dd-on str (start 0) m re)
11827 (goto-char pos)
11828 (when dodollar
11829 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
11830 re (nth 1 (assoc "$" org-latex-regexps)))
11831 (while (string-match re str start)
11832 (cond
11833 ((= (match-end 0) (length str))
11834 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
11835 ((= (match-end 0) (- (length str) 5))
11836 (throw 'exit nil))
11837 (t (setq start (match-end 0))))))
11838 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
11839 (goto-char pos)
11840 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
11841 (and (match-beginning 2) (throw 'exit nil))
11842 ;; count $$
11843 (while (re-search-backward "\\$\\$" lim t)
11844 (setq dd-on (not dd-on)))
11845 (goto-char pos)
11846 (if dd-on (cons "$$" m))))))
11849 (defun org-try-cdlatex-tab ()
11850 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
11851 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
11852 - inside a LaTeX fragment, or
11853 - after the first word in a line, where an abbreviation expansion could
11854 insert a LaTeX environment."
11855 (when org-cdlatex-mode
11856 (cond
11857 ((save-excursion
11858 (skip-chars-backward "a-zA-Z0-9*")
11859 (skip-chars-backward " \t")
11860 (bolp))
11861 (cdlatex-tab) t)
11862 ((org-inside-LaTeX-fragment-p)
11863 (cdlatex-tab) t)
11864 (t nil))))
11866 (defun org-cdlatex-underscore-caret (&optional arg)
11867 "Execute `cdlatex-sub-superscript' 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-sub-superscript)
11872 (let (org-cdlatex-mode)
11873 (call-interactively (key-binding (vector last-input-event))))))
11875 (defun org-cdlatex-math-modify (&optional arg)
11876 "Execute `cdlatex-math-modify' in LaTeX fragments.
11877 Revert to the normal definition outside of these fragments."
11878 (interactive "P")
11879 (if (org-inside-LaTeX-fragment-p)
11880 (call-interactively 'cdlatex-math-modify)
11881 (let (org-cdlatex-mode)
11882 (call-interactively (key-binding (vector last-input-event))))))
11884 (defvar org-latex-fragment-image-overlays nil
11885 "List of overlays carrying the images of latex fragments.")
11886 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
11888 (defun org-remove-latex-fragment-image-overlays ()
11889 "Remove all overlays with LaTeX fragment images in current buffer."
11890 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
11891 (setq org-latex-fragment-image-overlays nil))
11893 (defun org-preview-latex-fragment (&optional subtree)
11894 "Preview the LaTeX fragment at point, or all locally or globally.
11895 If the cursor is in a LaTeX fragment, create the image and overlay
11896 it over the source code. If there is no fragment at point, display
11897 all fragments in the current text, from one headline to the next. With
11898 prefix SUBTREE, display all fragments in the current subtree. With a
11899 double prefix `C-u C-u', or when the cursor is before the first headline,
11900 display all fragments in the buffer.
11901 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
11902 (interactive "P")
11903 (org-remove-latex-fragment-image-overlays)
11904 (save-excursion
11905 (save-restriction
11906 (let (beg end at msg)
11907 (cond
11908 ((or (equal subtree '(16))
11909 (not (save-excursion
11910 (re-search-backward (concat "^" outline-regexp) nil t))))
11911 (setq beg (point-min) end (point-max)
11912 msg "Creating images for buffer...%s"))
11913 ((equal subtree '(4))
11914 (org-back-to-heading)
11915 (setq beg (point) end (org-end-of-subtree t)
11916 msg "Creating images for subtree...%s"))
11918 (if (setq at (org-inside-LaTeX-fragment-p))
11919 (goto-char (max (point-min) (- (cdr at) 2)))
11920 (org-back-to-heading))
11921 (setq beg (point) end (progn (outline-next-heading) (point))
11922 msg (if at "Creating image...%s"
11923 "Creating images for entry...%s"))))
11924 (message msg "")
11925 (narrow-to-region beg end)
11926 (goto-char beg)
11927 (org-format-latex
11928 (concat "ltxpng/" (file-name-sans-extension
11929 (file-name-nondirectory
11930 buffer-file-name)))
11931 default-directory 'overlays msg at 'forbuffer)
11932 (message msg "done. Use `C-c C-c' to remove images.")))))
11934 (defvar org-latex-regexps
11935 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
11936 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
11937 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
11938 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
11939 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
11940 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
11941 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
11942 "Regular expressions for matching embedded LaTeX.")
11944 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
11945 "Replace LaTeX fragments with links to an image, and produce images."
11946 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
11947 (let* ((prefixnodir (file-name-nondirectory prefix))
11948 (absprefix (expand-file-name prefix dir))
11949 (todir (file-name-directory absprefix))
11950 (opt org-format-latex-options)
11951 (matchers (plist-get opt :matchers))
11952 (re-list org-latex-regexps)
11953 (cnt 0) txt link beg end re e checkdir
11954 m n block linkfile movefile ov)
11955 ;; Check if there are old images files with this prefix, and remove them
11956 (when (file-directory-p todir)
11957 (mapc 'delete-file
11958 (directory-files
11959 todir 'full
11960 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
11961 ;; Check the different regular expressions
11962 (while (setq e (pop re-list))
11963 (setq m (car e) re (nth 1 e) n (nth 2 e)
11964 block (if (nth 3 e) "\n\n" ""))
11965 (when (member m matchers)
11966 (goto-char (point-min))
11967 (while (re-search-forward re nil t)
11968 (when (or (not at) (equal (cdr at) (match-beginning n)))
11969 (setq txt (match-string n)
11970 beg (match-beginning n) end (match-end n)
11971 cnt (1+ cnt)
11972 linkfile (format "%s_%04d.png" prefix cnt)
11973 movefile (format "%s_%04d.png" absprefix cnt)
11974 link (concat block "[[file:" linkfile "]]" block))
11975 (if msg (message msg cnt))
11976 (goto-char beg)
11977 (unless checkdir ; make sure the directory exists
11978 (setq checkdir t)
11979 (or (file-directory-p todir) (make-directory todir)))
11980 (org-create-formula-image
11981 txt movefile opt forbuffer)
11982 (if overlays
11983 (progn
11984 (setq ov (org-make-overlay beg end))
11985 (if (featurep 'xemacs)
11986 (progn
11987 (org-overlay-put ov 'invisible t)
11988 (org-overlay-put
11989 ov 'end-glyph
11990 (make-glyph (vector 'png :file movefile))))
11991 (org-overlay-put
11992 ov 'display
11993 (list 'image :type 'png :file movefile :ascent 'center)))
11994 (push ov org-latex-fragment-image-overlays)
11995 (goto-char end))
11996 (delete-region beg end)
11997 (insert link))))))))
11999 ;; This function borrows from Ganesh Swami's latex2png.el
12000 (defun org-create-formula-image (string tofile options buffer)
12001 (let* ((tmpdir (if (featurep 'xemacs)
12002 (temp-directory)
12003 temporary-file-directory))
12004 (texfilebase (make-temp-name
12005 (expand-file-name "orgtex" tmpdir)))
12006 (texfile (concat texfilebase ".tex"))
12007 (dvifile (concat texfilebase ".dvi"))
12008 (pngfile (concat texfilebase ".png"))
12009 (fnh (if (featurep 'xemacs)
12010 (font-height (get-face-font 'default))
12011 (face-attribute 'default :height nil)))
12012 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
12013 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
12014 (fg (or (plist-get options (if buffer :foreground :html-foreground))
12015 "Black"))
12016 (bg (or (plist-get options (if buffer :background :html-background))
12017 "Transparent")))
12018 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
12019 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
12020 (with-temp-file texfile
12021 (insert org-format-latex-header
12022 "\n\\begin{document}\n" string "\n\\end{document}\n"))
12023 (let ((dir default-directory))
12024 (condition-case nil
12025 (progn
12026 (cd tmpdir)
12027 (call-process "latex" nil nil nil texfile))
12028 (error nil))
12029 (cd dir))
12030 (if (not (file-exists-p dvifile))
12031 (progn (message "Failed to create dvi file from %s" texfile) nil)
12032 (condition-case nil
12033 (call-process "dvipng" nil nil nil
12034 "-E" "-fg" fg "-bg" bg
12035 "-D" dpi
12036 ;;"-x" scale "-y" scale
12037 "-T" "tight"
12038 "-o" pngfile
12039 dvifile)
12040 (error nil))
12041 (if (not (file-exists-p pngfile))
12042 (progn (message "Failed to create png file from %s" texfile) nil)
12043 ;; Use the requested file name and clean up
12044 (copy-file pngfile tofile 'replace)
12045 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
12046 (delete-file (concat texfilebase e)))
12047 pngfile))))
12049 (defun org-dvipng-color (attr)
12050 "Return an rgb color specification for dvipng."
12051 (apply 'format "rgb %s %s %s"
12052 (mapcar 'org-normalize-color
12053 (color-values (face-attribute 'default attr nil)))))
12055 (defun org-normalize-color (value)
12056 "Return string to be used as color value for an RGB component."
12057 (format "%g" (/ value 65535.0)))
12060 ;;;; Key bindings
12062 ;; Make `C-c C-x' a prefix key
12063 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
12065 ;; TAB key with modifiers
12066 (org-defkey org-mode-map "\C-i" 'org-cycle)
12067 (org-defkey org-mode-map [(tab)] 'org-cycle)
12068 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
12069 (org-defkey org-mode-map [(meta tab)] 'org-complete)
12070 (org-defkey org-mode-map "\M-\t" 'org-complete)
12071 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
12072 ;; The following line is necessary under Suse GNU/Linux
12073 (unless (featurep 'xemacs)
12074 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
12075 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
12076 (define-key org-mode-map [backtab] 'org-shifttab)
12078 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
12079 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
12080 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
12082 ;; Cursor keys with modifiers
12083 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
12084 (org-defkey org-mode-map [(meta right)] 'org-metaright)
12085 (org-defkey org-mode-map [(meta up)] 'org-metaup)
12086 (org-defkey org-mode-map [(meta down)] 'org-metadown)
12088 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
12089 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
12090 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
12091 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
12093 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
12094 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
12095 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
12096 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
12098 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
12099 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
12101 ;;; Extra keys for tty access.
12102 ;; We only set them when really needed because otherwise the
12103 ;; menus don't show the simple keys
12105 (when (or org-use-extra-keys
12106 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
12107 (not window-system))
12108 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
12109 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
12110 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
12111 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
12112 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
12113 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
12114 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
12115 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
12116 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
12117 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
12118 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
12119 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
12120 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
12121 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
12122 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
12123 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
12124 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
12125 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
12126 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
12127 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
12128 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
12129 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
12131 ;; All the other keys
12133 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
12134 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
12135 (if (boundp 'narrow-map)
12136 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
12137 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
12138 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
12139 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
12140 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
12141 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
12142 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
12143 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
12144 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
12145 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
12146 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
12147 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
12148 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
12149 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
12150 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
12151 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
12152 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
12153 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
12154 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
12155 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
12156 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
12157 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
12158 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
12159 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
12160 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
12161 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
12162 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
12163 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
12164 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
12165 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
12166 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
12167 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
12168 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
12169 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
12170 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
12171 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
12172 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
12173 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
12174 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
12175 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
12176 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
12177 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
12178 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
12179 (org-defkey org-mode-map "\C-c^" 'org-sort)
12180 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
12181 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
12182 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
12183 (org-defkey org-mode-map "\C-m" 'org-return)
12184 (org-defkey org-mode-map "\C-j" 'org-return-indent)
12185 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
12186 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
12187 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
12188 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
12189 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
12190 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
12191 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
12192 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
12193 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
12194 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
12195 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
12196 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
12197 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
12198 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
12199 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
12201 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
12202 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
12203 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
12204 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
12206 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
12207 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
12208 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
12209 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
12210 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
12211 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
12212 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
12213 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
12214 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
12215 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
12216 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
12217 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
12219 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
12221 (when (featurep 'xemacs)
12222 (org-defkey org-mode-map 'button3 'popup-mode-menu))
12224 (defvar org-table-auto-blank-field) ; defined in org-table.el
12225 (defun org-self-insert-command (N)
12226 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
12227 If the cursor is in a table looking at whitespace, the whitespace is
12228 overwritten, and the table is not marked as requiring realignment."
12229 (interactive "p")
12230 (if (and (org-table-p)
12231 (progn
12232 ;; check if we blank the field, and if that triggers align
12233 (and (featurep 'org-table) org-table-auto-blank-field
12234 (member last-command
12235 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
12236 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
12237 ;; got extra space, this field does not determine column width
12238 (let (org-table-may-need-update) (org-table-blank-field))
12239 ;; no extra space, this field may determine column width
12240 (org-table-blank-field)))
12242 (eq N 1)
12243 (looking-at "[^|\n]* |"))
12244 (let (org-table-may-need-update)
12245 (goto-char (1- (match-end 0)))
12246 (delete-backward-char 1)
12247 (goto-char (match-beginning 0))
12248 (self-insert-command N))
12249 (setq org-table-may-need-update t)
12250 (self-insert-command N)
12251 (org-fix-tags-on-the-fly)))
12253 (defun org-fix-tags-on-the-fly ()
12254 (when (and (equal (char-after (point-at-bol)) ?*)
12255 (org-on-heading-p))
12256 (org-align-tags-here org-tags-column)))
12258 (defun org-delete-backward-char (N)
12259 "Like `delete-backward-char', insert whitespace at field end in tables.
12260 When deleting backwards, in tables this function will insert whitespace in
12261 front of the next \"|\" separator, to keep the table aligned. The table will
12262 still be marked for re-alignment if the field did fill the entire column,
12263 because, in this case the deletion might narrow the column."
12264 (interactive "p")
12265 (if (and (org-table-p)
12266 (eq N 1)
12267 (string-match "|" (buffer-substring (point-at-bol) (point)))
12268 (looking-at ".*?|"))
12269 (let ((pos (point))
12270 (noalign (looking-at "[^|\n\r]* |"))
12271 (c org-table-may-need-update))
12272 (backward-delete-char N)
12273 (skip-chars-forward "^|")
12274 (insert " ")
12275 (goto-char (1- pos))
12276 ;; noalign: if there were two spaces at the end, this field
12277 ;; does not determine the width of the column.
12278 (if noalign (setq org-table-may-need-update c)))
12279 (backward-delete-char N)
12280 (org-fix-tags-on-the-fly)))
12282 (defun org-delete-char (N)
12283 "Like `delete-char', but insert whitespace at field end in tables.
12284 When deleting characters, in tables this function will insert whitespace in
12285 front of the next \"|\" separator, to keep the table aligned. The table will
12286 still be marked for re-alignment if the field did fill the entire column,
12287 because, in this case the deletion might narrow the column."
12288 (interactive "p")
12289 (if (and (org-table-p)
12290 (not (bolp))
12291 (not (= (char-after) ?|))
12292 (eq N 1))
12293 (if (looking-at ".*?|")
12294 (let ((pos (point))
12295 (noalign (looking-at "[^|\n\r]* |"))
12296 (c org-table-may-need-update))
12297 (replace-match (concat
12298 (substring (match-string 0) 1 -1)
12299 " |"))
12300 (goto-char pos)
12301 ;; noalign: if there were two spaces at the end, this field
12302 ;; does not determine the width of the column.
12303 (if noalign (setq org-table-may-need-update c)))
12304 (delete-char N))
12305 (delete-char N)
12306 (org-fix-tags-on-the-fly)))
12308 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
12309 (put 'org-self-insert-command 'delete-selection t)
12310 (put 'orgtbl-self-insert-command 'delete-selection t)
12311 (put 'org-delete-char 'delete-selection 'supersede)
12312 (put 'org-delete-backward-char 'delete-selection 'supersede)
12314 ;; Make `flyspell-mode' delay after some commands
12315 (put 'org-self-insert-command 'flyspell-delayed t)
12316 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
12317 (put 'org-delete-char 'flyspell-delayed t)
12318 (put 'org-delete-backward-char 'flyspell-delayed t)
12320 ;; Make pabbrev-mode expand after org-mode commands
12321 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
12322 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
12324 ;; How to do this: Measure non-white length of current string
12325 ;; If equal to column width, we should realign.
12327 (defun org-remap (map &rest commands)
12328 "In MAP, remap the functions given in COMMANDS.
12329 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
12330 (let (new old)
12331 (while commands
12332 (setq old (pop commands) new (pop commands))
12333 (if (fboundp 'command-remapping)
12334 (org-defkey map (vector 'remap old) new)
12335 (substitute-key-definition old new map global-map)))))
12337 (when (eq org-enable-table-editor 'optimized)
12338 ;; If the user wants maximum table support, we need to hijack
12339 ;; some standard editing functions
12340 (org-remap org-mode-map
12341 'self-insert-command 'org-self-insert-command
12342 'delete-char 'org-delete-char
12343 'delete-backward-char 'org-delete-backward-char)
12344 (org-defkey org-mode-map "|" 'org-force-self-insert))
12346 (defun org-shiftcursor-error ()
12347 "Throw an error because Shift-Cursor command was applied in wrong context."
12348 (error "This command is active in special context like tables, headlines or timestamps"))
12350 (defun org-shifttab (&optional arg)
12351 "Global visibility cycling or move to previous table field.
12352 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
12353 on context.
12354 See the individual commands for more information."
12355 (interactive "P")
12356 (cond
12357 ((org-at-table-p) (call-interactively 'org-table-previous-field))
12358 ((integerp arg)
12359 (message "Content view to level: %d" arg)
12360 (org-content (prefix-numeric-value arg))
12361 (setq org-cycle-global-status 'overview))
12362 (t (call-interactively 'org-global-cycle))))
12364 (defun org-shiftmetaleft ()
12365 "Promote subtree or delete table column.
12366 Calls `org-promote-subtree', `org-outdent-item',
12367 or `org-table-delete-column', depending on context.
12368 See the individual commands for more information."
12369 (interactive)
12370 (cond
12371 ((org-at-table-p) (call-interactively 'org-table-delete-column))
12372 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
12373 ((org-at-item-p) (call-interactively 'org-outdent-item))
12374 (t (org-shiftcursor-error))))
12376 (defun org-shiftmetaright ()
12377 "Demote subtree or insert table column.
12378 Calls `org-demote-subtree', `org-indent-item',
12379 or `org-table-insert-column', depending on context.
12380 See the individual commands for more information."
12381 (interactive)
12382 (cond
12383 ((org-at-table-p) (call-interactively 'org-table-insert-column))
12384 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
12385 ((org-at-item-p) (call-interactively 'org-indent-item))
12386 (t (org-shiftcursor-error))))
12388 (defun org-shiftmetaup (&optional arg)
12389 "Move subtree up or kill table row.
12390 Calls `org-move-subtree-up' or `org-table-kill-row' or
12391 `org-move-item-up' depending on context. See the individual commands
12392 for more information."
12393 (interactive "P")
12394 (cond
12395 ((org-at-table-p) (call-interactively 'org-table-kill-row))
12396 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12397 ((org-at-item-p) (call-interactively 'org-move-item-up))
12398 (t (org-shiftcursor-error))))
12399 (defun org-shiftmetadown (&optional arg)
12400 "Move subtree down or insert table row.
12401 Calls `org-move-subtree-down' or `org-table-insert-row' or
12402 `org-move-item-down', depending on context. See the individual
12403 commands for more information."
12404 (interactive "P")
12405 (cond
12406 ((org-at-table-p) (call-interactively 'org-table-insert-row))
12407 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12408 ((org-at-item-p) (call-interactively 'org-move-item-down))
12409 (t (org-shiftcursor-error))))
12411 (defun org-metaleft (&optional arg)
12412 "Promote heading or move table column to left.
12413 Calls `org-do-promote' or `org-table-move-column', depending on context.
12414 With no specific context, calls the Emacs default `backward-word'.
12415 See the individual commands for more information."
12416 (interactive "P")
12417 (cond
12418 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
12419 ((or (org-on-heading-p) (org-region-active-p))
12420 (call-interactively 'org-do-promote))
12421 ((org-at-item-p) (call-interactively 'org-outdent-item))
12422 (t (call-interactively 'backward-word))))
12424 (defun org-metaright (&optional arg)
12425 "Demote subtree or move table column to right.
12426 Calls `org-do-demote' or `org-table-move-column', depending on context.
12427 With no specific context, calls the Emacs default `forward-word'.
12428 See the individual commands for more information."
12429 (interactive "P")
12430 (cond
12431 ((org-at-table-p) (call-interactively 'org-table-move-column))
12432 ((or (org-on-heading-p) (org-region-active-p))
12433 (call-interactively 'org-do-demote))
12434 ((org-at-item-p) (call-interactively 'org-indent-item))
12435 (t (call-interactively 'forward-word))))
12437 (defun org-metaup (&optional arg)
12438 "Move subtree up or move table row up.
12439 Calls `org-move-subtree-up' or `org-table-move-row' or
12440 `org-move-item-up', depending on context. See the individual commands
12441 for more information."
12442 (interactive "P")
12443 (cond
12444 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
12445 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12446 ((org-at-item-p) (call-interactively 'org-move-item-up))
12447 (t (transpose-lines 1) (beginning-of-line -1))))
12449 (defun org-metadown (&optional arg)
12450 "Move subtree down or move table row down.
12451 Calls `org-move-subtree-down' or `org-table-move-row' or
12452 `org-move-item-down', depending on context. See the individual
12453 commands for more information."
12454 (interactive "P")
12455 (cond
12456 ((org-at-table-p) (call-interactively 'org-table-move-row))
12457 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12458 ((org-at-item-p) (call-interactively 'org-move-item-down))
12459 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
12461 (defun org-shiftup (&optional arg)
12462 "Increase item in timestamp or increase priority of current headline.
12463 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
12464 depending on context. See the individual commands for more information."
12465 (interactive "P")
12466 (cond
12467 ((org-at-timestamp-p t)
12468 (call-interactively (if org-edit-timestamp-down-means-later
12469 'org-timestamp-down 'org-timestamp-up)))
12470 ((org-on-heading-p) (call-interactively 'org-priority-up))
12471 ((org-at-item-p) (call-interactively 'org-previous-item))
12472 ((org-clocktable-try-shift 'up arg))
12473 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
12475 (defun org-shiftdown (&optional arg)
12476 "Decrease item in timestamp or decrease priority of current headline.
12477 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
12478 depending on context. See the individual commands for more information."
12479 (interactive "P")
12480 (cond
12481 ((org-at-timestamp-p t)
12482 (call-interactively (if org-edit-timestamp-down-means-later
12483 'org-timestamp-up 'org-timestamp-down)))
12484 ((org-on-heading-p) (call-interactively 'org-priority-down))
12485 ((org-clocktable-try-shift 'down arg))
12486 (t (call-interactively 'org-next-item))))
12488 (defun org-shiftright (&optional arg)
12489 "Next TODO keyword or timestamp one day later, depending on context."
12490 (interactive "P")
12491 (cond
12492 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
12493 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
12494 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
12495 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
12496 ((org-clocktable-try-shift 'right arg))
12497 (t (org-shiftcursor-error))))
12499 (defun org-shiftleft (&optional arg)
12500 "Previous TODO keyword or timestamp one day earlier, depending on context."
12501 (interactive "P")
12502 (cond
12503 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
12504 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
12505 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
12506 ((org-at-property-p)
12507 (call-interactively 'org-property-previous-allowed-value))
12508 ((org-clocktable-try-shift 'left arg))
12509 (t (org-shiftcursor-error))))
12511 (defun org-shiftcontrolright ()
12512 "Switch to next TODO set."
12513 (interactive)
12514 (cond
12515 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
12516 (t (org-shiftcursor-error))))
12518 (defun org-shiftcontrolleft ()
12519 "Switch to previous TODO set."
12520 (interactive)
12521 (cond
12522 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
12523 (t (org-shiftcursor-error))))
12525 (defun org-ctrl-c-ret ()
12526 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
12527 (interactive)
12528 (cond
12529 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
12530 (t (call-interactively 'org-insert-heading))))
12532 (defun org-copy-special ()
12533 "Copy region in table or copy current subtree.
12534 Calls `org-table-copy' or `org-copy-subtree', depending on context.
12535 See the individual commands for more information."
12536 (interactive)
12537 (call-interactively
12538 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
12540 (defun org-cut-special ()
12541 "Cut region in table or cut current subtree.
12542 Calls `org-table-copy' or `org-cut-subtree', depending on context.
12543 See the individual commands for more information."
12544 (interactive)
12545 (call-interactively
12546 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
12548 (defun org-paste-special (arg)
12549 "Paste rectangular region into table, or past subtree relative to level.
12550 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
12551 See the individual commands for more information."
12552 (interactive "P")
12553 (if (org-at-table-p)
12554 (org-table-paste-rectangle)
12555 (org-paste-subtree arg)))
12557 (defun org-edit-special ()
12558 "Call a special editor for the stuff at point.
12559 When at a table, call the formula editor with `org-table-edit-formulas'.
12560 When at the first line of an src example, call `org-edit-src-code'.
12561 When in an #+include line, visit the include file. Otherwise call
12562 `ffap' to visit the file at point."
12563 (interactive)
12564 (cond
12565 ((org-at-table-p)
12566 (call-interactively 'org-table-edit-formulas))
12567 ((save-excursion
12568 (beginning-of-line 1)
12569 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
12570 (find-file (org-trim (match-string 1))))
12571 ((org-edit-src-code))
12572 ((org-edit-fixed-width-region))
12573 (t (call-interactively 'ffap))))
12575 (defun org-ctrl-c-ctrl-c (&optional arg)
12576 "Set tags in headline, or update according to changed information at point.
12578 This command does many different things, depending on context:
12580 - If the cursor is in a headline, prompt for tags and insert them
12581 into the current line, aligned to `org-tags-column'. When called
12582 with prefix arg, realign all tags in the current buffer.
12584 - If the cursor is in one of the special #+KEYWORD lines, this
12585 triggers scanning the buffer for these lines and updating the
12586 information.
12588 - If the cursor is inside a table, realign the table. This command
12589 works even if the automatic table editor has been turned off.
12591 - If the cursor is on a #+TBLFM line, re-apply the formulas to
12592 the entire table.
12594 - If the cursor is a the beginning of a dynamic block, update it.
12596 - If the cursor is inside a table created by the table.el package,
12597 activate that table.
12599 - If the current buffer is a remember buffer, close note and file it.
12600 with a prefix argument, file it without further interaction to the default
12601 location.
12603 - If the cursor is on a <<<target>>>, update radio targets and corresponding
12604 links in this buffer.
12606 - If the cursor is on a numbered item in a plain list, renumber the
12607 ordered list.
12609 - If the cursor is on a checkbox, toggle it."
12610 (interactive "P")
12611 (let ((org-enable-table-editor t))
12612 (cond
12613 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
12614 org-occur-highlights
12615 org-latex-fragment-image-overlays)
12616 (and (boundp 'org-clock-overlays) (org-remove-clock-overlays))
12617 (org-remove-occur-highlights)
12618 (org-remove-latex-fragment-image-overlays)
12619 (message "Temporary highlights/overlays removed from current buffer"))
12620 ((and (local-variable-p 'org-finish-function (current-buffer))
12621 (fboundp org-finish-function))
12622 (funcall org-finish-function))
12623 ((org-at-property-p)
12624 (call-interactively 'org-property-action))
12625 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
12626 ((org-on-heading-p) (call-interactively 'org-set-tags))
12627 ((org-at-table.el-p)
12628 (require 'table)
12629 (beginning-of-line 1)
12630 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
12631 (call-interactively 'table-recognize-table))
12632 ((org-at-table-p)
12633 (org-table-maybe-eval-formula)
12634 (if arg
12635 (call-interactively 'org-table-recalculate)
12636 (org-table-maybe-recalculate-line))
12637 (call-interactively 'org-table-align))
12638 ((org-at-item-checkbox-p)
12639 (call-interactively 'org-toggle-checkbox))
12640 ((org-at-item-p)
12641 (call-interactively 'org-maybe-renumber-ordered-list))
12642 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
12643 ;; Dynamic block
12644 (beginning-of-line 1)
12645 (save-excursion (org-update-dblock)))
12646 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
12647 (cond
12648 ((equal (match-string 1) "TBLFM")
12649 ;; Recalculate the table before this line
12650 (save-excursion
12651 (beginning-of-line 1)
12652 (skip-chars-backward " \r\n\t")
12653 (if (org-at-table-p)
12654 (org-call-with-arg 'org-table-recalculate t))))
12656 ; (org-set-regexps-and-options)
12657 ; (org-restart-font-lock)
12658 (let ((org-inhibit-startup t)) (org-mode-restart))
12659 (message "Local setup has been refreshed"))))
12660 (t (error "C-c C-c can do nothing useful at this location.")))))
12662 (defun org-mode-restart ()
12663 "Restart Org-mode, to scan again for special lines.
12664 Also updates the keyword regular expressions."
12665 (interactive)
12666 (org-mode)
12667 (message "Org-mode restarted"))
12669 (defun org-kill-note-or-show-branches ()
12670 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
12671 (interactive)
12672 (if (not org-finish-function)
12673 (call-interactively 'show-branches)
12674 (let ((org-note-abort t))
12675 (funcall org-finish-function))))
12677 (defun org-return (&optional indent)
12678 "Goto next table row or insert a newline.
12679 Calls `org-table-next-row' or `newline', depending on context.
12680 See the individual commands for more information."
12681 (interactive)
12682 (cond
12683 ((bobp) (if indent (newline-and-indent) (newline)))
12684 ((and (org-at-heading-p)
12685 (looking-at
12686 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
12687 (org-show-entry)
12688 (end-of-line 1)
12689 (newline))
12690 ((org-at-table-p)
12691 (org-table-justify-field-maybe)
12692 (call-interactively 'org-table-next-row))
12693 (t (if indent (newline-and-indent) (newline)))))
12695 (defun org-return-indent ()
12696 "Goto next table row or insert a newline and indent.
12697 Calls `org-table-next-row' or `newline-and-indent', depending on
12698 context. See the individual commands for more information."
12699 (interactive)
12700 (org-return t))
12702 (defun org-ctrl-c-star ()
12703 "Compute table, or change heading status of lines.
12704 Calls `org-table-recalculate' or `org-toggle-region-headings',
12705 depending on context. This will also turn a plain list item or a normal
12706 line into a subheading."
12707 (interactive)
12708 (cond
12709 ((org-at-table-p)
12710 (call-interactively 'org-table-recalculate))
12711 ((org-region-active-p)
12712 ;; Convert all lines in region to list items
12713 (call-interactively 'org-toggle-region-headings))
12714 ((org-on-heading-p)
12715 (org-toggle-region-headings (point-at-bol)
12716 (min (1+ (point-at-eol)) (point-max))))
12717 ((org-at-item-p)
12718 ;; Convert to heading
12719 (let ((level (save-match-data
12720 (save-excursion
12721 (condition-case nil
12722 (progn
12723 (org-back-to-heading t)
12724 (funcall outline-level))
12725 (error 0))))))
12726 (replace-match
12727 (concat (make-string (org-get-valid-level level 1) ?*) " ") t t)))
12728 (t (org-toggle-region-headings (point-at-bol)
12729 (min (1+ (point-at-eol)) (point-max))))))
12731 (defun org-ctrl-c-minus ()
12732 "Insert separator line in table or modify bullet status of line.
12733 Also turns a plain line or a region of lines into list items.
12734 Calls `org-table-insert-hline', `org-toggle-region-items', or
12735 `org-cycle-list-bullet', depending on context."
12736 (interactive)
12737 (cond
12738 ((org-at-table-p)
12739 (call-interactively 'org-table-insert-hline))
12740 ((org-on-heading-p)
12741 ;; Convert to item
12742 (save-excursion
12743 (beginning-of-line 1)
12744 (if (looking-at "\\*+ ")
12745 (replace-match (concat (make-string (- (match-end 0) (point) 1) ?\ ) "- ")))))
12746 ((org-region-active-p)
12747 ;; Convert all lines in region to list items
12748 (call-interactively 'org-toggle-region-items))
12749 ((org-in-item-p)
12750 (call-interactively 'org-cycle-list-bullet))
12751 (t (org-toggle-region-items (point-at-bol)
12752 (min (1+ (point-at-eol)) (point-max))))))
12754 (defun org-toggle-region-items (beg end)
12755 "Convert all lines in region to list items.
12756 If the first line is already an item, convert all list items in the region
12757 to normal lines."
12758 (interactive "r")
12759 (let (l2 l)
12760 (save-excursion
12761 (goto-char end)
12762 (setq l2 (org-current-line))
12763 (goto-char beg)
12764 (beginning-of-line 1)
12765 (setq l (1- (org-current-line)))
12766 (if (org-at-item-p)
12767 ;; We already have items, de-itemize
12768 (while (< (setq l (1+ l)) l2)
12769 (when (org-at-item-p)
12770 (goto-char (match-beginning 2))
12771 (delete-region (match-beginning 2) (match-end 2))
12772 (and (looking-at "[ \t]+") (replace-match "")))
12773 (beginning-of-line 2))
12774 (while (< (setq l (1+ l)) l2)
12775 (unless (org-at-item-p)
12776 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
12777 (replace-match "\\1- \\2")))
12778 (beginning-of-line 2))))))
12780 (defun org-toggle-region-headings (beg end)
12781 "Convert all lines in region to list items.
12782 If the first line is already an item, convert all list items in the region
12783 to normal lines."
12784 (interactive "r")
12785 (let (l2 l)
12786 (save-excursion
12787 (goto-char end)
12788 (setq l2 (org-current-line))
12789 (goto-char beg)
12790 (beginning-of-line 1)
12791 (setq l (1- (org-current-line)))
12792 (if (org-on-heading-p)
12793 ;; We already have headlines, de-star them
12794 (while (< (setq l (1+ l)) l2)
12795 (when (org-on-heading-p t)
12796 (and (looking-at outline-regexp) (replace-match "")))
12797 (beginning-of-line 2))
12798 (let* ((stars (save-excursion
12799 (re-search-backward org-complex-heading-regexp nil t)
12800 (or (match-string 1) "*")))
12801 (add-stars (if org-odd-levels-only "**" "*"))
12802 (rpl (concat stars add-stars " \\2")))
12803 (while (< (setq l (1+ l)) l2)
12804 (unless (org-on-heading-p)
12805 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
12806 (replace-match rpl)))
12807 (beginning-of-line 2)))))))
12809 (defun org-meta-return (&optional arg)
12810 "Insert a new heading or wrap a region in a table.
12811 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
12812 See the individual commands for more information."
12813 (interactive "P")
12814 (cond
12815 ((org-at-table-p)
12816 (call-interactively 'org-table-wrap-region))
12817 (t (call-interactively 'org-insert-heading))))
12819 ;;; Menu entries
12821 ;; Define the Org-mode menus
12822 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
12823 '("Tbl"
12824 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
12825 ["Next Field" org-cycle (org-at-table-p)]
12826 ["Previous Field" org-shifttab (org-at-table-p)]
12827 ["Next Row" org-return (org-at-table-p)]
12828 "--"
12829 ["Blank Field" org-table-blank-field (org-at-table-p)]
12830 ["Edit Field" org-table-edit-field (org-at-table-p)]
12831 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
12832 "--"
12833 ("Column"
12834 ["Move Column Left" org-metaleft (org-at-table-p)]
12835 ["Move Column Right" org-metaright (org-at-table-p)]
12836 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
12837 ["Insert Column" org-shiftmetaright (org-at-table-p)])
12838 ("Row"
12839 ["Move Row Up" org-metaup (org-at-table-p)]
12840 ["Move Row Down" org-metadown (org-at-table-p)]
12841 ["Delete Row" org-shiftmetaup (org-at-table-p)]
12842 ["Insert Row" org-shiftmetadown (org-at-table-p)]
12843 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
12844 "--"
12845 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
12846 ("Rectangle"
12847 ["Copy Rectangle" org-copy-special (org-at-table-p)]
12848 ["Cut Rectangle" org-cut-special (org-at-table-p)]
12849 ["Paste Rectangle" org-paste-special (org-at-table-p)]
12850 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
12851 "--"
12852 ("Calculate"
12853 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
12854 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
12855 ["Edit Formulas" org-edit-special (org-at-table-p)]
12856 "--"
12857 ["Recalculate line" org-table-recalculate (org-at-table-p)]
12858 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
12859 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
12860 "--"
12861 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
12862 "--"
12863 ["Sum Column/Rectangle" org-table-sum
12864 (or (org-at-table-p) (org-region-active-p))]
12865 ["Which Column?" org-table-current-column (org-at-table-p)])
12866 ["Debug Formulas"
12867 org-table-toggle-formula-debugger
12868 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
12869 ["Show Col/Row Numbers"
12870 org-table-toggle-coordinate-overlays
12871 :style toggle
12872 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
12873 "--"
12874 ["Create" org-table-create (and (not (org-at-table-p))
12875 org-enable-table-editor)]
12876 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
12877 ["Import from File" org-table-import (not (org-at-table-p))]
12878 ["Export to File" org-table-export (org-at-table-p)]
12879 "--"
12880 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
12882 (easy-menu-define org-org-menu org-mode-map "Org menu"
12883 '("Org"
12884 ("Show/Hide"
12885 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
12886 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
12887 ["Sparse Tree..." org-sparse-tree t]
12888 ["Reveal Context" org-reveal t]
12889 ["Show All" show-all t]
12890 "--"
12891 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
12892 "--"
12893 ["New Heading" org-insert-heading t]
12894 ("Navigate Headings"
12895 ["Up" outline-up-heading t]
12896 ["Next" outline-next-visible-heading t]
12897 ["Previous" outline-previous-visible-heading t]
12898 ["Next Same Level" outline-forward-same-level t]
12899 ["Previous Same Level" outline-backward-same-level t]
12900 "--"
12901 ["Jump" org-goto t])
12902 ("Edit Structure"
12903 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
12904 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
12905 "--"
12906 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
12907 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
12908 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
12909 "--"
12910 ["Promote Heading" org-metaleft (not (org-at-table-p))]
12911 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
12912 ["Demote Heading" org-metaright (not (org-at-table-p))]
12913 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
12914 "--"
12915 ["Sort Region/Children" org-sort (not (org-at-table-p))]
12916 "--"
12917 ["Convert to odd levels" org-convert-to-odd-levels t]
12918 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
12919 ("Editing"
12920 ["Emphasis..." org-emphasize t]
12921 ["Edit Source Example" org-edit-special t])
12922 ("Archive"
12923 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
12924 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
12925 ; :active t :keys "C-u C-c C-x C-a"]
12926 ["Sparse trees open ARCHIVE trees"
12927 (setq org-sparse-tree-open-archived-trees
12928 (not org-sparse-tree-open-archived-trees))
12929 :style toggle :selected org-sparse-tree-open-archived-trees]
12930 ["Cycling opens ARCHIVE trees"
12931 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
12932 :style toggle :selected org-cycle-open-archived-trees]
12933 "--"
12934 ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
12935 ["Move Subtree to Archive" org-advertized-archive-subtree t]
12936 ; ["Check and Move Children" (org-archive-subtree '(4))
12937 ; :active t :keys "C-u C-c C-x C-s"]
12939 "--"
12940 ("TODO Lists"
12941 ["TODO/DONE/-" org-todo t]
12942 ("Select keyword"
12943 ["Next keyword" org-shiftright (org-on-heading-p)]
12944 ["Previous keyword" org-shiftleft (org-on-heading-p)]
12945 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
12946 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
12947 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
12948 ["Show TODO Tree" org-show-todo-tree t]
12949 ["Global TODO list" org-todo-list t]
12950 "--"
12951 ["Set Priority" org-priority t]
12952 ["Priority Up" org-shiftup t]
12953 ["Priority Down" org-shiftdown t])
12954 ("TAGS and Properties"
12955 ["Set Tags" 'org-set-tags-command t]
12956 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
12957 "--"
12958 ["Set property" 'org-set-property t]
12959 ["Column view of properties" org-columns t]
12960 ["Insert Column View DBlock" org-insert-columns-dblock t])
12961 ("Dates and Scheduling"
12962 ["Timestamp" org-time-stamp t]
12963 ["Timestamp (inactive)" org-time-stamp-inactive t]
12964 ("Change Date"
12965 ["1 Day Later" org-shiftright t]
12966 ["1 Day Earlier" org-shiftleft t]
12967 ["1 ... Later" org-shiftup t]
12968 ["1 ... Earlier" org-shiftdown t])
12969 ["Compute Time Range" org-evaluate-time-range t]
12970 ["Schedule Item" org-schedule t]
12971 ["Deadline" org-deadline t]
12972 "--"
12973 ["Custom time format" org-toggle-time-stamp-overlays
12974 :style radio :selected org-display-custom-times]
12975 "--"
12976 ["Goto Calendar" org-goto-calendar t]
12977 ["Date from Calendar" org-date-from-calendar t])
12978 ("Logging work"
12979 ["Clock in" org-clock-in t]
12980 ["Clock out" org-clock-out t]
12981 ["Clock cancel" org-clock-cancel t]
12982 ["Goto running clock" org-clock-goto t]
12983 ["Display times" org-clock-display t]
12984 ["Create clock table" org-clock-report t]
12985 "--"
12986 ["Record DONE time"
12987 (progn (setq org-log-done (not org-log-done))
12988 (message "Switching to %s will %s record a timestamp"
12989 (car org-done-keywords)
12990 (if org-log-done "automatically" "not")))
12991 :style toggle :selected org-log-done])
12992 "--"
12993 ["Agenda Command..." org-agenda t]
12994 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
12995 ("File List for Agenda")
12996 ("Special views current file"
12997 ["TODO Tree" org-show-todo-tree t]
12998 ["Check Deadlines" org-check-deadlines t]
12999 ["Timeline" org-timeline t]
13000 ["Tags Tree" org-tags-sparse-tree t])
13001 "--"
13002 ("Hyperlinks"
13003 ["Store Link (Global)" org-store-link t]
13004 ["Insert Link" org-insert-link t]
13005 ["Follow Link" org-open-at-point t]
13006 "--"
13007 ["Next link" org-next-link t]
13008 ["Previous link" org-previous-link t]
13009 "--"
13010 ["Descriptive Links"
13011 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
13012 :style radio
13013 :selected (member '(org-link) buffer-invisibility-spec)]
13014 ["Literal Links"
13015 (progn
13016 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
13017 :style radio
13018 :selected (not (member '(org-link) buffer-invisibility-spec))])
13019 "--"
13020 ["Export/Publish..." org-export t]
13021 ("LaTeX"
13022 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
13023 :selected org-cdlatex-mode]
13024 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
13025 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
13026 ["Modify math symbol" org-cdlatex-math-modify
13027 (org-inside-LaTeX-fragment-p)]
13028 ["Export LaTeX fragments as images"
13029 (if (featurep 'org-exp)
13030 (setq org-export-with-LaTeX-fragments
13031 (not org-export-with-LaTeX-fragments))
13032 (require 'org-exp))
13033 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
13034 org-export-with-LaTeX-fragments)])
13035 "--"
13036 ("Documentation"
13037 ["Show Version" org-version t]
13038 ["Info Documentation" org-info t])
13039 ("Customize"
13040 ["Browse Org Group" org-customize t]
13041 "--"
13042 ["Expand This Menu" org-create-customize-menu
13043 (fboundp 'customize-menu-create)])
13044 "--"
13045 ["Refresh setup" org-mode-restart t]
13048 (defun org-info (&optional node)
13049 "Read documentation for Org-mode in the info system.
13050 With optional NODE, go directly to that node."
13051 (interactive)
13052 (info (format "(org)%s" (or node ""))))
13054 (defun org-install-agenda-files-menu ()
13055 (let ((bl (buffer-list)))
13056 (save-excursion
13057 (while bl
13058 (set-buffer (pop bl))
13059 (if (org-mode-p) (setq bl nil)))
13060 (when (org-mode-p)
13061 (easy-menu-change
13062 '("Org") "File List for Agenda"
13063 (append
13064 (list
13065 ["Edit File List" (org-edit-agenda-file-list) t]
13066 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
13067 ["Remove Current File from List" org-remove-file t]
13068 ["Cycle through agenda files" org-cycle-agenda-files t]
13069 ["Occur in all agenda files" org-occur-in-agenda-files t]
13070 "--")
13071 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
13073 ;;;; Documentation
13075 ;;;###autoload
13076 (defun org-require-autoloaded-modules ()
13077 (interactive)
13078 (mapc 'require
13079 '(org-agenda org-archive org-clock org-colview
13080 org-exp org-id org-export-latex org-publish
13081 org-remember org-table)))
13083 ;;;###autoload
13084 (defun org-customize ()
13085 "Call the customize function with org as argument."
13086 (interactive)
13087 (org-load-modules-maybe)
13088 (org-require-autoloaded-modules)
13089 (customize-browse 'org))
13091 (defun org-create-customize-menu ()
13092 "Create a full customization menu for Org-mode, insert it into the menu."
13093 (interactive)
13094 (org-load-modules-maybe)
13095 (org-require-autoloaded-modules)
13096 (if (fboundp 'customize-menu-create)
13097 (progn
13098 (easy-menu-change
13099 '("Org") "Customize"
13100 `(["Browse Org group" org-customize t]
13101 "--"
13102 ,(customize-menu-create 'org)
13103 ["Set" Custom-set t]
13104 ["Save" Custom-save t]
13105 ["Reset to Current" Custom-reset-current t]
13106 ["Reset to Saved" Custom-reset-saved t]
13107 ["Reset to Standard Settings" Custom-reset-standard t]))
13108 (message "\"Org\"-menu now contains full customization menu"))
13109 (error "Cannot expand menu (outdated version of cus-edit.el)")))
13111 ;;;; Miscellaneous stuff
13113 ;;; Generally useful functions
13115 (defun org-display-warning (message) ;; Copied from Emacs-Muse
13116 "Display the given MESSAGE as a warning."
13117 (if (fboundp 'display-warning)
13118 (display-warning 'org message
13119 (if (featurep 'xemacs)
13120 'warning
13121 :warning))
13122 (let ((buf (get-buffer-create "*Org warnings*")))
13123 (with-current-buffer buf
13124 (goto-char (point-max))
13125 (insert "Warning (Org): " message)
13126 (unless (bolp)
13127 (newline)))
13128 (display-buffer buf)
13129 (sit-for 0))))
13131 (defun org-goto-marker-or-bmk (marker &optional bookmark)
13132 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
13133 (if (and marker (marker-buffer marker)
13134 (buffer-live-p (marker-buffer marker)))
13135 (progn
13136 (switch-to-buffer (marker-buffer marker))
13137 (if (or (> marker (point-max)) (< marker (point-min)))
13138 (widen))
13139 (goto-char marker))
13140 (if bookmark
13141 (bookmark-jump bookmark)
13142 (error "Cannot find location"))))
13144 (defun org-quote-csv-field (s)
13145 "Quote field for inclusion in CSV material."
13146 (if (string-match "[\",]" s)
13147 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
13150 (defun org-plist-delete (plist property)
13151 "Delete PROPERTY from PLIST.
13152 This is in contrast to merely setting it to 0."
13153 (let (p)
13154 (while plist
13155 (if (not (eq property (car plist)))
13156 (setq p (plist-put p (car plist) (nth 1 plist))))
13157 (setq plist (cddr plist)))
13160 (defun org-force-self-insert (N)
13161 "Needed to enforce self-insert under remapping."
13162 (interactive "p")
13163 (self-insert-command N))
13165 (defun org-string-width (s)
13166 "Compute width of string, ignoring invisible characters.
13167 This ignores character with invisibility property `org-link', and also
13168 characters with property `org-cwidth', because these will become invisible
13169 upon the next fontification round."
13170 (let (b l)
13171 (when (or (eq t buffer-invisibility-spec)
13172 (assq 'org-link buffer-invisibility-spec))
13173 (while (setq b (text-property-any 0 (length s)
13174 'invisible 'org-link s))
13175 (setq s (concat (substring s 0 b)
13176 (substring s (or (next-single-property-change
13177 b 'invisible s) (length s)))))))
13178 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
13179 (setq s (concat (substring s 0 b)
13180 (substring s (or (next-single-property-change
13181 b 'org-cwidth s) (length s))))))
13182 (setq l (string-width s) b -1)
13183 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
13184 (setq l (- l (get-text-property b 'org-dwidth-n s))))
13187 (defun org-get-indentation (&optional line)
13188 "Get the indentation of the current line, interpreting tabs.
13189 When LINE is given, assume it represents a line and compute its indentation."
13190 (if line
13191 (if (string-match "^ *" (org-remove-tabs line))
13192 (match-end 0))
13193 (save-excursion
13194 (beginning-of-line 1)
13195 (skip-chars-forward " \t")
13196 (current-column))))
13198 (defun org-remove-tabs (s &optional width)
13199 "Replace tabulators in S with spaces.
13200 Assumes that s is a single line, starting in column 0."
13201 (setq width (or width tab-width))
13202 (while (string-match "\t" s)
13203 (setq s (replace-match
13204 (make-string
13205 (- (* width (/ (+ (match-beginning 0) width) width))
13206 (match-beginning 0)) ?\ )
13207 t t s)))
13210 (defun org-fix-indentation (line ind)
13211 "Fix indentation in LINE.
13212 IND is a cons cell with target and minimum indentation.
13213 If the current indenation in LINE is smaller than the minimum,
13214 leave it alone. If it is larger than ind, set it to the target."
13215 (let* ((l (org-remove-tabs line))
13216 (i (org-get-indentation l))
13217 (i1 (car ind)) (i2 (cdr ind)))
13218 (if (>= i i2) (setq l (substring line i2)))
13219 (if (> i1 0)
13220 (concat (make-string i1 ?\ ) l)
13221 l)))
13223 (defun org-base-buffer (buffer)
13224 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
13225 (if (not buffer)
13226 buffer
13227 (or (buffer-base-buffer buffer)
13228 buffer)))
13230 (defun org-trim (s)
13231 "Remove whitespace at beginning and end of string."
13232 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
13233 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
13236 (defun org-wrap (string &optional width lines)
13237 "Wrap string to either a number of lines, or a width in characters.
13238 If WIDTH is non-nil, the string is wrapped to that width, however many lines
13239 that costs. If there is a word longer than WIDTH, the text is actually
13240 wrapped to the length of that word.
13241 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
13242 many lines, whatever width that takes.
13243 The return value is a list of lines, without newlines at the end."
13244 (let* ((words (org-split-string string "[ \t\n]+"))
13245 (maxword (apply 'max (mapcar 'org-string-width words)))
13246 w ll)
13247 (cond (width
13248 (org-do-wrap words (max maxword width)))
13249 (lines
13250 (setq w maxword)
13251 (setq ll (org-do-wrap words maxword))
13252 (if (<= (length ll) lines)
13254 (setq ll words)
13255 (while (> (length ll) lines)
13256 (setq w (1+ w))
13257 (setq ll (org-do-wrap words w)))
13258 ll))
13259 (t (error "Cannot wrap this")))))
13261 (defun org-do-wrap (words width)
13262 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
13263 (let (lines line)
13264 (while words
13265 (setq line (pop words))
13266 (while (and words (< (+ (length line) (length (car words))) width))
13267 (setq line (concat line " " (pop words))))
13268 (setq lines (push line lines)))
13269 (nreverse lines)))
13271 (defun org-split-string (string &optional separators)
13272 "Splits STRING into substrings at SEPARATORS.
13273 No empty strings are returned if there are matches at the beginning
13274 and end of string."
13275 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
13276 (start 0)
13277 notfirst
13278 (list nil))
13279 (while (and (string-match rexp string
13280 (if (and notfirst
13281 (= start (match-beginning 0))
13282 (< start (length string)))
13283 (1+ start) start))
13284 (< (match-beginning 0) (length string)))
13285 (setq notfirst t)
13286 (or (eq (match-beginning 0) 0)
13287 (and (eq (match-beginning 0) (match-end 0))
13288 (eq (match-beginning 0) start))
13289 (setq list
13290 (cons (substring string start (match-beginning 0))
13291 list)))
13292 (setq start (match-end 0)))
13293 (or (eq start (length string))
13294 (setq list
13295 (cons (substring string start)
13296 list)))
13297 (nreverse list)))
13299 (defun org-context ()
13300 "Return a list of contexts of the current cursor position.
13301 If several contexts apply, all are returned.
13302 Each context entry is a list with a symbol naming the context, and
13303 two positions indicating start and end of the context. Possible
13304 contexts are:
13306 :headline anywhere in a headline
13307 :headline-stars on the leading stars in a headline
13308 :todo-keyword on a TODO keyword (including DONE) in a headline
13309 :tags on the TAGS in a headline
13310 :priority on the priority cookie in a headline
13311 :item on the first line of a plain list item
13312 :item-bullet on the bullet/number of a plain list item
13313 :checkbox on the checkbox in a plain list item
13314 :table in an org-mode table
13315 :table-special on a special filed in a table
13316 :table-table in a table.el table
13317 :link on a hyperlink
13318 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
13319 :target on a <<target>>
13320 :radio-target on a <<<radio-target>>>
13321 :latex-fragment on a LaTeX fragment
13322 :latex-preview on a LaTeX fragment with overlayed preview image
13324 This function expects the position to be visible because it uses font-lock
13325 faces as a help to recognize the following contexts: :table-special, :link,
13326 and :keyword."
13327 (let* ((f (get-text-property (point) 'face))
13328 (faces (if (listp f) f (list f)))
13329 (p (point)) clist o)
13330 ;; First the large context
13331 (cond
13332 ((org-on-heading-p t)
13333 (push (list :headline (point-at-bol) (point-at-eol)) clist)
13334 (when (progn
13335 (beginning-of-line 1)
13336 (looking-at org-todo-line-tags-regexp))
13337 (push (org-point-in-group p 1 :headline-stars) clist)
13338 (push (org-point-in-group p 2 :todo-keyword) clist)
13339 (push (org-point-in-group p 4 :tags) clist))
13340 (goto-char p)
13341 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
13342 (if (looking-at "\\[#[A-Z0-9]\\]")
13343 (push (org-point-in-group p 0 :priority) clist)))
13345 ((org-at-item-p)
13346 (push (org-point-in-group p 2 :item-bullet) clist)
13347 (push (list :item (point-at-bol)
13348 (save-excursion (org-end-of-item) (point)))
13349 clist)
13350 (and (org-at-item-checkbox-p)
13351 (push (org-point-in-group p 0 :checkbox) clist)))
13353 ((org-at-table-p)
13354 (push (list :table (org-table-begin) (org-table-end)) clist)
13355 (if (memq 'org-formula faces)
13356 (push (list :table-special
13357 (previous-single-property-change p 'face)
13358 (next-single-property-change p 'face)) clist)))
13359 ((org-at-table-p 'any)
13360 (push (list :table-table) clist)))
13361 (goto-char p)
13363 ;; Now the small context
13364 (cond
13365 ((org-at-timestamp-p)
13366 (push (org-point-in-group p 0 :timestamp) clist))
13367 ((memq 'org-link faces)
13368 (push (list :link
13369 (previous-single-property-change p 'face)
13370 (next-single-property-change p 'face)) clist))
13371 ((memq 'org-special-keyword faces)
13372 (push (list :keyword
13373 (previous-single-property-change p 'face)
13374 (next-single-property-change p 'face)) clist))
13375 ((org-on-target-p)
13376 (push (org-point-in-group p 0 :target) clist)
13377 (goto-char (1- (match-beginning 0)))
13378 (if (looking-at org-radio-target-regexp)
13379 (push (org-point-in-group p 0 :radio-target) clist))
13380 (goto-char p))
13381 ((setq o (car (delq nil
13382 (mapcar
13383 (lambda (x)
13384 (if (memq x org-latex-fragment-image-overlays) x))
13385 (org-overlays-at (point))))))
13386 (push (list :latex-fragment
13387 (org-overlay-start o) (org-overlay-end o)) clist)
13388 (push (list :latex-preview
13389 (org-overlay-start o) (org-overlay-end o)) clist))
13390 ((org-inside-LaTeX-fragment-p)
13391 ;; FIXME: positions wrong.
13392 (push (list :latex-fragment (point) (point)) clist)))
13394 (setq clist (nreverse (delq nil clist)))
13395 clist))
13397 ;; FIXME: Compare with at-regexp-p Do we need both?
13398 (defun org-in-regexp (re &optional nlines visually)
13399 "Check if point is inside a match of regexp.
13400 Normally only the current line is checked, but you can include NLINES extra
13401 lines both before and after point into the search.
13402 If VISUALLY is set, require that the cursor is not after the match but
13403 really on, so that the block visually is on the match."
13404 (catch 'exit
13405 (let ((pos (point))
13406 (eol (point-at-eol (+ 1 (or nlines 0))))
13407 (inc (if visually 1 0)))
13408 (save-excursion
13409 (beginning-of-line (- 1 (or nlines 0)))
13410 (while (re-search-forward re eol t)
13411 (if (and (<= (match-beginning 0) pos)
13412 (>= (+ inc (match-end 0)) pos))
13413 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
13415 (defun org-at-regexp-p (regexp)
13416 "Is point inside a match of REGEXP in the current line?"
13417 (catch 'exit
13418 (save-excursion
13419 (let ((pos (point)) (end (point-at-eol)))
13420 (beginning-of-line 1)
13421 (while (re-search-forward regexp end t)
13422 (if (and (<= (match-beginning 0) pos)
13423 (>= (match-end 0) pos))
13424 (throw 'exit t)))
13425 nil))))
13427 (defun org-occur-in-agenda-files (regexp &optional nlines)
13428 "Call `multi-occur' with buffers for all agenda files."
13429 (interactive "sOrg-files matching: \np")
13430 (let* ((files (org-agenda-files))
13431 (tnames (mapcar 'file-truename files))
13432 (extra org-agenda-text-search-extra-files)
13434 (when (eq (car extra) 'agenda-archives)
13435 (setq extra (cdr extra))
13436 (setq files (org-add-archive-files files)))
13437 (while (setq f (pop extra))
13438 (unless (member (file-truename f) tnames)
13439 (add-to-list 'files f 'append)
13440 (add-to-list 'tnames (file-truename f) 'append)))
13441 (multi-occur
13442 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
13443 regexp)))
13445 (if (boundp 'occur-mode-find-occurrence-hook)
13446 ;; Emacs 23
13447 (add-hook 'occur-mode-find-occurrence-hook
13448 (lambda ()
13449 (when (org-mode-p)
13450 (org-reveal))))
13451 ;; Emacs 22
13452 (defadvice occur-mode-goto-occurrence
13453 (after org-occur-reveal activate)
13454 (and (org-mode-p) (org-reveal)))
13455 (defadvice occur-mode-goto-occurrence-other-window
13456 (after org-occur-reveal activate)
13457 (and (org-mode-p) (org-reveal)))
13458 (defadvice occur-mode-display-occurrence
13459 (after org-occur-reveal activate)
13460 (when (org-mode-p)
13461 (let ((pos (occur-mode-find-occurrence)))
13462 (with-current-buffer (marker-buffer pos)
13463 (save-excursion
13464 (goto-char pos)
13465 (org-reveal)))))))
13467 (defun org-uniquify (list)
13468 "Remove duplicate elements from LIST."
13469 (let (res)
13470 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
13471 res))
13473 (defun org-delete-all (elts list)
13474 "Remove all elements in ELTS from LIST."
13475 (while elts
13476 (setq list (delete (pop elts) list)))
13477 list)
13479 (defun org-back-over-empty-lines ()
13480 "Move backwards over witespace, to the beginning of the first empty line.
13481 Returns the number of empty lines passed."
13482 (let ((pos (point)))
13483 (skip-chars-backward " \t\n\r")
13484 (beginning-of-line 2)
13485 (goto-char (min (point) pos))
13486 (count-lines (point) pos)))
13488 (defun org-skip-whitespace ()
13489 (skip-chars-forward " \t\n\r"))
13491 (defun org-point-in-group (point group &optional context)
13492 "Check if POINT is in match-group GROUP.
13493 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
13494 match. If the match group does ot exist or point is not inside it,
13495 return nil."
13496 (and (match-beginning group)
13497 (>= point (match-beginning group))
13498 (<= point (match-end group))
13499 (if context
13500 (list context (match-beginning group) (match-end group))
13501 t)))
13503 (defun org-switch-to-buffer-other-window (&rest args)
13504 "Switch to buffer in a second window on the current frame.
13505 In particular, do not allow pop-up frames."
13506 (let (pop-up-frames special-display-buffer-names special-display-regexps
13507 special-display-function)
13508 (apply 'switch-to-buffer-other-window args)))
13510 (defun org-combine-plists (&rest plists)
13511 "Create a single property list from all plists in PLISTS.
13512 The process starts by copying the first list, and then setting properties
13513 from the other lists. Settings in the last list are the most significant
13514 ones and overrule settings in the other lists."
13515 (let ((rtn (copy-sequence (pop plists)))
13516 p v ls)
13517 (while plists
13518 (setq ls (pop plists))
13519 (while ls
13520 (setq p (pop ls) v (pop ls))
13521 (setq rtn (plist-put rtn p v))))
13522 rtn))
13524 (defun org-move-line-down (arg)
13525 "Move the current line down. With prefix argument, move it past ARG lines."
13526 (interactive "p")
13527 (let ((col (current-column))
13528 beg end pos)
13529 (beginning-of-line 1) (setq beg (point))
13530 (beginning-of-line 2) (setq end (point))
13531 (beginning-of-line (+ 1 arg))
13532 (setq pos (move-marker (make-marker) (point)))
13533 (insert (delete-and-extract-region beg end))
13534 (goto-char pos)
13535 (org-move-to-column col)))
13537 (defun org-move-line-up (arg)
13538 "Move the current line up. With prefix argument, move it past ARG lines."
13539 (interactive "p")
13540 (let ((col (current-column))
13541 beg end pos)
13542 (beginning-of-line 1) (setq beg (point))
13543 (beginning-of-line 2) (setq end (point))
13544 (beginning-of-line (- arg))
13545 (setq pos (move-marker (make-marker) (point)))
13546 (insert (delete-and-extract-region beg end))
13547 (goto-char pos)
13548 (org-move-to-column col)))
13550 (defun org-replace-escapes (string table)
13551 "Replace %-escapes in STRING with values in TABLE.
13552 TABLE is an association list with keys like \"%a\" and string values.
13553 The sequences in STRING may contain normal field width and padding information,
13554 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
13555 so values can contain further %-escapes if they are define later in TABLE."
13556 (let ((case-fold-search nil)
13557 e re rpl)
13558 (while (setq e (pop table))
13559 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
13560 (while (string-match re string)
13561 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
13562 (cdr e)))
13563 (setq string (replace-match rpl t t string))))
13564 string))
13567 (defun org-sublist (list start end)
13568 "Return a section of LIST, from START to END.
13569 Counting starts at 1."
13570 (let (rtn (c start))
13571 (setq list (nthcdr (1- start) list))
13572 (while (and list (<= c end))
13573 (push (pop list) rtn)
13574 (setq c (1+ c)))
13575 (nreverse rtn)))
13577 (defun org-find-base-buffer-visiting (file)
13578 "Like `find-buffer-visiting' but alway return the base buffer and
13579 not an indirect buffer."
13580 (let ((buf (find-buffer-visiting file)))
13581 (if buf
13582 (or (buffer-base-buffer buf) buf)
13583 nil)))
13585 (defun org-image-file-name-regexp ()
13586 "Return regexp matching the file names of images."
13587 (if (fboundp 'image-file-name-regexp)
13588 (image-file-name-regexp)
13589 (let ((image-file-name-extensions
13590 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
13591 "xbm" "xpm" "pbm" "pgm" "ppm")))
13592 (concat "\\."
13593 (regexp-opt (nconc (mapcar 'upcase
13594 image-file-name-extensions)
13595 image-file-name-extensions)
13597 "\\'"))))
13599 (defun org-file-image-p (file)
13600 "Return non-nil if FILE is an image."
13601 (save-match-data
13602 (string-match (org-image-file-name-regexp) file)))
13604 (defun org-get-cursor-date ()
13605 "Return the date at cursor in as a time.
13606 This works in the calendar and in the agenda, anywhere else it just
13607 returns the current time."
13608 (let (date day defd)
13609 (cond
13610 ((eq major-mode 'calendar-mode)
13611 (setq date (calendar-cursor-to-date)
13612 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13613 ((eq major-mode 'org-agenda-mode)
13614 (setq day (get-text-property (point) 'day))
13615 (if day
13616 (setq date (calendar-gregorian-from-absolute day)
13617 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
13618 (nth 2 date))))))
13619 (or defd (current-time))))
13621 (defvar org-agenda-action-marker (make-marker)
13622 "Marker pointing to the entry for the next agenda action.")
13624 (defun org-mark-entry-for-agenda-action ()
13625 "Mark the current entry as target of an agenda action.
13626 Agenda actions are actions executed from the agenda with the key `k',
13627 which make use of the date at the cursor."
13628 (interactive)
13629 (move-marker org-agenda-action-marker
13630 (save-excursion (org-back-to-heading t) (point))
13631 (current-buffer))
13632 (message
13633 "Entry marked for action; press `k' at desired date in agenda or calendar"))
13635 ;;; Paragraph filling stuff.
13636 ;; We want this to be just right, so use the full arsenal.
13638 (defun org-indent-line-function ()
13639 "Indent line like previous, but further if previous was headline or item."
13640 (interactive)
13641 (let* ((pos (point))
13642 (itemp (org-at-item-p))
13643 column bpos bcol tpos tcol bullet btype bullet-type)
13644 ;; Find the previous relevant line
13645 (beginning-of-line 1)
13646 (cond
13647 ((looking-at "#") (setq column 0))
13648 ((looking-at "\\*+ ") (setq column 0))
13650 (beginning-of-line 0)
13651 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
13652 (beginning-of-line 0))
13653 (cond
13654 ((looking-at "\\*+[ \t]+")
13655 (if (not org-adapt-indentation)
13656 (setq column 0)
13657 (goto-char (match-end 0))
13658 (setq column (current-column))))
13659 ((org-in-item-p)
13660 (org-beginning-of-item)
13661 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
13662 (setq bpos (match-beginning 1) tpos (match-end 0)
13663 bcol (progn (goto-char bpos) (current-column))
13664 tcol (progn (goto-char tpos) (current-column))
13665 bullet (match-string 1)
13666 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
13667 (if (> tcol (+ bcol org-description-max-indent))
13668 (setq tcol (+ bcol 5)))
13669 (if (not itemp)
13670 (setq column tcol)
13671 (goto-char pos)
13672 (beginning-of-line 1)
13673 (if (looking-at "\\S-")
13674 (progn
13675 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
13676 (setq bullet (match-string 1)
13677 btype (if (string-match "[0-9]" bullet) "n" bullet))
13678 (setq column (if (equal btype bullet-type) bcol tcol)))
13679 (setq column (org-get-indentation)))))
13680 (t (setq column (org-get-indentation))))))
13681 (goto-char pos)
13682 (if (<= (current-column) (current-indentation))
13683 (org-indent-line-to column)
13684 (save-excursion (org-indent-line-to column)))
13685 (setq column (current-column))
13686 (beginning-of-line 1)
13687 (if (looking-at
13688 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
13689 (replace-match (concat "\\1" (format org-property-format
13690 (match-string 2) (match-string 3)))
13691 t nil))
13692 (org-move-to-column column)))
13694 (defun org-set-autofill-regexps ()
13695 (interactive)
13696 ;; In the paragraph separator we include headlines, because filling
13697 ;; text in a line directly attached to a headline would otherwise
13698 ;; fill the headline as well.
13699 (org-set-local 'comment-start-skip "^#+[ \t]*")
13700 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
13701 ;; The paragraph starter includes hand-formatted lists.
13702 (org-set-local 'paragraph-start
13703 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
13704 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
13705 ;; But only if the user has not turned off tables or fixed-width regions
13706 (org-set-local
13707 'auto-fill-inhibit-regexp
13708 (concat "\\*+ \\|#\\+"
13709 "\\|[ \t]*" org-keyword-time-regexp
13710 (if (or org-enable-table-editor org-enable-fixed-width-editor)
13711 (concat
13712 "\\|[ \t]*["
13713 (if org-enable-table-editor "|" "")
13714 (if org-enable-fixed-width-editor ":" "")
13715 "]"))))
13716 ;; We use our own fill-paragraph function, to make sure that tables
13717 ;; and fixed-width regions are not wrapped. That function will pass
13718 ;; through to `fill-paragraph' when appropriate.
13719 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
13720 ; Adaptive filling: To get full control, first make sure that
13721 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
13722 (org-set-local 'adaptive-fill-regexp "\000")
13723 (org-set-local 'adaptive-fill-function
13724 'org-adaptive-fill-function)
13725 (org-set-local
13726 'align-mode-rules-list
13727 '((org-in-buffer-settings
13728 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
13729 (modes . '(org-mode))))))
13731 (defun org-fill-paragraph (&optional justify)
13732 "Re-align a table, pass through to fill-paragraph if no table."
13733 (let ((table-p (org-at-table-p))
13734 (table.el-p (org-at-table.el-p)))
13735 (cond ((and (equal (char-after (point-at-bol)) ?*)
13736 (save-excursion (goto-char (point-at-bol))
13737 (looking-at outline-regexp)))
13738 t) ; skip headlines
13739 (table.el-p t) ; skip table.el tables
13740 (table-p (org-table-align) t) ; align org-mode tables
13741 (t nil)))) ; call paragraph-fill
13743 ;; For reference, this is the default value of adaptive-fill-regexp
13744 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
13746 (defun org-adaptive-fill-function ()
13747 "Return a fill prefix for org-mode files.
13748 In particular, this makes sure hanging paragraphs for hand-formatted lists
13749 work correctly."
13750 (cond ((looking-at "#[ \t]+")
13751 (match-string 0))
13752 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
13753 (save-excursion
13754 (if (> (match-end 1) (+ (match-beginning 1)
13755 org-description-max-indent))
13756 (goto-char (+ (match-beginning 1) 5))
13757 (goto-char (match-end 0)))
13758 (make-string (current-column) ?\ )))
13759 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
13760 (save-excursion
13761 (goto-char (match-end 0))
13762 (make-string (current-column) ?\ )))
13763 (t nil)))
13765 ;;; Other stuff.
13767 (defun org-toggle-fixed-width-section (arg)
13768 "Toggle the fixed-width export.
13769 If there is no active region, the QUOTE keyword at the current headline is
13770 inserted or removed. When present, it causes the text between this headline
13771 and the next to be exported as fixed-width text, and unmodified.
13772 If there is an active region, this command adds or removes a colon as the
13773 first character of this line. If the first character of a line is a colon,
13774 this line is also exported in fixed-width font."
13775 (interactive "P")
13776 (let* ((cc 0)
13777 (regionp (org-region-active-p))
13778 (beg (if regionp (region-beginning) (point)))
13779 (end (if regionp (region-end)))
13780 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
13781 (case-fold-search nil)
13782 (re "[ \t]*\\(:\\)")
13783 off)
13784 (if regionp
13785 (save-excursion
13786 (goto-char beg)
13787 (setq cc (current-column))
13788 (beginning-of-line 1)
13789 (setq off (looking-at re))
13790 (while (> nlines 0)
13791 (setq nlines (1- nlines))
13792 (beginning-of-line 1)
13793 (cond
13794 (arg
13795 (org-move-to-column cc t)
13796 (insert ":\n")
13797 (forward-line -1))
13798 ((and off (looking-at re))
13799 (replace-match "" t t nil 1))
13800 ((not off) (org-move-to-column cc t) (insert ":")))
13801 (forward-line 1)))
13802 (save-excursion
13803 (org-back-to-heading)
13804 (if (looking-at (concat outline-regexp
13805 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
13806 (replace-match "" t t nil 1)
13807 (if (looking-at outline-regexp)
13808 (progn
13809 (goto-char (match-end 0))
13810 (insert org-quote-string " "))))))))
13812 ;;;; Functions extending outline functionality
13814 (defun org-beginning-of-line (&optional arg)
13815 "Go to the beginning of the current line. If that is invisible, continue
13816 to a visible line beginning. This makes the function of C-a more intuitive.
13817 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
13818 first attempt, and only move to after the tags when the cursor is already
13819 beyond the end of the headline."
13820 (interactive "P")
13821 (let ((pos (point)) refpos)
13822 (beginning-of-line 1)
13823 (if (bobp)
13825 (backward-char 1)
13826 (if (org-invisible-p)
13827 (while (and (not (bobp)) (org-invisible-p))
13828 (backward-char 1)
13829 (beginning-of-line 1))
13830 (forward-char 1)))
13831 (when org-special-ctrl-a/e
13832 (cond
13833 ((and (looking-at org-complex-heading-regexp)
13834 (= (char-after (match-end 1)) ?\ ))
13835 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
13836 (point-at-eol)))
13837 (goto-char
13838 (if (eq org-special-ctrl-a/e t)
13839 (cond ((> pos refpos) refpos)
13840 ((= pos (point)) refpos)
13841 (t (point)))
13842 (cond ((> pos (point)) (point))
13843 ((not (eq last-command this-command)) (point))
13844 (t refpos)))))
13845 ((org-at-item-p)
13846 (goto-char
13847 (if (eq org-special-ctrl-a/e t)
13848 (cond ((> pos (match-end 4)) (match-end 4))
13849 ((= pos (point)) (match-end 4))
13850 (t (point)))
13851 (cond ((> pos (point)) (point))
13852 ((not (eq last-command this-command)) (point))
13853 (t (match-end 4))))))))
13854 (org-no-warnings
13855 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
13857 (defun org-end-of-line (&optional arg)
13858 "Go to the end of the line.
13859 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
13860 first attempt, and only move to after the tags when the cursor is already
13861 beyond the end of the headline."
13862 (interactive "P")
13863 (if (or (not org-special-ctrl-a/e)
13864 (not (org-on-heading-p)))
13865 (end-of-line arg)
13866 (let ((pos (point)))
13867 (beginning-of-line 1)
13868 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
13869 (if (eq org-special-ctrl-a/e t)
13870 (if (or (< pos (match-beginning 1))
13871 (= pos (match-end 0)))
13872 (goto-char (match-beginning 1))
13873 (goto-char (match-end 0)))
13874 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
13875 (goto-char (match-end 0))
13876 (goto-char (match-beginning 1))))
13877 (end-of-line arg))))
13878 (org-no-warnings
13879 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
13882 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
13883 (define-key org-mode-map "\C-e" 'org-end-of-line)
13885 (defun org-kill-line (&optional arg)
13886 "Kill line, to tags or end of line."
13887 (interactive "P")
13888 (cond
13889 ((or (not org-special-ctrl-k)
13890 (bolp)
13891 (not (org-on-heading-p)))
13892 (call-interactively 'kill-line))
13893 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
13894 (kill-region (point) (match-beginning 1))
13895 (org-set-tags nil t))
13896 (t (kill-region (point) (point-at-eol)))))
13898 (define-key org-mode-map "\C-k" 'org-kill-line)
13900 (defun org-yank ()
13901 "Yank. If the kill is a subtree, treat it specially.
13902 This command will look at the current kill and check it is a single
13903 subtree, or a series of subtrees[1]. If it passes the test, it is
13904 treated specially, depending on the value of the following variables, both
13905 set by default.
13907 org-yank-folded-subtrees
13908 When set, the subree(s) wiil be folded after insertion.
13910 org-yank-adjusted-subtrees
13911 When set, the subtree will be promoted or demoted in order to
13912 fit into the local outline tree structure.
13915 \[1] Basically, the test checks if the first non-white line is a heading
13916 and if there are no other headings with fewer stars."
13917 (interactive)
13918 (let ((subtreep (org-kill-is-subtree-p)))
13919 (if org-yank-folded-subtrees
13920 (let ((beg (point))
13921 end)
13922 (if (and subtreep org-yank-adjusted-subtrees)
13923 (org-paste-subtree nil nil 'for-yank)
13924 (call-interactively 'yank))
13925 (setq end (point))
13926 (goto-char beg)
13927 (when (and (bolp) subtreep)
13928 (or (looking-at outline-regexp)
13929 (re-search-forward (concat "^" outline-regexp) end t))
13930 (while (and (< (point) end) (looking-at outline-regexp))
13931 (hide-subtree)
13932 (org-cycle-show-empty-lines 'folded)
13933 (condition-case nil
13934 (outline-forward-same-level 1)
13935 (error (goto-char end)))))
13936 (goto-char end)
13937 (skip-chars-forward " \t\n\r"))
13938 (if (and subtreep org-yank-adjusted-subtrees)
13939 (org-paste-subtree nil nil 'for-yank)
13940 (call-interactively 'yank)))))
13942 (define-key org-mode-map "\C-y" 'org-yank)
13944 (defun org-invisible-p ()
13945 "Check if point is at a character currently not visible."
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 (defun org-invisible-p2 ()
13952 "Check if point is at a character currently not visible."
13953 (save-excursion
13954 (if (and (eolp) (not (bobp))) (backward-char 1))
13955 ;; Early versions of noutline don't have `outline-invisible-p'.
13956 (if (fboundp 'outline-invisible-p)
13957 (outline-invisible-p)
13958 (get-char-property (point) 'invisible))))
13960 (defalias 'org-back-to-heading 'outline-back-to-heading)
13961 (defalias 'org-on-heading-p 'outline-on-heading-p)
13962 (defalias 'org-at-heading-p 'outline-on-heading-p)
13963 (defun org-at-heading-or-item-p ()
13964 (or (org-on-heading-p) (org-at-item-p)))
13966 (defun org-on-target-p ()
13967 (or (org-in-regexp org-radio-target-regexp)
13968 (org-in-regexp org-target-regexp)))
13970 (defun org-up-heading-all (arg)
13971 "Move to the heading line of which the present line is a subheading.
13972 This function considers both visible and invisible heading lines.
13973 With argument, move up ARG levels."
13974 (if (fboundp 'outline-up-heading-all)
13975 (outline-up-heading-all arg) ; emacs 21 version of outline.el
13976 (outline-up-heading arg t))) ; emacs 22 version of outline.el
13978 (defun org-up-heading-safe ()
13979 "Move to the heading line of which the present line is a subheading.
13980 This version will not throw an error. It will return the level of the
13981 headline found, or nil if no higher level is found."
13982 (let ((pos (point)) start-level level
13983 (re (concat "^" outline-regexp)))
13984 (catch 'exit
13985 (outline-back-to-heading t)
13986 (setq start-level (funcall outline-level))
13987 (if (equal start-level 1) (throw 'exit nil))
13988 (while (re-search-backward re nil t)
13989 (setq level (funcall outline-level))
13990 (if (< level start-level) (throw 'exit level)))
13991 nil)))
13993 (defun org-first-sibling-p ()
13994 "Is this heading the first child of its parents?"
13995 (interactive)
13996 (let ((re (concat "^" outline-regexp))
13997 level l)
13998 (unless (org-at-heading-p t)
13999 (error "Not at a heading"))
14000 (setq level (funcall outline-level))
14001 (save-excursion
14002 (if (not (re-search-backward re nil t))
14004 (setq l (funcall outline-level))
14005 (< l level)))))
14007 (defun org-goto-sibling (&optional previous)
14008 "Goto the next sibling, even if it is invisible.
14009 When PREVIOUS is set, go to the previous sibling instead. Returns t
14010 when a sibling was found. When none is found, return nil and don't
14011 move point."
14012 (let ((fun (if previous 're-search-backward 're-search-forward))
14013 (pos (point))
14014 (re (concat "^" outline-regexp))
14015 level l)
14016 (when (condition-case nil (org-back-to-heading t) (error nil))
14017 (setq level (funcall outline-level))
14018 (catch 'exit
14019 (or previous (forward-char 1))
14020 (while (funcall fun re nil t)
14021 (setq l (funcall outline-level))
14022 (when (< l level) (goto-char pos) (throw 'exit nil))
14023 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
14024 (goto-char pos)
14025 nil))))
14027 (defun org-show-siblings ()
14028 "Show all siblings of the current headline."
14029 (save-excursion
14030 (while (org-goto-sibling) (org-flag-heading nil)))
14031 (save-excursion
14032 (while (org-goto-sibling 'previous)
14033 (org-flag-heading nil))))
14035 (defun org-show-hidden-entry ()
14036 "Show an entry where even the heading is hidden."
14037 (save-excursion
14038 (org-show-entry)))
14040 (defun org-flag-heading (flag &optional entry)
14041 "Flag the current heading. FLAG non-nil means make invisible.
14042 When ENTRY is non-nil, show the entire entry."
14043 (save-excursion
14044 (org-back-to-heading t)
14045 ;; Check if we should show the entire entry
14046 (if entry
14047 (progn
14048 (org-show-entry)
14049 (save-excursion
14050 (and (outline-next-heading)
14051 (org-flag-heading nil))))
14052 (outline-flag-region (max (point-min) (1- (point)))
14053 (save-excursion (outline-end-of-heading) (point))
14054 flag))))
14056 (defun org-forward-same-level (arg)
14057 "Move forward to the ARG'th subheading at same level as this one.
14058 Stop at the first and last subheadings of a superior heading.
14059 This is like outline-forward-same-level, but invisible headings are ok."
14060 (interactive "p")
14061 (outline-back-to-heading t)
14062 (while (> arg 0)
14063 (let ((point-to-move-to (save-excursion
14064 (org-get-next-sibling))))
14065 (if point-to-move-to
14066 (progn
14067 (goto-char point-to-move-to)
14068 (setq arg (1- arg)))
14069 (progn
14070 (setq arg 0)
14071 (error "No following same-level heading"))))))
14073 (defun org-get-next-sibling ()
14074 "Move to next heading of the same level, and return point.
14075 If there is no such heading, return nil.
14076 This is like outline-next-sibling, but invisible headings are ok."
14077 (let ((level (funcall outline-level)))
14078 (outline-next-heading)
14079 (while (and (not (eobp)) (> (funcall outline-level) level))
14080 (outline-next-heading))
14081 (if (or (eobp) (< (funcall outline-level) level))
14083 (point))))
14085 (defun org-end-of-subtree (&optional invisible-OK to-heading)
14086 ;; This is an exact copy of the original function, but it uses
14087 ;; `org-back-to-heading', to make it work also in invisible
14088 ;; trees. And is uses an invisible-OK argument.
14089 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
14090 (org-back-to-heading invisible-OK)
14091 (let ((first t)
14092 (level (funcall outline-level)))
14093 (while (and (not (eobp))
14094 (or first (> (funcall outline-level) level)))
14095 (setq first nil)
14096 (outline-next-heading))
14097 (unless to-heading
14098 (if (memq (preceding-char) '(?\n ?\^M))
14099 (progn
14100 ;; Go to end of line before heading
14101 (forward-char -1)
14102 (if (memq (preceding-char) '(?\n ?\^M))
14103 ;; leave blank line before heading
14104 (forward-char -1))))))
14105 (point))
14107 (defun org-show-subtree ()
14108 "Show everything after this heading at deeper levels."
14109 (outline-flag-region
14110 (point)
14111 (save-excursion
14112 (outline-end-of-subtree) (outline-next-heading) (point))
14113 nil))
14115 (defun org-show-entry ()
14116 "Show the body directly following this heading.
14117 Show the heading too, if it is currently invisible."
14118 (interactive)
14119 (save-excursion
14120 (condition-case nil
14121 (progn
14122 (org-back-to-heading t)
14123 (outline-flag-region
14124 (max (point-min) (1- (point)))
14125 (save-excursion
14126 (re-search-forward
14127 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
14128 (or (match-beginning 1) (point-max)))
14129 nil))
14130 (error nil))))
14132 (defun org-make-options-regexp (kwds)
14133 "Make a regular expression for keyword lines."
14134 (concat
14136 "#?[ \t]*\\+\\("
14137 (mapconcat 'regexp-quote kwds "\\|")
14138 "\\):[ \t]*"
14139 "\\(.+\\)"))
14141 ;; Make isearch reveal the necessary context
14142 (defun org-isearch-end ()
14143 "Reveal context after isearch exits."
14144 (when isearch-success ; only if search was successful
14145 (if (featurep 'xemacs)
14146 ;; Under XEmacs, the hook is run in the correct place,
14147 ;; we directly show the context.
14148 (org-show-context 'isearch)
14149 ;; In Emacs the hook runs *before* restoring the overlays.
14150 ;; So we have to use a one-time post-command-hook to do this.
14151 ;; (Emacs 22 has a special variable, see function `org-mode')
14152 (unless (and (boundp 'isearch-mode-end-hook-quit)
14153 isearch-mode-end-hook-quit)
14154 ;; Only when the isearch was not quitted.
14155 (org-add-hook 'post-command-hook 'org-isearch-post-command
14156 'append 'local)))))
14158 (defun org-isearch-post-command ()
14159 "Remove self from hook, and show context."
14160 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
14161 (org-show-context 'isearch))
14164 ;;;; Integration with and fixes for other packages
14166 ;;; Imenu support
14168 (defvar org-imenu-markers nil
14169 "All markers currently used by Imenu.")
14170 (make-variable-buffer-local 'org-imenu-markers)
14172 (defun org-imenu-new-marker (&optional pos)
14173 "Return a new marker for use by Imenu, and remember the marker."
14174 (let ((m (make-marker)))
14175 (move-marker m (or pos (point)))
14176 (push m org-imenu-markers)
14179 (defun org-imenu-get-tree ()
14180 "Produce the index for Imenu."
14181 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
14182 (setq org-imenu-markers nil)
14183 (let* ((n org-imenu-depth)
14184 (re (concat "^" outline-regexp))
14185 (subs (make-vector (1+ n) nil))
14186 (last-level 0)
14187 m tree level head)
14188 (save-excursion
14189 (save-restriction
14190 (widen)
14191 (goto-char (point-max))
14192 (while (re-search-backward re nil t)
14193 (setq level (org-reduced-level (funcall outline-level)))
14194 (when (<= level n)
14195 (looking-at org-complex-heading-regexp)
14196 (setq head (org-link-display-format
14197 (org-match-string-no-properties 4))
14198 m (org-imenu-new-marker))
14199 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
14200 (if (>= level last-level)
14201 (push (cons head m) (aref subs level))
14202 (push (cons head (aref subs (1+ level))) (aref subs level))
14203 (loop for i from (1+ level) to n do (aset subs i nil)))
14204 (setq last-level level)))))
14205 (aref subs 1)))
14207 (eval-after-load "imenu"
14208 '(progn
14209 (add-hook 'imenu-after-jump-hook
14210 (lambda ()
14211 (if (eq major-mode 'org-mode)
14212 (org-show-context 'org-goto))))))
14214 (defun org-link-display-format (link)
14215 "Replace a link with either the description, or the link target
14216 if no description is present"
14217 (save-match-data
14218 (if (string-match org-bracket-link-analytic-regexp link)
14219 (replace-match (or (match-string 5 link)
14220 (concat (match-string 1 link)
14221 (match-string 3 link)))
14222 nil nil link)
14223 link)))
14225 ;; Speedbar support
14227 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
14228 "Overlay marking the agenda restriction line in speedbar.")
14229 (org-overlay-put org-speedbar-restriction-lock-overlay
14230 'face 'org-agenda-restriction-lock)
14231 (org-overlay-put org-speedbar-restriction-lock-overlay
14232 'help-echo "Agendas are currently limited to this item.")
14233 (org-detach-overlay org-speedbar-restriction-lock-overlay)
14235 (defun org-speedbar-set-agenda-restriction ()
14236 "Restrict future agenda commands to the location at point in speedbar.
14237 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
14238 (interactive)
14239 (require 'org-agenda)
14240 (let (p m tp np dir txt w)
14241 (cond
14242 ((setq p (text-property-any (point-at-bol) (point-at-eol)
14243 'org-imenu t))
14244 (setq m (get-text-property p 'org-imenu-marker))
14245 (save-excursion
14246 (save-restriction
14247 (set-buffer (marker-buffer m))
14248 (goto-char m)
14249 (org-agenda-set-restriction-lock 'subtree))))
14250 ((setq p (text-property-any (point-at-bol) (point-at-eol)
14251 'speedbar-function 'speedbar-find-file))
14252 (setq tp (previous-single-property-change
14253 (1+ p) 'speedbar-function)
14254 np (next-single-property-change
14255 tp 'speedbar-function)
14256 dir (speedbar-line-directory)
14257 txt (buffer-substring-no-properties (or tp (point-min))
14258 (or np (point-max))))
14259 (save-excursion
14260 (save-restriction
14261 (set-buffer (find-file-noselect
14262 (let ((default-directory dir))
14263 (expand-file-name txt))))
14264 (unless (org-mode-p)
14265 (error "Cannot restrict to non-Org-mode file"))
14266 (org-agenda-set-restriction-lock 'file))))
14267 (t (error "Don't know how to restrict Org-mode's agenda")))
14268 (org-move-overlay org-speedbar-restriction-lock-overlay
14269 (point-at-bol) (point-at-eol))
14270 (setq current-prefix-arg nil)
14271 (org-agenda-maybe-redo)))
14273 (eval-after-load "speedbar"
14274 '(progn
14275 (speedbar-add-supported-extension ".org")
14276 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
14277 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
14278 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
14279 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
14280 (add-hook 'speedbar-visiting-tag-hook
14281 (lambda () (org-show-context 'org-goto)))))
14284 ;;; Fixes and Hacks for problems with other packages
14286 ;; Make flyspell not check words in links, to not mess up our keymap
14287 (defun org-mode-flyspell-verify ()
14288 "Don't let flyspell put overlays at active buttons."
14289 (not (get-text-property (point) 'keymap)))
14291 ;; Make `bookmark-jump' show the jump location if it was hidden.
14292 (eval-after-load "bookmark"
14293 '(if (boundp 'bookmark-after-jump-hook)
14294 ;; We can use the hook
14295 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
14296 ;; Hook not available, use advice
14297 (defadvice bookmark-jump (after org-make-visible activate)
14298 "Make the position visible."
14299 (org-bookmark-jump-unhide))))
14301 ;; Make sure saveplace show the location if it was hidden
14302 (eval-after-load "saveplace"
14303 '(defadvice save-place-find-file-hook (after org-make-visible activate)
14304 "Make the position visible."
14305 (org-bookmark-jump-unhide)))
14307 (defun org-bookmark-jump-unhide ()
14308 "Unhide the current position, to show the bookmark location."
14309 (and (org-mode-p)
14310 (or (org-invisible-p)
14311 (save-excursion (goto-char (max (point-min) (1- (point))))
14312 (org-invisible-p)))
14313 (org-show-context 'bookmark-jump)))
14315 ;; Make session.el ignore our circular variable
14316 (eval-after-load "session"
14317 '(add-to-list 'session-globals-exclude 'org-mark-ring))
14319 ;;;; Experimental code
14321 (defun org-closed-in-range ()
14322 "Sparse tree of items closed in a certain time range.
14323 Still experimental, may disappear in the future."
14324 (interactive)
14325 ;; Get the time interval from the user.
14326 (let* ((time1 (time-to-seconds
14327 (org-read-date nil 'to-time nil "Starting date: ")))
14328 (time2 (time-to-seconds
14329 (org-read-date nil 'to-time nil "End date:")))
14330 ;; callback function
14331 (callback (lambda ()
14332 (let ((time
14333 (time-to-seconds
14334 (apply 'encode-time
14335 (org-parse-time-string
14336 (match-string 1))))))
14337 ;; check if time in interval
14338 (and (>= time time1) (<= time time2))))))
14339 ;; make tree, check each match with the callback
14340 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
14343 ;;;; Finish up
14345 (provide 'org)
14347 (run-hooks 'org-load-hook)
14349 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
14351 ;;; org.el ends here