Release 6.12
[org-mode/org-tableheadings.git] / lisp / org.el
blob2be0b3c93701ce4e56a0a7d1101e66e59b8e191f
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.12
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.12"
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. However, do this only if no
641 text after the yank would be swallowed into a folded tree by this action."
642 :group 'org-edit-structure
643 :type 'boolean)
645 (defcustom org-yank-adjusted-subtrees t
646 "Non-nil means, when yanking subtrees, adjust the level.
647 With this setting, `org-paste-subtree' is used to insert the subtree, see
648 this function for details."
649 :group 'org-edit-structure
650 :type 'boolean)
652 (defcustom org-M-RET-may-split-line '((default . t))
653 "Non-nil means, M-RET will split the line at the cursor position.
654 When nil, it will go to the end of the line before making a
655 new line.
656 You may also set this option in a different way for different
657 contexts. Valid contexts are:
659 headline when creating a new headline
660 item when creating a new item
661 table in a table field
662 default the value to be used for all contexts not explicitly
663 customized"
664 :group 'org-structure
665 :group 'org-table
666 :type '(choice
667 (const :tag "Always" t)
668 (const :tag "Never" nil)
669 (repeat :greedy t :tag "Individual contexts"
670 (cons
671 (choice :tag "Context"
672 (const headline)
673 (const item)
674 (const table)
675 (const default))
676 (boolean)))))
679 (defcustom org-insert-heading-respect-content nil
680 "Non-nil means, insert new headings after the current subtree.
681 When nil, the new heading is created directly after the current line.
682 The commands \\[org-insert-heading-respect-content] and
683 \\[org-insert-todo-heading-respect-content] turn this variable on
684 for the duration of the command."
685 :group 'org-structure
686 :type 'boolean)
688 (defcustom org-blank-before-new-entry '((heading . nil)
689 (plain-list-item . nil))
690 "Should `org-insert-heading' leave a blank line before new heading/item?
691 The value is an alist, with `heading' and `plain-list-item' as car,
692 and a boolean flag as cdr."
693 :group 'org-edit-structure
694 :type '(list
695 (cons (const heading) (boolean))
696 (cons (const plain-list-item) (boolean))))
698 (defcustom org-insert-heading-hook nil
699 "Hook being run after inserting a new heading."
700 :group 'org-edit-structure
701 :type 'hook)
703 (defcustom org-enable-fixed-width-editor t
704 "Non-nil means, lines starting with \":\" are treated as fixed-width.
705 This currently only means, they are never auto-wrapped.
706 When nil, such lines will be treated like ordinary lines.
707 See also the QUOTE keyword."
708 :group 'org-edit-structure
709 :type 'boolean)
711 (defcustom org-edit-src-region-extra nil
712 "Additional regexps to identify regions for editing with `org-edit-src-code'.
713 For examples see the function `org-edit-src-find-region-and-lang'.
714 The regular expression identifying the begin marker should end with a newline,
715 and the regexp marking the end line should start with a newline, to make sure
716 there are kept outside the narrowed region."
717 :group 'org-edit-structure
718 :type '(repeat
719 (list
720 (regexp :tag "begin regexp")
721 (regexp :tag "end regexp")
722 (choice :tag "language"
723 (string :tag "specify")
724 (integer :tag "from match group")
725 (const :tag "from `lang' element")
726 (const :tag "from `style' element")))))
728 (defcustom org-edit-fixed-width-region-mode 'artist-mode
729 "The mode that should be used to edit fixed-width regions.
730 These are the regions where each line starts with a colon."
731 :group 'org-edit-structure
732 :type '(choice
733 (const artist-mode)
734 (const picture-mode)
735 (const fundamental-mode)
736 (function :tag "Other (specify)")))
738 (defcustom org-goto-auto-isearch t
739 "Non-nil means, typing characters in org-goto starts incremental search."
740 :group 'org-edit-structure
741 :type 'boolean)
743 (defgroup org-sparse-trees nil
744 "Options concerning sparse trees in Org-mode."
745 :tag "Org Sparse Trees"
746 :group 'org-structure)
748 (defcustom org-highlight-sparse-tree-matches t
749 "Non-nil means, highlight all matches that define a sparse tree.
750 The highlights will automatically disappear the next time the buffer is
751 changed by an edit command."
752 :group 'org-sparse-trees
753 :type 'boolean)
755 (defcustom org-remove-highlights-with-change t
756 "Non-nil means, any change to the buffer will remove temporary highlights.
757 Such highlights are created by `org-occur' and `org-clock-display'.
758 When nil, `C-c C-c needs to be used to get rid of the highlights.
759 The highlights created by `org-preview-latex-fragment' always need
760 `C-c C-c' to be removed."
761 :group 'org-sparse-trees
762 :group 'org-time
763 :type 'boolean)
766 (defcustom org-occur-hook '(org-first-headline-recenter)
767 "Hook that is run after `org-occur' has constructed a sparse tree.
768 This can be used to recenter the window to show as much of the structure
769 as possible."
770 :group 'org-sparse-trees
771 :type 'hook)
773 (defgroup org-imenu-and-speedbar nil
774 "Options concerning imenu and speedbar in Org-mode."
775 :tag "Org Imenu and Speedbar"
776 :group 'org-structure)
778 (defcustom org-imenu-depth 2
779 "The maximum level for Imenu access to Org-mode headlines.
780 This also applied for speedbar access."
781 :group 'org-imenu-and-speedbar
782 :type 'number)
784 (defgroup org-table nil
785 "Options concerning tables in Org-mode."
786 :tag "Org Table"
787 :group 'org)
789 (defcustom org-enable-table-editor 'optimized
790 "Non-nil means, lines starting with \"|\" are handled by the table editor.
791 When nil, such lines will be treated like ordinary lines.
793 When equal to the symbol `optimized', the table editor will be optimized to
794 do the following:
795 - Automatic overwrite mode in front of whitespace in table fields.
796 This makes the structure of the table stay in tact as long as the edited
797 field does not exceed the column width.
798 - Minimize the number of realigns. Normally, the table is aligned each time
799 TAB or RET are pressed to move to another field. With optimization this
800 happens only if changes to a field might have changed the column width.
801 Optimization requires replacing the functions `self-insert-command',
802 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
803 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
804 very good at guessing when a re-align will be necessary, but you can always
805 force one with \\[org-ctrl-c-ctrl-c].
807 If you would like to use the optimized version in Org-mode, but the
808 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
810 This variable can be used to turn on and off the table editor during a session,
811 but in order to toggle optimization, a restart is required.
813 See also the variable `org-table-auto-blank-field'."
814 :group 'org-table
815 :type '(choice
816 (const :tag "off" nil)
817 (const :tag "on" t)
818 (const :tag "on, optimized" optimized)))
820 (defcustom org-table-tab-recognizes-table.el t
821 "Non-nil means, TAB will automatically notice a table.el table.
822 When it sees such a table, it moves point into it and - if necessary -
823 calls `table-recognize-table'."
824 :group 'org-table-editing
825 :type 'boolean)
827 (defgroup org-link nil
828 "Options concerning links in Org-mode."
829 :tag "Org Link"
830 :group 'org)
832 (defvar org-link-abbrev-alist-local nil
833 "Buffer-local version of `org-link-abbrev-alist', which see.
834 The value of this is taken from the #+LINK lines.")
835 (make-variable-buffer-local 'org-link-abbrev-alist-local)
837 (defcustom org-link-abbrev-alist nil
838 "Alist of link abbreviations.
839 The car of each element is a string, to be replaced at the start of a link.
840 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
841 links in Org-mode buffers can have an optional tag after a double colon, e.g.
843 [[linkkey:tag][description]]
845 If REPLACE is a string, the tag will simply be appended to create the link.
846 If the string contains \"%s\", the tag will be inserted there.
848 REPLACE may also be a function that will be called with the tag as the
849 only argument to create the link, which should be returned as a string.
851 See the manual for examples."
852 :group 'org-link
853 :type '(repeat
854 (cons
855 (string :tag "Protocol")
856 (choice
857 (string :tag "Format")
858 (function)))))
860 (defcustom org-descriptive-links t
861 "Non-nil means, hide link part and only show description of bracket links.
862 Bracket links are like [[link][descritpion]]. This variable sets the initial
863 state in new org-mode buffers. The setting can then be toggled on a
864 per-buffer basis from the Org->Hyperlinks menu."
865 :group 'org-link
866 :type 'boolean)
868 (defcustom org-link-file-path-type 'adaptive
869 "How the path name in file links should be stored.
870 Valid values are:
872 relative Relative to the current directory, i.e. the directory of the file
873 into which the link is being inserted.
874 absolute Absolute path, if possible with ~ for home directory.
875 noabbrev Absolute path, no abbreviation of home directory.
876 adaptive Use relative path for files in the current directory and sub-
877 directories of it. For other files, use an absolute path."
878 :group 'org-link
879 :type '(choice
880 (const relative)
881 (const absolute)
882 (const noabbrev)
883 (const adaptive)))
885 (defcustom org-activate-links '(bracket angle plain radio tag date)
886 "Types of links that should be activated in Org-mode files.
887 This is a list of symbols, each leading to the activation of a certain link
888 type. In principle, it does not hurt to turn on most link types - there may
889 be a small gain when turning off unused link types. The types are:
891 bracket The recommended [[link][description]] or [[link]] links with hiding.
892 angular Links in angular brackes that may contain whitespace like
893 <bbdb:Carsten Dominik>.
894 plain Plain links in normal text, no whitespace, like http://google.com.
895 radio Text that is matched by a radio target, see manual for details.
896 tag Tag settings in a headline (link to tag search).
897 date Time stamps (link to calendar).
899 Changing this variable requires a restart of Emacs to become effective."
900 :group 'org-link
901 :type '(set (const :tag "Double bracket links (new style)" bracket)
902 (const :tag "Angular bracket links (old style)" angular)
903 (const :tag "Plain text links" plain)
904 (const :tag "Radio target matches" radio)
905 (const :tag "Tags" tag)
906 (const :tag "Timestamps" date)))
908 (defcustom org-make-link-description-function nil
909 "Function to use to generate link descriptions from links. If
910 nil the link location will be used. This function must take two
911 parameters; the first is the link and the second the description
912 org-insert-link has generated, and should return the description
913 to use."
914 :group 'org-link
915 :type 'function)
917 (defgroup org-link-store nil
918 "Options concerning storing links in Org-mode."
919 :tag "Org Store Link"
920 :group 'org-link)
922 (defcustom org-email-link-description-format "Email %c: %.30s"
923 "Format of the description part of a link to an email or usenet message.
924 The following %-excapes will be replaced by corresponding information:
926 %F full \"From\" field
927 %f name, taken from \"From\" field, address if no name
928 %T full \"To\" field
929 %t first name in \"To\" field, address if no name
930 %c correspondent. Unually \"from NAME\", but if you sent it yourself, it
931 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
932 %s subject
933 %m message-id.
935 You may use normal field width specification between the % and the letter.
936 This is for example useful to limit the length of the subject.
938 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
939 :group 'org-link-store
940 :type 'string)
942 (defcustom org-from-is-user-regexp
943 (let (r1 r2)
944 (when (and user-mail-address (not (string= user-mail-address "")))
945 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
946 (when (and user-full-name (not (string= user-full-name "")))
947 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
948 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
949 "Regexp mached against the \"From:\" header of an email or usenet message.
950 It should match if the message is from the user him/herself."
951 :group 'org-link-store
952 :type 'regexp)
954 (defcustom org-context-in-file-links t
955 "Non-nil means, file links from `org-store-link' contain context.
956 A search string will be added to the file name with :: as separator and
957 used to find the context when the link is activated by the command
958 `org-open-at-point'.
959 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
960 negates this setting for the duration of the command."
961 :group 'org-link-store
962 :type 'boolean)
964 (defcustom org-keep-stored-link-after-insertion nil
965 "Non-nil means, keep link in list for entire session.
967 The command `org-store-link' adds a link pointing to the current
968 location to an internal list. These links accumulate during a session.
969 The command `org-insert-link' can be used to insert links into any
970 Org-mode file (offering completion for all stored links). When this
971 option is nil, every link which has been inserted once using \\[org-insert-link]
972 will be removed from the list, to make completing the unused links
973 more efficient."
974 :group 'org-link-store
975 :type 'boolean)
977 (defgroup org-link-follow nil
978 "Options concerning following links in Org-mode."
979 :tag "Org Follow Link"
980 :group 'org-link)
982 (defcustom org-follow-link-hook nil
983 "Hook that is run after a link has been followed."
984 :group 'org-link-follow
985 :type 'hook)
987 (defcustom org-tab-follows-link nil
988 "Non-nil means, on links TAB 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-return-follows-link nil
994 "Non-nil means, on links RET will follow the link.
995 Needs to be set before org.el is loaded."
996 :group 'org-link-follow
997 :type 'boolean)
999 (defcustom org-mouse-1-follows-link
1000 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1001 "Non-nil means, mouse-1 on a link will follow the link.
1002 A longer mouse click will still set point. Does not work on XEmacs.
1003 Needs to be set before org.el is loaded."
1004 :group 'org-link-follow
1005 :type 'boolean)
1007 (defcustom org-mark-ring-length 4
1008 "Number of different positions to be recorded in the ring
1009 Changing this requires a restart of Emacs to work correctly."
1010 :group 'org-link-follow
1011 :type 'interger)
1013 (defcustom org-link-frame-setup
1014 '((vm . vm-visit-folder-other-frame)
1015 (gnus . gnus-other-frame)
1016 (file . find-file-other-window))
1017 "Setup the frame configuration for following links.
1018 When following a link with Emacs, it may often be useful to display
1019 this link in another window or frame. This variable can be used to
1020 set this up for the different types of links.
1021 For VM, use any of
1022 `vm-visit-folder'
1023 `vm-visit-folder-other-frame'
1024 For Gnus, use any of
1025 `gnus'
1026 `gnus-other-frame'
1027 `org-gnus-no-new-news'
1028 For FILE, use any of
1029 `find-file'
1030 `find-file-other-window'
1031 `find-file-other-frame'
1032 For the calendar, use the variable `calendar-setup'.
1033 For BBDB, it is currently only possible to display the matches in
1034 another window."
1035 :group 'org-link-follow
1036 :type '(list
1037 (cons (const vm)
1038 (choice
1039 (const vm-visit-folder)
1040 (const vm-visit-folder-other-window)
1041 (const vm-visit-folder-other-frame)))
1042 (cons (const gnus)
1043 (choice
1044 (const gnus)
1045 (const gnus-other-frame)
1046 (const org-gnus-no-new-news)))
1047 (cons (const file)
1048 (choice
1049 (const find-file)
1050 (const find-file-other-window)
1051 (const find-file-other-frame)))))
1053 (defcustom org-display-internal-link-with-indirect-buffer nil
1054 "Non-nil means, use indirect buffer to display infile links.
1055 Activating internal links (from one location in a file to another location
1056 in the same file) normally just jumps to the location. When the link is
1057 activated with a C-u prefix (or with mouse-3), the link is displayed in
1058 another window. When this option is set, the other window actually displays
1059 an indirect buffer clone of the current buffer, to avoid any visibility
1060 changes to the current buffer."
1061 :group 'org-link-follow
1062 :type 'boolean)
1064 (defcustom org-open-non-existing-files nil
1065 "Non-nil means, `org-open-file' will open non-existing files.
1066 When nil, an error will be generated."
1067 :group 'org-link-follow
1068 :type 'boolean)
1070 (defcustom org-open-directory-means-index-dot-org nil
1071 "Non-nil means, a link to a directory really means to index.org.
1072 When nil, following a directory link will run dired or open a finder/explorer
1073 window on that directory."
1074 :group 'org-link-follow
1075 :type 'boolean)
1077 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1078 "Function and arguments to call for following mailto links.
1079 This is a list with the first element being a lisp function, and the
1080 remaining elements being arguments to the function. In string arguments,
1081 %a will be replaced by the address, and %s will be replaced by the subject
1082 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1083 :group 'org-link-follow
1084 :type '(choice
1085 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1086 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1087 (const :tag "message-mail" (message-mail "%a" "%s"))
1088 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1090 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1091 "Non-nil means, ask for confirmation before executing shell links.
1092 Shell links can be dangerous: just think about a link
1094 [[shell:rm -rf ~/*][Google Search]]
1096 This link would show up in your Org-mode document as \"Google Search\",
1097 but really it would remove your entire home directory.
1098 Therefore we advise against setting this variable to nil.
1099 Just change it to `y-or-n-p' of you want to confirm with a
1100 single keystroke rather than having to type \"yes\"."
1101 :group 'org-link-follow
1102 :type '(choice
1103 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1104 (const :tag "with y-or-n (faster)" y-or-n-p)
1105 (const :tag "no confirmation (dangerous)" nil)))
1107 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1108 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1109 Elisp links can be dangerous: just think about a link
1111 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1113 This link would show up in your Org-mode document as \"Google Search\",
1114 but really it would remove your entire home directory.
1115 Therefore we advise against setting this variable to nil.
1116 Just change it to `y-or-n-p' of you want to confirm with a
1117 single keystroke rather than having to type \"yes\"."
1118 :group 'org-link-follow
1119 :type '(choice
1120 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1121 (const :tag "with y-or-n (faster)" y-or-n-p)
1122 (const :tag "no confirmation (dangerous)" nil)))
1124 (defconst org-file-apps-defaults-gnu
1125 '((remote . emacs)
1126 (system . mailcap)
1127 (t . mailcap))
1128 "Default file applications on a UNIX or GNU/Linux system.
1129 See `org-file-apps'.")
1131 (defconst org-file-apps-defaults-macosx
1132 '((remote . emacs)
1133 (t . "open %s")
1134 (system . "open %s")
1135 ("ps.gz" . "gv %s")
1136 ("eps.gz" . "gv %s")
1137 ("dvi" . "xdvi %s")
1138 ("fig" . "xfig %s"))
1139 "Default file applications on a MacOS X system.
1140 The system \"open\" is known as a default, but we use X11 applications
1141 for some files for which the OS does not have a good default.
1142 See `org-file-apps'.")
1144 (defconst org-file-apps-defaults-windowsnt
1145 (list
1146 '(remote . emacs)
1147 (cons t
1148 (list (if (featurep 'xemacs)
1149 'mswindows-shell-execute
1150 'w32-shell-execute)
1151 "open" 'file))
1152 (cons 'system
1153 (list (if (featurep 'xemacs)
1154 'mswindows-shell-execute
1155 'w32-shell-execute)
1156 "open" 'file)))
1157 "Default file applications on a Windows NT system.
1158 The system \"open\" is used for most files.
1159 See `org-file-apps'.")
1161 (defcustom org-file-apps
1163 (auto-mode . emacs)
1164 ("\\.x?html?\\'" . default)
1165 ("\\.pdf\\'" . default)
1167 "External applications for opening `file:path' items in a document.
1168 Org-mode uses system defaults for different file types, but
1169 you can use this variable to set the application for a given file
1170 extension. The entries in this list are cons cells where the car identifies
1171 files and the cdr the corresponding command. Possible values for the
1172 file identifier are
1173 \"regex\" Regular expression matched against the file name. For backward
1174 compatibility, this can also be a string with only alphanumeric
1175 characters, which is then interpreted as an extension.
1176 `directory' Matches a directory
1177 `remote' Matches a remote file, accessible through tramp or efs.
1178 Remote files most likely should be visited through Emacs
1179 because external applications cannot handle such paths.
1180 `auto-mode' Matches files that are mached by any entry in `auto-mode-alist',
1181 so all files Emacs knows how to handle. Using this with
1182 command `emacs' will open most files in Emacs. Beware that this
1183 will also open html files insite Emacs, unless you add
1184 (\"html\" . default) to the list as well.
1185 t Default for files not matched by any of the other options.
1186 `system' The system command to open files, like `open' on Windows
1187 and Mac OS X, and mailcap under GNU/Linux. This is the command
1188 that will be selected if you call `C-c C-o' with a double
1189 `C-u C-u' prefix.
1191 Possible values for the command are:
1192 `emacs' The file will be visited by the current Emacs process.
1193 `default' Use the default application for this file type, which is the
1194 association for t in the list, most likely in the system-specific
1195 part.
1196 This can be used to overrule an unwanted seting in the
1197 system-specific variable.
1198 `system' Use the system command for opening files, like \"open\".
1199 This command is specified by the entry whose car is `system'.
1200 Most likely, the system-specific version of this variable
1201 does define this command, but you can overrule/replace it
1202 here.
1203 string A command to be executed by a shell; %s will be replaced
1204 by the path to the file.
1205 sexp A Lisp form which will be evaluated. The file path will
1206 be available in the Lisp variable `file'.
1207 For more examples, see the system specific constants
1208 `org-file-apps-defaults-macosx'
1209 `org-file-apps-defaults-windowsnt'
1210 `org-file-apps-defaults-gnu'."
1211 :group 'org-link-follow
1212 :type '(repeat
1213 (cons (choice :value ""
1214 (string :tag "Extension")
1215 (const :tag "System command to open files" system)
1216 (const :tag "Default for unrecognized files" t)
1217 (const :tag "Remote file" remote)
1218 (const :tag "Links to a directory" directory)
1219 (const :tag "Any files that have Emacs modes"
1220 auto-mode))
1221 (choice :value ""
1222 (const :tag "Visit with Emacs" emacs)
1223 (const :tag "Use default" default)
1224 (const :tag "Use the system command" system)
1225 (string :tag "Command")
1226 (sexp :tag "Lisp form")))))
1228 (defgroup org-refile nil
1229 "Options concerning refiling entries in Org-mode."
1230 :tag "Org Remember"
1231 :group 'org)
1233 (defcustom org-directory "~/org"
1234 "Directory with org files.
1235 This directory will be used as default to prompt for org files.
1236 Used by the hooks for remember.el."
1237 :group 'org-refile
1238 :group 'org-remember
1239 :type 'directory)
1241 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1242 "Default target for storing notes.
1243 Used by the hooks for remember.el. This can be a string, or nil to mean
1244 the value of `remember-data-file'.
1245 You can set this on a per-template basis with the variable
1246 `org-remember-templates'."
1247 :group 'org-refile
1248 :group 'org-remember
1249 :type '(choice
1250 (const :tag "Default from remember-data-file" nil)
1251 file))
1253 (defcustom org-goto-interface 'outline
1254 "The default interface to be used for `org-goto'.
1255 Allowed vaues are:
1256 outline The interface shows an outline of the relevant file
1257 and the correct heading is found by moving through
1258 the outline or by searching with incremental search.
1259 outline-path-completion Headlines in the current buffer are offered via
1260 completion."
1261 :group 'org-refile
1262 :type '(choice
1263 (const :tag "Outline" outline)
1264 (const :tag "Outline-path-completion" outline-path-completion)))
1266 (defcustom org-reverse-note-order nil
1267 "Non-nil means, store new notes at the beginning of a file or entry.
1268 When nil, new notes will be filed to the end of a file or entry.
1269 This can also be a list with cons cells of regular expressions that
1270 are matched against file names, and values."
1271 :group 'org-remember
1272 :type '(choice
1273 (const :tag "Reverse always" t)
1274 (const :tag "Reverse never" nil)
1275 (repeat :tag "By file name regexp"
1276 (cons regexp boolean))))
1278 (defcustom org-refile-targets nil
1279 "Targets for refiling entries with \\[org-refile].
1280 This is list of cons cells. Each cell contains:
1281 - a specification of the files to be considered, either a list of files,
1282 or a symbol whose function or variable value will be used to retrieve
1283 a file name or a list of file names. Nil means, refile to a different
1284 heading in the current buffer.
1285 - A specification of how to find candidate refile targets. This may be
1286 any of
1287 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1288 This tag has to be present in all target headlines, inheritance will
1289 not be considered.
1290 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1291 todo keyword.
1292 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1293 headlines that are refiling targets.
1294 - a cons cell (:level . N). Any headline of level N is considered a target.
1295 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1297 When this variable is nil, all top-level headlines in the current buffer
1298 are used, equivalent to the value `((nil . (:level . 1))'."
1299 :group 'org-remember
1300 :type '(repeat
1301 (cons
1302 (choice :value org-agenda-files
1303 (const :tag "All agenda files" org-agenda-files)
1304 (const :tag "Current buffer" nil)
1305 (function) (variable) (file))
1306 (choice :tag "Identify target headline by"
1307 (cons :tag "Specific tag" (const :tag) (string))
1308 (cons :tag "TODO keyword" (const :todo) (string))
1309 (cons :tag "Regular expression" (const :regexp) (regexp))
1310 (cons :tag "Level number" (const :level) (integer))
1311 (cons :tag "Max Level number" (const :maxlevel) (integer))))))
1313 (defcustom org-refile-use-outline-path nil
1314 "Non-nil means, provide refile targets as paths.
1315 So a level 3 headline will be available as level1/level2/level3.
1316 When the value is `file', also include the file name (without directory)
1317 into the path. When `full-file-path', include the full file path."
1318 :group 'org-remember
1319 :type '(choice
1320 (const :tag "Not" nil)
1321 (const :tag "Yes" t)
1322 (const :tag "Start with file name" file)
1323 (const :tag "Start with full file path" full-file-path)))
1325 (defgroup org-todo nil
1326 "Options concerning TODO items in Org-mode."
1327 :tag "Org TODO"
1328 :group 'org)
1330 (defgroup org-progress nil
1331 "Options concerning Progress logging in Org-mode."
1332 :tag "Org Progress"
1333 :group 'org-time)
1335 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1336 "List of TODO entry keyword sequences and their interpretation.
1337 \\<org-mode-map>This is a list of sequences.
1339 Each sequence starts with a symbol, either `sequence' or `type',
1340 indicating if the keywords should be interpreted as a sequence of
1341 action steps, or as different types of TODO items. The first
1342 keywords are states requiring action - these states will select a headline
1343 for inclusion into the global TODO list Org-mode produces. If one of
1344 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1345 signify that no further action is necessary. If \"|\" is not found,
1346 the last keyword is treated as the only DONE state of the sequence.
1348 The command \\[org-todo] cycles an entry through these states, and one
1349 additional state where no keyword is present. For details about this
1350 cycling, see the manual.
1352 TODO keywords and interpretation can also be set on a per-file basis with
1353 the special #+SEQ_TODO and #+TYP_TODO lines.
1355 Each keyword can optionally specify a character for fast state selection
1356 \(in combination with the variable `org-use-fast-todo-selection')
1357 and specifiers for state change logging, using the same syntax
1358 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1359 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1360 indicates to record a time stamp each time this state is selected.
1362 Each keyword may also specify if a timestamp or a note should be
1363 recorded when entering or leaving the state, by adding additional
1364 characters in the parenthesis after the keyword. This looks like this:
1365 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1366 record only the time of the state change. With X and Y being either
1367 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1368 Y when leaving the state if and only if the *target* state does not
1369 define X. You may omit any of the fast-selection key or X or /Y,
1370 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1372 For backward compatibility, this variable may also be just a list
1373 of keywords - in this case the interptetation (sequence or type) will be
1374 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1375 :group 'org-todo
1376 :group 'org-keywords
1377 :type '(choice
1378 (repeat :tag "Old syntax, just keywords"
1379 (string :tag "Keyword"))
1380 (repeat :tag "New syntax"
1381 (cons
1382 (choice
1383 :tag "Interpretation"
1384 (const :tag "Sequence (cycling hits every state)" sequence)
1385 (const :tag "Type (cycling directly to DONE)" type))
1386 (repeat
1387 (string :tag "Keyword"))))))
1389 (defvar org-todo-keywords-1 nil
1390 "All TODO and DONE keywords active in a buffer.")
1391 (make-variable-buffer-local 'org-todo-keywords-1)
1392 (defvar org-todo-keywords-for-agenda nil)
1393 (defvar org-done-keywords-for-agenda nil)
1394 (defvar org-todo-keyword-alist-for-agenda nil)
1395 (defvar org-tag-alist-for-agenda nil)
1396 (defvar org-agenda-contributing-files nil)
1397 (defvar org-not-done-keywords nil)
1398 (make-variable-buffer-local 'org-not-done-keywords)
1399 (defvar org-done-keywords nil)
1400 (make-variable-buffer-local 'org-done-keywords)
1401 (defvar org-todo-heads nil)
1402 (make-variable-buffer-local 'org-todo-heads)
1403 (defvar org-todo-sets nil)
1404 (make-variable-buffer-local 'org-todo-sets)
1405 (defvar org-todo-log-states nil)
1406 (make-variable-buffer-local 'org-todo-log-states)
1407 (defvar org-todo-kwd-alist nil)
1408 (make-variable-buffer-local 'org-todo-kwd-alist)
1409 (defvar org-todo-key-alist nil)
1410 (make-variable-buffer-local 'org-todo-key-alist)
1411 (defvar org-todo-key-trigger nil)
1412 (make-variable-buffer-local 'org-todo-key-trigger)
1414 (defcustom org-todo-interpretation 'sequence
1415 "Controls how TODO keywords are interpreted.
1416 This variable is in principle obsolete and is only used for
1417 backward compatibility, if the interpretation of todo keywords is
1418 not given already in `org-todo-keywords'. See that variable for
1419 more information."
1420 :group 'org-todo
1421 :group 'org-keywords
1422 :type '(choice (const sequence)
1423 (const type)))
1425 (defcustom org-use-fast-todo-selection 'prefix
1426 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1427 This variable describes if and under what circumstances the cycling
1428 mechanism for TODO keywords will be replaced by a single-key, direct
1429 selection scheme.
1431 When nil, fast selection is never used.
1433 When the symbol `prefix', it will be used when `org-todo' is called with
1434 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1435 in an agenda buffer.
1437 When t, fast selection is used by default. In this case, the prefix
1438 argument forces cycling instead.
1440 In all cases, the special interface is only used if access keys have actually
1441 been assigned by the user, i.e. if keywords in the configuration are followed
1442 by a letter in parenthesis, like TODO(t)."
1443 :group 'org-todo
1444 :type '(choice
1445 (const :tag "Never" nil)
1446 (const :tag "By default" t)
1447 (const :tag "Only with C-u C-c C-t" prefix)))
1449 (defcustom org-provide-todo-statistics t
1450 "Non-nil means, update todo statistics after insert and toggle.
1451 When this is set, todo statistics is updated in the parent of the current
1452 entry each time a todo state is changed."
1453 :group 'org-todo
1454 :type 'boolean)
1456 (defcustom org-after-todo-state-change-hook nil
1457 "Hook which is run after the state of a TODO item was changed.
1458 The new state (a string with a TODO keyword, or nil) is available in the
1459 Lisp variable `state'."
1460 :group 'org-todo
1461 :type 'hook)
1463 (defcustom org-todo-state-tags-triggers nil
1464 "Tag changes that should be triggered by TODO state changes.
1465 This is a list. Each entry is
1467 (state-change (tag . flag) .......)
1469 State-change can be a string with a state, and empty string to indicate the
1470 state that has no TODO keyword, or it can be one of the symbols `todo'
1471 or `done', meaning any not-done or done state, respectively."
1472 :group 'org-todo
1473 :group 'org-tags
1474 :type '(repeat
1475 (cons (choice :tag "When changing to"
1476 (const :tag "Not-done state" todo)
1477 (const :tag "Done state" done)
1478 (string :tag "State"))
1479 (repeat
1480 (cons :tag "Tag action"
1481 (string :tag "Tag")
1482 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1484 (defcustom org-log-done nil
1485 "Non-nil means, record a CLOSED timestamp when moving an entry to DONE.
1486 When equal to the list (done), also prompt for a closing note.
1487 This can also be configured on a per-file basis by adding one of
1488 the following lines anywhere in the buffer:
1490 #+STARTUP: logdone
1491 #+STARTUP: lognotedone
1492 #+STARTUP: nologdone"
1493 :group 'org-todo
1494 :group 'org-progress
1495 :type '(choice
1496 (const :tag "No logging" nil)
1497 (const :tag "Record CLOSED timestamp" time)
1498 (const :tag "Record CLOSED timestamp with closing note." note)))
1500 ;; Normalize old uses of org-log-done.
1501 (cond
1502 ((eq org-log-done t) (setq org-log-done 'time))
1503 ((and (listp org-log-done) (memq 'done org-log-done))
1504 (setq org-log-done 'note)))
1506 (defcustom org-log-note-clock-out nil
1507 "Non-nil means, record a note when clocking out of an item.
1508 This can also be configured on a per-file basis by adding one of
1509 the following lines anywhere in the buffer:
1511 #+STARTUP: lognoteclock-out
1512 #+STARTUP: nolognoteclock-out"
1513 :group 'org-todo
1514 :group 'org-progress
1515 :type 'boolean)
1517 (defcustom org-log-done-with-time t
1518 "Non-nil means, the CLOSED time stamp will contain date and time.
1519 When nil, only the date will be recorded."
1520 :group 'org-progress
1521 :type 'boolean)
1523 (defcustom org-log-note-headings
1524 '((done . "CLOSING NOTE %t")
1525 (state . "State %-12s %t")
1526 (note . "Note taken on %t")
1527 (clock-out . ""))
1528 "Headings for notes added to entries.
1529 The value is an alist, with the car being a symbol indicating the note
1530 context, and the cdr is the heading to be used. The heading may also be the
1531 empty string.
1532 %t in the heading will be replaced by a time stamp.
1533 %s will be replaced by the new TODO state, in double quotes.
1534 %u will be replaced by the user name.
1535 %U will be replaced by the full user name."
1536 :group 'org-todo
1537 :group 'org-progress
1538 :type '(list :greedy t
1539 (cons (const :tag "Heading when closing an item" done) string)
1540 (cons (const :tag
1541 "Heading when changing todo state (todo sequence only)"
1542 state) string)
1543 (cons (const :tag "Heading when just taking a note" note) string)
1544 (cons (const :tag "Heading when clocking out" clock-out) string)))
1546 (unless (assq 'note org-log-note-headings)
1547 (push '(note . "%t") org-log-note-headings))
1549 (defcustom org-log-state-notes-insert-after-drawers nil
1550 "Non-nil means, insert state change notes after any drawers in entry.
1551 Only the drawers that *immediately* follow the headline and the
1552 deadline/scheduled line are skipped.
1553 When nil, insert notes right after the heading and perhaps the line
1554 with deadline/scheduling if present."
1555 :group 'org-todo
1556 :group 'org-progress
1557 :type 'boolean)
1559 (defcustom org-log-states-order-reversed t
1560 "Non-nil means, the latest state change note will be directly after heading.
1561 When nil, the notes will be orderer according to time."
1562 :group 'org-todo
1563 :group 'org-progress
1564 :type 'boolean)
1566 (defcustom org-log-repeat 'time
1567 "Non-nil means, record moving through the DONE state when triggering repeat.
1568 An auto-repeating tasks is immediately switched back to TODO when marked
1569 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1570 the TODO keyword definition, or recording a closing note by setting
1571 `org-log-done', there will be no record of the task moving through DONE.
1572 This variable forces taking a note anyway. Possible values are:
1574 nil Don't force a record
1575 time Record a time stamp
1576 note Record a note
1578 This option can also be set with on a per-file-basis with
1580 #+STARTUP: logrepeat
1581 #+STARTUP: lognoterepeat
1582 #+STARTUP: nologrepeat
1584 You can have local logging settings for a subtree by setting the LOGGING
1585 property to one or more of these keywords."
1586 :group 'org-todo
1587 :group 'org-progress
1588 :type '(choice
1589 (const :tag "Don't force a record" nil)
1590 (const :tag "Force recording the DONE state" time)
1591 (const :tag "Force recording a note with the DONE state" note)))
1594 (defgroup org-priorities nil
1595 "Priorities in Org-mode."
1596 :tag "Org Priorities"
1597 :group 'org-todo)
1599 (defcustom org-highest-priority ?A
1600 "The highest priority of TODO items. A character like ?A, ?B etc.
1601 Must have a smaller ASCII number than `org-lowest-priority'."
1602 :group 'org-priorities
1603 :type 'character)
1605 (defcustom org-lowest-priority ?C
1606 "The lowest priority of TODO items. A character like ?A, ?B etc.
1607 Must have a larger ASCII number than `org-highest-priority'."
1608 :group 'org-priorities
1609 :type 'character)
1611 (defcustom org-default-priority ?B
1612 "The default priority of TODO items.
1613 This is the priority an item get if no explicit priority is given."
1614 :group 'org-priorities
1615 :type 'character)
1617 (defcustom org-priority-start-cycle-with-default t
1618 "Non-nil means, start with default priority when starting to cycle.
1619 When this is nil, the first step in the cycle will be (depending on the
1620 command used) one higher or lower that the default priority."
1621 :group 'org-priorities
1622 :type 'boolean)
1624 (defgroup org-time nil
1625 "Options concerning time stamps and deadlines in Org-mode."
1626 :tag "Org Time"
1627 :group 'org)
1629 (defcustom org-insert-labeled-timestamps-at-point nil
1630 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1631 When nil, these labeled time stamps are forces into the second line of an
1632 entry, just after the headline. When scheduling from the global TODO list,
1633 the time stamp will always be forced into the second line."
1634 :group 'org-time
1635 :type 'boolean)
1637 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1638 "Formats for `format-time-string' which are used for time stamps.
1639 It is not recommended to change this constant.")
1641 (defcustom org-time-stamp-rounding-minutes '(0 5)
1642 "Number of minutes to round time stamps to.
1643 These are two values, the first applies when first creating a time stamp.
1644 The second applies when changing it with the commands `S-up' and `S-down'.
1645 When changing the time stamp, this means that it will change in steps
1646 of N minutes, as given by the second value.
1648 When a setting is 0 or 1, insert the time unmodified. Useful rounding
1649 numbers should be factors of 60, so for example 5, 10, 15.
1651 When this is larger than 1, you can still force an exact time-stamp by using
1652 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
1653 and by using a prefix arg to `S-up/down' to specify the exact number
1654 of minutes to shift."
1655 :group 'org-time
1656 :get '(lambda (var) ; Make sure all entries have 5 elements
1657 (if (integerp (default-value var))
1658 (list (default-value var) 5)
1659 (default-value var)))
1660 :type '(list
1661 (integer :tag "when inserting times")
1662 (integer :tag "when modifying times")))
1664 ;; Normalize old customizations of this variable.
1665 (when (integerp org-time-stamp-rounding-minutes)
1666 (setq org-time-stamp-rounding-minutes
1667 (list org-time-stamp-rounding-minutes
1668 org-time-stamp-rounding-minutes)))
1670 (defcustom org-display-custom-times nil
1671 "Non-nil means, overlay custom formats over all time stamps.
1672 The formats are defined through the variable `org-time-stamp-custom-formats'.
1673 To turn this on on a per-file basis, insert anywhere in the file:
1674 #+STARTUP: customtime"
1675 :group 'org-time
1676 :set 'set-default
1677 :type 'sexp)
1678 (make-variable-buffer-local 'org-display-custom-times)
1680 (defcustom org-time-stamp-custom-formats
1681 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1682 "Custom formats for time stamps. See `format-time-string' for the syntax.
1683 These are overlayed over the default ISO format if the variable
1684 `org-display-custom-times' is set. Time like %H:%M should be at the
1685 end of the second format."
1686 :group 'org-time
1687 :type 'sexp)
1689 (defun org-time-stamp-format (&optional long inactive)
1690 "Get the right format for a time string."
1691 (let ((f (if long (cdr org-time-stamp-formats)
1692 (car org-time-stamp-formats))))
1693 (if inactive
1694 (concat "[" (substring f 1 -1) "]")
1695 f)))
1697 (defcustom org-time-clocksum-format "%d:%02d"
1698 "The format string used when creating CLOCKSUM lines, or when
1699 org-mode generates a time duration."
1700 :group 'org-time
1701 :type 'string)
1703 (defcustom org-deadline-warning-days 14
1704 "No. of days before expiration during which a deadline becomes active.
1705 This variable governs the display in sparse trees and in the agenda.
1706 When 0 or negative, it means use this number (the absolute value of it)
1707 even if a deadline has a different individual lead time specified."
1708 :group 'org-time
1709 :group 'org-agenda-daily/weekly
1710 :type 'number)
1712 (defcustom org-read-date-prefer-future t
1713 "Non-nil means, assume future for incomplete date input from user.
1714 This affects the following situations:
1715 1. The user gives a day, but no month.
1716 For example, if today is the 15th, and you enter \"3\", Org-mode will
1717 read this as the third of *next* month. However, if you enter \"17\",
1718 it will be considered as *this* month.
1719 2. The user gives a month but not a year.
1720 For example, if it is april and you enter \"feb 2\", this will be read
1721 as feb 2, *next* year. \"May 5\", however, will be this year.
1723 Currently this does not work for ISO week specifications.
1725 When this option is nil, the current month and year will always be used
1726 as defaults."
1727 :group 'org-time
1728 :type 'boolean)
1730 (defcustom org-read-date-display-live t
1731 "Non-nil means, display current interpretation of date prompt live.
1732 This display will be in an overlay, in the minibuffer."
1733 :group 'org-time
1734 :type 'boolean)
1736 (defcustom org-read-date-popup-calendar t
1737 "Non-nil means, pop up a calendar when prompting for a date.
1738 In the calendar, the date can be selected with mouse-1. However, the
1739 minibuffer will also be active, and you can simply enter the date as well.
1740 When nil, only the minibuffer will be available."
1741 :group 'org-time
1742 :type 'boolean)
1743 (if (fboundp 'defvaralias)
1744 (defvaralias 'org-popup-calendar-for-date-prompt
1745 'org-read-date-popup-calendar))
1747 (defcustom org-extend-today-until 0
1748 "The hour when your day really ends. Must be an integer.
1749 This has influence for the following applications:
1750 - When switching the agenda to \"today\". It it is still earlier than
1751 the time given here, the day recognized as TODAY is actually yesterday.
1752 - When a date is read from the user and it is still before the time given
1753 here, the current date and time will be assumed to be yesterday, 23:59.
1754 Also, timestamps inserted in remember templates follow this rule.
1756 IMPORTANT: This is a feature whose implementation is and likely will
1757 remain incomplete. Really, it is only here because past midnight seems to
1758 be the favorite working time of John Wiegley :-)"
1759 :group 'org-time
1760 :type 'number)
1762 (defcustom org-edit-timestamp-down-means-later nil
1763 "Non-nil means, S-down will increase the time in a time stamp.
1764 When nil, S-up will increase."
1765 :group 'org-time
1766 :type 'boolean)
1768 (defcustom org-calendar-follow-timestamp-change t
1769 "Non-nil means, make the calendar window follow timestamp changes.
1770 When a timestamp is modified and the calendar window is visible, it will be
1771 moved to the new date."
1772 :group 'org-time
1773 :type 'boolean)
1775 (defgroup org-tags nil
1776 "Options concerning tags in Org-mode."
1777 :tag "Org Tags"
1778 :group 'org)
1780 (defcustom org-tag-alist nil
1781 "List of tags allowed in Org-mode files.
1782 When this list is nil, Org-mode will base TAG input on what is already in the
1783 buffer.
1784 The value of this variable is an alist, the car of each entry must be a
1785 keyword as a string, the cdr may be a character that is used to select
1786 that tag through the fast-tag-selection interface.
1787 See the manual for details."
1788 :group 'org-tags
1789 :type '(repeat
1790 (choice
1791 (cons (string :tag "Tag name")
1792 (character :tag "Access char"))
1793 (const :tag "Start radio group" (:startgroup))
1794 (const :tag "End radio group" (:endgroup)))))
1796 (defvar org-file-tags nil
1797 "List of tags that can be inherited by all entries in the file.
1798 The tags will be inherited if the variable `org-use-tag-inheritance'
1799 says they should be.
1800 This variable is populated from #+TAG lines.")
1802 (defcustom org-use-fast-tag-selection 'auto
1803 "Non-nil means, use fast tag selection scheme.
1804 This is a special interface to select and deselect tags with single keys.
1805 When nil, fast selection is never used.
1806 When the symbol `auto', fast selection is used if and only if selection
1807 characters for tags have been configured, either through the variable
1808 `org-tag-alist' or through a #+TAGS line in the buffer.
1809 When t, fast selection is always used and selection keys are assigned
1810 automatically if necessary."
1811 :group 'org-tags
1812 :type '(choice
1813 (const :tag "Always" t)
1814 (const :tag "Never" nil)
1815 (const :tag "When selection characters are configured" 'auto)))
1817 (defcustom org-fast-tag-selection-single-key nil
1818 "Non-nil means, fast tag selection exits after first change.
1819 When nil, you have to press RET to exit it.
1820 During fast tag selection, you can toggle this flag with `C-c'.
1821 This variable can also have the value `expert'. In this case, the window
1822 displaying the tags menu is not even shown, until you press C-c again."
1823 :group 'org-tags
1824 :type '(choice
1825 (const :tag "No" nil)
1826 (const :tag "Yes" t)
1827 (const :tag "Expert" expert)))
1829 (defvar org-fast-tag-selection-include-todo nil
1830 "Non-nil means, fast tags selection interface will also offer TODO states.
1831 This is an undocumented feature, you should not rely on it.")
1833 (defcustom org-tags-column (if (featurep 'xemacs) -79 -80)
1834 "The column to which tags should be indented in a headline.
1835 If this number is positive, it specifies the column. If it is negative,
1836 it means that the tags should be flushright to that column. For example,
1837 -80 works well for a normal 80 character screen."
1838 :group 'org-tags
1839 :type 'integer)
1841 (defcustom org-auto-align-tags t
1842 "Non-nil means, realign tags after pro/demotion of TODO state change.
1843 These operations change the length of a headline and therefore shift
1844 the tags around. With this options turned on, after each such operation
1845 the tags are again aligned to `org-tags-column'."
1846 :group 'org-tags
1847 :type 'boolean)
1849 (defcustom org-use-tag-inheritance t
1850 "Non-nil means, tags in levels apply also for sublevels.
1851 When nil, only the tags directly given in a specific line apply there.
1852 If this option is t, a match early-on in a tree can lead to a large
1853 number of matches in the subtree. If you only want to see the first
1854 match in a tree during a search, check out the variable
1855 `org-tags-match-list-sublevels'.
1857 This may also be a list of tags that should be inherited, or a regexp that
1858 matches tags that should be inherited."
1859 :group 'org-tags
1860 :type '(choice
1861 (const :tag "Not" nil)
1862 (const :tag "Always" t)
1863 (repeat :tag "Specific tags" (string :tag "Tag"))
1864 (regexp :tag "Tags matched by regexp")))
1866 (defun org-tag-inherit-p (tag)
1867 "Check if TAG is one that should be inherited."
1868 (cond
1869 ((eq org-use-tag-inheritance t) t)
1870 ((not org-use-tag-inheritance) nil)
1871 ((stringp org-use-tag-inheritance)
1872 (string-match org-use-tag-inheritance tag))
1873 ((listp org-use-tag-inheritance)
1874 (member tag org-use-tag-inheritance))
1875 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
1877 (defcustom org-tags-match-list-sublevels t
1878 "Non-nil means list also sublevels of headlines matching tag search.
1879 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1880 the sublevels of a headline matching a tag search often also match
1881 the same search. Listing all of them can create very long lists.
1882 Setting this variable to nil causes subtrees of a match to be skipped.
1883 This option is off by default, because inheritance in on. If you turn
1884 inheritance off, you very likely want to turn this option on.
1886 As a special case, if the tag search is restricted to TODO items, the
1887 value of this variable is ignored and sublevels are always checked, to
1888 make sure all corresponding TODO items find their way into the list."
1889 :group 'org-tags
1890 :type 'boolean)
1892 (defvar org-tags-history nil
1893 "History of minibuffer reads for tags.")
1894 (defvar org-last-tags-completion-table nil
1895 "The last used completion table for tags.")
1896 (defvar org-after-tags-change-hook nil
1897 "Hook that is run after the tags in a line have changed.")
1899 (defgroup org-properties nil
1900 "Options concerning properties in Org-mode."
1901 :tag "Org Properties"
1902 :group 'org)
1904 (defcustom org-property-format "%-10s %s"
1905 "How property key/value pairs should be formatted by `indent-line'.
1906 When `indent-line' hits a property definition, it will format the line
1907 according to this format, mainly to make sure that the values are
1908 lined-up with respect to each other."
1909 :group 'org-properties
1910 :type 'string)
1912 (defcustom org-use-property-inheritance nil
1913 "Non-nil means, properties apply also for sublevels.
1915 This setting is chiefly used during property searches. Turning it on can
1916 cause significant overhead when doing a search, which is why it is not
1917 on by default.
1919 When nil, only the properties directly given in the current entry count.
1920 When t, every property is inherited. The value may also be a list of
1921 properties that should have inheritance, or a regular expression matching
1922 properties that should be inherited.
1924 However, note that some special properties use inheritance under special
1925 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
1926 and the properties ending in \"_ALL\" when they are used as descriptor
1927 for valid values of a property.
1929 Note for programmers:
1930 When querying an entry with `org-entry-get', you can control if inheritance
1931 should be used. By default, `org-entry-get' looks only at the local
1932 properties. You can request inheritance by setting the inherit argument
1933 to t (to force inheritance) or to `selective' (to respect the setting
1934 in this variable)."
1935 :group 'org-properties
1936 :type '(choice
1937 (const :tag "Not" nil)
1938 (const :tag "Always" t)
1939 (repeat :tag "Specific properties" (string :tag "Property"))
1940 (regexp :tag "Properties matched by regexp")))
1942 (defun org-property-inherit-p (property)
1943 "Check if PROPERTY is one that should be inherited."
1944 (cond
1945 ((eq org-use-property-inheritance t) t)
1946 ((not org-use-property-inheritance) nil)
1947 ((stringp org-use-property-inheritance)
1948 (string-match org-use-property-inheritance property))
1949 ((listp org-use-property-inheritance)
1950 (member property org-use-property-inheritance))
1951 (t (error "Invalid setting of `org-use-property-inheritance'"))))
1953 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
1954 "The default column format, if no other format has been defined.
1955 This variable can be set on the per-file basis by inserting a line
1957 #+COLUMNS: %25ITEM ....."
1958 :group 'org-properties
1959 :type 'string)
1961 (defcustom org-columns-ellipses ".."
1962 "The ellipses to be used when a field in column view is truncated.
1963 When this is the empty string, as many characters as possible are shown,
1964 but then there will be no visual indication that the field has been truncated.
1965 When this is a string of length N, the last N characters of a truncated
1966 field are replaced by this string. If the column is narrower than the
1967 ellipses string, only part of the ellipses string will be shown."
1968 :group 'org-properties
1969 :type 'string)
1971 (defcustom org-columns-modify-value-for-display-function nil
1972 "Function that modifies values for display in column view.
1973 For example, it can be used to cut out a certain part from a time stamp.
1974 The function must take 2 arguments:
1976 column-title The tite of the column (*not* the property name)
1977 value The value that should be modified.
1979 The function should return the value that should be displayed,
1980 or nil if the normal value should be used."
1981 :group 'org-properties
1982 :type 'function)
1984 (defcustom org-effort-property "Effort"
1985 "The property that is being used to keep track of effort estimates.
1986 Effort estimates given in this property need to have the format H:MM."
1987 :group 'org-properties
1988 :group 'org-progress
1989 :type '(string :tag "Property"))
1991 (defconst org-global-properties-fixed
1992 '(("VISIBILITY_ALL" . "folded children content all"))
1993 "List of property/value pairs that can be inherited by any entry.
1994 These are fixed values, for the preset properties.")
1997 (defcustom org-global-properties nil
1998 "List of property/value pairs that can be inherited by any entry.
1999 You can set buffer-local values for this by adding lines like
2001 #+PROPERTY: NAME VALUE"
2002 :group 'org-properties
2003 :type '(repeat
2004 (cons (string :tag "Property")
2005 (string :tag "Value"))))
2007 (defvar org-file-properties nil
2008 "List of property/value pairs that can be inherited by any entry.
2009 Valid for the current buffer.
2010 This variable is populated from #+PROPERTY lines.")
2011 (make-variable-buffer-local 'org-file-properties)
2013 (defgroup org-agenda nil
2014 "Options concerning agenda views in Org-mode."
2015 :tag "Org Agenda"
2016 :group 'org)
2018 (defvar org-category nil
2019 "Variable used by org files to set a category for agenda display.
2020 Such files should use a file variable to set it, for example
2022 # -*- mode: org; org-category: \"ELisp\"
2024 or contain a special line
2026 #+CATEGORY: ELisp
2028 If the file does not specify a category, then file's base name
2029 is used instead.")
2030 (make-variable-buffer-local 'org-category)
2031 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2033 (defcustom org-agenda-files nil
2034 "The files to be used for agenda display.
2035 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2036 \\[org-remove-file]. You can also use customize to edit the list.
2038 If an entry is a directory, all files in that directory that are matched by
2039 `org-agenda-file-regexp' will be part of the file list.
2041 If the value of the variable is not a list but a single file name, then
2042 the list of agenda files is actually stored and maintained in that file, one
2043 agenda file per line."
2044 :group 'org-agenda
2045 :type '(choice
2046 (repeat :tag "List of files and directories" file)
2047 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2049 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2050 "Regular expression to match files for `org-agenda-files'.
2051 If any element in the list in that variable contains a directory instead
2052 of a normal file, all files in that directory that are matched by this
2053 regular expression will be included."
2054 :group 'org-agenda
2055 :type 'regexp)
2057 (defcustom org-agenda-text-search-extra-files nil
2058 "List of extra files to be searched by text search commands.
2059 These files will be search in addition to the agenda files by the
2060 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2061 Note that these files will only be searched for text search commands,
2062 not for the other agenda views like todo lists, tag searches or the weekly
2063 agenda. This variable is intended to list notes and possibly archive files
2064 that should also be searched by these two commands.
2065 In fact, if the first element in the list is the symbol `agenda-archives',
2066 than all archive files of all agenda files will be added to the search
2067 scope."
2068 :group 'org-agenda
2069 :type '(set :greedy t
2070 (const :tag "Agenda Archives" agenda-archives)
2071 (repeat :inline t (file))))
2073 (if (fboundp 'defvaralias)
2074 (defvaralias 'org-agenda-multi-occur-extra-files
2075 'org-agenda-text-search-extra-files))
2077 (defcustom org-agenda-skip-unavailable-files nil
2078 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2079 A nil value means to remove them, after a query, from the list."
2080 :group 'org-agenda
2081 :type 'boolean)
2083 (defcustom org-calendar-to-agenda-key [?c]
2084 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2085 The command `org-calendar-goto-agenda' will be bound to this key. The
2086 default is the character `c' because then `c' can be used to switch back and
2087 forth between agenda and calendar."
2088 :group 'org-agenda
2089 :type 'sexp)
2091 (defcustom org-calendar-agenda-action-key [?k]
2092 "The key to be installed in `calendar-mode-map' for agenda-action.
2093 The command `org-agenda-action' will be bound to this key. The
2094 default is the character `k' because we use the same key in the agenda."
2095 :group 'org-agenda
2096 :type 'sexp)
2098 (eval-after-load "calendar"
2099 '(progn
2100 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2101 'org-calendar-goto-agenda)
2102 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2103 'org-agenda-action)))
2105 (defgroup org-latex nil
2106 "Options for embedding LaTeX code into Org-mode."
2107 :tag "Org LaTeX"
2108 :group 'org)
2110 (defcustom org-format-latex-options
2111 '(:foreground default :background default :scale 1.0
2112 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2113 :matchers ("begin" "$" "$$" "\\(" "\\["))
2114 "Options for creating images from LaTeX fragments.
2115 This is a property list with the following properties:
2116 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2117 `default' means use the foreground of the default face.
2118 :background the background color, or \"Transparent\".
2119 `default' means use the background of the default face.
2120 :scale a scaling factor for the size of the images.
2121 :html-foreground, :html-background, :html-scale
2122 the same numbers for HTML export.
2123 :matchers a list indicating which matchers should be used to
2124 find LaTeX fragments. Valid members of this list are:
2125 \"begin\" find environments
2126 \"$\" find math expressions surrounded by $...$
2127 \"$$\" find math expressions surrounded by $$....$$
2128 \"\\(\" find math expressions surrounded by \\(...\\)
2129 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2130 :group 'org-latex
2131 :type 'plist)
2133 (defcustom org-format-latex-header "\\documentclass{article}
2134 \\usepackage{fullpage} % do not remove
2135 \\usepackage{amssymb}
2136 \\usepackage[usenames]{color}
2137 \\usepackage{amsmath}
2138 \\usepackage{latexsym}
2139 \\usepackage[mathscr]{eucal}
2140 \\pagestyle{empty} % do not remove"
2141 "The document header used for processing LaTeX fragments."
2142 :group 'org-latex
2143 :type 'string)
2146 (defgroup org-font-lock nil
2147 "Font-lock settings for highlighting in Org-mode."
2148 :tag "Org Font Lock"
2149 :group 'org)
2151 (defcustom org-level-color-stars-only nil
2152 "Non-nil means fontify only the stars in each headline.
2153 When nil, the entire headline is fontified.
2154 Changing it requires restart of `font-lock-mode' to become effective
2155 also in regions already fontified."
2156 :group 'org-font-lock
2157 :type 'boolean)
2159 (defcustom org-hide-leading-stars nil
2160 "Non-nil means, hide the first N-1 stars in a headline.
2161 This works by using the face `org-hide' for these stars. This
2162 face is white for a light background, and black for a dark
2163 background. You may have to customize the face `org-hide' to
2164 make this work.
2165 Changing it requires restart of `font-lock-mode' to become effective
2166 also in regions already fontified.
2167 You may also set this on a per-file basis by adding one of the following
2168 lines to the buffer:
2170 #+STARTUP: hidestars
2171 #+STARTUP: showstars"
2172 :group 'org-font-lock
2173 :type 'boolean)
2175 (defcustom org-fontify-done-headline nil
2176 "Non-nil means, change the face of a headline if it is marked DONE.
2177 Normally, only the TODO/DONE keyword indicates the state of a headline.
2178 When this is non-nil, the headline after the keyword is set to the
2179 `org-headline-done' as an additional indication."
2180 :group 'org-font-lock
2181 :type 'boolean)
2183 (defcustom org-fontify-emphasized-text t
2184 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2185 Changing this variable requires a restart of Emacs to take effect."
2186 :group 'org-font-lock
2187 :type 'boolean)
2189 (defcustom org-highlight-latex-fragments-and-specials nil
2190 "Non-nil means, fontify what is treated specially by the exporters."
2191 :group 'org-font-lock
2192 :type 'boolean)
2194 (defcustom org-hide-emphasis-markers nil
2195 "Non-nil mean font-lock should hide the emphasis marker characters."
2196 :group 'org-font-lock
2197 :type 'boolean)
2199 (defvar org-emph-re nil
2200 "Regular expression for matching emphasis.")
2201 (defvar org-verbatim-re nil
2202 "Regular expression for matching verbatim text.")
2203 (defvar org-emphasis-regexp-components) ; defined just below
2204 (defvar org-emphasis-alist) ; defined just below
2205 (defun org-set-emph-re (var val)
2206 "Set variable and compute the emphasis regular expression."
2207 (set var val)
2208 (when (and (boundp 'org-emphasis-alist)
2209 (boundp 'org-emphasis-regexp-components)
2210 org-emphasis-alist org-emphasis-regexp-components)
2211 (let* ((e org-emphasis-regexp-components)
2212 (pre (car e))
2213 (post (nth 1 e))
2214 (border (nth 2 e))
2215 (body (nth 3 e))
2216 (nl (nth 4 e))
2217 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
2218 (body1 (concat body "*?"))
2219 (markers (mapconcat 'car org-emphasis-alist ""))
2220 (vmarkers (mapconcat
2221 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2222 org-emphasis-alist "")))
2223 ;; make sure special characters appear at the right position in the class
2224 (if (string-match "\\^" markers)
2225 (setq markers (concat (replace-match "" t t markers) "^")))
2226 (if (string-match "-" markers)
2227 (setq markers (concat (replace-match "" t t markers) "-")))
2228 (if (string-match "\\^" vmarkers)
2229 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2230 (if (string-match "-" vmarkers)
2231 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2232 (if (> nl 0)
2233 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2234 (int-to-string nl) "\\}")))
2235 ;; Make the regexp
2236 (setq org-emph-re
2237 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
2238 "\\("
2239 "\\([" markers "]\\)"
2240 "\\("
2241 "[^" border "]\\|"
2242 "[^" border (if (and nil stacked) markers) "]"
2243 body1
2244 "[^" border (if (and nil stacked) markers) "]"
2245 "\\)"
2246 "\\3\\)"
2247 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
2248 (setq org-verbatim-re
2249 (concat "\\([" pre "]\\|^\\)"
2250 "\\("
2251 "\\([" vmarkers "]\\)"
2252 "\\("
2253 "[^" border "]\\|"
2254 "[^" border "]"
2255 body1
2256 "[^" border "]"
2257 "\\)"
2258 "\\3\\)"
2259 "\\([" post "]\\|$\\)")))))
2261 (defcustom org-emphasis-regexp-components
2262 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
2263 "Components used to build the regular expression for emphasis.
2264 This is a list with 6 entries. Terminology: In an emphasis string
2265 like \" *strong word* \", we call the initial space PREMATCH, the final
2266 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2267 and \"trong wor\" is the body. The different components in this variable
2268 specify what is allowed/forbidden in each part:
2270 pre Chars allowed as prematch. Beginning of line will be allowed too.
2271 post Chars allowed as postmatch. End of line will be allowed too.
2272 border The chars *forbidden* as border characters.
2273 body-regexp A regexp like \".\" to match a body character. Don't use
2274 non-shy groups here, and don't allow newline here.
2275 newline The maximum number of newlines allowed in an emphasis exp.
2277 Use customize to modify this, or restart Emacs after changing it."
2278 :group 'org-font-lock
2279 :set 'org-set-emph-re
2280 :type '(list
2281 (sexp :tag "Allowed chars in pre ")
2282 (sexp :tag "Allowed chars in post ")
2283 (sexp :tag "Forbidden chars in border ")
2284 (sexp :tag "Regexp for body ")
2285 (integer :tag "number of newlines allowed")
2286 (option (boolean :tag "Please ignore this button"))))
2288 (defcustom org-emphasis-alist
2289 `(("*" bold "<b>" "</b>")
2290 ("/" italic "<i>" "</i>")
2291 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
2292 ("=" org-code "<code>" "</code>" verbatim)
2293 ("~" org-verbatim "<code>" "</code>" verbatim)
2294 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2295 "<del>" "</del>")
2297 "Special syntax for emphasized text.
2298 Text starting and ending with a special character will be emphasized, for
2299 example *bold*, _underlined_ and /italic/. This variable sets the marker
2300 characters, the face to be used by font-lock for highlighting in Org-mode
2301 Emacs buffers, and the HTML tags to be used for this.
2302 Use customize to modify this, or restart Emacs after changing it."
2303 :group 'org-font-lock
2304 :set 'org-set-emph-re
2305 :type '(repeat
2306 (list
2307 (string :tag "Marker character")
2308 (choice
2309 (face :tag "Font-lock-face")
2310 (plist :tag "Face property list"))
2311 (string :tag "HTML start tag")
2312 (string :tag "HTML end tag")
2313 (option (const verbatim)))))
2315 ;;; Miscellaneous options
2317 (defgroup org-completion nil
2318 "Completion in Org-mode."
2319 :tag "Org Completion"
2320 :group 'org)
2322 (defcustom org-completion-fallback-command 'hippie-expand
2323 "The expansion command called by \\[org-complete] in normal context.
2324 Normal means, no org-mode-specific context."
2325 :group 'org-completion
2326 :type 'function)
2328 ;;; Functions and variables from ther packages
2329 ;; Declared here to avoid compiler warnings
2331 ;; XEmacs only
2332 (defvar outline-mode-menu-heading)
2333 (defvar outline-mode-menu-show)
2334 (defvar outline-mode-menu-hide)
2335 (defvar zmacs-regions) ; XEmacs regions
2337 ;; Emacs only
2338 (defvar mark-active)
2340 ;; Various packages
2341 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2342 (declare-function calendar-forward-day "cal-move" (arg))
2343 (declare-function calendar-goto-date "cal-move" (date))
2344 (declare-function calendar-goto-today "cal-move" ())
2345 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2346 (defvar calc-embedded-close-formula)
2347 (defvar calc-embedded-open-formula)
2348 (declare-function cdlatex-tab "ext:cdlatex" ())
2349 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2350 (defvar font-lock-unfontify-region-function)
2351 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2352 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2353 (defvar iswitchb-temp-buflist)
2354 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2355 (declare-function org-agenda-skip "org-agenda" ())
2356 (declare-function org-format-agenda-item "org-agenda"
2357 (extra txt &optional category tags dotime noprefix remove-re))
2358 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2359 (declare-function org-agenda-change-all-lines "org-agenda"
2360 (newhead hdmarker &optional fixface))
2361 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2362 (declare-function org-agenda-maybe-redo "org-agenda" ())
2363 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2364 (beg end))
2365 (declare-function parse-time-string "parse-time" (string))
2366 (declare-function remember "remember" (&optional initial))
2367 (declare-function remember-buffer-desc "remember" ())
2368 (declare-function remember-finalize "remember" ())
2369 (defvar remember-save-after-remembering)
2370 (defvar remember-data-file)
2371 (defvar remember-register)
2372 (defvar remember-buffer)
2373 (defvar remember-handler-functions)
2374 (defvar remember-annotation-functions)
2375 (defvar texmathp-why)
2376 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2377 (declare-function table--at-cell-p "table" (position &optional object at-column))
2379 (defvar w3m-current-url)
2380 (defvar w3m-current-title)
2382 (defvar org-latex-regexps)
2384 ;;; Autoload and prepare some org modules
2386 ;; Some table stuff that needs to be defined here, because it is used
2387 ;; by the functions setting up org-mode or checking for table context.
2389 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2390 "Detects an org-type or table-type table.")
2391 (defconst org-table-line-regexp "^[ \t]*|"
2392 "Detects an org-type table line.")
2393 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2394 "Detects an org-type table line.")
2395 (defconst org-table-hline-regexp "^[ \t]*|-"
2396 "Detects an org-type table hline.")
2397 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2398 "Detects a table-type table hline.")
2399 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2400 "Searching from within a table (any type) this finds the first line
2401 outside the table.")
2403 ;; Autoload the functions in org-table.el that are needed by functions here.
2405 (eval-and-compile
2406 (org-autoload "org-table"
2407 '(org-table-align org-table-begin org-table-blank-field
2408 org-table-convert org-table-convert-region org-table-copy-down
2409 org-table-copy-region org-table-create
2410 org-table-create-or-convert-from-region
2411 org-table-create-with-table.el org-table-current-dline
2412 org-table-cut-region org-table-delete-column org-table-edit-field
2413 org-table-edit-formulas org-table-end org-table-eval-formula
2414 org-table-export org-table-field-info
2415 org-table-get-stored-formulas org-table-goto-column
2416 org-table-hline-and-move org-table-import org-table-insert-column
2417 org-table-insert-hline org-table-insert-row org-table-iterate
2418 org-table-justify-field-maybe org-table-kill-row
2419 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2420 org-table-move-column org-table-move-column-left
2421 org-table-move-column-right org-table-move-row
2422 org-table-move-row-down org-table-move-row-up
2423 org-table-next-field org-table-next-row org-table-paste-rectangle
2424 org-table-previous-field org-table-recalculate
2425 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2426 org-table-toggle-coordinate-overlays
2427 org-table-toggle-formula-debugger org-table-wrap-region
2428 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
2430 (defun org-at-table-p (&optional table-type)
2431 "Return t if the cursor is inside an org-type table.
2432 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2433 (if org-enable-table-editor
2434 (save-excursion
2435 (beginning-of-line 1)
2436 (looking-at (if table-type org-table-any-line-regexp
2437 org-table-line-regexp)))
2438 nil))
2439 (defsubst org-table-p () (org-at-table-p))
2441 (defun org-at-table.el-p ()
2442 "Return t if and only if we are at a table.el table."
2443 (and (org-at-table-p 'any)
2444 (save-excursion
2445 (goto-char (org-table-begin 'any))
2446 (looking-at org-table1-hline-regexp))))
2447 (defun org-table-recognize-table.el ()
2448 "If there is a table.el table nearby, recognize it and move into it."
2449 (if org-table-tab-recognizes-table.el
2450 (if (org-at-table.el-p)
2451 (progn
2452 (beginning-of-line 1)
2453 (if (looking-at org-table-dataline-regexp)
2455 (if (looking-at org-table1-hline-regexp)
2456 (progn
2457 (beginning-of-line 2)
2458 (if (looking-at org-table-any-border-regexp)
2459 (beginning-of-line -1)))))
2460 (if (re-search-forward "|" (org-table-end t) t)
2461 (progn
2462 (require 'table)
2463 (if (table--at-cell-p (point))
2465 (message "recognizing table.el table...")
2466 (table-recognize-table)
2467 (message "recognizing table.el table...done")))
2468 (error "This should not happen..."))
2470 nil)
2471 nil))
2473 (defun org-at-table-hline-p ()
2474 "Return t if the cursor is inside a hline in a table."
2475 (if org-enable-table-editor
2476 (save-excursion
2477 (beginning-of-line 1)
2478 (looking-at org-table-hline-regexp))
2479 nil))
2481 (defvar org-table-clean-did-remove-column nil)
2483 (defun org-table-map-tables (function)
2484 "Apply FUNCTION to the start of all tables in the buffer."
2485 (save-excursion
2486 (save-restriction
2487 (widen)
2488 (goto-char (point-min))
2489 (while (re-search-forward org-table-any-line-regexp nil t)
2490 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2491 (beginning-of-line 1)
2492 (if (looking-at org-table-line-regexp)
2493 (save-excursion (funcall function)))
2494 (re-search-forward org-table-any-border-regexp nil 1))))
2495 (message "Mapping tables: done"))
2497 ;; Declare and autoload functions from org-exp.el
2499 (declare-function org-default-export-plist "org-exp")
2500 (declare-function org-infile-export-plist "org-exp")
2501 (declare-function org-get-current-options "org-exp")
2502 (eval-and-compile
2503 (org-autoload "org-exp"
2504 '(org-export org-export-as-ascii org-export-visible
2505 org-insert-export-options-template org-export-as-html-and-open
2506 org-export-as-html-batch org-export-as-html-to-buffer
2507 org-replace-region-by-html org-export-region-as-html
2508 org-export-as-html org-export-icalendar-this-file
2509 org-export-icalendar-all-agenda-files
2510 org-table-clean-before-export
2511 org-export-icalendar-combine-agenda-files org-export-as-xoxo)))
2513 ;; Declare and autoload functions from org-agenda.el
2515 (eval-and-compile
2516 (org-autoload "org-agenda"
2517 '(org-agenda org-agenda-list org-search-view
2518 org-todo-list org-tags-view org-agenda-list-stuck-projects
2519 org-diary org-agenda-to-appt)))
2521 ;; Autoload org-remember
2523 (eval-and-compile
2524 (org-autoload "org-remember"
2525 '(org-remember-insinuate org-remember-annotation
2526 org-remember-apply-template org-remember org-remember-handler)))
2528 ;; Autoload org-clock.el
2531 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
2532 (beg end))
2533 (declare-function org-update-mode-line "org-clock" ())
2534 (defvar org-clock-start-time)
2535 (defvar org-clock-marker (make-marker)
2536 "Marker recording the last clock-in.")
2538 (eval-and-compile
2539 (org-autoload
2540 "org-clock"
2541 '(org-clock-in org-clock-out org-clock-cancel
2542 org-clock-goto org-clock-sum org-clock-display
2543 org-remove-clock-overlays org-clock-report
2544 org-clocktable-shift org-dblock-write:clocktable
2545 org-get-clocktable)))
2547 (defun org-clock-update-time-maybe ()
2548 "If this is a CLOCK line, update it and return t.
2549 Otherwise, return nil."
2550 (interactive)
2551 (save-excursion
2552 (beginning-of-line 1)
2553 (skip-chars-forward " \t")
2554 (when (looking-at org-clock-string)
2555 (let ((re (concat "[ \t]*" org-clock-string
2556 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
2557 "\\([ \t]*=>.*\\)?\\)?"))
2558 ts te h m s neg)
2559 (cond
2560 ((not (looking-at re))
2561 nil)
2562 ((not (match-end 2))
2563 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2564 (> org-clock-marker (point))
2565 (<= org-clock-marker (point-at-eol)))
2566 ;; The clock is running here
2567 (setq org-clock-start-time
2568 (apply 'encode-time
2569 (org-parse-time-string (match-string 1))))
2570 (org-update-mode-line)))
2572 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
2573 (end-of-line 1)
2574 (setq ts (match-string 1)
2575 te (match-string 3))
2576 (setq s (- (time-to-seconds
2577 (apply 'encode-time (org-parse-time-string te)))
2578 (time-to-seconds
2579 (apply 'encode-time (org-parse-time-string ts))))
2580 neg (< s 0)
2581 s (abs s)
2582 h (floor (/ s 3600))
2583 s (- s (* 3600 h))
2584 m (floor (/ s 60))
2585 s (- s (* 60 s)))
2586 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
2587 t))))))
2589 (defun org-check-running-clock ()
2590 "Check if the current buffer contains the running clock.
2591 If yes, offer to stop it and to save the buffer with the changes."
2592 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2593 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
2594 (buffer-name))))
2595 (org-clock-out)
2596 (when (y-or-n-p "Save changed buffer?")
2597 (save-buffer))))
2599 (defun org-clocktable-try-shift (dir n)
2600 "Check if this line starts a clock table, if yes, shift the time block."
2601 (when (org-match-line "#\\+BEGIN: clocktable\\>")
2602 (org-clocktable-shift dir n)))
2604 ;; Autoload archiving code
2605 ;; The stuff that is needed for cycling and tags has to be defined here.
2607 (defgroup org-archive nil
2608 "Options concerning archiving in Org-mode."
2609 :tag "Org Archive"
2610 :group 'org-structure)
2612 (defcustom org-archive-location "%s_archive::"
2613 "The location where subtrees should be archived.
2615 Otherwise, the value of this variable is a string, consisting of two
2616 parts, separated by a double-colon.
2618 The first part is a file name - when omitted, archiving happens in the same
2619 file. %s will be replaced by the current file name (without directory part).
2620 Archiving to a different file is useful to keep archived entries from
2621 contributing to the Org-mode Agenda.
2623 The part after the double colon is a headline. The archived entries will be
2624 filed under that headline. When omitted, the subtrees are simply filed away
2625 at the end of the file, as top-level entries.
2627 Here are a few examples:
2628 \"%s_archive::\"
2629 If the current file is Projects.org, archive in file
2630 Projects.org_archive, as top-level trees. This is the default.
2632 \"::* Archived Tasks\"
2633 Archive in the current file, under the top-level headline
2634 \"* Archived Tasks\".
2636 \"~/org/archive.org::\"
2637 Archive in file ~/org/archive.org (absolute path), as top-level trees.
2639 \"basement::** Finished Tasks\"
2640 Archive in file ./basement (relative path), as level 3 trees
2641 below the level 2 heading \"** Finished Tasks\".
2643 You may set this option on a per-file basis by adding to the buffer a
2644 line like
2646 #+ARCHIVE: basement::** Finished Tasks
2648 You may also define it locally for a subtree by setting an ARCHIVE property
2649 in the entry. If such a property is found in an entry, or anywhere up
2650 the hierarchy, it will be used."
2651 :group 'org-archive
2652 :type 'string)
2654 (defcustom org-archive-tag "ARCHIVE"
2655 "The tag that marks a subtree as archived.
2656 An archived subtree does not open during visibility cycling, and does
2657 not contribute to the agenda listings.
2658 After changing this, font-lock must be restarted in the relevant buffers to
2659 get the proper fontification."
2660 :group 'org-archive
2661 :group 'org-keywords
2662 :type 'string)
2664 (defcustom org-agenda-skip-archived-trees t
2665 "Non-nil means, the agenda will skip any items located in archived trees.
2666 An archived tree is a tree marked with the tag ARCHIVE. The use of this
2667 variable is no longer recommended, you should leave it at the value t.
2668 Instead, use the key `v' to cycle the archives-mode in the agenda."
2669 :group 'org-archive
2670 :group 'org-agenda-skip
2671 :type 'boolean)
2673 (defcustom org-cycle-open-archived-trees nil
2674 "Non-nil means, `org-cycle' will open archived trees.
2675 An archived tree is a tree marked with the tag ARCHIVE.
2676 When nil, archived trees will stay folded. You can still open them with
2677 normal outline commands like `show-all', but not with the cycling commands."
2678 :group 'org-archive
2679 :group 'org-cycle
2680 :type 'boolean)
2682 (defcustom org-sparse-tree-open-archived-trees nil
2683 "Non-nil means sparse tree construction shows matches in archived trees.
2684 When nil, matches in these trees are highlighted, but the trees are kept in
2685 collapsed state."
2686 :group 'org-archive
2687 :group 'org-sparse-trees
2688 :type 'boolean)
2690 (defun org-cycle-hide-archived-subtrees (state)
2691 "Re-hide all archived subtrees after a visibility state change."
2692 (when (and (not org-cycle-open-archived-trees)
2693 (not (memq state '(overview folded))))
2694 (save-excursion
2695 (let* ((globalp (memq state '(contents all)))
2696 (beg (if globalp (point-min) (point)))
2697 (end (if globalp (point-max) (org-end-of-subtree t))))
2698 (org-hide-archived-subtrees beg end)
2699 (goto-char beg)
2700 (if (looking-at (concat ".*:" org-archive-tag ":"))
2701 (message "%s" (substitute-command-keys
2702 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
2704 (defun org-force-cycle-archived ()
2705 "Cycle subtree even if it is archived."
2706 (interactive)
2707 (setq this-command 'org-cycle)
2708 (let ((org-cycle-open-archived-trees t))
2709 (call-interactively 'org-cycle)))
2711 (defun org-hide-archived-subtrees (beg end)
2712 "Re-hide all archived subtrees after a visibility state change."
2713 (save-excursion
2714 (let* ((re (concat ":" org-archive-tag ":")))
2715 (goto-char beg)
2716 (while (re-search-forward re end t)
2717 (and (org-on-heading-p) (hide-subtree))
2718 (org-end-of-subtree t)))))
2720 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
2722 (eval-and-compile
2723 (org-autoload "org-archive"
2724 '(org-add-archive-files org-archive-subtree
2725 org-archive-to-archive-sibling org-toggle-archive-tag)))
2727 ;; Autoload Column View Code
2729 (declare-function org-columns-number-to-string "org-colview")
2730 (declare-function org-columns-get-format-and-top-level "org-colview")
2731 (declare-function org-columns-compute "org-colview")
2733 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
2734 '(org-columns-number-to-string org-columns-get-format-and-top-level
2735 org-columns-compute org-agenda-columns org-columns-remove-overlays
2736 org-columns org-insert-columns-dblock org-dblock-write:columnview))
2738 ;; Autoload ID code
2740 (org-autoload "org-id"
2741 '(org-id-get-create org-id-new org-id-copy org-id-get
2742 org-id-get-with-outline-path-completion
2743 org-id-get-with-outline-drilling
2744 org-id-goto org-id-find))
2746 ;;; Variables for pre-computed regular expressions, all buffer local
2748 (defvar org-drawer-regexp nil
2749 "Matches first line of a hidden block.")
2750 (make-variable-buffer-local 'org-drawer-regexp)
2751 (defvar org-todo-regexp nil
2752 "Matches any of the TODO state keywords.")
2753 (make-variable-buffer-local 'org-todo-regexp)
2754 (defvar org-not-done-regexp nil
2755 "Matches any of the TODO state keywords except the last one.")
2756 (make-variable-buffer-local 'org-not-done-regexp)
2757 (defvar org-todo-line-regexp nil
2758 "Matches a headline and puts TODO state into group 2 if present.")
2759 (make-variable-buffer-local 'org-todo-line-regexp)
2760 (defvar org-complex-heading-regexp nil
2761 "Matches a headline and puts everything into groups:
2762 group 1: the stars
2763 group 2: The todo keyword, maybe
2764 group 3: Priority cookie
2765 group 4: True headline
2766 group 5: Tags")
2767 (make-variable-buffer-local 'org-complex-heading-regexp)
2768 (defvar org-todo-line-tags-regexp nil
2769 "Matches a headline and puts TODO state into group 2 if present.
2770 Also put tags into group 4 if tags are present.")
2771 (make-variable-buffer-local 'org-todo-line-tags-regexp)
2772 (defvar org-nl-done-regexp nil
2773 "Matches newline followed by a headline with the DONE keyword.")
2774 (make-variable-buffer-local 'org-nl-done-regexp)
2775 (defvar org-looking-at-done-regexp nil
2776 "Matches the DONE keyword a point.")
2777 (make-variable-buffer-local 'org-looking-at-done-regexp)
2778 (defvar org-ds-keyword-length 12
2779 "Maximum length of the Deadline and SCHEDULED keywords.")
2780 (make-variable-buffer-local 'org-ds-keyword-length)
2781 (defvar org-deadline-regexp nil
2782 "Matches the DEADLINE keyword.")
2783 (make-variable-buffer-local 'org-deadline-regexp)
2784 (defvar org-deadline-time-regexp nil
2785 "Matches the DEADLINE keyword together with a time stamp.")
2786 (make-variable-buffer-local 'org-deadline-time-regexp)
2787 (defvar org-deadline-line-regexp nil
2788 "Matches the DEADLINE keyword and the rest of the line.")
2789 (make-variable-buffer-local 'org-deadline-line-regexp)
2790 (defvar org-scheduled-regexp nil
2791 "Matches the SCHEDULED keyword.")
2792 (make-variable-buffer-local 'org-scheduled-regexp)
2793 (defvar org-scheduled-time-regexp nil
2794 "Matches the SCHEDULED keyword together with a time stamp.")
2795 (make-variable-buffer-local 'org-scheduled-time-regexp)
2796 (defvar org-closed-time-regexp nil
2797 "Matches the CLOSED keyword together with a time stamp.")
2798 (make-variable-buffer-local 'org-closed-time-regexp)
2800 (defvar org-keyword-time-regexp nil
2801 "Matches any of the 4 keywords, together with the time stamp.")
2802 (make-variable-buffer-local 'org-keyword-time-regexp)
2803 (defvar org-keyword-time-not-clock-regexp nil
2804 "Matches any of the 3 keywords, together with the time stamp.")
2805 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
2806 (defvar org-maybe-keyword-time-regexp nil
2807 "Matches a timestamp, possibly preceeded by a keyword.")
2808 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
2809 (defvar org-planning-or-clock-line-re nil
2810 "Matches a line with planning or clock info.")
2811 (make-variable-buffer-local 'org-planning-or-clock-line-re)
2813 (defconst org-plain-time-of-day-regexp
2814 (concat
2815 "\\(\\<[012]?[0-9]"
2816 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2817 "\\(--?"
2818 "\\(\\<[012]?[0-9]"
2819 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2820 "\\)?")
2821 "Regular expression to match a plain time or time range.
2822 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2823 groups carry important information:
2824 0 the full match
2825 1 the first time, range or not
2826 8 the second time, if it is a range.")
2828 (defconst org-plain-time-extension-regexp
2829 (concat
2830 "\\(\\<[012]?[0-9]"
2831 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2832 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
2833 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
2834 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2835 groups carry important information:
2836 0 the full match
2837 7 hours of duration
2838 9 minutes of duration")
2840 (defconst org-stamp-time-of-day-regexp
2841 (concat
2842 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
2843 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
2844 "\\(--?"
2845 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
2846 "Regular expression to match a timestamp time or time range.
2847 After a match, the following groups carry important information:
2848 0 the full match
2849 1 date plus weekday, for backreferencing to make sure both times on same day
2850 2 the first time, range or not
2851 4 the second time, if it is a range.")
2853 (defconst org-startup-options
2854 '(("fold" org-startup-folded t)
2855 ("overview" org-startup-folded t)
2856 ("nofold" org-startup-folded nil)
2857 ("showall" org-startup-folded nil)
2858 ("content" org-startup-folded content)
2859 ("hidestars" org-hide-leading-stars t)
2860 ("showstars" org-hide-leading-stars nil)
2861 ("odd" org-odd-levels-only t)
2862 ("oddeven" org-odd-levels-only nil)
2863 ("align" org-startup-align-all-tables t)
2864 ("noalign" org-startup-align-all-tables nil)
2865 ("customtime" org-display-custom-times t)
2866 ("logdone" org-log-done time)
2867 ("lognotedone" org-log-done note)
2868 ("nologdone" org-log-done nil)
2869 ("lognoteclock-out" org-log-note-clock-out t)
2870 ("nolognoteclock-out" org-log-note-clock-out nil)
2871 ("logrepeat" org-log-repeat state)
2872 ("lognoterepeat" org-log-repeat note)
2873 ("nologrepeat" org-log-repeat nil)
2874 ("constcgs" constants-unit-system cgs)
2875 ("constSI" constants-unit-system SI))
2876 "Variable associated with STARTUP options for org-mode.
2877 Each element is a list of three items: The startup options as written
2878 in the #+STARTUP line, the corresponding variable, and the value to
2879 set this variable to if the option is found. An optional forth element PUSH
2880 means to push this value onto the list in the variable.")
2882 (defun org-set-regexps-and-options ()
2883 "Precompute regular expressions for current buffer."
2884 (when (org-mode-p)
2885 (org-set-local 'org-todo-kwd-alist nil)
2886 (org-set-local 'org-todo-key-alist nil)
2887 (org-set-local 'org-todo-key-trigger nil)
2888 (org-set-local 'org-todo-keywords-1 nil)
2889 (org-set-local 'org-done-keywords nil)
2890 (org-set-local 'org-todo-heads nil)
2891 (org-set-local 'org-todo-sets nil)
2892 (org-set-local 'org-todo-log-states nil)
2893 (org-set-local 'org-file-properties nil)
2894 (org-set-local 'org-file-tags nil)
2895 (let ((re (org-make-options-regexp
2896 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
2897 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
2898 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")))
2899 (splitre "[ \t]+")
2900 kwds kws0 kwsa key log value cat arch tags const links hw dws
2901 tail sep kws1 prio props ftags drawers
2902 ext-setup-or-nil setup-contents (start 0))
2903 (save-excursion
2904 (save-restriction
2905 (widen)
2906 (goto-char (point-min))
2907 (while (or (and ext-setup-or-nil
2908 (string-match re ext-setup-or-nil start)
2909 (setq start (match-end 0)))
2910 (and (setq ext-setup-or-nil nil start 0)
2911 (re-search-forward re nil t)))
2912 (setq key (upcase (match-string 1 ext-setup-or-nil))
2913 value (org-match-string-no-properties 2 ext-setup-or-nil))
2914 (cond
2915 ((equal key "CATEGORY")
2916 (if (string-match "[ \t]+$" value)
2917 (setq value (replace-match "" t t value)))
2918 (setq cat value))
2919 ((member key '("SEQ_TODO" "TODO"))
2920 (push (cons 'sequence (org-split-string value splitre)) kwds))
2921 ((equal key "TYP_TODO")
2922 (push (cons 'type (org-split-string value splitre)) kwds))
2923 ((equal key "TAGS")
2924 (setq tags (append tags (org-split-string value splitre))))
2925 ((equal key "COLUMNS")
2926 (org-set-local 'org-columns-default-format value))
2927 ((equal key "LINK")
2928 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
2929 (push (cons (match-string 1 value)
2930 (org-trim (match-string 2 value)))
2931 links)))
2932 ((equal key "PRIORITIES")
2933 (setq prio (org-split-string value " +")))
2934 ((equal key "PROPERTY")
2935 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
2936 (push (cons (match-string 1 value) (match-string 2 value))
2937 props)))
2938 ((equal key "FILETAGS")
2939 (when (string-match "\\S-" value)
2940 (setq ftags
2941 (append
2942 ftags
2943 (apply 'append
2944 (mapcar (lambda (x) (org-split-string x ":"))
2945 (org-split-string value)))))))
2946 ((equal key "DRAWERS")
2947 (setq drawers (org-split-string value splitre)))
2948 ((equal key "CONSTANTS")
2949 (setq const (append const (org-split-string value splitre))))
2950 ((equal key "STARTUP")
2951 (let ((opts (org-split-string value splitre))
2952 l var val)
2953 (while (setq l (pop opts))
2954 (when (setq l (assoc l org-startup-options))
2955 (setq var (nth 1 l) val (nth 2 l))
2956 (if (not (nth 3 l))
2957 (set (make-local-variable var) val)
2958 (if (not (listp (symbol-value var)))
2959 (set (make-local-variable var) nil))
2960 (set (make-local-variable var) (symbol-value var))
2961 (add-to-list var val))))))
2962 ((equal key "ARCHIVE")
2963 (string-match " *$" value)
2964 (setq arch (replace-match "" t t value))
2965 (remove-text-properties 0 (length arch)
2966 '(face t fontified t) arch))
2967 ((equal key "SETUPFILE")
2968 (setq setup-contents (org-file-contents
2969 (expand-file-name
2970 (org-remove-double-quotes value))
2971 'noerror))
2972 (if (not ext-setup-or-nil)
2973 (setq ext-setup-or-nil setup-contents start 0)
2974 (setq ext-setup-or-nil
2975 (concat (substring ext-setup-or-nil 0 start)
2976 "\n" setup-contents "\n"
2977 (substring ext-setup-or-nil start)))))
2978 ))))
2979 (when cat
2980 (org-set-local 'org-category (intern cat))
2981 (push (cons "CATEGORY" cat) props))
2982 (when prio
2983 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
2984 (setq prio (mapcar 'string-to-char prio))
2985 (org-set-local 'org-highest-priority (nth 0 prio))
2986 (org-set-local 'org-lowest-priority (nth 1 prio))
2987 (org-set-local 'org-default-priority (nth 2 prio)))
2988 (and props (org-set-local 'org-file-properties (nreverse props)))
2989 (and ftags (org-set-local 'org-file-tags ftags))
2990 (and drawers (org-set-local 'org-drawers drawers))
2991 (and arch (org-set-local 'org-archive-location arch))
2992 (and links (setq org-link-abbrev-alist-local (nreverse links)))
2993 ;; Process the TODO keywords
2994 (unless kwds
2995 ;; Use the global values as if they had been given locally.
2996 (setq kwds (default-value 'org-todo-keywords))
2997 (if (stringp (car kwds))
2998 (setq kwds (list (cons org-todo-interpretation
2999 (default-value 'org-todo-keywords)))))
3000 (setq kwds (reverse kwds)))
3001 (setq kwds (nreverse kwds))
3002 (let (inter kws kw)
3003 (while (setq kws (pop kwds))
3004 (setq inter (pop kws) sep (member "|" kws)
3005 kws0 (delete "|" (copy-sequence kws))
3006 kwsa nil
3007 kws1 (mapcar
3008 (lambda (x)
3009 ;; 1 2
3010 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3011 (progn
3012 (setq kw (match-string 1 x)
3013 key (and (match-end 2) (match-string 2 x))
3014 log (org-extract-log-state-settings x))
3015 (push (cons kw (and key (string-to-char key))) kwsa)
3016 (and log (push log org-todo-log-states))
3018 (error "Invalid TODO keyword %s" x)))
3019 kws0)
3020 kwsa (if kwsa (append '((:startgroup))
3021 (nreverse kwsa)
3022 '((:endgroup))))
3023 hw (car kws1)
3024 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3025 tail (list inter hw (car dws) (org-last dws)))
3026 (add-to-list 'org-todo-heads hw 'append)
3027 (push kws1 org-todo-sets)
3028 (setq org-done-keywords (append org-done-keywords dws nil))
3029 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3030 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3031 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3032 (setq org-todo-sets (nreverse org-todo-sets)
3033 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3034 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3035 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3036 ;; Process the constants
3037 (when const
3038 (let (e cst)
3039 (while (setq e (pop const))
3040 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3041 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3042 (setq org-table-formula-constants-local cst)))
3044 ;; Process the tags.
3045 (when tags
3046 (let (e tgs)
3047 (while (setq e (pop tags))
3048 (cond
3049 ((equal e "{") (push '(:startgroup) tgs))
3050 ((equal e "}") (push '(:endgroup) tgs))
3051 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3052 (push (cons (match-string 1 e)
3053 (string-to-char (match-string 2 e)))
3054 tgs))
3055 (t (push (list e) tgs))))
3056 (org-set-local 'org-tag-alist nil)
3057 (while (setq e (pop tgs))
3058 (or (and (stringp (car e))
3059 (assoc (car e) org-tag-alist))
3060 (push e org-tag-alist)))))
3062 ;; Compute the regular expressions and other local variables
3063 (if (not org-done-keywords)
3064 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
3065 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3066 (length org-scheduled-string)
3067 (length org-clock-string)
3068 (length org-closed-string)))
3069 org-drawer-regexp
3070 (concat "^[ \t]*:\\("
3071 (mapconcat 'regexp-quote org-drawers "\\|")
3072 "\\):[ \t]*$")
3073 org-not-done-keywords
3074 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3075 org-todo-regexp
3076 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3077 "\\|") "\\)\\>")
3078 org-not-done-regexp
3079 (concat "\\<\\("
3080 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3081 "\\)\\>")
3082 org-todo-line-regexp
3083 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3084 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3085 "\\)\\>\\)?[ \t]*\\(.*\\)")
3086 org-complex-heading-regexp
3087 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
3088 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3089 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3090 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3091 org-nl-done-regexp
3092 (concat "\n\\*+[ \t]+"
3093 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3094 "\\)" "\\>")
3095 org-todo-line-tags-regexp
3096 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3097 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3098 (org-re
3099 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3100 org-looking-at-done-regexp
3101 (concat "^" "\\(?:"
3102 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3103 "\\>")
3104 org-deadline-regexp (concat "\\<" org-deadline-string)
3105 org-deadline-time-regexp
3106 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3107 org-deadline-line-regexp
3108 (concat "\\<\\(" org-deadline-string "\\).*")
3109 org-scheduled-regexp
3110 (concat "\\<" org-scheduled-string)
3111 org-scheduled-time-regexp
3112 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3113 org-closed-time-regexp
3114 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3115 org-keyword-time-regexp
3116 (concat "\\<\\(" org-scheduled-string
3117 "\\|" org-deadline-string
3118 "\\|" org-closed-string
3119 "\\|" org-clock-string "\\)"
3120 " *[[<]\\([^]>]+\\)[]>]")
3121 org-keyword-time-not-clock-regexp
3122 (concat "\\<\\(" org-scheduled-string
3123 "\\|" org-deadline-string
3124 "\\|" org-closed-string
3125 "\\)"
3126 " *[[<]\\([^]>]+\\)[]>]")
3127 org-maybe-keyword-time-regexp
3128 (concat "\\(\\<\\(" org-scheduled-string
3129 "\\|" org-deadline-string
3130 "\\|" org-closed-string
3131 "\\|" org-clock-string "\\)\\)?"
3132 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3133 org-planning-or-clock-line-re
3134 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3135 "\\|" org-deadline-string
3136 "\\|" org-closed-string "\\|" org-clock-string
3137 "\\)\\>\\)")
3139 (org-compute-latex-and-specials-regexp)
3140 (org-set-font-lock-defaults))))
3142 (defun org-file-contents (file &optional noerror)
3143 "Return the contents of FILE, as a string."
3144 (if (or (not file)
3145 (not (file-readable-p file)))
3146 (if noerror
3147 (progn
3148 (message "Cannot read file %s" file)
3149 (ding) (sit-for 2)
3151 (error "Cannot read file %s" file))
3152 (with-temp-buffer
3153 (insert-file-contents file)
3154 (buffer-string))))
3156 (defun org-extract-log-state-settings (x)
3157 "Extract the log state setting from a TODO keyword string.
3158 This will extract info from a string like \"WAIT(w@/!)\"."
3159 (let (kw key log1 log2)
3160 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3161 (setq kw (match-string 1 x)
3162 key (and (match-end 2) (match-string 2 x))
3163 log1 (and (match-end 3) (match-string 3 x))
3164 log2 (and (match-end 4) (match-string 4 x)))
3165 (and (or log1 log2)
3166 (list kw
3167 (and log1 (if (equal log1 "!") 'time 'note))
3168 (and log2 (if (equal log2 "!") 'time 'note)))))))
3170 (defun org-remove-keyword-keys (list)
3171 "Remove a pair of parenthesis at the end of each string in LIST."
3172 (mapcar (lambda (x)
3173 (if (string-match "(.*)$" x)
3174 (substring x 0 (match-beginning 0))
3176 list))
3178 ;; FIXME: this could be done much better, using second characters etc.
3179 (defun org-assign-fast-keys (alist)
3180 "Assign fast keys to a keyword-key alist.
3181 Respect keys that are already there."
3182 (let (new e k c c1 c2 (char ?a))
3183 (while (setq e (pop alist))
3184 (cond
3185 ((equal e '(:startgroup)) (push e new))
3186 ((equal e '(:endgroup)) (push e new))
3188 (setq k (car e) c2 nil)
3189 (if (cdr e)
3190 (setq c (cdr e))
3191 ;; automatically assign a character.
3192 (setq c1 (string-to-char
3193 (downcase (substring
3194 k (if (= (string-to-char k) ?@) 1 0)))))
3195 (if (or (rassoc c1 new) (rassoc c1 alist))
3196 (while (or (rassoc char new) (rassoc char alist))
3197 (setq char (1+ char)))
3198 (setq c2 c1))
3199 (setq c (or c2 char)))
3200 (push (cons k c) new))))
3201 (nreverse new)))
3203 ;;; Some variables used in various places
3205 (defvar org-window-configuration nil
3206 "Used in various places to store a window configuration.")
3207 (defvar org-finish-function nil
3208 "Function to be called when `C-c C-c' is used.
3209 This is for getting out of special buffers like remember.")
3212 ;; FIXME: Occasionally check by commenting these, to make sure
3213 ;; no other functions uses these, forgetting to let-bind them.
3214 (defvar entry)
3215 (defvar state)
3216 (defvar last-state)
3217 (defvar date)
3218 (defvar description)
3220 ;; Defined somewhere in this file, but used before definition.
3221 (defvar org-html-entities)
3222 (defvar org-struct-menu)
3223 (defvar org-org-menu)
3224 (defvar org-tbl-menu)
3225 (defvar org-agenda-keymap)
3227 ;;;; Define the Org-mode
3229 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3230 (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."))
3233 ;; We use a before-change function to check if a table might need
3234 ;; an update.
3235 (defvar org-table-may-need-update t
3236 "Indicates that a table might need an update.
3237 This variable is set by `org-before-change-function'.
3238 `org-table-align' sets it back to nil.")
3239 (defun org-before-change-function (beg end)
3240 "Every change indicates that a table might need an update."
3241 (setq org-table-may-need-update t))
3242 (defvar org-mode-map)
3243 (defvar org-mode-hook nil)
3244 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3245 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3246 (defvar org-table-buffer-is-an nil)
3247 (defconst org-outline-regexp "\\*+ ")
3249 ;;;###autoload
3250 (define-derived-mode org-mode outline-mode "Org"
3251 "Outline-based notes management and organizer, alias
3252 \"Carsten's outline-mode for keeping track of everything.\"
3254 Org-mode develops organizational tasks around a NOTES file which
3255 contains information about projects as plain text. Org-mode is
3256 implemented on top of outline-mode, which is ideal to keep the content
3257 of large files well structured. It supports ToDo items, deadlines and
3258 time stamps, which magically appear in the diary listing of the Emacs
3259 calendar. Tables are easily created with a built-in table editor.
3260 Plain text URL-like links connect to websites, emails (VM), Usenet
3261 messages (Gnus), BBDB entries, and any files related to the project.
3262 For printing and sharing of notes, an Org-mode file (or a part of it)
3263 can be exported as a structured ASCII or HTML file.
3265 The following commands are available:
3267 \\{org-mode-map}"
3269 ;; Get rid of Outline menus, they are not needed
3270 ;; Need to do this here because define-derived-mode sets up
3271 ;; the keymap so late. Still, it is a waste to call this each time
3272 ;; we switch another buffer into org-mode.
3273 (if (featurep 'xemacs)
3274 (when (boundp 'outline-mode-menu-heading)
3275 ;; Assume this is Greg's port, it used easymenu
3276 (easy-menu-remove outline-mode-menu-heading)
3277 (easy-menu-remove outline-mode-menu-show)
3278 (easy-menu-remove outline-mode-menu-hide))
3279 (define-key org-mode-map [menu-bar headings] 'undefined)
3280 (define-key org-mode-map [menu-bar hide] 'undefined)
3281 (define-key org-mode-map [menu-bar show] 'undefined))
3283 (org-load-modules-maybe)
3284 (easy-menu-add org-org-menu)
3285 (easy-menu-add org-tbl-menu)
3286 (org-install-agenda-files-menu)
3287 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3288 (org-add-to-invisibility-spec '(org-cwidth))
3289 (when (featurep 'xemacs)
3290 (org-set-local 'line-move-ignore-invisible t))
3291 (org-set-local 'outline-regexp org-outline-regexp)
3292 (org-set-local 'outline-level 'org-outline-level)
3293 (when (and org-ellipsis
3294 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3295 (fboundp 'make-glyph-code))
3296 (unless org-display-table
3297 (setq org-display-table (make-display-table)))
3298 (set-display-table-slot
3299 org-display-table 4
3300 (vconcat (mapcar
3301 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3302 org-ellipsis)))
3303 (if (stringp org-ellipsis) org-ellipsis "..."))))
3304 (setq buffer-display-table org-display-table))
3305 (org-set-regexps-and-options)
3306 ;; Calc embedded
3307 (org-set-local 'calc-embedded-open-mode "# ")
3308 (modify-syntax-entry ?# "<")
3309 (modify-syntax-entry ?@ "w")
3310 (if org-startup-truncated (setq truncate-lines t))
3311 (org-set-local 'font-lock-unfontify-region-function
3312 'org-unfontify-region)
3313 ;; Activate before-change-function
3314 (org-set-local 'org-table-may-need-update t)
3315 (org-add-hook 'before-change-functions 'org-before-change-function nil
3316 'local)
3317 ;; Check for running clock before killing a buffer
3318 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3319 ;; Paragraphs and auto-filling
3320 (org-set-autofill-regexps)
3321 (setq indent-line-function 'org-indent-line-function)
3322 (org-update-radio-target-regexp)
3324 ;; Comment characters
3325 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3326 (org-set-local 'comment-padding " ")
3328 ;; Align options lines
3329 (org-set-local
3330 'align-mode-rules-list
3331 '((org-in-buffer-settings
3332 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3333 (modes . '(org-mode)))))
3335 ;; Imenu
3336 (org-set-local 'imenu-create-index-function
3337 'org-imenu-get-tree)
3339 ;; Make isearch reveal context
3340 (if (or (featurep 'xemacs)
3341 (not (boundp 'outline-isearch-open-invisible-function)))
3342 ;; Emacs 21 and XEmacs make use of the hook
3343 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3344 ;; Emacs 22 deals with this through a special variable
3345 (org-set-local 'outline-isearch-open-invisible-function
3346 (lambda (&rest ignore) (org-show-context 'isearch))))
3348 ;; If empty file that did not turn on org-mode automatically, make it to.
3349 (if (and org-insert-mode-line-in-empty-file
3350 (interactive-p)
3351 (= (point-min) (point-max)))
3352 (insert "# -*- mode: org -*-\n\n"))
3354 (unless org-inhibit-startup
3355 (when org-startup-align-all-tables
3356 (let ((bmp (buffer-modified-p)))
3357 (org-table-map-tables 'org-table-align)
3358 (set-buffer-modified-p bmp)))
3359 (org-set-startup-visibility)))
3361 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3363 (defun org-current-time ()
3364 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3365 (if (> (car org-time-stamp-rounding-minutes) 1)
3366 (let ((r (car org-time-stamp-rounding-minutes))
3367 (time (decode-time)))
3368 (apply 'encode-time
3369 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3370 (nthcdr 2 time))))
3371 (current-time)))
3373 ;;;; Font-Lock stuff, including the activators
3375 (defvar org-mouse-map (make-sparse-keymap))
3376 (org-defkey org-mouse-map
3377 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3378 (org-defkey org-mouse-map
3379 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3380 (when org-mouse-1-follows-link
3381 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3382 (when org-tab-follows-link
3383 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3384 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3385 (when org-return-follows-link
3386 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
3387 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
3389 (require 'font-lock)
3391 (defconst org-non-link-chars "]\t\n\r<>")
3392 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3393 "shell" "elisp"))
3394 (defvar org-link-types-re nil
3395 "Matches a link that has a url-like prefix like \"http:\"")
3396 (defvar org-link-re-with-space nil
3397 "Matches a link with spaces, optional angular brackets around it.")
3398 (defvar org-link-re-with-space2 nil
3399 "Matches a link with spaces, optional angular brackets around it.")
3400 (defvar org-angle-link-re nil
3401 "Matches link with angular brackets, spaces are allowed.")
3402 (defvar org-plain-link-re nil
3403 "Matches plain link, without spaces.")
3404 (defvar org-bracket-link-regexp nil
3405 "Matches a link in double brackets.")
3406 (defvar org-bracket-link-analytic-regexp nil
3407 "Regular expression used to analyze links.
3408 Here is what the match groups contain after a match:
3409 1: http:
3410 2: http
3411 3: path
3412 4: [desc]
3413 5: desc")
3414 (defvar org-any-link-re nil
3415 "Regular expression matching any link.")
3417 (defun org-make-link-regexps ()
3418 "Update the link regular expressions.
3419 This should be called after the variable `org-link-types' has changed."
3420 (setq org-link-types-re
3421 (concat
3422 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3423 org-link-re-with-space
3424 (concat
3425 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3426 "\\([^" org-non-link-chars " ]"
3427 "[^" org-non-link-chars "]*"
3428 "[^" org-non-link-chars " ]\\)>?")
3429 org-link-re-with-space2
3430 (concat
3431 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3432 "\\([^" org-non-link-chars " ]"
3433 "[^\t\n\r]*"
3434 "[^" org-non-link-chars " ]\\)>?")
3435 org-angle-link-re
3436 (concat
3437 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3438 "\\([^" org-non-link-chars " ]"
3439 "[^" org-non-link-chars "]*"
3440 "\\)>")
3441 org-plain-link-re
3442 (concat
3443 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3444 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3445 org-bracket-link-regexp
3446 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3447 org-bracket-link-analytic-regexp
3448 (concat
3449 "\\[\\["
3450 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3451 "\\([^]]+\\)"
3452 "\\]"
3453 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3454 "\\]")
3455 org-any-link-re
3456 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3457 org-angle-link-re "\\)\\|\\("
3458 org-plain-link-re "\\)")))
3460 (org-make-link-regexps)
3462 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
3463 "Regular expression for fast time stamp matching.")
3464 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
3465 "Regular expression for fast time stamp matching.")
3466 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3467 "Regular expression matching time strings for analysis.
3468 This one does not require the space after the date, so it can be used
3469 on a string that terminates immediately after the date.")
3470 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3471 "Regular expression matching time strings for analysis.")
3472 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
3473 "Regular expression matching time stamps, with groups.")
3474 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
3475 "Regular expression matching time stamps (also [..]), with groups.")
3476 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3477 "Regular expression matching a time stamp range.")
3478 (defconst org-tr-regexp-both
3479 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3480 "Regular expression matching a time stamp range.")
3481 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3482 org-ts-regexp "\\)?")
3483 "Regular expression matching a time stamp or time stamp range.")
3484 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3485 org-ts-regexp-both "\\)?")
3486 "Regular expression matching a time stamp or time stamp range.
3487 The time stamps may be either active or inactive.")
3489 (defvar org-emph-face nil)
3491 (defun org-do-emphasis-faces (limit)
3492 "Run through the buffer and add overlays to links."
3493 (let (rtn)
3494 (while (and (not rtn) (re-search-forward org-emph-re limit t))
3495 (if (not (= (char-after (match-beginning 3))
3496 (char-after (match-beginning 4))))
3497 (progn
3498 (setq rtn t)
3499 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3500 'face
3501 (nth 1 (assoc (match-string 3)
3502 org-emphasis-alist)))
3503 (add-text-properties (match-beginning 2) (match-end 2)
3504 '(font-lock-multiline t))
3505 (when org-hide-emphasis-markers
3506 (add-text-properties (match-end 4) (match-beginning 5)
3507 '(invisible org-link))
3508 (add-text-properties (match-beginning 3) (match-end 3)
3509 '(invisible org-link)))))
3510 (backward-char 1))
3511 rtn))
3513 (defun org-emphasize (&optional char)
3514 "Insert or change an emphasis, i.e. a font like bold or italic.
3515 If there is an active region, change that region to a new emphasis.
3516 If there is no region, just insert the marker characters and position
3517 the cursor between them.
3518 CHAR should be either the marker character, or the first character of the
3519 HTML tag associated with that emphasis. If CHAR is a space, the means
3520 to remove the emphasis of the selected region.
3521 If char is not given (for example in an interactive call) it
3522 will be prompted for."
3523 (interactive)
3524 (let ((eal org-emphasis-alist) e det
3525 (erc org-emphasis-regexp-components)
3526 (prompt "")
3527 (string "") beg end move tag c s)
3528 (if (org-region-active-p)
3529 (setq beg (region-beginning) end (region-end)
3530 string (buffer-substring beg end))
3531 (setq move t))
3533 (while (setq e (pop eal))
3534 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
3535 c (aref tag 0))
3536 (push (cons c (string-to-char (car e))) det)
3537 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
3538 (substring tag 1)))))
3539 (setq det (nreverse det))
3540 (unless char
3541 (message "%s" (concat "Emphasis marker or tag:" prompt))
3542 (setq char (read-char-exclusive)))
3543 (setq char (or (cdr (assoc char det)) char))
3544 (if (equal char ?\ )
3545 (setq s "" move nil)
3546 (unless (assoc (char-to-string char) org-emphasis-alist)
3547 (error "No such emphasis marker: \"%c\"" char))
3548 (setq s (char-to-string char)))
3549 (while (and (> (length string) 1)
3550 (equal (substring string 0 1) (substring string -1))
3551 (assoc (substring string 0 1) org-emphasis-alist))
3552 (setq string (substring string 1 -1)))
3553 (setq string (concat s string s))
3554 (if beg (delete-region beg end))
3555 (unless (or (bolp)
3556 (string-match (concat "[" (nth 0 erc) "\n]")
3557 (char-to-string (char-before (point)))))
3558 (insert " "))
3559 (unless (string-match (concat "[" (nth 1 erc) "\n]")
3560 (char-to-string (char-after (point))))
3561 (insert " ") (backward-char 1))
3562 (insert string)
3563 (and move (backward-char 1))))
3565 (defconst org-nonsticky-props
3566 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
3569 (defun org-activate-plain-links (limit)
3570 "Run through the buffer and add overlays to links."
3571 (catch 'exit
3572 (let (f)
3573 (while (re-search-forward org-plain-link-re limit t)
3574 (setq f (get-text-property (match-beginning 0) 'face))
3575 (if (or (eq f 'org-tag)
3576 (and (listp f) (memq 'org-tag f)))
3578 (add-text-properties (match-beginning 0) (match-end 0)
3579 (list 'mouse-face 'highlight
3580 'rear-nonsticky org-nonsticky-props
3581 'keymap org-mouse-map
3583 (throw 'exit t))))))
3585 (defun org-activate-code (limit)
3586 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
3587 (progn
3588 (remove-text-properties (match-beginning 0) (match-end 0)
3589 '(display t invisible t intangible t))
3590 t)))
3592 (defun org-activate-angle-links (limit)
3593 "Run through the buffer and add overlays to links."
3594 (if (re-search-forward org-angle-link-re limit t)
3595 (progn
3596 (add-text-properties (match-beginning 0) (match-end 0)
3597 (list 'mouse-face 'highlight
3598 'rear-nonsticky org-nonsticky-props
3599 'keymap org-mouse-map
3601 t)))
3603 (defun org-activate-bracket-links (limit)
3604 "Run through the buffer and add overlays to bracketed links."
3605 (if (re-search-forward org-bracket-link-regexp limit t)
3606 (let* ((help (concat "LINK: "
3607 (org-match-string-no-properties 1)))
3608 ;; FIXME: above we should remove the escapes.
3609 ;; but that requires another match, protecting match data,
3610 ;; a lot of overhead for font-lock.
3611 (ip (org-maybe-intangible
3612 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
3613 'keymap org-mouse-map 'mouse-face 'highlight
3614 'font-lock-multiline t 'help-echo help)))
3615 (vp (list 'rear-nonsticky org-nonsticky-props
3616 'keymap org-mouse-map 'mouse-face 'highlight
3617 ' font-lock-multiline t 'help-echo help)))
3618 ;; We need to remove the invisible property here. Table narrowing
3619 ;; may have made some of this invisible.
3620 (remove-text-properties (match-beginning 0) (match-end 0)
3621 '(invisible nil))
3622 (if (match-end 3)
3623 (progn
3624 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3625 (add-text-properties (match-beginning 3) (match-end 3) vp)
3626 (add-text-properties (match-end 3) (match-end 0) ip))
3627 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3628 (add-text-properties (match-beginning 1) (match-end 1) vp)
3629 (add-text-properties (match-end 1) (match-end 0) ip))
3630 t)))
3632 (defun org-activate-dates (limit)
3633 "Run through the buffer and add overlays to dates."
3634 (if (re-search-forward org-tsr-regexp-both limit t)
3635 (progn
3636 (add-text-properties (match-beginning 0) (match-end 0)
3637 (list 'mouse-face 'highlight
3638 'rear-nonsticky org-nonsticky-props
3639 'keymap org-mouse-map))
3640 (when org-display-custom-times
3641 (if (match-end 3)
3642 (org-display-custom-time (match-beginning 3) (match-end 3)))
3643 (org-display-custom-time (match-beginning 1) (match-end 1)))
3644 t)))
3646 (defvar org-target-link-regexp nil
3647 "Regular expression matching radio targets in plain text.")
3648 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3649 "Regular expression matching a link target.")
3650 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3651 "Regular expression matching a radio target.")
3652 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
3653 "Regular expression matching any target.")
3655 (defun org-activate-target-links (limit)
3656 "Run through the buffer and add overlays to target matches."
3657 (when org-target-link-regexp
3658 (let ((case-fold-search t))
3659 (if (re-search-forward org-target-link-regexp limit t)
3660 (progn
3661 (add-text-properties (match-beginning 0) (match-end 0)
3662 (list 'mouse-face 'highlight
3663 'rear-nonsticky org-nonsticky-props
3664 'keymap org-mouse-map
3665 'help-echo "Radio target link"
3666 'org-linked-text t))
3667 t)))))
3669 (defun org-update-radio-target-regexp ()
3670 "Find all radio targets in this file and update the regular expression."
3671 (interactive)
3672 (when (memq 'radio org-activate-links)
3673 (setq org-target-link-regexp
3674 (org-make-target-link-regexp (org-all-targets 'radio)))
3675 (org-restart-font-lock)))
3677 (defun org-hide-wide-columns (limit)
3678 (let (s e)
3679 (setq s (text-property-any (point) (or limit (point-max))
3680 'org-cwidth t))
3681 (when s
3682 (setq e (next-single-property-change s 'org-cwidth))
3683 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
3684 (goto-char e)
3685 t)))
3687 (defvar org-latex-and-specials-regexp nil
3688 "Regular expression for highlighting export special stuff.")
3689 (defvar org-match-substring-regexp)
3690 (defvar org-match-substring-with-braces-regexp)
3691 (defvar org-export-html-special-string-regexps)
3693 (defun org-compute-latex-and-specials-regexp ()
3694 "Compute regular expression for stuff treated specially by exporters."
3695 (if (not org-highlight-latex-fragments-and-specials)
3696 (org-set-local 'org-latex-and-specials-regexp nil)
3697 (require 'org-exp)
3698 (let*
3699 ((matchers (plist-get org-format-latex-options :matchers))
3700 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
3701 org-latex-regexps)))
3702 (options (org-combine-plists (org-default-export-plist)
3703 (org-infile-export-plist)))
3704 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
3705 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
3706 (org-export-with-TeX-macros (plist-get options :TeX-macros))
3707 (org-export-html-expand (plist-get options :expand-quoted-html))
3708 (org-export-with-special-strings (plist-get options :special-strings))
3709 (re-sub
3710 (cond
3711 ((equal org-export-with-sub-superscripts '{})
3712 (list org-match-substring-with-braces-regexp))
3713 (org-export-with-sub-superscripts
3714 (list org-match-substring-regexp))
3715 (t nil)))
3716 (re-latex
3717 (if org-export-with-LaTeX-fragments
3718 (mapcar (lambda (x) (nth 1 x)) latexs)))
3719 (re-macros
3720 (if org-export-with-TeX-macros
3721 (list (concat "\\\\"
3722 (regexp-opt
3723 (append (mapcar 'car org-html-entities)
3724 (if (boundp 'org-latex-entities)
3725 org-latex-entities nil))
3726 'words))) ; FIXME
3728 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
3729 (re-special (if org-export-with-special-strings
3730 (mapcar (lambda (x) (car x))
3731 org-export-html-special-string-regexps)))
3732 (re-rest
3733 (delq nil
3734 (list
3735 (if org-export-html-expand "@<[^>\n]+>")
3736 ))))
3737 (org-set-local
3738 'org-latex-and-specials-regexp
3739 (mapconcat 'identity (append re-latex re-sub re-macros re-special
3740 re-rest) "\\|")))))
3742 (defun org-do-latex-and-special-faces (limit)
3743 "Run through the buffer and add overlays to links."
3744 (when org-latex-and-specials-regexp
3745 (let (rtn d)
3746 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
3747 limit t))
3748 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
3749 'face))
3750 '(org-code org-verbatim underline)))
3751 (progn
3752 (setq rtn t
3753 d (cond ((member (char-after (1+ (match-beginning 0)))
3754 '(?_ ?^)) 1)
3755 (t 0)))
3756 (font-lock-prepend-text-property
3757 (+ d (match-beginning 0)) (match-end 0)
3758 'face 'org-latex-and-export-specials)
3759 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
3760 '(font-lock-multiline t)))))
3761 rtn)))
3763 (defun org-restart-font-lock ()
3764 "Restart font-lock-mode, to force refontification."
3765 (when (and (boundp 'font-lock-mode) font-lock-mode)
3766 (font-lock-mode -1)
3767 (font-lock-mode 1)))
3769 (defun org-all-targets (&optional radio)
3770 "Return a list of all targets in this file.
3771 With optional argument RADIO, only find radio targets."
3772 (let ((re (if radio org-radio-target-regexp org-target-regexp))
3773 rtn)
3774 (save-excursion
3775 (goto-char (point-min))
3776 (while (re-search-forward re nil t)
3777 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
3778 rtn)))
3780 (defun org-make-target-link-regexp (targets)
3781 "Make regular expression matching all strings in TARGETS.
3782 The regular expression finds the targets also if there is a line break
3783 between words."
3784 (and targets
3785 (concat
3786 "\\<\\("
3787 (mapconcat
3788 (lambda (x)
3789 (while (string-match " +" x)
3790 (setq x (replace-match "\\s-+" t t x)))
3792 targets
3793 "\\|")
3794 "\\)\\>")))
3796 (defun org-activate-tags (limit)
3797 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
3798 (progn
3799 (add-text-properties (match-beginning 1) (match-end 1)
3800 (list 'mouse-face 'highlight
3801 'rear-nonsticky org-nonsticky-props
3802 'keymap org-mouse-map))
3803 t)))
3805 (defun org-outline-level ()
3806 (save-excursion
3807 (looking-at outline-regexp)
3808 (if (match-beginning 1)
3809 (+ (org-get-string-indentation (match-string 1)) 1000)
3810 (1- (- (match-end 0) (match-beginning 0))))))
3812 (defvar org-font-lock-keywords nil)
3814 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
3815 "Regular expression matching a property line.")
3817 (defvar org-font-lock-hook nil
3818 "Functions to be called for special font lock stuff.")
3820 (defun org-font-lock-hook (limit)
3821 (run-hook-with-args 'org-font-lock-hook limit))
3823 (defun org-set-font-lock-defaults ()
3824 (let* ((em org-fontify-emphasized-text)
3825 (lk org-activate-links)
3826 (org-font-lock-extra-keywords
3827 (list
3828 ;; Call the hook
3829 '(org-font-lock-hook)
3830 ;; Headlines
3831 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
3832 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
3833 ;; Table lines
3834 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
3835 (1 'org-table t))
3836 ;; Table internals
3837 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
3838 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
3839 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
3840 ;; Drawers
3841 (list org-drawer-regexp '(0 'org-special-keyword t))
3842 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
3843 ;; Properties
3844 (list org-property-re
3845 '(1 'org-special-keyword t)
3846 '(3 'org-property-value t))
3847 (if org-format-transports-properties-p
3848 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
3849 ;; Links
3850 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
3851 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
3852 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
3853 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
3854 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
3855 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
3856 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
3857 '(org-hide-wide-columns (0 nil append))
3858 ;; TODO lines
3859 (list (concat "^\\*+[ \t]+" org-todo-regexp)
3860 '(1 (org-get-todo-face 1) t))
3861 ;; DONE
3862 (if org-fontify-done-headline
3863 (list (concat "^[*]+ +\\<\\("
3864 (mapconcat 'regexp-quote org-done-keywords "\\|")
3865 "\\)\\(.*\\)")
3866 '(2 'org-headline-done t))
3867 nil)
3868 ;; Priorities
3869 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
3870 ;; Special keywords
3871 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
3872 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
3873 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
3874 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
3875 ;; Emphasis
3876 (if em
3877 (if (featurep 'xemacs)
3878 '(org-do-emphasis-faces (0 nil append))
3879 '(org-do-emphasis-faces)))
3880 ;; Checkboxes
3881 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
3882 2 'bold prepend)
3883 (if org-provide-checkbox-statistics
3884 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
3885 (0 (org-get-checkbox-statistics-face) t)))
3886 ;; Description list items
3887 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
3888 2 'bold prepend)
3889 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
3890 '(1 'org-archived prepend))
3891 ;; Specials
3892 '(org-do-latex-and-special-faces)
3893 ;; Code
3894 '(org-activate-code (1 'org-code t))
3895 ;; COMMENT
3896 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
3897 "\\|" org-quote-string "\\)\\>")
3898 '(1 'org-special-keyword t))
3899 '("^#.*" (0 'font-lock-comment-face t))
3901 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
3902 ;; Now set the full font-lock-keywords
3903 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
3904 (org-set-local 'font-lock-defaults
3905 '(org-font-lock-keywords t nil nil backward-paragraph))
3906 (kill-local-variable 'font-lock-keywords) nil))
3908 (defvar org-m nil)
3909 (defvar org-l nil)
3910 (defvar org-f nil)
3911 (defun org-get-level-face (n)
3912 "Get the right face for match N in font-lock matching of healdines."
3913 (setq org-l (- (match-end 2) (match-beginning 1) 1))
3914 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
3915 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
3916 (cond
3917 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
3918 ((eq n 2) org-f)
3919 (t (if org-level-color-stars-only nil org-f))))
3921 (defun org-get-todo-face (kwd)
3922 "Get the right face for a TODO keyword KWD.
3923 If KWD is a number, get the corresponding match group."
3924 (if (numberp kwd) (setq kwd (match-string kwd)))
3925 (or (cdr (assoc kwd org-todo-keyword-faces))
3926 (and (member kwd org-done-keywords) 'org-done)
3927 'org-todo))
3929 (defun org-unfontify-region (beg end &optional maybe_loudly)
3930 "Remove fontification and activation overlays from links."
3931 (font-lock-default-unfontify-region beg end)
3932 (let* ((buffer-undo-list t)
3933 (inhibit-read-only t) (inhibit-point-motion-hooks t)
3934 (inhibit-modification-hooks t)
3935 deactivate-mark buffer-file-name buffer-file-truename)
3936 (remove-text-properties beg end
3937 '(mouse-face t keymap t org-linked-text t
3938 invisible t intangible t))))
3940 ;;;; Visibility cycling, including org-goto and indirect buffer
3942 ;;; Cycling
3944 (defvar org-cycle-global-status nil)
3945 (make-variable-buffer-local 'org-cycle-global-status)
3946 (defvar org-cycle-subtree-status nil)
3947 (make-variable-buffer-local 'org-cycle-subtree-status)
3949 ;;;###autoload
3950 (defun org-cycle (&optional arg)
3951 "Visibility cycling for Org-mode.
3953 - When this function is called with a prefix argument, rotate the entire
3954 buffer through 3 states (global cycling)
3955 1. OVERVIEW: Show only top-level headlines.
3956 2. CONTENTS: Show all headlines of all levels, but no body text.
3957 3. SHOW ALL: Show everything.
3958 When called with two C-u C-u prefixes, switch to the startup visibility,
3959 determined by the variable `org-startup-folded', and by any VISIBILITY
3960 properties in the buffer.
3961 When called with three C-u C-u C-u prefixed, show the entire buffer,
3962 including drawers.
3964 - When point is at the beginning of a headline, rotate the subtree started
3965 by this line through 3 different states (local cycling)
3966 1. FOLDED: Only the main headline is shown.
3967 2. CHILDREN: The main headline and the direct children are shown.
3968 From this state, you can move to one of the children
3969 and zoom in further.
3970 3. SUBTREE: Show the entire subtree, including body text.
3972 - When there is a numeric prefix, go up to a heading with level ARG, do
3973 a `show-subtree' and return to the previous cursor position. If ARG
3974 is negative, go up that many levels.
3976 - When point is not at the beginning of a headline, execute the global
3977 binding for TAB, which is re-indenting the line. See the option
3978 `org-cycle-emulate-tab' for details.
3980 - Special case: if point is at the beginning of the buffer and there is
3981 no headline in line 1, this function will act as if called with prefix arg.
3982 But only if also the variable `org-cycle-global-at-bob' is t."
3983 (interactive "P")
3984 (org-load-modules-maybe)
3985 (let* ((outline-regexp
3986 (if (and (org-mode-p) org-cycle-include-plain-lists)
3987 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
3988 outline-regexp))
3989 (bob-special (and org-cycle-global-at-bob (bobp)
3990 (not (looking-at outline-regexp))))
3991 (org-cycle-hook
3992 (if bob-special
3993 (delq 'org-optimize-window-after-visibility-change
3994 (copy-sequence org-cycle-hook))
3995 org-cycle-hook))
3996 (pos (point)))
3998 (if (or bob-special (equal arg '(4)))
3999 ;; special case: use global cycling
4000 (setq arg t))
4002 (cond
4004 ((equal arg '(16))
4005 (org-set-startup-visibility)
4006 (message "Startup visibility, plus VISIBILITY properties"))
4008 ((equal arg '(64))
4009 (show-all)
4010 (message "Entire buffer visible, including drawers"))
4012 ((org-at-table-p 'any)
4013 ;; Enter the table or move to the next field in the table
4014 (or (org-table-recognize-table.el)
4015 (progn
4016 (if arg (org-table-edit-field t)
4017 (org-table-justify-field-maybe)
4018 (call-interactively 'org-table-next-field)))))
4020 ((eq arg t) ;; Global cycling
4022 (cond
4023 ((and (eq last-command this-command)
4024 (eq org-cycle-global-status 'overview))
4025 ;; We just created the overview - now do table of contents
4026 ;; This can be slow in very large buffers, so indicate action
4027 (message "CONTENTS...")
4028 (org-content)
4029 (message "CONTENTS...done")
4030 (setq org-cycle-global-status 'contents)
4031 (run-hook-with-args 'org-cycle-hook 'contents))
4033 ((and (eq last-command this-command)
4034 (eq org-cycle-global-status 'contents))
4035 ;; We just showed the table of contents - now show everything
4036 (show-all)
4037 (message "SHOW ALL")
4038 (setq org-cycle-global-status 'all)
4039 (run-hook-with-args 'org-cycle-hook 'all))
4042 ;; Default action: go to overview
4043 (org-overview)
4044 (message "OVERVIEW")
4045 (setq org-cycle-global-status 'overview)
4046 (run-hook-with-args 'org-cycle-hook 'overview))))
4048 ((and org-drawers org-drawer-regexp
4049 (save-excursion
4050 (beginning-of-line 1)
4051 (looking-at org-drawer-regexp)))
4052 ;; Toggle block visibility
4053 (org-flag-drawer
4054 (not (get-char-property (match-end 0) 'invisible))))
4056 ((integerp arg)
4057 ;; Show-subtree, ARG levels up from here.
4058 (save-excursion
4059 (org-back-to-heading)
4060 (outline-up-heading (if (< arg 0) (- arg)
4061 (- (funcall outline-level) arg)))
4062 (org-show-subtree)))
4064 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4065 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4066 ;; At a heading: rotate between three different views
4067 (org-back-to-heading)
4068 (let ((goal-column 0) eoh eol eos)
4069 ;; First, some boundaries
4070 (save-excursion
4071 (org-back-to-heading)
4072 (save-excursion
4073 (beginning-of-line 2)
4074 (while (and (not (eobp)) ;; this is like `next-line'
4075 (get-char-property (1- (point)) 'invisible))
4076 (beginning-of-line 2)) (setq eol (point)))
4077 (outline-end-of-heading) (setq eoh (point))
4078 (org-end-of-subtree t)
4079 (unless (eobp)
4080 (skip-chars-forward " \t\n")
4081 (beginning-of-line 1) ; in case this is an item
4083 (setq eos (1- (point))))
4084 ;; Find out what to do next and set `this-command'
4085 (cond
4086 ((= eos eoh)
4087 ;; Nothing is hidden behind this heading
4088 (message "EMPTY ENTRY")
4089 (setq org-cycle-subtree-status nil)
4090 (save-excursion
4091 (goto-char eos)
4092 (outline-next-heading)
4093 (if (org-invisible-p) (org-flag-heading nil))))
4094 ((or (>= eol eos)
4095 (not (string-match "\\S-" (buffer-substring eol eos))))
4096 ;; Entire subtree is hidden in one line: open it
4097 (org-show-entry)
4098 (show-children)
4099 (message "CHILDREN")
4100 (save-excursion
4101 (goto-char eos)
4102 (outline-next-heading)
4103 (if (org-invisible-p) (org-flag-heading nil)))
4104 (setq org-cycle-subtree-status 'children)
4105 (run-hook-with-args 'org-cycle-hook 'children))
4106 ((and (eq last-command this-command)
4107 (eq org-cycle-subtree-status 'children))
4108 ;; We just showed the children, now show everything.
4109 (org-show-subtree)
4110 (message "SUBTREE")
4111 (setq org-cycle-subtree-status 'subtree)
4112 (run-hook-with-args 'org-cycle-hook 'subtree))
4114 ;; Default action: hide the subtree.
4115 (hide-subtree)
4116 (message "FOLDED")
4117 (setq org-cycle-subtree-status 'folded)
4118 (run-hook-with-args 'org-cycle-hook 'folded)))))
4120 ;; TAB emulation and template completion
4121 (buffer-read-only (org-back-to-heading))
4123 ((org-try-structure-completion))
4125 ((org-try-cdlatex-tab))
4127 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4128 (or (not (bolp))
4129 (not (looking-at outline-regexp))))
4130 (call-interactively (global-key-binding "\t")))
4132 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4133 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4134 (or (and (eq org-cycle-emulate-tab 'white)
4135 (= (match-end 0) (point-at-eol)))
4136 (and (eq org-cycle-emulate-tab 'whitestart)
4137 (>= (match-end 0) pos))))
4139 (eq org-cycle-emulate-tab t))
4140 (call-interactively (global-key-binding "\t")))
4142 (t (save-excursion
4143 (org-back-to-heading)
4144 (org-cycle))))))
4146 ;;;###autoload
4147 (defun org-global-cycle (&optional arg)
4148 "Cycle the global visibility. For details see `org-cycle'.
4149 With C-u prefix arg, switch to startup visibility.
4150 With a numeric prefix, show all headlines up to that level."
4151 (interactive "P")
4152 (let ((org-cycle-include-plain-lists
4153 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4154 (cond
4155 ((integerp arg)
4156 (show-all)
4157 (hide-sublevels arg)
4158 (setq org-cycle-global-status 'contents))
4159 ((equal arg '(4))
4160 (org-set-startup-visibility)
4161 (message "Startup visibility, plus VISIBILITY properties."))
4163 (org-cycle '(4))))))
4165 (defun org-set-startup-visibility ()
4166 "Set the visibility required by startup options and properties."
4167 (cond
4168 ((eq org-startup-folded t)
4169 (org-cycle '(4)))
4170 ((eq org-startup-folded 'content)
4171 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4172 (org-cycle '(4)) (org-cycle '(4)))))
4173 (org-set-visibility-according-to-property 'no-cleanup)
4174 (org-cycle-hide-archived-subtrees 'all)
4175 (org-cycle-hide-drawers 'all)
4176 (org-cycle-show-empty-lines 'all))
4178 (defun org-set-visibility-according-to-property (&optional no-cleanup)
4179 "Switch subtree visibilities according to :VISIBILITY: property."
4180 (interactive)
4181 (let (state)
4182 (save-excursion
4183 (goto-char (point-min))
4184 (while (re-search-forward
4185 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
4186 nil t)
4187 (setq state (match-string 1))
4188 (save-excursion
4189 (org-back-to-heading t)
4190 (hide-subtree)
4191 (org-reveal)
4192 (cond
4193 ((equal state '("fold" "folded"))
4194 (hide-subtree))
4195 ((equal state "children")
4196 (org-show-hidden-entry)
4197 (show-children))
4198 ((equal state "content")
4199 (save-excursion
4200 (save-restriction
4201 (org-narrow-to-subtree)
4202 (org-content))))
4203 ((member state '("all" "showall"))
4204 (show-subtree)))))
4205 (unless no-cleanup
4206 (org-cycle-hide-archived-subtrees 'all)
4207 (org-cycle-hide-drawers 'all)
4208 (org-cycle-show-empty-lines 'all)))))
4210 (defun org-overview ()
4211 "Switch to overview mode, shoing only top-level headlines.
4212 Really, this shows all headlines with level equal or greater than the level
4213 of the first headline in the buffer. This is important, because if the
4214 first headline is not level one, then (hide-sublevels 1) gives confusing
4215 results."
4216 (interactive)
4217 (let ((level (save-excursion
4218 (goto-char (point-min))
4219 (if (re-search-forward (concat "^" outline-regexp) nil t)
4220 (progn
4221 (goto-char (match-beginning 0))
4222 (funcall outline-level))))))
4223 (and level (hide-sublevels level))))
4225 (defun org-content (&optional arg)
4226 "Show all headlines in the buffer, like a table of contents.
4227 With numerical argument N, show content up to level N."
4228 (interactive "P")
4229 (save-excursion
4230 ;; Visit all headings and show their offspring
4231 (and (integerp arg) (org-overview))
4232 (goto-char (point-max))
4233 (catch 'exit
4234 (while (and (progn (condition-case nil
4235 (outline-previous-visible-heading 1)
4236 (error (goto-char (point-min))))
4238 (looking-at outline-regexp))
4239 (if (integerp arg)
4240 (show-children (1- arg))
4241 (show-branches))
4242 (if (bobp) (throw 'exit nil))))))
4245 (defun org-optimize-window-after-visibility-change (state)
4246 "Adjust the window after a change in outline visibility.
4247 This function is the default value of the hook `org-cycle-hook'."
4248 (when (get-buffer-window (current-buffer))
4249 (cond
4250 ; ((eq state 'overview) (org-first-headline-recenter 1))
4251 ; ((eq state 'overview) (org-beginning-of-line))
4252 ((eq state 'content) nil)
4253 ((eq state 'all) nil)
4254 ((eq state 'folded) nil)
4255 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4256 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4258 (defun org-compact-display-after-subtree-move ()
4259 (let (beg end)
4260 (save-excursion
4261 (if (org-up-heading-safe)
4262 (progn
4263 (hide-subtree)
4264 (show-entry)
4265 (show-children)
4266 (org-cycle-show-empty-lines 'children)
4267 (org-cycle-hide-drawers 'children))
4268 (org-overview)))))
4270 (defun org-cycle-show-empty-lines (state)
4271 "Show empty lines above all visible headlines.
4272 The region to be covered depends on STATE when called through
4273 `org-cycle-hook'. Lisp program can use t for STATE to get the
4274 entire buffer covered. Note that an empty line is only shown if there
4275 are at least `org-cycle-separator-lines' empty lines before the headeline."
4276 (when (> org-cycle-separator-lines 0)
4277 (save-excursion
4278 (let* ((n org-cycle-separator-lines)
4279 (re (cond
4280 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
4281 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
4282 (t (let ((ns (number-to-string (- n 2))))
4283 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
4284 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
4285 beg end)
4286 (cond
4287 ((memq state '(overview contents t))
4288 (setq beg (point-min) end (point-max)))
4289 ((memq state '(children folded))
4290 (setq beg (point) end (progn (org-end-of-subtree t t)
4291 (beginning-of-line 2)
4292 (point)))))
4293 (when beg
4294 (goto-char beg)
4295 (while (re-search-forward re end t)
4296 (if (not (get-char-property (match-end 1) 'invisible))
4297 (outline-flag-region
4298 (match-beginning 1) (match-end 1) nil)))))))
4299 ;; Never hide empty lines at the end of the file.
4300 (save-excursion
4301 (goto-char (point-max))
4302 (outline-previous-heading)
4303 (outline-end-of-heading)
4304 (if (and (looking-at "[ \t\n]+")
4305 (= (match-end 0) (point-max)))
4306 (outline-flag-region (point) (match-end 0) nil))))
4308 (defun org-show-empty-lines-in-parent ()
4309 "Move to the parent and re-show empty lines before visible headlines."
4310 (save-excursion
4311 (let ((context (if (org-up-heading-safe) 'children 'overview)))
4312 (org-cycle-show-empty-lines context))))
4314 (defun org-cycle-hide-drawers (state)
4315 "Re-hide all drawers after a visibility state change."
4316 (when (and (org-mode-p)
4317 (not (memq state '(overview folded))))
4318 (save-excursion
4319 (let* ((globalp (memq state '(contents all)))
4320 (beg (if globalp (point-min) (point)))
4321 (end (if globalp (point-max) (org-end-of-subtree t))))
4322 (goto-char beg)
4323 (while (re-search-forward org-drawer-regexp end t)
4324 (org-flag-drawer t))))))
4326 (defun org-flag-drawer (flag)
4327 (save-excursion
4328 (beginning-of-line 1)
4329 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
4330 (let ((b (match-end 0))
4331 (outline-regexp org-outline-regexp))
4332 (if (re-search-forward
4333 "^[ \t]*:END:"
4334 (save-excursion (outline-next-heading) (point)) t)
4335 (outline-flag-region b (point-at-eol) flag)
4336 (error ":END: line missing"))))))
4338 (defun org-subtree-end-visible-p ()
4339 "Is the end of the current subtree visible?"
4340 (pos-visible-in-window-p
4341 (save-excursion (org-end-of-subtree t) (point))))
4343 (defun org-first-headline-recenter (&optional N)
4344 "Move cursor to the first headline and recenter the headline.
4345 Optional argument N means, put the headline into the Nth line of the window."
4346 (goto-char (point-min))
4347 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4348 (beginning-of-line)
4349 (recenter (prefix-numeric-value N))))
4351 ;;; Org-goto
4353 (defvar org-goto-window-configuration nil)
4354 (defvar org-goto-marker nil)
4355 (defvar org-goto-map
4356 (let ((map (make-sparse-keymap)))
4357 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
4358 (while (setq cmd (pop cmds))
4359 (substitute-key-definition cmd cmd map global-map)))
4360 (suppress-keymap map)
4361 (org-defkey map "\C-m" 'org-goto-ret)
4362 (org-defkey map [(return)] 'org-goto-ret)
4363 (org-defkey map [(left)] 'org-goto-left)
4364 (org-defkey map [(right)] 'org-goto-right)
4365 (org-defkey map [(control ?g)] 'org-goto-quit)
4366 (org-defkey map "\C-i" 'org-cycle)
4367 (org-defkey map [(tab)] 'org-cycle)
4368 (org-defkey map [(down)] 'outline-next-visible-heading)
4369 (org-defkey map [(up)] 'outline-previous-visible-heading)
4370 (if org-goto-auto-isearch
4371 (if (fboundp 'define-key-after)
4372 (define-key-after map [t] 'org-goto-local-auto-isearch)
4373 nil)
4374 (org-defkey map "q" 'org-goto-quit)
4375 (org-defkey map "n" 'outline-next-visible-heading)
4376 (org-defkey map "p" 'outline-previous-visible-heading)
4377 (org-defkey map "f" 'outline-forward-same-level)
4378 (org-defkey map "b" 'outline-backward-same-level)
4379 (org-defkey map "u" 'outline-up-heading))
4380 (org-defkey map "/" 'org-occur)
4381 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4382 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4383 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
4384 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
4385 (org-defkey map "\C-c\C-u" 'outline-up-heading)
4386 map))
4388 (defconst org-goto-help
4389 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4390 RET=jump to location [Q]uit and return to previous location
4391 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4393 (defvar org-goto-start-pos) ; dynamically scoped parameter
4395 ;; FIXME: Docstring doe not mention both interfaces
4396 (defun org-goto (&optional alternative-interface)
4397 "Look up a different location in the current file, keeping current visibility.
4399 When you want look-up or go to a different location in a document, the
4400 fastest way is often to fold the entire buffer and then dive into the tree.
4401 This method has the disadvantage, that the previous location will be folded,
4402 which may not be what you want.
4404 This command works around this by showing a copy of the current buffer
4405 in an indirect buffer, in overview mode. You can dive into the tree in
4406 that copy, use org-occur and incremental search to find a location.
4407 When pressing RET or `Q', the command returns to the original buffer in
4408 which the visibility is still unchanged. After RET is will also jump to
4409 the location selected in the indirect buffer and expose the
4410 the headline hierarchy above."
4411 (interactive "P")
4412 (let* ((org-refile-targets '((nil . (:maxlevel . 10))))
4413 (org-refile-use-outline-path t)
4414 (interface
4415 (if (not alternative-interface)
4416 org-goto-interface
4417 (if (eq org-goto-interface 'outline)
4418 'outline-path-completion
4419 'outline)))
4420 (org-goto-start-pos (point))
4421 (selected-point
4422 (if (eq interface 'outline)
4423 (car (org-get-location (current-buffer) org-goto-help))
4424 (nth 3 (org-refile-get-location "Goto: ")))))
4425 (if selected-point
4426 (progn
4427 (org-mark-ring-push org-goto-start-pos)
4428 (goto-char selected-point)
4429 (if (or (org-invisible-p) (org-invisible-p2))
4430 (org-show-context 'org-goto)))
4431 (message "Quit"))))
4433 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
4434 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
4435 (defvar org-goto-local-auto-isearch-map) ; defined below
4437 (defun org-get-location (buf help)
4438 "Let the user select a location in the Org-mode buffer BUF.
4439 This function uses a recursive edit. It returns the selected position
4440 or nil."
4441 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
4442 (isearch-hide-immediately nil)
4443 (isearch-search-fun-function
4444 (lambda () 'org-goto-local-search-headings))
4445 (org-goto-selected-point org-goto-exit-command))
4446 (save-excursion
4447 (save-window-excursion
4448 (delete-other-windows)
4449 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
4450 (switch-to-buffer
4451 (condition-case nil
4452 (make-indirect-buffer (current-buffer) "*org-goto*")
4453 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
4454 (with-output-to-temp-buffer "*Help*"
4455 (princ help))
4456 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
4457 (setq buffer-read-only nil)
4458 (let ((org-startup-truncated t)
4459 (org-startup-folded nil)
4460 (org-startup-align-all-tables nil))
4461 (org-mode)
4462 (org-overview))
4463 (setq buffer-read-only t)
4464 (if (and (boundp 'org-goto-start-pos)
4465 (integer-or-marker-p org-goto-start-pos))
4466 (let ((org-show-hierarchy-above t)
4467 (org-show-siblings t)
4468 (org-show-following-heading t))
4469 (goto-char org-goto-start-pos)
4470 (and (org-invisible-p) (org-show-context)))
4471 (goto-char (point-min)))
4472 (org-beginning-of-line)
4473 (message "Select location and press RET")
4474 (use-local-map org-goto-map)
4475 (recursive-edit)
4477 (kill-buffer "*org-goto*")
4478 (cons org-goto-selected-point org-goto-exit-command)))
4480 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
4481 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
4482 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
4483 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
4485 (defun org-goto-local-search-headings (string bound noerror)
4486 "Search and make sure that any matches are in headlines."
4487 (catch 'return
4488 (while (if isearch-forward
4489 (search-forward string bound noerror)
4490 (search-backward string bound noerror))
4491 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
4492 (and (member :headline context)
4493 (not (member :tags context))))
4494 (throw 'return (point))))))
4496 (defun org-goto-local-auto-isearch ()
4497 "Start isearch."
4498 (interactive)
4499 (goto-char (point-min))
4500 (let ((keys (this-command-keys)))
4501 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
4502 (isearch-mode t)
4503 (isearch-process-search-char (string-to-char keys)))))
4505 (defun org-goto-ret (&optional arg)
4506 "Finish `org-goto' by going to the new location."
4507 (interactive "P")
4508 (setq org-goto-selected-point (point)
4509 org-goto-exit-command 'return)
4510 (throw 'exit nil))
4512 (defun org-goto-left ()
4513 "Finish `org-goto' by going to the new location."
4514 (interactive)
4515 (if (org-on-heading-p)
4516 (progn
4517 (beginning-of-line 1)
4518 (setq org-goto-selected-point (point)
4519 org-goto-exit-command 'left)
4520 (throw 'exit nil))
4521 (error "Not on a heading")))
4523 (defun org-goto-right ()
4524 "Finish `org-goto' by going to the new location."
4525 (interactive)
4526 (if (org-on-heading-p)
4527 (progn
4528 (setq org-goto-selected-point (point)
4529 org-goto-exit-command 'right)
4530 (throw 'exit nil))
4531 (error "Not on a heading")))
4533 (defun org-goto-quit ()
4534 "Finish `org-goto' without cursor motion."
4535 (interactive)
4536 (setq org-goto-selected-point nil)
4537 (setq org-goto-exit-command 'quit)
4538 (throw 'exit nil))
4540 ;;; Indirect buffer display of subtrees
4542 (defvar org-indirect-dedicated-frame nil
4543 "This is the frame being used for indirect tree display.")
4544 (defvar org-last-indirect-buffer nil)
4546 (defun org-tree-to-indirect-buffer (&optional arg)
4547 "Create indirect buffer and narrow it to current subtree.
4548 With numerical prefix ARG, go up to this level and then take that tree.
4549 If ARG is negative, go up that many levels.
4550 If `org-indirect-buffer-display' is not `new-frame', the command removes the
4551 indirect buffer previously made with this command, to avoid proliferation of
4552 indirect buffers. However, when you call the command with a `C-u' prefix, or
4553 when `org-indirect-buffer-display' is `new-frame', the last buffer
4554 is kept so that you can work with several indirect buffers at the same time.
4555 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
4556 requests that a new frame be made for the new buffer, so that the dedicated
4557 frame is not changed."
4558 (interactive "P")
4559 (let ((cbuf (current-buffer))
4560 (cwin (selected-window))
4561 (pos (point))
4562 beg end level heading ibuf)
4563 (save-excursion
4564 (org-back-to-heading t)
4565 (when (numberp arg)
4566 (setq level (org-outline-level))
4567 (if (< arg 0) (setq arg (+ level arg)))
4568 (while (> (setq level (org-outline-level)) arg)
4569 (outline-up-heading 1 t)))
4570 (setq beg (point)
4571 heading (org-get-heading))
4572 (org-end-of-subtree t) (setq end (point)))
4573 (if (and (buffer-live-p org-last-indirect-buffer)
4574 (not (eq org-indirect-buffer-display 'new-frame))
4575 (not arg))
4576 (kill-buffer org-last-indirect-buffer))
4577 (setq ibuf (org-get-indirect-buffer cbuf)
4578 org-last-indirect-buffer ibuf)
4579 (cond
4580 ((or (eq org-indirect-buffer-display 'new-frame)
4581 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
4582 (select-frame (make-frame))
4583 (delete-other-windows)
4584 (switch-to-buffer ibuf)
4585 (org-set-frame-title heading))
4586 ((eq org-indirect-buffer-display 'dedicated-frame)
4587 (raise-frame
4588 (select-frame (or (and org-indirect-dedicated-frame
4589 (frame-live-p org-indirect-dedicated-frame)
4590 org-indirect-dedicated-frame)
4591 (setq org-indirect-dedicated-frame (make-frame)))))
4592 (delete-other-windows)
4593 (switch-to-buffer ibuf)
4594 (org-set-frame-title (concat "Indirect: " heading)))
4595 ((eq org-indirect-buffer-display 'current-window)
4596 (switch-to-buffer ibuf))
4597 ((eq org-indirect-buffer-display 'other-window)
4598 (pop-to-buffer ibuf))
4599 (t (error "Invalid value.")))
4600 (if (featurep 'xemacs)
4601 (save-excursion (org-mode) (turn-on-font-lock)))
4602 (narrow-to-region beg end)
4603 (show-all)
4604 (goto-char pos)
4605 (and (window-live-p cwin) (select-window cwin))))
4607 (defun org-get-indirect-buffer (&optional buffer)
4608 (setq buffer (or buffer (current-buffer)))
4609 (let ((n 1) (base (buffer-name buffer)) bname)
4610 (while (buffer-live-p
4611 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
4612 (setq n (1+ n)))
4613 (condition-case nil
4614 (make-indirect-buffer buffer bname 'clone)
4615 (error (make-indirect-buffer buffer bname)))))
4617 (defun org-set-frame-title (title)
4618 "Set the title of the current frame to the string TITLE."
4619 ;; FIXME: how to name a single frame in XEmacs???
4620 (unless (featurep 'xemacs)
4621 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
4623 ;;;; Structure editing
4625 ;;; Inserting headlines
4627 (defun org-insert-heading (&optional force-heading)
4628 "Insert a new heading or item with same depth at point.
4629 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
4630 If point is at the beginning of a headline, insert a sibling before the
4631 current headline. If point is not at the beginning, do not split the line,
4632 but create the new headline after the current line."
4633 (interactive "P")
4634 (if (= (buffer-size) 0)
4635 (insert "\n* ")
4636 (when (or force-heading (not (org-insert-item)))
4637 (let* ((head (save-excursion
4638 (condition-case nil
4639 (progn
4640 (org-back-to-heading)
4641 (match-string 0))
4642 (error "*"))))
4643 (blank (cdr (assq 'heading org-blank-before-new-entry)))
4644 pos hide-previous previous-pos)
4645 (cond
4646 ((and (org-on-heading-p) (bolp)
4647 (or (bobp)
4648 (save-excursion (backward-char 1) (not (org-invisible-p)))))
4649 ;; insert before the current line
4650 (open-line (if blank 2 1)))
4651 ((and (bolp)
4652 (or (bobp)
4653 (save-excursion
4654 (backward-char 1) (not (org-invisible-p)))))
4655 ;; insert right here
4656 nil)
4658 ;; somewhere in the line
4659 (save-excursion
4660 (setq previous-pos (point-at-bol))
4661 (end-of-line)
4662 (setq hide-previous (org-invisible-p)))
4663 (and org-insert-heading-respect-content (org-show-subtree))
4664 (let ((split
4665 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
4666 (save-excursion
4667 (let ((p (point)))
4668 (goto-char (point-at-bol))
4669 (and (looking-at org-complex-heading-regexp)
4670 (> p (match-beginning 4)))))))
4671 tags pos)
4672 (cond
4673 (org-insert-heading-respect-content
4674 (org-end-of-subtree nil t)
4675 (or (bolp) (newline))
4676 (open-line 1))
4677 ((org-on-heading-p)
4678 (when hide-previous
4679 (show-children)
4680 (org-show-entry))
4681 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4682 (setq tags (and (match-end 2) (match-string 2)))
4683 (and (match-end 1)
4684 (delete-region (match-beginning 1) (match-end 1)))
4685 (setq pos (point-at-bol))
4686 (or split (end-of-line 1))
4687 (delete-horizontal-space)
4688 (newline (if blank 2 1))
4689 (when tags
4690 (save-excursion
4691 (goto-char pos)
4692 (end-of-line 1)
4693 (insert " " tags)
4694 (org-set-tags nil 'align))))
4696 (or split (end-of-line 1))
4697 (newline (if blank 2 1)))))))
4698 (insert head) (just-one-space)
4699 (setq pos (point))
4700 (end-of-line 1)
4701 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
4702 (when (and org-insert-heading-respect-content hide-previous)
4703 (save-excursion
4704 (goto-char previous-pos)
4705 (hide-subtree)))
4706 (run-hooks 'org-insert-heading-hook)))))
4708 (defun org-get-heading (&optional no-tags)
4709 "Return the heading of the current entry, without the stars."
4710 (save-excursion
4711 (org-back-to-heading t)
4712 (if (looking-at
4713 (if no-tags
4714 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
4715 "\\*+[ \t]+\\([^\r\n]*\\)"))
4716 (match-string 1) "")))
4718 (defun org-insert-heading-after-current ()
4719 "Insert a new heading with same level as current, after current subtree."
4720 (interactive)
4721 (org-back-to-heading)
4722 (org-insert-heading)
4723 (org-move-subtree-down)
4724 (end-of-line 1))
4726 (defun org-insert-heading-respect-content ()
4727 (interactive)
4728 (let ((org-insert-heading-respect-content t))
4729 (org-insert-heading t)))
4731 (defun org-insert-todo-heading-respect-content (&optional force-state)
4732 (interactive "P")
4733 (let ((org-insert-heading-respect-content t))
4734 (org-insert-todo-heading force-state t)))
4736 (defun org-insert-todo-heading (arg &optional force-heading)
4737 "Insert a new heading with the same level and TODO state as current heading.
4738 If the heading has no TODO state, or if the state is DONE, use the first
4739 state (TODO by default). Also with prefix arg, force first state."
4740 (interactive "P")
4741 (when (or force-heading (not (org-insert-item 'checkbox)))
4742 (org-insert-heading force-heading)
4743 (save-excursion
4744 (org-back-to-heading)
4745 (outline-previous-heading)
4746 (looking-at org-todo-line-regexp))
4747 (if (or arg
4748 (not (match-beginning 2))
4749 (member (match-string 2) org-done-keywords))
4750 (insert (car org-todo-keywords-1) " ")
4751 (insert (match-string 2) " "))
4752 (when org-provide-todo-statistics
4753 (org-update-parent-todo-statistics))))
4755 (defun org-insert-subheading (arg)
4756 "Insert a new subheading and demote it.
4757 Works for outline headings and for plain lists alike."
4758 (interactive "P")
4759 (org-insert-heading arg)
4760 (cond
4761 ((org-on-heading-p) (org-do-demote))
4762 ((org-at-item-p) (org-indent-item 1))))
4764 (defun org-insert-todo-subheading (arg)
4765 "Insert a new subheading with TODO keyword or checkbox and demote it.
4766 Works for outline headings and for plain lists alike."
4767 (interactive "P")
4768 (org-insert-todo-heading arg)
4769 (cond
4770 ((org-on-heading-p) (org-do-demote))
4771 ((org-at-item-p) (org-indent-item 1))))
4773 ;;; Promotion and Demotion
4775 (defun org-promote-subtree ()
4776 "Promote the entire subtree.
4777 See also `org-promote'."
4778 (interactive)
4779 (save-excursion
4780 (org-map-tree 'org-promote))
4781 (org-fix-position-after-promote))
4783 (defun org-demote-subtree ()
4784 "Demote the entire subtree. See `org-demote'.
4785 See also `org-promote'."
4786 (interactive)
4787 (save-excursion
4788 (org-map-tree 'org-demote))
4789 (org-fix-position-after-promote))
4792 (defun org-do-promote ()
4793 "Promote the current heading higher up the tree.
4794 If the region is active in `transient-mark-mode', promote all headings
4795 in the region."
4796 (interactive)
4797 (save-excursion
4798 (if (org-region-active-p)
4799 (org-map-region 'org-promote (region-beginning) (region-end))
4800 (org-promote)))
4801 (org-fix-position-after-promote))
4803 (defun org-do-demote ()
4804 "Demote the current heading lower down the tree.
4805 If the region is active in `transient-mark-mode', demote all headings
4806 in the region."
4807 (interactive)
4808 (save-excursion
4809 (if (org-region-active-p)
4810 (org-map-region 'org-demote (region-beginning) (region-end))
4811 (org-demote)))
4812 (org-fix-position-after-promote))
4814 (defun org-fix-position-after-promote ()
4815 "Make sure that after pro/demotion cursor position is right."
4816 (let ((pos (point)))
4817 (when (save-excursion
4818 (beginning-of-line 1)
4819 (looking-at org-todo-line-regexp)
4820 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
4821 (cond ((eobp) (insert " "))
4822 ((eolp) (insert " "))
4823 ((equal (char-after) ?\ ) (forward-char 1))))))
4825 (defun org-reduced-level (l)
4826 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
4828 (defun org-get-valid-level (level &optional change)
4829 "Rectify a level change under the influence of `org-odd-levels-only'
4830 LEVEL is a current level, CHANGE is by how much the level should be
4831 modified. Even if CHANGE is nil, LEVEL may be returned modified because
4832 even level numbers will become the next higher odd number."
4833 (if org-odd-levels-only
4834 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
4835 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
4836 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
4837 (max 1 (+ level change))))
4839 (if (boundp 'define-obsolete-function-alias)
4840 (if (or (featurep 'xemacs) (< emacs-major-version 23))
4841 (define-obsolete-function-alias 'org-get-legal-level
4842 'org-get-valid-level)
4843 (define-obsolete-function-alias 'org-get-legal-level
4844 'org-get-valid-level "23.1")))
4846 (defun org-promote ()
4847 "Promote the current heading higher up the tree.
4848 If the region is active in `transient-mark-mode', promote all headings
4849 in the region."
4850 (org-back-to-heading t)
4851 (let* ((level (save-match-data (funcall outline-level)))
4852 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
4853 (diff (abs (- level (length up-head) -1))))
4854 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
4855 (replace-match up-head nil t)
4856 ;; Fixup tag positioning
4857 (and org-auto-align-tags (org-set-tags nil t))
4858 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
4860 (defun org-demote ()
4861 "Demote the current heading lower down the tree.
4862 If the region is active in `transient-mark-mode', demote all headings
4863 in the region."
4864 (org-back-to-heading t)
4865 (let* ((level (save-match-data (funcall outline-level)))
4866 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
4867 (diff (abs (- level (length down-head) -1))))
4868 (replace-match down-head nil t)
4869 ;; Fixup tag positioning
4870 (and org-auto-align-tags (org-set-tags nil t))
4871 (if org-adapt-indentation (org-fixup-indentation diff))))
4873 (defun org-map-tree (fun)
4874 "Call FUN for every heading underneath the current one."
4875 (org-back-to-heading)
4876 (let ((level (funcall outline-level)))
4877 (save-excursion
4878 (funcall fun)
4879 (while (and (progn
4880 (outline-next-heading)
4881 (> (funcall outline-level) level))
4882 (not (eobp)))
4883 (funcall fun)))))
4885 (defun org-map-region (fun beg end)
4886 "Call FUN for every heading between BEG and END."
4887 (let ((org-ignore-region t))
4888 (save-excursion
4889 (setq end (copy-marker end))
4890 (goto-char beg)
4891 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
4892 (< (point) end))
4893 (funcall fun))
4894 (while (and (progn
4895 (outline-next-heading)
4896 (< (point) end))
4897 (not (eobp)))
4898 (funcall fun)))))
4900 (defun org-fixup-indentation (diff)
4901 "Change the indentation in the current entry by DIFF
4902 However, if any line in the current entry has no indentation, or if it
4903 would end up with no indentation after the change, nothing at all is done."
4904 (save-excursion
4905 (let ((end (save-excursion (outline-next-heading)
4906 (point-marker)))
4907 (prohibit (if (> diff 0)
4908 "^\\S-"
4909 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
4910 col)
4911 (unless (save-excursion (end-of-line 1)
4912 (re-search-forward prohibit end t))
4913 (while (and (< (point) end)
4914 (re-search-forward "^[ \t]+" end t))
4915 (goto-char (match-end 0))
4916 (setq col (current-column))
4917 (if (< diff 0) (replace-match ""))
4918 (indent-to (+ diff col))))
4919 (move-marker end nil))))
4921 (defun org-convert-to-odd-levels ()
4922 "Convert an org-mode file with all levels allowed to one with odd levels.
4923 This will leave level 1 alone, convert level 2 to level 3, level 3 to
4924 level 5 etc."
4925 (interactive)
4926 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
4927 (let ((org-odd-levels-only nil) n)
4928 (save-excursion
4929 (goto-char (point-min))
4930 (while (re-search-forward "^\\*\\*+ " nil t)
4931 (setq n (- (length (match-string 0)) 2))
4932 (while (>= (setq n (1- n)) 0)
4933 (org-demote))
4934 (end-of-line 1))))))
4937 (defun org-convert-to-oddeven-levels ()
4938 "Convert an org-mode file with only odd levels to one with odd and even levels.
4939 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
4940 section with an even level, conversion would destroy the structure of the file. An error
4941 is signaled in this case."
4942 (interactive)
4943 (goto-char (point-min))
4944 ;; First check if there are no even levels
4945 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
4946 (org-show-context t)
4947 (error "Not all levels are odd in this file. Conversion not possible."))
4948 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
4949 (let ((org-odd-levels-only nil) n)
4950 (save-excursion
4951 (goto-char (point-min))
4952 (while (re-search-forward "^\\*\\*+ " nil t)
4953 (setq n (/ (1- (length (match-string 0))) 2))
4954 (while (>= (setq n (1- n)) 0)
4955 (org-promote))
4956 (end-of-line 1))))))
4958 (defun org-tr-level (n)
4959 "Make N odd if required."
4960 (if org-odd-levels-only (1+ (/ n 2)) n))
4962 ;;; Vertical tree motion, cutting and pasting of subtrees
4964 (defun org-move-subtree-up (&optional arg)
4965 "Move the current subtree up past ARG headlines of the same level."
4966 (interactive "p")
4967 (org-move-subtree-down (- (prefix-numeric-value arg))))
4969 (defun org-move-subtree-down (&optional arg)
4970 "Move the current subtree down past ARG headlines of the same level."
4971 (interactive "p")
4972 (setq arg (prefix-numeric-value arg))
4973 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
4974 'outline-get-last-sibling))
4975 (ins-point (make-marker))
4976 (cnt (abs arg))
4977 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
4978 ;; Select the tree
4979 (org-back-to-heading)
4980 (setq beg0 (point))
4981 (save-excursion
4982 (setq ne-beg (org-back-over-empty-lines))
4983 (setq beg (point)))
4984 (save-match-data
4985 (save-excursion (outline-end-of-heading)
4986 (setq folded (org-invisible-p)))
4987 (outline-end-of-subtree))
4988 (outline-next-heading)
4989 (setq ne-end (org-back-over-empty-lines))
4990 (setq end (point))
4991 (goto-char beg0)
4992 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
4993 ;; include less whitespace
4994 (save-excursion
4995 (goto-char beg)
4996 (forward-line (- ne-beg ne-end))
4997 (setq beg (point))))
4998 ;; Find insertion point, with error handling
4999 (while (> cnt 0)
5000 (or (and (funcall movfunc) (looking-at outline-regexp))
5001 (progn (goto-char beg0)
5002 (error "Cannot move past superior level or buffer limit")))
5003 (setq cnt (1- cnt)))
5004 (if (> arg 0)
5005 ;; Moving forward - still need to move over subtree
5006 (progn (org-end-of-subtree t t)
5007 (save-excursion
5008 (org-back-over-empty-lines)
5009 (or (bolp) (newline)))))
5010 (setq ne-ins (org-back-over-empty-lines))
5011 (move-marker ins-point (point))
5012 (setq txt (buffer-substring beg end))
5013 (org-save-markers-in-region beg end)
5014 (delete-region beg end)
5015 (outline-flag-region (1- beg) beg nil)
5016 (outline-flag-region (1- (point)) (point) nil)
5017 (let ((bbb (point)))
5018 (insert-before-markers txt)
5019 (org-reinstall-markers-in-region bbb)
5020 (move-marker ins-point bbb))
5021 (or (bolp) (insert "\n"))
5022 (setq ins-end (point))
5023 (goto-char ins-point)
5024 (org-skip-whitespace)
5025 (when (and (< arg 0)
5026 (org-first-sibling-p)
5027 (> ne-ins ne-beg))
5028 ;; Move whitespace back to beginning
5029 (save-excursion
5030 (goto-char ins-end)
5031 (let ((kill-whole-line t))
5032 (kill-line (- ne-ins ne-beg)) (point)))
5033 (insert (make-string (- ne-ins ne-beg) ?\n)))
5034 (move-marker ins-point nil)
5035 (org-compact-display-after-subtree-move)
5036 (org-show-empty-lines-in-parent)
5037 (unless folded
5038 (org-show-entry)
5039 (show-children)
5040 (org-cycle-hide-drawers 'children))))
5042 (defvar org-subtree-clip ""
5043 "Clipboard for cut and paste of subtrees.
5044 This is actually only a copy of the kill, because we use the normal kill
5045 ring. We need it to check if the kill was created by `org-copy-subtree'.")
5047 (defvar org-subtree-clip-folded nil
5048 "Was the last copied subtree folded?
5049 This is used to fold the tree back after pasting.")
5051 (defun org-cut-subtree (&optional n)
5052 "Cut the current subtree into the clipboard.
5053 With prefix arg N, cut this many sequential subtrees.
5054 This is a short-hand for marking the subtree and then cutting it."
5055 (interactive "p")
5056 (org-copy-subtree n 'cut))
5058 (defun org-copy-subtree (&optional n cut force-store-markers)
5059 "Cut the current subtree into the clipboard.
5060 With prefix arg N, cut this many sequential subtrees.
5061 This is a short-hand for marking the subtree and then copying it.
5062 If CUT is non-nil, actually cut the subtree.
5063 If FORCE-STORE-MARKERS is non-nil, store the relative locations
5064 of some markers in the region, even if CUT is non-nil. This is
5065 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
5066 (interactive "p")
5067 (let (beg end folded (beg0 (point)))
5068 (if (interactive-p)
5069 (org-back-to-heading nil) ; take what looks like a subtree
5070 (org-back-to-heading t)) ; take what is really there
5071 (org-back-over-empty-lines)
5072 (setq beg (point))
5073 (skip-chars-forward " \t\r\n")
5074 (save-match-data
5075 (save-excursion (outline-end-of-heading)
5076 (setq folded (org-invisible-p)))
5077 (condition-case nil
5078 (outline-forward-same-level (1- n))
5079 (error nil))
5080 (org-end-of-subtree t t))
5081 (org-back-over-empty-lines)
5082 (setq end (point))
5083 (goto-char beg0)
5084 (when (> end beg)
5085 (setq org-subtree-clip-folded folded)
5086 (when (or cut force-store-markers)
5087 (org-save-markers-in-region beg end))
5088 (if cut (kill-region beg end) (copy-region-as-kill beg end))
5089 (setq org-subtree-clip (current-kill 0))
5090 (message "%s: Subtree(s) with %d characters"
5091 (if cut "Cut" "Copied")
5092 (length org-subtree-clip)))))
5094 (defun org-paste-subtree (&optional level tree for-yank)
5095 "Paste the clipboard as a subtree, with modification of headline level.
5096 The entire subtree is promoted or demoted in order to match a new headline
5097 level.
5099 If the cursor is at the beginning of a headline, the same level as
5100 that headline is used to paste the tree
5102 If not, the new level is derived from the *visible* headings
5103 before and after the insertion point, and taken to be the inferior headline
5104 level of the two. So if the previous visible heading is level 3 and the
5105 next is level 4 (or vice versa), level 4 will be used for insertion.
5106 This makes sure that the subtree remains an independent subtree and does
5107 not swallow low level entries.
5109 You can also force a different level, either by using a numeric prefix
5110 argument, or by inserting the heading marker by hand. For example, if the
5111 cursor is after \"*****\", then the tree will be shifted to level 5.
5113 If optional TREE is given, use this text instead of the kill ring.
5115 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
5116 move back over whitespace before inserting, and move point to the end of
5117 the inserted text when done."
5118 (interactive "P")
5119 (unless (org-kill-is-subtree-p tree)
5120 (error "%s"
5121 (substitute-command-keys
5122 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
5123 (let* ((visp (not (org-invisible-p)))
5124 (txt (or tree (and kill-ring (current-kill 0))))
5125 (^re (concat "^\\(" outline-regexp "\\)"))
5126 (re (concat "\\(" outline-regexp "\\)"))
5127 (^re_ (concat "\\(\\*+\\)[ \t]*"))
5129 (old-level (if (string-match ^re txt)
5130 (- (match-end 0) (match-beginning 0) 1)
5131 -1))
5132 (force-level (cond (level (prefix-numeric-value level))
5133 ((and (looking-at "[ \t]*$")
5134 (string-match
5135 ^re_ (buffer-substring
5136 (point-at-bol) (point))))
5137 (- (match-end 1) (match-beginning 1)))
5138 ((and (bolp)
5139 (looking-at org-outline-regexp))
5140 (- (match-end 0) (point) 1))
5141 (t nil)))
5142 (previous-level (save-excursion
5143 (condition-case nil
5144 (progn
5145 (outline-previous-visible-heading 1)
5146 (if (looking-at re)
5147 (- (match-end 0) (match-beginning 0) 1)
5149 (error 1))))
5150 (next-level (save-excursion
5151 (condition-case nil
5152 (progn
5153 (or (looking-at outline-regexp)
5154 (outline-next-visible-heading 1))
5155 (if (looking-at re)
5156 (- (match-end 0) (match-beginning 0) 1)
5158 (error 1))))
5159 (new-level (or force-level (max previous-level next-level)))
5160 (shift (if (or (= old-level -1)
5161 (= new-level -1)
5162 (= old-level new-level))
5164 (- new-level old-level)))
5165 (delta (if (> shift 0) -1 1))
5166 (func (if (> shift 0) 'org-demote 'org-promote))
5167 (org-odd-levels-only nil)
5168 beg end newend)
5169 ;; Remove the forced level indicator
5170 (if force-level
5171 (delete-region (point-at-bol) (point)))
5172 ;; Paste
5173 (beginning-of-line 1)
5174 (unless for-yank (org-back-over-empty-lines))
5175 (setq beg (point))
5176 (insert-before-markers txt)
5177 (unless (string-match "\n\\'" txt) (insert "\n"))
5178 (setq newend (point))
5179 (org-reinstall-markers-in-region beg)
5180 (setq end (point))
5181 (goto-char beg)
5182 (skip-chars-forward " \t\n\r")
5183 (setq beg (point))
5184 (if (and (org-invisible-p) visp)
5185 (save-excursion (outline-show-heading)))
5186 ;; Shift if necessary
5187 (unless (= shift 0)
5188 (save-restriction
5189 (narrow-to-region beg end)
5190 (while (not (= shift 0))
5191 (org-map-region func (point-min) (point-max))
5192 (setq shift (+ delta shift)))
5193 (goto-char (point-min))
5194 (setq newend (point-max))))
5195 (when (or (interactive-p) for-yank)
5196 (message "Clipboard pasted as level %d subtree" new-level))
5197 (if (and (not for-yank) ; in this case, org-yank will decide about folding
5198 kill-ring
5199 (eq org-subtree-clip (current-kill 0))
5200 org-subtree-clip-folded)
5201 ;; The tree was folded before it was killed/copied
5202 (hide-subtree))
5203 (and for-yank (goto-char newend))))
5205 (defun org-kill-is-subtree-p (&optional txt)
5206 "Check if the current kill is an outline subtree, or a set of trees.
5207 Returns nil if kill does not start with a headline, or if the first
5208 headline level is not the largest headline level in the tree.
5209 So this will actually accept several entries of equal levels as well,
5210 which is OK for `org-paste-subtree'.
5211 If optional TXT is given, check this string instead of the current kill."
5212 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
5213 (start-level (and kill
5214 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
5215 org-outline-regexp "\\)")
5216 kill)
5217 (- (match-end 2) (match-beginning 2) 1)))
5218 (re (concat "^" org-outline-regexp))
5219 (start (1+ (or (match-beginning 2) -1))))
5220 (if (not start-level)
5221 (progn
5222 nil) ;; does not even start with a heading
5223 (catch 'exit
5224 (while (setq start (string-match re kill (1+ start)))
5225 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
5226 (throw 'exit nil)))
5227 t))))
5229 (defvar org-markers-to-move nil
5230 "Markers that should be moved with a cut-and-paste operation.
5231 Those markers are stored together with their positions relative to
5232 the start of the region.")
5234 (defun org-save-markers-in-region (beg end)
5235 "Check markers in region.
5236 If these markers are between BEG and END, record their position relative
5237 to BEG, so that after moving the block of text, we can put the markers back
5238 into place.
5239 This function gets called just before an entry or tree gets cut from the
5240 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
5241 called immediately, to move the markers with the entries."
5242 (setq org-markers-to-move nil)
5243 (when (featurep 'org-clock)
5244 (org-clock-save-markers-for-cut-and-paste beg end))
5245 (when (featurep 'org-agenda)
5246 (org-agenda-save-markers-for-cut-and-paste beg end)))
5248 (defun org-check-and-save-marker (marker beg end)
5249 "Check if MARKER is between BEG and END.
5250 If yes, remember the marker and the distance to BEG."
5251 (when (and (marker-buffer marker)
5252 (equal (marker-buffer marker) (current-buffer)))
5253 (if (and (>= marker beg) (< marker end))
5254 (push (cons marker (- marker beg)) org-markers-to-move))))
5256 (defun org-reinstall-markers-in-region (beg)
5257 "Move all remembered markers to their position relative to BEG."
5258 (mapc (lambda (x)
5259 (move-marker (car x) (+ beg (cdr x))))
5260 org-markers-to-move)
5261 (setq org-markers-to-move nil))
5263 (defun org-narrow-to-subtree ()
5264 "Narrow buffer to the current subtree."
5265 (interactive)
5266 (save-excursion
5267 (save-match-data
5268 (narrow-to-region
5269 (progn (org-back-to-heading) (point))
5270 (progn (org-end-of-subtree t) (point))))))
5273 ;;; Outline Sorting
5275 (defun org-sort (with-case)
5276 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
5277 Optional argument WITH-CASE means sort case-sensitively."
5278 (interactive "P")
5279 (if (org-at-table-p)
5280 (org-call-with-arg 'org-table-sort-lines with-case)
5281 (org-call-with-arg 'org-sort-entries-or-items with-case)))
5283 (defun org-sort-remove-invisible (s)
5284 (remove-text-properties 0 (length s) org-rm-props s)
5285 (while (string-match org-bracket-link-regexp s)
5286 (setq s (replace-match (if (match-end 2)
5287 (match-string 3 s)
5288 (match-string 1 s)) t t s)))
5291 (defvar org-priority-regexp) ; defined later in the file
5293 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
5294 "Sort entries on a certain level of an outline tree.
5295 If there is an active region, the entries in the region are sorted.
5296 Else, if the cursor is before the first entry, sort the top-level items.
5297 Else, the children of the entry at point are sorted.
5299 Sorting can be alphabetically, numerically, and by date/time as given by
5300 the first time stamp in the entry. The command prompts for the sorting
5301 type unless it has been given to the function through the SORTING-TYPE
5302 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
5303 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
5304 called with point at the beginning of the record. It must return either
5305 a string or a number that should serve as the sorting key for that record.
5307 Comparing entries ignores case by default. However, with an optional argument
5308 WITH-CASE, the sorting considers case as well."
5309 (interactive "P")
5310 (let ((case-func (if with-case 'identity 'downcase))
5311 start beg end stars re re2
5312 txt what tmp plain-list-p)
5313 ;; Find beginning and end of region to sort
5314 (cond
5315 ((org-region-active-p)
5316 ;; we will sort the region
5317 (setq end (region-end)
5318 what "region")
5319 (goto-char (region-beginning))
5320 (if (not (org-on-heading-p)) (outline-next-heading))
5321 (setq start (point)))
5322 ((org-at-item-p)
5323 ;; we will sort this plain list
5324 (org-beginning-of-item-list) (setq start (point))
5325 (org-end-of-item-list) (setq end (point))
5326 (goto-char start)
5327 (setq plain-list-p t
5328 what "plain list"))
5329 ((or (org-on-heading-p)
5330 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
5331 ;; we will sort the children of the current headline
5332 (org-back-to-heading)
5333 (setq start (point)
5334 end (progn (org-end-of-subtree t t)
5335 (org-back-over-empty-lines)
5336 (point))
5337 what "children")
5338 (goto-char start)
5339 (show-subtree)
5340 (outline-next-heading))
5342 ;; we will sort the top-level entries in this file
5343 (goto-char (point-min))
5344 (or (org-on-heading-p) (outline-next-heading))
5345 (setq start (point) end (point-max) what "top-level")
5346 (goto-char start)
5347 (show-all)))
5349 (setq beg (point))
5350 (if (>= beg end) (error "Nothing to sort"))
5352 (unless plain-list-p
5353 (looking-at "\\(\\*+\\)")
5354 (setq stars (match-string 1)
5355 re (concat "^" (regexp-quote stars) " +")
5356 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
5357 txt (buffer-substring beg end))
5358 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
5359 (if (and (not (equal stars "*")) (string-match re2 txt))
5360 (error "Region to sort contains a level above the first entry")))
5362 (unless sorting-type
5363 (message
5364 (if plain-list-p
5365 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
5366 "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:")
5367 what)
5368 (setq sorting-type (read-char-exclusive))
5370 (and (= (downcase sorting-type) ?f)
5371 (setq getkey-func
5372 (completing-read "Sort using function: "
5373 obarray 'fboundp t nil nil))
5374 (setq getkey-func (intern getkey-func)))
5376 (and (= (downcase sorting-type) ?r)
5377 (setq property
5378 (completing-read "Property: "
5379 (mapcar 'list (org-buffer-property-keys t))
5380 nil t))))
5382 (message "Sorting entries...")
5384 (save-restriction
5385 (narrow-to-region start end)
5387 (let ((dcst (downcase sorting-type))
5388 (now (current-time)))
5389 (sort-subr
5390 (/= dcst sorting-type)
5391 ;; This function moves to the beginning character of the "record" to
5392 ;; be sorted.
5393 (if plain-list-p
5394 (lambda nil
5395 (if (org-at-item-p) t (goto-char (point-max))))
5396 (lambda nil
5397 (if (re-search-forward re nil t)
5398 (goto-char (match-beginning 0))
5399 (goto-char (point-max)))))
5400 ;; This function moves to the last character of the "record" being
5401 ;; sorted.
5402 (if plain-list-p
5403 'org-end-of-item
5404 (lambda nil
5405 (save-match-data
5406 (condition-case nil
5407 (outline-forward-same-level 1)
5408 (error
5409 (goto-char (point-max)))))))
5411 ;; This function returns the value that gets sorted against.
5412 (if plain-list-p
5413 (lambda nil
5414 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
5415 (cond
5416 ((= dcst ?n)
5417 (string-to-number (buffer-substring (match-end 0)
5418 (point-at-eol))))
5419 ((= dcst ?a)
5420 (buffer-substring (match-end 0) (point-at-eol)))
5421 ((= dcst ?t)
5422 (if (re-search-forward org-ts-regexp
5423 (point-at-eol) t)
5424 (org-time-string-to-time (match-string 0))
5425 now))
5426 ((= dcst ?f)
5427 (if getkey-func
5428 (progn
5429 (setq tmp (funcall getkey-func))
5430 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5431 tmp)
5432 (error "Invalid key function `%s'" getkey-func)))
5433 (t (error "Invalid sorting type `%c'" sorting-type)))))
5434 (lambda nil
5435 (cond
5436 ((= dcst ?n)
5437 (if (looking-at org-complex-heading-regexp)
5438 (string-to-number (match-string 4))
5439 nil))
5440 ((= dcst ?a)
5441 (if (looking-at org-complex-heading-regexp)
5442 (funcall case-func (match-string 4))
5443 nil))
5444 ((= dcst ?t)
5445 (if (re-search-forward org-ts-regexp
5446 (save-excursion
5447 (forward-line 2)
5448 (point)) t)
5449 (org-time-string-to-time (match-string 0))
5450 now))
5451 ((= dcst ?p)
5452 (if (re-search-forward org-priority-regexp (point-at-eol) t)
5453 (string-to-char (match-string 2))
5454 org-default-priority))
5455 ((= dcst ?r)
5456 (or (org-entry-get nil property) ""))
5457 ((= dcst ?o)
5458 (if (looking-at org-complex-heading-regexp)
5459 (- 9999 (length (member (match-string 2)
5460 org-todo-keywords-1)))))
5461 ((= dcst ?f)
5462 (if getkey-func
5463 (progn
5464 (setq tmp (funcall getkey-func))
5465 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5466 tmp)
5467 (error "Invalid key function `%s'" getkey-func)))
5468 (t (error "Invalid sorting type `%c'" sorting-type)))))
5470 (cond
5471 ((= dcst ?a) 'string<)
5472 ((= dcst ?t) 'time-less-p)
5473 (t nil)))))
5474 (message "Sorting entries...done")))
5476 (defun org-do-sort (table what &optional with-case sorting-type)
5477 "Sort TABLE of WHAT according to SORTING-TYPE.
5478 The user will be prompted for the SORTING-TYPE if the call to this
5479 function does not specify it. WHAT is only for the prompt, to indicate
5480 what is being sorted. The sorting key will be extracted from
5481 the car of the elements of the table.
5482 If WITH-CASE is non-nil, the sorting will be case-sensitive."
5483 (unless sorting-type
5484 (message
5485 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
5486 what)
5487 (setq sorting-type (read-char-exclusive)))
5488 (let ((dcst (downcase sorting-type))
5489 extractfun comparefun)
5490 ;; Define the appropriate functions
5491 (cond
5492 ((= dcst ?n)
5493 (setq extractfun 'string-to-number
5494 comparefun (if (= dcst sorting-type) '< '>)))
5495 ((= dcst ?a)
5496 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
5497 (lambda(x) (downcase (org-sort-remove-invisible x))))
5498 comparefun (if (= dcst sorting-type)
5499 'string<
5500 (lambda (a b) (and (not (string< a b))
5501 (not (string= a b)))))))
5502 ((= dcst ?t)
5503 (setq extractfun
5504 (lambda (x)
5505 (if (string-match org-ts-regexp x)
5506 (time-to-seconds
5507 (org-time-string-to-time (match-string 0 x)))
5509 comparefun (if (= dcst sorting-type) '< '>)))
5510 (t (error "Invalid sorting type `%c'" sorting-type)))
5512 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5513 table)
5514 (lambda (a b) (funcall comparefun (car a) (car b))))))
5516 ;;; Editing source examples
5518 (defvar org-exit-edit-mode-map (make-sparse-keymap))
5519 (define-key org-exit-edit-mode-map "\C-c'" 'org-edit-src-exit)
5520 (defvar org-edit-src-force-single-line nil)
5521 (defvar org-edit-src-from-org-mode nil)
5522 (defvar org-edit-src-picture nil)
5524 (define-minor-mode org-exit-edit-mode
5525 "Minor mode installing a single key binding, \"C-c '\" to exit special edit.")
5527 (defun org-edit-src-code ()
5528 "Edit the source code example at point.
5529 An indirect buffer is created, and that buffer is then narrowed to the
5530 example at point and switched to the correct language mode. When done,
5531 exit by killing the buffer with \\[org-edit-src-exit]."
5532 (interactive)
5533 (let ((line (org-current-line))
5534 (case-fold-search t)
5535 (msg (substitute-command-keys
5536 "Edit, then exit with C-c ' (C-c and single quote)"))
5537 (info (org-edit-src-find-region-and-lang))
5538 (org-mode-p (eq major-mode 'org-mode))
5539 beg end lang lang-f single)
5540 (if (not info)
5542 (setq beg (nth 0 info)
5543 end (nth 1 info)
5544 lang (nth 2 info)
5545 single (nth 3 info)
5546 lang-f (intern (concat lang "-mode")))
5547 (unless (functionp lang-f)
5548 (error "No such language mode: %s" lang-f))
5549 (goto-line line)
5550 (if (get-buffer "*Org Edit Src Example*")
5551 (kill-buffer "*Org Edit Src Example*"))
5552 (switch-to-buffer (make-indirect-buffer (current-buffer)
5553 "*Org Edit Src Example*"))
5554 (narrow-to-region beg end)
5555 (remove-text-properties beg end '(display nil invisible nil
5556 intangible nil))
5557 (let ((org-inhibit-startup t))
5558 (funcall lang-f))
5559 (set (make-local-variable 'org-edit-src-force-single-line) single)
5560 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5561 (when org-mode-p
5562 (goto-char (point-min))
5563 (while (re-search-forward "^," nil t)
5564 (replace-match "")))
5565 (goto-line line)
5566 (org-exit-edit-mode)
5567 (org-set-local 'header-line-format msg)
5568 (message "%s" msg)
5569 t)))
5571 (defun org-edit-fixed-width-region ()
5572 "Edit the fixed-width ascii drawing at point.
5573 This must be a region where each line starts with ca colon followed by
5574 a space character.
5575 An indirect buffer is created, and that buffer is then narrowed to the
5576 example at point and switched to artist-mode. When done,
5577 exit by killing the buffer with \\[org-edit-src-exit]."
5578 (interactive)
5579 (let ((line (org-current-line))
5580 (case-fold-search t)
5581 (msg (substitute-command-keys
5582 "Edit, then exit with C-c ' (C-c and single quote)"))
5583 (org-mode-p (eq major-mode 'org-mode))
5584 beg end lang lang-f)
5585 (beginning-of-line 1)
5586 (if (looking-at "[ \t]*[^:\n \t]")
5588 (if (looking-at "[ \t]*\\(\n\\|\\'\\)]")
5589 (setq beg (point) end (match-end 0))
5590 (save-excursion
5591 (if (re-search-backward "^[ \t]*[^:]" nil 'move)
5592 (setq beg (point-at-bol 2))
5593 (setq beg (point))))
5594 (save-excursion
5595 (if (re-search-forward "^[ \t]*[^:]" nil 'move)
5596 (setq end (1- (match-beginning 0)))
5597 (setq end (point))))
5598 (goto-line line)
5599 (if (get-buffer "*Org Edit Picture*")
5600 (kill-buffer "*Org Edit Picture*"))
5601 (switch-to-buffer (make-indirect-buffer (current-buffer)
5602 "*Org Edit Picture*"))
5603 (narrow-to-region beg end)
5604 (remove-text-properties beg end '(display nil invisible nil
5605 intangible nil))
5606 (when (fboundp 'font-lock-unfontify-region)
5607 (font-lock-unfontify-region (point-min) (point-max)))
5608 (cond
5609 ((eq org-edit-fixed-width-region-mode 'artist-mode)
5610 (fundamental-mode)
5611 (artist-mode 1))
5612 (t (funcall org-edit-fixed-width-region-mode)))
5613 (set (make-local-variable 'org-edit-src-force-single-line) nil)
5614 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5615 (set (make-local-variable 'org-edit-src-picture) t)
5616 (goto-char (point-min))
5617 (while (re-search-forward "^[ \t]*: " nil t)
5618 (replace-match ""))
5619 (goto-line line)
5620 (org-exit-edit-mode)
5621 (org-set-local 'header-line-format msg)
5622 (message "%s" msg)
5623 t))))
5626 (defun org-edit-src-find-region-and-lang ()
5627 "Find the region and language for a local edit.
5628 Return a list with beginning and end of the region, a string representing
5629 the language, a switch telling of the content should be in a single line."
5630 (let ((re-list
5631 (append
5632 org-edit-src-region-extra
5634 ("<src\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</src>" lang)
5635 ("<literal\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</literal>" style)
5636 ("<example>[ \t]*\n?" "\n?[ \t]*</example>" "fundamental")
5637 ("<lisp>[ \t]*\n?" "\n?[ \t]*</lisp>" "emacs-lisp")
5638 ("<perl>[ \t]*\n?" "\n?[ \t]*</perl>" "perl")
5639 ("<python>[ \t]*\n?" "\n?[ \t]*</python>" "python")
5640 ("<ruby>[ \t]*\n?" "\n?[ \t]*</ruby>" "ruby")
5641 ("^#\\+begin_src\\( \\([^ \t\n]+\\)\\)?.*\n" "\n#\\+end_src" 2)
5642 ("^#\\+begin_example.*\n" "\n#\\+end_example" "fundamental")
5643 ("^#\\+html:" "\n" "html" single-line)
5644 ("^#\\+begin_html.*\n" "\n#\\+end_html" "html")
5645 ("^#\\+begin_latex.*\n" "\n#\\+end_latex" "latex")
5646 ("^#\\+latex:" "\n" "latex" single-line)
5647 ("^#\\+begin_ascii.*\n" "\n#\\+end_ascii" "fundamental")
5648 ("^#\\+ascii:" "\n" "ascii" single-line)
5650 (pos (point))
5651 re re1 re2 single beg end lang)
5652 (catch 'exit
5653 (while (setq entry (pop re-list))
5654 (setq re1 (car entry) re2 (nth 1 entry) lang (nth 2 entry)
5655 single (nth 3 entry))
5656 (save-excursion
5657 (if (or (looking-at re1)
5658 (re-search-backward re1 nil t))
5659 (progn
5660 (setq beg (match-end 0) lang (org-edit-src-get-lang lang))
5661 (if (and (re-search-forward re2 nil t)
5662 (>= (match-end 0) pos))
5663 (throw 'exit (list beg (match-beginning 0) lang single))))
5664 (if (or (looking-at re2)
5665 (re-search-forward re2 nil t))
5666 (progn
5667 (setq end (match-beginning 0))
5668 (if (and (re-search-backward re1 nil t)
5669 (<= (match-beginning 0) pos))
5670 (throw 'exit
5671 (list (match-end 0) end
5672 (org-edit-src-get-lang lang) single)))))))))))
5674 (defun org-edit-src-get-lang (lang)
5675 "Extract the src language."
5676 (let ((m (match-string 0)))
5677 (cond
5678 ((stringp lang) lang)
5679 ((integerp lang) (match-string lang))
5680 ((and (eq lang 'lang)
5681 (string-match "\\<lang=\"\\([^ \t\n\"]+\\)\"" m))
5682 (match-string 1 m))
5683 ((and (eq lang 'style)
5684 (string-match "\\<style=\"\\([^ \t\n\"]+\\)\"" m))
5685 (match-string 1 m))
5686 (t "fundamental"))))
5688 (defun org-edit-src-exit ()
5689 "Exit special edit and protect problematic lines."
5690 (interactive)
5691 (unless (buffer-base-buffer (current-buffer))
5692 (error "This is not an indirect buffer, something is wrong..."))
5693 (unless (> (point-min) 1)
5694 (error "This buffer is not narrowed, something is wrong..."))
5695 (goto-char (point-min))
5696 (if (looking-at "[ \t\n]*\n") (replace-match ""))
5697 (if (re-search-forward "\n[ \t\n]*\\'" nil t) (replace-match ""))
5698 (when (org-bound-and-true-p org-edit-src-force-single-line)
5699 (goto-char (point-min))
5700 (while (re-search-forward "\n" nil t)
5701 (replace-match " "))
5702 (goto-char (point-min))
5703 (if (looking-at "\\s-*") (replace-match " "))
5704 (if (re-search-forward "\\s-+\\'" nil t)
5705 (replace-match "")))
5706 (when (org-bound-and-true-p org-edit-src-from-org-mode)
5707 (goto-char (point-min))
5708 (while (re-search-forward (if (org-mode-p) "^\\(.\\)" "^\\([*#]\\)") nil t)
5709 (replace-match ",\\1"))
5710 (when font-lock-mode
5711 (font-lock-unfontify-region (point-min) (point-max)))
5712 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
5713 (when (org-bound-and-true-p org-edit-src-picture)
5714 (goto-char (point-min))
5715 (while (re-search-forward "^" nil t)
5716 (replace-match ": "))
5717 (when font-lock-mode
5718 (font-lock-unfontify-region (point-min) (point-max)))
5719 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
5720 (kill-buffer (current-buffer))
5721 (and (org-mode-p) (org-restart-font-lock)))
5724 ;;; The orgstruct minor mode
5726 ;; Define a minor mode which can be used in other modes in order to
5727 ;; integrate the org-mode structure editing commands.
5729 ;; This is really a hack, because the org-mode structure commands use
5730 ;; keys which normally belong to the major mode. Here is how it
5731 ;; works: The minor mode defines all the keys necessary to operate the
5732 ;; structure commands, but wraps the commands into a function which
5733 ;; tests if the cursor is currently at a headline or a plain list
5734 ;; item. If that is the case, the structure command is used,
5735 ;; temporarily setting many Org-mode variables like regular
5736 ;; expressions for filling etc. However, when any of those keys is
5737 ;; used at a different location, function uses `key-binding' to look
5738 ;; up if the key has an associated command in another currently active
5739 ;; keymap (minor modes, major mode, global), and executes that
5740 ;; command. There might be problems if any of the keys is otherwise
5741 ;; used as a prefix key.
5743 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
5744 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
5745 ;; addresses this by checking explicitly for both bindings.
5747 (defvar orgstruct-mode-map (make-sparse-keymap)
5748 "Keymap for the minor `orgstruct-mode'.")
5750 (defvar org-local-vars nil
5751 "List of local variables, for use by `orgstruct-mode'")
5753 ;;;###autoload
5754 (define-minor-mode orgstruct-mode
5755 "Toggle the minor more `orgstruct-mode'.
5756 This mode is for using Org-mode structure commands in other modes.
5757 The following key behave as if Org-mode was active, if the cursor
5758 is on a headline, or on a plain list item (both in the definition
5759 of Org-mode).
5761 M-up Move entry/item up
5762 M-down Move entry/item down
5763 M-left Promote
5764 M-right Demote
5765 M-S-up Move entry/item up
5766 M-S-down Move entry/item down
5767 M-S-left Promote subtree
5768 M-S-right Demote subtree
5769 M-q Fill paragraph and items like in Org-mode
5770 C-c ^ Sort entries
5771 C-c - Cycle list bullet
5772 TAB Cycle item visibility
5773 M-RET Insert new heading/item
5774 S-M-RET Insert new TODO heading / Chekbox item
5775 C-c C-c Set tags / toggle checkbox"
5776 nil " OrgStruct" nil
5777 (org-load-modules-maybe)
5778 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
5780 ;;;###autoload
5781 (defun turn-on-orgstruct ()
5782 "Unconditionally turn on `orgstruct-mode'."
5783 (orgstruct-mode 1))
5785 ;;;###autoload
5786 (defun turn-on-orgstruct++ ()
5787 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
5788 In addition to setting orgstruct-mode, this also exports all indentation and
5789 autofilling variables from org-mode into the buffer. Note that turning
5790 off orgstruct-mode will *not* remove these additional settings."
5791 (orgstruct-mode 1)
5792 (let (var val)
5793 (mapc
5794 (lambda (x)
5795 (when (string-match
5796 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
5797 (symbol-name (car x)))
5798 (setq var (car x) val (nth 1 x))
5799 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
5800 org-local-vars)))
5802 (defun orgstruct-error ()
5803 "Error when there is no default binding for a structure key."
5804 (interactive)
5805 (error "This key has no function outside structure elements"))
5807 (defun orgstruct-setup ()
5808 "Setup orgstruct keymaps."
5809 (let ((nfunc 0)
5810 (bindings
5811 (list
5812 '([(meta up)] org-metaup)
5813 '([(meta down)] org-metadown)
5814 '([(meta left)] org-metaleft)
5815 '([(meta right)] org-metaright)
5816 '([(meta shift up)] org-shiftmetaup)
5817 '([(meta shift down)] org-shiftmetadown)
5818 '([(meta shift left)] org-shiftmetaleft)
5819 '([(meta shift right)] org-shiftmetaright)
5820 '([(shift up)] org-shiftup)
5821 '([(shift down)] org-shiftdown)
5822 '("\C-c\C-c" org-ctrl-c-ctrl-c)
5823 '("\M-q" fill-paragraph)
5824 '("\C-c^" org-sort)
5825 '("\C-c-" org-cycle-list-bullet)))
5826 elt key fun cmd)
5827 (while (setq elt (pop bindings))
5828 (setq nfunc (1+ nfunc))
5829 (setq key (org-key (car elt))
5830 fun (nth 1 elt)
5831 cmd (orgstruct-make-binding fun nfunc key))
5832 (org-defkey orgstruct-mode-map key cmd))
5834 ;; Special treatment needed for TAB and RET
5835 (org-defkey orgstruct-mode-map [(tab)]
5836 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
5837 (org-defkey orgstruct-mode-map "\C-i"
5838 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
5840 (org-defkey orgstruct-mode-map "\M-\C-m"
5841 (orgstruct-make-binding 'org-insert-heading 105
5842 "\M-\C-m" [(meta return)]))
5843 (org-defkey orgstruct-mode-map [(meta return)]
5844 (orgstruct-make-binding 'org-insert-heading 106
5845 [(meta return)] "\M-\C-m"))
5847 (org-defkey orgstruct-mode-map [(shift meta return)]
5848 (orgstruct-make-binding 'org-insert-todo-heading 107
5849 [(meta return)] "\M-\C-m"))
5851 (unless org-local-vars
5852 (setq org-local-vars (org-get-local-variables)))
5856 (defun orgstruct-make-binding (fun n &rest keys)
5857 "Create a function for binding in the structure minor mode.
5858 FUN is the command to call inside a table. N is used to create a unique
5859 command name. KEYS are keys that should be checked in for a command
5860 to execute outside of tables."
5861 (eval
5862 (list 'defun
5863 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
5864 '(arg)
5865 (concat "In Structure, run `" (symbol-name fun) "'.\n"
5866 "Outside of structure, run the binding of `"
5867 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
5868 "'.")
5869 '(interactive "p")
5870 (list 'if
5871 '(org-context-p 'headline 'item)
5872 (list 'org-run-like-in-org-mode (list 'quote fun))
5873 (list 'let '(orgstruct-mode)
5874 (list 'call-interactively
5875 (append '(or)
5876 (mapcar (lambda (k)
5877 (list 'key-binding k))
5878 keys)
5879 '('orgstruct-error))))))))
5881 (defun org-context-p (&rest contexts)
5882 "Check if local context is any of CONTEXTS.
5883 Possible values in the list of contexts are `table', `headline', and `item'."
5884 (let ((pos (point)))
5885 (goto-char (point-at-bol))
5886 (prog1 (or (and (memq 'table contexts)
5887 (looking-at "[ \t]*|"))
5888 (and (memq 'headline contexts)
5889 ;;????????? (looking-at "\\*+"))
5890 (looking-at outline-regexp))
5891 (and (memq 'item contexts)
5892 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
5893 (goto-char pos))))
5895 (defun org-get-local-variables ()
5896 "Return a list of all local variables in an org-mode buffer."
5897 (let (varlist)
5898 (with-current-buffer (get-buffer-create "*Org tmp*")
5899 (erase-buffer)
5900 (org-mode)
5901 (setq varlist (buffer-local-variables)))
5902 (kill-buffer "*Org tmp*")
5903 (delq nil
5904 (mapcar
5905 (lambda (x)
5906 (setq x
5907 (if (symbolp x)
5908 (list x)
5909 (list (car x) (list 'quote (cdr x)))))
5910 (if (string-match
5911 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
5912 (symbol-name (car x)))
5913 x nil))
5914 varlist))))
5916 ;;;###autoload
5917 (defun org-run-like-in-org-mode (cmd)
5918 (org-load-modules-maybe)
5919 (unless org-local-vars
5920 (setq org-local-vars (org-get-local-variables)))
5921 (eval (list 'let org-local-vars
5922 (list 'call-interactively (list 'quote cmd)))))
5924 ;;;; Archiving
5926 (defun org-get-category (&optional pos)
5927 "Get the category applying to position POS."
5928 (get-text-property (or pos (point)) 'org-category))
5930 (defun org-refresh-category-properties ()
5931 "Refresh category text properties in the buffer."
5932 (let ((def-cat (cond
5933 ((null org-category)
5934 (if buffer-file-name
5935 (file-name-sans-extension
5936 (file-name-nondirectory buffer-file-name))
5937 "???"))
5938 ((symbolp org-category) (symbol-name org-category))
5939 (t org-category)))
5940 beg end cat pos optionp)
5941 (org-unmodified
5942 (save-excursion
5943 (save-restriction
5944 (widen)
5945 (goto-char (point-min))
5946 (put-text-property (point) (point-max) 'org-category def-cat)
5947 (while (re-search-forward
5948 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
5949 (setq pos (match-end 0)
5950 optionp (equal (char-after (match-beginning 0)) ?#)
5951 cat (org-trim (match-string 2)))
5952 (if optionp
5953 (setq beg (point-at-bol) end (point-max))
5954 (org-back-to-heading t)
5955 (setq beg (point) end (org-end-of-subtree t t)))
5956 (put-text-property beg end 'org-category cat)
5957 (goto-char pos)))))))
5960 ;;;; Link Stuff
5962 ;;; Link abbreviations
5964 (defun org-link-expand-abbrev (link)
5965 "Apply replacements as defined in `org-link-abbrev-alist."
5966 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
5967 (let* ((key (match-string 1 link))
5968 (as (or (assoc key org-link-abbrev-alist-local)
5969 (assoc key org-link-abbrev-alist)))
5970 (tag (and (match-end 2) (match-string 3 link)))
5971 rpl)
5972 (if (not as)
5973 link
5974 (setq rpl (cdr as))
5975 (cond
5976 ((symbolp rpl) (funcall rpl tag))
5977 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
5978 (t (concat rpl tag)))))
5979 link))
5981 ;;; Storing and inserting links
5983 (defvar org-insert-link-history nil
5984 "Minibuffer history for links inserted with `org-insert-link'.")
5986 (defvar org-stored-links nil
5987 "Contains the links stored with `org-store-link'.")
5989 (defvar org-store-link-plist nil
5990 "Plist with info about the most recently link created with `org-store-link'.")
5992 (defvar org-link-protocols nil
5993 "Link protocols added to Org-mode using `org-add-link-type'.")
5995 (defvar org-store-link-functions nil
5996 "List of functions that are called to create and store a link.
5997 Each function will be called in turn until one returns a non-nil
5998 value. Each function should check if it is responsible for creating
5999 this link (for example by looking at the major mode).
6000 If not, it must exit and return nil.
6001 If yes, it should return a non-nil value after a calling
6002 `org-store-link-props' with a list of properties and values.
6003 Special properties are:
6005 :type The link prefix. like \"http\". This must be given.
6006 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6007 This is obligatory as well.
6008 :description Optional default description for the second pair
6009 of brackets in an Org-mode link. The user can still change
6010 this when inserting this link into an Org-mode buffer.
6012 In addition to these, any additional properties can be specified
6013 and then used in remember templates.")
6015 (defun org-add-link-type (type &optional follow export)
6016 "Add TYPE to the list of `org-link-types'.
6017 Re-compute all regular expressions depending on `org-link-types'
6019 FOLLOW and EXPORT are two functions.
6021 FOLLOW should take the link path as the single argument and do whatever
6022 is necessary to follow the link, for example find a file or display
6023 a mail message.
6025 EXPORT should format the link path for export to one of the export formats.
6026 It should be a function accepting three arguments:
6028 path the path of the link, the text after the prefix (like \"http:\")
6029 desc the description of the link, if any, nil if there was no descripton
6030 format the export format, a symbol like `html' or `latex'.
6032 The function may use the FORMAT information to return different values
6033 depending on the format. The return value will be put literally into
6034 the exported file.
6035 Org-mode has a built-in default for exporting links. If you are happy with
6036 this default, there is no need to define an export function for the link
6037 type. For a simple example of an export function, see `org-bbdb.el'."
6038 (add-to-list 'org-link-types type t)
6039 (org-make-link-regexps)
6040 (if (assoc type org-link-protocols)
6041 (setcdr (assoc type org-link-protocols) (list follow export))
6042 (push (list type follow export) org-link-protocols)))
6045 ;;;###autoload
6046 (defun org-store-link (arg)
6047 "\\<org-mode-map>Store an org-link to the current location.
6048 This link is added to `org-stored-links' and can later be inserted
6049 into an org-buffer with \\[org-insert-link].
6051 For some link types, a prefix arg is interpreted:
6052 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
6053 For file links, arg negates `org-context-in-file-links'."
6054 (interactive "P")
6055 (org-load-modules-maybe)
6056 (setq org-store-link-plist nil) ; reset
6057 (let (link cpltxt desc description search txt)
6058 (cond
6060 ((run-hook-with-args-until-success 'org-store-link-functions)
6061 (setq link (plist-get org-store-link-plist :link)
6062 desc (or (plist-get org-store-link-plist :description) link)))
6064 ((eq major-mode 'calendar-mode)
6065 (let ((cd (calendar-cursor-to-date)))
6066 (setq link
6067 (format-time-string
6068 (car org-time-stamp-formats)
6069 (apply 'encode-time
6070 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6071 nil nil nil))))
6072 (org-store-link-props :type "calendar" :date cd)))
6074 ((eq major-mode 'w3-mode)
6075 (setq cpltxt (url-view-url t)
6076 link (org-make-link cpltxt))
6077 (org-store-link-props :type "w3" :url (url-view-url t)))
6079 ((eq major-mode 'w3m-mode)
6080 (setq cpltxt (or w3m-current-title w3m-current-url)
6081 link (org-make-link w3m-current-url))
6082 (org-store-link-props :type "w3m" :url (url-view-url t)))
6084 ((setq search (run-hook-with-args-until-success
6085 'org-create-file-search-functions))
6086 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6087 "::" search))
6088 (setq cpltxt (or description link)))
6090 ((eq major-mode 'image-mode)
6091 (setq cpltxt (concat "file:"
6092 (abbreviate-file-name buffer-file-name))
6093 link (org-make-link cpltxt))
6094 (org-store-link-props :type "image" :file buffer-file-name))
6096 ((eq major-mode 'dired-mode)
6097 ;; link to the file in the current line
6098 (setq cpltxt (concat "file:"
6099 (abbreviate-file-name
6100 (expand-file-name
6101 (dired-get-filename nil t))))
6102 link (org-make-link cpltxt)))
6104 ((and buffer-file-name (org-mode-p))
6105 ;; Just link to current headline
6106 (setq cpltxt (concat "file:"
6107 (abbreviate-file-name buffer-file-name)))
6108 ;; Add a context search string
6109 (when (org-xor org-context-in-file-links arg)
6110 ;; Check if we are on a target
6111 (if (org-in-regexp "<<\\(.*?\\)>>")
6112 (setq cpltxt (concat cpltxt "::" (match-string 1)))
6113 (setq txt (cond
6114 ((org-on-heading-p) nil)
6115 ((org-region-active-p)
6116 (buffer-substring (region-beginning) (region-end)))
6117 (t nil)))
6118 (when (or (null txt) (string-match "\\S-" txt))
6119 (setq cpltxt
6120 (concat cpltxt "::"
6121 (condition-case nil
6122 (org-make-org-heading-search-string txt)
6123 (error "")))
6124 desc "NONE"))))
6125 (if (string-match "::\\'" cpltxt)
6126 (setq cpltxt (substring cpltxt 0 -2)))
6127 (setq link (org-make-link cpltxt)))
6129 ((buffer-file-name (buffer-base-buffer))
6130 ;; Just link to this file here.
6131 (setq cpltxt (concat "file:"
6132 (abbreviate-file-name
6133 (buffer-file-name (buffer-base-buffer)))))
6134 ;; Add a context string
6135 (when (org-xor org-context-in-file-links arg)
6136 (setq txt (if (org-region-active-p)
6137 (buffer-substring (region-beginning) (region-end))
6138 (buffer-substring (point-at-bol) (point-at-eol))))
6139 ;; Only use search option if there is some text.
6140 (when (string-match "\\S-" txt)
6141 (setq cpltxt
6142 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6143 desc "NONE")))
6144 (setq link (org-make-link cpltxt)))
6146 ((interactive-p)
6147 (error "Cannot link to a buffer which is not visiting a file"))
6149 (t (setq link nil)))
6151 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6152 (setq link (or link cpltxt)
6153 desc (or desc cpltxt))
6154 (if (equal desc "NONE") (setq desc nil))
6156 (if (and (interactive-p) link)
6157 (progn
6158 (setq org-stored-links
6159 (cons (list link desc) org-stored-links))
6160 (message "Stored: %s" (or desc link)))
6161 (and link (org-make-link-string link desc)))))
6163 (defun org-store-link-props (&rest plist)
6164 "Store link properties, extract names and addresses."
6165 (let (x adr)
6166 (when (setq x (plist-get plist :from))
6167 (setq adr (mail-extract-address-components x))
6168 (setq plist (plist-put plist :fromname (car adr)))
6169 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
6170 (when (setq x (plist-get plist :to))
6171 (setq adr (mail-extract-address-components x))
6172 (setq plist (plist-put plist :toname (car adr)))
6173 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
6174 (let ((from (plist-get plist :from))
6175 (to (plist-get plist :to)))
6176 (when (and from to org-from-is-user-regexp)
6177 (setq plist
6178 (plist-put plist :fromto
6179 (if (string-match org-from-is-user-regexp from)
6180 (concat "to %t")
6181 (concat "from %f"))))))
6182 (setq org-store-link-plist plist))
6184 (defun org-add-link-props (&rest plist)
6185 "Add these properties to the link property list."
6186 (let (key value)
6187 (while plist
6188 (setq key (pop plist) value (pop plist))
6189 (setq org-store-link-plist
6190 (plist-put org-store-link-plist key value)))))
6192 (defun org-email-link-description (&optional fmt)
6193 "Return the description part of an email link.
6194 This takes information from `org-store-link-plist' and formats it
6195 according to FMT (default from `org-email-link-description-format')."
6196 (setq fmt (or fmt org-email-link-description-format))
6197 (let* ((p org-store-link-plist)
6198 (to (plist-get p :toaddress))
6199 (from (plist-get p :fromaddress))
6200 (table
6201 (list
6202 (cons "%c" (plist-get p :fromto))
6203 (cons "%F" (plist-get p :from))
6204 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
6205 (cons "%T" (plist-get p :to))
6206 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
6207 (cons "%s" (plist-get p :subject))
6208 (cons "%m" (plist-get p :message-id)))))
6209 (when (string-match "%c" fmt)
6210 ;; Check if the user wrote this message
6211 (if (and org-from-is-user-regexp from to
6212 (save-match-data (string-match org-from-is-user-regexp from)))
6213 (setq fmt (replace-match "to %t" t t fmt))
6214 (setq fmt (replace-match "from %f" t t fmt))))
6215 (org-replace-escapes fmt table)))
6217 (defun org-make-org-heading-search-string (&optional string heading)
6218 "Make search string for STRING or current headline."
6219 (interactive)
6220 (let ((s (or string (org-get-heading))))
6221 (unless (and string (not heading))
6222 ;; We are using a headline, clean up garbage in there.
6223 (if (string-match org-todo-regexp s)
6224 (setq s (replace-match "" t t s)))
6225 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
6226 (setq s (replace-match "" t t s)))
6227 (setq s (org-trim s))
6228 (if (string-match (concat "^\\(" org-quote-string "\\|"
6229 org-comment-string "\\)") s)
6230 (setq s (replace-match "" t t s)))
6231 (while (string-match org-ts-regexp s)
6232 (setq s (replace-match "" t t s))))
6233 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
6234 (setq s (replace-match " " t t s)))
6235 (or string (setq s (concat "*" s))) ; Add * for headlines
6236 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
6238 (defun org-make-link (&rest strings)
6239 "Concatenate STRINGS."
6240 (apply 'concat strings))
6242 (defun org-make-link-string (link &optional description)
6243 "Make a link with brackets, consisting of LINK and DESCRIPTION."
6244 (unless (string-match "\\S-" link)
6245 (error "Empty link"))
6246 (when (stringp description)
6247 ;; Remove brackets from the description, they are fatal.
6248 (while (string-match "\\[" description)
6249 (setq description (replace-match "{" t t description)))
6250 (while (string-match "\\]" description)
6251 (setq description (replace-match "}" t t description))))
6252 (when (equal (org-link-escape link) description)
6253 ;; No description needed, it is identical
6254 (setq description nil))
6255 (when (and (not description)
6256 (not (equal link (org-link-escape link))))
6257 (setq description (org-extract-attributes link)))
6258 (concat "[[" (org-link-escape link) "]"
6259 (if description (concat "[" description "]") "")
6260 "]"))
6262 (defconst org-link-escape-chars
6263 '((?\ . "%20")
6264 (?\[ . "%5B")
6265 (?\] . "%5D")
6266 (?\340 . "%E0") ; `a
6267 (?\342 . "%E2") ; ^a
6268 (?\347 . "%E7") ; ,c
6269 (?\350 . "%E8") ; `e
6270 (?\351 . "%E9") ; 'e
6271 (?\352 . "%EA") ; ^e
6272 (?\356 . "%EE") ; ^i
6273 (?\364 . "%F4") ; ^o
6274 (?\371 . "%F9") ; `u
6275 (?\373 . "%FB") ; ^u
6276 (?\; . "%3B")
6277 (?? . "%3F")
6278 (?= . "%3D")
6279 (?+ . "%2B")
6281 "Association list of escapes for some characters problematic in links.
6282 This is the list that is used for internal purposes.")
6284 (defconst org-link-escape-chars-browser
6285 '((?\ . "%20")) ; 32 for the SPC char
6286 "Association list of escapes for some characters problematic in links.
6287 This is the list that is used before handing over to the browser.")
6289 (defun org-link-escape (text &optional table)
6290 "Escape charaters in TEXT that are problematic for links."
6291 (setq table (or table org-link-escape-chars))
6292 (when text
6293 (let ((re (mapconcat (lambda (x) (regexp-quote
6294 (char-to-string (car x))))
6295 table "\\|")))
6296 (while (string-match re text)
6297 (setq text
6298 (replace-match
6299 (cdr (assoc (string-to-char (match-string 0 text))
6300 table))
6301 t t text)))
6302 text)))
6304 (defun org-link-unescape (text &optional table)
6305 "Reverse the action of `org-link-escape'."
6306 (setq table (or table org-link-escape-chars))
6307 (when text
6308 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
6309 table "\\|")))
6310 (while (string-match re text)
6311 (setq text
6312 (replace-match
6313 (char-to-string (car (rassoc (match-string 0 text) table)))
6314 t t text)))
6315 text)))
6317 (defun org-xor (a b)
6318 "Exclusive or."
6319 (if a (not b) b))
6321 (defun org-get-header (header)
6322 "Find a header field in the current buffer."
6323 (save-excursion
6324 (goto-char (point-min))
6325 (let ((case-fold-search t) s)
6326 (cond
6327 ((eq header 'from)
6328 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
6329 (setq s (match-string 1)))
6330 (while (string-match "\"" s)
6331 (setq s (replace-match "" t t s)))
6332 (if (string-match "[<(].*" s)
6333 (setq s (replace-match "" t t s))))
6334 ((eq header 'message-id)
6335 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
6336 (setq s (match-string 1))))
6337 ((eq header 'subject)
6338 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
6339 (setq s (match-string 1)))))
6340 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
6341 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
6342 s)))
6345 (defun org-fixup-message-id-for-http (s)
6346 "Replace special characters in a message id, so it can be used in an http query."
6347 (while (string-match "<" s)
6348 (setq s (replace-match "%3C" t t s)))
6349 (while (string-match ">" s)
6350 (setq s (replace-match "%3E" t t s)))
6351 (while (string-match "@" s)
6352 (setq s (replace-match "%40" t t s)))
6355 ;;;###autoload
6356 (defun org-insert-link-global ()
6357 "Insert a link like Org-mode does.
6358 This command can be called in any mode to insert a link in Org-mode syntax."
6359 (interactive)
6360 (org-load-modules-maybe)
6361 (org-run-like-in-org-mode 'org-insert-link))
6363 (defun org-insert-link (&optional complete-file link-location)
6364 "Insert a link. At the prompt, enter the link.
6366 Completion can be used to insert any of the link protocol prefixes like
6367 http or ftp in use.
6369 The history can be used to select a link previously stored with
6370 `org-store-link'. When the empty string is entered (i.e. if you just
6371 press RET at the prompt), the link defaults to the most recently
6372 stored link. As SPC triggers completion in the minibuffer, you need to
6373 use M-SPC or C-q SPC to force the insertion of a space character.
6375 You will also be prompted for a description, and if one is given, it will
6376 be displayed in the buffer instead of the link.
6378 If there is already a link at point, this command will allow you to edit link
6379 and description parts.
6381 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
6382 be selected using completion. The path to the file will be relative to the
6383 current directory if the file is in the current directory or a subdirectory.
6384 Otherwise, the link will be the absolute path as completed in the minibuffer
6385 \(i.e. normally ~/path/to/file). You can configure this behavior using the
6386 option `org-link-file-path-type'.
6388 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
6389 the current directory or below.
6391 With three \\[universal-argument] prefixes, negate the meaning of
6392 `org-keep-stored-link-after-insertion'.
6394 If `org-make-link-description-function' is non-nil, this function will be
6395 called with the link target, and the result will be the default
6396 link description.
6398 If the LINK-LOCATION parameter is non-nil, this value will be
6399 used as the link location instead of reading one interactively."
6400 (interactive "P")
6401 (let* ((wcf (current-window-configuration))
6402 (region (if (org-region-active-p)
6403 (buffer-substring (region-beginning) (region-end))))
6404 (remove (and region (list (region-beginning) (region-end))))
6405 (desc region)
6406 tmphist ; byte-compile incorrectly complains about this
6407 (link link-location)
6408 entry file)
6409 (cond
6410 (link-location) ; specified by arg, just use it.
6411 ((org-in-regexp org-bracket-link-regexp 1)
6412 ;; We do have a link at point, and we are going to edit it.
6413 (setq remove (list (match-beginning 0) (match-end 0)))
6414 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
6415 (setq link (read-string "Link: "
6416 (org-link-unescape
6417 (org-match-string-no-properties 1)))))
6418 ((or (org-in-regexp org-angle-link-re)
6419 (org-in-regexp org-plain-link-re))
6420 ;; Convert to bracket link
6421 (setq remove (list (match-beginning 0) (match-end 0))
6422 link (read-string "Link: "
6423 (org-remove-angle-brackets (match-string 0)))))
6424 ((member complete-file '((4) (16)))
6425 ;; Completing read for file names.
6426 (setq file (read-file-name "File: "))
6427 (let ((pwd (file-name-as-directory (expand-file-name ".")))
6428 (pwd1 (file-name-as-directory (abbreviate-file-name
6429 (expand-file-name ".")))))
6430 (cond
6431 ((equal complete-file '(16))
6432 (setq link (org-make-link
6433 "file:"
6434 (abbreviate-file-name (expand-file-name file)))))
6435 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
6436 (setq link (org-make-link "file:" (match-string 1 file))))
6437 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
6438 (expand-file-name file))
6439 (setq link (org-make-link
6440 "file:" (match-string 1 (expand-file-name file)))))
6441 (t (setq link (org-make-link "file:" file))))))
6443 ;; Read link, with completion for stored links.
6444 (with-output-to-temp-buffer "*Org Links*"
6445 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
6446 (when org-stored-links
6447 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
6448 (princ (mapconcat
6449 (lambda (x)
6450 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
6451 (reverse org-stored-links) "\n"))))
6452 (let ((cw (selected-window)))
6453 (select-window (get-buffer-window "*Org Links*"))
6454 (org-fit-window-to-buffer)
6455 (setq truncate-lines t)
6456 (select-window cw))
6457 ;; Fake a link history, containing the stored links.
6458 (setq tmphist (append (mapcar 'car org-stored-links)
6459 org-insert-link-history))
6460 (unwind-protect
6461 (setq link (org-completing-read
6462 "Link: "
6463 (append
6464 (mapcar (lambda (x) (list (concat (car x) ":")))
6465 (append org-link-abbrev-alist-local org-link-abbrev-alist))
6466 (mapcar (lambda (x) (list (concat x ":")))
6467 org-link-types))
6468 nil nil nil
6469 'tmphist
6470 (or (car (car org-stored-links)))))
6471 (set-window-configuration wcf)
6472 (kill-buffer "*Org Links*"))
6473 (setq entry (assoc link org-stored-links))
6474 (or entry (push link org-insert-link-history))
6475 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
6476 (not org-keep-stored-link-after-insertion))
6477 (setq org-stored-links (delq (assoc link org-stored-links)
6478 org-stored-links)))
6479 (setq desc (or desc (nth 1 entry)))))
6481 (if (string-match org-plain-link-re link)
6482 ;; URL-like link, normalize the use of angular brackets.
6483 (setq link (org-make-link (org-remove-angle-brackets link))))
6485 ;; Check if we are linking to the current file with a search option
6486 ;; If yes, simplify the link by using only the search option.
6487 (when (and buffer-file-name
6488 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
6489 (let* ((path (match-string 1 link))
6490 (case-fold-search nil)
6491 (search (match-string 2 link)))
6492 (save-match-data
6493 (if (equal (file-truename buffer-file-name) (file-truename path))
6494 ;; We are linking to this same file, with a search option
6495 (setq link search)))))
6497 ;; Check if we can/should use a relative path. If yes, simplify the link
6498 (when (string-match "\\<file:\\(.*\\)" link)
6499 (let* ((path (match-string 1 link))
6500 (origpath path)
6501 (case-fold-search nil))
6502 (cond
6503 ((or (eq org-link-file-path-type 'absolute)
6504 (equal complete-file '(16)))
6505 (setq path (abbreviate-file-name (expand-file-name path))))
6506 ((eq org-link-file-path-type 'noabbrev)
6507 (setq path (expand-file-name path)))
6508 ((eq org-link-file-path-type 'relative)
6509 (setq path (file-relative-name path)))
6511 (save-match-data
6512 (if (string-match (concat "^" (regexp-quote
6513 (file-name-as-directory
6514 (expand-file-name "."))))
6515 (expand-file-name path))
6516 ;; We are linking a file with relative path name.
6517 (setq path (substring (expand-file-name path)
6518 (match-end 0)))
6519 (setq path (abbreviate-file-name (expand-file-name path)))))))
6520 (setq link (concat "file:" path))
6521 (if (equal desc origpath)
6522 (setq desc path))))
6524 (if org-make-link-description-function
6525 (setq desc (funcall org-make-link-description-function link desc)))
6527 (setq desc (read-string "Description: " desc))
6528 (unless (string-match "\\S-" desc) (setq desc nil))
6529 (if remove (apply 'delete-region remove))
6530 (insert (org-make-link-string link desc))))
6532 (defun org-completing-read (&rest args)
6533 "Completing-read with SPACE being a normal character."
6534 (let ((minibuffer-local-completion-map
6535 (copy-keymap minibuffer-local-completion-map)))
6536 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
6537 (apply 'completing-read args)))
6539 (defun org-extract-attributes (s)
6540 "Extract the attributes cookie from a string and set as text property."
6541 (let (a attr (start 0) key value)
6542 (save-match-data
6543 (when (string-match "{{\\([^}]+\\)}}$" s)
6544 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
6545 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
6546 (setq key (match-string 1 a) value (match-string 2 a)
6547 start (match-end 0)
6548 attr (plist-put attr (intern key) value))))
6549 (org-add-props s nil 'org-attributes attr))
6552 (defun org-attributes-to-string (plist)
6553 "Format a property list into an HTML attribute list."
6554 (let ((s "") key value)
6555 (while plist
6556 (setq key (pop plist) value (pop plist))
6557 (setq s (concat s " "(symbol-name key) "=\"" value "\"")))
6560 ;;; Opening/following a link
6562 (defvar org-link-search-failed nil)
6564 (defun org-next-link ()
6565 "Move forward to the next link.
6566 If the link is in hidden text, expose it."
6567 (interactive)
6568 (when (and org-link-search-failed (eq this-command last-command))
6569 (goto-char (point-min))
6570 (message "Link search wrapped back to beginning of buffer"))
6571 (setq org-link-search-failed nil)
6572 (let* ((pos (point))
6573 (ct (org-context))
6574 (a (assoc :link ct)))
6575 (if a (goto-char (nth 2 a)))
6576 (if (re-search-forward org-any-link-re nil t)
6577 (progn
6578 (goto-char (match-beginning 0))
6579 (if (org-invisible-p) (org-show-context)))
6580 (goto-char pos)
6581 (setq org-link-search-failed t)
6582 (error "No further link found"))))
6584 (defun org-previous-link ()
6585 "Move backward to the previous link.
6586 If the link is in hidden text, expose it."
6587 (interactive)
6588 (when (and org-link-search-failed (eq this-command last-command))
6589 (goto-char (point-max))
6590 (message "Link search wrapped back to end of buffer"))
6591 (setq org-link-search-failed nil)
6592 (let* ((pos (point))
6593 (ct (org-context))
6594 (a (assoc :link ct)))
6595 (if a (goto-char (nth 1 a)))
6596 (if (re-search-backward org-any-link-re nil t)
6597 (progn
6598 (goto-char (match-beginning 0))
6599 (if (org-invisible-p) (org-show-context)))
6600 (goto-char pos)
6601 (setq org-link-search-failed t)
6602 (error "No further link found"))))
6604 (defun org-find-file-at-mouse (ev)
6605 "Open file link or URL at mouse."
6606 (interactive "e")
6607 (mouse-set-point ev)
6608 (org-open-at-point 'in-emacs))
6610 (defun org-open-at-mouse (ev)
6611 "Open file link or URL at mouse."
6612 (interactive "e")
6613 (mouse-set-point ev)
6614 (org-open-at-point))
6616 (defvar org-window-config-before-follow-link nil
6617 "The window configuration before following a link.
6618 This is saved in case the need arises to restore it.")
6620 (defvar org-open-link-marker (make-marker)
6621 "Marker pointing to the location where `org-open-at-point; was called.")
6623 ;;;###autoload
6624 (defun org-open-at-point-global ()
6625 "Follow a link like Org-mode does.
6626 This command can be called in any mode to follow a link that has
6627 Org-mode syntax."
6628 (interactive)
6629 (org-run-like-in-org-mode 'org-open-at-point))
6631 ;;;###autoload
6632 (defun org-open-link-from-string (s &optional arg)
6633 "Open a link in the string S, as if it was in Org-mode."
6634 (interactive "sLink: \nP")
6635 (with-temp-buffer
6636 (let ((org-inhibit-startup t))
6637 (org-mode)
6638 (insert s)
6639 (goto-char (point-min))
6640 (org-open-at-point arg))))
6642 (defun org-open-at-point (&optional in-emacs)
6643 "Open link at or after point.
6644 If there is no link at point, this function will search forward up to
6645 the end of the current subtree.
6646 Normally, files will be opened by an appropriate application. If the
6647 optional argument IN-EMACS is non-nil, Emacs will visit the file.
6648 With a double prefix argument, try to open outside of Emacs, in the
6649 application the system uses for this file type."
6650 (interactive "P")
6651 (org-load-modules-maybe)
6652 (move-marker org-open-link-marker (point))
6653 (setq org-window-config-before-follow-link (current-window-configuration))
6654 (org-remove-occur-highlights nil nil t)
6655 (if (org-at-timestamp-p t)
6656 (org-follow-timestamp-link)
6657 (let (type path link line search (pos (point)))
6658 (catch 'match
6659 (save-excursion
6660 (skip-chars-forward "^]\n\r")
6661 (when (org-in-regexp org-bracket-link-regexp)
6662 (setq link (org-extract-attributes
6663 (org-link-unescape (org-match-string-no-properties 1))))
6664 (while (string-match " *\n *" link)
6665 (setq link (replace-match " " t t link)))
6666 (setq link (org-link-expand-abbrev link))
6667 (cond
6668 ((or (file-name-absolute-p link)
6669 (string-match "^\\.\\.?/" link))
6670 (setq type "file" path link))
6671 ((string-match org-link-re-with-space2 link)
6672 (setq type (match-string 1 link) path (match-string 2 link)))
6673 (t (setq type "thisfile" path link)))
6674 (throw 'match t)))
6676 (when (get-text-property (point) 'org-linked-text)
6677 (setq type "thisfile"
6678 pos (if (get-text-property (1+ (point)) 'org-linked-text)
6679 (1+ (point)) (point))
6680 path (buffer-substring
6681 (previous-single-property-change pos 'org-linked-text)
6682 (next-single-property-change pos 'org-linked-text)))
6683 (throw 'match t))
6685 (save-excursion
6686 (when (or (org-in-regexp org-angle-link-re)
6687 (org-in-regexp org-plain-link-re))
6688 (setq type (match-string 1) path (match-string 2))
6689 (throw 'match t)))
6690 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
6691 (setq type "tree-match"
6692 path (match-string 1))
6693 (throw 'match t))
6694 (save-excursion
6695 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
6696 (setq type "tags"
6697 path (match-string 1))
6698 (while (string-match ":" path)
6699 (setq path (replace-match "+" t t path)))
6700 (throw 'match t))))
6701 (unless path
6702 (error "No link found"))
6703 ;; Remove any trailing spaces in path
6704 (if (string-match " +\\'" path)
6705 (setq path (replace-match "" t t path)))
6707 (cond
6709 ((assoc type org-link-protocols)
6710 (funcall (nth 1 (assoc type org-link-protocols)) path))
6712 ((equal type "mailto")
6713 (let ((cmd (car org-link-mailto-program))
6714 (args (cdr org-link-mailto-program)) args1
6715 (address path) (subject "") a)
6716 (if (string-match "\\(.*\\)::\\(.*\\)" path)
6717 (setq address (match-string 1 path)
6718 subject (org-link-escape (match-string 2 path))))
6719 (while args
6720 (cond
6721 ((not (stringp (car args))) (push (pop args) args1))
6722 (t (setq a (pop args))
6723 (if (string-match "%a" a)
6724 (setq a (replace-match address t t a)))
6725 (if (string-match "%s" a)
6726 (setq a (replace-match subject t t a)))
6727 (push a args1))))
6728 (apply cmd (nreverse args1))))
6730 ((member type '("http" "https" "ftp" "news"))
6731 (browse-url (concat type ":" (org-link-escape
6732 path org-link-escape-chars-browser))))
6734 ((member type '("message"))
6735 (browse-url (concat type ":" path)))
6737 ((string= type "tags")
6738 (org-tags-view in-emacs path))
6739 ((string= type "thisfile")
6740 (if in-emacs
6741 (switch-to-buffer-other-window
6742 (org-get-buffer-for-internal-link (current-buffer)))
6743 (org-mark-ring-push))
6744 (let ((cmd `(org-link-search
6745 ,path
6746 ,(cond ((equal in-emacs '(4)) 'occur)
6747 ((equal in-emacs '(16)) 'org-occur)
6748 (t nil))
6749 ,pos)))
6750 (condition-case nil (eval cmd)
6751 (error (progn (widen) (eval cmd))))))
6753 ((string= type "tree-match")
6754 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
6756 ((string= type "file")
6757 (if (string-match "::\\([0-9]+\\)\\'" path)
6758 (setq line (string-to-number (match-string 1 path))
6759 path (substring path 0 (match-beginning 0)))
6760 (if (string-match "::\\(.+\\)\\'" path)
6761 (setq search (match-string 1 path)
6762 path (substring path 0 (match-beginning 0)))))
6763 (if (string-match "[*?{]" (file-name-nondirectory path))
6764 (dired path)
6765 (org-open-file path in-emacs line search)))
6767 ((string= type "news")
6768 (require 'org-gnus)
6769 (org-gnus-follow-link path))
6771 ((string= type "shell")
6772 (let ((cmd path))
6773 (if (or (not org-confirm-shell-link-function)
6774 (funcall org-confirm-shell-link-function
6775 (format "Execute \"%s\" in shell? "
6776 (org-add-props cmd nil
6777 'face 'org-warning))))
6778 (progn
6779 (message "Executing %s" cmd)
6780 (shell-command cmd))
6781 (error "Abort"))))
6783 ((string= type "elisp")
6784 (let ((cmd path))
6785 (if (or (not org-confirm-elisp-link-function)
6786 (funcall org-confirm-elisp-link-function
6787 (format "Execute \"%s\" as elisp? "
6788 (org-add-props cmd nil
6789 'face 'org-warning))))
6790 (message "%s => %s" cmd (eval (read cmd)))
6791 (error "Abort"))))
6794 (browse-url-at-point)))))
6795 (move-marker org-open-link-marker nil)
6796 (run-hook-with-args 'org-follow-link-hook))
6798 ;;;; Time estimates
6800 (defun org-get-effort (&optional pom)
6801 "Get the effort estimate for the current entry."
6802 (org-entry-get pom org-effort-property))
6804 ;;; File search
6806 (defvar org-create-file-search-functions nil
6807 "List of functions to construct the right search string for a file link.
6808 These functions are called in turn with point at the location to
6809 which the link should point.
6811 A function in the hook should first test if it would like to
6812 handle this file type, for example by checking the major-mode or
6813 the file extension. If it decides not to handle this file, it
6814 should just return nil to give other functions a chance. If it
6815 does handle the file, it must return the search string to be used
6816 when following the link. The search string will be part of the
6817 file link, given after a double colon, and `org-open-at-point'
6818 will automatically search for it. If special measures must be
6819 taken to make the search successful, another function should be
6820 added to the companion hook `org-execute-file-search-functions',
6821 which see.
6823 A function in this hook may also use `setq' to set the variable
6824 `description' to provide a suggestion for the descriptive text to
6825 be used for this link when it gets inserted into an Org-mode
6826 buffer with \\[org-insert-link].")
6828 (defvar org-execute-file-search-functions nil
6829 "List of functions to execute a file search triggered by a link.
6831 Functions added to this hook must accept a single argument, the
6832 search string that was part of the file link, the part after the
6833 double colon. The function must first check if it would like to
6834 handle this search, for example by checking the major-mode or the
6835 file extension. If it decides not to handle this search, it
6836 should just return nil to give other functions a chance. If it
6837 does handle the search, it must return a non-nil value to keep
6838 other functions from trying.
6840 Each function can access the current prefix argument through the
6841 variable `current-prefix-argument'. Note that a single prefix is
6842 used to force opening a link in Emacs, so it may be good to only
6843 use a numeric or double prefix to guide the search function.
6845 In case this is needed, a function in this hook can also restore
6846 the window configuration before `org-open-at-point' was called using:
6848 (set-window-configuration org-window-config-before-follow-link)")
6850 (defun org-link-search (s &optional type avoid-pos)
6851 "Search for a link search option.
6852 If S is surrounded by forward slashes, it is interpreted as a
6853 regular expression. In org-mode files, this will create an `org-occur'
6854 sparse tree. In ordinary files, `occur' will be used to list matches.
6855 If the current buffer is in `dired-mode', grep will be used to search
6856 in all files. If AVOID-POS is given, ignore matches near that position."
6857 (let ((case-fold-search t)
6858 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
6859 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
6860 (append '(("") (" ") ("\t") ("\n"))
6861 org-emphasis-alist)
6862 "\\|") "\\)"))
6863 (pos (point))
6864 (pre nil) (post nil)
6865 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
6866 (cond
6867 ;; First check if there are any special
6868 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
6869 ;; Now try the builtin stuff
6870 ((save-excursion
6871 (goto-char (point-min))
6872 (and
6873 (re-search-forward
6874 (concat "<<" (regexp-quote s0) ">>") nil t)
6875 (setq type 'dedicated
6876 pos (match-beginning 0))))
6877 ;; There is an exact target for this
6878 (goto-char pos))
6879 ((string-match "^/\\(.*\\)/$" s)
6880 ;; A regular expression
6881 (cond
6882 ((org-mode-p)
6883 (org-occur (match-string 1 s)))
6884 ;;((eq major-mode 'dired-mode)
6885 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
6886 (t (org-do-occur (match-string 1 s)))))
6888 ;; A normal search strings
6889 (when (equal (string-to-char s) ?*)
6890 ;; Anchor on headlines, post may include tags.
6891 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
6892 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
6893 s (substring s 1)))
6894 (remove-text-properties
6895 0 (length s)
6896 '(face nil mouse-face nil keymap nil fontified nil) s)
6897 ;; Make a series of regular expressions to find a match
6898 (setq words (org-split-string s "[ \n\r\t]+")
6900 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
6901 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
6902 "\\)" markers)
6903 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
6904 re2a (concat "[ \t\r\n]" re2a_)
6905 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
6906 re4 (concat "[^a-zA-Z_]" re4_)
6908 re1 (concat pre re2 post)
6909 re3 (concat pre (if pre re4_ re4) post)
6910 re5 (concat pre ".*" re4)
6911 re2 (concat pre re2)
6912 re2a (concat pre (if pre re2a_ re2a))
6913 re4 (concat pre (if pre re4_ re4))
6914 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
6915 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
6916 re5 "\\)"
6918 (cond
6919 ((eq type 'org-occur) (org-occur reall))
6920 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
6921 (t (goto-char (point-min))
6922 (setq type 'fuzzy)
6923 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
6924 (org-search-not-self 1 re1 nil t)
6925 (org-search-not-self 1 re2 nil t)
6926 (org-search-not-self 1 re2a nil t)
6927 (org-search-not-self 1 re3 nil t)
6928 (org-search-not-self 1 re4 nil t)
6929 (org-search-not-self 1 re5 nil t)
6931 (goto-char (match-beginning 1))
6932 (goto-char pos)
6933 (error "No match")))))
6935 ;; Normal string-search
6936 (goto-char (point-min))
6937 (if (search-forward s nil t)
6938 (goto-char (match-beginning 0))
6939 (error "No match"))))
6940 (and (org-mode-p) (org-show-context 'link-search))
6941 type))
6943 (defun org-search-not-self (group &rest args)
6944 "Execute `re-search-forward', but only accept matches that do not
6945 enclose the position of `org-open-link-marker'."
6946 (let ((m org-open-link-marker))
6947 (catch 'exit
6948 (while (apply 're-search-forward args)
6949 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
6950 (goto-char (match-end group))
6951 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
6952 (> (match-beginning 0) (marker-position m))
6953 (< (match-end 0) (marker-position m)))
6954 (save-match-data
6955 (or (not (org-in-regexp
6956 org-bracket-link-analytic-regexp 1))
6957 (not (match-end 4)) ; no description
6958 (and (<= (match-beginning 4) (point))
6959 (>= (match-end 4) (point))))))
6960 (throw 'exit (point))))))))
6962 (defun org-get-buffer-for-internal-link (buffer)
6963 "Return a buffer to be used for displaying the link target of internal links."
6964 (cond
6965 ((not org-display-internal-link-with-indirect-buffer)
6966 buffer)
6967 ((string-match "(Clone)$" (buffer-name buffer))
6968 (message "Buffer is already a clone, not making another one")
6969 ;; we also do not modify visibility in this case
6970 buffer)
6971 (t ; make a new indirect buffer for displaying the link
6972 (let* ((bn (buffer-name buffer))
6973 (ibn (concat bn "(Clone)"))
6974 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
6975 (with-current-buffer ib (org-overview))
6976 ib))))
6978 (defun org-do-occur (regexp &optional cleanup)
6979 "Call the Emacs command `occur'.
6980 If CLEANUP is non-nil, remove the printout of the regular expression
6981 in the *Occur* buffer. This is useful if the regex is long and not useful
6982 to read."
6983 (occur regexp)
6984 (when cleanup
6985 (let ((cwin (selected-window)) win beg end)
6986 (when (setq win (get-buffer-window "*Occur*"))
6987 (select-window win))
6988 (goto-char (point-min))
6989 (when (re-search-forward "match[a-z]+" nil t)
6990 (setq beg (match-end 0))
6991 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
6992 (setq end (1- (match-beginning 0)))))
6993 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
6994 (goto-char (point-min))
6995 (select-window cwin))))
6997 ;;; The mark ring for links jumps
6999 (defvar org-mark-ring nil
7000 "Mark ring for positions before jumps in Org-mode.")
7001 (defvar org-mark-ring-last-goto nil
7002 "Last position in the mark ring used to go back.")
7003 ;; Fill and close the ring
7004 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7005 (loop for i from 1 to org-mark-ring-length do
7006 (push (make-marker) org-mark-ring))
7007 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7008 org-mark-ring)
7010 (defun org-mark-ring-push (&optional pos buffer)
7011 "Put the current position or POS into the mark ring and rotate it."
7012 (interactive)
7013 (setq pos (or pos (point)))
7014 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7015 (move-marker (car org-mark-ring)
7016 (or pos (point))
7017 (or buffer (current-buffer)))
7018 (message "%s"
7019 (substitute-command-keys
7020 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7022 (defun org-mark-ring-goto (&optional n)
7023 "Jump to the previous position in the mark ring.
7024 With prefix arg N, jump back that many stored positions. When
7025 called several times in succession, walk through the entire ring.
7026 Org-mode commands jumping to a different position in the current file,
7027 or to another Org-mode file, automatically push the old position
7028 onto the ring."
7029 (interactive "p")
7030 (let (p m)
7031 (if (eq last-command this-command)
7032 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7033 (setq p org-mark-ring))
7034 (setq org-mark-ring-last-goto p)
7035 (setq m (car p))
7036 (switch-to-buffer (marker-buffer m))
7037 (goto-char m)
7038 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
7040 (defun org-remove-angle-brackets (s)
7041 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7042 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7044 (defun org-add-angle-brackets (s)
7045 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7046 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7048 (defun org-remove-double-quotes (s)
7049 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
7050 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
7053 ;;; Following specific links
7055 (defun org-follow-timestamp-link ()
7056 (cond
7057 ((org-at-date-range-p t)
7058 (let ((org-agenda-start-on-weekday)
7059 (t1 (match-string 1))
7060 (t2 (match-string 2)))
7061 (setq t1 (time-to-days (org-time-string-to-time t1))
7062 t2 (time-to-days (org-time-string-to-time t2)))
7063 (org-agenda-list nil t1 (1+ (- t2 t1)))))
7064 ((org-at-timestamp-p t)
7065 (org-agenda-list nil (time-to-days (org-time-string-to-time
7066 (substring (match-string 1) 0 10)))
7068 (t (error "This should not happen"))))
7071 ;;; Following file links
7072 (defvar org-wait nil)
7073 (defun org-open-file (path &optional in-emacs line search)
7074 "Open the file at PATH.
7075 First, this expands any special file name abbreviations. Then the
7076 configuration variable `org-file-apps' is checked if it contains an
7077 entry for this file type, and if yes, the corresponding command is launched.
7079 If no application is found, Emacs simply visits the file.
7081 With optional prefix argument IN-EMACS, Emacs will visit the file.
7082 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
7083 and o use an external application to visit the file.
7085 Optional LINE specifies a line to go to, optional SEARCH a string to
7086 search for. If LINE or SEARCH is given, the file will always be
7087 opened in Emacs.
7088 If the file does not exist, an error is thrown."
7089 (setq in-emacs (or in-emacs line search))
7090 (let* ((file (if (equal path "")
7091 buffer-file-name
7092 (substitute-in-file-name (expand-file-name path))))
7093 (apps (append org-file-apps (org-default-apps)))
7094 (remp (and (assq 'remote apps) (org-file-remote-p file)))
7095 (dirp (if remp nil (file-directory-p file)))
7096 (file (if (and dirp org-open-directory-means-index-dot-org)
7097 (concat (file-name-as-directory file) "index.org")
7098 file))
7099 (a-m-a-p (assq 'auto-mode apps))
7100 (dfile (downcase file))
7101 (old-buffer (current-buffer))
7102 (old-pos (point))
7103 (old-mode major-mode)
7104 ext cmd)
7105 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7106 (setq ext (match-string 1 dfile))
7107 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7108 (setq ext (match-string 1 dfile))))
7109 (cond
7110 ((equal in-emacs '(16))
7111 (setq cmd (cdr (assoc 'system apps))))
7112 (in-emacs (setq cmd 'emacs))
7114 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
7115 (and dirp (cdr (assoc 'directory apps)))
7116 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
7117 'string-match)
7118 (cdr (assoc ext apps))
7119 (cdr (assoc t apps))))))
7120 (when (eq cmd 'system)
7121 (setq cmd (cdr (assoc 'system apps))))
7122 (when (eq cmd 'default)
7123 (setq cmd (cdr (assoc t apps))))
7124 (when (eq cmd 'mailcap)
7125 (require 'mailcap)
7126 (mailcap-parse-mailcaps)
7127 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7128 (command (mailcap-mime-info mime-type)))
7129 (if (stringp command)
7130 (setq cmd command)
7131 (setq cmd 'emacs))))
7132 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
7133 (not (file-exists-p file))
7134 (not org-open-non-existing-files))
7135 (error "No such file: %s" file))
7136 (cond
7137 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7138 ;; Remove quotes around the file name - we'll use shell-quote-argument.
7139 (while (string-match "['\"]%s['\"]" cmd)
7140 (setq cmd (replace-match "%s" t t cmd)))
7141 (while (string-match "%s" cmd)
7142 (setq cmd (replace-match
7143 (save-match-data
7144 (shell-quote-argument
7145 (convert-standard-filename file)))
7146 t t cmd)))
7147 (save-window-excursion
7148 (start-process-shell-command cmd nil cmd)
7149 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
7151 ((or (stringp cmd)
7152 (eq cmd 'emacs))
7153 (funcall (cdr (assq 'file org-link-frame-setup)) file)
7154 (widen)
7155 (if line (goto-line line)
7156 (if search (org-link-search search))))
7157 ((consp cmd)
7158 (let ((file (convert-standard-filename file)))
7159 (eval cmd)))
7160 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7161 (and (org-mode-p) (eq old-mode 'org-mode)
7162 (or (not (equal old-buffer (current-buffer)))
7163 (not (equal old-pos (point))))
7164 (org-mark-ring-push old-pos old-buffer))))
7166 (defun org-default-apps ()
7167 "Return the default applications for this operating system."
7168 (cond
7169 ((eq system-type 'darwin)
7170 org-file-apps-defaults-macosx)
7171 ((eq system-type 'windows-nt)
7172 org-file-apps-defaults-windowsnt)
7173 (t org-file-apps-defaults-gnu)))
7175 (defun org-apps-regexp-alist (list &optional add-auto-mode)
7176 "Convert extensions to regular expressions in the cars of LIST.
7177 Also, weed out any non-string entries, because the return value is used
7178 only for regexp matching.
7179 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
7180 point to the symbol `emacs', indicating that the file should
7181 be opened in Emacs."
7182 (append
7183 (delq nil
7184 (mapcar (lambda (x)
7185 (if (not (stringp (car x)))
7187 (if (string-match "\\W" (car x))
7189 (cons (concat "\\." (car x) "\\'") (cdr x)))))
7190 list))
7191 (if add-auto-mode
7192 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
7194 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
7195 (defun org-file-remote-p (file)
7196 "Test whether FILE specifies a location on a remote system.
7197 Return non-nil if the location is indeed remote.
7199 For example, the filename \"/user@host:/foo\" specifies a location
7200 on the system \"/user@host:\"."
7201 (cond ((fboundp 'file-remote-p)
7202 (file-remote-p file))
7203 ((fboundp 'tramp-handle-file-remote-p)
7204 (tramp-handle-file-remote-p file))
7205 ((and (boundp 'ange-ftp-name-format)
7206 (string-match (car ange-ftp-name-format) file))
7208 (t nil)))
7211 ;;;; Refiling
7213 (defun org-get-org-file ()
7214 "Read a filename, with default directory `org-directory'."
7215 (let ((default (or org-default-notes-file remember-data-file)))
7216 (read-file-name (format "File name [%s]: " default)
7217 (file-name-as-directory org-directory)
7218 default)))
7220 (defun org-notes-order-reversed-p ()
7221 "Check if the current file should receive notes in reversed order."
7222 (cond
7223 ((not org-reverse-note-order) nil)
7224 ((eq t org-reverse-note-order) t)
7225 ((not (listp org-reverse-note-order)) nil)
7226 (t (catch 'exit
7227 (let ((all org-reverse-note-order)
7228 entry)
7229 (while (setq entry (pop all))
7230 (if (string-match (car entry) buffer-file-name)
7231 (throw 'exit (cdr entry))))
7232 nil)))))
7234 (defvar org-refile-target-table nil
7235 "The list of refile targets, created by `org-refile'.")
7237 (defvar org-agenda-new-buffers nil
7238 "Buffers created to visit agenda files.")
7240 (defun org-get-refile-targets (&optional default-buffer)
7241 "Produce a table with refile targets."
7242 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
7243 targets txt re files f desc descre)
7244 (with-current-buffer (or default-buffer (current-buffer))
7245 (while (setq entry (pop entries))
7246 (setq files (car entry) desc (cdr entry))
7247 (cond
7248 ((null files) (setq files (list (current-buffer))))
7249 ((eq files 'org-agenda-files)
7250 (setq files (org-agenda-files 'unrestricted)))
7251 ((and (symbolp files) (fboundp files))
7252 (setq files (funcall files)))
7253 ((and (symbolp files) (boundp files))
7254 (setq files (symbol-value files))))
7255 (if (stringp files) (setq files (list files)))
7256 (cond
7257 ((eq (car desc) :tag)
7258 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
7259 ((eq (car desc) :todo)
7260 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
7261 ((eq (car desc) :regexp)
7262 (setq descre (cdr desc)))
7263 ((eq (car desc) :level)
7264 (setq descre (concat "^\\*\\{" (number-to-string
7265 (if org-odd-levels-only
7266 (1- (* 2 (cdr desc)))
7267 (cdr desc)))
7268 "\\}[ \t]")))
7269 ((eq (car desc) :maxlevel)
7270 (setq descre (concat "^\\*\\{1," (number-to-string
7271 (if org-odd-levels-only
7272 (1- (* 2 (cdr desc)))
7273 (cdr desc)))
7274 "\\}[ \t]")))
7275 (t (error "Bad refiling target description %s" desc)))
7276 (while (setq f (pop files))
7277 (save-excursion
7278 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
7279 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
7280 (save-excursion
7281 (save-restriction
7282 (widen)
7283 (goto-char (point-min))
7284 (while (re-search-forward descre nil t)
7285 (goto-char (point-at-bol))
7286 (when (looking-at org-complex-heading-regexp)
7287 (setq txt (org-link-display-format (match-string 4))
7288 re (concat "^" (regexp-quote
7289 (buffer-substring (match-beginning 1)
7290 (match-end 4)))))
7291 (if (match-end 5) (setq re (concat re "[ \t]+"
7292 (regexp-quote
7293 (match-string 5)))))
7294 (setq re (concat re "[ \t]*$"))
7295 (when org-refile-use-outline-path
7296 (setq txt (mapconcat 'org-protect-slash
7297 (append
7298 (if (eq org-refile-use-outline-path 'file)
7299 (list (file-name-nondirectory
7300 (buffer-file-name (buffer-base-buffer))))
7301 (if (eq org-refile-use-outline-path 'full-file-path)
7302 (list (buffer-file-name (buffer-base-buffer)))))
7303 (org-get-outline-path)
7304 (list txt))
7305 "/")))
7306 (push (list txt f re (point)) targets))
7307 (goto-char (point-at-eol))))))))
7308 (nreverse targets))))
7310 (defun org-protect-slash (s)
7311 (while (string-match "/" s)
7312 (setq s (replace-match "\\" t t s)))
7315 (defun org-get-outline-path ()
7316 "Return the outline path to the current entry, as a list."
7317 (let (rtn)
7318 (save-excursion
7319 (while (org-up-heading-safe)
7320 (when (looking-at org-complex-heading-regexp)
7321 (push (org-match-string-no-properties 4) rtn)))
7322 rtn)))
7324 (defvar org-refile-history nil
7325 "History for refiling operations.")
7327 (defun org-refile (&optional goto default-buffer)
7328 "Move the entry at point to another heading.
7329 The list of target headings is compiled using the information in
7330 `org-refile-targets', which see. This list is created before each use
7331 and will therefore always be up-to-date.
7333 At the target location, the entry is filed as a subitem of the target heading.
7334 Depending on `org-reverse-note-order', the new subitem will either be the
7335 first or the last subitem.
7337 If there is an active region, all entries in that region will be moved.
7338 However, the region must fulfil the requirement that the first heading
7339 is the first one sets the top-level of the moved text - at most siblings
7340 below it are allowed.
7342 With prefix arg GOTO, the command will only visit the target location,
7343 not actually move anything.
7344 With a double prefix `C-u C-u', go to the location where the last refiling
7345 operation has put the subtree."
7346 (interactive "P")
7347 (let* ((cbuf (current-buffer))
7348 (regionp (org-region-active-p))
7349 (region-start (and regionp (region-beginning)))
7350 (region-end (and regionp (region-end)))
7351 (region-length (and regionp (- region-end region-start)))
7352 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7353 pos it nbuf file re level reversed)
7354 (when regionp (goto-char region-start)
7355 (unless (org-kill-is-subtree-p
7356 (buffer-substring region-start region-end))
7357 (error "The region is not a (sequence of) subtree(s)")))
7358 (if (equal goto '(16))
7359 (org-refile-goto-last-stored)
7360 (when (setq it (org-refile-get-location
7361 (if goto "Goto: " "Refile to: ") default-buffer))
7362 (setq file (nth 1 it)
7363 re (nth 2 it)
7364 pos (nth 3 it))
7365 (setq nbuf (or (find-buffer-visiting file)
7366 (find-file-noselect file)))
7367 (if goto
7368 (progn
7369 (switch-to-buffer nbuf)
7370 (goto-char pos)
7371 (org-show-context 'org-goto))
7372 (if regionp
7373 (progn
7374 (kill-new (buffer-substring region-start region-end))
7375 (org-save-markers-in-region region-start region-end))
7376 (org-copy-subtree 1 nil t))
7377 (save-excursion
7378 (set-buffer (setq nbuf (or (find-buffer-visiting file)
7379 (find-file-noselect file))))
7380 (setq reversed (org-notes-order-reversed-p))
7381 (save-excursion
7382 (save-restriction
7383 (widen)
7384 (goto-char pos)
7385 (looking-at outline-regexp)
7386 (setq level (org-get-valid-level (funcall outline-level) 1))
7387 (goto-char
7388 (if reversed
7389 (or (outline-next-heading) (point-max))
7390 (or (save-excursion (outline-get-next-sibling))
7391 (org-end-of-subtree t t)
7392 (point-max))))
7393 (if (not (bolp)) (newline))
7394 (bookmark-set "org-refile-last-stored")
7395 (org-paste-subtree level))))
7396 (if regionp
7397 (delete-region (point) (+ (point) region-length))
7398 (org-cut-subtree))
7399 (setq org-markers-to-move nil)
7400 (message "Refiled to \"%s\"" (car it)))))))
7402 (defun org-refile-goto-last-stored ()
7403 "Go to the location where the last refile was stored."
7404 (interactive)
7405 (bookmark-jump "org-refile-last-stored")
7406 (message "This is the location of the last refile"))
7408 (defun org-refile-get-location (&optional prompt default-buffer)
7409 "Prompt the user for a refile location, using PROMPT."
7410 (let ((org-refile-targets org-refile-targets)
7411 (org-refile-use-outline-path org-refile-use-outline-path))
7412 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
7413 (unless org-refile-target-table
7414 (error "No refile targets"))
7415 (let* ((cbuf (current-buffer))
7416 (cfunc (if org-refile-use-outline-path
7417 'org-olpath-completing-read
7418 'completing-read))
7419 (extra (if org-refile-use-outline-path "/" ""))
7420 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7421 (fname (and filename (file-truename filename)))
7422 (tbl (mapcar
7423 (lambda (x)
7424 (if (not (equal fname (file-truename (nth 1 x))))
7425 (cons (concat (car x) extra " ("
7426 (file-name-nondirectory (nth 1 x)) ")")
7427 (cdr x))
7428 (cons (concat (car x) extra) (cdr x))))
7429 org-refile-target-table))
7430 (completion-ignore-case t))
7431 (assoc (funcall cfunc prompt tbl nil t nil 'org-refile-history)
7432 tbl)))
7434 (defun org-olpath-completing-read (prompt collection &rest args)
7435 "Read an outline path like a file name."
7436 (let ((thetable collection))
7437 (apply
7438 'completing-read prompt
7439 (lambda (string predicate &optional flag)
7440 (let (rtn r s f (l (length string)))
7441 (cond
7442 ((eq flag nil)
7443 ;; try completion
7444 (try-completion string thetable))
7445 ((eq flag t)
7446 ;; all-completions
7447 (setq rtn (all-completions string thetable predicate))
7448 (mapcar
7449 (lambda (x)
7450 (setq r (substring x l))
7451 (if (string-match " ([^)]*)$" x)
7452 (setq f (match-string 0 x))
7453 (setq f ""))
7454 (if (string-match "/" r)
7455 (concat string (substring r 0 (match-end 0)) f)
7457 rtn))
7458 ((eq flag 'lambda)
7459 ;; exact match?
7460 (assoc string thetable)))
7462 args)))
7464 ;;;; Dynamic blocks
7466 (defun org-find-dblock (name)
7467 "Find the first dynamic block with name NAME in the buffer.
7468 If not found, stay at current position and return nil."
7469 (let (pos)
7470 (save-excursion
7471 (goto-char (point-min))
7472 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
7473 nil t)
7474 (match-beginning 0))))
7475 (if pos (goto-char pos))
7476 pos))
7478 (defconst org-dblock-start-re
7479 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
7480 "Matches the startline of a dynamic block, with parameters.")
7482 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
7483 "Matches the end of a dyhamic block.")
7485 (defun org-create-dblock (plist)
7486 "Create a dynamic block section, with parameters taken from PLIST.
7487 PLIST must containe a :name entry which is used as name of the block."
7488 (unless (bolp) (newline))
7489 (let ((name (plist-get plist :name)))
7490 (insert "#+BEGIN: " name)
7491 (while plist
7492 (if (eq (car plist) :name)
7493 (setq plist (cddr plist))
7494 (insert " " (prin1-to-string (pop plist)))))
7495 (insert "\n\n#+END:\n")
7496 (beginning-of-line -2)))
7498 (defun org-prepare-dblock ()
7499 "Prepare dynamic block for refresh.
7500 This empties the block, puts the cursor at the insert position and returns
7501 the property list including an extra property :name with the block name."
7502 (unless (looking-at org-dblock-start-re)
7503 (error "Not at a dynamic block"))
7504 (let* ((begdel (1+ (match-end 0)))
7505 (name (org-no-properties (match-string 1)))
7506 (params (append (list :name name)
7507 (read (concat "(" (match-string 3) ")")))))
7508 (unless (re-search-forward org-dblock-end-re nil t)
7509 (error "Dynamic block not terminated"))
7510 (setq params
7511 (append params
7512 (list :content (buffer-substring
7513 begdel (match-beginning 0)))))
7514 (delete-region begdel (match-beginning 0))
7515 (goto-char begdel)
7516 (open-line 1)
7517 params))
7519 (defun org-map-dblocks (&optional command)
7520 "Apply COMMAND to all dynamic blocks in the current buffer.
7521 If COMMAND is not given, use `org-update-dblock'."
7522 (let ((cmd (or command 'org-update-dblock))
7523 pos)
7524 (save-excursion
7525 (goto-char (point-min))
7526 (while (re-search-forward org-dblock-start-re nil t)
7527 (goto-char (setq pos (match-beginning 0)))
7528 (condition-case nil
7529 (funcall cmd)
7530 (error (message "Error during update of dynamic block")))
7531 (goto-char pos)
7532 (unless (re-search-forward org-dblock-end-re nil t)
7533 (error "Dynamic block not terminated"))))))
7535 (defun org-dblock-update (&optional arg)
7536 "User command for updating dynamic blocks.
7537 Update the dynamic block at point. With prefix ARG, update all dynamic
7538 blocks in the buffer."
7539 (interactive "P")
7540 (if arg
7541 (org-update-all-dblocks)
7542 (or (looking-at org-dblock-start-re)
7543 (org-beginning-of-dblock))
7544 (org-update-dblock)))
7546 (defun org-update-dblock ()
7547 "Update the dynamic block at point
7548 This means to empty the block, parse for parameters and then call
7549 the correct writing function."
7550 (save-window-excursion
7551 (let* ((pos (point))
7552 (line (org-current-line))
7553 (params (org-prepare-dblock))
7554 (name (plist-get params :name))
7555 (cmd (intern (concat "org-dblock-write:" name))))
7556 (message "Updating dynamic block `%s' at line %d..." name line)
7557 (funcall cmd params)
7558 (message "Updating dynamic block `%s' at line %d...done" name line)
7559 (goto-char pos))))
7561 (defun org-beginning-of-dblock ()
7562 "Find the beginning of the dynamic block at point.
7563 Error if there is no scuh block at point."
7564 (let ((pos (point))
7565 beg)
7566 (end-of-line 1)
7567 (if (and (re-search-backward org-dblock-start-re nil t)
7568 (setq beg (match-beginning 0))
7569 (re-search-forward org-dblock-end-re nil t)
7570 (> (match-end 0) pos))
7571 (goto-char beg)
7572 (goto-char pos)
7573 (error "Not in a dynamic block"))))
7575 (defun org-update-all-dblocks ()
7576 "Update all dynamic blocks in the buffer.
7577 This function can be used in a hook."
7578 (when (org-mode-p)
7579 (org-map-dblocks 'org-update-dblock)))
7582 ;;;; Completion
7584 (defconst org-additional-option-like-keywords
7585 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
7586 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
7587 "BEGIN_EXAMPLE" "END_EXAMPLE"
7588 "BEGIN_QUOTE" "END_QUOTE"
7589 "BEGIN_VERSE" "END_VERSE"
7590 "BEGIN_SRC" "END_SRC"))
7592 (defcustom org-structure-template-alist
7594 ("s" "#+begin_src ?\n\n#+end_src"
7595 "<src lang=\"?\">\n\n</src>")
7596 ("e" "#+begin_example\n?\n#+end_example"
7597 "<example>\n?\n</example>")
7598 ("q" "#+begin_quote\n?\n#+end_quote"
7599 "<quote>\n?\n</quote>")
7600 ("v" "#+begin_verse\n?\n#+end_verse"
7601 "<verse>\n?\n/verse>")
7602 ("l" "#+begin_latex\n?\n#+end_latex"
7603 "<literal style=\"latex\">\n?\n</literal>")
7604 ("L" "#+latex: "
7605 "<literal style=\"latex\">?</literal>")
7606 ("h" "#+begin_html\n?\n#+end_html"
7607 "<literal style=\"html\">\n?\n</literal>")
7608 ("H" "#+html: "
7609 "<literal style=\"html\">?</literal>")
7610 ("a" "#+begin_ascii\n?\n#+end_ascii")
7611 ("A" "#+ascii: ")
7612 ("i" "#+include %file ?"
7613 "<include file=%file markup=\"?\">")
7615 "Structure completion elements.
7616 This is a list of abbreviation keys and values. The value gets inserted
7617 it you type @samp{.} followed by the key and then the completion key,
7618 usually `M-TAB'. %file will be replaced by a file name after prompting
7619 for the file uning completion.
7620 There are two templates for each key, the first uses the original Org syntax,
7621 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
7622 the default when the /org-mtags.el/ module has been loaded. See also the
7623 variable `org-mtags-prefere-muse-templates'.
7624 This is an experimental feature, it is undecided if it is going to stay in."
7625 :group 'org-completion
7626 :type '(repeat
7627 (string :tag "Key")
7628 (string :tag "Template")
7629 (string :tag "Muse Template")))
7631 (defun org-try-structure-completion ()
7632 "Try to complete a structure template before point.
7633 This looks for strings like \"<e\" on an otherwise empty line and
7634 expands them."
7635 (let ((l (buffer-substring (point-at-bol) (point)))
7637 (when (and (looking-at "[ \t]*$")
7638 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
7639 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
7640 (org-complete-expand-structure-template (+ -1 (point-at-bol)
7641 (match-beginning 1)) a)
7642 t)))
7644 (defun org-complete-expand-structure-template (start cell)
7645 "Expand a structure template."
7646 (let* ((musep (org-bound-and-true-p org-mtags-prefere-muse-templates))
7647 (rpl (nth (if musep 2 1) cell)))
7648 (delete-region start (point))
7649 (when (string-match "\\`#\\+" rpl)
7650 (cond
7651 ((bolp))
7652 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
7653 (delete-region (point-at-bol) (point)))
7654 (t (newline))))
7655 (setq start (point))
7656 (if (string-match "%file" rpl)
7657 (setq rpl (replace-match
7658 (concat
7659 "\""
7660 (save-match-data
7661 (abbreviate-file-name (read-file-name "Include file: ")))
7662 "\"")
7663 t t rpl)))
7664 (insert rpl)
7665 (if (re-search-backward "\\?" start t) (delete-char 1))))
7668 (defun org-complete (&optional arg)
7669 "Perform completion on word at point.
7670 At the beginning of a headline, this completes TODO keywords as given in
7671 `org-todo-keywords'.
7672 If the current word is preceded by a backslash, completes the TeX symbols
7673 that are supported for HTML support.
7674 If the current word is preceded by \"#+\", completes special words for
7675 setting file options.
7676 In the line after \"#+STARTUP:, complete valid keywords.\"
7677 At all other locations, this simply calls the value of
7678 `org-completion-fallback-command'."
7679 (interactive "P")
7680 (org-without-partial-completion
7681 (catch 'exit
7682 (let* ((a nil)
7683 (end (point))
7684 (beg1 (save-excursion
7685 (skip-chars-backward (org-re "[:alnum:]_@"))
7686 (point)))
7687 (beg (save-excursion
7688 (skip-chars-backward "a-zA-Z0-9_:$")
7689 (point)))
7690 (confirm (lambda (x) (stringp (car x))))
7691 (searchhead (equal (char-before beg) ?*))
7692 (struct
7693 (when (and (member (char-before beg1) '(?. ?<))
7694 (setq a (assoc (buffer-substring beg1 (point))
7695 org-structure-template-alist)))
7696 (org-complete-expand-structure-template (1- beg1) a)
7697 (throw 'exit t)))
7698 (tag (and (equal (char-before beg1) ?:)
7699 (equal (char-after (point-at-bol)) ?*)))
7700 (prop (and (equal (char-before beg1) ?:)
7701 (not (equal (char-after (point-at-bol)) ?*))))
7702 (texp (equal (char-before beg) ?\\))
7703 (link (equal (char-before beg) ?\[))
7704 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
7705 beg)
7706 "#+"))
7707 (startup (string-match "^#\\+STARTUP:.*"
7708 (buffer-substring (point-at-bol) (point))))
7709 (completion-ignore-case opt)
7710 (type nil)
7711 (tbl nil)
7712 (table (cond
7713 (opt
7714 (setq type :opt)
7715 (require 'org-exp)
7716 (append
7717 (mapcar
7718 (lambda (x)
7719 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
7720 (cons (match-string 2 x) (match-string 1 x)))
7721 (org-split-string (org-get-current-options) "\n"))
7722 (mapcar 'list org-additional-option-like-keywords)))
7723 (startup
7724 (setq type :startup)
7725 org-startup-options)
7726 (link (append org-link-abbrev-alist-local
7727 org-link-abbrev-alist))
7728 (texp
7729 (setq type :tex)
7730 org-html-entities)
7731 ((string-match "\\`\\*+[ \t]+\\'"
7732 (buffer-substring (point-at-bol) beg))
7733 (setq type :todo)
7734 (mapcar 'list org-todo-keywords-1))
7735 (searchhead
7736 (setq type :searchhead)
7737 (save-excursion
7738 (goto-char (point-min))
7739 (while (re-search-forward org-todo-line-regexp nil t)
7740 (push (list
7741 (org-make-org-heading-search-string
7742 (match-string 3) t))
7743 tbl)))
7744 tbl)
7745 (tag (setq type :tag beg beg1)
7746 (or org-tag-alist (org-get-buffer-tags)))
7747 (prop (setq type :prop beg beg1)
7748 (mapcar 'list (org-buffer-property-keys nil t t)))
7749 (t (progn
7750 (call-interactively org-completion-fallback-command)
7751 (throw 'exit nil)))))
7752 (pattern (buffer-substring-no-properties beg end))
7753 (completion (try-completion pattern table confirm)))
7754 (cond ((eq completion t)
7755 (if (not (assoc (upcase pattern) table))
7756 (message "Already complete")
7757 (if (and (equal type :opt)
7758 (not (member (car (assoc (upcase pattern) table))
7759 org-additional-option-like-keywords)))
7760 (insert (substring (cdr (assoc (upcase pattern) table))
7761 (length pattern)))
7762 (if (memq type '(:tag :prop)) (insert ":")))))
7763 ((null completion)
7764 (message "Can't find completion for \"%s\"" pattern)
7765 (ding))
7766 ((not (string= pattern completion))
7767 (delete-region beg end)
7768 (if (string-match " +$" completion)
7769 (setq completion (replace-match "" t t completion)))
7770 (insert completion)
7771 (if (get-buffer-window "*Completions*")
7772 (delete-window (get-buffer-window "*Completions*")))
7773 (if (assoc completion table)
7774 (if (eq type :todo) (insert " ")
7775 (if (memq type '(:tag :prop)) (insert ":"))))
7776 (if (and (equal type :opt) (assoc completion table))
7777 (message "%s" (substitute-command-keys
7778 "Press \\[org-complete] again to insert example settings"))))
7780 (message "Making completion list...")
7781 (let ((list (sort (all-completions pattern table confirm)
7782 'string<)))
7783 (with-output-to-temp-buffer "*Completions*"
7784 (condition-case nil
7785 ;; Protection needed for XEmacs and emacs 21
7786 (display-completion-list list pattern)
7787 (error (display-completion-list list)))))
7788 (message "Making completion list...%s" "done")))))))
7790 ;;;; TODO, DEADLINE, Comments
7792 (defun org-toggle-comment ()
7793 "Change the COMMENT state of an entry."
7794 (interactive)
7795 (save-excursion
7796 (org-back-to-heading)
7797 (let (case-fold-search)
7798 (if (looking-at (concat outline-regexp
7799 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
7800 (replace-match "" t t nil 1)
7801 (if (looking-at outline-regexp)
7802 (progn
7803 (goto-char (match-end 0))
7804 (insert org-comment-string " ")))))))
7806 (defvar org-last-todo-state-is-todo nil
7807 "This is non-nil when the last TODO state change led to a TODO state.
7808 If the last change removed the TODO tag or switched to DONE, then
7809 this is nil.")
7811 (defvar org-setting-tags nil) ; dynamically skiped
7813 (defun org-parse-local-options (string var)
7814 "Parse STRING for startup setting relevant for variable VAR."
7815 (let ((rtn (symbol-value var))
7816 e opts)
7817 (save-match-data
7818 (if (or (not string) (not (string-match "\\S-" string)))
7820 (setq opts (delq nil (mapcar (lambda (x)
7821 (setq e (assoc x org-startup-options))
7822 (if (eq (nth 1 e) var) e nil))
7823 (org-split-string string "[ \t]+"))))
7824 (if (not opts)
7826 (setq rtn nil)
7827 (while (setq e (pop opts))
7828 (if (not (nth 3 e))
7829 (setq rtn (nth 2 e))
7830 (if (not (listp rtn)) (setq rtn nil))
7831 (push (nth 2 e) rtn)))
7832 rtn)))))
7834 (defvar org-blocker-hook nil
7835 "Hook for functions that are allowed to block a state change.
7837 Each function gets as its single argument a property list, see
7838 `org-trigger-hook' for more information about this list.
7840 If any of the functions in this hook returns nil, the state change
7841 is blocked.")
7843 (defvar org-trigger-hook nil
7844 "Hook for functions that are triggered by a state change.
7846 Each function gets as its single argument a property list with at least
7847 the following elements:
7849 (:type type-of-change :position pos-at-entry-start
7850 :from old-state :to new-state)
7852 Depending on the type, more properties may be present.
7854 This mechanism is currently implemented for:
7856 TODO state changes
7857 ------------------
7858 :type todo-state-change
7859 :from previous state (keyword as a string), or nil
7860 :to new state (keyword as a string), or nil")
7862 (defvar org-agenda-headline-snapshot-before-repeat)
7863 (defun org-todo (&optional arg)
7864 "Change the TODO state of an item.
7865 The state of an item is given by a keyword at the start of the heading,
7866 like
7867 *** TODO Write paper
7868 *** DONE Call mom
7870 The different keywords are specified in the variable `org-todo-keywords'.
7871 By default the available states are \"TODO\" and \"DONE\".
7872 So for this example: when the item starts with TODO, it is changed to DONE.
7873 When it starts with DONE, the DONE is removed. And when neither TODO nor
7874 DONE are present, add TODO at the beginning of the heading.
7876 With C-u prefix arg, use completion to determine the new state.
7877 With numeric prefix arg, switch to that state.
7879 For calling through lisp, arg is also interpreted in the following way:
7880 'none -> empty state
7881 \"\"(empty string) -> switch to empty state
7882 'done -> switch to DONE
7883 'nextset -> switch to the next set of keywords
7884 'previousset -> switch to the previous set of keywords
7885 \"WAITING\" -> switch to the specified keyword, but only if it
7886 really is a member of `org-todo-keywords'."
7887 (interactive "P")
7888 (save-excursion
7889 (catch 'exit
7890 (org-back-to-heading)
7891 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
7892 (or (looking-at (concat " +" org-todo-regexp " *"))
7893 (looking-at " *"))
7894 (let* ((match-data (match-data))
7895 (startpos (point-at-bol))
7896 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
7897 (org-log-done org-log-done)
7898 (org-log-repeat org-log-repeat)
7899 (org-todo-log-states org-todo-log-states)
7900 (this (match-string 1))
7901 (hl-pos (match-beginning 0))
7902 (head (org-get-todo-sequence-head this))
7903 (ass (assoc head org-todo-kwd-alist))
7904 (interpret (nth 1 ass))
7905 (done-word (nth 3 ass))
7906 (final-done-word (nth 4 ass))
7907 (last-state (or this ""))
7908 (completion-ignore-case t)
7909 (member (member this org-todo-keywords-1))
7910 (tail (cdr member))
7911 (state (cond
7912 ((and org-todo-key-trigger
7913 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
7914 (and (not arg) org-use-fast-todo-selection
7915 (not (eq org-use-fast-todo-selection 'prefix)))))
7916 ;; Use fast selection
7917 (org-fast-todo-selection))
7918 ((and (equal arg '(4))
7919 (or (not org-use-fast-todo-selection)
7920 (not org-todo-key-trigger)))
7921 ;; Read a state with completion
7922 (completing-read "State: " (mapcar (lambda(x) (list x))
7923 org-todo-keywords-1)
7924 nil t))
7925 ((eq arg 'right)
7926 (if this
7927 (if tail (car tail) nil)
7928 (car org-todo-keywords-1)))
7929 ((eq arg 'left)
7930 (if (equal member org-todo-keywords-1)
7932 (if this
7933 (nth (- (length org-todo-keywords-1) (length tail) 2)
7934 org-todo-keywords-1)
7935 (org-last org-todo-keywords-1))))
7936 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
7937 (setq arg nil))) ; hack to fall back to cycling
7938 (arg
7939 ;; user or caller requests a specific state
7940 (cond
7941 ((equal arg "") nil)
7942 ((eq arg 'none) nil)
7943 ((eq arg 'done) (or done-word (car org-done-keywords)))
7944 ((eq arg 'nextset)
7945 (or (car (cdr (member head org-todo-heads)))
7946 (car org-todo-heads)))
7947 ((eq arg 'previousset)
7948 (let ((org-todo-heads (reverse org-todo-heads)))
7949 (or (car (cdr (member head org-todo-heads)))
7950 (car org-todo-heads))))
7951 ((car (member arg org-todo-keywords-1)))
7952 ((nth (1- (prefix-numeric-value arg))
7953 org-todo-keywords-1))))
7954 ((null member) (or head (car org-todo-keywords-1)))
7955 ((equal this final-done-word) nil) ;; -> make empty
7956 ((null tail) nil) ;; -> first entry
7957 ((eq interpret 'sequence)
7958 (car tail))
7959 ((memq interpret '(type priority))
7960 (if (eq this-command last-command)
7961 (car tail)
7962 (if (> (length tail) 0)
7963 (or done-word (car org-done-keywords))
7964 nil)))
7965 (t nil)))
7966 (next (if state (concat " " state " ") " "))
7967 (change-plist (list :type 'todo-state-change :from this :to state
7968 :position startpos))
7969 dolog now-done-p)
7970 (when org-blocker-hook
7971 (unless (save-excursion
7972 (save-match-data
7973 (run-hook-with-args-until-failure
7974 'org-blocker-hook change-plist)))
7975 (if (interactive-p)
7976 (error "TODO state change from %s to %s blocked" this state)
7977 ;; fail silently
7978 (message "TODO state change from %s to %s blocked" this state)
7979 (throw 'exit nil))))
7980 (store-match-data match-data)
7981 (replace-match next t t)
7982 (unless (pos-visible-in-window-p hl-pos)
7983 (message "TODO state changed to %s" (org-trim next)))
7984 (unless head
7985 (setq head (org-get-todo-sequence-head state)
7986 ass (assoc head org-todo-kwd-alist)
7987 interpret (nth 1 ass)
7988 done-word (nth 3 ass)
7989 final-done-word (nth 4 ass)))
7990 (when (memq arg '(nextset previousset))
7991 (message "Keyword-Set %d/%d: %s"
7992 (- (length org-todo-sets) -1
7993 (length (memq (assoc state org-todo-sets) org-todo-sets)))
7994 (length org-todo-sets)
7995 (mapconcat 'identity (assoc state org-todo-sets) " ")))
7996 (setq org-last-todo-state-is-todo
7997 (not (member state org-done-keywords)))
7998 (setq now-done-p (and (member state org-done-keywords)
7999 (not (member this org-done-keywords))))
8000 (and logging (org-local-logging logging))
8001 (when (and (or org-todo-log-states org-log-done)
8002 (not (memq arg '(nextset previousset))))
8003 ;; we need to look at recording a time and note
8004 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
8005 (nth 2 (assoc this org-todo-log-states))))
8006 (when (and state
8007 (member state org-not-done-keywords)
8008 (not (member this org-not-done-keywords)))
8009 ;; This is now a todo state and was not one before
8010 ;; If there was a CLOSED time stamp, get rid of it.
8011 (org-add-planning-info nil nil 'closed))
8012 (when (and now-done-p org-log-done)
8013 ;; It is now done, and it was not done before
8014 (org-add-planning-info 'closed (org-current-time))
8015 (if (and (not dolog) (eq 'note org-log-done))
8016 (org-add-log-setup 'done state 'findpos 'note)))
8017 (when (and state dolog)
8018 ;; This is a non-nil state, and we need to log it
8019 (org-add-log-setup 'state state 'findpos dolog)))
8020 ;; Fixup tag positioning
8021 (org-todo-trigger-tag-changes state)
8022 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
8023 (when org-provide-todo-statistics
8024 (org-update-parent-todo-statistics))
8025 (run-hooks 'org-after-todo-state-change-hook)
8026 (if (and arg (not (member state org-done-keywords)))
8027 (setq head (org-get-todo-sequence-head state)))
8028 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
8029 ;; Do we need to trigger a repeat?
8030 (when now-done-p
8031 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
8032 ;; This is for the agenda, take a snapshot of the headline.
8033 (save-match-data
8034 (setq org-agenda-headline-snapshot-before-repeat
8035 (org-get-heading))))
8036 (org-auto-repeat-maybe state))
8037 ;; Fixup cursor location if close to the keyword
8038 (if (and (outline-on-heading-p)
8039 (not (bolp))
8040 (save-excursion (beginning-of-line 1)
8041 (looking-at org-todo-line-regexp))
8042 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
8043 (progn
8044 (goto-char (or (match-end 2) (match-end 1)))
8045 (just-one-space)))
8046 (when org-trigger-hook
8047 (save-excursion
8048 (run-hook-with-args 'org-trigger-hook change-plist)))))))
8050 (defun org-update-parent-todo-statistics ()
8051 "Update any statistics cookie in the parent of the current headline."
8052 (interactive)
8053 (let ((box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
8054 level (cnt-all 0) (cnt-done 0) is-percent kwd)
8055 (catch 'exit
8056 (save-excursion
8057 (setq level (org-up-heading-safe))
8058 (unless (and level
8059 (re-search-forward box-re (point-at-eol) t))
8060 (throw 'exit nil))
8061 (setq is-percent (match-end 2))
8062 (save-match-data
8063 (unless (outline-next-heading) (throw 'exit nil))
8064 (while (looking-at org-todo-line-regexp)
8065 (setq kwd (match-string 2))
8066 (and kwd (setq cnt-all (1+ cnt-all)))
8067 (and (member kwd org-done-keywords)
8068 (setq cnt-done (1+ cnt-done)))
8069 (condition-case nil
8070 (org-forward-same-level 1)
8071 (error (end-of-line 1)))))
8072 (replace-match
8073 (if is-percent
8074 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
8075 (format "[%d/%d]" cnt-done cnt-all)))
8076 (run-hook-with-args 'org-after-todo-statistics-hook
8077 cnt-done (- cnt-all cnt-done))))))
8079 (defvar org-after-todo-statistics-hook nil
8080 "Hook that is called after a TODO statistics cookie has been updated.
8081 Each function is called with two arguments: the number of not-done entries
8082 and the number of done entries.
8084 For example, the following function, when added to this hook, will switch
8085 an entry to DONE when all children are done, and back to TODO when new
8086 entries are set to a TODO status. Note that this hook is only called
8087 when there is a statistics cookie in the headline!
8089 (defun org-summary-todo (n-done n-not-done)
8090 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
8091 (let (org-log-done org-log-states) ; turn off logging
8092 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
8095 (defun org-todo-trigger-tag-changes (state)
8096 "Apply the changes defined in `org-todo-state-tags-triggers'."
8097 (let ((l org-todo-state-tags-triggers)
8098 changes)
8099 (when (or (not state) (equal state ""))
8100 (setq changes (append changes (cdr (assoc "" l)))))
8101 (when (and (stringp state) (> (length state) 0))
8102 (setq changes (append changes (cdr (assoc state l)))))
8103 (when (member state org-not-done-keywords)
8104 (setq changes (append changes (cdr (assoc 'todo l)))))
8105 (when (member state org-done-keywords)
8106 (setq changes (append changes (cdr (assoc 'done l)))))
8107 (dolist (c changes)
8108 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
8110 (defun org-local-logging (value)
8111 "Get logging settings from a property VALUE."
8112 (let* (words w a)
8113 ;; directly set the variables, they are already local.
8114 (setq org-log-done nil
8115 org-log-repeat nil
8116 org-todo-log-states nil)
8117 (setq words (org-split-string value))
8118 (while (setq w (pop words))
8119 (cond
8120 ((setq a (assoc w org-startup-options))
8121 (and (member (nth 1 a) '(org-log-done org-log-repeat))
8122 (set (nth 1 a) (nth 2 a))))
8123 ((setq a (org-extract-log-state-settings w))
8124 (and (member (car a) org-todo-keywords-1)
8125 (push a org-todo-log-states)))))))
8127 (defun org-get-todo-sequence-head (kwd)
8128 "Return the head of the TODO sequence to which KWD belongs.
8129 If KWD is not set, check if there is a text property remembering the
8130 right sequence."
8131 (let (p)
8132 (cond
8133 ((not kwd)
8134 (or (get-text-property (point-at-bol) 'org-todo-head)
8135 (progn
8136 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
8137 nil (point-at-eol)))
8138 (get-text-property p 'org-todo-head))))
8139 ((not (member kwd org-todo-keywords-1))
8140 (car org-todo-keywords-1))
8141 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
8143 (defun org-fast-todo-selection ()
8144 "Fast TODO keyword selection with single keys.
8145 Returns the new TODO keyword, or nil if no state change should occur."
8146 (let* ((fulltable org-todo-key-alist)
8147 (done-keywords org-done-keywords) ;; needed for the faces.
8148 (maxlen (apply 'max (mapcar
8149 (lambda (x)
8150 (if (stringp (car x)) (string-width (car x)) 0))
8151 fulltable)))
8152 (expert nil)
8153 (fwidth (+ maxlen 3 1 3))
8154 (ncol (/ (- (window-width) 4) fwidth))
8155 tg cnt e c tbl
8156 groups ingroup)
8157 (save-window-excursion
8158 (if expert
8159 (set-buffer (get-buffer-create " *Org todo*"))
8160 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
8161 (erase-buffer)
8162 (org-set-local 'org-done-keywords done-keywords)
8163 (setq tbl fulltable cnt 0)
8164 (while (setq e (pop tbl))
8165 (cond
8166 ((equal e '(:startgroup))
8167 (push '() groups) (setq ingroup t)
8168 (when (not (= cnt 0))
8169 (setq cnt 0)
8170 (insert "\n"))
8171 (insert "{ "))
8172 ((equal e '(:endgroup))
8173 (setq ingroup nil cnt 0)
8174 (insert "}\n"))
8176 (setq tg (car e) c (cdr e))
8177 (if ingroup (push tg (car groups)))
8178 (setq tg (org-add-props tg nil 'face
8179 (org-get-todo-face tg)))
8180 (if (and (= cnt 0) (not ingroup)) (insert " "))
8181 (insert "[" c "] " tg (make-string
8182 (- fwidth 4 (length tg)) ?\ ))
8183 (when (= (setq cnt (1+ cnt)) ncol)
8184 (insert "\n")
8185 (if ingroup (insert " "))
8186 (setq cnt 0)))))
8187 (insert "\n")
8188 (goto-char (point-min))
8189 (if (not expert) (org-fit-window-to-buffer))
8190 (message "[a-z..]:Set [SPC]:clear")
8191 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
8192 (cond
8193 ((or (= c ?\C-g)
8194 (and (= c ?q) (not (rassoc c fulltable))))
8195 (setq quit-flag t))
8196 ((= c ?\ ) nil)
8197 ((setq e (rassoc c fulltable) tg (car e))
8199 (t (setq quit-flag t))))))
8201 (defun org-entry-is-todo-p ()
8202 (member (org-get-todo-state) org-not-done-keywords))
8204 (defun org-entry-is-done-p ()
8205 (member (org-get-todo-state) org-done-keywords))
8207 (defun org-get-todo-state ()
8208 (save-excursion
8209 (org-back-to-heading t)
8210 (and (looking-at org-todo-line-regexp)
8211 (match-end 2)
8212 (match-string 2))))
8214 (defun org-at-date-range-p (&optional inactive-ok)
8215 "Is the cursor inside a date range?"
8216 (interactive)
8217 (save-excursion
8218 (catch 'exit
8219 (let ((pos (point)))
8220 (skip-chars-backward "^[<\r\n")
8221 (skip-chars-backward "<[")
8222 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8223 (>= (match-end 0) pos)
8224 (throw 'exit t))
8225 (skip-chars-backward "^<[\r\n")
8226 (skip-chars-backward "<[")
8227 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8228 (>= (match-end 0) pos)
8229 (throw 'exit t)))
8230 nil)))
8232 (defun org-get-repeat ()
8233 "Check if there is a deadline/schedule with repeater in this entry."
8234 (save-match-data
8235 (save-excursion
8236 (org-back-to-heading t)
8237 (if (re-search-forward
8238 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
8239 (match-string 1)))))
8241 (defvar org-last-changed-timestamp)
8242 (defvar org-last-inserted-timestamp)
8243 (defvar org-log-post-message)
8244 (defvar org-log-note-purpose)
8245 (defvar org-log-note-how)
8246 (defvar org-log-note-extra)
8247 (defun org-auto-repeat-maybe (done-word)
8248 "Check if the current headline contains a repeated deadline/schedule.
8249 If yes, set TODO state back to what it was and change the base date
8250 of repeating deadline/scheduled time stamps to new date.
8251 This function is run automatically after each state change to a DONE state."
8252 ;; last-state is dynamically scoped into this function
8253 (let* ((repeat (org-get-repeat))
8254 (aa (assoc last-state org-todo-kwd-alist))
8255 (interpret (nth 1 aa))
8256 (head (nth 2 aa))
8257 (whata '(("d" . day) ("m" . month) ("y" . year)))
8258 (msg "Entry repeats: ")
8259 (org-log-done nil)
8260 (org-todo-log-states nil)
8261 (nshiftmax 10) (nshift 0)
8262 re type n what ts mb0 time)
8263 (when repeat
8264 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
8265 (org-todo (if (eq interpret 'type) last-state head))
8266 (when org-log-repeat
8267 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
8268 (memq 'org-add-log-note post-command-hook))
8269 ;; OK, we are already setup for some record
8270 (if (eq org-log-repeat 'note)
8271 ;; make sure we take a note, not only a time stamp
8272 (setq org-log-note-how 'note))
8273 ;; Set up for taking a record
8274 (org-add-log-setup 'state (or done-word (car org-done-keywords))
8275 'findpos org-log-repeat)))
8276 (org-back-to-heading t)
8277 (org-add-planning-info nil nil 'closed)
8278 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
8279 org-deadline-time-regexp "\\)\\|\\("
8280 org-ts-regexp "\\)"))
8281 (while (re-search-forward
8282 re (save-excursion (outline-next-heading) (point)) t)
8283 (setq type (if (match-end 1) org-scheduled-string
8284 (if (match-end 3) org-deadline-string "Plain:"))
8285 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0)))
8286 mb0 (match-beginning 0))
8287 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
8288 (setq n (string-to-number (match-string 2 ts))
8289 what (match-string 3 ts))
8290 (if (equal what "w") (setq n (* n 7) what "d"))
8291 ;; Preparation, see if we need to modify the start date for the change
8292 (when (match-end 1)
8293 (setq time (save-match-data (org-time-string-to-time ts)))
8294 (cond
8295 ((equal (match-string 1 ts) ".")
8296 ;; Shift starting date to today
8297 (org-timestamp-change
8298 (- (time-to-days (current-time)) (time-to-days time))
8299 'day))
8300 ((equal (match-string 1 ts) "+")
8301 (while (or (= nshift 0)
8302 (<= (time-to-days time) (time-to-days (current-time))))
8303 (when (= (incf nshift) nshiftmax)
8304 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
8305 (error "Abort")))
8306 (org-timestamp-change n (cdr (assoc what whata)))
8307 (org-at-timestamp-p t)
8308 (setq ts (match-string 1))
8309 (setq time (save-match-data (org-time-string-to-time ts))))
8310 (org-timestamp-change (- n) (cdr (assoc what whata)))
8311 ;; rematch, so that we have everything in place for the real shift
8312 (org-at-timestamp-p t)
8313 (setq ts (match-string 1))
8314 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
8315 (org-timestamp-change n (cdr (assoc what whata)))
8316 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
8317 (setq org-log-post-message msg)
8318 (message "%s" msg))))
8320 (defun org-show-todo-tree (arg)
8321 "Make a compact tree which shows all headlines marked with TODO.
8322 The tree will show the lines where the regexp matches, and all higher
8323 headlines above the match.
8324 With a \\[universal-argument] prefix, also show the DONE entries.
8325 With a numeric prefix N, construct a sparse tree for the Nth element
8326 of `org-todo-keywords-1'."
8327 (interactive "P")
8328 (let ((case-fold-search nil)
8329 (kwd-re
8330 (cond ((null arg) org-not-done-regexp)
8331 ((equal arg '(4))
8332 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
8333 (mapcar 'list org-todo-keywords-1))))
8334 (concat "\\("
8335 (mapconcat 'identity (org-split-string kwd "|") "\\|")
8336 "\\)\\>")))
8337 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
8338 (regexp-quote (nth (1- (prefix-numeric-value arg))
8339 org-todo-keywords-1)))
8340 (t (error "Invalid prefix argument: %s" arg)))))
8341 (message "%d TODO entries found"
8342 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
8344 (defun org-deadline (&optional remove time)
8345 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
8346 With argument REMOVE, remove any deadline from the item.
8347 When TIME is set, it should be an internal time specification, and the
8348 scheduling will use the corresponding date."
8349 (interactive "P")
8350 (if remove
8351 (progn
8352 (org-remove-timestamp-with-keyword org-deadline-string)
8353 (message "Item no longer has a deadline."))
8354 (if (org-get-repeat)
8355 (error "Cannot change deadline on task with repeater, please do that by hand")
8356 (org-add-planning-info 'deadline time 'closed)
8357 (message "Deadline on %s" org-last-inserted-timestamp))))
8359 (defun org-schedule (&optional remove time)
8360 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
8361 With argument REMOVE, remove any scheduling date from the item.
8362 When TIME is set, it should be an internal time specification, and the
8363 scheduling will use the corresponding date."
8364 (interactive "P")
8365 (if remove
8366 (progn
8367 (org-remove-timestamp-with-keyword org-scheduled-string)
8368 (message "Item is no longer scheduled."))
8369 (if (org-get-repeat)
8370 (error "Cannot reschedule task with repeater, please do that by hand")
8371 (org-add-planning-info 'scheduled time 'closed)
8372 (message "Scheduled to %s" org-last-inserted-timestamp))))
8374 (defun org-remove-timestamp-with-keyword (keyword)
8375 "Remove all time stamps with KEYWORD in the current entry."
8376 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
8377 beg)
8378 (save-excursion
8379 (org-back-to-heading t)
8380 (setq beg (point))
8381 (org-end-of-subtree t t)
8382 (while (re-search-backward re beg t)
8383 (replace-match "")
8384 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
8385 (equal (char-before) ?\ ))
8386 (backward-delete-char 1)
8387 (if (string-match "^[ \t]*$" (buffer-substring
8388 (point-at-bol) (point-at-eol)))
8389 (delete-region (point-at-bol)
8390 (min (point-max) (1+ (point-at-eol))))))))))
8392 (defun org-add-planning-info (what &optional time &rest remove)
8393 "Insert new timestamp with keyword in the line directly after the headline.
8394 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
8395 If non is given, the user is prompted for a date.
8396 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
8397 be removed."
8398 (interactive)
8399 (let (org-time-was-given org-end-time-was-given ts
8400 end default-time default-input)
8402 (when (and (not time) (memq what '(scheduled deadline)))
8403 ;; Try to get a default date/time from existing timestamp
8404 (save-excursion
8405 (org-back-to-heading t)
8406 (setq end (save-excursion (outline-next-heading) (point)))
8407 (when (re-search-forward (if (eq what 'scheduled)
8408 org-scheduled-time-regexp
8409 org-deadline-time-regexp)
8410 end t)
8411 (setq ts (match-string 1)
8412 default-time
8413 (apply 'encode-time (org-parse-time-string ts))
8414 default-input (and ts (org-get-compact-tod ts))))))
8415 (when what
8416 ;; If necessary, get the time from the user
8417 (setq time (or time (org-read-date nil 'to-time nil nil
8418 default-time default-input))))
8420 (when (and org-insert-labeled-timestamps-at-point
8421 (member what '(scheduled deadline)))
8422 (insert
8423 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
8424 (org-insert-time-stamp time org-time-was-given
8425 nil nil nil (list org-end-time-was-given))
8426 (setq what nil))
8427 (save-excursion
8428 (save-restriction
8429 (let (col list elt ts buffer-invisibility-spec)
8430 (org-back-to-heading t)
8431 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
8432 (goto-char (match-end 1))
8433 (setq col (current-column))
8434 (goto-char (match-end 0))
8435 (if (eobp) (insert "\n") (forward-char 1))
8436 (if (and (not (looking-at outline-regexp))
8437 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
8438 "[^\r\n]*"))
8439 (not (equal (match-string 1) org-clock-string)))
8440 (narrow-to-region (match-beginning 0) (match-end 0))
8441 (insert-before-markers "\n")
8442 (backward-char 1)
8443 (narrow-to-region (point) (point))
8444 (and org-adapt-indentation (org-indent-to-column col)))
8445 ;; Check if we have to remove something.
8446 (setq list (cons what remove))
8447 (while list
8448 (setq elt (pop list))
8449 (goto-char (point-min))
8450 (when (or (and (eq elt 'scheduled)
8451 (re-search-forward org-scheduled-time-regexp nil t))
8452 (and (eq elt 'deadline)
8453 (re-search-forward org-deadline-time-regexp nil t))
8454 (and (eq elt 'closed)
8455 (re-search-forward org-closed-time-regexp nil t)))
8456 (replace-match "")
8457 (if (looking-at "--+<[^>]+>") (replace-match ""))
8458 (if (looking-at " +") (replace-match ""))))
8459 (goto-char (point-max))
8460 (when what
8461 (insert
8462 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
8463 (cond ((eq what 'scheduled) org-scheduled-string)
8464 ((eq what 'deadline) org-deadline-string)
8465 ((eq what 'closed) org-closed-string))
8466 " ")
8467 (setq ts (org-insert-time-stamp
8468 time
8469 (or org-time-was-given
8470 (and (eq what 'closed) org-log-done-with-time))
8471 (eq what 'closed)
8472 nil nil (list org-end-time-was-given)))
8473 (end-of-line 1))
8474 (goto-char (point-min))
8475 (widen)
8476 (if (and (looking-at "[ \t]+\n")
8477 (equal (char-before) ?\n))
8478 (delete-region (1- (point)) (point-at-eol)))
8479 ts)))))
8481 (defvar org-log-note-marker (make-marker))
8482 (defvar org-log-note-purpose nil)
8483 (defvar org-log-note-state nil)
8484 (defvar org-log-note-how nil)
8485 (defvar org-log-note-extra nil)
8486 (defvar org-log-note-window-configuration nil)
8487 (defvar org-log-note-return-to (make-marker))
8488 (defvar org-log-post-message nil
8489 "Message to be displayed after a log note has been stored.
8490 The auto-repeater uses this.")
8492 (defun org-add-note ()
8493 "Add a note to the current entry.
8494 This is done in the same way as adding a state change note."
8495 (interactive)
8496 (org-add-log-setup 'note nil 'findpos nil))
8498 (defvar org-property-end-re)
8499 (defun org-add-log-setup (&optional purpose state findpos how &optional extra)
8500 "Set up the post command hook to take a note.
8501 If this is about to TODO state change, the new state is expected in STATE.
8502 When FINDPOS is non-nil, find the correct position for the note in
8503 the current entry. If not, assume that it can be inserted at point.
8504 HOW is an indicator what kind of note should be created.
8505 EXTRA is additional text that will be inserted into the notes buffer."
8506 (save-restriction
8507 (save-excursion
8508 (when findpos
8509 (org-back-to-heading t)
8510 (narrow-to-region (point) (save-excursion
8511 (outline-next-heading) (point)))
8512 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
8513 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
8514 "[^\r\n]*\\)?"))
8515 (goto-char (match-end 0))
8516 (when (and org-log-state-notes-insert-after-drawers
8517 (save-excursion
8518 (forward-line) (looking-at org-drawer-regexp)))
8519 (progn (forward-line)
8520 (while (looking-at org-drawer-regexp)
8521 (goto-char (match-end 0))
8522 (re-search-forward org-property-end-re (point-max) t)
8523 (forward-line))
8524 (forward-line -1)))
8525 (unless org-log-states-order-reversed
8526 (and (= (char-after) ?\n) (forward-char 1))
8527 (org-skip-over-state-notes)
8528 (skip-chars-backward " \t\n\r")))
8529 (move-marker org-log-note-marker (point))
8530 (setq org-log-note-purpose purpose
8531 org-log-note-state state
8532 org-log-note-how how
8533 org-log-note-extra extra)
8534 (add-hook 'post-command-hook 'org-add-log-note 'append))))
8536 (defun org-skip-over-state-notes ()
8537 "Skip past the list of State notes in an entry."
8538 (if (looking-at "\n[ \t]*- State") (forward-char 1))
8539 (while (looking-at "[ \t]*- State")
8540 (condition-case nil
8541 (org-next-item)
8542 (error (org-end-of-item)))))
8544 (defun org-add-log-note (&optional purpose)
8545 "Pop up a window for taking a note, and add this note later at point."
8546 (remove-hook 'post-command-hook 'org-add-log-note)
8547 (setq org-log-note-window-configuration (current-window-configuration))
8548 (delete-other-windows)
8549 (move-marker org-log-note-return-to (point))
8550 (switch-to-buffer (marker-buffer org-log-note-marker))
8551 (goto-char org-log-note-marker)
8552 (org-switch-to-buffer-other-window "*Org Note*")
8553 (erase-buffer)
8554 (if (memq org-log-note-how '(time state))
8555 (let (current-prefix-arg) (org-store-log-note))
8556 (let ((org-inhibit-startup t)) (org-mode))
8557 (insert (format "# Insert note for %s.
8558 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
8559 (cond
8560 ((eq org-log-note-purpose 'clock-out) "stopped clock")
8561 ((eq org-log-note-purpose 'done) "closed todo item")
8562 ((eq org-log-note-purpose 'state)
8563 (format "state change to \"%s\"" org-log-note-state))
8564 ((eq org-log-note-purpose 'note)
8565 "this entry")
8566 (t (error "This should not happen")))))
8567 (if org-log-note-extra (insert org-log-note-extra))
8568 (org-set-local 'org-finish-function 'org-store-log-note)))
8570 (defvar org-note-abort nil) ; dynamically scoped
8571 (defun org-store-log-note ()
8572 "Finish taking a log note, and insert it to where it belongs."
8573 (let ((txt (buffer-string))
8574 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
8575 lines ind)
8576 (kill-buffer (current-buffer))
8577 (while (string-match "\\`#.*\n[ \t\n]*" txt)
8578 (setq txt (replace-match "" t t txt)))
8579 (if (string-match "\\s-+\\'" txt)
8580 (setq txt (replace-match "" t t txt)))
8581 (setq lines (org-split-string txt "\n"))
8582 (when (and note (string-match "\\S-" note))
8583 (setq note
8584 (org-replace-escapes
8585 note
8586 (list (cons "%u" (user-login-name))
8587 (cons "%U" user-full-name)
8588 (cons "%t" (format-time-string
8589 (org-time-stamp-format 'long 'inactive)
8590 (current-time)))
8591 (cons "%s" (if org-log-note-state
8592 (concat "\"" org-log-note-state "\"")
8593 "")))))
8594 (if lines (setq note (concat note " \\\\")))
8595 (push note lines))
8596 (when (or current-prefix-arg org-note-abort) (setq lines nil))
8597 (when lines
8598 (save-excursion
8599 (set-buffer (marker-buffer org-log-note-marker))
8600 (save-excursion
8601 (goto-char org-log-note-marker)
8602 (move-marker org-log-note-marker nil)
8603 (end-of-line 1)
8604 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
8605 (indent-relative nil)
8606 (insert "- " (pop lines))
8607 (org-indent-line-function)
8608 (beginning-of-line 1)
8609 (looking-at "[ \t]*")
8610 (setq ind (concat (match-string 0) " "))
8611 (end-of-line 1)
8612 (while lines (insert "\n" ind (pop lines)))))))
8613 (set-window-configuration org-log-note-window-configuration)
8614 (with-current-buffer (marker-buffer org-log-note-return-to)
8615 (goto-char org-log-note-return-to))
8616 (move-marker org-log-note-return-to nil)
8617 (and org-log-post-message (message "%s" org-log-post-message)))
8619 (defun org-sparse-tree (&optional arg)
8620 "Create a sparse tree, prompt for the details.
8621 This command can create sparse trees. You first need to select the type
8622 of match used to create the tree:
8624 t Show entries with a specific TODO keyword.
8625 T Show entries selected by a tags match.
8626 p Enter a property name and its value (both with completion on existing
8627 names/values) and show entries with that property.
8628 r Show entries matching a regular expression
8629 d Show deadlines due within `org-deadline-warning-days'."
8630 (interactive "P")
8631 (let (ans kwd value)
8632 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
8633 (setq ans (read-char-exclusive))
8634 (cond
8635 ((equal ans ?d)
8636 (call-interactively 'org-check-deadlines))
8637 ((equal ans ?b)
8638 (call-interactively 'org-check-before-date))
8639 ((equal ans ?t)
8640 (org-show-todo-tree '(4)))
8641 ((equal ans ?T)
8642 (call-interactively 'org-tags-sparse-tree))
8643 ((member ans '(?p ?P))
8644 (setq kwd (completing-read "Property: "
8645 (mapcar 'list (org-buffer-property-keys))))
8646 (setq value (completing-read "Value: "
8647 (mapcar 'list (org-property-values kwd))))
8648 (unless (string-match "\\`{.*}\\'" value)
8649 (setq value (concat "\"" value "\"")))
8650 (org-tags-sparse-tree arg (concat kwd "=" value)))
8651 ((member ans '(?r ?R ?/))
8652 (call-interactively 'org-occur))
8653 (t (error "No such sparse tree command \"%c\"" ans)))))
8655 (defvar org-occur-highlights nil
8656 "List of overlays used for occur matches.")
8657 (make-variable-buffer-local 'org-occur-highlights)
8658 (defvar org-occur-parameters nil
8659 "Parameters of the active org-occur calls.
8660 This is a list, each call to org-occur pushes as cons cell,
8661 containing the regular expression and the callback, onto the list.
8662 The list can contain several entries if `org-occur' has been called
8663 several time with the KEEP-PREVIOUS argument. Otherwise, this list
8664 will only contain one set of parameters. When the highlights are
8665 removed (for example with `C-c C-c', or with the next edit (depending
8666 on `org-remove-highlights-with-change'), this variable is emptied
8667 as well.")
8668 (make-variable-buffer-local 'org-occur-parameters)
8670 (defun org-occur (regexp &optional keep-previous callback)
8671 "Make a compact tree which shows all matches of REGEXP.
8672 The tree will show the lines where the regexp matches, and all higher
8673 headlines above the match. It will also show the heading after the match,
8674 to make sure editing the matching entry is easy.
8675 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
8676 call to `org-occur' will be kept, to allow stacking of calls to this
8677 command.
8678 If CALLBACK is non-nil, it is a function which is called to confirm
8679 that the match should indeed be shown."
8680 (interactive "sRegexp: \nP")
8681 (unless keep-previous
8682 (org-remove-occur-highlights nil nil t))
8683 (push (cons regexp callback) org-occur-parameters)
8684 (let ((cnt 0))
8685 (save-excursion
8686 (goto-char (point-min))
8687 (if (or (not keep-previous) ; do not want to keep
8688 (not org-occur-highlights)) ; no previous matches
8689 ;; hide everything
8690 (org-overview))
8691 (while (re-search-forward regexp nil t)
8692 (when (or (not callback)
8693 (save-match-data (funcall callback)))
8694 (setq cnt (1+ cnt))
8695 (when org-highlight-sparse-tree-matches
8696 (org-highlight-new-match (match-beginning 0) (match-end 0)))
8697 (org-show-context 'occur-tree))))
8698 (when org-remove-highlights-with-change
8699 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
8700 nil 'local))
8701 (unless org-sparse-tree-open-archived-trees
8702 (org-hide-archived-subtrees (point-min) (point-max)))
8703 (run-hooks 'org-occur-hook)
8704 (if (interactive-p)
8705 (message "%d match(es) for regexp %s" cnt regexp))
8706 cnt))
8708 (defun org-show-context (&optional key)
8709 "Make sure point and context and visible.
8710 How much context is shown depends upon the variables
8711 `org-show-hierarchy-above', `org-show-following-heading'. and
8712 `org-show-siblings'."
8713 (let ((heading-p (org-on-heading-p t))
8714 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
8715 (following-p (org-get-alist-option org-show-following-heading key))
8716 (entry-p (org-get-alist-option org-show-entry-below key))
8717 (siblings-p (org-get-alist-option org-show-siblings key)))
8718 (catch 'exit
8719 ;; Show heading or entry text
8720 (if (and heading-p (not entry-p))
8721 (org-flag-heading nil) ; only show the heading
8722 (and (or entry-p (org-invisible-p) (org-invisible-p2))
8723 (org-show-hidden-entry))) ; show entire entry
8724 (when following-p
8725 ;; Show next sibling, or heading below text
8726 (save-excursion
8727 (and (if heading-p (org-goto-sibling) (outline-next-heading))
8728 (org-flag-heading nil))))
8729 (when siblings-p (org-show-siblings))
8730 (when hierarchy-p
8731 ;; show all higher headings, possibly with siblings
8732 (save-excursion
8733 (while (and (condition-case nil
8734 (progn (org-up-heading-all 1) t)
8735 (error nil))
8736 (not (bobp)))
8737 (org-flag-heading nil)
8738 (when siblings-p (org-show-siblings))))))))
8740 (defun org-reveal (&optional siblings)
8741 "Show current entry, hierarchy above it, and the following headline.
8742 This can be used to show a consistent set of context around locations
8743 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
8744 not t for the search context.
8746 With optional argument SIBLINGS, on each level of the hierarchy all
8747 siblings are shown. This repairs the tree structure to what it would
8748 look like when opened with hierarchical calls to `org-cycle'."
8749 (interactive "P")
8750 (let ((org-show-hierarchy-above t)
8751 (org-show-following-heading t)
8752 (org-show-siblings (if siblings t org-show-siblings)))
8753 (org-show-context nil)))
8755 (defun org-highlight-new-match (beg end)
8756 "Highlight from BEG to END and mark the highlight is an occur headline."
8757 (let ((ov (org-make-overlay beg end)))
8758 (org-overlay-put ov 'face 'secondary-selection)
8759 (push ov org-occur-highlights)))
8761 (defun org-remove-occur-highlights (&optional beg end noremove)
8762 "Remove the occur highlights from the buffer.
8763 BEG and END are ignored. If NOREMOVE is nil, remove this function
8764 from the `before-change-functions' in the current buffer."
8765 (interactive)
8766 (unless org-inhibit-highlight-removal
8767 (mapc 'org-delete-overlay org-occur-highlights)
8768 (setq org-occur-highlights nil)
8769 (setq org-occur-parameters nil)
8770 (unless noremove
8771 (remove-hook 'before-change-functions
8772 'org-remove-occur-highlights 'local))))
8774 ;;;; Priorities
8776 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
8777 "Regular expression matching the priority indicator.")
8779 (defvar org-remove-priority-next-time nil)
8781 (defun org-priority-up ()
8782 "Increase the priority of the current item."
8783 (interactive)
8784 (org-priority 'up))
8786 (defun org-priority-down ()
8787 "Decrease the priority of the current item."
8788 (interactive)
8789 (org-priority 'down))
8791 (defun org-priority (&optional action)
8792 "Change the priority of an item by ARG.
8793 ACTION can be `set', `up', `down', or a character."
8794 (interactive)
8795 (setq action (or action 'set))
8796 (let (current new news have remove)
8797 (save-excursion
8798 (org-back-to-heading)
8799 (if (looking-at org-priority-regexp)
8800 (setq current (string-to-char (match-string 2))
8801 have t)
8802 (setq current org-default-priority))
8803 (cond
8804 ((or (eq action 'set)
8805 (if (featurep 'xemacs) (characterp action) (integerp action)))
8806 (if (not (eq action 'set))
8807 (setq new action)
8808 (message "Priority %c-%c, SPC to remove: "
8809 org-highest-priority org-lowest-priority)
8810 (setq new (read-char-exclusive)))
8811 (if (and (= (upcase org-highest-priority) org-highest-priority)
8812 (= (upcase org-lowest-priority) org-lowest-priority))
8813 (setq new (upcase new)))
8814 (cond ((equal new ?\ ) (setq remove t))
8815 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
8816 (error "Priority must be between `%c' and `%c'"
8817 org-highest-priority org-lowest-priority))))
8818 ((eq action 'up)
8819 (if (and (not have) (eq last-command this-command))
8820 (setq new org-lowest-priority)
8821 (setq new (if (and org-priority-start-cycle-with-default (not have))
8822 org-default-priority (1- current)))))
8823 ((eq action 'down)
8824 (if (and (not have) (eq last-command this-command))
8825 (setq new org-highest-priority)
8826 (setq new (if (and org-priority-start-cycle-with-default (not have))
8827 org-default-priority (1+ current)))))
8828 (t (error "Invalid action")))
8829 (if (or (< (upcase new) org-highest-priority)
8830 (> (upcase new) org-lowest-priority))
8831 (setq remove t))
8832 (setq news (format "%c" new))
8833 (if have
8834 (if remove
8835 (replace-match "" t t nil 1)
8836 (replace-match news t t nil 2))
8837 (if remove
8838 (error "No priority cookie found in line")
8839 (looking-at org-todo-line-regexp)
8840 (if (match-end 2)
8841 (progn
8842 (goto-char (match-end 2))
8843 (insert " [#" news "]"))
8844 (goto-char (match-beginning 3))
8845 (insert "[#" news "] ")))))
8846 (org-preserve-lc (org-set-tags nil 'align))
8847 (if remove
8848 (message "Priority removed")
8849 (message "Priority of current item set to %s" news))))
8852 (defun org-get-priority (s)
8853 "Find priority cookie and return priority."
8854 (save-match-data
8855 (if (not (string-match org-priority-regexp s))
8856 (* 1000 (- org-lowest-priority org-default-priority))
8857 (* 1000 (- org-lowest-priority
8858 (string-to-char (match-string 2 s)))))))
8860 ;;;; Tags
8862 (defvar org-agenda-archives-mode)
8863 (defun org-scan-tags (action matcher &optional todo-only)
8864 "Scan headline tags with inheritance and produce output ACTION.
8866 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
8867 or `agenda' to produce an entry list for an agenda view. It can also be
8868 a Lisp form or a function that should be called at each matched headline, in
8869 this case the return value is a list of all return values from these calls.
8871 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
8872 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
8873 only lines with a TODO keyword are included in the output."
8874 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
8875 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
8876 (org-re
8877 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
8878 (props (list 'face 'default
8879 'done-face 'org-done
8880 'undone-face 'default
8881 'mouse-face 'highlight
8882 'org-not-done-regexp org-not-done-regexp
8883 'org-todo-regexp org-todo-regexp
8884 'keymap org-agenda-keymap
8885 'help-echo
8886 (format "mouse-2 or RET jump to org file %s"
8887 (abbreviate-file-name
8888 (or (buffer-file-name (buffer-base-buffer))
8889 (buffer-name (buffer-base-buffer)))))))
8890 (case-fold-search nil)
8891 lspos tags tags-list
8892 (tags-alist (list (cons 0 (mapcar 'downcase org-file-tags))))
8893 (llast 0) rtn rtn1 level category i txt
8894 todo marker entry priority)
8895 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
8896 (setq action (list 'lambda nil action)))
8897 (save-excursion
8898 (goto-char (point-min))
8899 (when (eq action 'sparse-tree)
8900 (org-overview)
8901 (org-remove-occur-highlights))
8902 (while (re-search-forward re nil t)
8903 (catch :skip
8904 (setq todo (if (match-end 1) (match-string 2))
8905 tags (if (match-end 4) (match-string 4)))
8906 (goto-char (setq lspos (1+ (match-beginning 0))))
8907 (setq level (org-reduced-level (funcall outline-level))
8908 category (org-get-category))
8909 (setq i llast llast level)
8910 ;; remove tag lists from same and sublevels
8911 (while (>= i level)
8912 (when (setq entry (assoc i tags-alist))
8913 (setq tags-alist (delete entry tags-alist)))
8914 (setq i (1- i)))
8915 ;; add the next tags
8916 (when tags
8917 (setq tags (mapcar 'downcase (org-split-string tags ":"))
8918 tags-alist
8919 (cons (cons level tags) tags-alist)))
8920 ;; compile tags for current headline
8921 (setq tags-list
8922 (if org-use-tag-inheritance
8923 (apply 'append (mapcar 'cdr tags-alist))
8924 tags))
8925 (when (and tags org-use-tag-inheritance
8926 (not (eq t org-use-tag-inheritance)))
8927 ;; selective inheritance, remove uninherited ones
8928 (setcdr (car tags-alist)
8929 (org-remove-uniherited-tags (cdar tags-alist))))
8930 (when (and (or (not todo-only) (member todo org-not-done-keywords))
8931 (let ((case-fold-search t)) (eval matcher))
8933 (not (member org-archive-tag tags-list))
8934 ;; we have an archive tag, should we use this anyway?
8935 (or (not org-agenda-skip-archived-trees)
8936 (and (eq action 'agenda) org-agenda-archives-mode))))
8937 (unless (eq action 'sparse-tree) (org-agenda-skip))
8939 ;; select this headline
8941 (cond
8942 ((eq action 'sparse-tree)
8943 (and org-highlight-sparse-tree-matches
8944 (org-get-heading) (match-end 0)
8945 (org-highlight-new-match
8946 (match-beginning 0) (match-beginning 1)))
8947 (org-show-context 'tags-tree))
8948 ((eq action 'agenda)
8949 (setq txt (org-format-agenda-item
8951 (concat
8952 (if org-tags-match-list-sublevels
8953 (make-string (1- level) ?.) "")
8954 (org-get-heading))
8955 category tags-list)
8956 priority (org-get-priority txt))
8957 (goto-char lspos)
8958 (setq marker (org-agenda-new-marker))
8959 (org-add-props txt props
8960 'org-marker marker 'org-hd-marker marker 'org-category category
8961 'priority priority 'type "tagsmatch")
8962 (push txt rtn))
8963 ((functionp action)
8964 (save-excursion
8965 (setq rtn1 (funcall action))
8966 (push rtn1 rtn))
8967 (goto-char (point-at-eol)))
8968 (t (error "Invalid action")))
8970 ;; if we are to skip sublevels, jump to end of subtree
8971 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
8972 (when (and (eq action 'sparse-tree)
8973 (not org-sparse-tree-open-archived-trees))
8974 (org-hide-archived-subtrees (point-min) (point-max)))
8975 (nreverse rtn)))
8977 (defun org-remove-uniherited-tags (tags)
8978 "Remove all tags that are not inherited from the list TAGS."
8979 (cond
8980 ((eq org-use-tag-inheritance t) tags)
8981 ((not org-use-tag-inheritance) nil)
8982 ((stringp org-use-tag-inheritance)
8983 (delq nil (mapcar
8984 (lambda (x) (if (string-match org-use-tag-inheritance x) x nil))
8985 tags)))
8986 ((listp org-use-tag-inheritance)
8987 (delq nil (mapcar
8988 (lambda (x) (if (member x org-use-tag-inheritance) x nil))
8989 tags)))))
8991 (defvar todo-only) ;; dynamically scoped
8993 (defun org-tags-sparse-tree (&optional todo-only match)
8994 "Create a sparse tree according to tags string MATCH.
8995 MATCH can contain positive and negative selection of tags, like
8996 \"+WORK+URGENT-WITHBOSS\".
8997 If optional argument TODO_ONLY is non-nil, only select lines that are
8998 also TODO lines."
8999 (interactive "P")
9000 (org-prepare-agenda-buffers (list (current-buffer)))
9001 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
9003 (defvar org-cached-props nil)
9004 (defun org-cached-entry-get (pom property)
9005 (if (or (eq t org-use-property-inheritance)
9006 (and (stringp org-use-property-inheritance)
9007 (string-match org-use-property-inheritance property))
9008 (and (listp org-use-property-inheritance)
9009 (member property org-use-property-inheritance)))
9010 ;; Caching is not possible, check it directly
9011 (org-entry-get pom property 'inherit)
9012 ;; Get all properties, so that we can do complicated checks easily
9013 (cdr (assoc property (or org-cached-props
9014 (setq org-cached-props
9015 (org-entry-properties pom)))))))
9017 (defun org-global-tags-completion-table (&optional files)
9018 "Return the list of all tags in all agenda buffer/files."
9019 (save-excursion
9020 (org-uniquify
9021 (delq nil
9022 (apply 'append
9023 (mapcar
9024 (lambda (file)
9025 (set-buffer (find-file-noselect file))
9026 (append (org-get-buffer-tags)
9027 (mapcar (lambda (x) (if (stringp (car-safe x))
9028 (list (car-safe x)) nil))
9029 org-tag-alist)))
9030 (if (and files (car files))
9031 files
9032 (org-agenda-files))))))))
9034 (defun org-make-tags-matcher (match)
9035 "Create the TAGS//TODO matcher form for the selection string MATCH."
9036 ;; todo-only is scoped dynamically into this function, and the function
9037 ;; may change it it the matcher asksk for it.
9038 (unless match
9039 ;; Get a new match request, with completion
9040 (let ((org-last-tags-completion-table
9041 (org-global-tags-completion-table)))
9042 (setq match (completing-read
9043 "Match: " 'org-tags-completion-function nil nil nil
9044 'org-tags-history))))
9046 ;; Parse the string and create a lisp form
9047 (let ((match0 match)
9048 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
9049 minus tag mm
9050 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
9051 orterms term orlist re-p str-p level-p level-op time-p
9052 prop-p pn pv po cat-p gv rest)
9053 (if (string-match "/+" match)
9054 ;; match contains also a todo-matching request
9055 (progn
9056 (setq tagsmatch (substring match 0 (match-beginning 0))
9057 todomatch (substring match (match-end 0)))
9058 (if (string-match "^!" todomatch)
9059 (setq todo-only t todomatch (substring todomatch 1)))
9060 (if (string-match "^\\s-*$" todomatch)
9061 (setq todomatch nil)))
9062 ;; only matching tags
9063 (setq tagsmatch match todomatch nil))
9065 ;; Make the tags matcher
9066 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
9067 (setq tagsmatcher t)
9068 (setq orterms (org-split-string tagsmatch "|") orlist nil)
9069 (while (setq term (pop orterms))
9070 (while (and (equal (substring term -1) "\\") orterms)
9071 (setq term (concat term "|" (pop orterms)))) ; repair bad split
9072 (while (string-match re term)
9073 (setq rest (substring term (match-end 0))
9074 minus (and (match-end 1)
9075 (equal (match-string 1 term) "-"))
9076 tag (match-string 2 term)
9077 re-p (equal (string-to-char tag) ?{)
9078 level-p (match-end 4)
9079 prop-p (match-end 5)
9080 mm (cond
9081 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
9082 (level-p
9083 (setq level-op (org-op-to-function (match-string 3 term)))
9084 `(,level-op level ,(string-to-number
9085 (match-string 4 term))))
9086 (prop-p
9087 (setq pn (match-string 5 term)
9088 po (match-string 6 term)
9089 pv (match-string 7 term)
9090 cat-p (equal pn "CATEGORY")
9091 re-p (equal (string-to-char pv) ?{)
9092 str-p (equal (string-to-char pv) ?\")
9093 time-p (save-match-data
9094 (string-match "^\"[[<].*[]>]\"$" pv))
9095 pv (if (or re-p str-p) (substring pv 1 -1) pv))
9096 (if time-p (setq pv (org-matcher-time pv)))
9097 (setq po (org-op-to-function po (if time-p 'time str-p)))
9098 (cond
9099 ((equal pn "CATEGORY")
9100 (setq gv '(get-text-property (point) 'org-category)))
9101 ((equal pn "TODO")
9102 (setq gv 'todo))
9104 (setq gv `(org-cached-entry-get nil ,pn))))
9105 (if re-p
9106 (if (eq po 'org<>)
9107 `(not (string-match ,pv (or ,gv "")))
9108 `(string-match ,pv (or ,gv "")))
9109 (if str-p
9110 `(,po (or ,gv "") ,pv)
9111 `(,po (string-to-number (or ,gv ""))
9112 ,(string-to-number pv) ))))
9113 (t `(member ,(downcase tag) tags-list)))
9114 mm (if minus (list 'not mm) mm)
9115 term rest)
9116 (push mm tagsmatcher))
9117 (push (if (> (length tagsmatcher) 1)
9118 (cons 'and tagsmatcher)
9119 (car tagsmatcher))
9120 orlist)
9121 (setq tagsmatcher nil))
9122 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
9123 (setq tagsmatcher
9124 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
9125 ;; Make the todo matcher
9126 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
9127 (setq todomatcher t)
9128 (setq orterms (org-split-string todomatch "|") orlist nil)
9129 (while (setq term (pop orterms))
9130 (while (string-match re term)
9131 (setq minus (and (match-end 1)
9132 (equal (match-string 1 term) "-"))
9133 kwd (match-string 2 term)
9134 re-p (equal (string-to-char kwd) ?{)
9135 term (substring term (match-end 0))
9136 mm (if re-p
9137 `(string-match ,(substring kwd 1 -1) todo)
9138 (list 'equal 'todo kwd))
9139 mm (if minus (list 'not mm) mm))
9140 (push mm todomatcher))
9141 (push (if (> (length todomatcher) 1)
9142 (cons 'and todomatcher)
9143 (car todomatcher))
9144 orlist)
9145 (setq todomatcher nil))
9146 (setq todomatcher (if (> (length orlist) 1)
9147 (cons 'or orlist) (car orlist))))
9149 ;; Return the string and lisp forms of the matcher
9150 (setq matcher (if todomatcher
9151 (list 'and tagsmatcher todomatcher)
9152 tagsmatcher))
9153 (cons match0 matcher)))
9155 (defun org-op-to-function (op &optional stringp)
9156 "Turn an operator into the appropriate function."
9157 (setq op
9158 (cond
9159 ((equal op "<" ) '(< string< org-time<))
9160 ((equal op ">" ) '(> org-string> org-time>))
9161 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
9162 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
9163 ((member op '("=" "==")) '(= string= org-time=))
9164 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
9165 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
9167 (defun org<> (a b) (not (= a b)))
9168 (defun org-string<= (a b) (or (string= a b) (string< a b)))
9169 (defun org-string>= (a b) (not (string< a b)))
9170 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
9171 (defun org-string<> (a b) (not (string= a b)))
9172 (defun org-time= (a b) (= (org-2ft a) (org-2ft b)))
9173 (defun org-time< (a b) (< (org-2ft a) (org-2ft b)))
9174 (defun org-time<= (a b) (<= (org-2ft a) (org-2ft b)))
9175 (defun org-time> (a b) (> (org-2ft a) (org-2ft b)))
9176 (defun org-time>= (a b) (>= (org-2ft a) (org-2ft b)))
9177 (defun org-time<> (a b) (org<> (org-2ft a) (org-2ft b)))
9178 (defun org-2ft (s)
9179 "Convert S to a floating point time.
9180 If S is already a number, just return it. If it is a string, parse
9181 it as a time string and apply `float-time' to it. f S is nil, just return 0."
9182 (cond
9183 ((numberp s) s)
9184 ((stringp s)
9185 (condition-case nil
9186 (float-time (apply 'encode-time (org-parse-time-string s)))
9187 (error 0.)))
9188 (t 0.)))
9190 (defun org-matcher-time (s)
9191 (cond
9192 ((equal s "<now>") (float-time))
9193 ((equal s "<today>")
9194 (float-time (append '(0 0 0) (nthcdr 3 (decode-time)))))
9195 (t (org-2ft s))))
9197 (defun org-match-any-p (re list)
9198 "Does re match any element of list?"
9199 (setq list (mapcar (lambda (x) (string-match re x)) list))
9200 (delq nil list))
9202 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
9203 (defvar org-tags-overlay (org-make-overlay 1 1))
9204 (org-detach-overlay org-tags-overlay)
9206 (defun org-get-local-tags-at (&optional pos)
9207 "Get a list of tags defined in the current headline."
9208 (org-get-tags-at pos 'local))
9210 (defun org-get-local-tags ()
9211 "Get a list of tags defined in the current headline."
9212 (org-get-tags-at nil 'local))
9214 (defun org-get-tags-at (&optional pos local)
9215 "Get a list of all headline tags applicable at POS.
9216 POS defaults to point. If tags are inherited, the list contains
9217 the targets in the same sequence as the headlines appear, i.e.
9218 the tags of the current headline come last.
9219 When LOCAL is non-nil, only return tags from the current headline,
9220 ignore inherited ones."
9221 (interactive)
9222 (let (tags ltags lastpos parent)
9223 (save-excursion
9224 (save-restriction
9225 (widen)
9226 (goto-char (or pos (point)))
9227 (save-match-data
9228 (catch 'done
9229 (condition-case nil
9230 (progn
9231 (org-back-to-heading t)
9232 (while (not (equal lastpos (point)))
9233 (setq lastpos (point))
9234 (when (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
9235 (setq ltags (org-split-string
9236 (org-match-string-no-properties 1) ":"))
9237 (setq tags (append
9238 (if parent
9239 (org-remove-uniherited-tags ltags)
9240 ltags)
9241 tags)))
9242 (or org-use-tag-inheritance (throw 'done t))
9243 (if local (throw 'done t))
9244 (org-up-heading-all 1)
9245 (setq parent t)))
9246 (error nil)))))
9247 (append (org-remove-uniherited-tags org-file-tags) tags))))
9249 (defun org-toggle-tag (tag &optional onoff)
9250 "Toggle the tag TAG for the current line.
9251 If ONOFF is `on' or `off', don't toggle but set to this state."
9252 (unless (org-on-heading-p t) (error "Not on headling"))
9253 (let (res current)
9254 (save-excursion
9255 (beginning-of-line)
9256 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
9257 (point-at-eol) t)
9258 (progn
9259 (setq current (match-string 1))
9260 (replace-match ""))
9261 (setq current ""))
9262 (setq current (nreverse (org-split-string current ":")))
9263 (cond
9264 ((eq onoff 'on)
9265 (setq res t)
9266 (or (member tag current) (push tag current)))
9267 ((eq onoff 'off)
9268 (or (not (member tag current)) (setq current (delete tag current))))
9269 (t (if (member tag current)
9270 (setq current (delete tag current))
9271 (setq res t)
9272 (push tag current))))
9273 (end-of-line 1)
9274 (if current
9275 (progn
9276 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
9277 (org-set-tags nil t))
9278 (delete-horizontal-space))
9279 (run-hooks 'org-after-tags-change-hook))
9280 res))
9282 (defun org-align-tags-here (to-col)
9283 ;; Assumes that this is a headline
9284 (let ((pos (point)) (col (current-column)) ncol tags-l p)
9285 (beginning-of-line 1)
9286 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9287 (< pos (match-beginning 2)))
9288 (progn
9289 (setq tags-l (- (match-end 2) (match-beginning 2)))
9290 (goto-char (match-beginning 1))
9291 (insert " ")
9292 (delete-region (point) (1+ (match-beginning 2)))
9293 (setq ncol (max (1+ (current-column))
9294 (1+ col)
9295 (if (> to-col 0)
9296 to-col
9297 (- (abs to-col) tags-l))))
9298 (setq p (point))
9299 (insert (make-string (- ncol (current-column)) ?\ ))
9300 (setq ncol (current-column))
9301 (when indent-tabs-mode (tabify p (point-at-eol)))
9302 (org-move-to-column (min ncol col) t))
9303 (goto-char pos))))
9305 (defun org-set-tags-command (&optional arg just-align)
9306 "Call the set-tags command for the current entry."
9307 (interactive "P")
9308 (if (org-on-heading-p)
9309 (org-set-tags arg just-align)
9310 (save-excursion
9311 (org-back-to-heading t)
9312 (org-set-tags arg just-align))))
9314 (defun org-set-tags (&optional arg just-align)
9315 "Set the tags for the current headline.
9316 With prefix ARG, realign all tags in headings in the current buffer."
9317 (interactive "P")
9318 (let* ((re (concat "^" outline-regexp))
9319 (current (org-get-tags-string))
9320 (col (current-column))
9321 (org-setting-tags t)
9322 table current-tags inherited-tags ; computed below when needed
9323 tags p0 c0 c1 rpl)
9324 (if arg
9325 (save-excursion
9326 (goto-char (point-min))
9327 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
9328 (while (re-search-forward re nil t)
9329 (org-set-tags nil t)
9330 (end-of-line 1)))
9331 (message "All tags realigned to column %d" org-tags-column))
9332 (if just-align
9333 (setq tags current)
9334 ;; Get a new set of tags from the user
9335 (save-excursion
9336 (setq table (or org-tag-alist (org-get-buffer-tags))
9337 org-last-tags-completion-table table
9338 current-tags (org-split-string current ":")
9339 inherited-tags (nreverse
9340 (nthcdr (length current-tags)
9341 (nreverse (org-get-tags-at))))
9342 tags
9343 (if (or (eq t org-use-fast-tag-selection)
9344 (and org-use-fast-tag-selection
9345 (delq nil (mapcar 'cdr table))))
9346 (org-fast-tag-selection
9347 current-tags inherited-tags table
9348 (if org-fast-tag-selection-include-todo org-todo-key-alist))
9349 (let ((org-add-colon-after-tag-completion t))
9350 (org-trim
9351 (org-without-partial-completion
9352 (completing-read "Tags: " 'org-tags-completion-function
9353 nil nil current 'org-tags-history)))))))
9354 (while (string-match "[-+&]+" tags)
9355 ;; No boolean logic, just a list
9356 (setq tags (replace-match ":" t t tags))))
9358 (if (string-match "\\`[\t ]*\\'" tags)
9359 (setq tags "")
9360 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
9361 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
9363 ;; Insert new tags at the correct column
9364 (beginning-of-line 1)
9365 (cond
9366 ((and (equal current "") (equal tags "")))
9367 ((re-search-forward
9368 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
9369 (point-at-eol) t)
9370 (if (equal tags "")
9371 (setq rpl "")
9372 (goto-char (match-beginning 0))
9373 (setq c0 (current-column) p0 (point)
9374 c1 (max (1+ c0) (if (> org-tags-column 0)
9375 org-tags-column
9376 (- (- org-tags-column) (length tags))))
9377 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
9378 (replace-match rpl t t)
9379 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
9380 tags)
9381 (t (error "Tags alignment failed")))
9382 (org-move-to-column col)
9383 (unless just-align
9384 (run-hooks 'org-after-tags-change-hook)))))
9386 (defun org-change-tag-in-region (beg end tag off)
9387 "Add or remove TAG for each entry in the region.
9388 This works in the agenda, and also in an org-mode buffer."
9389 (interactive
9390 (list (region-beginning) (region-end)
9391 (let ((org-last-tags-completion-table
9392 (if (org-mode-p)
9393 (org-get-buffer-tags)
9394 (org-global-tags-completion-table))))
9395 (completing-read
9396 "Tag: " 'org-tags-completion-function nil nil nil
9397 'org-tags-history))
9398 (progn
9399 (message "[s]et or [r]emove? ")
9400 (equal (read-char-exclusive) ?r))))
9401 (if (fboundp 'deactivate-mark) (deactivate-mark))
9402 (let ((agendap (equal major-mode 'org-agenda-mode))
9403 l1 l2 m buf pos newhead (cnt 0))
9404 (goto-char end)
9405 (setq l2 (1- (org-current-line)))
9406 (goto-char beg)
9407 (setq l1 (org-current-line))
9408 (loop for l from l1 to l2 do
9409 (goto-line l)
9410 (setq m (get-text-property (point) 'org-hd-marker))
9411 (when (or (and (org-mode-p) (org-on-heading-p))
9412 (and agendap m))
9413 (setq buf (if agendap (marker-buffer m) (current-buffer))
9414 pos (if agendap m (point)))
9415 (with-current-buffer buf
9416 (save-excursion
9417 (save-restriction
9418 (goto-char pos)
9419 (setq cnt (1+ cnt))
9420 (org-toggle-tag tag (if off 'off 'on))
9421 (setq newhead (org-get-heading)))))
9422 (and agendap (org-agenda-change-all-lines newhead m))))
9423 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
9425 (defun org-tags-completion-function (string predicate &optional flag)
9426 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
9427 (confirm (lambda (x) (stringp (car x)))))
9428 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
9429 (setq s1 (match-string 1 string)
9430 s2 (match-string 2 string))
9431 (setq s1 "" s2 string))
9432 (cond
9433 ((eq flag nil)
9434 ;; try completion
9435 (setq rtn (try-completion s2 ctable confirm))
9436 (if (stringp rtn)
9437 (setq rtn
9438 (concat s1 s2 (substring rtn (length s2))
9439 (if (and org-add-colon-after-tag-completion
9440 (assoc rtn ctable))
9441 ":" ""))))
9442 rtn)
9443 ((eq flag t)
9444 ;; all-completions
9445 (all-completions s2 ctable confirm)
9447 ((eq flag 'lambda)
9448 ;; exact match?
9449 (assoc s2 ctable)))
9452 (defun org-fast-tag-insert (kwd tags face &optional end)
9453 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
9454 (insert (format "%-12s" (concat kwd ":"))
9455 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
9456 (or end "")))
9458 (defun org-fast-tag-show-exit (flag)
9459 (save-excursion
9460 (goto-line 3)
9461 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
9462 (replace-match ""))
9463 (when flag
9464 (end-of-line 1)
9465 (org-move-to-column (- (window-width) 19) t)
9466 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
9468 (defun org-set-current-tags-overlay (current prefix)
9469 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
9470 (if (featurep 'xemacs)
9471 (org-overlay-display org-tags-overlay (concat prefix s)
9472 'secondary-selection)
9473 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
9474 (org-overlay-display org-tags-overlay (concat prefix s)))))
9476 (defun org-fast-tag-selection (current inherited table &optional todo-table)
9477 "Fast tag selection with single keys.
9478 CURRENT is the current list of tags in the headline, INHERITED is the
9479 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
9480 possibly with grouping information. TODO-TABLE is a similar table with
9481 TODO keywords, should these have keys assigned to them.
9482 If the keys are nil, a-z are automatically assigned.
9483 Returns the new tags string, or nil to not change the current settings."
9484 (let* ((fulltable (append table todo-table))
9485 (maxlen (apply 'max (mapcar
9486 (lambda (x)
9487 (if (stringp (car x)) (string-width (car x)) 0))
9488 fulltable)))
9489 (buf (current-buffer))
9490 (expert (eq org-fast-tag-selection-single-key 'expert))
9491 (buffer-tags nil)
9492 (fwidth (+ maxlen 3 1 3))
9493 (ncol (/ (- (window-width) 4) fwidth))
9494 (i-face 'org-done)
9495 (c-face 'org-todo)
9496 tg cnt e c char c1 c2 ntable tbl rtn
9497 ov-start ov-end ov-prefix
9498 (exit-after-next org-fast-tag-selection-single-key)
9499 (done-keywords org-done-keywords)
9500 groups ingroup)
9501 (save-excursion
9502 (beginning-of-line 1)
9503 (if (looking-at
9504 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9505 (setq ov-start (match-beginning 1)
9506 ov-end (match-end 1)
9507 ov-prefix "")
9508 (setq ov-start (1- (point-at-eol))
9509 ov-end (1+ ov-start))
9510 (skip-chars-forward "^\n\r")
9511 (setq ov-prefix
9512 (concat
9513 (buffer-substring (1- (point)) (point))
9514 (if (> (current-column) org-tags-column)
9516 (make-string (- org-tags-column (current-column)) ?\ ))))))
9517 (org-move-overlay org-tags-overlay ov-start ov-end)
9518 (save-window-excursion
9519 (if expert
9520 (set-buffer (get-buffer-create " *Org tags*"))
9521 (delete-other-windows)
9522 (split-window-vertically)
9523 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
9524 (erase-buffer)
9525 (org-set-local 'org-done-keywords done-keywords)
9526 (org-fast-tag-insert "Inherited" inherited i-face "\n")
9527 (org-fast-tag-insert "Current" current c-face "\n\n")
9528 (org-fast-tag-show-exit exit-after-next)
9529 (org-set-current-tags-overlay current ov-prefix)
9530 (setq tbl fulltable char ?a cnt 0)
9531 (while (setq e (pop tbl))
9532 (cond
9533 ((equal e '(:startgroup))
9534 (push '() groups) (setq ingroup t)
9535 (when (not (= cnt 0))
9536 (setq cnt 0)
9537 (insert "\n"))
9538 (insert "{ "))
9539 ((equal e '(:endgroup))
9540 (setq ingroup nil cnt 0)
9541 (insert "}\n"))
9543 (setq tg (car e) c2 nil)
9544 (if (cdr e)
9545 (setq c (cdr e))
9546 ;; automatically assign a character.
9547 (setq c1 (string-to-char
9548 (downcase (substring
9549 tg (if (= (string-to-char tg) ?@) 1 0)))))
9550 (if (or (rassoc c1 ntable) (rassoc c1 table))
9551 (while (or (rassoc char ntable) (rassoc char table))
9552 (setq char (1+ char)))
9553 (setq c2 c1))
9554 (setq c (or c2 char)))
9555 (if ingroup (push tg (car groups)))
9556 (setq tg (org-add-props tg nil 'face
9557 (cond
9558 ((not (assoc tg table))
9559 (org-get-todo-face tg))
9560 ((member tg current) c-face)
9561 ((member tg inherited) i-face)
9562 (t nil))))
9563 (if (and (= cnt 0) (not ingroup)) (insert " "))
9564 (insert "[" c "] " tg (make-string
9565 (- fwidth 4 (length tg)) ?\ ))
9566 (push (cons tg c) ntable)
9567 (when (= (setq cnt (1+ cnt)) ncol)
9568 (insert "\n")
9569 (if ingroup (insert " "))
9570 (setq cnt 0)))))
9571 (setq ntable (nreverse ntable))
9572 (insert "\n")
9573 (goto-char (point-min))
9574 (if (not expert) (org-fit-window-to-buffer))
9575 (setq rtn
9576 (catch 'exit
9577 (while t
9578 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
9579 (if groups " [!] no groups" " [!]groups")
9580 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
9581 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9582 (cond
9583 ((= c ?\r) (throw 'exit t))
9584 ((= c ?!)
9585 (setq groups (not groups))
9586 (goto-char (point-min))
9587 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
9588 ((= c ?\C-c)
9589 (if (not expert)
9590 (org-fast-tag-show-exit
9591 (setq exit-after-next (not exit-after-next)))
9592 (setq expert nil)
9593 (delete-other-windows)
9594 (split-window-vertically)
9595 (org-switch-to-buffer-other-window " *Org tags*")
9596 (org-fit-window-to-buffer)))
9597 ((or (= c ?\C-g)
9598 (and (= c ?q) (not (rassoc c ntable))))
9599 (org-detach-overlay org-tags-overlay)
9600 (setq quit-flag t))
9601 ((= c ?\ )
9602 (setq current nil)
9603 (if exit-after-next (setq exit-after-next 'now)))
9604 ((= c ?\t)
9605 (condition-case nil
9606 (setq tg (completing-read
9607 "Tag: "
9608 (or buffer-tags
9609 (with-current-buffer buf
9610 (org-get-buffer-tags)))))
9611 (quit (setq tg "")))
9612 (when (string-match "\\S-" tg)
9613 (add-to-list 'buffer-tags (list tg))
9614 (if (member tg current)
9615 (setq current (delete tg current))
9616 (push tg current)))
9617 (if exit-after-next (setq exit-after-next 'now)))
9618 ((setq e (rassoc c todo-table) tg (car e))
9619 (with-current-buffer buf
9620 (save-excursion (org-todo tg)))
9621 (if exit-after-next (setq exit-after-next 'now)))
9622 ((setq e (rassoc c ntable) tg (car e))
9623 (if (member tg current)
9624 (setq current (delete tg current))
9625 (loop for g in groups do
9626 (if (member tg g)
9627 (mapc (lambda (x)
9628 (setq current (delete x current)))
9629 g)))
9630 (push tg current))
9631 (if exit-after-next (setq exit-after-next 'now))))
9633 ;; Create a sorted list
9634 (setq current
9635 (sort current
9636 (lambda (a b)
9637 (assoc b (cdr (memq (assoc a ntable) ntable))))))
9638 (if (eq exit-after-next 'now) (throw 'exit t))
9639 (goto-char (point-min))
9640 (beginning-of-line 2)
9641 (delete-region (point) (point-at-eol))
9642 (org-fast-tag-insert "Current" current c-face)
9643 (org-set-current-tags-overlay current ov-prefix)
9644 (while (re-search-forward
9645 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
9646 (setq tg (match-string 1))
9647 (add-text-properties
9648 (match-beginning 1) (match-end 1)
9649 (list 'face
9650 (cond
9651 ((member tg current) c-face)
9652 ((member tg inherited) i-face)
9653 (t (get-text-property (match-beginning 1) 'face))))))
9654 (goto-char (point-min)))))
9655 (org-detach-overlay org-tags-overlay)
9656 (if rtn
9657 (mapconcat 'identity current ":")
9658 nil))))
9660 (defun org-get-tags-string ()
9661 "Get the TAGS string in the current headline."
9662 (unless (org-on-heading-p t)
9663 (error "Not on a heading"))
9664 (save-excursion
9665 (beginning-of-line 1)
9666 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9667 (org-match-string-no-properties 1)
9668 "")))
9670 (defun org-get-tags ()
9671 "Get the list of tags specified in the current headline."
9672 (org-split-string (org-get-tags-string) ":"))
9674 (defun org-get-buffer-tags ()
9675 "Get a table of all tags used in the buffer, for completion."
9676 (let (tags)
9677 (save-excursion
9678 (goto-char (point-min))
9679 (while (re-search-forward
9680 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
9681 (when (equal (char-after (point-at-bol 0)) ?*)
9682 (mapc (lambda (x) (add-to-list 'tags x))
9683 (org-split-string (org-match-string-no-properties 1) ":")))))
9684 (mapcar 'list tags)))
9686 ;;;; The mapping API
9688 ;;;###autoload
9689 (defun org-map-entries (func &optional match scope &rest skip)
9690 "Call FUNC at each headline selected by MATCH in SCOPE.
9692 FUNC is a function or a lisp form. The function will be called without
9693 arguments, with the cursor positioned at the beginning of the headline.
9694 The return values of all calls to the function will be collected and
9695 returned as a list.
9697 MATCH is a tags/property/todo match as it is used in the agenda tags view.
9698 Only headlines that are matched by this query will be considered during
9699 the iteration. When MATCH is nil or t, all headlines will be
9700 visited by the iteration.
9702 SCOPE determines the scope of this command. It can be any of:
9704 nil The current buffer, respecting the restriction if any
9705 tree The subtree started with the entry at point
9706 file The current buffer, without restriction
9707 file-with-archives
9708 The current buffer, and any archives associated with it
9709 agenda All agenda files
9710 agenda-with-archives
9711 All agenda files with any archive files associated with them
9712 \(file1 file2 ...)
9713 If this is a list, all files in the list will be scanned
9715 The remaining args are treated as settings for the skipping facilities of
9716 the scanner. The following items can be given here:
9718 archive skip trees with the archive tag.
9719 comment skip trees with the COMMENT keyword
9720 function or Emacs Lisp form:
9721 will be used as value for `org-agenda-skip-function', so whenever
9722 the the function returns t, FUNC will not be called for that
9723 entry and search will continue from the point where the
9724 function leaves it."
9725 (let* ((org-agenda-archives-mode nil) ; just to make sure
9726 (org-agenda-skip-archived-trees (memq 'archive skip))
9727 (org-agenda-skip-comment-trees (memq 'comment skip))
9728 (org-agenda-skip-function
9729 (car (org-delete-all '(comment archive) skip)))
9730 (org-tags-match-list-sublevels t)
9731 matcher pos file
9732 org-todo-keywords-for-agenda
9733 org-done-keywords-for-agenda
9734 org-todo-keyword-alist-for-agenda
9735 org-tag-alist-for-agenda)
9737 (cond
9738 ((eq match t) (setq matcher t))
9739 ((eq match nil) (setq matcher t))
9740 (t (setq matcher (if match (org-make-tags-matcher match) t))))
9742 (when (eq scope 'tree)
9743 (org-back-to-heading t)
9744 (org-narrow-to-subtree)
9745 (setq scope nil))
9747 (if (not scope)
9748 (progn
9749 (org-prepare-agenda-buffers
9750 (list (buffer-file-name (current-buffer))))
9751 (org-scan-tags func matcher))
9752 ;; Get the right scope
9753 (setq pos (point))
9754 (cond
9755 ((and scope (listp scope) (symbolp (car scope)))
9756 (setq scope (eval scope)))
9757 ((eq scope 'agenda)
9758 (setq scope (org-agenda-files t)))
9759 ((eq scope 'agenda-with-archives)
9760 (setq scope (org-agenda-files t))
9761 (setq scope (org-add-archive-files scope)))
9762 ((eq scope 'file)
9763 (setq scope (list (buffer-file-name))))
9764 ((eq scope 'file-with-archives)
9765 (setq scope (org-add-archive-files (list (buffer-file-name))))))
9766 (org-prepare-agenda-buffers scope)
9767 (while (setq file (pop scope))
9768 (with-current-buffer (org-find-base-buffer-visiting file)
9769 (save-excursion
9770 (save-restriction
9771 (widen)
9772 (goto-char (point-min))
9773 (org-scan-tags func matcher))))))))
9775 ;;;; Properties
9777 ;;; Setting and retrieving properties
9779 (defconst org-special-properties
9780 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
9781 "TIMESTAMP" "TIMESTAMP_IA")
9782 "The special properties valid in Org-mode.
9784 These are properties that are not defined in the property drawer,
9785 but in some other way.")
9787 (defconst org-default-properties
9788 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
9789 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
9790 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
9791 "EXPORT_FILE_NAME" "EXPORT_TITLE")
9792 "Some properties that are used by Org-mode for various purposes.
9793 Being in this list makes sure that they are offered for completion.")
9795 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
9796 "Regular expression matching the first line of a property drawer.")
9798 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
9799 "Regular expression matching the first line of a property drawer.")
9801 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
9802 "Regular expression matching the first line of a property drawer.")
9804 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
9805 "Regular expression matching the first line of a property drawer.")
9807 (defconst org-property-drawer-re
9808 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
9809 org-property-end-re "\\)\n?")
9810 "Matches an entire property drawer.")
9812 (defconst org-clock-drawer-re
9813 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
9814 org-property-end-re "\\)\n?")
9815 "Matches an entire clock drawer.")
9817 (defun org-property-action ()
9818 "Do an action on properties."
9819 (interactive)
9820 (let (c)
9821 (org-at-property-p)
9822 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
9823 (setq c (read-char-exclusive))
9824 (cond
9825 ((equal c ?s)
9826 (call-interactively 'org-set-property))
9827 ((equal c ?d)
9828 (call-interactively 'org-delete-property))
9829 ((equal c ?D)
9830 (call-interactively 'org-delete-property-globally))
9831 ((equal c ?c)
9832 (call-interactively 'org-compute-property-at-point))
9833 (t (error "No such property action %c" c)))))
9835 (defun org-at-property-p ()
9836 "Is the cursor in a property line?"
9837 ;; FIXME: Does not check if we are actually in the drawer.
9838 ;; FIXME: also returns true on any drawers.....
9839 ;; This is used by C-c C-c for property action.
9840 (save-excursion
9841 (beginning-of-line 1)
9842 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
9844 (defun org-get-property-block (&optional beg end force)
9845 "Return the (beg . end) range of the body of the property drawer.
9846 BEG and END can be beginning and end of subtree, if not given
9847 they will be found.
9848 If the drawer does not exist and FORCE is non-nil, create the drawer."
9849 (catch 'exit
9850 (save-excursion
9851 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
9852 (end (or end (progn (outline-next-heading) (point)))))
9853 (goto-char beg)
9854 (if (re-search-forward org-property-start-re end t)
9855 (setq beg (1+ (match-end 0)))
9856 (if force
9857 (save-excursion
9858 (org-insert-property-drawer)
9859 (setq end (progn (outline-next-heading) (point))))
9860 (throw 'exit nil))
9861 (goto-char beg)
9862 (if (re-search-forward org-property-start-re end t)
9863 (setq beg (1+ (match-end 0)))))
9864 (if (re-search-forward org-property-end-re end t)
9865 (setq end (match-beginning 0))
9866 (or force (throw 'exit nil))
9867 (goto-char beg)
9868 (setq end beg)
9869 (org-indent-line-function)
9870 (insert ":END:\n"))
9871 (cons beg end)))))
9873 (defun org-entry-properties (&optional pom which)
9874 "Get all properties of the entry at point-or-marker POM.
9875 This includes the TODO keyword, the tags, time strings for deadline,
9876 scheduled, and clocking, and any additional properties defined in the
9877 entry. The return value is an alist, keys may occur multiple times
9878 if the property key was used several times.
9879 POM may also be nil, in which case the current entry is used.
9880 If WHICH is nil or `all', get all properties. If WHICH is
9881 `special' or `standard', only get that subclass."
9882 (setq which (or which 'all))
9883 (org-with-point-at pom
9884 (let ((clockstr (substring org-clock-string 0 -1))
9885 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
9886 beg end range props sum-props key value string clocksum)
9887 (save-excursion
9888 (when (condition-case nil (org-back-to-heading t) (error nil))
9889 (setq beg (point))
9890 (setq sum-props (get-text-property (point) 'org-summaries))
9891 (setq clocksum (get-text-property (point) :org-clock-minutes))
9892 (outline-next-heading)
9893 (setq end (point))
9894 (when (memq which '(all special))
9895 ;; Get the special properties, like TODO and tags
9896 (goto-char beg)
9897 (when (and (looking-at org-todo-line-regexp) (match-end 2))
9898 (push (cons "TODO" (org-match-string-no-properties 2)) props))
9899 (when (looking-at org-priority-regexp)
9900 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
9901 (when (and (setq value (org-get-tags-string))
9902 (string-match "\\S-" value))
9903 (push (cons "TAGS" value) props))
9904 (when (setq value (org-get-tags-at))
9905 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
9906 props))
9907 (while (re-search-forward org-maybe-keyword-time-regexp end t)
9908 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
9909 string (if (equal key clockstr)
9910 (org-no-properties
9911 (org-trim
9912 (buffer-substring
9913 (match-beginning 3) (goto-char (point-at-eol)))))
9914 (substring (org-match-string-no-properties 3) 1 -1)))
9915 (unless key
9916 (if (= (char-after (match-beginning 3)) ?\[)
9917 (setq key "TIMESTAMP_IA")
9918 (setq key "TIMESTAMP")))
9919 (when (or (equal key clockstr) (not (assoc key props)))
9920 (push (cons key string) props)))
9924 (when (memq which '(all standard))
9925 ;; Get the standard properties, like :PORP: ...
9926 (setq range (org-get-property-block beg end))
9927 (when range
9928 (goto-char (car range))
9929 (while (re-search-forward
9930 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
9931 (cdr range) t)
9932 (setq key (org-match-string-no-properties 1)
9933 value (org-trim (or (org-match-string-no-properties 2) "")))
9934 (unless (member key excluded)
9935 (push (cons key (or value "")) props)))))
9936 (if clocksum
9937 (push (cons "CLOCKSUM"
9938 (org-columns-number-to-string (/ (float clocksum) 60.)
9939 'add_times))
9940 props))
9941 (unless (assoc "CATEGORY" props)
9942 (setq value (or (org-get-category)
9943 (progn (org-refresh-category-properties)
9944 (org-get-category))))
9945 (push (cons "CATEGORY" value) props))
9946 (append sum-props (nreverse props)))))))
9948 (defun org-entry-get (pom property &optional inherit)
9949 "Get value of PROPERTY for entry at point-or-marker POM.
9950 If INHERIT is non-nil and the entry does not have the property,
9951 then also check higher levels of the hierarchy.
9952 If INHERIT is the symbol `selective', use inheritance only if the setting
9953 in `org-use-property-inheritance' selects PROPERTY for inheritance.
9954 If the property is present but empty, the return value is the empty string.
9955 If the property is not present at all, nil is returned."
9956 (org-with-point-at pom
9957 (if (and inherit (if (eq inherit 'selective)
9958 (org-property-inherit-p property)
9960 (org-entry-get-with-inheritance property)
9961 (if (member property org-special-properties)
9962 ;; We need a special property. Use brute force, get all properties.
9963 (cdr (assoc property (org-entry-properties nil 'special)))
9964 (let ((range (org-get-property-block)))
9965 (if (and range
9966 (goto-char (car range))
9967 (re-search-forward
9968 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
9969 (cdr range) t))
9970 ;; Found the property, return it.
9971 (if (match-end 1)
9972 (org-match-string-no-properties 1)
9973 "")))))))
9975 (defun org-property-or-variable-value (var &optional inherit)
9976 "Check if there is a property fixing the value of VAR.
9977 If yes, return this value. If not, return the current value of the variable."
9978 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
9979 (if (and prop (stringp prop) (string-match "\\S-" prop))
9980 (read prop)
9981 (symbol-value var))))
9983 (defun org-entry-delete (pom property)
9984 "Delete the property PROPERTY from entry at point-or-marker POM."
9985 (org-with-point-at pom
9986 (if (member property org-special-properties)
9987 nil ; cannot delete these properties.
9988 (let ((range (org-get-property-block)))
9989 (if (and range
9990 (goto-char (car range))
9991 (re-search-forward
9992 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
9993 (cdr range) t))
9994 (progn
9995 (delete-region (match-beginning 0) (1+ (point-at-eol)))
9997 nil)))))
9999 ;; Multi-values properties are properties that contain multiple values
10000 ;; These values are assumed to be single words, separated by whitespace.
10001 (defun org-entry-add-to-multivalued-property (pom property value)
10002 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
10003 (let* ((old (org-entry-get pom property))
10004 (values (and old (org-split-string old "[ \t]"))))
10005 (setq value (org-entry-protect-space value))
10006 (unless (member value values)
10007 (setq values (cons value values))
10008 (org-entry-put pom property
10009 (mapconcat 'identity values " ")))))
10011 (defun org-entry-remove-from-multivalued-property (pom property value)
10012 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
10013 (let* ((old (org-entry-get pom property))
10014 (values (and old (org-split-string old "[ \t]"))))
10015 (setq value (org-entry-protect-space value))
10016 (when (member value values)
10017 (setq values (delete value values))
10018 (org-entry-put pom property
10019 (mapconcat 'identity values " ")))))
10021 (defun org-entry-member-in-multivalued-property (pom property value)
10022 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
10023 (let* ((old (org-entry-get pom property))
10024 (values (and old (org-split-string old "[ \t]"))))
10025 (setq value (org-entry-protect-space value))
10026 (member value values)))
10028 (defun org-entry-get-multivalued-property (pom property)
10029 "Return a list of values in a multivalued property."
10030 (let* ((value (org-entry-get pom property))
10031 (values (and value (org-split-string value "[ \t]"))))
10032 (mapcar 'org-entry-restore-space values)))
10034 (defun org-entry-put-multivalued-property (pom property &rest values)
10035 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
10036 VALUES should be a list of strings. Spaces will be protected."
10037 (org-entry-put pom property
10038 (mapconcat 'org-entry-protect-space values " "))
10039 (let* ((value (org-entry-get pom property))
10040 (values (and value (org-split-string value "[ \t]"))))
10041 (mapcar 'org-entry-restore-space values)))
10043 (defun org-entry-protect-space (s)
10044 "Protect spaces and newline in string S."
10045 (while (string-match " " s)
10046 (setq s (replace-match "%20" t t s)))
10047 (while (string-match "\n" s)
10048 (setq s (replace-match "%0A" t t s)))
10051 (defun org-entry-restore-space (s)
10052 "Restore spaces and newline in string S."
10053 (while (string-match "%20" s)
10054 (setq s (replace-match " " t t s)))
10055 (while (string-match "%0A" s)
10056 (setq s (replace-match "\n" t t s)))
10059 (defvar org-entry-property-inherited-from (make-marker)
10060 "Marker pointing to the entry from where a proerty was inherited.
10061 Each call to `org-entry-get-with-inheritance' will set this marker to the
10062 location of the entry where the inheriance search matched. If there was
10063 no match, the marker will point nowhere.
10064 Note that also `org-entry-get' calls this function, if the INHERIT flag
10065 is set.")
10067 (defun org-entry-get-with-inheritance (property)
10068 "Get entry property, and search higher levels if not present."
10069 (move-marker org-entry-property-inherited-from nil)
10070 (let (tmp)
10071 (save-excursion
10072 (save-restriction
10073 (widen)
10074 (catch 'ex
10075 (while t
10076 (when (setq tmp (org-entry-get nil property))
10077 (org-back-to-heading t)
10078 (move-marker org-entry-property-inherited-from (point))
10079 (throw 'ex tmp))
10080 (or (org-up-heading-safe) (throw 'ex nil)))))
10081 (or tmp
10082 (cdr (assoc property org-file-properties))
10083 (cdr (assoc property org-global-properties))
10084 (cdr (assoc property org-global-properties-fixed))))))
10086 (defun org-entry-put (pom property value)
10087 "Set PROPERTY to VALUE for entry at point-or-marker POM."
10088 (org-with-point-at pom
10089 (org-back-to-heading t)
10090 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
10091 range)
10092 (cond
10093 ((equal property "TODO")
10094 (when (and (stringp value) (string-match "\\S-" value)
10095 (not (member value org-todo-keywords-1)))
10096 (error "\"%s\" is not a valid TODO state" value))
10097 (if (or (not value)
10098 (not (string-match "\\S-" value)))
10099 (setq value 'none))
10100 (org-todo value)
10101 (org-set-tags nil 'align))
10102 ((equal property "PRIORITY")
10103 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
10104 (string-to-char value) ?\ ))
10105 (org-set-tags nil 'align))
10106 ((equal property "SCHEDULED")
10107 (if (re-search-forward org-scheduled-time-regexp end t)
10108 (cond
10109 ((eq value 'earlier) (org-timestamp-change -1 'day))
10110 ((eq value 'later) (org-timestamp-change 1 'day))
10111 (t (call-interactively 'org-schedule)))
10112 (call-interactively 'org-schedule)))
10113 ((equal property "DEADLINE")
10114 (if (re-search-forward org-deadline-time-regexp end t)
10115 (cond
10116 ((eq value 'earlier) (org-timestamp-change -1 'day))
10117 ((eq value 'later) (org-timestamp-change 1 'day))
10118 (t (call-interactively 'org-deadline)))
10119 (call-interactively 'org-deadline)))
10120 ((member property org-special-properties)
10121 (error "The %s property can not yet be set with `org-entry-put'"
10122 property))
10123 (t ; a non-special property
10124 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
10125 (setq range (org-get-property-block beg end 'force))
10126 (goto-char (car range))
10127 (if (re-search-forward
10128 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
10129 (progn
10130 (delete-region (match-beginning 1) (match-end 1))
10131 (goto-char (match-beginning 1)))
10132 (goto-char (cdr range))
10133 (insert "\n")
10134 (backward-char 1)
10135 (org-indent-line-function)
10136 (insert ":" property ":"))
10137 (and value (insert " " value))
10138 (org-indent-line-function)))))))
10140 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
10141 "Get all property keys in the current buffer.
10142 With INCLUDE-SPECIALS, also list the special properties that relect things
10143 like tags and TODO state.
10144 With INCLUDE-DEFAULTS, also include properties that has special meaning
10145 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
10146 With INCLUDE-COLUMNS, also include property names given in COLUMN
10147 formats in the current buffer."
10148 (let (rtn range cfmt cols s p)
10149 (save-excursion
10150 (save-restriction
10151 (widen)
10152 (goto-char (point-min))
10153 (while (re-search-forward org-property-start-re nil t)
10154 (setq range (org-get-property-block))
10155 (goto-char (car range))
10156 (while (re-search-forward
10157 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
10158 (cdr range) t)
10159 (add-to-list 'rtn (org-match-string-no-properties 1)))
10160 (outline-next-heading))))
10162 (when include-specials
10163 (setq rtn (append org-special-properties rtn)))
10165 (when include-defaults
10166 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
10168 (when include-columns
10169 (save-excursion
10170 (save-restriction
10171 (widen)
10172 (goto-char (point-min))
10173 (while (re-search-forward
10174 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
10175 nil t)
10176 (setq cfmt (match-string 2) s 0)
10177 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
10178 cfmt s)
10179 (setq s (match-end 0)
10180 p (match-string 1 cfmt))
10181 (unless (or (equal p "ITEM")
10182 (member p org-special-properties))
10183 (add-to-list 'rtn (match-string 1 cfmt))))))))
10185 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
10187 (defun org-property-values (key)
10188 "Return a list of all values of property KEY."
10189 (save-excursion
10190 (save-restriction
10191 (widen)
10192 (goto-char (point-min))
10193 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
10194 values)
10195 (while (re-search-forward re nil t)
10196 (add-to-list 'values (org-trim (match-string 1))))
10197 (delete "" values)))))
10199 (defun org-insert-property-drawer ()
10200 "Insert a property drawer into the current entry."
10201 (interactive)
10202 (org-back-to-heading t)
10203 (looking-at outline-regexp)
10204 (let ((indent (- (match-end 0)(match-beginning 0)))
10205 (beg (point))
10206 (re (concat "^[ \t]*" org-keyword-time-regexp))
10207 end hiddenp)
10208 (outline-next-heading)
10209 (setq end (point))
10210 (goto-char beg)
10211 (while (re-search-forward re end t))
10212 (setq hiddenp (org-invisible-p))
10213 (end-of-line 1)
10214 (and (equal (char-after) ?\n) (forward-char 1))
10215 (while (looking-at "^[ \t]*\\(:CLOCK:\\|CLOCK\\|:END:\\)")
10216 (beginning-of-line 2))
10217 (org-skip-over-state-notes)
10218 (skip-chars-backward " \t\n\r")
10219 (if (eq (char-before) ?*) (forward-char 1))
10220 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
10221 (beginning-of-line 0)
10222 (org-indent-to-column indent)
10223 (beginning-of-line 2)
10224 (org-indent-to-column indent)
10225 (beginning-of-line 0)
10226 (if hiddenp
10227 (save-excursion
10228 (org-back-to-heading t)
10229 (hide-entry))
10230 (org-flag-drawer t))))
10232 (defun org-set-property (property value)
10233 "In the current entry, set PROPERTY to VALUE.
10234 When called interactively, this will prompt for a property name, offering
10235 completion on existing and default properties. And then it will prompt
10236 for a value, offering competion either on allowed values (via an inherited
10237 xxx_ALL property) or on existing values in other instances of this property
10238 in the current file."
10239 (interactive
10240 (let* ((completion-ignore-case t)
10241 (keys (org-buffer-property-keys nil t t))
10242 (prop0 (completing-read "Property: " (mapcar 'list keys)))
10243 (prop (if (member prop0 keys)
10244 prop0
10245 (or (cdr (assoc (downcase prop0)
10246 (mapcar (lambda (x) (cons (downcase x) x))
10247 keys)))
10248 prop0)))
10249 (cur (org-entry-get nil prop))
10250 (allowed (org-property-get-allowed-values nil prop 'table))
10251 (existing (mapcar 'list (org-property-values prop)))
10252 (val (if allowed
10253 (org-completing-read "Value: " allowed nil 'req-match)
10254 (org-completing-read
10255 (concat "Value" (if (and cur (string-match "\\S-" cur))
10256 (concat "[" cur "]") "")
10257 ": ")
10258 existing nil nil "" nil cur))))
10259 (list prop (if (equal val "") cur val))))
10260 (unless (equal (org-entry-get nil property) value)
10261 (org-entry-put nil property value)))
10263 (defun org-delete-property (property)
10264 "In the current entry, delete PROPERTY."
10265 (interactive
10266 (let* ((completion-ignore-case t)
10267 (prop (completing-read
10268 "Property: " (org-entry-properties nil 'standard))))
10269 (list prop)))
10270 (message "Property %s %s" property
10271 (if (org-entry-delete nil property)
10272 "deleted"
10273 "was not present in the entry")))
10275 (defun org-delete-property-globally (property)
10276 "Remove PROPERTY globally, from all entries."
10277 (interactive
10278 (let* ((completion-ignore-case t)
10279 (prop (completing-read
10280 "Globally remove property: "
10281 (mapcar 'list (org-buffer-property-keys)))))
10282 (list prop)))
10283 (save-excursion
10284 (save-restriction
10285 (widen)
10286 (goto-char (point-min))
10287 (let ((cnt 0))
10288 (while (re-search-forward
10289 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
10290 nil t)
10291 (setq cnt (1+ cnt))
10292 (replace-match ""))
10293 (message "Property \"%s\" removed from %d entries" property cnt)))))
10295 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
10297 (defun org-compute-property-at-point ()
10298 "Compute the property at point.
10299 This looks for an enclosing column format, extracts the operator and
10300 then applies it to the proerty in the column format's scope."
10301 (interactive)
10302 (unless (org-at-property-p)
10303 (error "Not at a property"))
10304 (let ((prop (org-match-string-no-properties 2)))
10305 (org-columns-get-format-and-top-level)
10306 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
10307 (error "No operator defined for property %s" prop))
10308 (org-columns-compute prop)))
10310 (defun org-property-get-allowed-values (pom property &optional table)
10311 "Get allowed values for the property PROPERTY.
10312 When TABLE is non-nil, return an alist that can directly be used for
10313 completion."
10314 (let (vals)
10315 (cond
10316 ((equal property "TODO")
10317 (setq vals (org-with-point-at pom
10318 (append org-todo-keywords-1 '("")))))
10319 ((equal property "PRIORITY")
10320 (let ((n org-lowest-priority))
10321 (while (>= n org-highest-priority)
10322 (push (char-to-string n) vals)
10323 (setq n (1- n)))))
10324 ((member property org-special-properties))
10326 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
10328 (when (and vals (string-match "\\S-" vals))
10329 (setq vals (car (read-from-string (concat "(" vals ")"))))
10330 (setq vals (mapcar (lambda (x)
10331 (cond ((stringp x) x)
10332 ((numberp x) (number-to-string x))
10333 ((symbolp x) (symbol-name x))
10334 (t "???")))
10335 vals)))))
10336 (if table (mapcar 'list vals) vals)))
10338 (defun org-property-previous-allowed-value (&optional previous)
10339 "Switch to the next allowed value for this property."
10340 (interactive)
10341 (org-property-next-allowed-value t))
10343 (defun org-property-next-allowed-value (&optional previous)
10344 "Switch to the next allowed value for this property."
10345 (interactive)
10346 (unless (org-at-property-p)
10347 (error "Not at a property"))
10348 (let* ((key (match-string 2))
10349 (value (match-string 3))
10350 (allowed (or (org-property-get-allowed-values (point) key)
10351 (and (member value '("[ ]" "[-]" "[X]"))
10352 '("[ ]" "[X]"))))
10353 nval)
10354 (unless allowed
10355 (error "Allowed values for this property have not been defined"))
10356 (if previous (setq allowed (reverse allowed)))
10357 (if (member value allowed)
10358 (setq nval (car (cdr (member value allowed)))))
10359 (setq nval (or nval (car allowed)))
10360 (if (equal nval value)
10361 (error "Only one allowed value for this property"))
10362 (org-at-property-p)
10363 (replace-match (concat " :" key ": " nval) t t)
10364 (org-indent-line-function)
10365 (beginning-of-line 1)
10366 (skip-chars-forward " \t")))
10368 (defun org-find-entry-with-id (ident)
10369 "Locate the entry that contains the ID property with exact value IDENT.
10370 IDENT can be a string, a symbol or a number, this function will search for
10371 the string representation of it.
10372 Return the position where this entry starts, or nil if there is no such entry."
10373 (let ((id (cond
10374 ((stringp ident) ident)
10375 ((symbol-name ident) (symbol-name ident))
10376 ((numberp ident) (number-to-string ident))
10377 (t (error "IDENT %s must be a string, symbol or number" ident))))
10378 (case-fold-search nil))
10379 (save-excursion
10380 (save-restriction
10381 (widen)
10382 (goto-char (point-min))
10383 (when (re-search-forward
10384 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
10385 nil t)
10386 (org-back-to-heading)
10387 (point))))))
10389 ;;;; Timestamps
10391 (defvar org-last-changed-timestamp nil)
10392 (defvar org-last-inserted-timestamp nil
10393 "The last time stamp inserted with `org-insert-time-stamp'.")
10394 (defvar org-time-was-given) ; dynamically scoped parameter
10395 (defvar org-end-time-was-given) ; dynamically scoped parameter
10396 (defvar org-ts-what) ; dynamically scoped parameter
10398 (defun org-time-stamp (arg &optional inactive)
10399 "Prompt for a date/time and insert a time stamp.
10400 If the user specifies a time like HH:MM, or if this command is called
10401 with a prefix argument, the time stamp will contain date and time.
10402 Otherwise, only the date will be included. All parts of a date not
10403 specified by the user will be filled in from the current date/time.
10404 So if you press just return without typing anything, the time stamp
10405 will represent the current date/time. If there is already a timestamp
10406 at the cursor, it will be modified."
10407 (interactive "P")
10408 (let* ((ts nil)
10409 (default-time
10410 ;; Default time is either today, or, when entering a range,
10411 ;; the range start.
10412 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
10413 (save-excursion
10414 (re-search-backward
10415 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
10416 (- (point) 20) t)))
10417 (apply 'encode-time (org-parse-time-string (match-string 1)))
10418 (current-time)))
10419 (default-input (and ts (org-get-compact-tod ts)))
10420 org-time-was-given org-end-time-was-given time)
10421 (cond
10422 ((and (org-at-timestamp-p t)
10423 (memq last-command '(org-time-stamp org-time-stamp-inactive))
10424 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
10425 (insert "--")
10426 (setq time (let ((this-command this-command))
10427 (org-read-date arg 'totime nil nil
10428 default-time default-input)))
10429 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
10430 ((org-at-timestamp-p t)
10431 (setq time (let ((this-command this-command))
10432 (org-read-date arg 'totime nil nil default-time default-input)))
10433 (when (org-at-timestamp-p t) ; just to get the match data
10434 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
10435 (replace-match "")
10436 (setq org-last-changed-timestamp
10437 (org-insert-time-stamp
10438 time (or org-time-was-given arg)
10439 inactive nil nil (list org-end-time-was-given))))
10440 (message "Timestamp updated"))
10442 (setq time (let ((this-command this-command))
10443 (org-read-date arg 'totime nil nil default-time default-input)))
10444 (org-insert-time-stamp time (or org-time-was-given arg) inactive
10445 nil nil (list org-end-time-was-given))))))
10447 ;; FIXME: can we use this for something else, like computing time differences?
10448 (defun org-get-compact-tod (s)
10449 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
10450 (let* ((t1 (match-string 1 s))
10451 (h1 (string-to-number (match-string 2 s)))
10452 (m1 (string-to-number (match-string 3 s)))
10453 (t2 (and (match-end 4) (match-string 5 s)))
10454 (h2 (and t2 (string-to-number (match-string 6 s))))
10455 (m2 (and t2 (string-to-number (match-string 7 s))))
10456 dh dm)
10457 (if (not t2)
10459 (setq dh (- h2 h1) dm (- m2 m1))
10460 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
10461 (concat t1 "+" (number-to-string dh)
10462 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
10464 (defun org-time-stamp-inactive (&optional arg)
10465 "Insert an inactive time stamp.
10466 An inactive time stamp is enclosed in square brackets instead of angle
10467 brackets. It is inactive in the sense that it does not trigger agenda entries,
10468 does not link to the calendar and cannot be changed with the S-cursor keys.
10469 So these are more for recording a certain time/date."
10470 (interactive "P")
10471 (org-time-stamp arg 'inactive))
10473 (defvar org-date-ovl (org-make-overlay 1 1))
10474 (org-overlay-put org-date-ovl 'face 'org-warning)
10475 (org-detach-overlay org-date-ovl)
10477 (defvar org-ans1) ; dynamically scoped parameter
10478 (defvar org-ans2) ; dynamically scoped parameter
10480 (defvar org-plain-time-of-day-regexp) ; defined below
10482 (defvar org-overriding-default-time nil) ; dynamically scoped
10483 (defvar org-read-date-overlay nil)
10484 (defvar org-dcst nil) ; dynamically scoped
10486 (defun org-read-date (&optional with-time to-time from-string prompt
10487 default-time default-input)
10488 "Read a date, possibly a time, and make things smooth for the user.
10489 The prompt will suggest to enter an ISO date, but you can also enter anything
10490 which will at least partially be understood by `parse-time-string'.
10491 Unrecognized parts of the date will default to the current day, month, year,
10492 hour and minute. If this command is called to replace a timestamp at point,
10493 of to enter the second timestamp of a range, the default time is taken from the
10494 existing stamp. For example,
10495 3-2-5 --> 2003-02-05
10496 feb 15 --> currentyear-02-15
10497 sep 12 9 --> 2009-09-12
10498 12:45 --> today 12:45
10499 22 sept 0:34 --> currentyear-09-22 0:34
10500 12 --> currentyear-currentmonth-12
10501 Fri --> nearest Friday (today or later)
10502 etc.
10504 Furthermore you can specify a relative date by giving, as the *first* thing
10505 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
10506 change in days weeks, months, years.
10507 With a single plus or minus, the date is relative to today. With a double
10508 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
10509 +4d --> four days from today
10510 +4 --> same as above
10511 +2w --> two weeks from today
10512 ++5 --> five days from default date
10514 The function understands only English month and weekday abbreviations,
10515 but this can be configured with the variables `parse-time-months' and
10516 `parse-time-weekdays'.
10518 While prompting, a calendar is popped up - you can also select the
10519 date with the mouse (button 1). The calendar shows a period of three
10520 months. To scroll it to other months, use the keys `>' and `<'.
10521 If you don't like the calendar, turn it off with
10522 \(setq org-read-date-popup-calendar nil)
10524 With optional argument TO-TIME, the date will immediately be converted
10525 to an internal time.
10526 With an optional argument WITH-TIME, the prompt will suggest to also
10527 insert a time. Note that when WITH-TIME is not set, you can still
10528 enter a time, and this function will inform the calling routine about
10529 this change. The calling routine may then choose to change the format
10530 used to insert the time stamp into the buffer to include the time.
10531 With optional argument FROM-STRING, read from this string instead from
10532 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
10533 the time/date that is used for everything that is not specified by the
10534 user."
10535 (require 'parse-time)
10536 (let* ((org-time-stamp-rounding-minutes
10537 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
10538 (org-dcst org-display-custom-times)
10539 (ct (org-current-time))
10540 (def (or org-overriding-default-time default-time ct))
10541 (defdecode (decode-time def))
10542 (dummy (progn
10543 (when (< (nth 2 defdecode) org-extend-today-until)
10544 (setcar (nthcdr 2 defdecode) -1)
10545 (setcar (nthcdr 1 defdecode) 59)
10546 (setq def (apply 'encode-time defdecode)
10547 defdecode (decode-time def)))))
10548 (calendar-move-hook nil)
10549 (calendar-view-diary-initially-flag nil)
10550 (view-diary-entries-initially nil)
10551 (calendar-view-holidays-initially-flag nil)
10552 (view-calendar-holidays-initially nil)
10553 (timestr (format-time-string
10554 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
10555 (prompt (concat (if prompt (concat prompt " ") "")
10556 (format "Date+time [%s]: " timestr)))
10557 ans (org-ans0 "") org-ans1 org-ans2 final)
10559 (cond
10560 (from-string (setq ans from-string))
10561 (org-read-date-popup-calendar
10562 (save-excursion
10563 (save-window-excursion
10564 (calendar)
10565 (calendar-forward-day (- (time-to-days def)
10566 (calendar-absolute-from-gregorian
10567 (calendar-current-date))))
10568 (org-eval-in-calendar nil t)
10569 (let* ((old-map (current-local-map))
10570 (map (copy-keymap calendar-mode-map))
10571 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
10572 (org-defkey map (kbd "RET") 'org-calendar-select)
10573 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
10574 'org-calendar-select-mouse)
10575 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
10576 'org-calendar-select-mouse)
10577 (org-defkey minibuffer-local-map [(meta shift left)]
10578 (lambda () (interactive)
10579 (org-eval-in-calendar '(calendar-backward-month 1))))
10580 (org-defkey minibuffer-local-map [(meta shift right)]
10581 (lambda () (interactive)
10582 (org-eval-in-calendar '(calendar-forward-month 1))))
10583 (org-defkey minibuffer-local-map [(meta shift up)]
10584 (lambda () (interactive)
10585 (org-eval-in-calendar '(calendar-backward-year 1))))
10586 (org-defkey minibuffer-local-map [(meta shift down)]
10587 (lambda () (interactive)
10588 (org-eval-in-calendar '(calendar-forward-year 1))))
10589 (org-defkey minibuffer-local-map [(shift up)]
10590 (lambda () (interactive)
10591 (org-eval-in-calendar '(calendar-backward-week 1))))
10592 (org-defkey minibuffer-local-map [(shift down)]
10593 (lambda () (interactive)
10594 (org-eval-in-calendar '(calendar-forward-week 1))))
10595 (org-defkey minibuffer-local-map [(shift left)]
10596 (lambda () (interactive)
10597 (org-eval-in-calendar '(calendar-backward-day 1))))
10598 (org-defkey minibuffer-local-map [(shift right)]
10599 (lambda () (interactive)
10600 (org-eval-in-calendar '(calendar-forward-day 1))))
10601 (org-defkey minibuffer-local-map ">"
10602 (lambda () (interactive)
10603 (org-eval-in-calendar '(scroll-calendar-left 1))))
10604 (org-defkey minibuffer-local-map "<"
10605 (lambda () (interactive)
10606 (org-eval-in-calendar '(scroll-calendar-right 1))))
10607 (unwind-protect
10608 (progn
10609 (use-local-map map)
10610 (add-hook 'post-command-hook 'org-read-date-display)
10611 (setq org-ans0 (read-string prompt default-input nil nil))
10612 ;; org-ans0: from prompt
10613 ;; org-ans1: from mouse click
10614 ;; org-ans2: from calendar motion
10615 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
10616 (remove-hook 'post-command-hook 'org-read-date-display)
10617 (use-local-map old-map)
10618 (when org-read-date-overlay
10619 (org-delete-overlay org-read-date-overlay)
10620 (setq org-read-date-overlay nil)))))))
10622 (t ; Naked prompt only
10623 (unwind-protect
10624 (setq ans (read-string prompt default-input nil timestr))
10625 (when org-read-date-overlay
10626 (org-delete-overlay org-read-date-overlay)
10627 (setq org-read-date-overlay nil)))))
10629 (setq final (org-read-date-analyze ans def defdecode))
10631 (if to-time
10632 (apply 'encode-time final)
10633 (if (and (boundp 'org-time-was-given) org-time-was-given)
10634 (format "%04d-%02d-%02d %02d:%02d"
10635 (nth 5 final) (nth 4 final) (nth 3 final)
10636 (nth 2 final) (nth 1 final))
10637 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
10638 (defvar def)
10639 (defvar defdecode)
10640 (defvar with-time)
10641 (defun org-read-date-display ()
10642 "Display the currrent date prompt interpretation in the minibuffer."
10643 (when org-read-date-display-live
10644 (when org-read-date-overlay
10645 (org-delete-overlay org-read-date-overlay))
10646 (let ((p (point)))
10647 (end-of-line 1)
10648 (while (not (equal (buffer-substring
10649 (max (point-min) (- (point) 4)) (point))
10650 " "))
10651 (insert " "))
10652 (goto-char p))
10653 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
10654 " " (or org-ans1 org-ans2)))
10655 (org-end-time-was-given nil)
10656 (f (org-read-date-analyze ans def defdecode))
10657 (fmts (if org-dcst
10658 org-time-stamp-custom-formats
10659 org-time-stamp-formats))
10660 (fmt (if (or with-time
10661 (and (boundp 'org-time-was-given) org-time-was-given))
10662 (cdr fmts)
10663 (car fmts)))
10664 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
10665 (when (and org-end-time-was-given
10666 (string-match org-plain-time-of-day-regexp txt))
10667 (setq txt (concat (substring txt 0 (match-end 0)) "-"
10668 org-end-time-was-given
10669 (substring txt (match-end 0)))))
10670 (setq org-read-date-overlay
10671 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
10672 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
10674 (defun org-read-date-analyze (ans def defdecode)
10675 "Analyze the combined answer of the date prompt."
10676 ;; FIXME: cleanup and comment
10677 (let (delta deltan deltaw deltadef year month day
10678 hour minute second wday pm h2 m2 tl wday1
10679 iso-year iso-weekday iso-week iso-year iso-date)
10681 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
10682 (setq ans "+0"))
10684 (when (setq delta (org-read-date-get-relative ans (current-time) def))
10685 (setq ans (replace-match "" t t ans)
10686 deltan (car delta)
10687 deltaw (nth 1 delta)
10688 deltadef (nth 2 delta)))
10690 ;; Check if there is an iso week date in there
10691 ;; If yes, sore the info and ostpone interpreting it until the rest
10692 ;; of the parsing is done
10693 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
10694 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
10695 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
10696 iso-week (string-to-number (match-string 2 ans)))
10697 (setq ans (replace-match "" t t ans)))
10699 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
10700 (when (string-match
10701 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
10702 (setq year (if (match-end 2)
10703 (string-to-number (match-string 2 ans))
10704 (string-to-number (format-time-string "%Y")))
10705 month (string-to-number (match-string 3 ans))
10706 day (string-to-number (match-string 4 ans)))
10707 (if (< year 100) (setq year (+ 2000 year)))
10708 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
10709 t nil ans)))
10710 ;; Help matching am/pm times, because `parse-time-string' does not do that.
10711 ;; If there is a time with am/pm, and *no* time without it, we convert
10712 ;; so that matching will be successful.
10713 (loop for i from 1 to 2 do ; twice, for end time as well
10714 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
10715 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
10716 (setq hour (string-to-number (match-string 1 ans))
10717 minute (if (match-end 3)
10718 (string-to-number (match-string 3 ans))
10720 pm (equal ?p
10721 (string-to-char (downcase (match-string 4 ans)))))
10722 (if (and (= hour 12) (not pm))
10723 (setq hour 0)
10724 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
10725 (setq ans (replace-match (format "%02d:%02d" hour minute)
10726 t t ans))))
10728 ;; Check if a time range is given as a duration
10729 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
10730 (setq hour (string-to-number (match-string 1 ans))
10731 h2 (+ hour (string-to-number (match-string 3 ans)))
10732 minute (string-to-number (match-string 2 ans))
10733 m2 (+ minute (if (match-end 5) (string-to-number
10734 (match-string 5 ans))0)))
10735 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
10736 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
10737 t t ans)))
10739 ;; Check if there is a time range
10740 (when (boundp 'org-end-time-was-given)
10741 (setq org-time-was-given nil)
10742 (when (and (string-match org-plain-time-of-day-regexp ans)
10743 (match-end 8))
10744 (setq org-end-time-was-given (match-string 8 ans))
10745 (setq ans (concat (substring ans 0 (match-beginning 7))
10746 (substring ans (match-end 7))))))
10748 (setq tl (parse-time-string ans)
10749 day (or (nth 3 tl) (nth 3 defdecode))
10750 month (or (nth 4 tl)
10751 (if (and org-read-date-prefer-future
10752 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
10753 (1+ (nth 4 defdecode))
10754 (nth 4 defdecode)))
10755 year (or (nth 5 tl)
10756 (if (and org-read-date-prefer-future
10757 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
10758 (1+ (nth 5 defdecode))
10759 (nth 5 defdecode)))
10760 hour (or (nth 2 tl) (nth 2 defdecode))
10761 minute (or (nth 1 tl) (nth 1 defdecode))
10762 second (or (nth 0 tl) 0)
10763 wday (nth 6 tl))
10765 ;; Special date definitions below
10766 (cond
10767 (iso-week
10768 ;; There was an iso week
10769 (setq year (or iso-year year)
10770 day (or iso-weekday wday 1)
10771 wday nil ; to make sure that the trigger below does not match
10772 iso-date (calendar-gregorian-from-absolute
10773 (calendar-absolute-from-iso
10774 (list iso-week day year))))
10775 ; FIXME: Should we also push ISO weeks into the future?
10776 ; (when (and org-read-date-prefer-future
10777 ; (not iso-year)
10778 ; (< (calendar-absolute-from-gregorian iso-date)
10779 ; (time-to-days (current-time))))
10780 ; (setq year (1+ year)
10781 ; iso-date (calendar-gregorian-from-absolute
10782 ; (calendar-absolute-from-iso
10783 ; (list iso-week day year)))))
10784 (setq month (car iso-date)
10785 year (nth 2 iso-date)
10786 day (nth 1 iso-date)))
10787 (deltan
10788 (unless deltadef
10789 (let ((now (decode-time (current-time))))
10790 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
10791 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
10792 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
10793 ((equal deltaw "m") (setq month (+ month deltan)))
10794 ((equal deltaw "y") (setq year (+ year deltan)))))
10795 ((and wday (not (nth 3 tl)))
10796 ;; Weekday was given, but no day, so pick that day in the week
10797 ;; on or after the derived date.
10798 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
10799 (unless (equal wday wday1)
10800 (setq day (+ day (% (- wday wday1 -7) 7))))))
10801 (if (and (boundp 'org-time-was-given)
10802 (nth 2 tl))
10803 (setq org-time-was-given t))
10804 (if (< year 100) (setq year (+ 2000 year)))
10805 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
10806 (list second minute hour day month year)))
10808 (defvar parse-time-weekdays)
10810 (defun org-read-date-get-relative (s today default)
10811 "Check string S for special relative date string.
10812 TODAY and DEFAULT are internal times, for today and for a default.
10813 Return shift list (N what def-flag)
10814 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
10815 N is the number of WHATs to shift.
10816 DEF-FLAG is t when a double ++ or -- indicates shift relative to
10817 the DEFAULT date rather than TODAY."
10818 (when (and
10819 (string-match
10820 (concat
10821 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
10822 "\\([0-9]+\\)?"
10823 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
10824 "\\([ \t]\\|$\\)") s)
10825 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
10826 (let* ((dir (if (> (match-end 1) (match-beginning 1))
10827 (string-to-char (substring (match-string 1 s) -1))
10828 ?+))
10829 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
10830 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
10831 (what (if (match-end 3) (match-string 3 s) "d"))
10832 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
10833 (date (if rel default today))
10834 (wday (nth 6 (decode-time date)))
10835 delta)
10836 (if wday1
10837 (progn
10838 (setq delta (mod (+ 7 (- wday1 wday)) 7))
10839 (if (= dir ?-) (setq delta (- delta 7)))
10840 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
10841 (list delta "d" rel))
10842 (list (* n (if (= dir ?-) -1 1)) what rel)))))
10844 (defun org-eval-in-calendar (form &optional keepdate)
10845 "Eval FORM in the calendar window and return to current window.
10846 Also, store the cursor date in variable org-ans2."
10847 (let ((sw (selected-window)))
10848 (select-window (get-buffer-window "*Calendar*"))
10849 (eval form)
10850 (when (and (not keepdate) (calendar-cursor-to-date))
10851 (let* ((date (calendar-cursor-to-date))
10852 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10853 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
10854 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
10855 (select-window sw)))
10857 (defun org-calendar-select ()
10858 "Return to `org-read-date' with the date currently selected.
10859 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
10860 (interactive)
10861 (when (calendar-cursor-to-date)
10862 (let* ((date (calendar-cursor-to-date))
10863 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10864 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
10865 (if (active-minibuffer-window) (exit-minibuffer))))
10867 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
10868 "Insert a date stamp for the date given by the internal TIME.
10869 WITH-HM means, use the stamp format that includes the time of the day.
10870 INACTIVE means use square brackets instead of angular ones, so that the
10871 stamp will not contribute to the agenda.
10872 PRE and POST are optional strings to be inserted before and after the
10873 stamp.
10874 The command returns the inserted time stamp."
10875 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
10876 stamp)
10877 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
10878 (insert-before-markers (or pre ""))
10879 (insert-before-markers (setq stamp (format-time-string fmt time)))
10880 (when (listp extra)
10881 (setq extra (car extra))
10882 (if (and (stringp extra)
10883 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
10884 (setq extra (format "-%02d:%02d"
10885 (string-to-number (match-string 1 extra))
10886 (string-to-number (match-string 2 extra))))
10887 (setq extra nil)))
10888 (when extra
10889 (backward-char 1)
10890 (insert-before-markers extra)
10891 (forward-char 1))
10892 (insert-before-markers (or post ""))
10893 (setq org-last-inserted-timestamp stamp)))
10895 (defun org-toggle-time-stamp-overlays ()
10896 "Toggle the use of custom time stamp formats."
10897 (interactive)
10898 (setq org-display-custom-times (not org-display-custom-times))
10899 (unless org-display-custom-times
10900 (let ((p (point-min)) (bmp (buffer-modified-p)))
10901 (while (setq p (next-single-property-change p 'display))
10902 (if (and (get-text-property p 'display)
10903 (eq (get-text-property p 'face) 'org-date))
10904 (remove-text-properties
10905 p (setq p (next-single-property-change p 'display))
10906 '(display t))))
10907 (set-buffer-modified-p bmp)))
10908 (if (featurep 'xemacs)
10909 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
10910 (org-restart-font-lock)
10911 (setq org-table-may-need-update t)
10912 (if org-display-custom-times
10913 (message "Time stamps are overlayed with custom format")
10914 (message "Time stamp overlays removed")))
10916 (defun org-display-custom-time (beg end)
10917 "Overlay modified time stamp format over timestamp between BEG and END."
10918 (let* ((ts (buffer-substring beg end))
10919 t1 w1 with-hm tf time str w2 (off 0))
10920 (save-match-data
10921 (setq t1 (org-parse-time-string ts t))
10922 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
10923 (setq off (- (match-end 0) (match-beginning 0)))))
10924 (setq end (- end off))
10925 (setq w1 (- end beg)
10926 with-hm (and (nth 1 t1) (nth 2 t1))
10927 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
10928 time (org-fix-decoded-time t1)
10929 str (org-add-props
10930 (format-time-string
10931 (substring tf 1 -1) (apply 'encode-time time))
10932 nil 'mouse-face 'highlight)
10933 w2 (length str))
10934 (if (not (= w2 w1))
10935 (add-text-properties (1+ beg) (+ 2 beg)
10936 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
10937 (if (featurep 'xemacs)
10938 (progn
10939 (put-text-property beg end 'invisible t)
10940 (put-text-property beg end 'end-glyph (make-glyph str)))
10941 (put-text-property beg end 'display str))))
10943 (defun org-translate-time (string)
10944 "Translate all timestamps in STRING to custom format.
10945 But do this only if the variable `org-display-custom-times' is set."
10946 (when org-display-custom-times
10947 (save-match-data
10948 (let* ((start 0)
10949 (re org-ts-regexp-both)
10950 t1 with-hm inactive tf time str beg end)
10951 (while (setq start (string-match re string start))
10952 (setq beg (match-beginning 0)
10953 end (match-end 0)
10954 t1 (save-match-data
10955 (org-parse-time-string (substring string beg end) t))
10956 with-hm (and (nth 1 t1) (nth 2 t1))
10957 inactive (equal (substring string beg (1+ beg)) "[")
10958 tf (funcall (if with-hm 'cdr 'car)
10959 org-time-stamp-custom-formats)
10960 time (org-fix-decoded-time t1)
10961 str (format-time-string
10962 (concat
10963 (if inactive "[" "<") (substring tf 1 -1)
10964 (if inactive "]" ">"))
10965 (apply 'encode-time time))
10966 string (replace-match str t t string)
10967 start (+ start (length str)))))))
10968 string)
10970 (defun org-fix-decoded-time (time)
10971 "Set 0 instead of nil for the first 6 elements of time.
10972 Don't touch the rest."
10973 (let ((n 0))
10974 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
10976 (defun org-days-to-time (timestamp-string)
10977 "Difference between TIMESTAMP-STRING and now in days."
10978 (- (time-to-days (org-time-string-to-time timestamp-string))
10979 (time-to-days (current-time))))
10981 (defun org-deadline-close (timestamp-string &optional ndays)
10982 "Is the time in TIMESTAMP-STRING close to the current date?"
10983 (setq ndays (or ndays (org-get-wdays timestamp-string)))
10984 (and (< (org-days-to-time timestamp-string) ndays)
10985 (not (org-entry-is-done-p))))
10987 (defun org-get-wdays (ts)
10988 "Get the deadline lead time appropriate for timestring TS."
10989 (cond
10990 ((<= org-deadline-warning-days 0)
10991 ;; 0 or negative, enforce this value no matter what
10992 (- org-deadline-warning-days))
10993 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
10994 ;; lead time is specified.
10995 (floor (* (string-to-number (match-string 1 ts))
10996 (cdr (assoc (match-string 2 ts)
10997 '(("d" . 1) ("w" . 7)
10998 ("m" . 30.4) ("y" . 365.25)))))))
10999 ;; go for the default.
11000 (t org-deadline-warning-days)))
11002 (defun org-calendar-select-mouse (ev)
11003 "Return to `org-read-date' with the date currently selected.
11004 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11005 (interactive "e")
11006 (mouse-set-point ev)
11007 (when (calendar-cursor-to-date)
11008 (let* ((date (calendar-cursor-to-date))
11009 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11010 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11011 (if (active-minibuffer-window) (exit-minibuffer))))
11013 (defun org-check-deadlines (ndays)
11014 "Check if there are any deadlines due or past due.
11015 A deadline is considered due if it happens within `org-deadline-warning-days'
11016 days from today's date. If the deadline appears in an entry marked DONE,
11017 it is not shown. The prefix arg NDAYS can be used to test that many
11018 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
11019 (interactive "P")
11020 (let* ((org-warn-days
11021 (cond
11022 ((equal ndays '(4)) 100000)
11023 (ndays (prefix-numeric-value ndays))
11024 (t (abs org-deadline-warning-days))))
11025 (case-fold-search nil)
11026 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
11027 (callback
11028 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
11030 (message "%d deadlines past-due or due within %d days"
11031 (org-occur regexp nil callback)
11032 org-warn-days)))
11034 (defun org-check-before-date (date)
11035 "Check if there are deadlines or scheduled entries before DATE."
11036 (interactive (list (org-read-date)))
11037 (let ((case-fold-search nil)
11038 (regexp (concat "\\<\\(" org-deadline-string
11039 "\\|" org-scheduled-string
11040 "\\) *<\\([^>]+\\)>"))
11041 (callback
11042 (lambda () (time-less-p
11043 (org-time-string-to-time (match-string 2))
11044 (org-time-string-to-time date)))))
11045 (message "%d entries before %s"
11046 (org-occur regexp nil callback) date)))
11048 (defun org-evaluate-time-range (&optional to-buffer)
11049 "Evaluate a time range by computing the difference between start and end.
11050 Normally the result is just printed in the echo area, but with prefix arg
11051 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
11052 If the time range is actually in a table, the result is inserted into the
11053 next column.
11054 For time difference computation, a year is assumed to be exactly 365
11055 days in order to avoid rounding problems."
11056 (interactive "P")
11058 (org-clock-update-time-maybe)
11059 (save-excursion
11060 (unless (org-at-date-range-p t)
11061 (goto-char (point-at-bol))
11062 (re-search-forward org-tr-regexp-both (point-at-eol) t))
11063 (if (not (org-at-date-range-p t))
11064 (error "Not at a time-stamp range, and none found in current line")))
11065 (let* ((ts1 (match-string 1))
11066 (ts2 (match-string 2))
11067 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
11068 (match-end (match-end 0))
11069 (time1 (org-time-string-to-time ts1))
11070 (time2 (org-time-string-to-time ts2))
11071 (t1 (time-to-seconds time1))
11072 (t2 (time-to-seconds time2))
11073 (diff (abs (- t2 t1)))
11074 (negative (< (- t2 t1) 0))
11075 ;; (ys (floor (* 365 24 60 60)))
11076 (ds (* 24 60 60))
11077 (hs (* 60 60))
11078 (fy "%dy %dd %02d:%02d")
11079 (fy1 "%dy %dd")
11080 (fd "%dd %02d:%02d")
11081 (fd1 "%dd")
11082 (fh "%02d:%02d")
11083 y d h m align)
11084 (if havetime
11085 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11087 d (floor (/ diff ds)) diff (mod diff ds)
11088 h (floor (/ diff hs)) diff (mod diff hs)
11089 m (floor (/ diff 60)))
11090 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11092 d (floor (+ (/ diff ds) 0.5))
11093 h 0 m 0))
11094 (if (not to-buffer)
11095 (message "%s" (org-make-tdiff-string y d h m))
11096 (if (org-at-table-p)
11097 (progn
11098 (goto-char match-end)
11099 (setq align t)
11100 (and (looking-at " *|") (goto-char (match-end 0))))
11101 (goto-char match-end))
11102 (if (looking-at
11103 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
11104 (replace-match ""))
11105 (if negative (insert " -"))
11106 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
11107 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
11108 (insert " " (format fh h m))))
11109 (if align (org-table-align))
11110 (message "Time difference inserted")))))
11112 (defun org-make-tdiff-string (y d h m)
11113 (let ((fmt "")
11114 (l nil))
11115 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
11116 l (push y l)))
11117 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
11118 l (push d l)))
11119 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
11120 l (push h l)))
11121 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
11122 l (push m l)))
11123 (apply 'format fmt (nreverse l))))
11125 (defun org-time-string-to-time (s)
11126 (apply 'encode-time (org-parse-time-string s)))
11128 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
11129 "Convert a time stamp to an absolute day number.
11130 If there is a specifyer for a cyclic time stamp, get the closest date to
11131 DAYNR.
11132 PREFER and SHOW_ALL are passed through to `org-closest-date'."
11133 (cond
11134 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
11135 (if (org-diary-sexp-entry (match-string 1 s) "" date)
11136 daynr
11137 (+ daynr 1000)))
11138 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
11139 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
11140 (time-to-days (current-time))) (match-string 0 s)
11141 prefer show-all))
11142 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
11144 (defun org-days-to-iso-week (days)
11145 "Return the iso week number."
11146 (require 'cal-iso)
11147 (car (calendar-iso-from-absolute days)))
11149 (defun org-small-year-to-year (year)
11150 "Convert 2-digit years into 4-digit years.
11151 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
11152 The year 2000 cannot be abbreviated. Any year lager than 99
11153 is retrned unchanged."
11154 (if (< year 38)
11155 (setq year (+ 2000 year))
11156 (if (< year 100)
11157 (setq year (+ 1900 year))))
11158 year)
11160 (defun org-time-from-absolute (d)
11161 "Return the time corresponding to date D.
11162 D may be an absolute day number, or a calendar-type list (month day year)."
11163 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
11164 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
11166 (defun org-calendar-holiday ()
11167 "List of holidays, for Diary display in Org-mode."
11168 (require 'holidays)
11169 (let ((hl (funcall
11170 (if (fboundp 'calendar-check-holidays)
11171 'calendar-check-holidays 'check-calendar-holidays) date)))
11172 (if hl (mapconcat 'identity hl "; "))))
11174 (defun org-diary-sexp-entry (sexp entry date)
11175 "Process a SEXP diary ENTRY for DATE."
11176 (require 'diary-lib)
11177 (let ((result (if calendar-debug-sexp
11178 (let ((stack-trace-on-error t))
11179 (eval (car (read-from-string sexp))))
11180 (condition-case nil
11181 (eval (car (read-from-string sexp)))
11182 (error
11183 (beep)
11184 (message "Bad sexp at line %d in %s: %s"
11185 (org-current-line)
11186 (buffer-file-name) sexp)
11187 (sleep-for 2))))))
11188 (cond ((stringp result) result)
11189 ((and (consp result)
11190 (stringp (cdr result))) (cdr result))
11191 (result entry)
11192 (t nil))))
11194 (defun org-diary-to-ical-string (frombuf)
11195 "Get iCalendar entries from diary entries in buffer FROMBUF.
11196 This uses the icalendar.el library."
11197 (let* ((tmpdir (if (featurep 'xemacs)
11198 (temp-directory)
11199 temporary-file-directory))
11200 (tmpfile (make-temp-name
11201 (expand-file-name "orgics" tmpdir)))
11202 buf rtn b e)
11203 (save-excursion
11204 (set-buffer frombuf)
11205 (icalendar-export-region (point-min) (point-max) tmpfile)
11206 (setq buf (find-buffer-visiting tmpfile))
11207 (set-buffer buf)
11208 (goto-char (point-min))
11209 (if (re-search-forward "^BEGIN:VEVENT" nil t)
11210 (setq b (match-beginning 0)))
11211 (goto-char (point-max))
11212 (if (re-search-backward "^END:VEVENT" nil t)
11213 (setq e (match-end 0)))
11214 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
11215 (kill-buffer buf)
11216 (delete-file tmpfile)
11217 rtn))
11219 (defun org-closest-date (start current change prefer show-all)
11220 "Find the date closest to CURRENT that is consistent with START and CHANGE.
11221 When PREFER is `past' return a date that is either CURRENT or past.
11222 When PREFER is `future', return a date that is either CURRENT or future.
11223 When SHOW-ALL is nil, only return the current occurence of a time stamp."
11224 ;; Make the proper lists from the dates
11225 (catch 'exit
11226 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
11227 dn dw sday cday n1 n2
11228 d m y y1 y2 date1 date2 nmonths nm ny m2)
11230 (setq start (org-date-to-gregorian start)
11231 current (org-date-to-gregorian
11232 (if show-all
11233 current
11234 (time-to-days (current-time))))
11235 sday (calendar-absolute-from-gregorian start)
11236 cday (calendar-absolute-from-gregorian current))
11238 (if (<= cday sday) (throw 'exit sday))
11240 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
11241 (setq dn (string-to-number (match-string 1 change))
11242 dw (cdr (assoc (match-string 2 change) a1)))
11243 (error "Invalid change specifyer: %s" change))
11244 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
11245 (cond
11246 ((eq dw 'day)
11247 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
11248 n2 (+ n1 dn)))
11249 ((eq dw 'year)
11250 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
11251 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
11252 (setq date1 (list m d y1)
11253 n1 (calendar-absolute-from-gregorian date1)
11254 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
11255 n2 (calendar-absolute-from-gregorian date2)))
11256 ((eq dw 'month)
11257 ;; approx number of month between the two dates
11258 (setq nmonths (floor (/ (- cday sday) 30.436875)))
11259 ;; How often does dn fit in there?
11260 (setq d (nth 1 start) m (car start) y (nth 2 start)
11261 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
11262 m (+ m nm)
11263 ny (floor (/ m 12))
11264 y (+ y ny)
11265 m (- m (* ny 12)))
11266 (while (> m 12) (setq m (- m 12) y (1+ y)))
11267 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
11268 (setq m2 (+ m dn) y2 y)
11269 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11270 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
11271 (while (<= n2 cday)
11272 (setq n1 n2 m m2 y y2)
11273 (setq m2 (+ m dn) y2 y)
11274 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11275 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
11276 (if show-all
11277 (cond
11278 ((eq prefer 'past) n1)
11279 ((eq prefer 'future) (if (= cday n1) n1 n2))
11280 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
11281 (cond
11282 ((eq prefer 'past) n1)
11283 ((eq prefer 'future) (if (= cday n1) n1 n2))
11284 (t (if (= cday n1) n1 n2)))))))
11286 (defun org-date-to-gregorian (date)
11287 "Turn any specification of DATE into a gregorian date for the calendar."
11288 (cond ((integerp date) (calendar-gregorian-from-absolute date))
11289 ((and (listp date) (= (length date) 3)) date)
11290 ((stringp date)
11291 (setq date (org-parse-time-string date))
11292 (list (nth 4 date) (nth 3 date) (nth 5 date)))
11293 ((listp date)
11294 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
11296 (defun org-parse-time-string (s &optional nodefault)
11297 "Parse the standard Org-mode time string.
11298 This should be a lot faster than the normal `parse-time-string'.
11299 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
11300 hour and minute fields will be nil if not given."
11301 (if (string-match org-ts-regexp0 s)
11302 (list 0
11303 (if (or (match-beginning 8) (not nodefault))
11304 (string-to-number (or (match-string 8 s) "0")))
11305 (if (or (match-beginning 7) (not nodefault))
11306 (string-to-number (or (match-string 7 s) "0")))
11307 (string-to-number (match-string 4 s))
11308 (string-to-number (match-string 3 s))
11309 (string-to-number (match-string 2 s))
11310 nil nil nil)
11311 (make-list 9 0)))
11313 (defun org-timestamp-up (&optional arg)
11314 "Increase the date item at the cursor by one.
11315 If the cursor is on the year, change the year. If it is on the month or
11316 the day, change that.
11317 With prefix ARG, change by that many units."
11318 (interactive "p")
11319 (org-timestamp-change (prefix-numeric-value arg)))
11321 (defun org-timestamp-down (&optional arg)
11322 "Decrease the date item at the cursor by one.
11323 If the cursor is on the year, change the year. If it is on the month or
11324 the day, change that.
11325 With prefix ARG, change by that many units."
11326 (interactive "p")
11327 (org-timestamp-change (- (prefix-numeric-value arg))))
11329 (defun org-timestamp-up-day (&optional arg)
11330 "Increase the date in the time stamp by one day.
11331 With prefix ARG, change that many days."
11332 (interactive "p")
11333 (if (and (not (org-at-timestamp-p t))
11334 (org-on-heading-p))
11335 (org-todo 'up)
11336 (org-timestamp-change (prefix-numeric-value arg) 'day)))
11338 (defun org-timestamp-down-day (&optional arg)
11339 "Decrease the date in the time stamp by one day.
11340 With prefix ARG, change that many days."
11341 (interactive "p")
11342 (if (and (not (org-at-timestamp-p t))
11343 (org-on-heading-p))
11344 (org-todo 'down)
11345 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
11347 (defun org-at-timestamp-p (&optional inactive-ok)
11348 "Determine if the cursor is in or at a timestamp."
11349 (interactive)
11350 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
11351 (pos (point))
11352 (ans (or (looking-at tsr)
11353 (save-excursion
11354 (skip-chars-backward "^[<\n\r\t")
11355 (if (> (point) (point-min)) (backward-char 1))
11356 (and (looking-at tsr)
11357 (> (- (match-end 0) pos) -1))))))
11358 (and ans
11359 (boundp 'org-ts-what)
11360 (setq org-ts-what
11361 (cond
11362 ((= pos (match-beginning 0)) 'bracket)
11363 ((= pos (1- (match-end 0))) 'bracket)
11364 ((org-pos-in-match-range pos 2) 'year)
11365 ((org-pos-in-match-range pos 3) 'month)
11366 ((org-pos-in-match-range pos 7) 'hour)
11367 ((org-pos-in-match-range pos 8) 'minute)
11368 ((or (org-pos-in-match-range pos 4)
11369 (org-pos-in-match-range pos 5)) 'day)
11370 ((and (> pos (or (match-end 8) (match-end 5)))
11371 (< pos (match-end 0)))
11372 (- pos (or (match-end 8) (match-end 5))))
11373 (t 'day))))
11374 ans))
11376 (defun org-toggle-timestamp-type ()
11377 "Toggle the type (<active> or [inactive]) of a time stamp."
11378 (interactive)
11379 (when (org-at-timestamp-p t)
11380 (let ((beg (match-beginning 0)) (end (match-end 0))
11381 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
11382 (save-excursion
11383 (goto-char beg)
11384 (while (re-search-forward "[][<>]" end t)
11385 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
11386 t t)))
11387 (message "Timestamp is now %sactive"
11388 (if (equal (char-after beg) ?<) "" "in")))))
11390 (defun org-timestamp-change (n &optional what)
11391 "Change the date in the time stamp at point.
11392 The date will be changed by N times WHAT. WHAT can be `day', `month',
11393 `year', `minute', `second'. If WHAT is not given, the cursor position
11394 in the timestamp determines what will be changed."
11395 (let ((pos (point))
11396 with-hm inactive
11397 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
11398 org-ts-what
11399 extra rem
11400 ts time time0)
11401 (if (not (org-at-timestamp-p t))
11402 (error "Not at a timestamp"))
11403 (if (and (not what) (eq org-ts-what 'bracket))
11404 (org-toggle-timestamp-type)
11405 (if (and (not what) (not (eq org-ts-what 'day))
11406 org-display-custom-times
11407 (get-text-property (point) 'display)
11408 (not (get-text-property (1- (point)) 'display)))
11409 (setq org-ts-what 'day))
11410 (setq org-ts-what (or what org-ts-what)
11411 inactive (= (char-after (match-beginning 0)) ?\[)
11412 ts (match-string 0))
11413 (replace-match "")
11414 (if (string-match
11415 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
11417 (setq extra (match-string 1 ts)))
11418 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
11419 (setq with-hm t))
11420 (setq time0 (org-parse-time-string ts))
11421 (when (and (eq org-ts-what 'minute)
11422 (eq current-prefix-arg nil))
11423 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
11424 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
11425 (setcar (cdr time0) (+ (nth 1 time0)
11426 (if (> n 0) (- rem) (- dm rem))))))
11427 (setq time
11428 (encode-time (or (car time0) 0)
11429 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
11430 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
11431 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
11432 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
11433 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
11434 (nthcdr 6 time0)))
11435 (when (integerp org-ts-what)
11436 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
11437 (if (eq what 'calendar)
11438 (let ((cal-date (org-get-date-from-calendar)))
11439 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
11440 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
11441 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
11442 (setcar time0 (or (car time0) 0))
11443 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
11444 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
11445 (setq time (apply 'encode-time time0))))
11446 (setq org-last-changed-timestamp
11447 (org-insert-time-stamp time with-hm inactive nil nil extra))
11448 (org-clock-update-time-maybe)
11449 (goto-char pos)
11450 ;; Try to recenter the calendar window, if any
11451 (if (and org-calendar-follow-timestamp-change
11452 (get-buffer-window "*Calendar*" t)
11453 (memq org-ts-what '(day month year)))
11454 (org-recenter-calendar (time-to-days time))))))
11456 (defun org-modify-ts-extra (s pos n dm)
11457 "Change the different parts of the lead-time and repeat fields in timestamp."
11458 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
11459 ng h m new rem)
11460 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
11461 (cond
11462 ((or (org-pos-in-match-range pos 2)
11463 (org-pos-in-match-range pos 3))
11464 (setq m (string-to-number (match-string 3 s))
11465 h (string-to-number (match-string 2 s)))
11466 (if (org-pos-in-match-range pos 2)
11467 (setq h (+ h n))
11468 (setq n (* dm (org-no-warnings (signum n))))
11469 (when (not (= 0 (setq rem (% m dm))))
11470 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
11471 (setq m (+ m n)))
11472 (if (< m 0) (setq m (+ m 60) h (1- h)))
11473 (if (> m 59) (setq m (- m 60) h (1+ h)))
11474 (setq h (min 24 (max 0 h)))
11475 (setq ng 1 new (format "-%02d:%02d" h m)))
11476 ((org-pos-in-match-range pos 6)
11477 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
11478 ((org-pos-in-match-range pos 5)
11479 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
11481 ((org-pos-in-match-range pos 9)
11482 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
11483 ((org-pos-in-match-range pos 8)
11484 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
11486 (when ng
11487 (setq s (concat
11488 (substring s 0 (match-beginning ng))
11490 (substring s (match-end ng))))))
11493 (defun org-recenter-calendar (date)
11494 "If the calendar is visible, recenter it to DATE."
11495 (let* ((win (selected-window))
11496 (cwin (get-buffer-window "*Calendar*" t))
11497 (calendar-move-hook nil))
11498 (when cwin
11499 (select-window cwin)
11500 (calendar-goto-date (if (listp date) date
11501 (calendar-gregorian-from-absolute date)))
11502 (select-window win))))
11504 (defun org-goto-calendar (&optional arg)
11505 "Go to the Emacs calendar at the current date.
11506 If there is a time stamp in the current line, go to that date.
11507 A prefix ARG can be used to force the current date."
11508 (interactive "P")
11509 (let ((tsr org-ts-regexp) diff
11510 (calendar-move-hook nil)
11511 (calendar-view-holidays-initially-flag nil)
11512 (view-calendar-holidays-initially nil)
11513 (calendar-view-diary-initially-flag nil)
11514 (view-diary-entries-initially nil))
11515 (if (or (org-at-timestamp-p)
11516 (save-excursion
11517 (beginning-of-line 1)
11518 (looking-at (concat ".*" tsr))))
11519 (let ((d1 (time-to-days (current-time)))
11520 (d2 (time-to-days
11521 (org-time-string-to-time (match-string 1)))))
11522 (setq diff (- d2 d1))))
11523 (calendar)
11524 (calendar-goto-today)
11525 (if (and diff (not arg)) (calendar-forward-day diff))))
11527 (defun org-get-date-from-calendar ()
11528 "Return a list (month day year) of date at point in calendar."
11529 (with-current-buffer "*Calendar*"
11530 (save-match-data
11531 (calendar-cursor-to-date))))
11533 (defun org-date-from-calendar ()
11534 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
11535 If there is already a time stamp at the cursor position, update it."
11536 (interactive)
11537 (if (org-at-timestamp-p t)
11538 (org-timestamp-change 0 'calendar)
11539 (let ((cal-date (org-get-date-from-calendar)))
11540 (org-insert-time-stamp
11541 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
11543 (defun org-minutes-to-hh:mm-string (m)
11544 "Compute H:MM from a number of minutes."
11545 (let ((h (/ m 60)))
11546 (setq m (- m (* 60 h)))
11547 (format org-time-clocksum-format h m)))
11549 (defun org-hh:mm-string-to-minutes (s)
11550 "Convert a string H:MM to a number of minutes."
11551 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
11552 (+ (* (string-to-number (match-string 1 s)) 60)
11553 (string-to-number (match-string 2 s)))
11556 ;;;; Agenda files
11558 ;;;###autoload
11559 (defun org-iswitchb (&optional arg)
11560 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
11561 With a prefix argument, restrict available to files.
11562 With two prefix arguments, restrict available buffers to agenda files.
11564 Due to some yet unresolved reason, the global function
11565 `iswitchb-mode' needs to be active for this function to work."
11566 (interactive "P")
11567 (require 'iswitchb)
11568 (let ((enabled iswitchb-mode) blist)
11569 (or enabled (iswitchb-mode 1))
11570 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
11571 ((equal arg '(16)) (org-buffer-list 'agenda))
11572 (t (org-buffer-list))))
11573 (unwind-protect
11574 (let ((iswitchb-make-buflist-hook
11575 (lambda ()
11576 (setq iswitchb-temp-buflist
11577 (mapcar 'buffer-name blist)))))
11578 (switch-to-buffer
11579 (iswitchb-read-buffer
11580 "Switch-to: " nil t))
11581 (or enabled (iswitchb-mode -1))))))
11583 (defun org-buffer-list (&optional predicate exclude-tmp)
11584 "Return a list of Org buffers.
11585 PREDICATE can be `export', `files' or `agenda'.
11587 export restrict the list to Export buffers.
11588 files restrict the list to buffers visiting Org files.
11589 agenda restrict the list to buffers visiting agenda files.
11591 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
11592 (let* ((bfn nil)
11593 (agenda-files (and (eq predicate 'agenda)
11594 (mapcar 'file-truename (org-agenda-files t))))
11595 (filter
11596 (cond
11597 ((eq predicate 'files)
11598 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
11599 ((eq predicate 'export)
11600 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
11601 ((eq predicate 'agenda)
11602 (lambda (b)
11603 (with-current-buffer b
11604 (and (eq major-mode 'org-mode)
11605 (setq bfn (buffer-file-name b))
11606 (member (file-truename bfn) agenda-files)))))
11607 (t (lambda (b) (with-current-buffer b
11608 (or (eq major-mode 'org-mode)
11609 (string-match "\*Org .*Export"
11610 (buffer-name b)))))))))
11611 (delq nil
11612 (mapcar
11613 (lambda(b)
11614 (if (and (funcall filter b)
11615 (or (not exclude-tmp)
11616 (not (string-match "tmp" (buffer-name b)))))
11618 nil))
11619 (buffer-list)))))
11621 (defun org-agenda-files (&optional unrestricted archives)
11622 "Get the list of agenda files.
11623 Optional UNRESTRICTED means return the full list even if a restriction
11624 is currently in place.
11625 When ARCHIVES is t, include all archive files hat are really being
11626 used by the agenda files. If ARCHIVE is `ifmode', do this only if
11627 `org-agenda-archives-mode' is t."
11628 (let ((files
11629 (cond
11630 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
11631 ((stringp org-agenda-files) (org-read-agenda-file-list))
11632 ((listp org-agenda-files) org-agenda-files)
11633 (t (error "Invalid value of `org-agenda-files'")))))
11634 (setq files (apply 'append
11635 (mapcar (lambda (f)
11636 (if (file-directory-p f)
11637 (directory-files
11638 f t org-agenda-file-regexp)
11639 (list f)))
11640 files)))
11641 (when org-agenda-skip-unavailable-files
11642 (setq files (delq nil
11643 (mapcar (function
11644 (lambda (file)
11645 (and (file-readable-p file) file)))
11646 files))))
11647 (when (or (eq archives t)
11648 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
11649 (setq files (org-add-archive-files files)))
11650 files))
11652 (defun org-edit-agenda-file-list ()
11653 "Edit the list of agenda files.
11654 Depending on setup, this either uses customize to edit the variable
11655 `org-agenda-files', or it visits the file that is holding the list. In the
11656 latter case, the buffer is set up in a way that saving it automatically kills
11657 the buffer and restores the previous window configuration."
11658 (interactive)
11659 (if (stringp org-agenda-files)
11660 (let ((cw (current-window-configuration)))
11661 (find-file org-agenda-files)
11662 (org-set-local 'org-window-configuration cw)
11663 (org-add-hook 'after-save-hook
11664 (lambda ()
11665 (set-window-configuration
11666 (prog1 org-window-configuration
11667 (kill-buffer (current-buffer))))
11668 (org-install-agenda-files-menu)
11669 (message "New agenda file list installed"))
11670 nil 'local)
11671 (message "%s" (substitute-command-keys
11672 "Edit list and finish with \\[save-buffer]")))
11673 (customize-variable 'org-agenda-files)))
11675 (defun org-store-new-agenda-file-list (list)
11676 "Set new value for the agenda file list and save it correcly."
11677 (if (stringp org-agenda-files)
11678 (let ((f org-agenda-files) b)
11679 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
11680 (with-temp-file f
11681 (insert (mapconcat 'identity list "\n") "\n")))
11682 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
11683 (setq org-agenda-files list)
11684 (customize-save-variable 'org-agenda-files org-agenda-files))))
11686 (defun org-read-agenda-file-list ()
11687 "Read the list of agenda files from a file."
11688 (when (file-directory-p org-agenda-files)
11689 (error "`org-agenda-files' cannot be a single directory"))
11690 (when (stringp org-agenda-files)
11691 (with-temp-buffer
11692 (insert-file-contents org-agenda-files)
11693 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
11696 ;;;###autoload
11697 (defun org-cycle-agenda-files ()
11698 "Cycle through the files in `org-agenda-files'.
11699 If the current buffer visits an agenda file, find the next one in the list.
11700 If the current buffer does not, find the first agenda file."
11701 (interactive)
11702 (let* ((fs (org-agenda-files t))
11703 (files (append fs (list (car fs))))
11704 (tcf (if buffer-file-name (file-truename buffer-file-name)))
11705 file)
11706 (unless files (error "No agenda files"))
11707 (catch 'exit
11708 (while (setq file (pop files))
11709 (if (equal (file-truename file) tcf)
11710 (when (car files)
11711 (find-file (car files))
11712 (throw 'exit t))))
11713 (find-file (car fs)))
11714 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
11716 (defun org-agenda-file-to-front (&optional to-end)
11717 "Move/add the current file to the top of the agenda file list.
11718 If the file is not present in the list, it is added to the front. If it is
11719 present, it is moved there. With optional argument TO-END, add/move to the
11720 end of the list."
11721 (interactive "P")
11722 (let ((org-agenda-skip-unavailable-files nil)
11723 (file-alist (mapcar (lambda (x)
11724 (cons (file-truename x) x))
11725 (org-agenda-files t)))
11726 (ctf (file-truename buffer-file-name))
11727 x had)
11728 (setq x (assoc ctf file-alist) had x)
11730 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
11731 (if to-end
11732 (setq file-alist (append (delq x file-alist) (list x)))
11733 (setq file-alist (cons x (delq x file-alist))))
11734 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
11735 (org-install-agenda-files-menu)
11736 (message "File %s to %s of agenda file list"
11737 (if had "moved" "added") (if to-end "end" "front"))))
11739 (defun org-remove-file (&optional file)
11740 "Remove current file from the list of files in variable `org-agenda-files'.
11741 These are the files which are being checked for agenda entries.
11742 Optional argument FILE means, use this file instead of the current."
11743 (interactive)
11744 (let* ((org-agenda-skip-unavailable-files nil)
11745 (file (or file buffer-file-name))
11746 (true-file (file-truename file))
11747 (afile (abbreviate-file-name file))
11748 (files (delq nil (mapcar
11749 (lambda (x)
11750 (if (equal true-file
11751 (file-truename x))
11752 nil x))
11753 (org-agenda-files t)))))
11754 (if (not (= (length files) (length (org-agenda-files t))))
11755 (progn
11756 (org-store-new-agenda-file-list files)
11757 (org-install-agenda-files-menu)
11758 (message "Removed file: %s" afile))
11759 (message "File was not in list: %s (not removed)" afile))))
11761 (defun org-file-menu-entry (file)
11762 (vector file (list 'find-file file) t))
11764 (defun org-check-agenda-file (file)
11765 "Make sure FILE exists. If not, ask user what to do."
11766 (when (not (file-exists-p file))
11767 (message "non-existent file %s. [R]emove from list or [A]bort?"
11768 (abbreviate-file-name file))
11769 (let ((r (downcase (read-char-exclusive))))
11770 (cond
11771 ((equal r ?r)
11772 (org-remove-file file)
11773 (throw 'nextfile t))
11774 (t (error "Abort"))))))
11776 (defun org-get-agenda-file-buffer (file)
11777 "Get a buffer visiting FILE. If the buffer needs to be created, add
11778 it to the list of buffers which might be released later."
11779 (let ((buf (org-find-base-buffer-visiting file)))
11780 (if buf
11781 buf ; just return it
11782 ;; Make a new buffer and remember it
11783 (setq buf (find-file-noselect file))
11784 (if buf (push buf org-agenda-new-buffers))
11785 buf)))
11787 (defun org-release-buffers (blist)
11788 "Release all buffers in list, asking the user for confirmation when needed.
11789 When a buffer is unmodified, it is just killed. When modified, it is saved
11790 \(if the user agrees) and then killed."
11791 (let (buf file)
11792 (while (setq buf (pop blist))
11793 (setq file (buffer-file-name buf))
11794 (when (and (buffer-modified-p buf)
11795 file
11796 (y-or-n-p (format "Save file %s? " file)))
11797 (with-current-buffer buf (save-buffer)))
11798 (kill-buffer buf))))
11800 (defun org-prepare-agenda-buffers (files)
11801 "Create buffers for all agenda files, protect archived trees and comments."
11802 (interactive)
11803 (let ((pa '(:org-archived t))
11804 (pc '(:org-comment t))
11805 (pall '(:org-archived t :org-comment t))
11806 (inhibit-read-only t)
11807 (rea (concat ":" org-archive-tag ":"))
11808 bmp file re)
11809 (save-excursion
11810 (save-restriction
11811 (while (setq file (pop files))
11812 (if (bufferp file)
11813 (set-buffer file)
11814 (org-check-agenda-file file)
11815 (set-buffer (org-get-agenda-file-buffer file)))
11816 (widen)
11817 (setq bmp (buffer-modified-p))
11818 (org-refresh-category-properties)
11819 (setq org-todo-keywords-for-agenda
11820 (append org-todo-keywords-for-agenda org-todo-keywords-1))
11821 (setq org-done-keywords-for-agenda
11822 (append org-done-keywords-for-agenda org-done-keywords))
11823 (setq org-todo-keyword-alist-for-agenda
11824 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
11825 (setq org-tag-alist-for-agenda
11826 (append org-tag-alist-for-agenda org-tag-alist))
11828 (save-excursion
11829 (remove-text-properties (point-min) (point-max) pall)
11830 (when org-agenda-skip-archived-trees
11831 (goto-char (point-min))
11832 (while (re-search-forward rea nil t)
11833 (if (org-on-heading-p t)
11834 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
11835 (goto-char (point-min))
11836 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
11837 (while (re-search-forward re nil t)
11838 (add-text-properties
11839 (match-beginning 0) (org-end-of-subtree t) pc)))
11840 (set-buffer-modified-p bmp))))
11841 (setq org-todo-keyword-alist-for-agenda
11842 (org-uniquify org-todo-keyword-alist-for-agenda)
11843 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
11845 ;;;; Embedded LaTeX
11847 (defvar org-cdlatex-mode-map (make-sparse-keymap)
11848 "Keymap for the minor `org-cdlatex-mode'.")
11850 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
11851 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
11852 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
11853 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
11854 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
11856 (defvar org-cdlatex-texmathp-advice-is-done nil
11857 "Flag remembering if we have applied the advice to texmathp already.")
11859 (define-minor-mode org-cdlatex-mode
11860 "Toggle the minor `org-cdlatex-mode'.
11861 This mode supports entering LaTeX environment and math in LaTeX fragments
11862 in Org-mode.
11863 \\{org-cdlatex-mode-map}"
11864 nil " OCDL" nil
11865 (when org-cdlatex-mode (require 'cdlatex))
11866 (unless org-cdlatex-texmathp-advice-is-done
11867 (setq org-cdlatex-texmathp-advice-is-done t)
11868 (defadvice texmathp (around org-math-always-on activate)
11869 "Always return t in org-mode buffers.
11870 This is because we want to insert math symbols without dollars even outside
11871 the LaTeX math segments. If Orgmode thinks that point is actually inside
11872 en embedded LaTeX fragement, let texmathp do its job.
11873 \\[org-cdlatex-mode-map]"
11874 (interactive)
11875 (let (p)
11876 (cond
11877 ((not (org-mode-p)) ad-do-it)
11878 ((eq this-command 'cdlatex-math-symbol)
11879 (setq ad-return-value t
11880 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
11882 (let ((p (org-inside-LaTeX-fragment-p)))
11883 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
11884 (setq ad-return-value t
11885 texmathp-why '("Org-mode embedded math" . 0))
11886 (if p ad-do-it)))))))))
11888 (defun turn-on-org-cdlatex ()
11889 "Unconditionally turn on `org-cdlatex-mode'."
11890 (org-cdlatex-mode 1))
11892 (defun org-inside-LaTeX-fragment-p ()
11893 "Test if point is inside a LaTeX fragment.
11894 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
11895 sequence appearing also before point.
11896 Even though the matchers for math are configurable, this function assumes
11897 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
11898 delimiters are skipped when they have been removed by customization.
11899 The return value is nil, or a cons cell with the delimiter and
11900 and the position of this delimiter.
11902 This function does a reasonably good job, but can locally be fooled by
11903 for example currency specifications. For example it will assume being in
11904 inline math after \"$22.34\". The LaTeX fragment formatter will only format
11905 fragments that are properly closed, but during editing, we have to live
11906 with the uncertainty caused by missing closing delimiters. This function
11907 looks only before point, not after."
11908 (catch 'exit
11909 (let ((pos (point))
11910 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
11911 (lim (progn
11912 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
11913 (point)))
11914 dd-on str (start 0) m re)
11915 (goto-char pos)
11916 (when dodollar
11917 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
11918 re (nth 1 (assoc "$" org-latex-regexps)))
11919 (while (string-match re str start)
11920 (cond
11921 ((= (match-end 0) (length str))
11922 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
11923 ((= (match-end 0) (- (length str) 5))
11924 (throw 'exit nil))
11925 (t (setq start (match-end 0))))))
11926 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
11927 (goto-char pos)
11928 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
11929 (and (match-beginning 2) (throw 'exit nil))
11930 ;; count $$
11931 (while (re-search-backward "\\$\\$" lim t)
11932 (setq dd-on (not dd-on)))
11933 (goto-char pos)
11934 (if dd-on (cons "$$" m))))))
11937 (defun org-try-cdlatex-tab ()
11938 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
11939 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
11940 - inside a LaTeX fragment, or
11941 - after the first word in a line, where an abbreviation expansion could
11942 insert a LaTeX environment."
11943 (when org-cdlatex-mode
11944 (cond
11945 ((save-excursion
11946 (skip-chars-backward "a-zA-Z0-9*")
11947 (skip-chars-backward " \t")
11948 (bolp))
11949 (cdlatex-tab) t)
11950 ((org-inside-LaTeX-fragment-p)
11951 (cdlatex-tab) t)
11952 (t nil))))
11954 (defun org-cdlatex-underscore-caret (&optional arg)
11955 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
11956 Revert to the normal definition outside of these fragments."
11957 (interactive "P")
11958 (if (org-inside-LaTeX-fragment-p)
11959 (call-interactively 'cdlatex-sub-superscript)
11960 (let (org-cdlatex-mode)
11961 (call-interactively (key-binding (vector last-input-event))))))
11963 (defun org-cdlatex-math-modify (&optional arg)
11964 "Execute `cdlatex-math-modify' in LaTeX fragments.
11965 Revert to the normal definition outside of these fragments."
11966 (interactive "P")
11967 (if (org-inside-LaTeX-fragment-p)
11968 (call-interactively 'cdlatex-math-modify)
11969 (let (org-cdlatex-mode)
11970 (call-interactively (key-binding (vector last-input-event))))))
11972 (defvar org-latex-fragment-image-overlays nil
11973 "List of overlays carrying the images of latex fragments.")
11974 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
11976 (defun org-remove-latex-fragment-image-overlays ()
11977 "Remove all overlays with LaTeX fragment images in current buffer."
11978 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
11979 (setq org-latex-fragment-image-overlays nil))
11981 (defun org-preview-latex-fragment (&optional subtree)
11982 "Preview the LaTeX fragment at point, or all locally or globally.
11983 If the cursor is in a LaTeX fragment, create the image and overlay
11984 it over the source code. If there is no fragment at point, display
11985 all fragments in the current text, from one headline to the next. With
11986 prefix SUBTREE, display all fragments in the current subtree. With a
11987 double prefix `C-u C-u', or when the cursor is before the first headline,
11988 display all fragments in the buffer.
11989 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
11990 (interactive "P")
11991 (org-remove-latex-fragment-image-overlays)
11992 (save-excursion
11993 (save-restriction
11994 (let (beg end at msg)
11995 (cond
11996 ((or (equal subtree '(16))
11997 (not (save-excursion
11998 (re-search-backward (concat "^" outline-regexp) nil t))))
11999 (setq beg (point-min) end (point-max)
12000 msg "Creating images for buffer...%s"))
12001 ((equal subtree '(4))
12002 (org-back-to-heading)
12003 (setq beg (point) end (org-end-of-subtree t)
12004 msg "Creating images for subtree...%s"))
12006 (if (setq at (org-inside-LaTeX-fragment-p))
12007 (goto-char (max (point-min) (- (cdr at) 2)))
12008 (org-back-to-heading))
12009 (setq beg (point) end (progn (outline-next-heading) (point))
12010 msg (if at "Creating image...%s"
12011 "Creating images for entry...%s"))))
12012 (message msg "")
12013 (narrow-to-region beg end)
12014 (goto-char beg)
12015 (org-format-latex
12016 (concat "ltxpng/" (file-name-sans-extension
12017 (file-name-nondirectory
12018 buffer-file-name)))
12019 default-directory 'overlays msg at 'forbuffer)
12020 (message msg "done. Use `C-c C-c' to remove images.")))))
12022 (defvar org-latex-regexps
12023 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
12024 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
12025 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
12026 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
12027 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
12028 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
12029 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
12030 "Regular expressions for matching embedded LaTeX.")
12032 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
12033 "Replace LaTeX fragments with links to an image, and produce images."
12034 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
12035 (let* ((prefixnodir (file-name-nondirectory prefix))
12036 (absprefix (expand-file-name prefix dir))
12037 (todir (file-name-directory absprefix))
12038 (opt org-format-latex-options)
12039 (matchers (plist-get opt :matchers))
12040 (re-list org-latex-regexps)
12041 (cnt 0) txt link beg end re e checkdir
12042 m n block linkfile movefile ov)
12043 ;; Check if there are old images files with this prefix, and remove them
12044 (when (file-directory-p todir)
12045 (mapc 'delete-file
12046 (directory-files
12047 todir 'full
12048 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
12049 ;; Check the different regular expressions
12050 (while (setq e (pop re-list))
12051 (setq m (car e) re (nth 1 e) n (nth 2 e)
12052 block (if (nth 3 e) "\n\n" ""))
12053 (when (member m matchers)
12054 (goto-char (point-min))
12055 (while (re-search-forward re nil t)
12056 (when (or (not at) (equal (cdr at) (match-beginning n)))
12057 (setq txt (match-string n)
12058 beg (match-beginning n) end (match-end n)
12059 cnt (1+ cnt)
12060 linkfile (format "%s_%04d.png" prefix cnt)
12061 movefile (format "%s_%04d.png" absprefix cnt)
12062 link (concat block "[[file:" linkfile "]]" block))
12063 (if msg (message msg cnt))
12064 (goto-char beg)
12065 (unless checkdir ; make sure the directory exists
12066 (setq checkdir t)
12067 (or (file-directory-p todir) (make-directory todir)))
12068 (org-create-formula-image
12069 txt movefile opt forbuffer)
12070 (if overlays
12071 (progn
12072 (setq ov (org-make-overlay beg end))
12073 (if (featurep 'xemacs)
12074 (progn
12075 (org-overlay-put ov 'invisible t)
12076 (org-overlay-put
12077 ov 'end-glyph
12078 (make-glyph (vector 'png :file movefile))))
12079 (org-overlay-put
12080 ov 'display
12081 (list 'image :type 'png :file movefile :ascent 'center)))
12082 (push ov org-latex-fragment-image-overlays)
12083 (goto-char end))
12084 (delete-region beg end)
12085 (insert link))))))))
12087 ;; This function borrows from Ganesh Swami's latex2png.el
12088 (defun org-create-formula-image (string tofile options buffer)
12089 (let* ((tmpdir (if (featurep 'xemacs)
12090 (temp-directory)
12091 temporary-file-directory))
12092 (texfilebase (make-temp-name
12093 (expand-file-name "orgtex" tmpdir)))
12094 (texfile (concat texfilebase ".tex"))
12095 (dvifile (concat texfilebase ".dvi"))
12096 (pngfile (concat texfilebase ".png"))
12097 (fnh (if (featurep 'xemacs)
12098 (font-height (get-face-font 'default))
12099 (face-attribute 'default :height nil)))
12100 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
12101 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
12102 (fg (or (plist-get options (if buffer :foreground :html-foreground))
12103 "Black"))
12104 (bg (or (plist-get options (if buffer :background :html-background))
12105 "Transparent")))
12106 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
12107 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
12108 (with-temp-file texfile
12109 (insert org-format-latex-header
12110 "\n\\begin{document}\n" string "\n\\end{document}\n"))
12111 (let ((dir default-directory))
12112 (condition-case nil
12113 (progn
12114 (cd tmpdir)
12115 (call-process "latex" nil nil nil texfile))
12116 (error nil))
12117 (cd dir))
12118 (if (not (file-exists-p dvifile))
12119 (progn (message "Failed to create dvi file from %s" texfile) nil)
12120 (condition-case nil
12121 (call-process "dvipng" nil nil nil
12122 "-E" "-fg" fg "-bg" bg
12123 "-D" dpi
12124 ;;"-x" scale "-y" scale
12125 "-T" "tight"
12126 "-o" pngfile
12127 dvifile)
12128 (error nil))
12129 (if (not (file-exists-p pngfile))
12130 (progn (message "Failed to create png file from %s" texfile) nil)
12131 ;; Use the requested file name and clean up
12132 (copy-file pngfile tofile 'replace)
12133 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
12134 (delete-file (concat texfilebase e)))
12135 pngfile))))
12137 (defun org-dvipng-color (attr)
12138 "Return an rgb color specification for dvipng."
12139 (apply 'format "rgb %s %s %s"
12140 (mapcar 'org-normalize-color
12141 (color-values (face-attribute 'default attr nil)))))
12143 (defun org-normalize-color (value)
12144 "Return string to be used as color value for an RGB component."
12145 (format "%g" (/ value 65535.0)))
12148 ;;;; Key bindings
12150 ;; Make `C-c C-x' a prefix key
12151 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
12153 ;; TAB key with modifiers
12154 (org-defkey org-mode-map "\C-i" 'org-cycle)
12155 (org-defkey org-mode-map [(tab)] 'org-cycle)
12156 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
12157 (org-defkey org-mode-map [(meta tab)] 'org-complete)
12158 (org-defkey org-mode-map "\M-\t" 'org-complete)
12159 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
12160 ;; The following line is necessary under Suse GNU/Linux
12161 (unless (featurep 'xemacs)
12162 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
12163 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
12164 (define-key org-mode-map [backtab] 'org-shifttab)
12166 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
12167 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
12168 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
12170 ;; Cursor keys with modifiers
12171 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
12172 (org-defkey org-mode-map [(meta right)] 'org-metaright)
12173 (org-defkey org-mode-map [(meta up)] 'org-metaup)
12174 (org-defkey org-mode-map [(meta down)] 'org-metadown)
12176 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
12177 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
12178 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
12179 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
12181 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
12182 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
12183 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
12184 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
12186 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
12187 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
12189 ;;; Extra keys for tty access.
12190 ;; We only set them when really needed because otherwise the
12191 ;; menus don't show the simple keys
12193 (when (or org-use-extra-keys
12194 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
12195 (not window-system))
12196 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
12197 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
12198 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
12199 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
12200 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
12201 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
12202 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
12203 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
12204 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
12205 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
12206 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
12207 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
12208 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
12209 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
12210 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
12211 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
12212 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
12213 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
12214 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
12215 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
12216 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
12217 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
12219 ;; All the other keys
12221 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
12222 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
12223 (if (boundp 'narrow-map)
12224 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
12225 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
12226 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
12227 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
12228 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
12229 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
12230 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
12231 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
12232 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
12233 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
12234 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
12235 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
12236 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
12237 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
12238 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
12239 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
12240 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
12241 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
12242 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
12243 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
12244 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
12245 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
12246 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
12247 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
12248 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
12249 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
12250 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
12251 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
12252 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
12253 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
12254 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
12255 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
12256 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
12257 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
12258 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
12259 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
12260 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
12261 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
12262 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
12263 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
12264 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
12265 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
12266 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
12267 (org-defkey org-mode-map "\C-c^" 'org-sort)
12268 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
12269 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
12270 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
12271 (org-defkey org-mode-map "\C-m" 'org-return)
12272 (org-defkey org-mode-map "\C-j" 'org-return-indent)
12273 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
12274 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
12275 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
12276 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
12277 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
12278 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
12279 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
12280 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
12281 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
12282 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
12283 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
12284 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
12285 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
12286 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
12287 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
12289 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
12290 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
12291 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
12292 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
12294 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
12295 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
12296 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
12297 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
12298 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
12299 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
12300 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
12301 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
12302 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
12303 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
12304 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
12305 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
12307 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
12309 (when (featurep 'xemacs)
12310 (org-defkey org-mode-map 'button3 'popup-mode-menu))
12312 (defvar org-table-auto-blank-field) ; defined in org-table.el
12313 (defun org-self-insert-command (N)
12314 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
12315 If the cursor is in a table looking at whitespace, the whitespace is
12316 overwritten, and the table is not marked as requiring realignment."
12317 (interactive "p")
12318 (if (and (org-table-p)
12319 (progn
12320 ;; check if we blank the field, and if that triggers align
12321 (and (featurep 'org-table) org-table-auto-blank-field
12322 (member last-command
12323 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
12324 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
12325 ;; got extra space, this field does not determine column width
12326 (let (org-table-may-need-update) (org-table-blank-field))
12327 ;; no extra space, this field may determine column width
12328 (org-table-blank-field)))
12330 (eq N 1)
12331 (looking-at "[^|\n]* |"))
12332 (let (org-table-may-need-update)
12333 (goto-char (1- (match-end 0)))
12334 (delete-backward-char 1)
12335 (goto-char (match-beginning 0))
12336 (self-insert-command N))
12337 (setq org-table-may-need-update t)
12338 (self-insert-command N)
12339 (org-fix-tags-on-the-fly)))
12341 (defun org-fix-tags-on-the-fly ()
12342 (when (and (equal (char-after (point-at-bol)) ?*)
12343 (org-on-heading-p))
12344 (org-align-tags-here org-tags-column)))
12346 (defun org-delete-backward-char (N)
12347 "Like `delete-backward-char', insert whitespace at field end in tables.
12348 When deleting backwards, in tables this function will insert whitespace in
12349 front of the next \"|\" separator, to keep the table aligned. The table will
12350 still be marked for re-alignment if the field did fill the entire column,
12351 because, in this case the deletion might narrow the column."
12352 (interactive "p")
12353 (if (and (org-table-p)
12354 (eq N 1)
12355 (string-match "|" (buffer-substring (point-at-bol) (point)))
12356 (looking-at ".*?|"))
12357 (let ((pos (point))
12358 (noalign (looking-at "[^|\n\r]* |"))
12359 (c org-table-may-need-update))
12360 (backward-delete-char N)
12361 (skip-chars-forward "^|")
12362 (insert " ")
12363 (goto-char (1- pos))
12364 ;; noalign: if there were two spaces at the end, this field
12365 ;; does not determine the width of the column.
12366 (if noalign (setq org-table-may-need-update c)))
12367 (backward-delete-char N)
12368 (org-fix-tags-on-the-fly)))
12370 (defun org-delete-char (N)
12371 "Like `delete-char', but insert whitespace at field end in tables.
12372 When deleting characters, in tables this function will insert whitespace in
12373 front of the next \"|\" separator, to keep the table aligned. The table will
12374 still be marked for re-alignment if the field did fill the entire column,
12375 because, in this case the deletion might narrow the column."
12376 (interactive "p")
12377 (if (and (org-table-p)
12378 (not (bolp))
12379 (not (= (char-after) ?|))
12380 (eq N 1))
12381 (if (looking-at ".*?|")
12382 (let ((pos (point))
12383 (noalign (looking-at "[^|\n\r]* |"))
12384 (c org-table-may-need-update))
12385 (replace-match (concat
12386 (substring (match-string 0) 1 -1)
12387 " |"))
12388 (goto-char pos)
12389 ;; noalign: if there were two spaces at the end, this field
12390 ;; does not determine the width of the column.
12391 (if noalign (setq org-table-may-need-update c)))
12392 (delete-char N))
12393 (delete-char N)
12394 (org-fix-tags-on-the-fly)))
12396 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
12397 (put 'org-self-insert-command 'delete-selection t)
12398 (put 'orgtbl-self-insert-command 'delete-selection t)
12399 (put 'org-delete-char 'delete-selection 'supersede)
12400 (put 'org-delete-backward-char 'delete-selection 'supersede)
12402 ;; Make `flyspell-mode' delay after some commands
12403 (put 'org-self-insert-command 'flyspell-delayed t)
12404 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
12405 (put 'org-delete-char 'flyspell-delayed t)
12406 (put 'org-delete-backward-char 'flyspell-delayed t)
12408 ;; Make pabbrev-mode expand after org-mode commands
12409 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
12410 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
12412 ;; How to do this: Measure non-white length of current string
12413 ;; If equal to column width, we should realign.
12415 (defun org-remap (map &rest commands)
12416 "In MAP, remap the functions given in COMMANDS.
12417 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
12418 (let (new old)
12419 (while commands
12420 (setq old (pop commands) new (pop commands))
12421 (if (fboundp 'command-remapping)
12422 (org-defkey map (vector 'remap old) new)
12423 (substitute-key-definition old new map global-map)))))
12425 (when (eq org-enable-table-editor 'optimized)
12426 ;; If the user wants maximum table support, we need to hijack
12427 ;; some standard editing functions
12428 (org-remap org-mode-map
12429 'self-insert-command 'org-self-insert-command
12430 'delete-char 'org-delete-char
12431 'delete-backward-char 'org-delete-backward-char)
12432 (org-defkey org-mode-map "|" 'org-force-self-insert))
12434 (defun org-shiftcursor-error ()
12435 "Throw an error because Shift-Cursor command was applied in wrong context."
12436 (error "This command is active in special context like tables, headlines or timestamps"))
12438 (defun org-shifttab (&optional arg)
12439 "Global visibility cycling or move to previous table field.
12440 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
12441 on context.
12442 See the individual commands for more information."
12443 (interactive "P")
12444 (cond
12445 ((org-at-table-p) (call-interactively 'org-table-previous-field))
12446 ((integerp arg)
12447 (message "Content view to level: %d" arg)
12448 (org-content (prefix-numeric-value arg))
12449 (setq org-cycle-global-status 'overview))
12450 (t (call-interactively 'org-global-cycle))))
12452 (defun org-shiftmetaleft ()
12453 "Promote subtree or delete table column.
12454 Calls `org-promote-subtree', `org-outdent-item',
12455 or `org-table-delete-column', depending on context.
12456 See the individual commands for more information."
12457 (interactive)
12458 (cond
12459 ((org-at-table-p) (call-interactively 'org-table-delete-column))
12460 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
12461 ((org-at-item-p) (call-interactively 'org-outdent-item))
12462 (t (org-shiftcursor-error))))
12464 (defun org-shiftmetaright ()
12465 "Demote subtree or insert table column.
12466 Calls `org-demote-subtree', `org-indent-item',
12467 or `org-table-insert-column', depending on context.
12468 See the individual commands for more information."
12469 (interactive)
12470 (cond
12471 ((org-at-table-p) (call-interactively 'org-table-insert-column))
12472 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
12473 ((org-at-item-p) (call-interactively 'org-indent-item))
12474 (t (org-shiftcursor-error))))
12476 (defun org-shiftmetaup (&optional arg)
12477 "Move subtree up or kill table row.
12478 Calls `org-move-subtree-up' or `org-table-kill-row' or
12479 `org-move-item-up' depending on context. See the individual commands
12480 for more information."
12481 (interactive "P")
12482 (cond
12483 ((org-at-table-p) (call-interactively 'org-table-kill-row))
12484 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12485 ((org-at-item-p) (call-interactively 'org-move-item-up))
12486 (t (org-shiftcursor-error))))
12487 (defun org-shiftmetadown (&optional arg)
12488 "Move subtree down or insert table row.
12489 Calls `org-move-subtree-down' or `org-table-insert-row' or
12490 `org-move-item-down', depending on context. See the individual
12491 commands for more information."
12492 (interactive "P")
12493 (cond
12494 ((org-at-table-p) (call-interactively 'org-table-insert-row))
12495 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12496 ((org-at-item-p) (call-interactively 'org-move-item-down))
12497 (t (org-shiftcursor-error))))
12499 (defun org-metaleft (&optional arg)
12500 "Promote heading or move table column to left.
12501 Calls `org-do-promote' or `org-table-move-column', depending on context.
12502 With no specific context, calls the Emacs default `backward-word'.
12503 See the individual commands for more information."
12504 (interactive "P")
12505 (cond
12506 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
12507 ((or (org-on-heading-p) (org-region-active-p))
12508 (call-interactively 'org-do-promote))
12509 ((org-at-item-p) (call-interactively 'org-outdent-item))
12510 (t (call-interactively 'backward-word))))
12512 (defun org-metaright (&optional arg)
12513 "Demote subtree or move table column to right.
12514 Calls `org-do-demote' or `org-table-move-column', depending on context.
12515 With no specific context, calls the Emacs default `forward-word'.
12516 See the individual commands for more information."
12517 (interactive "P")
12518 (cond
12519 ((org-at-table-p) (call-interactively 'org-table-move-column))
12520 ((or (org-on-heading-p) (org-region-active-p))
12521 (call-interactively 'org-do-demote))
12522 ((org-at-item-p) (call-interactively 'org-indent-item))
12523 (t (call-interactively 'forward-word))))
12525 (defun org-metaup (&optional arg)
12526 "Move subtree up or move table row up.
12527 Calls `org-move-subtree-up' or `org-table-move-row' or
12528 `org-move-item-up', depending on context. See the individual commands
12529 for more information."
12530 (interactive "P")
12531 (cond
12532 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
12533 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12534 ((org-at-item-p) (call-interactively 'org-move-item-up))
12535 (t (transpose-lines 1) (beginning-of-line -1))))
12537 (defun org-metadown (&optional arg)
12538 "Move subtree down or move table row down.
12539 Calls `org-move-subtree-down' or `org-table-move-row' or
12540 `org-move-item-down', depending on context. See the individual
12541 commands for more information."
12542 (interactive "P")
12543 (cond
12544 ((org-at-table-p) (call-interactively 'org-table-move-row))
12545 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12546 ((org-at-item-p) (call-interactively 'org-move-item-down))
12547 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
12549 (defun org-shiftup (&optional arg)
12550 "Increase item in timestamp or increase priority of current headline.
12551 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
12552 depending on context. See the individual commands for more information."
12553 (interactive "P")
12554 (cond
12555 ((org-at-timestamp-p t)
12556 (call-interactively (if org-edit-timestamp-down-means-later
12557 'org-timestamp-down 'org-timestamp-up)))
12558 ((org-on-heading-p) (call-interactively 'org-priority-up))
12559 ((org-at-item-p) (call-interactively 'org-previous-item))
12560 ((org-clocktable-try-shift 'up arg))
12561 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
12563 (defun org-shiftdown (&optional arg)
12564 "Decrease item in timestamp or decrease priority of current headline.
12565 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
12566 depending on context. See the individual commands for more information."
12567 (interactive "P")
12568 (cond
12569 ((org-at-timestamp-p t)
12570 (call-interactively (if org-edit-timestamp-down-means-later
12571 'org-timestamp-up 'org-timestamp-down)))
12572 ((org-on-heading-p) (call-interactively 'org-priority-down))
12573 ((org-clocktable-try-shift 'down arg))
12574 (t (call-interactively 'org-next-item))))
12576 (defun org-shiftright (&optional arg)
12577 "Next TODO keyword or timestamp one day later, depending on context."
12578 (interactive "P")
12579 (cond
12580 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
12581 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
12582 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
12583 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
12584 ((org-clocktable-try-shift 'right arg))
12585 (t (org-shiftcursor-error))))
12587 (defun org-shiftleft (&optional arg)
12588 "Previous TODO keyword or timestamp one day earlier, depending on context."
12589 (interactive "P")
12590 (cond
12591 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
12592 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
12593 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
12594 ((org-at-property-p)
12595 (call-interactively 'org-property-previous-allowed-value))
12596 ((org-clocktable-try-shift 'left arg))
12597 (t (org-shiftcursor-error))))
12599 (defun org-shiftcontrolright ()
12600 "Switch to next TODO set."
12601 (interactive)
12602 (cond
12603 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
12604 (t (org-shiftcursor-error))))
12606 (defun org-shiftcontrolleft ()
12607 "Switch to previous TODO set."
12608 (interactive)
12609 (cond
12610 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
12611 (t (org-shiftcursor-error))))
12613 (defun org-ctrl-c-ret ()
12614 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
12615 (interactive)
12616 (cond
12617 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
12618 (t (call-interactively 'org-insert-heading))))
12620 (defun org-copy-special ()
12621 "Copy region in table or copy current subtree.
12622 Calls `org-table-copy' or `org-copy-subtree', depending on context.
12623 See the individual commands for more information."
12624 (interactive)
12625 (call-interactively
12626 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
12628 (defun org-cut-special ()
12629 "Cut region in table or cut current subtree.
12630 Calls `org-table-copy' or `org-cut-subtree', depending on context.
12631 See the individual commands for more information."
12632 (interactive)
12633 (call-interactively
12634 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
12636 (defun org-paste-special (arg)
12637 "Paste rectangular region into table, or past subtree relative to level.
12638 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
12639 See the individual commands for more information."
12640 (interactive "P")
12641 (if (org-at-table-p)
12642 (org-table-paste-rectangle)
12643 (org-paste-subtree arg)))
12645 (defun org-edit-special ()
12646 "Call a special editor for the stuff at point.
12647 When at a table, call the formula editor with `org-table-edit-formulas'.
12648 When at the first line of an src example, call `org-edit-src-code'.
12649 When in an #+include line, visit the include file. Otherwise call
12650 `ffap' to visit the file at point."
12651 (interactive)
12652 (cond
12653 ((org-at-table-p)
12654 (call-interactively 'org-table-edit-formulas))
12655 ((save-excursion
12656 (beginning-of-line 1)
12657 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
12658 (find-file (org-trim (match-string 1))))
12659 ((org-edit-src-code))
12660 ((org-edit-fixed-width-region))
12661 (t (call-interactively 'ffap))))
12663 (defun org-ctrl-c-ctrl-c (&optional arg)
12664 "Set tags in headline, or update according to changed information at point.
12666 This command does many different things, depending on context:
12668 - If the cursor is in a headline, prompt for tags and insert them
12669 into the current line, aligned to `org-tags-column'. When called
12670 with prefix arg, realign all tags in the current buffer.
12672 - If the cursor is in one of the special #+KEYWORD lines, this
12673 triggers scanning the buffer for these lines and updating the
12674 information.
12676 - If the cursor is inside a table, realign the table. This command
12677 works even if the automatic table editor has been turned off.
12679 - If the cursor is on a #+TBLFM line, re-apply the formulas to
12680 the entire table.
12682 - If the cursor is a the beginning of a dynamic block, update it.
12684 - If the cursor is inside a table created by the table.el package,
12685 activate that table.
12687 - If the current buffer is a remember buffer, close note and file
12688 it. A prefix argument of 1 files to the default location
12689 without further interaction. A prefix argument of 2 files to
12690 the currently clocking task.
12692 - If the cursor is on a <<<target>>>, update radio targets and corresponding
12693 links in this buffer.
12695 - If the cursor is on a numbered item in a plain list, renumber the
12696 ordered list.
12698 - If the cursor is on a checkbox, toggle it."
12699 (interactive "P")
12700 (let ((org-enable-table-editor t))
12701 (cond
12702 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
12703 org-occur-highlights
12704 org-latex-fragment-image-overlays)
12705 (and (boundp 'org-clock-overlays) (org-remove-clock-overlays))
12706 (org-remove-occur-highlights)
12707 (org-remove-latex-fragment-image-overlays)
12708 (message "Temporary highlights/overlays removed from current buffer"))
12709 ((and (local-variable-p 'org-finish-function (current-buffer))
12710 (fboundp org-finish-function))
12711 (funcall org-finish-function))
12712 ((org-at-property-p)
12713 (call-interactively 'org-property-action))
12714 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
12715 ((org-on-heading-p) (call-interactively 'org-set-tags))
12716 ((org-at-table.el-p)
12717 (require 'table)
12718 (beginning-of-line 1)
12719 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
12720 (call-interactively 'table-recognize-table))
12721 ((org-at-table-p)
12722 (org-table-maybe-eval-formula)
12723 (if arg
12724 (call-interactively 'org-table-recalculate)
12725 (org-table-maybe-recalculate-line))
12726 (call-interactively 'org-table-align))
12727 ((org-at-item-checkbox-p)
12728 (call-interactively 'org-toggle-checkbox))
12729 ((org-at-item-p)
12730 (call-interactively 'org-maybe-renumber-ordered-list))
12731 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
12732 ;; Dynamic block
12733 (beginning-of-line 1)
12734 (save-excursion (org-update-dblock)))
12735 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
12736 (cond
12737 ((equal (match-string 1) "TBLFM")
12738 ;; Recalculate the table before this line
12739 (save-excursion
12740 (beginning-of-line 1)
12741 (skip-chars-backward " \r\n\t")
12742 (if (org-at-table-p)
12743 (org-call-with-arg 'org-table-recalculate t))))
12745 ; (org-set-regexps-and-options)
12746 ; (org-restart-font-lock)
12747 (let ((org-inhibit-startup t)) (org-mode-restart))
12748 (message "Local setup has been refreshed"))))
12749 (t (error "C-c C-c can do nothing useful at this location.")))))
12751 (defun org-mode-restart ()
12752 "Restart Org-mode, to scan again for special lines.
12753 Also updates the keyword regular expressions."
12754 (interactive)
12755 (org-mode)
12756 (message "Org-mode restarted"))
12758 (defun org-kill-note-or-show-branches ()
12759 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
12760 (interactive)
12761 (if (not org-finish-function)
12762 (call-interactively 'show-branches)
12763 (let ((org-note-abort t))
12764 (funcall org-finish-function))))
12766 (defun org-return (&optional indent)
12767 "Goto next table row or insert a newline.
12768 Calls `org-table-next-row' or `newline', depending on context.
12769 See the individual commands for more information."
12770 (interactive)
12771 (cond
12772 ((bobp) (if indent (newline-and-indent) (newline)))
12773 ((and (org-at-heading-p)
12774 (looking-at
12775 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
12776 (org-show-entry)
12777 (end-of-line 1)
12778 (newline))
12779 ((org-at-table-p)
12780 (org-table-justify-field-maybe)
12781 (call-interactively 'org-table-next-row))
12782 (t (if indent (newline-and-indent) (newline)))))
12784 (defun org-return-indent ()
12785 "Goto next table row or insert a newline and indent.
12786 Calls `org-table-next-row' or `newline-and-indent', depending on
12787 context. See the individual commands for more information."
12788 (interactive)
12789 (org-return t))
12791 (defun org-ctrl-c-star ()
12792 "Compute table, or change heading status of lines.
12793 Calls `org-table-recalculate' or `org-toggle-region-headings',
12794 depending on context. This will also turn a plain list item or a normal
12795 line into a subheading."
12796 (interactive)
12797 (cond
12798 ((org-at-table-p)
12799 (call-interactively 'org-table-recalculate))
12800 ((org-region-active-p)
12801 ;; Convert all lines in region to list items
12802 (call-interactively 'org-toggle-region-headings))
12803 ((org-on-heading-p)
12804 (org-toggle-region-headings (point-at-bol)
12805 (min (1+ (point-at-eol)) (point-max))))
12806 ((org-at-item-p)
12807 ;; Convert to heading
12808 (let ((level (save-match-data
12809 (save-excursion
12810 (condition-case nil
12811 (progn
12812 (org-back-to-heading t)
12813 (funcall outline-level))
12814 (error 0))))))
12815 (replace-match
12816 (concat (make-string (org-get-valid-level level 1) ?*) " ") t t)))
12817 (t (org-toggle-region-headings (point-at-bol)
12818 (min (1+ (point-at-eol)) (point-max))))))
12820 (defun org-ctrl-c-minus ()
12821 "Insert separator line in table or modify bullet status of line.
12822 Also turns a plain line or a region of lines into list items.
12823 Calls `org-table-insert-hline', `org-toggle-region-items', or
12824 `org-cycle-list-bullet', depending on context."
12825 (interactive)
12826 (cond
12827 ((org-at-table-p)
12828 (call-interactively 'org-table-insert-hline))
12829 ((org-on-heading-p)
12830 ;; Convert to item
12831 (save-excursion
12832 (beginning-of-line 1)
12833 (if (looking-at "\\*+ ")
12834 (replace-match (concat (make-string (- (match-end 0) (point) 1) ?\ ) "- ")))))
12835 ((org-region-active-p)
12836 ;; Convert all lines in region to list items
12837 (call-interactively 'org-toggle-region-items))
12838 ((org-in-item-p)
12839 (call-interactively 'org-cycle-list-bullet))
12840 (t (org-toggle-region-items (point-at-bol)
12841 (min (1+ (point-at-eol)) (point-max))))))
12843 (defun org-toggle-region-items (beg end)
12844 "Convert all lines in region to list items.
12845 If the first line is already an item, convert all list items in the region
12846 to normal lines."
12847 (interactive "r")
12848 (let (l2 l)
12849 (save-excursion
12850 (goto-char end)
12851 (setq l2 (org-current-line))
12852 (goto-char beg)
12853 (beginning-of-line 1)
12854 (setq l (1- (org-current-line)))
12855 (if (org-at-item-p)
12856 ;; We already have items, de-itemize
12857 (while (< (setq l (1+ l)) l2)
12858 (when (org-at-item-p)
12859 (goto-char (match-beginning 2))
12860 (delete-region (match-beginning 2) (match-end 2))
12861 (and (looking-at "[ \t]+") (replace-match "")))
12862 (beginning-of-line 2))
12863 (while (< (setq l (1+ l)) l2)
12864 (unless (org-at-item-p)
12865 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
12866 (replace-match "\\1- \\2")))
12867 (beginning-of-line 2))))))
12869 (defun org-toggle-region-headings (beg end)
12870 "Convert all lines in region to list items.
12871 If the first line is already an item, convert all list items in the region
12872 to normal lines."
12873 (interactive "r")
12874 (let (l2 l)
12875 (save-excursion
12876 (goto-char end)
12877 (setq l2 (org-current-line))
12878 (goto-char beg)
12879 (beginning-of-line 1)
12880 (setq l (1- (org-current-line)))
12881 (if (org-on-heading-p)
12882 ;; We already have headlines, de-star them
12883 (while (< (setq l (1+ l)) l2)
12884 (when (org-on-heading-p t)
12885 (and (looking-at outline-regexp) (replace-match "")))
12886 (beginning-of-line 2))
12887 (let* ((stars (save-excursion
12888 (re-search-backward org-complex-heading-regexp nil t)
12889 (or (match-string 1) "*")))
12890 (add-stars (if org-odd-levels-only "**" "*"))
12891 (rpl (concat stars add-stars " \\2")))
12892 (while (< (setq l (1+ l)) l2)
12893 (unless (org-on-heading-p)
12894 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
12895 (replace-match rpl)))
12896 (beginning-of-line 2)))))))
12898 (defun org-meta-return (&optional arg)
12899 "Insert a new heading or wrap a region in a table.
12900 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
12901 See the individual commands for more information."
12902 (interactive "P")
12903 (cond
12904 ((org-at-table-p)
12905 (call-interactively 'org-table-wrap-region))
12906 (t (call-interactively 'org-insert-heading))))
12908 ;;; Menu entries
12910 ;; Define the Org-mode menus
12911 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
12912 '("Tbl"
12913 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
12914 ["Next Field" org-cycle (org-at-table-p)]
12915 ["Previous Field" org-shifttab (org-at-table-p)]
12916 ["Next Row" org-return (org-at-table-p)]
12917 "--"
12918 ["Blank Field" org-table-blank-field (org-at-table-p)]
12919 ["Edit Field" org-table-edit-field (org-at-table-p)]
12920 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
12921 "--"
12922 ("Column"
12923 ["Move Column Left" org-metaleft (org-at-table-p)]
12924 ["Move Column Right" org-metaright (org-at-table-p)]
12925 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
12926 ["Insert Column" org-shiftmetaright (org-at-table-p)])
12927 ("Row"
12928 ["Move Row Up" org-metaup (org-at-table-p)]
12929 ["Move Row Down" org-metadown (org-at-table-p)]
12930 ["Delete Row" org-shiftmetaup (org-at-table-p)]
12931 ["Insert Row" org-shiftmetadown (org-at-table-p)]
12932 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
12933 "--"
12934 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
12935 ("Rectangle"
12936 ["Copy Rectangle" org-copy-special (org-at-table-p)]
12937 ["Cut Rectangle" org-cut-special (org-at-table-p)]
12938 ["Paste Rectangle" org-paste-special (org-at-table-p)]
12939 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
12940 "--"
12941 ("Calculate"
12942 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
12943 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
12944 ["Edit Formulas" org-edit-special (org-at-table-p)]
12945 "--"
12946 ["Recalculate line" org-table-recalculate (org-at-table-p)]
12947 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
12948 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
12949 "--"
12950 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
12951 "--"
12952 ["Sum Column/Rectangle" org-table-sum
12953 (or (org-at-table-p) (org-region-active-p))]
12954 ["Which Column?" org-table-current-column (org-at-table-p)])
12955 ["Debug Formulas"
12956 org-table-toggle-formula-debugger
12957 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
12958 ["Show Col/Row Numbers"
12959 org-table-toggle-coordinate-overlays
12960 :style toggle
12961 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
12962 "--"
12963 ["Create" org-table-create (and (not (org-at-table-p))
12964 org-enable-table-editor)]
12965 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
12966 ["Import from File" org-table-import (not (org-at-table-p))]
12967 ["Export to File" org-table-export (org-at-table-p)]
12968 "--"
12969 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
12971 (easy-menu-define org-org-menu org-mode-map "Org menu"
12972 '("Org"
12973 ("Show/Hide"
12974 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
12975 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
12976 ["Sparse Tree..." org-sparse-tree t]
12977 ["Reveal Context" org-reveal t]
12978 ["Show All" show-all t]
12979 "--"
12980 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
12981 "--"
12982 ["New Heading" org-insert-heading t]
12983 ("Navigate Headings"
12984 ["Up" outline-up-heading t]
12985 ["Next" outline-next-visible-heading t]
12986 ["Previous" outline-previous-visible-heading t]
12987 ["Next Same Level" outline-forward-same-level t]
12988 ["Previous Same Level" outline-backward-same-level t]
12989 "--"
12990 ["Jump" org-goto t])
12991 ("Edit Structure"
12992 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
12993 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
12994 "--"
12995 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
12996 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
12997 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
12998 "--"
12999 ["Promote Heading" org-metaleft (not (org-at-table-p))]
13000 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
13001 ["Demote Heading" org-metaright (not (org-at-table-p))]
13002 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
13003 "--"
13004 ["Sort Region/Children" org-sort (not (org-at-table-p))]
13005 "--"
13006 ["Convert to odd levels" org-convert-to-odd-levels t]
13007 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
13008 ("Editing"
13009 ["Emphasis..." org-emphasize t]
13010 ["Edit Source Example" org-edit-special t])
13011 ("Archive"
13012 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
13013 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
13014 ; :active t :keys "C-u C-c C-x C-a"]
13015 ["Sparse trees open ARCHIVE trees"
13016 (setq org-sparse-tree-open-archived-trees
13017 (not org-sparse-tree-open-archived-trees))
13018 :style toggle :selected org-sparse-tree-open-archived-trees]
13019 ["Cycling opens ARCHIVE trees"
13020 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
13021 :style toggle :selected org-cycle-open-archived-trees]
13022 "--"
13023 ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
13024 ["Move Subtree to Archive" org-advertized-archive-subtree t]
13025 ; ["Check and Move Children" (org-archive-subtree '(4))
13026 ; :active t :keys "C-u C-c C-x C-s"]
13028 "--"
13029 ("TODO Lists"
13030 ["TODO/DONE/-" org-todo t]
13031 ("Select keyword"
13032 ["Next keyword" org-shiftright (org-on-heading-p)]
13033 ["Previous keyword" org-shiftleft (org-on-heading-p)]
13034 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
13035 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
13036 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
13037 ["Show TODO Tree" org-show-todo-tree t]
13038 ["Global TODO list" org-todo-list t]
13039 "--"
13040 ["Set Priority" org-priority t]
13041 ["Priority Up" org-shiftup t]
13042 ["Priority Down" org-shiftdown t])
13043 ("TAGS and Properties"
13044 ["Set Tags" 'org-set-tags-command t]
13045 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
13046 "--"
13047 ["Set property" 'org-set-property t]
13048 ["Column view of properties" org-columns t]
13049 ["Insert Column View DBlock" org-insert-columns-dblock t])
13050 ("Dates and Scheduling"
13051 ["Timestamp" org-time-stamp t]
13052 ["Timestamp (inactive)" org-time-stamp-inactive t]
13053 ("Change Date"
13054 ["1 Day Later" org-shiftright t]
13055 ["1 Day Earlier" org-shiftleft t]
13056 ["1 ... Later" org-shiftup t]
13057 ["1 ... Earlier" org-shiftdown t])
13058 ["Compute Time Range" org-evaluate-time-range t]
13059 ["Schedule Item" org-schedule t]
13060 ["Deadline" org-deadline t]
13061 "--"
13062 ["Custom time format" org-toggle-time-stamp-overlays
13063 :style radio :selected org-display-custom-times]
13064 "--"
13065 ["Goto Calendar" org-goto-calendar t]
13066 ["Date from Calendar" org-date-from-calendar t])
13067 ("Logging work"
13068 ["Clock in" org-clock-in t]
13069 ["Clock out" org-clock-out t]
13070 ["Clock cancel" org-clock-cancel t]
13071 ["Goto running clock" org-clock-goto t]
13072 ["Display times" org-clock-display t]
13073 ["Create clock table" org-clock-report t]
13074 "--"
13075 ["Record DONE time"
13076 (progn (setq org-log-done (not org-log-done))
13077 (message "Switching to %s will %s record a timestamp"
13078 (car org-done-keywords)
13079 (if org-log-done "automatically" "not")))
13080 :style toggle :selected org-log-done])
13081 "--"
13082 ["Agenda Command..." org-agenda t]
13083 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
13084 ("File List for Agenda")
13085 ("Special views current file"
13086 ["TODO Tree" org-show-todo-tree t]
13087 ["Check Deadlines" org-check-deadlines t]
13088 ["Timeline" org-timeline t]
13089 ["Tags Tree" org-tags-sparse-tree t])
13090 "--"
13091 ("Hyperlinks"
13092 ["Store Link (Global)" org-store-link t]
13093 ["Insert Link" org-insert-link t]
13094 ["Follow Link" org-open-at-point t]
13095 "--"
13096 ["Next link" org-next-link t]
13097 ["Previous link" org-previous-link t]
13098 "--"
13099 ["Descriptive Links"
13100 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
13101 :style radio
13102 :selected (member '(org-link) buffer-invisibility-spec)]
13103 ["Literal Links"
13104 (progn
13105 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
13106 :style radio
13107 :selected (not (member '(org-link) buffer-invisibility-spec))])
13108 "--"
13109 ["Export/Publish..." org-export t]
13110 ("LaTeX"
13111 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
13112 :selected org-cdlatex-mode]
13113 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
13114 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
13115 ["Modify math symbol" org-cdlatex-math-modify
13116 (org-inside-LaTeX-fragment-p)]
13117 ["Export LaTeX fragments as images"
13118 (if (featurep 'org-exp)
13119 (setq org-export-with-LaTeX-fragments
13120 (not org-export-with-LaTeX-fragments))
13121 (require 'org-exp))
13122 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
13123 org-export-with-LaTeX-fragments)])
13124 "--"
13125 ("Documentation"
13126 ["Show Version" org-version t]
13127 ["Info Documentation" org-info t])
13128 ("Customize"
13129 ["Browse Org Group" org-customize t]
13130 "--"
13131 ["Expand This Menu" org-create-customize-menu
13132 (fboundp 'customize-menu-create)])
13133 "--"
13134 ["Refresh setup" org-mode-restart t]
13137 (defun org-info (&optional node)
13138 "Read documentation for Org-mode in the info system.
13139 With optional NODE, go directly to that node."
13140 (interactive)
13141 (info (format "(org)%s" (or node ""))))
13143 (defun org-install-agenda-files-menu ()
13144 (let ((bl (buffer-list)))
13145 (save-excursion
13146 (while bl
13147 (set-buffer (pop bl))
13148 (if (org-mode-p) (setq bl nil)))
13149 (when (org-mode-p)
13150 (easy-menu-change
13151 '("Org") "File List for Agenda"
13152 (append
13153 (list
13154 ["Edit File List" (org-edit-agenda-file-list) t]
13155 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
13156 ["Remove Current File from List" org-remove-file t]
13157 ["Cycle through agenda files" org-cycle-agenda-files t]
13158 ["Occur in all agenda files" org-occur-in-agenda-files t]
13159 "--")
13160 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
13162 ;;;; Documentation
13164 ;;;###autoload
13165 (defun org-require-autoloaded-modules ()
13166 (interactive)
13167 (mapc 'require
13168 '(org-agenda org-archive org-clock org-colview
13169 org-exp org-id org-export-latex org-publish
13170 org-remember org-table)))
13172 ;;;###autoload
13173 (defun org-customize ()
13174 "Call the customize function with org as argument."
13175 (interactive)
13176 (org-load-modules-maybe)
13177 (org-require-autoloaded-modules)
13178 (customize-browse 'org))
13180 (defun org-create-customize-menu ()
13181 "Create a full customization menu for Org-mode, insert it into the menu."
13182 (interactive)
13183 (org-load-modules-maybe)
13184 (org-require-autoloaded-modules)
13185 (if (fboundp 'customize-menu-create)
13186 (progn
13187 (easy-menu-change
13188 '("Org") "Customize"
13189 `(["Browse Org group" org-customize t]
13190 "--"
13191 ,(customize-menu-create 'org)
13192 ["Set" Custom-set t]
13193 ["Save" Custom-save t]
13194 ["Reset to Current" Custom-reset-current t]
13195 ["Reset to Saved" Custom-reset-saved t]
13196 ["Reset to Standard Settings" Custom-reset-standard t]))
13197 (message "\"Org\"-menu now contains full customization menu"))
13198 (error "Cannot expand menu (outdated version of cus-edit.el)")))
13200 ;;;; Miscellaneous stuff
13202 ;;; Generally useful functions
13204 (defun org-display-warning (message) ;; Copied from Emacs-Muse
13205 "Display the given MESSAGE as a warning."
13206 (if (fboundp 'display-warning)
13207 (display-warning 'org message
13208 (if (featurep 'xemacs)
13209 'warning
13210 :warning))
13211 (let ((buf (get-buffer-create "*Org warnings*")))
13212 (with-current-buffer buf
13213 (goto-char (point-max))
13214 (insert "Warning (Org): " message)
13215 (unless (bolp)
13216 (newline)))
13217 (display-buffer buf)
13218 (sit-for 0))))
13220 (defun org-goto-marker-or-bmk (marker &optional bookmark)
13221 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
13222 (if (and marker (marker-buffer marker)
13223 (buffer-live-p (marker-buffer marker)))
13224 (progn
13225 (switch-to-buffer (marker-buffer marker))
13226 (if (or (> marker (point-max)) (< marker (point-min)))
13227 (widen))
13228 (goto-char marker))
13229 (if bookmark
13230 (bookmark-jump bookmark)
13231 (error "Cannot find location"))))
13233 (defun org-quote-csv-field (s)
13234 "Quote field for inclusion in CSV material."
13235 (if (string-match "[\",]" s)
13236 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
13239 (defun org-plist-delete (plist property)
13240 "Delete PROPERTY from PLIST.
13241 This is in contrast to merely setting it to 0."
13242 (let (p)
13243 (while plist
13244 (if (not (eq property (car plist)))
13245 (setq p (plist-put p (car plist) (nth 1 plist))))
13246 (setq plist (cddr plist)))
13249 (defun org-force-self-insert (N)
13250 "Needed to enforce self-insert under remapping."
13251 (interactive "p")
13252 (self-insert-command N))
13254 (defun org-string-width (s)
13255 "Compute width of string, ignoring invisible characters.
13256 This ignores character with invisibility property `org-link', and also
13257 characters with property `org-cwidth', because these will become invisible
13258 upon the next fontification round."
13259 (let (b l)
13260 (when (or (eq t buffer-invisibility-spec)
13261 (assq 'org-link buffer-invisibility-spec))
13262 (while (setq b (text-property-any 0 (length s)
13263 'invisible 'org-link s))
13264 (setq s (concat (substring s 0 b)
13265 (substring s (or (next-single-property-change
13266 b 'invisible s) (length s)))))))
13267 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
13268 (setq s (concat (substring s 0 b)
13269 (substring s (or (next-single-property-change
13270 b 'org-cwidth s) (length s))))))
13271 (setq l (string-width s) b -1)
13272 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
13273 (setq l (- l (get-text-property b 'org-dwidth-n s))))
13276 (defun org-get-indentation (&optional line)
13277 "Get the indentation of the current line, interpreting tabs.
13278 When LINE is given, assume it represents a line and compute its indentation."
13279 (if line
13280 (if (string-match "^ *" (org-remove-tabs line))
13281 (match-end 0))
13282 (save-excursion
13283 (beginning-of-line 1)
13284 (skip-chars-forward " \t")
13285 (current-column))))
13287 (defun org-remove-tabs (s &optional width)
13288 "Replace tabulators in S with spaces.
13289 Assumes that s is a single line, starting in column 0."
13290 (setq width (or width tab-width))
13291 (while (string-match "\t" s)
13292 (setq s (replace-match
13293 (make-string
13294 (- (* width (/ (+ (match-beginning 0) width) width))
13295 (match-beginning 0)) ?\ )
13296 t t s)))
13299 (defun org-fix-indentation (line ind)
13300 "Fix indentation in LINE.
13301 IND is a cons cell with target and minimum indentation.
13302 If the current indenation in LINE is smaller than the minimum,
13303 leave it alone. If it is larger than ind, set it to the target."
13304 (let* ((l (org-remove-tabs line))
13305 (i (org-get-indentation l))
13306 (i1 (car ind)) (i2 (cdr ind)))
13307 (if (>= i i2) (setq l (substring line i2)))
13308 (if (> i1 0)
13309 (concat (make-string i1 ?\ ) l)
13310 l)))
13312 (defun org-base-buffer (buffer)
13313 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
13314 (if (not buffer)
13315 buffer
13316 (or (buffer-base-buffer buffer)
13317 buffer)))
13319 (defun org-trim (s)
13320 "Remove whitespace at beginning and end of string."
13321 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
13322 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
13325 (defun org-wrap (string &optional width lines)
13326 "Wrap string to either a number of lines, or a width in characters.
13327 If WIDTH is non-nil, the string is wrapped to that width, however many lines
13328 that costs. If there is a word longer than WIDTH, the text is actually
13329 wrapped to the length of that word.
13330 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
13331 many lines, whatever width that takes.
13332 The return value is a list of lines, without newlines at the end."
13333 (let* ((words (org-split-string string "[ \t\n]+"))
13334 (maxword (apply 'max (mapcar 'org-string-width words)))
13335 w ll)
13336 (cond (width
13337 (org-do-wrap words (max maxword width)))
13338 (lines
13339 (setq w maxword)
13340 (setq ll (org-do-wrap words maxword))
13341 (if (<= (length ll) lines)
13343 (setq ll words)
13344 (while (> (length ll) lines)
13345 (setq w (1+ w))
13346 (setq ll (org-do-wrap words w)))
13347 ll))
13348 (t (error "Cannot wrap this")))))
13350 (defun org-do-wrap (words width)
13351 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
13352 (let (lines line)
13353 (while words
13354 (setq line (pop words))
13355 (while (and words (< (+ (length line) (length (car words))) width))
13356 (setq line (concat line " " (pop words))))
13357 (setq lines (push line lines)))
13358 (nreverse lines)))
13360 (defun org-split-string (string &optional separators)
13361 "Splits STRING into substrings at SEPARATORS.
13362 No empty strings are returned if there are matches at the beginning
13363 and end of string."
13364 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
13365 (start 0)
13366 notfirst
13367 (list nil))
13368 (while (and (string-match rexp string
13369 (if (and notfirst
13370 (= start (match-beginning 0))
13371 (< start (length string)))
13372 (1+ start) start))
13373 (< (match-beginning 0) (length string)))
13374 (setq notfirst t)
13375 (or (eq (match-beginning 0) 0)
13376 (and (eq (match-beginning 0) (match-end 0))
13377 (eq (match-beginning 0) start))
13378 (setq list
13379 (cons (substring string start (match-beginning 0))
13380 list)))
13381 (setq start (match-end 0)))
13382 (or (eq start (length string))
13383 (setq list
13384 (cons (substring string start)
13385 list)))
13386 (nreverse list)))
13388 (defun org-context ()
13389 "Return a list of contexts of the current cursor position.
13390 If several contexts apply, all are returned.
13391 Each context entry is a list with a symbol naming the context, and
13392 two positions indicating start and end of the context. Possible
13393 contexts are:
13395 :headline anywhere in a headline
13396 :headline-stars on the leading stars in a headline
13397 :todo-keyword on a TODO keyword (including DONE) in a headline
13398 :tags on the TAGS in a headline
13399 :priority on the priority cookie in a headline
13400 :item on the first line of a plain list item
13401 :item-bullet on the bullet/number of a plain list item
13402 :checkbox on the checkbox in a plain list item
13403 :table in an org-mode table
13404 :table-special on a special filed in a table
13405 :table-table in a table.el table
13406 :link on a hyperlink
13407 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
13408 :target on a <<target>>
13409 :radio-target on a <<<radio-target>>>
13410 :latex-fragment on a LaTeX fragment
13411 :latex-preview on a LaTeX fragment with overlayed preview image
13413 This function expects the position to be visible because it uses font-lock
13414 faces as a help to recognize the following contexts: :table-special, :link,
13415 and :keyword."
13416 (let* ((f (get-text-property (point) 'face))
13417 (faces (if (listp f) f (list f)))
13418 (p (point)) clist o)
13419 ;; First the large context
13420 (cond
13421 ((org-on-heading-p t)
13422 (push (list :headline (point-at-bol) (point-at-eol)) clist)
13423 (when (progn
13424 (beginning-of-line 1)
13425 (looking-at org-todo-line-tags-regexp))
13426 (push (org-point-in-group p 1 :headline-stars) clist)
13427 (push (org-point-in-group p 2 :todo-keyword) clist)
13428 (push (org-point-in-group p 4 :tags) clist))
13429 (goto-char p)
13430 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
13431 (if (looking-at "\\[#[A-Z0-9]\\]")
13432 (push (org-point-in-group p 0 :priority) clist)))
13434 ((org-at-item-p)
13435 (push (org-point-in-group p 2 :item-bullet) clist)
13436 (push (list :item (point-at-bol)
13437 (save-excursion (org-end-of-item) (point)))
13438 clist)
13439 (and (org-at-item-checkbox-p)
13440 (push (org-point-in-group p 0 :checkbox) clist)))
13442 ((org-at-table-p)
13443 (push (list :table (org-table-begin) (org-table-end)) clist)
13444 (if (memq 'org-formula faces)
13445 (push (list :table-special
13446 (previous-single-property-change p 'face)
13447 (next-single-property-change p 'face)) clist)))
13448 ((org-at-table-p 'any)
13449 (push (list :table-table) clist)))
13450 (goto-char p)
13452 ;; Now the small context
13453 (cond
13454 ((org-at-timestamp-p)
13455 (push (org-point-in-group p 0 :timestamp) clist))
13456 ((memq 'org-link faces)
13457 (push (list :link
13458 (previous-single-property-change p 'face)
13459 (next-single-property-change p 'face)) clist))
13460 ((memq 'org-special-keyword faces)
13461 (push (list :keyword
13462 (previous-single-property-change p 'face)
13463 (next-single-property-change p 'face)) clist))
13464 ((org-on-target-p)
13465 (push (org-point-in-group p 0 :target) clist)
13466 (goto-char (1- (match-beginning 0)))
13467 (if (looking-at org-radio-target-regexp)
13468 (push (org-point-in-group p 0 :radio-target) clist))
13469 (goto-char p))
13470 ((setq o (car (delq nil
13471 (mapcar
13472 (lambda (x)
13473 (if (memq x org-latex-fragment-image-overlays) x))
13474 (org-overlays-at (point))))))
13475 (push (list :latex-fragment
13476 (org-overlay-start o) (org-overlay-end o)) clist)
13477 (push (list :latex-preview
13478 (org-overlay-start o) (org-overlay-end o)) clist))
13479 ((org-inside-LaTeX-fragment-p)
13480 ;; FIXME: positions wrong.
13481 (push (list :latex-fragment (point) (point)) clist)))
13483 (setq clist (nreverse (delq nil clist)))
13484 clist))
13486 ;; FIXME: Compare with at-regexp-p Do we need both?
13487 (defun org-in-regexp (re &optional nlines visually)
13488 "Check if point is inside a match of regexp.
13489 Normally only the current line is checked, but you can include NLINES extra
13490 lines both before and after point into the search.
13491 If VISUALLY is set, require that the cursor is not after the match but
13492 really on, so that the block visually is on the match."
13493 (catch 'exit
13494 (let ((pos (point))
13495 (eol (point-at-eol (+ 1 (or nlines 0))))
13496 (inc (if visually 1 0)))
13497 (save-excursion
13498 (beginning-of-line (- 1 (or nlines 0)))
13499 (while (re-search-forward re eol t)
13500 (if (and (<= (match-beginning 0) pos)
13501 (>= (+ inc (match-end 0)) pos))
13502 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
13504 (defun org-at-regexp-p (regexp)
13505 "Is point inside a match of REGEXP in the current line?"
13506 (catch 'exit
13507 (save-excursion
13508 (let ((pos (point)) (end (point-at-eol)))
13509 (beginning-of-line 1)
13510 (while (re-search-forward regexp end t)
13511 (if (and (<= (match-beginning 0) pos)
13512 (>= (match-end 0) pos))
13513 (throw 'exit t)))
13514 nil))))
13516 (defun org-occur-in-agenda-files (regexp &optional nlines)
13517 "Call `multi-occur' with buffers for all agenda files."
13518 (interactive "sOrg-files matching: \np")
13519 (let* ((files (org-agenda-files))
13520 (tnames (mapcar 'file-truename files))
13521 (extra org-agenda-text-search-extra-files)
13523 (when (eq (car extra) 'agenda-archives)
13524 (setq extra (cdr extra))
13525 (setq files (org-add-archive-files files)))
13526 (while (setq f (pop extra))
13527 (unless (member (file-truename f) tnames)
13528 (add-to-list 'files f 'append)
13529 (add-to-list 'tnames (file-truename f) 'append)))
13530 (multi-occur
13531 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
13532 regexp)))
13534 (if (boundp 'occur-mode-find-occurrence-hook)
13535 ;; Emacs 23
13536 (add-hook 'occur-mode-find-occurrence-hook
13537 (lambda ()
13538 (when (org-mode-p)
13539 (org-reveal))))
13540 ;; Emacs 22
13541 (defadvice occur-mode-goto-occurrence
13542 (after org-occur-reveal activate)
13543 (and (org-mode-p) (org-reveal)))
13544 (defadvice occur-mode-goto-occurrence-other-window
13545 (after org-occur-reveal activate)
13546 (and (org-mode-p) (org-reveal)))
13547 (defadvice occur-mode-display-occurrence
13548 (after org-occur-reveal activate)
13549 (when (org-mode-p)
13550 (let ((pos (occur-mode-find-occurrence)))
13551 (with-current-buffer (marker-buffer pos)
13552 (save-excursion
13553 (goto-char pos)
13554 (org-reveal)))))))
13556 (defun org-uniquify (list)
13557 "Remove duplicate elements from LIST."
13558 (let (res)
13559 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
13560 res))
13562 (defun org-delete-all (elts list)
13563 "Remove all elements in ELTS from LIST."
13564 (while elts
13565 (setq list (delete (pop elts) list)))
13566 list)
13568 (defun org-back-over-empty-lines ()
13569 "Move backwards over witespace, to the beginning of the first empty line.
13570 Returns the number of empty lines passed."
13571 (let ((pos (point)))
13572 (skip-chars-backward " \t\n\r")
13573 (beginning-of-line 2)
13574 (goto-char (min (point) pos))
13575 (count-lines (point) pos)))
13577 (defun org-skip-whitespace ()
13578 (skip-chars-forward " \t\n\r"))
13580 (defun org-point-in-group (point group &optional context)
13581 "Check if POINT is in match-group GROUP.
13582 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
13583 match. If the match group does ot exist or point is not inside it,
13584 return nil."
13585 (and (match-beginning group)
13586 (>= point (match-beginning group))
13587 (<= point (match-end group))
13588 (if context
13589 (list context (match-beginning group) (match-end group))
13590 t)))
13592 (defun org-switch-to-buffer-other-window (&rest args)
13593 "Switch to buffer in a second window on the current frame.
13594 In particular, do not allow pop-up frames."
13595 (let (pop-up-frames special-display-buffer-names special-display-regexps
13596 special-display-function)
13597 (apply 'switch-to-buffer-other-window args)))
13599 (defun org-combine-plists (&rest plists)
13600 "Create a single property list from all plists in PLISTS.
13601 The process starts by copying the first list, and then setting properties
13602 from the other lists. Settings in the last list are the most significant
13603 ones and overrule settings in the other lists."
13604 (let ((rtn (copy-sequence (pop plists)))
13605 p v ls)
13606 (while plists
13607 (setq ls (pop plists))
13608 (while ls
13609 (setq p (pop ls) v (pop ls))
13610 (setq rtn (plist-put rtn p v))))
13611 rtn))
13613 (defun org-move-line-down (arg)
13614 "Move the current line down. With prefix argument, move it past ARG lines."
13615 (interactive "p")
13616 (let ((col (current-column))
13617 beg end pos)
13618 (beginning-of-line 1) (setq beg (point))
13619 (beginning-of-line 2) (setq end (point))
13620 (beginning-of-line (+ 1 arg))
13621 (setq pos (move-marker (make-marker) (point)))
13622 (insert (delete-and-extract-region beg end))
13623 (goto-char pos)
13624 (org-move-to-column col)))
13626 (defun org-move-line-up (arg)
13627 "Move the current line up. With prefix argument, move it past ARG lines."
13628 (interactive "p")
13629 (let ((col (current-column))
13630 beg end pos)
13631 (beginning-of-line 1) (setq beg (point))
13632 (beginning-of-line 2) (setq end (point))
13633 (beginning-of-line (- arg))
13634 (setq pos (move-marker (make-marker) (point)))
13635 (insert (delete-and-extract-region beg end))
13636 (goto-char pos)
13637 (org-move-to-column col)))
13639 (defun org-replace-escapes (string table)
13640 "Replace %-escapes in STRING with values in TABLE.
13641 TABLE is an association list with keys like \"%a\" and string values.
13642 The sequences in STRING may contain normal field width and padding information,
13643 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
13644 so values can contain further %-escapes if they are define later in TABLE."
13645 (let ((case-fold-search nil)
13646 e re rpl)
13647 (while (setq e (pop table))
13648 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
13649 (while (string-match re string)
13650 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
13651 (cdr e)))
13652 (setq string (replace-match rpl t t string))))
13653 string))
13656 (defun org-sublist (list start end)
13657 "Return a section of LIST, from START to END.
13658 Counting starts at 1."
13659 (let (rtn (c start))
13660 (setq list (nthcdr (1- start) list))
13661 (while (and list (<= c end))
13662 (push (pop list) rtn)
13663 (setq c (1+ c)))
13664 (nreverse rtn)))
13666 (defun org-find-base-buffer-visiting (file)
13667 "Like `find-buffer-visiting' but alway return the base buffer and
13668 not an indirect buffer."
13669 (let ((buf (find-buffer-visiting file)))
13670 (if buf
13671 (or (buffer-base-buffer buf) buf)
13672 nil)))
13674 (defun org-image-file-name-regexp ()
13675 "Return regexp matching the file names of images."
13676 (if (fboundp 'image-file-name-regexp)
13677 (image-file-name-regexp)
13678 (let ((image-file-name-extensions
13679 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
13680 "xbm" "xpm" "pbm" "pgm" "ppm")))
13681 (concat "\\."
13682 (regexp-opt (nconc (mapcar 'upcase
13683 image-file-name-extensions)
13684 image-file-name-extensions)
13686 "\\'"))))
13688 (defun org-file-image-p (file)
13689 "Return non-nil if FILE is an image."
13690 (save-match-data
13691 (string-match (org-image-file-name-regexp) file)))
13693 (defun org-get-cursor-date ()
13694 "Return the date at cursor in as a time.
13695 This works in the calendar and in the agenda, anywhere else it just
13696 returns the current time."
13697 (let (date day defd)
13698 (cond
13699 ((eq major-mode 'calendar-mode)
13700 (setq date (calendar-cursor-to-date)
13701 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13702 ((eq major-mode 'org-agenda-mode)
13703 (setq day (get-text-property (point) 'day))
13704 (if day
13705 (setq date (calendar-gregorian-from-absolute day)
13706 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
13707 (nth 2 date))))))
13708 (or defd (current-time))))
13710 (defvar org-agenda-action-marker (make-marker)
13711 "Marker pointing to the entry for the next agenda action.")
13713 (defun org-mark-entry-for-agenda-action ()
13714 "Mark the current entry as target of an agenda action.
13715 Agenda actions are actions executed from the agenda with the key `k',
13716 which make use of the date at the cursor."
13717 (interactive)
13718 (move-marker org-agenda-action-marker
13719 (save-excursion (org-back-to-heading t) (point))
13720 (current-buffer))
13721 (message
13722 "Entry marked for action; press `k' at desired date in agenda or calendar"))
13724 ;;; Paragraph filling stuff.
13725 ;; We want this to be just right, so use the full arsenal.
13727 (defun org-indent-line-function ()
13728 "Indent line like previous, but further if previous was headline or item."
13729 (interactive)
13730 (let* ((pos (point))
13731 (itemp (org-at-item-p))
13732 column bpos bcol tpos tcol bullet btype bullet-type)
13733 ;; Find the previous relevant line
13734 (beginning-of-line 1)
13735 (cond
13736 ((looking-at "#") (setq column 0))
13737 ((looking-at "\\*+ ") (setq column 0))
13739 (beginning-of-line 0)
13740 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
13741 (beginning-of-line 0))
13742 (cond
13743 ((looking-at "\\*+[ \t]+")
13744 (if (not org-adapt-indentation)
13745 (setq column 0)
13746 (goto-char (match-end 0))
13747 (setq column (current-column))))
13748 ((org-in-item-p)
13749 (org-beginning-of-item)
13750 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
13751 (setq bpos (match-beginning 1) tpos (match-end 0)
13752 bcol (progn (goto-char bpos) (current-column))
13753 tcol (progn (goto-char tpos) (current-column))
13754 bullet (match-string 1)
13755 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
13756 (if (> tcol (+ bcol org-description-max-indent))
13757 (setq tcol (+ bcol 5)))
13758 (if (not itemp)
13759 (setq column tcol)
13760 (goto-char pos)
13761 (beginning-of-line 1)
13762 (if (looking-at "\\S-")
13763 (progn
13764 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
13765 (setq bullet (match-string 1)
13766 btype (if (string-match "[0-9]" bullet) "n" bullet))
13767 (setq column (if (equal btype bullet-type) bcol tcol)))
13768 (setq column (org-get-indentation)))))
13769 (t (setq column (org-get-indentation))))))
13770 (goto-char pos)
13771 (if (<= (current-column) (current-indentation))
13772 (org-indent-line-to column)
13773 (save-excursion (org-indent-line-to column)))
13774 (setq column (current-column))
13775 (beginning-of-line 1)
13776 (if (looking-at
13777 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
13778 (replace-match (concat "\\1" (format org-property-format
13779 (match-string 2) (match-string 3)))
13780 t nil))
13781 (org-move-to-column column)))
13783 (defun org-set-autofill-regexps ()
13784 (interactive)
13785 ;; In the paragraph separator we include headlines, because filling
13786 ;; text in a line directly attached to a headline would otherwise
13787 ;; fill the headline as well.
13788 (org-set-local 'comment-start-skip "^#+[ \t]*")
13789 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
13790 ;; The paragraph starter includes hand-formatted lists.
13791 (org-set-local 'paragraph-start
13792 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
13793 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
13794 ;; But only if the user has not turned off tables or fixed-width regions
13795 (org-set-local
13796 'auto-fill-inhibit-regexp
13797 (concat "\\*+ \\|#\\+"
13798 "\\|[ \t]*" org-keyword-time-regexp
13799 (if (or org-enable-table-editor org-enable-fixed-width-editor)
13800 (concat
13801 "\\|[ \t]*["
13802 (if org-enable-table-editor "|" "")
13803 (if org-enable-fixed-width-editor ":" "")
13804 "]"))))
13805 ;; We use our own fill-paragraph function, to make sure that tables
13806 ;; and fixed-width regions are not wrapped. That function will pass
13807 ;; through to `fill-paragraph' when appropriate.
13808 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
13809 ; Adaptive filling: To get full control, first make sure that
13810 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
13811 (org-set-local 'adaptive-fill-regexp "\000")
13812 (org-set-local 'adaptive-fill-function
13813 'org-adaptive-fill-function)
13814 (org-set-local
13815 'align-mode-rules-list
13816 '((org-in-buffer-settings
13817 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
13818 (modes . '(org-mode))))))
13820 (defun org-fill-paragraph (&optional justify)
13821 "Re-align a table, pass through to fill-paragraph if no table."
13822 (let ((table-p (org-at-table-p))
13823 (table.el-p (org-at-table.el-p)))
13824 (cond ((and (equal (char-after (point-at-bol)) ?*)
13825 (save-excursion (goto-char (point-at-bol))
13826 (looking-at outline-regexp)))
13827 t) ; skip headlines
13828 (table.el-p t) ; skip table.el tables
13829 (table-p (org-table-align) t) ; align org-mode tables
13830 (t nil)))) ; call paragraph-fill
13832 ;; For reference, this is the default value of adaptive-fill-regexp
13833 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
13835 (defun org-adaptive-fill-function ()
13836 "Return a fill prefix for org-mode files.
13837 In particular, this makes sure hanging paragraphs for hand-formatted lists
13838 work correctly."
13839 (cond ((looking-at "#[ \t]+")
13840 (match-string 0))
13841 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
13842 (save-excursion
13843 (if (> (match-end 1) (+ (match-beginning 1)
13844 org-description-max-indent))
13845 (goto-char (+ (match-beginning 1) 5))
13846 (goto-char (match-end 0)))
13847 (make-string (current-column) ?\ )))
13848 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
13849 (save-excursion
13850 (goto-char (match-end 0))
13851 (make-string (current-column) ?\ )))
13852 (t nil)))
13854 ;;; Other stuff.
13856 (defun org-toggle-fixed-width-section (arg)
13857 "Toggle the fixed-width export.
13858 If there is no active region, the QUOTE keyword at the current headline is
13859 inserted or removed. When present, it causes the text between this headline
13860 and the next to be exported as fixed-width text, and unmodified.
13861 If there is an active region, this command adds or removes a colon as the
13862 first character of this line. If the first character of a line is a colon,
13863 this line is also exported in fixed-width font."
13864 (interactive "P")
13865 (let* ((cc 0)
13866 (regionp (org-region-active-p))
13867 (beg (if regionp (region-beginning) (point)))
13868 (end (if regionp (region-end)))
13869 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
13870 (case-fold-search nil)
13871 (re "[ \t]*\\(:\\)")
13872 off)
13873 (if regionp
13874 (save-excursion
13875 (goto-char beg)
13876 (setq cc (current-column))
13877 (beginning-of-line 1)
13878 (setq off (looking-at re))
13879 (while (> nlines 0)
13880 (setq nlines (1- nlines))
13881 (beginning-of-line 1)
13882 (cond
13883 (arg
13884 (org-move-to-column cc t)
13885 (insert ":\n")
13886 (forward-line -1))
13887 ((and off (looking-at re))
13888 (replace-match "" t t nil 1))
13889 ((not off) (org-move-to-column cc t) (insert ":")))
13890 (forward-line 1)))
13891 (save-excursion
13892 (org-back-to-heading)
13893 (if (looking-at (concat outline-regexp
13894 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
13895 (replace-match "" t t nil 1)
13896 (if (looking-at outline-regexp)
13897 (progn
13898 (goto-char (match-end 0))
13899 (insert org-quote-string " "))))))))
13901 ;;;; Functions extending outline functionality
13903 (defun org-beginning-of-line (&optional arg)
13904 "Go to the beginning of the current line. If that is invisible, continue
13905 to a visible line beginning. This makes the function of C-a more intuitive.
13906 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
13907 first attempt, and only move to after the tags when the cursor is already
13908 beyond the end of the headline."
13909 (interactive "P")
13910 (let ((pos (point)) refpos)
13911 (beginning-of-line 1)
13912 (if (bobp)
13914 (backward-char 1)
13915 (if (org-invisible-p)
13916 (while (and (not (bobp)) (org-invisible-p))
13917 (backward-char 1)
13918 (beginning-of-line 1))
13919 (forward-char 1)))
13920 (when org-special-ctrl-a/e
13921 (cond
13922 ((and (looking-at org-complex-heading-regexp)
13923 (= (char-after (match-end 1)) ?\ ))
13924 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
13925 (point-at-eol)))
13926 (goto-char
13927 (if (eq org-special-ctrl-a/e t)
13928 (cond ((> pos refpos) refpos)
13929 ((= pos (point)) refpos)
13930 (t (point)))
13931 (cond ((> pos (point)) (point))
13932 ((not (eq last-command this-command)) (point))
13933 (t refpos)))))
13934 ((org-at-item-p)
13935 (goto-char
13936 (if (eq org-special-ctrl-a/e t)
13937 (cond ((> pos (match-end 4)) (match-end 4))
13938 ((= pos (point)) (match-end 4))
13939 (t (point)))
13940 (cond ((> pos (point)) (point))
13941 ((not (eq last-command this-command)) (point))
13942 (t (match-end 4))))))))
13943 (org-no-warnings
13944 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
13946 (defun org-end-of-line (&optional arg)
13947 "Go to the end of the line.
13948 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
13949 first attempt, and only move to after the tags when the cursor is already
13950 beyond the end of the headline."
13951 (interactive "P")
13952 (if (or (not org-special-ctrl-a/e)
13953 (not (org-on-heading-p)))
13954 (end-of-line arg)
13955 (let ((pos (point)))
13956 (beginning-of-line 1)
13957 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
13958 (if (eq org-special-ctrl-a/e t)
13959 (if (or (< pos (match-beginning 1))
13960 (= pos (match-end 0)))
13961 (goto-char (match-beginning 1))
13962 (goto-char (match-end 0)))
13963 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
13964 (goto-char (match-end 0))
13965 (goto-char (match-beginning 1))))
13966 (end-of-line arg))))
13967 (org-no-warnings
13968 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
13971 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
13972 (define-key org-mode-map "\C-e" 'org-end-of-line)
13974 (defun org-kill-line (&optional arg)
13975 "Kill line, to tags or end of line."
13976 (interactive "P")
13977 (cond
13978 ((or (not org-special-ctrl-k)
13979 (bolp)
13980 (not (org-on-heading-p)))
13981 (call-interactively 'kill-line))
13982 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
13983 (kill-region (point) (match-beginning 1))
13984 (org-set-tags nil t))
13985 (t (kill-region (point) (point-at-eol)))))
13987 (define-key org-mode-map "\C-k" 'org-kill-line)
13989 (defun org-yank (&optional arg)
13990 "Yank. If the kill is a subtree, treat it specially.
13991 This command will look at the current kill and check if is a single
13992 subtree, or a series of subtrees[1]. If it passes the test, and if the
13993 cursor is at the beginning of a line or after the stars of a currently
13994 empty headline, then the yank is handeled specially. How exactly depends
13995 on the value of the following variables, both set by default.
13997 org-yank-folded-subtrees
13998 When set, the subree(s) will be folded after insertion, but only
13999 if doing so would now swallow text after the yanked text.
14001 org-yank-adjusted-subtrees
14002 When set, the subtree will be promoted or demoted in order to
14003 fit into the local outline tree structure, which means that the level
14004 will be adjusted so that it becomes the smaller of the two *visible*
14005 surrounding headings.
14007 Any prefix to this command will cause `yank' to be caalled directly with
14008 no special treatment. In particular, a simple `C-u' prefix will just
14009 plainly yank the text as it is.
14011 \[1] Basically, the test checks if the first non-white line is a heading
14012 and if there are no other headings with fewer stars."
14013 (interactive "P")
14014 (if arg
14015 (call-interactively 'yank)
14016 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
14017 (and (org-kill-is-subtree-p)
14018 (or (bolp)
14019 (and (looking-at "[ \t]*$")
14020 (string-match
14021 "\\`\\*+\\'"
14022 (buffer-substring (point-at-bol) (point)))))))
14023 swallowp)
14024 (cond
14025 ((and subtreep org-yank-folded-subtrees)
14026 (let ((beg (point))
14027 end)
14028 (if (and subtreep org-yank-adjusted-subtrees)
14029 (org-paste-subtree nil nil 'for-yank)
14030 (call-interactively 'yank))
14031 (setq end (point))
14032 (goto-char beg)
14033 (when (and (bolp) subtreep
14034 (not (setq swallowp
14035 (org-yank-folding-would-swallow-text beg end))))
14036 (or (looking-at outline-regexp)
14037 (re-search-forward (concat "^" outline-regexp) end t))
14038 (while (and (< (point) end) (looking-at outline-regexp))
14039 (hide-subtree)
14040 (org-cycle-show-empty-lines 'folded)
14041 (condition-case nil
14042 (outline-forward-same-level 1)
14043 (error (goto-char end)))))
14044 (when swallowp
14045 (message
14046 "Yanked text not folded because that would swallow text"))
14047 (goto-char end)
14048 (skip-chars-forward " \t\n\r")
14049 (beginning-of-line 1)))
14050 ((and subtreep org-yank-adjusted-subtrees)
14051 (org-paste-subtree nil nil 'for-yank))
14053 (call-interactively 'yank))))))
14055 (defun org-yank-folding-would-swallow-text (beg end)
14056 "Would hide-subtree at BEG swallow any text after END?"
14057 (let (level)
14058 (save-excursion
14059 (goto-char beg)
14060 (when (or (looking-at outline-regexp)
14061 (re-search-forward (concat "^" outline-regexp) end t))
14062 (setq level (org-outline-level)))
14063 (goto-char end)
14064 (skip-chars-forward " \t\r\n\v\f")
14065 (if (or (eobp)
14066 (and (bolp) (looking-at org-outline-regexp)
14067 (<= (org-outline-level) level)))
14068 nil ; Nothing would be swallowed
14069 t)))) ; something would swallow
14071 (define-key org-mode-map "\C-y" 'org-yank)
14073 (defun org-invisible-p ()
14074 "Check if point is at a character currently not visible."
14075 ;; Early versions of noutline don't have `outline-invisible-p'.
14076 (if (fboundp 'outline-invisible-p)
14077 (outline-invisible-p)
14078 (get-char-property (point) 'invisible)))
14080 (defun org-invisible-p2 ()
14081 "Check if point is at a character currently not visible."
14082 (save-excursion
14083 (if (and (eolp) (not (bobp))) (backward-char 1))
14084 ;; Early versions of noutline don't have `outline-invisible-p'.
14085 (if (fboundp 'outline-invisible-p)
14086 (outline-invisible-p)
14087 (get-char-property (point) 'invisible))))
14089 (defalias 'org-back-to-heading 'outline-back-to-heading)
14090 (defalias 'org-on-heading-p 'outline-on-heading-p)
14091 (defalias 'org-at-heading-p 'outline-on-heading-p)
14092 (defun org-at-heading-or-item-p ()
14093 (or (org-on-heading-p) (org-at-item-p)))
14095 (defun org-on-target-p ()
14096 (or (org-in-regexp org-radio-target-regexp)
14097 (org-in-regexp org-target-regexp)))
14099 (defun org-up-heading-all (arg)
14100 "Move to the heading line of which the present line is a subheading.
14101 This function considers both visible and invisible heading lines.
14102 With argument, move up ARG levels."
14103 (if (fboundp 'outline-up-heading-all)
14104 (outline-up-heading-all arg) ; emacs 21 version of outline.el
14105 (outline-up-heading arg t))) ; emacs 22 version of outline.el
14107 (defun org-up-heading-safe ()
14108 "Move to the heading line of which the present line is a subheading.
14109 This version will not throw an error. It will return the level of the
14110 headline found, or nil if no higher level is found."
14111 (let ((pos (point)) start-level level
14112 (re (concat "^" outline-regexp)))
14113 (catch 'exit
14114 (outline-back-to-heading t)
14115 (setq start-level (funcall outline-level))
14116 (if (equal start-level 1) (throw 'exit nil))
14117 (while (re-search-backward re nil t)
14118 (setq level (funcall outline-level))
14119 (if (< level start-level) (throw 'exit level)))
14120 nil)))
14122 (defun org-first-sibling-p ()
14123 "Is this heading the first child of its parents?"
14124 (interactive)
14125 (let ((re (concat "^" outline-regexp))
14126 level l)
14127 (unless (org-at-heading-p t)
14128 (error "Not at a heading"))
14129 (setq level (funcall outline-level))
14130 (save-excursion
14131 (if (not (re-search-backward re nil t))
14133 (setq l (funcall outline-level))
14134 (< l level)))))
14136 (defun org-goto-sibling (&optional previous)
14137 "Goto the next sibling, even if it is invisible.
14138 When PREVIOUS is set, go to the previous sibling instead. Returns t
14139 when a sibling was found. When none is found, return nil and don't
14140 move point."
14141 (let ((fun (if previous 're-search-backward 're-search-forward))
14142 (pos (point))
14143 (re (concat "^" outline-regexp))
14144 level l)
14145 (when (condition-case nil (org-back-to-heading t) (error nil))
14146 (setq level (funcall outline-level))
14147 (catch 'exit
14148 (or previous (forward-char 1))
14149 (while (funcall fun re nil t)
14150 (setq l (funcall outline-level))
14151 (when (< l level) (goto-char pos) (throw 'exit nil))
14152 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
14153 (goto-char pos)
14154 nil))))
14156 (defun org-show-siblings ()
14157 "Show all siblings of the current headline."
14158 (save-excursion
14159 (while (org-goto-sibling) (org-flag-heading nil)))
14160 (save-excursion
14161 (while (org-goto-sibling 'previous)
14162 (org-flag-heading nil))))
14164 (defun org-show-hidden-entry ()
14165 "Show an entry where even the heading is hidden."
14166 (save-excursion
14167 (org-show-entry)))
14169 (defun org-flag-heading (flag &optional entry)
14170 "Flag the current heading. FLAG non-nil means make invisible.
14171 When ENTRY is non-nil, show the entire entry."
14172 (save-excursion
14173 (org-back-to-heading t)
14174 ;; Check if we should show the entire entry
14175 (if entry
14176 (progn
14177 (org-show-entry)
14178 (save-excursion
14179 (and (outline-next-heading)
14180 (org-flag-heading nil))))
14181 (outline-flag-region (max (point-min) (1- (point)))
14182 (save-excursion (outline-end-of-heading) (point))
14183 flag))))
14185 (defun org-forward-same-level (arg)
14186 "Move forward to the ARG'th subheading at same level as this one.
14187 Stop at the first and last subheadings of a superior heading.
14188 This is like outline-forward-same-level, but invisible headings are ok."
14189 (interactive "p")
14190 (outline-back-to-heading t)
14191 (while (> arg 0)
14192 (let ((point-to-move-to (save-excursion
14193 (org-get-next-sibling))))
14194 (if point-to-move-to
14195 (progn
14196 (goto-char point-to-move-to)
14197 (setq arg (1- arg)))
14198 (progn
14199 (setq arg 0)
14200 (error "No following same-level heading"))))))
14202 (defun org-get-next-sibling ()
14203 "Move to next heading of the same level, and return point.
14204 If there is no such heading, return nil.
14205 This is like outline-next-sibling, but invisible headings are ok."
14206 (let ((level (funcall outline-level)))
14207 (outline-next-heading)
14208 (while (and (not (eobp)) (> (funcall outline-level) level))
14209 (outline-next-heading))
14210 (if (or (eobp) (< (funcall outline-level) level))
14212 (point))))
14214 (defun org-end-of-subtree (&optional invisible-OK to-heading)
14215 ;; This is an exact copy of the original function, but it uses
14216 ;; `org-back-to-heading', to make it work also in invisible
14217 ;; trees. And is uses an invisible-OK argument.
14218 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
14219 (org-back-to-heading invisible-OK)
14220 (let ((first t)
14221 (level (funcall outline-level)))
14222 (while (and (not (eobp))
14223 (or first (> (funcall outline-level) level)))
14224 (setq first nil)
14225 (outline-next-heading))
14226 (unless to-heading
14227 (if (memq (preceding-char) '(?\n ?\^M))
14228 (progn
14229 ;; Go to end of line before heading
14230 (forward-char -1)
14231 (if (memq (preceding-char) '(?\n ?\^M))
14232 ;; leave blank line before heading
14233 (forward-char -1))))))
14234 (point))
14236 (defun org-show-subtree ()
14237 "Show everything after this heading at deeper levels."
14238 (outline-flag-region
14239 (point)
14240 (save-excursion
14241 (outline-end-of-subtree) (outline-next-heading) (point))
14242 nil))
14244 (defun org-show-entry ()
14245 "Show the body directly following this heading.
14246 Show the heading too, if it is currently invisible."
14247 (interactive)
14248 (save-excursion
14249 (condition-case nil
14250 (progn
14251 (org-back-to-heading t)
14252 (outline-flag-region
14253 (max (point-min) (1- (point)))
14254 (save-excursion
14255 (re-search-forward
14256 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
14257 (or (match-beginning 1) (point-max)))
14258 nil))
14259 (error nil))))
14261 (defun org-make-options-regexp (kwds)
14262 "Make a regular expression for keyword lines."
14263 (concat
14265 "#?[ \t]*\\+\\("
14266 (mapconcat 'regexp-quote kwds "\\|")
14267 "\\):[ \t]*"
14268 "\\(.+\\)"))
14270 ;; Make isearch reveal the necessary context
14271 (defun org-isearch-end ()
14272 "Reveal context after isearch exits."
14273 (when isearch-success ; only if search was successful
14274 (if (featurep 'xemacs)
14275 ;; Under XEmacs, the hook is run in the correct place,
14276 ;; we directly show the context.
14277 (org-show-context 'isearch)
14278 ;; In Emacs the hook runs *before* restoring the overlays.
14279 ;; So we have to use a one-time post-command-hook to do this.
14280 ;; (Emacs 22 has a special variable, see function `org-mode')
14281 (unless (and (boundp 'isearch-mode-end-hook-quit)
14282 isearch-mode-end-hook-quit)
14283 ;; Only when the isearch was not quitted.
14284 (org-add-hook 'post-command-hook 'org-isearch-post-command
14285 'append 'local)))))
14287 (defun org-isearch-post-command ()
14288 "Remove self from hook, and show context."
14289 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
14290 (org-show-context 'isearch))
14293 ;;;; Integration with and fixes for other packages
14295 ;;; Imenu support
14297 (defvar org-imenu-markers nil
14298 "All markers currently used by Imenu.")
14299 (make-variable-buffer-local 'org-imenu-markers)
14301 (defun org-imenu-new-marker (&optional pos)
14302 "Return a new marker for use by Imenu, and remember the marker."
14303 (let ((m (make-marker)))
14304 (move-marker m (or pos (point)))
14305 (push m org-imenu-markers)
14308 (defun org-imenu-get-tree ()
14309 "Produce the index for Imenu."
14310 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
14311 (setq org-imenu-markers nil)
14312 (let* ((n org-imenu-depth)
14313 (re (concat "^" outline-regexp))
14314 (subs (make-vector (1+ n) nil))
14315 (last-level 0)
14316 m tree level head)
14317 (save-excursion
14318 (save-restriction
14319 (widen)
14320 (goto-char (point-max))
14321 (while (re-search-backward re nil t)
14322 (setq level (org-reduced-level (funcall outline-level)))
14323 (when (<= level n)
14324 (looking-at org-complex-heading-regexp)
14325 (setq head (org-link-display-format
14326 (org-match-string-no-properties 4))
14327 m (org-imenu-new-marker))
14328 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
14329 (if (>= level last-level)
14330 (push (cons head m) (aref subs level))
14331 (push (cons head (aref subs (1+ level))) (aref subs level))
14332 (loop for i from (1+ level) to n do (aset subs i nil)))
14333 (setq last-level level)))))
14334 (aref subs 1)))
14336 (eval-after-load "imenu"
14337 '(progn
14338 (add-hook 'imenu-after-jump-hook
14339 (lambda ()
14340 (if (eq major-mode 'org-mode)
14341 (org-show-context 'org-goto))))))
14343 (defun org-link-display-format (link)
14344 "Replace a link with either the description, or the link target
14345 if no description is present"
14346 (save-match-data
14347 (if (string-match org-bracket-link-analytic-regexp link)
14348 (replace-match (or (match-string 5 link)
14349 (concat (match-string 1 link)
14350 (match-string 3 link)))
14351 nil nil link)
14352 link)))
14354 ;; Speedbar support
14356 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
14357 "Overlay marking the agenda restriction line in speedbar.")
14358 (org-overlay-put org-speedbar-restriction-lock-overlay
14359 'face 'org-agenda-restriction-lock)
14360 (org-overlay-put org-speedbar-restriction-lock-overlay
14361 'help-echo "Agendas are currently limited to this item.")
14362 (org-detach-overlay org-speedbar-restriction-lock-overlay)
14364 (defun org-speedbar-set-agenda-restriction ()
14365 "Restrict future agenda commands to the location at point in speedbar.
14366 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
14367 (interactive)
14368 (require 'org-agenda)
14369 (let (p m tp np dir txt w)
14370 (cond
14371 ((setq p (text-property-any (point-at-bol) (point-at-eol)
14372 'org-imenu t))
14373 (setq m (get-text-property p 'org-imenu-marker))
14374 (save-excursion
14375 (save-restriction
14376 (set-buffer (marker-buffer m))
14377 (goto-char m)
14378 (org-agenda-set-restriction-lock 'subtree))))
14379 ((setq p (text-property-any (point-at-bol) (point-at-eol)
14380 'speedbar-function 'speedbar-find-file))
14381 (setq tp (previous-single-property-change
14382 (1+ p) 'speedbar-function)
14383 np (next-single-property-change
14384 tp 'speedbar-function)
14385 dir (speedbar-line-directory)
14386 txt (buffer-substring-no-properties (or tp (point-min))
14387 (or np (point-max))))
14388 (save-excursion
14389 (save-restriction
14390 (set-buffer (find-file-noselect
14391 (let ((default-directory dir))
14392 (expand-file-name txt))))
14393 (unless (org-mode-p)
14394 (error "Cannot restrict to non-Org-mode file"))
14395 (org-agenda-set-restriction-lock 'file))))
14396 (t (error "Don't know how to restrict Org-mode's agenda")))
14397 (org-move-overlay org-speedbar-restriction-lock-overlay
14398 (point-at-bol) (point-at-eol))
14399 (setq current-prefix-arg nil)
14400 (org-agenda-maybe-redo)))
14402 (eval-after-load "speedbar"
14403 '(progn
14404 (speedbar-add-supported-extension ".org")
14405 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
14406 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
14407 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
14408 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
14409 (add-hook 'speedbar-visiting-tag-hook
14410 (lambda () (org-show-context 'org-goto)))))
14413 ;;; Fixes and Hacks for problems with other packages
14415 ;; Make flyspell not check words in links, to not mess up our keymap
14416 (defun org-mode-flyspell-verify ()
14417 "Don't let flyspell put overlays at active buttons."
14418 (not (get-text-property (point) 'keymap)))
14420 ;; Make `bookmark-jump' show the jump location if it was hidden.
14421 (eval-after-load "bookmark"
14422 '(if (boundp 'bookmark-after-jump-hook)
14423 ;; We can use the hook
14424 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
14425 ;; Hook not available, use advice
14426 (defadvice bookmark-jump (after org-make-visible activate)
14427 "Make the position visible."
14428 (org-bookmark-jump-unhide))))
14430 ;; Make sure saveplace show the location if it was hidden
14431 (eval-after-load "saveplace"
14432 '(defadvice save-place-find-file-hook (after org-make-visible activate)
14433 "Make the position visible."
14434 (org-bookmark-jump-unhide)))
14436 (defun org-bookmark-jump-unhide ()
14437 "Unhide the current position, to show the bookmark location."
14438 (and (org-mode-p)
14439 (or (org-invisible-p)
14440 (save-excursion (goto-char (max (point-min) (1- (point))))
14441 (org-invisible-p)))
14442 (org-show-context 'bookmark-jump)))
14444 ;; Make session.el ignore our circular variable
14445 (eval-after-load "session"
14446 '(add-to-list 'session-globals-exclude 'org-mark-ring))
14448 ;;;; Experimental code
14450 (defun org-closed-in-range ()
14451 "Sparse tree of items closed in a certain time range.
14452 Still experimental, may disappear in the future."
14453 (interactive)
14454 ;; Get the time interval from the user.
14455 (let* ((time1 (time-to-seconds
14456 (org-read-date nil 'to-time nil "Starting date: ")))
14457 (time2 (time-to-seconds
14458 (org-read-date nil 'to-time nil "End date:")))
14459 ;; callback function
14460 (callback (lambda ()
14461 (let ((time
14462 (time-to-seconds
14463 (apply 'encode-time
14464 (org-parse-time-string
14465 (match-string 1))))))
14466 ;; check if time in interval
14467 (and (>= time time1) (<= time time2))))))
14468 ;; make tree, check each match with the callback
14469 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
14472 ;;;; Finish up
14474 (provide 'org)
14476 (run-hooks 'org-load-hook)
14478 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
14480 ;;; org.el ends here