Introduce function to create links to attachments.
[org-mode/org-tableheadings.git] / lisp / org.el
blob6caf9c19f8a2589318bdada2909a5beb2c512623
1 ;;; org.el --- Outline-based notes management and organizer
2 ;; Carstens outline-mode for keeping track of everything.
3 ;; Copyright (C) 2004, 2005, 2006, 2007, 2008 Free Software Foundation, Inc.
4 ;;
5 ;; Author: Carsten Dominik <carsten at orgmode dot org>
6 ;; Keywords: outlines, hypermedia, calendar, wp
7 ;; Homepage: http://orgmode.org
8 ;; Version: 6.10c
9 ;;
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
24 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
26 ;;; Commentary:
28 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
29 ;; project planning with a fast and effective plain-text system.
31 ;; Org-mode develops organizational tasks around NOTES files that contain
32 ;; information about projects as plain text. Org-mode is implemented on
33 ;; top of outline-mode, which makes it possible to keep the content of
34 ;; large files well structured. Visibility cycling and structure editing
35 ;; help to work with the tree. Tables are easily created with a built-in
36 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
37 ;; and scheduling. It dynamically compiles entries into an agenda that
38 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
39 ;; Plain text URL-like links connect to websites, emails, Usenet
40 ;; messages, BBDB entries, and any files related to the projects. For
41 ;; printing and sharing of notes, an Org-mode file can be exported as a
42 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
43 ;; iCalendar file. It can also serve as a publishing tool for a set of
44 ;; linked webpages.
46 ;; Installation and Activation
47 ;; ---------------------------
48 ;; See the corresponding sections in the manual at
50 ;; http://orgmode.org/org.html#Installation
52 ;; Documentation
53 ;; -------------
54 ;; The documentation of Org-mode can be found in the TeXInfo file. The
55 ;; distribution also contains a PDF version of it. At the homepage of
56 ;; Org-mode, you can read the same text online as HTML. There is also an
57 ;; excellent reference card made by Philip Rooke. This card can be found
58 ;; in the etc/ directory of Emacs 22.
60 ;; A list of recent changes can be found at
61 ;; http://orgmode.org/Changes.html
63 ;;; Code:
65 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
66 (defvar org-table-formula-constants-local nil
67 "Local version of `org-table-formula-constants'.")
68 (make-variable-buffer-local 'org-table-formula-constants-local)
70 ;;;; Require other packages
72 (eval-when-compile
73 (require 'cl)
74 (require 'gnus-sum)
75 (require 'calendar))
76 ;; For XEmacs, noutline is not yet provided by outline.el, so arrange for
77 ;; the file noutline.el being loaded.
78 (if (featurep 'xemacs) (condition-case nil (require 'noutline)))
79 ;; We require noutline, which might be provided in outline.el
80 (require 'outline) (require 'noutline)
81 ;; Other stuff we need.
82 (require 'time-date)
83 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
84 (require 'easymenu)
86 (require 'org-macs)
87 (require 'org-compat)
88 (require 'org-faces)
89 (require 'org-list)
91 ;;;; Customization variables
93 ;;; Version
95 (defconst org-version "6.10c"
96 "The version number of the file org.el.")
98 (defun org-version (&optional here)
99 "Show the org-mode version in the echo area.
100 With prefix arg HERE, insert it at point."
101 (interactive "P")
102 (let ((version (format "Org-mode version %s" org-version)))
103 (message version)
104 (if here
105 (insert version))))
107 ;;; Compatibility constants
109 ;;; The custom variables
111 (defgroup org nil
112 "Outline-based notes management and organizer."
113 :tag "Org"
114 :group 'outlines
115 :group 'hypermedia
116 :group 'calendar)
118 (defcustom org-load-hook nil
119 "Hook that is run after org.el has been loaded."
120 :group 'org
121 :type 'hook)
123 (defvar org-modules) ; defined below
124 (defvar org-modules-loaded nil
125 "Have the modules been loaded already?")
127 (defun org-load-modules-maybe (&optional force)
128 "Load all extensions listed in `org-default-extensions'."
129 (when (or force (not org-modules-loaded))
130 (mapc (lambda (ext)
131 (condition-case nil (require ext)
132 (error (message "Problems while trying to load feature `%s'" ext))))
133 org-modules)
134 (setq org-modules-loaded t)))
136 (defun org-set-modules (var value)
137 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
138 (set var value)
139 (when (featurep 'org)
140 (org-load-modules-maybe 'force)))
142 (when (org-bound-and-true-p org-modules)
143 (let ((a (member 'org-infojs org-modules)))
144 (and a (setcar a 'org-jsinfo))))
146 (defcustom org-modules '(org-bbdb org-bibtex org-gnus org-info org-jsinfo org-irc org-mew org-mhe org-rmail org-vm org-wl)
147 "Modules that should always be loaded together with org.el.
148 If a description starts with <C>, the file is not part of Emacs
149 and loading it will require that you have downloaded and properly installed
150 the org-mode distribution.
152 You can also use this system to load external packages (i.e. neither Org
153 core modules, not modules from the CONTRIB directory). Just add symbols
154 to the end of the list. If the package is called org-xyz.el, then you need
155 to add the symbol `xyz', and the package must have a call to
157 (provide 'org-xyz)"
158 :group 'org
159 :set 'org-set-modules
160 :type
161 '(set :greedy t
162 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
163 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
164 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
165 (const :tag " id: Global id's for identifying entries" org-id)
166 (const :tag " info: Links to Info nodes" org-info)
167 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
168 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
169 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
170 (const :tag " mew Links to Mew folders/messages" org-mew)
171 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
172 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
173 (const :tag " vm: Links to VM folders/messages" org-vm)
174 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
175 (const :tag " mouse: Additional mouse support" org-mouse)
177 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
178 (const :tag "C annotation-helper: Call Remeber directly from Browser" org-annotation-helper)
179 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
180 (const :tag "C depend: TODO dependencies for Org-mode" org-depend)
181 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
182 (const :tag "C eval: Include command output as text" org-eval)
183 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
184 (const :tag "C id: Global id's for identifying entries" org-id)
185 (const :tag "C interactive-query: Interactive modification of tags query" org-interactive-query)
186 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
187 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
188 (const :tag "C mtags: Support for muse-like tags" org-mtags)
189 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
190 (const :tag "C registry: A registry for Org links" org-registry)
191 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
192 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
193 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
194 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
195 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
198 (defgroup org-startup nil
199 "Options concerning startup of Org-mode."
200 :tag "Org Startup"
201 :group 'org)
203 (defcustom org-startup-folded t
204 "Non-nil means, entering Org-mode will switch to OVERVIEW.
205 This can also be configured on a per-file basis by adding one of
206 the following lines anywhere in the buffer:
208 #+STARTUP: fold
209 #+STARTUP: nofold
210 #+STARTUP: content"
211 :group 'org-startup
212 :type '(choice
213 (const :tag "nofold: show all" nil)
214 (const :tag "fold: overview" t)
215 (const :tag "content: all headlines" content)))
217 (defcustom org-startup-truncated t
218 "Non-nil means, entering Org-mode will set `truncate-lines'.
219 This is useful since some lines containing links can be very long and
220 uninteresting. Also tables look terrible when wrapped."
221 :group 'org-startup
222 :type 'boolean)
224 (defcustom org-startup-align-all-tables nil
225 "Non-nil means, align all tables when visiting a file.
226 This is useful when the column width in tables is forced with <N> cookies
227 in table fields. Such tables will look correct only after the first re-align.
228 This can also be configured on a per-file basis by adding one of
229 the following lines anywhere in the buffer:
230 #+STARTUP: align
231 #+STARTUP: noalign"
232 :group 'org-startup
233 :type 'boolean)
235 (defcustom org-insert-mode-line-in-empty-file nil
236 "Non-nil means insert the first line setting Org-mode in empty files.
237 When the function `org-mode' is called interactively in an empty file, this
238 normally means that the file name does not automatically trigger Org-mode.
239 To ensure that the file will always be in Org-mode in the future, a
240 line enforcing Org-mode will be inserted into the buffer, if this option
241 has been set."
242 :group 'org-startup
243 :type 'boolean)
245 (defcustom org-replace-disputed-keys nil
246 "Non-nil means use alternative key bindings for some keys.
247 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
248 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
249 If you want to use Org-mode together with one of these other modes,
250 or more generally if you would like to move some Org-mode commands to
251 other keys, set this variable and configure the keys with the variable
252 `org-disputed-keys'.
254 This option is only relevant at load-time of Org-mode, and must be set
255 *before* org.el is loaded. Changing it requires a restart of Emacs to
256 become effective."
257 :group 'org-startup
258 :type 'boolean)
260 (defcustom org-use-extra-keys nil
261 "Non-nil means use extra key sequence definitions for certain
262 commands. This happens automatically if you run XEmacs or if
263 window-system is nil. This variable lets you do the same
264 manually. You must set it before loading org.
266 Example: on Carbon Emacs 22 running graphically, with an external
267 keyboard on a Powerbook, the default way of setting M-left might
268 not work for either Alt or ESC. Setting this variable will make
269 it work for ESC."
270 :group 'org-startup
271 :type 'boolean)
273 (if (fboundp 'defvaralias)
274 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
276 (defcustom org-disputed-keys
277 '(([(shift up)] . [(meta p)])
278 ([(shift down)] . [(meta n)])
279 ([(shift left)] . [(meta -)])
280 ([(shift right)] . [(meta +)])
281 ([(control shift right)] . [(meta shift +)])
282 ([(control shift left)] . [(meta shift -)]))
283 "Keys for which Org-mode and other modes compete.
284 This is an alist, cars are the default keys, second element specifies
285 the alternative to use when `org-replace-disputed-keys' is t.
287 Keys can be specified in any syntax supported by `define-key'.
288 The value of this option takes effect only at Org-mode's startup,
289 therefore you'll have to restart Emacs to apply it after changing."
290 :group 'org-startup
291 :type 'alist)
293 (defun org-key (key)
294 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
295 Or return the original if not disputed."
296 (if org-replace-disputed-keys
297 (let* ((nkey (key-description key))
298 (x (org-find-if (lambda (x)
299 (equal (key-description (car x)) nkey))
300 org-disputed-keys)))
301 (if x (cdr x) key))
302 key))
304 (defun org-find-if (predicate seq)
305 (catch 'exit
306 (while seq
307 (if (funcall predicate (car seq))
308 (throw 'exit (car seq))
309 (pop seq)))))
311 (defun org-defkey (keymap key def)
312 "Define a key, possibly translated, as returned by `org-key'."
313 (define-key keymap (org-key key) def))
315 (defcustom org-ellipsis nil
316 "The ellipsis to use in the Org-mode outline.
317 When nil, just use the standard three dots. When a string, use that instead,
318 When a face, use the standart 3 dots, but with the specified face.
319 The change affects only Org-mode (which will then use its own display table).
320 Changing this requires executing `M-x org-mode' in a buffer to become
321 effective."
322 :group 'org-startup
323 :type '(choice (const :tag "Default" nil)
324 (face :tag "Face" :value org-warning)
325 (string :tag "String" :value "...#")))
327 (defvar org-display-table nil
328 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
330 (defgroup org-keywords nil
331 "Keywords in Org-mode."
332 :tag "Org Keywords"
333 :group 'org)
335 (defcustom org-deadline-string "DEADLINE:"
336 "String to mark deadline entries.
337 A deadline is this string, followed by a time stamp. Should be a word,
338 terminated by a colon. You can insert a schedule keyword and
339 a timestamp with \\[org-deadline].
340 Changes become only effective after restarting Emacs."
341 :group 'org-keywords
342 :type 'string)
344 (defcustom org-scheduled-string "SCHEDULED:"
345 "String to mark scheduled TODO entries.
346 A schedule is this string, followed by a time stamp. Should be a word,
347 terminated by a colon. You can insert a schedule keyword and
348 a timestamp with \\[org-schedule].
349 Changes become only effective after restarting Emacs."
350 :group 'org-keywords
351 :type 'string)
353 (defcustom org-closed-string "CLOSED:"
354 "String used as the prefix for timestamps logging closing a TODO entry."
355 :group 'org-keywords
356 :type 'string)
358 (defcustom org-clock-string "CLOCK:"
359 "String used as prefix for timestamps clocking work hours on an item."
360 :group 'org-keywords
361 :type 'string)
363 (defcustom org-comment-string "COMMENT"
364 "Entries starting with this keyword will never be exported.
365 An entry can be toggled between COMMENT and normal with
366 \\[org-toggle-comment].
367 Changes become only effective after restarting Emacs."
368 :group 'org-keywords
369 :type 'string)
371 (defcustom org-quote-string "QUOTE"
372 "Entries starting with this keyword will be exported in fixed-width font.
373 Quoting applies only to the text in the entry following the headline, and does
374 not extend beyond the next headline, even if that is lower level.
375 An entry can be toggled between QUOTE and normal with
376 \\[org-toggle-fixed-width-section]."
377 :group 'org-keywords
378 :type 'string)
380 (defconst org-repeat-re
381 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\([.+]?\\+[0-9]+[dwmy]\\)"
382 "Regular expression for specifying repeated events.
383 After a match, group 1 contains the repeat expression.")
385 (defgroup org-structure nil
386 "Options concerning the general structure of Org-mode files."
387 :tag "Org Structure"
388 :group 'org)
390 (defgroup org-reveal-location nil
391 "Options about how to make context of a location visible."
392 :tag "Org Reveal Location"
393 :group 'org-structure)
395 (defconst org-context-choice
396 '(choice
397 (const :tag "Always" t)
398 (const :tag "Never" nil)
399 (repeat :greedy t :tag "Individual contexts"
400 (cons
401 (choice :tag "Context"
402 (const agenda)
403 (const org-goto)
404 (const occur-tree)
405 (const tags-tree)
406 (const link-search)
407 (const mark-goto)
408 (const bookmark-jump)
409 (const isearch)
410 (const default))
411 (boolean))))
412 "Contexts for the reveal options.")
414 (defcustom org-show-hierarchy-above '((default . t))
415 "Non-nil means, show full hierarchy when revealing a location.
416 Org-mode often shows locations in an org-mode file which might have
417 been invisible before. When this is set, the hierarchy of headings
418 above the exposed location is shown.
419 Turning this off for example for sparse trees makes them very compact.
420 Instead of t, this can also be an alist specifying this option for different
421 contexts. Valid contexts are
422 agenda when exposing an entry from the agenda
423 org-goto when using the command `org-goto' on key C-c C-j
424 occur-tree when using the command `org-occur' on key C-c /
425 tags-tree when constructing a sparse tree based on tags matches
426 link-search when exposing search matches associated with a link
427 mark-goto when exposing the jump goal of a mark
428 bookmark-jump when exposing a bookmark location
429 isearch when exiting from an incremental search
430 default default for all contexts not set explicitly"
431 :group 'org-reveal-location
432 :type org-context-choice)
434 (defcustom org-show-following-heading '((default . nil))
435 "Non-nil means, show following heading when revealing a location.
436 Org-mode often shows locations in an org-mode file which might have
437 been invisible before. When this is set, the heading following the
438 match is shown.
439 Turning this off for example for sparse trees makes them very compact,
440 but makes it harder to edit the location of the match. In such a case,
441 use the command \\[org-reveal] to show more context.
442 Instead of t, this can also be an alist specifying this option for different
443 contexts. See `org-show-hierarchy-above' for valid contexts."
444 :group 'org-reveal-location
445 :type org-context-choice)
447 (defcustom org-show-siblings '((default . nil) (isearch t))
448 "Non-nil means, show all sibling heading when revealing a location.
449 Org-mode often shows locations in an org-mode file which might have
450 been invisible before. When this is set, the sibling of the current entry
451 heading are all made visible. If `org-show-hierarchy-above' is t,
452 the same happens on each level of the hierarchy above the current entry.
454 By default this is on for the isearch context, off for all other contexts.
455 Turning this off for example for sparse trees makes them very compact,
456 but makes it harder to edit the location of the match. In such a case,
457 use the command \\[org-reveal] to show more context.
458 Instead of t, this can also be an alist specifying this option for different
459 contexts. See `org-show-hierarchy-above' for valid contexts."
460 :group 'org-reveal-location
461 :type org-context-choice)
463 (defcustom org-show-entry-below '((default . nil))
464 "Non-nil means, show the entry below a headline when revealing a location.
465 Org-mode often shows locations in an org-mode file which might have
466 been invisible before. When this is set, the text below the headline that is
467 exposed is also shown.
469 By default this is off for all contexts.
470 Instead of t, this can also be an alist specifying this option for different
471 contexts. See `org-show-hierarchy-above' for valid contexts."
472 :group 'org-reveal-location
473 :type org-context-choice)
475 (defcustom org-indirect-buffer-display 'other-window
476 "How should indirect tree buffers be displayed?
477 This applies to indirect buffers created with the commands
478 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
479 Valid values are:
480 current-window Display in the current window
481 other-window Just display in another window.
482 dedicated-frame Create one new frame, and re-use it each time.
483 new-frame Make a new frame each time. Note that in this case
484 previously-made indirect buffers are kept, and you need to
485 kill these buffers yourself."
486 :group 'org-structure
487 :group 'org-agenda-windows
488 :type '(choice
489 (const :tag "In current window" current-window)
490 (const :tag "In current frame, other window" other-window)
491 (const :tag "Each time a new frame" new-frame)
492 (const :tag "One dedicated frame" dedicated-frame)))
494 (defgroup org-cycle nil
495 "Options concerning visibility cycling in Org-mode."
496 :tag "Org Cycle"
497 :group 'org-structure)
499 (defcustom org-drawers '("PROPERTIES" "CLOCK")
500 "Names of drawers. Drawers are not opened by cycling on the headline above.
501 Drawers only open with a TAB on the drawer line itself. A drawer looks like
502 this:
503 :DRAWERNAME:
504 .....
505 :END:
506 The drawer \"PROPERTIES\" is special for capturing properties through
507 the property API.
509 Drawers can be defined on the per-file basis with a line like:
511 #+DRAWERS: HIDDEN STATE PROPERTIES"
512 :group 'org-structure
513 :type '(repeat (string :tag "Drawer Name")))
515 (defcustom org-cycle-global-at-bob nil
516 "Cycle globally if cursor is at beginning of buffer and not at a headline.
517 This makes it possible to do global cycling without having to use S-TAB or
518 C-u TAB. For this special case to work, the first line of the buffer
519 must not be a headline - it may be empty ot some other text. When used in
520 this way, `org-cycle-hook' is disables temporarily, to make sure the
521 cursor stays at the beginning of the buffer.
522 When this option is nil, don't do anything special at the beginning
523 of the buffer."
524 :group 'org-cycle
525 :type 'boolean)
527 (defcustom org-cycle-emulate-tab t
528 "Where should `org-cycle' emulate TAB.
529 nil Never
530 white Only in completely white lines
531 whitestart Only at the beginning of lines, before the first non-white char
532 t Everywhere except in headlines
533 exc-hl-bol Everywhere except at the start of a headline
534 If TAB is used in a place where it does not emulate TAB, the current subtree
535 visibility is cycled."
536 :group 'org-cycle
537 :type '(choice (const :tag "Never" nil)
538 (const :tag "Only in completely white lines" white)
539 (const :tag "Before first char in a line" whitestart)
540 (const :tag "Everywhere except in headlines" t)
541 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
544 (defcustom org-cycle-separator-lines 2
545 "Number of empty lines needed to keep an empty line between collapsed trees.
546 If you leave an empty line between the end of a subtree and the following
547 headline, this empty line is hidden when the subtree is folded.
548 Org-mode will leave (exactly) one empty line visible if the number of
549 empty lines is equal or larger to the number given in this variable.
550 So the default 2 means, at least 2 empty lines after the end of a subtree
551 are needed to produce free space between a collapsed subtree and the
552 following headline.
554 Special case: when 0, never leave empty lines in collapsed view."
555 :group 'org-cycle
556 :type 'integer)
557 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
559 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
560 org-cycle-hide-drawers
561 org-cycle-show-empty-lines
562 org-optimize-window-after-visibility-change)
563 "Hook that is run after `org-cycle' has changed the buffer visibility.
564 The function(s) in this hook must accept a single argument which indicates
565 the new state that was set by the most recent `org-cycle' command. The
566 argument is a symbol. After a global state change, it can have the values
567 `overview', `content', or `all'. After a local state change, it can have
568 the values `folded', `children', or `subtree'."
569 :group 'org-cycle
570 :type 'hook)
572 (defgroup org-edit-structure nil
573 "Options concerning structure editing in Org-mode."
574 :tag "Org Edit Structure"
575 :group 'org-structure)
577 (defcustom org-odd-levels-only nil
578 "Non-nil means, skip even levels and only use odd levels for the outline.
579 This has the effect that two stars are being added/taken away in
580 promotion/demotion commands. It also influences how levels are
581 handled by the exporters.
582 Changing it requires restart of `font-lock-mode' to become effective
583 for fontification also in regions already fontified.
584 You may also set this on a per-file basis by adding one of the following
585 lines to the buffer:
587 #+STARTUP: odd
588 #+STARTUP: oddeven"
589 :group 'org-edit-structure
590 :group 'org-font-lock
591 :type 'boolean)
593 (defcustom org-adapt-indentation t
594 "Non-nil means, adapt indentation when promoting and demoting.
595 When this is set and the *entire* text in an entry is indented, the
596 indentation is increased by one space in a demotion command, and
597 decreased by one in a promotion command. If any line in the entry
598 body starts at column 0, indentation is not changed at all."
599 :group 'org-edit-structure
600 :type 'boolean)
602 (defcustom org-special-ctrl-a/e nil
603 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
604 When t, `C-a' will bring back the cursor to the beginning of the
605 headline text, i.e. after the stars and after a possible TODO keyword.
606 In an item, this will be the position after the bullet.
607 When the cursor is already at that position, another `C-a' will bring
608 it to the beginning of the line.
609 `C-e' will jump to the end of the headline, ignoring the presence of tags
610 in the headline. A second `C-e' will then jump to the true end of the
611 line, after any tags.
612 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
613 and only a directly following, identical keypress will bring the cursor
614 to the special positions."
615 :group 'org-edit-structure
616 :type '(choice
617 (const :tag "off" nil)
618 (const :tag "after bullet first" t)
619 (const :tag "border first" reversed)))
621 (if (fboundp 'defvaralias)
622 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
624 (defcustom org-special-ctrl-k nil
625 "Non-nil means `C-k' will behave specially in headlines.
626 When nil, `C-k' will call the default `kill-line' command.
627 When t, the following will happen while the cursor is in the headline:
629 - When the cursor is at the beginning of a headline, kill the entire
630 line and possible the folded subtree below the line.
631 - When in the middle of the headline text, kill the headline up to the tags.
632 - When after the headline text, kill the tags."
633 :group 'org-edit-structure
634 :type 'boolean)
636 (defcustom org-yank-folded-subtrees t
637 "Non-nil means, when yanking subtrees, fold them.
638 If the kill is a single subtree, or a sequence of subtrees, i.e. if
639 it starts with a heading and all other headings in it are either children
640 or siblings, then fold all the subtrees."
641 :group 'org-edit-structure
642 :type 'boolean)
644 (defcustom org-yank-adjusted-subtrees t
645 "Non-nil means, when yanking subtrees, adjust the level.
646 With this setting, `org-paste-subtree' is used to insert the subtree, see
647 this function for details."
648 :group 'org-edit-structure
649 :type 'boolean)
651 (defcustom org-M-RET-may-split-line '((default . t))
652 "Non-nil means, M-RET will split the line at the cursor position.
653 When nil, it will go to the end of the line before making a
654 new line.
655 You may also set this option in a different way for different
656 contexts. Valid contexts are:
658 headline when creating a new headline
659 item when creating a new item
660 table in a table field
661 default the value to be used for all contexts not explicitly
662 customized"
663 :group 'org-structure
664 :group 'org-table
665 :type '(choice
666 (const :tag "Always" t)
667 (const :tag "Never" nil)
668 (repeat :greedy t :tag "Individual contexts"
669 (cons
670 (choice :tag "Context"
671 (const headline)
672 (const item)
673 (const table)
674 (const default))
675 (boolean)))))
678 (defcustom org-insert-heading-respect-content nil
679 "Non-nil means, insert new headings after the current subtree.
680 When nil, the new heading is created directly after the current line.
681 The commands \\[org-insert-heading-respect-content] and
682 \\[org-insert-todo-heading-respect-content] turn this variable on
683 for the duration of the command."
684 :group 'org-structure
685 :type 'boolean)
687 (defcustom org-blank-before-new-entry '((heading . nil)
688 (plain-list-item . nil))
689 "Should `org-insert-heading' leave a blank line before new heading/item?
690 The value is an alist, with `heading' and `plain-list-item' as car,
691 and a boolean flag as cdr."
692 :group 'org-edit-structure
693 :type '(list
694 (cons (const heading) (boolean))
695 (cons (const plain-list-item) (boolean))))
697 (defcustom org-insert-heading-hook nil
698 "Hook being run after inserting a new heading."
699 :group 'org-edit-structure
700 :type 'hook)
702 (defcustom org-enable-fixed-width-editor t
703 "Non-nil means, lines starting with \":\" are treated as fixed-width.
704 This currently only means, they are never auto-wrapped.
705 When nil, such lines will be treated like ordinary lines.
706 See also the QUOTE keyword."
707 :group 'org-edit-structure
708 :type 'boolean)
710 (defcustom org-edit-src-region-extra nil
711 "Additional regexps to identify regions for editing with `org-edit-src-code'.
712 For examples see the function `org-edit-src-find-region-and-lang'.
713 The regular expression identifying the begin marker should end with a newline,
714 and the regexp marking the end line should start with a newline, to make sure
715 there are kept outside the narrowed region."
716 :group 'org-edit-structure
717 :type '(repeat
718 (list
719 (regexp :tag "begin regexp")
720 (regexp :tag "end regexp")
721 (choice :tag "language"
722 (string :tag "specify")
723 (integer :tag "from match group")
724 (const :tag "from `lang' element")
725 (const :tag "from `style' element")))))
727 (defcustom org-edit-fixed-width-region-mode 'artist-mode
728 "The mode that should be used to edit fixed-width regions.
729 These are the regions where each line starts with a colon."
730 :group 'org-edit-structure
731 :type '(choice
732 (const artist-mode)
733 (const picture-mode)
734 (const fundamental-mode)
735 (function :tag "Other (specify)")))
737 (defcustom org-goto-auto-isearch t
738 "Non-nil means, typing characters in org-goto starts incremental search."
739 :group 'org-edit-structure
740 :type 'boolean)
742 (defgroup org-sparse-trees nil
743 "Options concerning sparse trees in Org-mode."
744 :tag "Org Sparse Trees"
745 :group 'org-structure)
747 (defcustom org-highlight-sparse-tree-matches t
748 "Non-nil means, highlight all matches that define a sparse tree.
749 The highlights will automatically disappear the next time the buffer is
750 changed by an edit command."
751 :group 'org-sparse-trees
752 :type 'boolean)
754 (defcustom org-remove-highlights-with-change t
755 "Non-nil means, any change to the buffer will remove temporary highlights.
756 Such highlights are created by `org-occur' and `org-clock-display'.
757 When nil, `C-c C-c needs to be used to get rid of the highlights.
758 The highlights created by `org-preview-latex-fragment' always need
759 `C-c C-c' to be removed."
760 :group 'org-sparse-trees
761 :group 'org-time
762 :type 'boolean)
765 (defcustom org-occur-hook '(org-first-headline-recenter)
766 "Hook that is run after `org-occur' has constructed a sparse tree.
767 This can be used to recenter the window to show as much of the structure
768 as possible."
769 :group 'org-sparse-trees
770 :type 'hook)
772 (defgroup org-imenu-and-speedbar nil
773 "Options concerning imenu and speedbar in Org-mode."
774 :tag "Org Imenu and Speedbar"
775 :group 'org-structure)
777 (defcustom org-imenu-depth 2
778 "The maximum level for Imenu access to Org-mode headlines.
779 This also applied for speedbar access."
780 :group 'org-imenu-and-speedbar
781 :type 'number)
783 (defgroup org-table nil
784 "Options concerning tables in Org-mode."
785 :tag "Org Table"
786 :group 'org)
788 (defcustom org-enable-table-editor 'optimized
789 "Non-nil means, lines starting with \"|\" are handled by the table editor.
790 When nil, such lines will be treated like ordinary lines.
792 When equal to the symbol `optimized', the table editor will be optimized to
793 do the following:
794 - Automatic overwrite mode in front of whitespace in table fields.
795 This makes the structure of the table stay in tact as long as the edited
796 field does not exceed the column width.
797 - Minimize the number of realigns. Normally, the table is aligned each time
798 TAB or RET are pressed to move to another field. With optimization this
799 happens only if changes to a field might have changed the column width.
800 Optimization requires replacing the functions `self-insert-command',
801 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
802 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
803 very good at guessing when a re-align will be necessary, but you can always
804 force one with \\[org-ctrl-c-ctrl-c].
806 If you would like to use the optimized version in Org-mode, but the
807 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
809 This variable can be used to turn on and off the table editor during a session,
810 but in order to toggle optimization, a restart is required.
812 See also the variable `org-table-auto-blank-field'."
813 :group 'org-table
814 :type '(choice
815 (const :tag "off" nil)
816 (const :tag "on" t)
817 (const :tag "on, optimized" optimized)))
819 (defcustom org-table-tab-recognizes-table.el t
820 "Non-nil means, TAB will automatically notice a table.el table.
821 When it sees such a table, it moves point into it and - if necessary -
822 calls `table-recognize-table'."
823 :group 'org-table-editing
824 :type 'boolean)
826 (defgroup org-link nil
827 "Options concerning links in Org-mode."
828 :tag "Org Link"
829 :group 'org)
831 (defvar org-link-abbrev-alist-local nil
832 "Buffer-local version of `org-link-abbrev-alist', which see.
833 The value of this is taken from the #+LINK lines.")
834 (make-variable-buffer-local 'org-link-abbrev-alist-local)
836 (defcustom org-link-abbrev-alist nil
837 "Alist of link abbreviations.
838 The car of each element is a string, to be replaced at the start of a link.
839 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
840 links in Org-mode buffers can have an optional tag after a double colon, e.g.
842 [[linkkey:tag][description]]
844 If REPLACE is a string, the tag will simply be appended to create the link.
845 If the string contains \"%s\", the tag will be inserted there.
847 REPLACE may also be a function that will be called with the tag as the
848 only argument to create the link, which should be returned as a string.
850 See the manual for examples."
851 :group 'org-link
852 :type '(repeat
853 (cons
854 (string :tag "Protocol")
855 (choice
856 (string :tag "Format")
857 (function)))))
859 (defcustom org-descriptive-links t
860 "Non-nil means, hide link part and only show description of bracket links.
861 Bracket links are like [[link][descritpion]]. This variable sets the initial
862 state in new org-mode buffers. The setting can then be toggled on a
863 per-buffer basis from the Org->Hyperlinks menu."
864 :group 'org-link
865 :type 'boolean)
867 (defcustom org-link-file-path-type 'adaptive
868 "How the path name in file links should be stored.
869 Valid values are:
871 relative Relative to the current directory, i.e. the directory of the file
872 into which the link is being inserted.
873 absolute Absolute path, if possible with ~ for home directory.
874 noabbrev Absolute path, no abbreviation of home directory.
875 adaptive Use relative path for files in the current directory and sub-
876 directories of it. For other files, use an absolute path."
877 :group 'org-link
878 :type '(choice
879 (const relative)
880 (const absolute)
881 (const noabbrev)
882 (const adaptive)))
884 (defcustom org-activate-links '(bracket angle plain radio tag date)
885 "Types of links that should be activated in Org-mode files.
886 This is a list of symbols, each leading to the activation of a certain link
887 type. In principle, it does not hurt to turn on most link types - there may
888 be a small gain when turning off unused link types. The types are:
890 bracket The recommended [[link][description]] or [[link]] links with hiding.
891 angular Links in angular brackes that may contain whitespace like
892 <bbdb:Carsten Dominik>.
893 plain Plain links in normal text, no whitespace, like http://google.com.
894 radio Text that is matched by a radio target, see manual for details.
895 tag Tag settings in a headline (link to tag search).
896 date Time stamps (link to calendar).
898 Changing this variable requires a restart of Emacs to become effective."
899 :group 'org-link
900 :type '(set (const :tag "Double bracket links (new style)" bracket)
901 (const :tag "Angular bracket links (old style)" angular)
902 (const :tag "Plain text links" plain)
903 (const :tag "Radio target matches" radio)
904 (const :tag "Tags" tag)
905 (const :tag "Timestamps" date)))
907 (defcustom org-make-link-description-function nil
908 "Function to use to generate link descriptions from links. If
909 nil the link location will be used. This function must take two
910 parameters; the first is the link and the second the description
911 org-insert-link has generated, and should return the description
912 to use."
913 :group 'org-link
914 :type 'function)
916 (defgroup org-link-store nil
917 "Options concerning storing links in Org-mode."
918 :tag "Org Store Link"
919 :group 'org-link)
921 (defcustom org-email-link-description-format "Email %c: %.30s"
922 "Format of the description part of a link to an email or usenet message.
923 The following %-excapes will be replaced by corresponding information:
925 %F full \"From\" field
926 %f name, taken from \"From\" field, address if no name
927 %T full \"To\" field
928 %t first name in \"To\" field, address if no name
929 %c correspondent. Unually \"from NAME\", but if you sent it yourself, it
930 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
931 %s subject
932 %m message-id.
934 You may use normal field width specification between the % and the letter.
935 This is for example useful to limit the length of the subject.
937 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
938 :group 'org-link-store
939 :type 'string)
941 (defcustom org-from-is-user-regexp
942 (let (r1 r2)
943 (when (and user-mail-address (not (string= user-mail-address "")))
944 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
945 (when (and user-full-name (not (string= user-full-name "")))
946 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
947 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
948 "Regexp mached against the \"From:\" header of an email or usenet message.
949 It should match if the message is from the user him/herself."
950 :group 'org-link-store
951 :type 'regexp)
953 (defcustom org-context-in-file-links t
954 "Non-nil means, file links from `org-store-link' contain context.
955 A search string will be added to the file name with :: as separator and
956 used to find the context when the link is activated by the command
957 `org-open-at-point'.
958 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
959 negates this setting for the duration of the command."
960 :group 'org-link-store
961 :type 'boolean)
963 (defcustom org-keep-stored-link-after-insertion nil
964 "Non-nil means, keep link in list for entire session.
966 The command `org-store-link' adds a link pointing to the current
967 location to an internal list. These links accumulate during a session.
968 The command `org-insert-link' can be used to insert links into any
969 Org-mode file (offering completion for all stored links). When this
970 option is nil, every link which has been inserted once using \\[org-insert-link]
971 will be removed from the list, to make completing the unused links
972 more efficient."
973 :group 'org-link-store
974 :type 'boolean)
976 (defgroup org-link-follow nil
977 "Options concerning following links in Org-mode."
978 :tag "Org Follow Link"
979 :group 'org-link)
981 (defcustom org-follow-link-hook nil
982 "Hook that is run after a link has been followed."
983 :group 'org-link-follow
984 :type 'hook)
986 (defcustom org-tab-follows-link nil
987 "Non-nil means, on links TAB will follow the link.
988 Needs to be set before org.el is loaded."
989 :group 'org-link-follow
990 :type 'boolean)
992 (defcustom org-return-follows-link nil
993 "Non-nil means, on links RET will follow the link.
994 Needs to be set before org.el is loaded."
995 :group 'org-link-follow
996 :type 'boolean)
998 (defcustom org-mouse-1-follows-link
999 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1000 "Non-nil means, mouse-1 on a link will follow the link.
1001 A longer mouse click will still set point. Does not work on XEmacs.
1002 Needs to be set before org.el is loaded."
1003 :group 'org-link-follow
1004 :type 'boolean)
1006 (defcustom org-mark-ring-length 4
1007 "Number of different positions to be recorded in the ring
1008 Changing this requires a restart of Emacs to work correctly."
1009 :group 'org-link-follow
1010 :type 'interger)
1012 (defcustom org-link-frame-setup
1013 '((vm . vm-visit-folder-other-frame)
1014 (gnus . gnus-other-frame)
1015 (file . find-file-other-window))
1016 "Setup the frame configuration for following links.
1017 When following a link with Emacs, it may often be useful to display
1018 this link in another window or frame. This variable can be used to
1019 set this up for the different types of links.
1020 For VM, use any of
1021 `vm-visit-folder'
1022 `vm-visit-folder-other-frame'
1023 For Gnus, use any of
1024 `gnus'
1025 `gnus-other-frame'
1026 `org-gnus-no-new-news'
1027 For FILE, use any of
1028 `find-file'
1029 `find-file-other-window'
1030 `find-file-other-frame'
1031 For the calendar, use the variable `calendar-setup'.
1032 For BBDB, it is currently only possible to display the matches in
1033 another window."
1034 :group 'org-link-follow
1035 :type '(list
1036 (cons (const vm)
1037 (choice
1038 (const vm-visit-folder)
1039 (const vm-visit-folder-other-window)
1040 (const vm-visit-folder-other-frame)))
1041 (cons (const gnus)
1042 (choice
1043 (const gnus)
1044 (const gnus-other-frame)
1045 (const org-gnus-no-new-news)))
1046 (cons (const file)
1047 (choice
1048 (const find-file)
1049 (const find-file-other-window)
1050 (const find-file-other-frame)))))
1052 (defcustom org-display-internal-link-with-indirect-buffer nil
1053 "Non-nil means, use indirect buffer to display infile links.
1054 Activating internal links (from one location in a file to another location
1055 in the same file) normally just jumps to the location. When the link is
1056 activated with a C-u prefix (or with mouse-3), the link is displayed in
1057 another window. When this option is set, the other window actually displays
1058 an indirect buffer clone of the current buffer, to avoid any visibility
1059 changes to the current buffer."
1060 :group 'org-link-follow
1061 :type 'boolean)
1063 (defcustom org-open-non-existing-files nil
1064 "Non-nil means, `org-open-file' will open non-existing files.
1065 When nil, an error will be generated."
1066 :group 'org-link-follow
1067 :type 'boolean)
1069 (defcustom org-open-directory-means-index-dot-org nil
1070 "Non-nil means, a link to a directory really means to index.org.
1071 When nil, following a directory link will run dired or open a finder/explorer
1072 window on that directory."
1073 :group 'org-link-follow
1074 :type 'boolean)
1076 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1077 "Function and arguments to call for following mailto links.
1078 This is a list with the first element being a lisp function, and the
1079 remaining elements being arguments to the function. In string arguments,
1080 %a will be replaced by the address, and %s will be replaced by the subject
1081 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1082 :group 'org-link-follow
1083 :type '(choice
1084 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1085 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1086 (const :tag "message-mail" (message-mail "%a" "%s"))
1087 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1089 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1090 "Non-nil means, ask for confirmation before executing shell links.
1091 Shell links can be dangerous: just think about a link
1093 [[shell:rm -rf ~/*][Google Search]]
1095 This link would show up in your Org-mode document as \"Google Search\",
1096 but really it would remove your entire home directory.
1097 Therefore we advise against setting this variable to nil.
1098 Just change it to `y-or-n-p' of you want to confirm with a
1099 single keystroke rather than having to type \"yes\"."
1100 :group 'org-link-follow
1101 :type '(choice
1102 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1103 (const :tag "with y-or-n (faster)" y-or-n-p)
1104 (const :tag "no confirmation (dangerous)" nil)))
1106 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1107 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1108 Elisp links can be dangerous: just think about a link
1110 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1112 This link would show up in your Org-mode document as \"Google Search\",
1113 but really it would remove your entire home directory.
1114 Therefore we advise against setting this variable to nil.
1115 Just change it to `y-or-n-p' of you want to confirm with a
1116 single keystroke rather than having to type \"yes\"."
1117 :group 'org-link-follow
1118 :type '(choice
1119 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1120 (const :tag "with y-or-n (faster)" y-or-n-p)
1121 (const :tag "no confirmation (dangerous)" nil)))
1123 (defconst org-file-apps-defaults-gnu
1124 '((remote . emacs)
1125 (system . mailcap)
1126 (t . mailcap))
1127 "Default file applications on a UNIX or GNU/Linux system.
1128 See `org-file-apps'.")
1130 (defconst org-file-apps-defaults-macosx
1131 '((remote . emacs)
1132 (t . "open %s")
1133 (system . "open %s")
1134 ("ps.gz" . "gv %s")
1135 ("eps.gz" . "gv %s")
1136 ("dvi" . "xdvi %s")
1137 ("fig" . "xfig %s"))
1138 "Default file applications on a MacOS X system.
1139 The system \"open\" is known as a default, but we use X11 applications
1140 for some files for which the OS does not have a good default.
1141 See `org-file-apps'.")
1143 (defconst org-file-apps-defaults-windowsnt
1144 (list
1145 '(remote . emacs)
1146 (cons t
1147 (list (if (featurep 'xemacs)
1148 'mswindows-shell-execute
1149 'w32-shell-execute)
1150 "open" 'file))
1151 (cons 'system
1152 (list (if (featurep 'xemacs)
1153 'mswindows-shell-execute
1154 'w32-shell-execute)
1155 "open" 'file)))
1156 "Default file applications on a Windows NT system.
1157 The system \"open\" is used for most files.
1158 See `org-file-apps'.")
1160 (defcustom org-file-apps
1162 (auto-mode . emacs)
1163 ("\\.x?html?\\'" . default)
1164 ("\\.pdf\\'" . default)
1166 "External applications for opening `file:path' items in a document.
1167 Org-mode uses system defaults for different file types, but
1168 you can use this variable to set the application for a given file
1169 extension. The entries in this list are cons cells where the car identifies
1170 files and the cdr the corresponding command. Possible values for the
1171 file identifier are
1172 \"regex\" Regular expression matched against the file name. For backward
1173 compatibility, this can also be a string with only alphanumeric
1174 characters, which is then interpreted as an extension.
1175 `directory' Matches a directory
1176 `remote' Matches a remote file, accessible through tramp or efs.
1177 Remote files most likely should be visited through Emacs
1178 because external applications cannot handle such paths.
1179 `auto-mode' Matches files that are mached by any entry in `auto-mode-alist',
1180 so all files Emacs knows how to handle. Using this with
1181 command `emacs' will open most files in Emacs. Beware that this
1182 will also open html files insite Emacs, unless you add
1183 (\"html\" . default) to the list as well.
1184 t Default for files not matched by any of the other options.
1185 `system' The system command to open files, like `open' on Windows
1186 and Mac OS X, and mailcap under GNU/Linux. This is the command
1187 that will be selected if you call `C-c C-o' with a double
1188 `C-u C-u' prefix.
1190 Possible values for the command are:
1191 `emacs' The file will be visited by the current Emacs process.
1192 `default' Use the default application for this file type, which is the
1193 association for t in the list, most likely in the system-specific
1194 part.
1195 This can be used to overrule an unwanted seting in the
1196 system-specific variable.
1197 `system' Use the system command for opening files, like \"open\".
1198 This command is specified by the entry whose car is `system'.
1199 Most likely, the system-specific version of this variable
1200 does define this command, but you can overrule/replace it
1201 here.
1202 string A command to be executed by a shell; %s will be replaced
1203 by the path to the file.
1204 sexp A Lisp form which will be evaluated. The file path will
1205 be available in the Lisp variable `file'.
1206 For more examples, see the system specific constants
1207 `org-file-apps-defaults-macosx'
1208 `org-file-apps-defaults-windowsnt'
1209 `org-file-apps-defaults-gnu'."
1210 :group 'org-link-follow
1211 :type '(repeat
1212 (cons (choice :value ""
1213 (string :tag "Extension")
1214 (const :tag "System command to open files" system)
1215 (const :tag "Default for unrecognized files" t)
1216 (const :tag "Remote file" remote)
1217 (const :tag "Links to a directory" directory)
1218 (const :tag "Any files that have Emacs modes"
1219 auto-mode))
1220 (choice :value ""
1221 (const :tag "Visit with Emacs" emacs)
1222 (const :tag "Use default" default)
1223 (const :tag "Use the system command" system)
1224 (string :tag "Command")
1225 (sexp :tag "Lisp form")))))
1227 (defgroup org-refile nil
1228 "Options concerning refiling entries in Org-mode."
1229 :tag "Org Remember"
1230 :group 'org)
1232 (defcustom org-directory "~/org"
1233 "Directory with org files.
1234 This directory will be used as default to prompt for org files.
1235 Used by the hooks for remember.el."
1236 :group 'org-refile
1237 :group 'org-remember
1238 :type 'directory)
1240 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1241 "Default target for storing notes.
1242 Used by the hooks for remember.el. This can be a string, or nil to mean
1243 the value of `remember-data-file'.
1244 You can set this on a per-template basis with the variable
1245 `org-remember-templates'."
1246 :group 'org-refile
1247 :group 'org-remember
1248 :type '(choice
1249 (const :tag "Default from remember-data-file" nil)
1250 file))
1252 (defcustom org-goto-interface 'outline
1253 "The default interface to be used for `org-goto'.
1254 Allowed vaues are:
1255 outline The interface shows an outline of the relevant file
1256 and the correct heading is found by moving through
1257 the outline or by searching with incremental search.
1258 outline-path-completion Headlines in the current buffer are offered via
1259 completion."
1260 :group 'org-refile
1261 :type '(choice
1262 (const :tag "Outline" outline)
1263 (const :tag "Outline-path-completion" outline-path-completion)))
1265 (defcustom org-reverse-note-order nil
1266 "Non-nil means, store new notes at the beginning of a file or entry.
1267 When nil, new notes will be filed to the end of a file or entry.
1268 This can also be a list with cons cells of regular expressions that
1269 are matched against file names, and values."
1270 :group 'org-remember
1271 :type '(choice
1272 (const :tag "Reverse always" t)
1273 (const :tag "Reverse never" nil)
1274 (repeat :tag "By file name regexp"
1275 (cons regexp boolean))))
1277 (defcustom org-refile-targets nil
1278 "Targets for refiling entries with \\[org-refile].
1279 This is list of cons cells. Each cell contains:
1280 - a specification of the files to be considered, either a list of files,
1281 or a symbol whose function or variable value will be used to retrieve
1282 a file name or a list of file names. Nil means, refile to a different
1283 heading in the current buffer.
1284 - A specification of how to find candidate refile targets. This may be
1285 any of
1286 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1287 This tag has to be present in all target headlines, inheritance will
1288 not be considered.
1289 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1290 todo keyword.
1291 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1292 headlines that are refiling targets.
1293 - a cons cell (:level . N). Any headline of level N is considered a target.
1294 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1296 When this variable is nil, all top-level headlines in the current buffer
1297 are used, equivalent to the vlaue `((nil . (:level . 1))'."
1298 :group 'org-remember
1299 :type '(repeat
1300 (cons
1301 (choice :value org-agenda-files
1302 (const :tag "All agenda files" org-agenda-files)
1303 (const :tag "Current buffer" nil)
1304 (function) (variable) (file))
1305 (choice :tag "Identify target headline by"
1306 (cons :tag "Specific tag" (const :tag) (string))
1307 (cons :tag "TODO keyword" (const :todo) (string))
1308 (cons :tag "Regular expression" (const :regexp) (regexp))
1309 (cons :tag "Level number" (const :level) (integer))
1310 (cons :tag "Max Level number" (const :maxlevel) (integer))))))
1312 (defcustom org-refile-use-outline-path nil
1313 "Non-nil means, provide refile targets as paths.
1314 So a level 3 headline will be available as level1/level2/level3.
1315 When the value is `file', also include the file name (without directory)
1316 into the path. When `full-file-path', include the full file path."
1317 :group 'org-remember
1318 :type '(choice
1319 (const :tag "Not" nil)
1320 (const :tag "Yes" t)
1321 (const :tag "Start with file name" file)
1322 (const :tag "Start with full file path" full-file-path)))
1324 (defgroup org-todo nil
1325 "Options concerning TODO items in Org-mode."
1326 :tag "Org TODO"
1327 :group 'org)
1329 (defgroup org-progress nil
1330 "Options concerning Progress logging in Org-mode."
1331 :tag "Org Progress"
1332 :group 'org-time)
1334 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1335 "List of TODO entry keyword sequences and their interpretation.
1336 \\<org-mode-map>This is a list of sequences.
1338 Each sequence starts with a symbol, either `sequence' or `type',
1339 indicating if the keywords should be interpreted as a sequence of
1340 action steps, or as different types of TODO items. The first
1341 keywords are states requiring action - these states will select a headline
1342 for inclusion into the global TODO list Org-mode produces. If one of
1343 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1344 signify that no further action is necessary. If \"|\" is not found,
1345 the last keyword is treated as the only DONE state of the sequence.
1347 The command \\[org-todo] cycles an entry through these states, and one
1348 additional state where no keyword is present. For details about this
1349 cycling, see the manual.
1351 TODO keywords and interpretation can also be set on a per-file basis with
1352 the special #+SEQ_TODO and #+TYP_TODO lines.
1354 Each keyword can optionally specify a character for fast state selection
1355 \(in combination with the variable `org-use-fast-todo-selection')
1356 and specifiers for state change logging, using the same syntax
1357 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1358 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1359 indicates to record a time stamp each time this state is selected.
1361 Each keyword may also specify if a timestamp or a note should be
1362 recorded when entering or leaving the state, by adding additional
1363 characters in the parenthesis after the keyword. This looks like this:
1364 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1365 record only the time of the state change. With X and Y being either
1366 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1367 Y when leaving the state if and only if the *target* state does not
1368 define X. You may omit any of the fast-selection key or X or /Y,
1369 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1371 For backward compatibility, this variable may also be just a list
1372 of keywords - in this case the interptetation (sequence or type) will be
1373 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1374 :group 'org-todo
1375 :group 'org-keywords
1376 :type '(choice
1377 (repeat :tag "Old syntax, just keywords"
1378 (string :tag "Keyword"))
1379 (repeat :tag "New syntax"
1380 (cons
1381 (choice
1382 :tag "Interpretation"
1383 (const :tag "Sequence (cycling hits every state)" sequence)
1384 (const :tag "Type (cycling directly to DONE)" type))
1385 (repeat
1386 (string :tag "Keyword"))))))
1388 (defvar org-todo-keywords-1 nil
1389 "All TODO and DONE keywords active in a buffer.")
1390 (make-variable-buffer-local 'org-todo-keywords-1)
1391 (defvar org-todo-keywords-for-agenda nil)
1392 (defvar org-done-keywords-for-agenda nil)
1393 (defvar org-todo-keyword-alist-for-agenda nil)
1394 (defvar org-tag-alist-for-agenda nil)
1395 (defvar org-agenda-contributing-files nil)
1396 (defvar org-not-done-keywords nil)
1397 (make-variable-buffer-local 'org-not-done-keywords)
1398 (defvar org-done-keywords nil)
1399 (make-variable-buffer-local 'org-done-keywords)
1400 (defvar org-todo-heads nil)
1401 (make-variable-buffer-local 'org-todo-heads)
1402 (defvar org-todo-sets nil)
1403 (make-variable-buffer-local 'org-todo-sets)
1404 (defvar org-todo-log-states nil)
1405 (make-variable-buffer-local 'org-todo-log-states)
1406 (defvar org-todo-kwd-alist nil)
1407 (make-variable-buffer-local 'org-todo-kwd-alist)
1408 (defvar org-todo-key-alist nil)
1409 (make-variable-buffer-local 'org-todo-key-alist)
1410 (defvar org-todo-key-trigger nil)
1411 (make-variable-buffer-local 'org-todo-key-trigger)
1413 (defcustom org-todo-interpretation 'sequence
1414 "Controls how TODO keywords are interpreted.
1415 This variable is in principle obsolete and is only used for
1416 backward compatibility, if the interpretation of todo keywords is
1417 not given already in `org-todo-keywords'. See that variable for
1418 more information."
1419 :group 'org-todo
1420 :group 'org-keywords
1421 :type '(choice (const sequence)
1422 (const type)))
1424 (defcustom org-use-fast-todo-selection 'prefix
1425 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1426 This variable describes if and under what circumstances the cycling
1427 mechanism for TODO keywords will be replaced by a single-key, direct
1428 selection scheme.
1430 When nil, fast selection is never used.
1432 When the symbol `prefix', it will be used when `org-todo' is called with
1433 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1434 in an agenda buffer.
1436 When t, fast selection is used by default. In this case, the prefix
1437 argument forces cycling instead.
1439 In all cases, the special interface is only used if access keys have actually
1440 been assigned by the user, i.e. if keywords in the configuration are followed
1441 by a letter in parenthesis, like TODO(t)."
1442 :group 'org-todo
1443 :type '(choice
1444 (const :tag "Never" nil)
1445 (const :tag "By default" t)
1446 (const :tag "Only with C-u C-c C-t" prefix)))
1448 (defcustom org-provide-todo-statistics t
1449 "Non-nil means, update todo statistics after insert and toggle.
1450 When this is set, todo statistics is updated in the parent of the current
1451 entry each time a todo state is changed."
1452 :group 'org-todo
1453 :type 'boolean)
1455 (defcustom org-after-todo-state-change-hook nil
1456 "Hook which is run after the state of a TODO item was changed.
1457 The new state (a string with a TODO keyword, or nil) is available in the
1458 Lisp variable `state'."
1459 :group 'org-todo
1460 :type 'hook)
1462 (defcustom org-todo-state-tags-triggers nil
1463 "Tag changes that should be triggered by TODO state changes.
1464 This is a list. Each entry is
1466 (state-change (tag . flag) .......)
1468 State-change can be a string with a state, and empty string to indicate the
1469 state that has no TODO keyword, or it can be one of the symbols `todo'
1470 or `done', meaning any not-done or done state, respectively."
1471 :group 'org-todo
1472 :group 'org-tags
1473 :type '(repeat
1474 (cons (choice :tag "When changing to"
1475 (const :tag "Not-done state" todo)
1476 (const :tag "Done state" done)
1477 (string :tag "State"))
1478 (repeat
1479 (cons :tag "Tag action"
1480 (string :tag "Tag")
1481 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1483 (defcustom org-log-done nil
1484 "Non-nil means, record a CLOSED timestamp when moving an entry to DONE.
1485 When equal to the list (done), also prompt for a closing note.
1486 This can also be configured on a per-file basis by adding one of
1487 the following lines anywhere in the buffer:
1489 #+STARTUP: logdone
1490 #+STARTUP: lognotedone
1491 #+STARTUP: nologdone"
1492 :group 'org-todo
1493 :group 'org-progress
1494 :type '(choice
1495 (const :tag "No logging" nil)
1496 (const :tag "Record CLOSED timestamp" time)
1497 (const :tag "Record CLOSED timestamp with closing note." note)))
1499 ;; Normalize old uses of org-log-done.
1500 (cond
1501 ((eq org-log-done t) (setq org-log-done 'time))
1502 ((and (listp org-log-done) (memq 'done org-log-done))
1503 (setq org-log-done 'note)))
1505 (defcustom org-log-note-clock-out nil
1506 "Non-nil means, record a note when clocking out of an item.
1507 This can also be configured on a per-file basis by adding one of
1508 the following lines anywhere in the buffer:
1510 #+STARTUP: lognoteclock-out
1511 #+STARTUP: nolognoteclock-out"
1512 :group 'org-todo
1513 :group 'org-progress
1514 :type 'boolean)
1516 (defcustom org-log-done-with-time t
1517 "Non-nil means, the CLOSED time stamp will contain date and time.
1518 When nil, only the date will be recorded."
1519 :group 'org-progress
1520 :type 'boolean)
1522 (defcustom org-log-note-headings
1523 '((done . "CLOSING NOTE %t")
1524 (state . "State %-12s %t")
1525 (note . "Note taken on %t")
1526 (clock-out . ""))
1527 "Headings for notes added to entries.
1528 The value is an alist, with the car being a symbol indicating the note
1529 context, and the cdr is the heading to be used. The heading may also be the
1530 empty string.
1531 %t in the heading will be replaced by a time stamp.
1532 %s will be replaced by the new TODO state, in double quotes.
1533 %u will be replaced by the user name.
1534 %U will be replaced by the full user name."
1535 :group 'org-todo
1536 :group 'org-progress
1537 :type '(list :greedy t
1538 (cons (const :tag "Heading when closing an item" done) string)
1539 (cons (const :tag
1540 "Heading when changing todo state (todo sequence only)"
1541 state) string)
1542 (cons (const :tag "Heading when just taking a note" note) string)
1543 (cons (const :tag "Heading when clocking out" clock-out) string)))
1545 (unless (assq 'note org-log-note-headings)
1546 (push '(note . "%t") org-log-note-headings))
1548 (defcustom org-log-state-notes-insert-after-drawers nil
1549 "Non-nil means, insert state change notes after any drawers in entry.
1550 Only the drawers that *immediately* follow the headline and the
1551 deadline/scheduled line are skipped.
1552 When nil, insert notes right after the heading and perhaps the line
1553 with deadline/scheduling if present."
1554 :group 'org-todo
1555 :group 'org-progress
1556 :type 'boolean)
1558 (defcustom org-log-states-order-reversed t
1559 "Non-nil means, the latest state change note will be directly after heading.
1560 When nil, the notes will be orderer according to time."
1561 :group 'org-todo
1562 :group 'org-progress
1563 :type 'boolean)
1565 (defcustom org-log-repeat 'time
1566 "Non-nil means, record moving through the DONE state when triggering repeat.
1567 An auto-repeating tasks is immediately switched back to TODO when marked
1568 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1569 the TODO keyword definition, or recording a closing note by setting
1570 `org-log-done', there will be no record of the task moving through DONE.
1571 This variable forces taking a note anyway. Possible values are:
1573 nil Don't force a record
1574 time Record a time stamp
1575 note Record a note
1577 This option can also be set with on a per-file-basis with
1579 #+STARTUP: logrepeat
1580 #+STARTUP: lognoterepeat
1581 #+STARTUP: nologrepeat
1583 You can have local logging settings for a subtree by setting the LOGGING
1584 property to one or more of these keywords."
1585 :group 'org-todo
1586 :group 'org-progress
1587 :type '(choice
1588 (const :tag "Don't force a record" nil)
1589 (const :tag "Force recording the DONE state" time)
1590 (const :tag "Force recording a note with the DONE state" note)))
1593 (defgroup org-priorities nil
1594 "Priorities in Org-mode."
1595 :tag "Org Priorities"
1596 :group 'org-todo)
1598 (defcustom org-highest-priority ?A
1599 "The highest priority of TODO items. A character like ?A, ?B etc.
1600 Must have a smaller ASCII number than `org-lowest-priority'."
1601 :group 'org-priorities
1602 :type 'character)
1604 (defcustom org-lowest-priority ?C
1605 "The lowest priority of TODO items. A character like ?A, ?B etc.
1606 Must have a larger ASCII number than `org-highest-priority'."
1607 :group 'org-priorities
1608 :type 'character)
1610 (defcustom org-default-priority ?B
1611 "The default priority of TODO items.
1612 This is the priority an item get if no explicit priority is given."
1613 :group 'org-priorities
1614 :type 'character)
1616 (defcustom org-priority-start-cycle-with-default t
1617 "Non-nil means, start with default priority when starting to cycle.
1618 When this is nil, the first step in the cycle will be (depending on the
1619 command used) one higher or lower that the default priority."
1620 :group 'org-priorities
1621 :type 'boolean)
1623 (defgroup org-time nil
1624 "Options concerning time stamps and deadlines in Org-mode."
1625 :tag "Org Time"
1626 :group 'org)
1628 (defcustom org-insert-labeled-timestamps-at-point nil
1629 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1630 When nil, these labeled time stamps are forces into the second line of an
1631 entry, just after the headline. When scheduling from the global TODO list,
1632 the time stamp will always be forced into the second line."
1633 :group 'org-time
1634 :type 'boolean)
1636 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1637 "Formats for `format-time-string' which are used for time stamps.
1638 It is not recommended to change this constant.")
1640 (defcustom org-time-stamp-rounding-minutes '(0 5)
1641 "Number of minutes to round time stamps to.
1642 These are two values, the first applies when first creating a time stamp.
1643 The second applies when changing it with the commands `S-up' and `S-down'.
1644 When changing the time stamp, this means that it will change in steps
1645 of N minutes, as given by the second value.
1647 When a setting is 0 or 1, insert the time unmodified. Useful rounding
1648 numbers should be factors of 60, so for example 5, 10, 15.
1650 When this is larger than 1, you can still force an exact time-stamp by using
1651 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
1652 and by using a prefix arg to `S-up/down' to specify the exact number
1653 of minutes to shift."
1654 :group 'org-time
1655 :get '(lambda (var) ; Make sure all entries have 5 elements
1656 (if (integerp (default-value var))
1657 (list (default-value var) 5)
1658 (default-value var)))
1659 :type '(list
1660 (integer :tag "when inserting times")
1661 (integer :tag "when modifying times")))
1663 ;; Normalize old customizations of this variable.
1664 (when (integerp org-time-stamp-rounding-minutes)
1665 (setq org-time-stamp-rounding-minutes
1666 (list org-time-stamp-rounding-minutes
1667 org-time-stamp-rounding-minutes)))
1669 (defcustom org-display-custom-times nil
1670 "Non-nil means, overlay custom formats over all time stamps.
1671 The formats are defined through the variable `org-time-stamp-custom-formats'.
1672 To turn this on on a per-file basis, insert anywhere in the file:
1673 #+STARTUP: customtime"
1674 :group 'org-time
1675 :set 'set-default
1676 :type 'sexp)
1677 (make-variable-buffer-local 'org-display-custom-times)
1679 (defcustom org-time-stamp-custom-formats
1680 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1681 "Custom formats for time stamps. See `format-time-string' for the syntax.
1682 These are overlayed over the default ISO format if the variable
1683 `org-display-custom-times' is set. Time like %H:%M should be at the
1684 end of the second format."
1685 :group 'org-time
1686 :type 'sexp)
1688 (defun org-time-stamp-format (&optional long inactive)
1689 "Get the right format for a time string."
1690 (let ((f (if long (cdr org-time-stamp-formats)
1691 (car org-time-stamp-formats))))
1692 (if inactive
1693 (concat "[" (substring f 1 -1) "]")
1694 f)))
1696 (defcustom org-time-clocksum-format "%d:%02d"
1697 "The format string used when creating CLOCKSUM lines, or when
1698 org-mode generates a time duration."
1699 :group 'org-time
1700 :type 'string)
1702 (defcustom org-deadline-warning-days 14
1703 "No. of days before expiration during which a deadline becomes active.
1704 This variable governs the display in sparse trees and in the agenda.
1705 When 0 or negative, it means use this number (the absolute value of it)
1706 even if a deadline has a different individual lead time specified."
1707 :group 'org-time
1708 :group 'org-agenda-daily/weekly
1709 :type 'number)
1711 (defcustom org-read-date-prefer-future t
1712 "Non-nil means, assume future for incomplete date input from user.
1713 This affects the following situations:
1714 1. The user gives a day, but no month.
1715 For example, if today is the 15th, and you enter \"3\", Org-mode will
1716 read this as the third of *next* month. However, if you enter \"17\",
1717 it will be considered as *this* month.
1718 2. The user gives a month but not a year.
1719 For example, if it is april and you enter \"feb 2\", this will be read
1720 as feb 2, *next* year. \"May 5\", however, will be this year.
1722 Currently this does not work for ISO week specifications.
1724 When this option is nil, the current month and year will always be used
1725 as defaults."
1726 :group 'org-time
1727 :type 'boolean)
1729 (defcustom org-read-date-display-live t
1730 "Non-nil means, display current interpretation of date prompt live.
1731 This display will be in an overlay, in the minibuffer."
1732 :group 'org-time
1733 :type 'boolean)
1735 (defcustom org-read-date-popup-calendar t
1736 "Non-nil means, pop up a calendar when prompting for a date.
1737 In the calendar, the date can be selected with mouse-1. However, the
1738 minibuffer will also be active, and you can simply enter the date as well.
1739 When nil, only the minibuffer will be available."
1740 :group 'org-time
1741 :type 'boolean)
1742 (if (fboundp 'defvaralias)
1743 (defvaralias 'org-popup-calendar-for-date-prompt
1744 'org-read-date-popup-calendar))
1746 (defcustom org-extend-today-until 0
1747 "The hour when your day really ends. Must be an integer.
1748 This has influence for the following applications:
1749 - When switching the agenda to \"today\". It it is still earlier than
1750 the time given here, the day recognized as TODAY is actually yesterday.
1751 - When a date is read from the user and it is still before the time given
1752 here, the current date and time will be assumed to be yesterday, 23:59.
1753 Also, timestamps inserted in remember templates follow this rule.
1755 IMPORTANT: This is a feature whose implementation is and likely will
1756 remain incomplete. Really, it is only here because past midnight seems to
1757 be the favorite working time of John Wiegley :-)"
1758 :group 'org-time
1759 :type 'number)
1761 (defcustom org-edit-timestamp-down-means-later nil
1762 "Non-nil means, S-down will increase the time in a time stamp.
1763 When nil, S-up will increase."
1764 :group 'org-time
1765 :type 'boolean)
1767 (defcustom org-calendar-follow-timestamp-change t
1768 "Non-nil means, make the calendar window follow timestamp changes.
1769 When a timestamp is modified and the calendar window is visible, it will be
1770 moved to the new date."
1771 :group 'org-time
1772 :type 'boolean)
1774 (defgroup org-tags nil
1775 "Options concerning tags in Org-mode."
1776 :tag "Org Tags"
1777 :group 'org)
1779 (defcustom org-tag-alist nil
1780 "List of tags allowed in Org-mode files.
1781 When this list is nil, Org-mode will base TAG input on what is already in the
1782 buffer.
1783 The value of this variable is an alist, the car of each entry must be a
1784 keyword as a string, the cdr may be a character that is used to select
1785 that tag through the fast-tag-selection interface.
1786 See the manual for details."
1787 :group 'org-tags
1788 :type '(repeat
1789 (choice
1790 (cons (string :tag "Tag name")
1791 (character :tag "Access char"))
1792 (const :tag "Start radio group" (:startgroup))
1793 (const :tag "End radio group" (:endgroup)))))
1795 (defvar org-file-tags nil
1796 "List of tags that can be inherited by all entries in the file.
1797 The tags will be inherited if the variable `org-use-tag-inheritance'
1798 says they should be.
1799 This variable is populated from #+TAG lines.")
1801 (defcustom org-use-fast-tag-selection 'auto
1802 "Non-nil means, use fast tag selection scheme.
1803 This is a special interface to select and deselect tags with single keys.
1804 When nil, fast selection is never used.
1805 When the symbol `auto', fast selection is used if and only if selection
1806 characters for tags have been configured, either through the variable
1807 `org-tag-alist' or through a #+TAGS line in the buffer.
1808 When t, fast selection is always used and selection keys are assigned
1809 automatically if necessary."
1810 :group 'org-tags
1811 :type '(choice
1812 (const :tag "Always" t)
1813 (const :tag "Never" nil)
1814 (const :tag "When selection characters are configured" 'auto)))
1816 (defcustom org-fast-tag-selection-single-key nil
1817 "Non-nil means, fast tag selection exits after first change.
1818 When nil, you have to press RET to exit it.
1819 During fast tag selection, you can toggle this flag with `C-c'.
1820 This variable can also have the value `expert'. In this case, the window
1821 displaying the tags menu is not even shown, until you press C-c again."
1822 :group 'org-tags
1823 :type '(choice
1824 (const :tag "No" nil)
1825 (const :tag "Yes" t)
1826 (const :tag "Expert" expert)))
1828 (defvar org-fast-tag-selection-include-todo nil
1829 "Non-nil means, fast tags selection interface will also offer TODO states.
1830 This is an undocumented feature, you should not rely on it.")
1832 (defcustom org-tags-column (if (featurep 'xemacs) -79 -80)
1833 "The column to which tags should be indented in a headline.
1834 If this number is positive, it specifies the column. If it is negative,
1835 it means that the tags should be flushright to that column. For example,
1836 -80 works well for a normal 80 character screen."
1837 :group 'org-tags
1838 :type 'integer)
1840 (defcustom org-auto-align-tags t
1841 "Non-nil means, realign tags after pro/demotion of TODO state change.
1842 These operations change the length of a headline and therefore shift
1843 the tags around. With this options turned on, after each such operation
1844 the tags are again aligned to `org-tags-column'."
1845 :group 'org-tags
1846 :type 'boolean)
1848 (defcustom org-use-tag-inheritance t
1849 "Non-nil means, tags in levels apply also for sublevels.
1850 When nil, only the tags directly given in a specific line apply there.
1851 If this option is t, a match early-on in a tree can lead to a large
1852 number of matches in the subtree. If you only want to see the first
1853 match in a tree during a search, check out the variable
1854 `org-tags-match-list-sublevels'.
1856 This may also be a list of tags that should be inherited, or a regexp that
1857 matches tags that should be inherited."
1858 :group 'org-tags
1859 :type '(choice
1860 (const :tag "Not" nil)
1861 (const :tag "Always" t)
1862 (repeat :tag "Specific tags" (string :tag "Tag"))
1863 (regexp :tag "Tags matched by regexp")))
1865 (defun org-tag-inherit-p (tag)
1866 "Check if TAG is one that should be inherited."
1867 (cond
1868 ((eq org-use-tag-inheritance t) t)
1869 ((not org-use-tag-inheritance) nil)
1870 ((stringp org-use-tag-inheritance)
1871 (string-match org-use-tag-inheritance tag))
1872 ((listp org-use-tag-inheritance)
1873 (member tag org-use-tag-inheritance))
1874 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
1876 (defcustom org-tags-match-list-sublevels t
1877 "Non-nil means list also sublevels of headlines matching tag search.
1878 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1879 the sublevels of a headline matching a tag search often also match
1880 the same search. Listing all of them can create very long lists.
1881 Setting this variable to nil causes subtrees of a match to be skipped.
1882 This option is off by default, because inheritance in on. If you turn
1883 inheritance off, you very likely want to turn this option on.
1885 As a special case, if the tag search is restricted to TODO items, the
1886 value of this variable is ignored and sublevels are always checked, to
1887 make sure all corresponding TODO items find their way into the list."
1888 :group 'org-tags
1889 :type 'boolean)
1891 (defvar org-tags-history nil
1892 "History of minibuffer reads for tags.")
1893 (defvar org-last-tags-completion-table nil
1894 "The last used completion table for tags.")
1895 (defvar org-after-tags-change-hook nil
1896 "Hook that is run after the tags in a line have changed.")
1898 (defgroup org-properties nil
1899 "Options concerning properties in Org-mode."
1900 :tag "Org Properties"
1901 :group 'org)
1903 (defcustom org-property-format "%-10s %s"
1904 "How property key/value pairs should be formatted by `indent-line'.
1905 When `indent-line' hits a property definition, it will format the line
1906 according to this format, mainly to make sure that the values are
1907 lined-up with respect to each other."
1908 :group 'org-properties
1909 :type 'string)
1911 (defcustom org-use-property-inheritance nil
1912 "Non-nil means, properties apply also for sublevels.
1914 This setting is chiefly used during property searches. Turning it on can
1915 cause significant overhead when doing a search, which is why it is not
1916 on by default.
1918 When nil, only the properties directly given in the current entry count.
1919 When t, every property is inherited. The value may also be a list of
1920 properties that should have inheritance, or a regular expression matching
1921 properties that should be inherited.
1923 However, note that some special properties use inheritance under special
1924 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
1925 and the properties ending in \"_ALL\" when they are used as descriptor
1926 for valid values of a property.
1928 Note for programmers:
1929 When querying an entry with `org-entry-get', you can control if inheritance
1930 should be used. By default, `org-entry-get' looks only at the local
1931 properties. You can request inheritance by setting the inherit argument
1932 to t (to force inheritance) or to `selective' (to respect the setting
1933 in this variable)."
1934 :group 'org-properties
1935 :type '(choice
1936 (const :tag "Not" nil)
1937 (const :tag "Always" t)
1938 (repeat :tag "Specific properties" (string :tag "Property"))
1939 (regexp :tag "Properties matched by regexp")))
1941 (defun org-property-inherit-p (property)
1942 "Check if PROPERTY is one that should be inherited."
1943 (cond
1944 ((eq org-use-property-inheritance t) t)
1945 ((not org-use-property-inheritance) nil)
1946 ((stringp org-use-property-inheritance)
1947 (string-match org-use-property-inheritance property))
1948 ((listp org-use-property-inheritance)
1949 (member property org-use-property-inheritance))
1950 (t (error "Invalid setting of `org-use-property-inheritance'"))))
1952 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
1953 "The default column format, if no other format has been defined.
1954 This variable can be set on the per-file basis by inserting a line
1956 #+COLUMNS: %25ITEM ....."
1957 :group 'org-properties
1958 :type 'string)
1960 (defcustom org-columns-ellipses ".."
1961 "The ellipses to be used when a field in column view is truncated.
1962 When this is the empty string, as many characters as possible are shown,
1963 but then there will be no visual indication that the field has been truncated.
1964 When this is a string of length N, the last N characters of a truncated
1965 field are replaced by this string. If the column is narrower than the
1966 ellipses string, only part of the ellipses string will be shown."
1967 :group 'org-properties
1968 :type 'string)
1970 (defcustom org-columns-modify-value-for-display-function nil
1971 "Function that modifies values for display in column view.
1972 For example, it can be used to cut out a certain part from a time stamp.
1973 The function must take 2 argments:
1975 column-title The tite of the column (*not* the property name)
1976 value The value that should be modified.
1978 The function should return the value that should be displayed,
1979 or nil if the normal value should be used."
1980 :group 'org-properties
1981 :type 'function)
1983 (defcustom org-effort-property "Effort"
1984 "The property that is being used to keep track of effort estimates.
1985 Effort estimates given in this property need to have the format H:MM."
1986 :group 'org-properties
1987 :group 'org-progress
1988 :type '(string :tag "Property"))
1990 (defconst org-global-properties-fixed
1991 '(("VISIBILITY_ALL" . "folded children content all"))
1992 "List of property/value pairs that can be inherited by any entry.
1993 These are fixed values, for the preset properties.")
1996 (defcustom org-global-properties nil
1997 "List of property/value pairs that can be inherited by any entry.
1998 You can set buffer-local values for this by adding lines like
2000 #+PROPERTY: NAME VALUE"
2001 :group 'org-properties
2002 :type '(repeat
2003 (cons (string :tag "Property")
2004 (string :tag "Value"))))
2006 (defvar org-file-properties nil
2007 "List of property/value pairs that can be inherited by any entry.
2008 Valid for the current buffer.
2009 This variable is populated from #+PROPERTY lines.")
2010 (make-variable-buffer-local 'org-file-properties)
2012 (defgroup org-agenda nil
2013 "Options concerning agenda views in Org-mode."
2014 :tag "Org Agenda"
2015 :group 'org)
2017 (defvar org-category nil
2018 "Variable used by org files to set a category for agenda display.
2019 Such files should use a file variable to set it, for example
2021 # -*- mode: org; org-category: \"ELisp\"
2023 or contain a special line
2025 #+CATEGORY: ELisp
2027 If the file does not specify a category, then file's base name
2028 is used instead.")
2029 (make-variable-buffer-local 'org-category)
2030 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2032 (defcustom org-agenda-files nil
2033 "The files to be used for agenda display.
2034 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2035 \\[org-remove-file]. You can also use customize to edit the list.
2037 If an entry is a directory, all files in that directory that are matched by
2038 `org-agenda-file-regexp' will be part of the file list.
2040 If the value of the variable is not a list but a single file name, then
2041 the list of agenda files is actually stored and maintained in that file, one
2042 agenda file per line."
2043 :group 'org-agenda
2044 :type '(choice
2045 (repeat :tag "List of files and directories" file)
2046 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2048 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2049 "Regular expression to match files for `org-agenda-files'.
2050 If any element in the list in that variable contains a directory instead
2051 of a normal file, all files in that directory that are matched by this
2052 regular expression will be included."
2053 :group 'org-agenda
2054 :type 'regexp)
2056 (defcustom org-agenda-text-search-extra-files nil
2057 "List of extra files to be searched by text search commands.
2058 These files will be search in addition to the agenda files by the
2059 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2060 Note that these files will only be searched for text search commands,
2061 not for the other agenda views like todo lists, tag searches or the weekly
2062 agenda. This variable is intended to list notes and possibly archive files
2063 that should also be searched by these two commands.
2064 In fact, if the first element in the list is the symbol `agenda-archives',
2065 than all archive files of all agenda files will be added to the search
2066 scope."
2067 :group 'org-agenda
2068 :type '(set :greedy t
2069 (const :tag "Agenda Archives" agenda-archives)
2070 (repeat :inline t (file))))
2072 (if (fboundp 'defvaralias)
2073 (defvaralias 'org-agenda-multi-occur-extra-files
2074 'org-agenda-text-search-extra-files))
2076 (defcustom org-agenda-skip-unavailable-files nil
2077 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2078 A nil value means to remove them, after a query, from the list."
2079 :group 'org-agenda
2080 :type 'boolean)
2082 (defcustom org-calendar-to-agenda-key [?c]
2083 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2084 The command `org-calendar-goto-agenda' will be bound to this key. The
2085 default is the character `c' because then `c' can be used to switch back and
2086 forth between agenda and calendar."
2087 :group 'org-agenda
2088 :type 'sexp)
2090 (defcustom org-calendar-agenda-action-key [?k]
2091 "The key to be installed in `calendar-mode-map' for agenda-action.
2092 The command `org-agenda-action' will be bound to this key. The
2093 default is the character `k' because we use the same key in the agenda."
2094 :group 'org-agenda
2095 :type 'sexp)
2097 (eval-after-load "calendar"
2098 '(progn
2099 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2100 'org-calendar-goto-agenda)
2101 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2102 'org-agenda-action)))
2104 (defgroup org-latex nil
2105 "Options for embedding LaTeX code into Org-mode."
2106 :tag "Org LaTeX"
2107 :group 'org)
2109 (defcustom org-format-latex-options
2110 '(:foreground default :background default :scale 1.0
2111 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2112 :matchers ("begin" "$" "$$" "\\(" "\\["))
2113 "Options for creating images from LaTeX fragments.
2114 This is a property list with the following properties:
2115 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2116 `default' means use the foreground of the default face.
2117 :background the background color, or \"Transparent\".
2118 `default' means use the background of the default face.
2119 :scale a scaling factor for the size of the images.
2120 :html-foreground, :html-background, :html-scale
2121 the same numbers for HTML export.
2122 :matchers a list indicating which matchers should be used to
2123 find LaTeX fragments. Valid members of this list are:
2124 \"begin\" find environments
2125 \"$\" find math expressions surrounded by $...$
2126 \"$$\" find math expressions surrounded by $$....$$
2127 \"\\(\" find math expressions surrounded by \\(...\\)
2128 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2129 :group 'org-latex
2130 :type 'plist)
2132 (defcustom org-format-latex-header "\\documentclass{article}
2133 \\usepackage{fullpage} % do not remove
2134 \\usepackage{amssymb}
2135 \\usepackage[usenames]{color}
2136 \\usepackage{amsmath}
2137 \\usepackage{latexsym}
2138 \\usepackage[mathscr]{eucal}
2139 \\pagestyle{empty} % do not remove"
2140 "The document header used for processing LaTeX fragments."
2141 :group 'org-latex
2142 :type 'string)
2145 (defgroup org-font-lock nil
2146 "Font-lock settings for highlighting in Org-mode."
2147 :tag "Org Font Lock"
2148 :group 'org)
2150 (defcustom org-level-color-stars-only nil
2151 "Non-nil means fontify only the stars in each headline.
2152 When nil, the entire headline is fontified.
2153 Changing it requires restart of `font-lock-mode' to become effective
2154 also in regions already fontified."
2155 :group 'org-font-lock
2156 :type 'boolean)
2158 (defcustom org-hide-leading-stars nil
2159 "Non-nil means, hide the first N-1 stars in a headline.
2160 This works by using the face `org-hide' for these stars. This
2161 face is white for a light background, and black for a dark
2162 background. You may have to customize the face `org-hide' to
2163 make this work.
2164 Changing it requires restart of `font-lock-mode' to become effective
2165 also in regions already fontified.
2166 You may also set this on a per-file basis by adding one of the following
2167 lines to the buffer:
2169 #+STARTUP: hidestars
2170 #+STARTUP: showstars"
2171 :group 'org-font-lock
2172 :type 'boolean)
2174 (defcustom org-fontify-done-headline nil
2175 "Non-nil means, change the face of a headline if it is marked DONE.
2176 Normally, only the TODO/DONE keyword indicates the state of a headline.
2177 When this is non-nil, the headline after the keyword is set to the
2178 `org-headline-done' as an additional indication."
2179 :group 'org-font-lock
2180 :type 'boolean)
2182 (defcustom org-fontify-emphasized-text t
2183 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2184 Changing this variable requires a restart of Emacs to take effect."
2185 :group 'org-font-lock
2186 :type 'boolean)
2188 (defcustom org-highlight-latex-fragments-and-specials nil
2189 "Non-nil means, fontify what is treated specially by the exporters."
2190 :group 'org-font-lock
2191 :type 'boolean)
2193 (defcustom org-hide-emphasis-markers nil
2194 "Non-nil mean font-lock should hide the emphasis marker characters."
2195 :group 'org-font-lock
2196 :type 'boolean)
2198 (defvar org-emph-re nil
2199 "Regular expression for matching emphasis.")
2200 (defvar org-verbatim-re nil
2201 "Regular expression for matching verbatim text.")
2202 (defvar org-emphasis-regexp-components) ; defined just below
2203 (defvar org-emphasis-alist) ; defined just below
2204 (defun org-set-emph-re (var val)
2205 "Set variable and compute the emphasis regular expression."
2206 (set var val)
2207 (when (and (boundp 'org-emphasis-alist)
2208 (boundp 'org-emphasis-regexp-components)
2209 org-emphasis-alist org-emphasis-regexp-components)
2210 (let* ((e org-emphasis-regexp-components)
2211 (pre (car e))
2212 (post (nth 1 e))
2213 (border (nth 2 e))
2214 (body (nth 3 e))
2215 (nl (nth 4 e))
2216 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
2217 (body1 (concat body "*?"))
2218 (markers (mapconcat 'car org-emphasis-alist ""))
2219 (vmarkers (mapconcat
2220 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2221 org-emphasis-alist "")))
2222 ;; make sure special characters appear at the right position in the class
2223 (if (string-match "\\^" markers)
2224 (setq markers (concat (replace-match "" t t markers) "^")))
2225 (if (string-match "-" markers)
2226 (setq markers (concat (replace-match "" t t markers) "-")))
2227 (if (string-match "\\^" vmarkers)
2228 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2229 (if (string-match "-" vmarkers)
2230 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2231 (if (> nl 0)
2232 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2233 (int-to-string nl) "\\}")))
2234 ;; Make the regexp
2235 (setq org-emph-re
2236 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
2237 "\\("
2238 "\\([" markers "]\\)"
2239 "\\("
2240 "[^" border "]\\|"
2241 "[^" border (if (and nil stacked) markers) "]"
2242 body1
2243 "[^" border (if (and nil stacked) markers) "]"
2244 "\\)"
2245 "\\3\\)"
2246 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
2247 (setq org-verbatim-re
2248 (concat "\\([" pre "]\\|^\\)"
2249 "\\("
2250 "\\([" vmarkers "]\\)"
2251 "\\("
2252 "[^" border "]\\|"
2253 "[^" border "]"
2254 body1
2255 "[^" border "]"
2256 "\\)"
2257 "\\3\\)"
2258 "\\([" post "]\\|$\\)")))))
2260 (defcustom org-emphasis-regexp-components
2261 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
2262 "Components used to build the regular expression for emphasis.
2263 This is a list with 6 entries. Terminology: In an emphasis string
2264 like \" *strong word* \", we call the initial space PREMATCH, the final
2265 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2266 and \"trong wor\" is the body. The different components in this variable
2267 specify what is allowed/forbidden in each part:
2269 pre Chars allowed as prematch. Beginning of line will be allowed too.
2270 post Chars allowed as postmatch. End of line will be allowed too.
2271 border The chars *forbidden* as border characters.
2272 body-regexp A regexp like \".\" to match a body character. Don't use
2273 non-shy groups here, and don't allow newline here.
2274 newline The maximum number of newlines allowed in an emphasis exp.
2276 Use customize to modify this, or restart Emacs after changing it."
2277 :group 'org-font-lock
2278 :set 'org-set-emph-re
2279 :type '(list
2280 (sexp :tag "Allowed chars in pre ")
2281 (sexp :tag "Allowed chars in post ")
2282 (sexp :tag "Forbidden chars in border ")
2283 (sexp :tag "Regexp for body ")
2284 (integer :tag "number of newlines allowed")
2285 (option (boolean :tag "Please ignore this button"))))
2287 (defcustom org-emphasis-alist
2288 `(("*" bold "<b>" "</b>")
2289 ("/" italic "<i>" "</i>")
2290 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
2291 ("=" org-code "<code>" "</code>" verbatim)
2292 ("~" org-verbatim "<code>" "</code>" verbatim)
2293 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2294 "<del>" "</del>")
2296 "Special syntax for emphasized text.
2297 Text starting and ending with a special character will be emphasized, for
2298 example *bold*, _underlined_ and /italic/. This variable sets the marker
2299 characters, the face to be used by font-lock for highlighting in Org-mode
2300 Emacs buffers, and the HTML tags to be used for this.
2301 Use customize to modify this, or restart Emacs after changing it."
2302 :group 'org-font-lock
2303 :set 'org-set-emph-re
2304 :type '(repeat
2305 (list
2306 (string :tag "Marker character")
2307 (choice
2308 (face :tag "Font-lock-face")
2309 (plist :tag "Face property list"))
2310 (string :tag "HTML start tag")
2311 (string :tag "HTML end tag")
2312 (option (const verbatim)))))
2314 ;;; Miscellaneous options
2316 (defgroup org-completion nil
2317 "Completion in Org-mode."
2318 :tag "Org Completion"
2319 :group 'org)
2321 (defcustom org-completion-fallback-command 'hippie-expand
2322 "The expansion command called by \\[org-complete] in normal context.
2323 Normal means, no org-mode-specific context."
2324 :group 'org-completion
2325 :type 'function)
2327 ;;; Functions and variables from ther packages
2328 ;; Declared here to avoid compiler warnings
2330 ;; XEmacs only
2331 (defvar outline-mode-menu-heading)
2332 (defvar outline-mode-menu-show)
2333 (defvar outline-mode-menu-hide)
2334 (defvar zmacs-regions) ; XEmacs regions
2336 ;; Emacs only
2337 (defvar mark-active)
2339 ;; Various packages
2340 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2341 (declare-function calendar-forward-day "cal-move" (arg))
2342 (declare-function calendar-goto-date "cal-move" (date))
2343 (declare-function calendar-goto-today "cal-move" ())
2344 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2345 (defvar calc-embedded-close-formula)
2346 (defvar calc-embedded-open-formula)
2347 (declare-function cdlatex-tab "ext:cdlatex" ())
2348 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2349 (defvar font-lock-unfontify-region-function)
2350 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2351 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2352 (defvar iswitchb-temp-buflist)
2353 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2354 (declare-function org-agenda-skip "org-agenda" ())
2355 (declare-function org-format-agenda-item "org-agenda"
2356 (extra txt &optional category tags dotime noprefix remove-re))
2357 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2358 (declare-function org-agenda-change-all-lines "org-agenda"
2359 (newhead hdmarker &optional fixface))
2360 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2361 (declare-function org-agenda-maybe-redo "org-agenda" ())
2362 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2363 (beg end))
2364 (declare-function parse-time-string "parse-time" (string))
2365 (declare-function remember "remember" (&optional initial))
2366 (declare-function remember-buffer-desc "remember" ())
2367 (declare-function remember-finalize "remember" ())
2368 (defvar remember-save-after-remembering)
2369 (defvar remember-data-file)
2370 (defvar remember-register)
2371 (defvar remember-buffer)
2372 (defvar remember-handler-functions)
2373 (defvar remember-annotation-functions)
2374 (defvar texmathp-why)
2375 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2376 (declare-function table--at-cell-p "table" (position &optional object at-column))
2378 (defvar w3m-current-url)
2379 (defvar w3m-current-title)
2381 (defvar org-latex-regexps)
2383 ;;; Autoload and prepare some org modules
2385 ;; Some table stuff that needs to be defined here, because it is used
2386 ;; by the functions setting up org-mode or checking for table context.
2388 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2389 "Detects an org-type or table-type table.")
2390 (defconst org-table-line-regexp "^[ \t]*|"
2391 "Detects an org-type table line.")
2392 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2393 "Detects an org-type table line.")
2394 (defconst org-table-hline-regexp "^[ \t]*|-"
2395 "Detects an org-type table hline.")
2396 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2397 "Detects a table-type table hline.")
2398 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2399 "Searching from within a table (any type) this finds the first line
2400 outside the table.")
2402 ;; Autoload the functions in org-table.el that are needed by functions here.
2404 (eval-and-compile
2405 (org-autoload "org-table"
2406 '(org-table-align org-table-begin org-table-blank-field
2407 org-table-convert org-table-convert-region org-table-copy-down
2408 org-table-copy-region org-table-create
2409 org-table-create-or-convert-from-region
2410 org-table-create-with-table.el org-table-current-dline
2411 org-table-cut-region org-table-delete-column org-table-edit-field
2412 org-table-edit-formulas org-table-end org-table-eval-formula
2413 org-table-export org-table-field-info
2414 org-table-get-stored-formulas org-table-goto-column
2415 org-table-hline-and-move org-table-import org-table-insert-column
2416 org-table-insert-hline org-table-insert-row org-table-iterate
2417 org-table-justify-field-maybe org-table-kill-row
2418 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2419 org-table-move-column org-table-move-column-left
2420 org-table-move-column-right org-table-move-row
2421 org-table-move-row-down org-table-move-row-up
2422 org-table-next-field org-table-next-row org-table-paste-rectangle
2423 org-table-previous-field org-table-recalculate
2424 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2425 org-table-toggle-coordinate-overlays
2426 org-table-toggle-formula-debugger org-table-wrap-region
2427 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
2429 (defun org-at-table-p (&optional table-type)
2430 "Return t if the cursor is inside an org-type table.
2431 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2432 (if org-enable-table-editor
2433 (save-excursion
2434 (beginning-of-line 1)
2435 (looking-at (if table-type org-table-any-line-regexp
2436 org-table-line-regexp)))
2437 nil))
2438 (defsubst org-table-p () (org-at-table-p))
2440 (defun org-at-table.el-p ()
2441 "Return t if and only if we are at a table.el table."
2442 (and (org-at-table-p 'any)
2443 (save-excursion
2444 (goto-char (org-table-begin 'any))
2445 (looking-at org-table1-hline-regexp))))
2446 (defun org-table-recognize-table.el ()
2447 "If there is a table.el table nearby, recognize it and move into it."
2448 (if org-table-tab-recognizes-table.el
2449 (if (org-at-table.el-p)
2450 (progn
2451 (beginning-of-line 1)
2452 (if (looking-at org-table-dataline-regexp)
2454 (if (looking-at org-table1-hline-regexp)
2455 (progn
2456 (beginning-of-line 2)
2457 (if (looking-at org-table-any-border-regexp)
2458 (beginning-of-line -1)))))
2459 (if (re-search-forward "|" (org-table-end t) t)
2460 (progn
2461 (require 'table)
2462 (if (table--at-cell-p (point))
2464 (message "recognizing table.el table...")
2465 (table-recognize-table)
2466 (message "recognizing table.el table...done")))
2467 (error "This should not happen..."))
2469 nil)
2470 nil))
2472 (defun org-at-table-hline-p ()
2473 "Return t if the cursor is inside a hline in a table."
2474 (if org-enable-table-editor
2475 (save-excursion
2476 (beginning-of-line 1)
2477 (looking-at org-table-hline-regexp))
2478 nil))
2480 (defvar org-table-clean-did-remove-column nil)
2482 (defun org-table-map-tables (function)
2483 "Apply FUNCTION to the start of all tables in the buffer."
2484 (save-excursion
2485 (save-restriction
2486 (widen)
2487 (goto-char (point-min))
2488 (while (re-search-forward org-table-any-line-regexp nil t)
2489 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2490 (beginning-of-line 1)
2491 (if (looking-at org-table-line-regexp)
2492 (save-excursion (funcall function)))
2493 (re-search-forward org-table-any-border-regexp nil 1))))
2494 (message "Mapping tables: done"))
2496 ;; Declare and autoload functions from org-exp.el
2498 (declare-function org-default-export-plist "org-exp")
2499 (declare-function org-infile-export-plist "org-exp")
2500 (declare-function org-get-current-options "org-exp")
2501 (eval-and-compile
2502 (org-autoload "org-exp"
2503 '(org-export org-export-as-ascii org-export-visible
2504 org-insert-export-options-template org-export-as-html-and-open
2505 org-export-as-html-batch org-export-as-html-to-buffer
2506 org-replace-region-by-html org-export-region-as-html
2507 org-export-as-html org-export-icalendar-this-file
2508 org-export-icalendar-all-agenda-files
2509 org-table-clean-before-export
2510 org-export-icalendar-combine-agenda-files org-export-as-xoxo)))
2512 ;; Declare and autoload functions from org-agenda.el
2514 (eval-and-compile
2515 (org-autoload "org-agenda"
2516 '(org-agenda org-agenda-list org-search-view
2517 org-todo-list org-tags-view org-agenda-list-stuck-projects
2518 org-diary org-agenda-to-appt)))
2520 ;; Autoload org-remember
2522 (eval-and-compile
2523 (org-autoload "org-remember"
2524 '(org-remember-insinuate org-remember-annotation
2525 org-remember-apply-template org-remember org-remember-handler)))
2527 ;; Autoload org-clock.el
2530 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
2531 (beg end))
2532 (declare-function org-update-mode-line "org-clock" ())
2533 (defvar org-clock-start-time)
2534 (defvar org-clock-marker (make-marker)
2535 "Marker recording the last clock-in.")
2537 (eval-and-compile
2538 (org-autoload
2539 "org-clock"
2540 '(org-clock-in org-clock-out org-clock-cancel
2541 org-clock-goto org-clock-sum org-clock-display
2542 org-remove-clock-overlays org-clock-report
2543 org-clocktable-shift org-dblock-write:clocktable
2544 org-get-clocktable)))
2546 (defun org-clock-update-time-maybe ()
2547 "If this is a CLOCK line, update it and return t.
2548 Otherwise, return nil."
2549 (interactive)
2550 (save-excursion
2551 (beginning-of-line 1)
2552 (skip-chars-forward " \t")
2553 (when (looking-at org-clock-string)
2554 (let ((re (concat "[ \t]*" org-clock-string
2555 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
2556 "\\([ \t]*=>.*\\)?\\)?"))
2557 ts te h m s neg)
2558 (cond
2559 ((not (looking-at re))
2560 nil)
2561 ((not (match-end 2))
2562 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2563 (> org-clock-marker (point))
2564 (<= org-clock-marker (point-at-eol)))
2565 ;; The clock is running here
2566 (setq org-clock-start-time
2567 (apply 'encode-time
2568 (org-parse-time-string (match-string 1))))
2569 (org-update-mode-line)))
2571 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
2572 (end-of-line 1)
2573 (setq ts (match-string 1)
2574 te (match-string 3))
2575 (setq s (- (time-to-seconds
2576 (apply 'encode-time (org-parse-time-string te)))
2577 (time-to-seconds
2578 (apply 'encode-time (org-parse-time-string ts))))
2579 neg (< s 0)
2580 s (abs s)
2581 h (floor (/ s 3600))
2582 s (- s (* 3600 h))
2583 m (floor (/ s 60))
2584 s (- s (* 60 s)))
2585 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
2586 t))))))
2588 (defun org-check-running-clock ()
2589 "Check if the current buffer contains the running clock.
2590 If yes, offer to stop it and to save the buffer with the changes."
2591 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2592 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
2593 (buffer-name))))
2594 (org-clock-out)
2595 (when (y-or-n-p "Save changed buffer?")
2596 (save-buffer))))
2598 (defun org-clocktable-try-shift (dir n)
2599 "Check if this line starts a clock table, if yes, shift the time block."
2600 (when (org-match-line "#\\+BEGIN: clocktable\\>")
2601 (org-clocktable-shift dir n)))
2603 ;; Autoload archiving code
2604 ;; The stuff that is needed for cycling and tags has to be defined here.
2606 (defgroup org-archive nil
2607 "Options concerning archiving in Org-mode."
2608 :tag "Org Archive"
2609 :group 'org-structure)
2611 (defcustom org-archive-location "%s_archive::"
2612 "The location where subtrees should be archived.
2614 Otherwise, the value of this variable is a string, consisting of two
2615 parts, separated by a double-colon.
2617 The first part is a file name - when omitted, archiving happens in the same
2618 file. %s will be replaced by the current file name (without directory part).
2619 Archiving to a different file is useful to keep archived entries from
2620 contributing to the Org-mode Agenda.
2622 The part after the double colon is a headline. The archived entries will be
2623 filed under that headline. When omitted, the subtrees are simply filed away
2624 at the end of the file, as top-level entries.
2626 Here are a few examples:
2627 \"%s_archive::\"
2628 If the current file is Projects.org, archive in file
2629 Projects.org_archive, as top-level trees. This is the default.
2631 \"::* Archived Tasks\"
2632 Archive in the current file, under the top-level headline
2633 \"* Archived Tasks\".
2635 \"~/org/archive.org::\"
2636 Archive in file ~/org/archive.org (absolute path), as top-level trees.
2638 \"basement::** Finished Tasks\"
2639 Archive in file ./basement (relative path), as level 3 trees
2640 below the level 2 heading \"** Finished Tasks\".
2642 You may set this option on a per-file basis by adding to the buffer a
2643 line like
2645 #+ARCHIVE: basement::** Finished Tasks
2647 You may also define it locally for a subtree by setting an ARCHIVE property
2648 in the entry. If such a property is found in an entry, or anywhere up
2649 the hierarchy, it will be used."
2650 :group 'org-archive
2651 :type 'string)
2653 (defcustom org-archive-tag "ARCHIVE"
2654 "The tag that marks a subtree as archived.
2655 An archived subtree does not open during visibility cycling, and does
2656 not contribute to the agenda listings.
2657 After changing this, font-lock must be restarted in the relevant buffers to
2658 get the proper fontification."
2659 :group 'org-archive
2660 :group 'org-keywords
2661 :type 'string)
2663 (defcustom org-agenda-skip-archived-trees t
2664 "Non-nil means, the agenda will skip any items located in archived trees.
2665 An archived tree is a tree marked with the tag ARCHIVE. The use of this
2666 variable is no longer recommended, you should leave it at the value t.
2667 Instead, use the key `v' to cycle the archives-mode in the agenda."
2668 :group 'org-archive
2669 :group 'org-agenda-skip
2670 :type 'boolean)
2672 (defcustom org-cycle-open-archived-trees nil
2673 "Non-nil means, `org-cycle' will open archived trees.
2674 An archived tree is a tree marked with the tag ARCHIVE.
2675 When nil, archived trees will stay folded. You can still open them with
2676 normal outline commands like `show-all', but not with the cycling commands."
2677 :group 'org-archive
2678 :group 'org-cycle
2679 :type 'boolean)
2681 (defcustom org-sparse-tree-open-archived-trees nil
2682 "Non-nil means sparse tree construction shows matches in archived trees.
2683 When nil, matches in these trees are highlighted, but the trees are kept in
2684 collapsed state."
2685 :group 'org-archive
2686 :group 'org-sparse-trees
2687 :type 'boolean)
2689 (defun org-cycle-hide-archived-subtrees (state)
2690 "Re-hide all archived subtrees after a visibility state change."
2691 (when (and (not org-cycle-open-archived-trees)
2692 (not (memq state '(overview folded))))
2693 (save-excursion
2694 (let* ((globalp (memq state '(contents all)))
2695 (beg (if globalp (point-min) (point)))
2696 (end (if globalp (point-max) (org-end-of-subtree t))))
2697 (org-hide-archived-subtrees beg end)
2698 (goto-char beg)
2699 (if (looking-at (concat ".*:" org-archive-tag ":"))
2700 (message "%s" (substitute-command-keys
2701 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
2703 (defun org-force-cycle-archived ()
2704 "Cycle subtree even if it is archived."
2705 (interactive)
2706 (setq this-command 'org-cycle)
2707 (let ((org-cycle-open-archived-trees t))
2708 (call-interactively 'org-cycle)))
2710 (defun org-hide-archived-subtrees (beg end)
2711 "Re-hide all archived subtrees after a visibility state change."
2712 (save-excursion
2713 (let* ((re (concat ":" org-archive-tag ":")))
2714 (goto-char beg)
2715 (while (re-search-forward re end t)
2716 (and (org-on-heading-p) (hide-subtree))
2717 (org-end-of-subtree t)))))
2719 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
2721 (eval-and-compile
2722 (org-autoload "org-archive"
2723 '(org-add-archive-files org-archive-subtree
2724 org-archive-to-archive-sibling org-toggle-archive-tag)))
2726 ;; Autoload Column View Code
2728 (declare-function org-columns-number-to-string "org-colview")
2729 (declare-function org-columns-get-format-and-top-level "org-colview")
2730 (declare-function org-columns-compute "org-colview")
2732 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
2733 '(org-columns-number-to-string org-columns-get-format-and-top-level
2734 org-columns-compute org-agenda-columns org-columns-remove-overlays
2735 org-columns org-insert-columns-dblock org-dblock-write:columnview))
2737 ;; Autoload ID code
2739 (org-autoload "org-id"
2740 '(org-id-get-create org-id-new org-id-copy org-id-get
2741 org-id-get-with-outline-path-completion
2742 org-id-get-with-outline-drilling
2743 org-id-goto org-id-find))
2745 ;;; Variables for pre-computed regular expressions, all buffer local
2747 (defvar org-drawer-regexp nil
2748 "Matches first line of a hidden block.")
2749 (make-variable-buffer-local 'org-drawer-regexp)
2750 (defvar org-todo-regexp nil
2751 "Matches any of the TODO state keywords.")
2752 (make-variable-buffer-local 'org-todo-regexp)
2753 (defvar org-not-done-regexp nil
2754 "Matches any of the TODO state keywords except the last one.")
2755 (make-variable-buffer-local 'org-not-done-regexp)
2756 (defvar org-todo-line-regexp nil
2757 "Matches a headline and puts TODO state into group 2 if present.")
2758 (make-variable-buffer-local 'org-todo-line-regexp)
2759 (defvar org-complex-heading-regexp nil
2760 "Matches a headline and puts everything into groups:
2761 group 1: the stars
2762 group 2: The todo keyword, maybe
2763 group 3: Priority cookie
2764 group 4: True headline
2765 group 5: Tags")
2766 (make-variable-buffer-local 'org-complex-heading-regexp)
2767 (defvar org-todo-line-tags-regexp nil
2768 "Matches a headline and puts TODO state into group 2 if present.
2769 Also put tags into group 4 if tags are present.")
2770 (make-variable-buffer-local 'org-todo-line-tags-regexp)
2771 (defvar org-nl-done-regexp nil
2772 "Matches newline followed by a headline with the DONE keyword.")
2773 (make-variable-buffer-local 'org-nl-done-regexp)
2774 (defvar org-looking-at-done-regexp nil
2775 "Matches the DONE keyword a point.")
2776 (make-variable-buffer-local 'org-looking-at-done-regexp)
2777 (defvar org-ds-keyword-length 12
2778 "Maximum length of the Deadline and SCHEDULED keywords.")
2779 (make-variable-buffer-local 'org-ds-keyword-length)
2780 (defvar org-deadline-regexp nil
2781 "Matches the DEADLINE keyword.")
2782 (make-variable-buffer-local 'org-deadline-regexp)
2783 (defvar org-deadline-time-regexp nil
2784 "Matches the DEADLINE keyword together with a time stamp.")
2785 (make-variable-buffer-local 'org-deadline-time-regexp)
2786 (defvar org-deadline-line-regexp nil
2787 "Matches the DEADLINE keyword and the rest of the line.")
2788 (make-variable-buffer-local 'org-deadline-line-regexp)
2789 (defvar org-scheduled-regexp nil
2790 "Matches the SCHEDULED keyword.")
2791 (make-variable-buffer-local 'org-scheduled-regexp)
2792 (defvar org-scheduled-time-regexp nil
2793 "Matches the SCHEDULED keyword together with a time stamp.")
2794 (make-variable-buffer-local 'org-scheduled-time-regexp)
2795 (defvar org-closed-time-regexp nil
2796 "Matches the CLOSED keyword together with a time stamp.")
2797 (make-variable-buffer-local 'org-closed-time-regexp)
2799 (defvar org-keyword-time-regexp nil
2800 "Matches any of the 4 keywords, together with the time stamp.")
2801 (make-variable-buffer-local 'org-keyword-time-regexp)
2802 (defvar org-keyword-time-not-clock-regexp nil
2803 "Matches any of the 3 keywords, together with the time stamp.")
2804 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
2805 (defvar org-maybe-keyword-time-regexp nil
2806 "Matches a timestamp, possibly preceeded by a keyword.")
2807 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
2808 (defvar org-planning-or-clock-line-re nil
2809 "Matches a line with planning or clock info.")
2810 (make-variable-buffer-local 'org-planning-or-clock-line-re)
2812 (defconst org-plain-time-of-day-regexp
2813 (concat
2814 "\\(\\<[012]?[0-9]"
2815 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2816 "\\(--?"
2817 "\\(\\<[012]?[0-9]"
2818 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2819 "\\)?")
2820 "Regular expression to match a plain time or time range.
2821 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2822 groups carry important information:
2823 0 the full match
2824 1 the first time, range or not
2825 8 the second time, if it is a range.")
2827 (defconst org-plain-time-extension-regexp
2828 (concat
2829 "\\(\\<[012]?[0-9]"
2830 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2831 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
2832 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
2833 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2834 groups carry important information:
2835 0 the full match
2836 7 hours of duration
2837 9 minutes of duration")
2839 (defconst org-stamp-time-of-day-regexp
2840 (concat
2841 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
2842 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
2843 "\\(--?"
2844 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
2845 "Regular expression to match a timestamp time or time range.
2846 After a match, the following groups carry important information:
2847 0 the full match
2848 1 date plus weekday, for backreferencing to make sure both times on same day
2849 2 the first time, range or not
2850 4 the second time, if it is a range.")
2852 (defconst org-startup-options
2853 '(("fold" org-startup-folded t)
2854 ("overview" org-startup-folded t)
2855 ("nofold" org-startup-folded nil)
2856 ("showall" org-startup-folded nil)
2857 ("content" org-startup-folded content)
2858 ("hidestars" org-hide-leading-stars t)
2859 ("showstars" org-hide-leading-stars nil)
2860 ("odd" org-odd-levels-only t)
2861 ("oddeven" org-odd-levels-only nil)
2862 ("align" org-startup-align-all-tables t)
2863 ("noalign" org-startup-align-all-tables nil)
2864 ("customtime" org-display-custom-times t)
2865 ("logdone" org-log-done time)
2866 ("lognotedone" org-log-done note)
2867 ("nologdone" org-log-done nil)
2868 ("lognoteclock-out" org-log-note-clock-out t)
2869 ("nolognoteclock-out" org-log-note-clock-out nil)
2870 ("logrepeat" org-log-repeat state)
2871 ("lognoterepeat" org-log-repeat note)
2872 ("nologrepeat" org-log-repeat nil)
2873 ("constcgs" constants-unit-system cgs)
2874 ("constSI" constants-unit-system SI))
2875 "Variable associated with STARTUP options for org-mode.
2876 Each element is a list of three items: The startup options as written
2877 in the #+STARTUP line, the corresponding variable, and the value to
2878 set this variable to if the option is found. An optional forth element PUSH
2879 means to push this value onto the list in the variable.")
2881 (defun org-set-regexps-and-options ()
2882 "Precompute regular expressions for current buffer."
2883 (when (org-mode-p)
2884 (org-set-local 'org-todo-kwd-alist nil)
2885 (org-set-local 'org-todo-key-alist nil)
2886 (org-set-local 'org-todo-key-trigger nil)
2887 (org-set-local 'org-todo-keywords-1 nil)
2888 (org-set-local 'org-done-keywords nil)
2889 (org-set-local 'org-todo-heads nil)
2890 (org-set-local 'org-todo-sets nil)
2891 (org-set-local 'org-todo-log-states nil)
2892 (org-set-local 'org-file-properties nil)
2893 (org-set-local 'org-file-tags nil)
2894 (let ((re (org-make-options-regexp
2895 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
2896 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
2897 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")))
2898 (splitre "[ \t]+")
2899 kwds kws0 kwsa key log value cat arch tags const links hw dws
2900 tail sep kws1 prio props ftags drawers
2901 ext-setup-or-nil setup-contents (start 0))
2902 (save-excursion
2903 (save-restriction
2904 (widen)
2905 (goto-char (point-min))
2906 (while (or (and ext-setup-or-nil
2907 (string-match re ext-setup-or-nil start)
2908 (setq start (match-end 0)))
2909 (and (setq ext-setup-or-nil nil start 0)
2910 (re-search-forward re nil t)))
2911 (setq key (upcase (match-string 1 ext-setup-or-nil))
2912 value (org-match-string-no-properties 2 ext-setup-or-nil))
2913 (cond
2914 ((equal key "CATEGORY")
2915 (if (string-match "[ \t]+$" value)
2916 (setq value (replace-match "" t t value)))
2917 (setq cat value))
2918 ((member key '("SEQ_TODO" "TODO"))
2919 (push (cons 'sequence (org-split-string value splitre)) kwds))
2920 ((equal key "TYP_TODO")
2921 (push (cons 'type (org-split-string value splitre)) kwds))
2922 ((equal key "TAGS")
2923 (setq tags (append tags (org-split-string value splitre))))
2924 ((equal key "COLUMNS")
2925 (org-set-local 'org-columns-default-format value))
2926 ((equal key "LINK")
2927 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
2928 (push (cons (match-string 1 value)
2929 (org-trim (match-string 2 value)))
2930 links)))
2931 ((equal key "PRIORITIES")
2932 (setq prio (org-split-string value " +")))
2933 ((equal key "PROPERTY")
2934 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
2935 (push (cons (match-string 1 value) (match-string 2 value))
2936 props)))
2937 ((equal key "FILETAGS")
2938 (when (string-match "\\S-" value)
2939 (setq ftags
2940 (append
2941 ftags
2942 (apply 'append
2943 (mapcar (lambda (x) (org-split-string x ":"))
2944 (org-split-string value)))))))
2945 ((equal key "DRAWERS")
2946 (setq drawers (org-split-string value splitre)))
2947 ((equal key "CONSTANTS")
2948 (setq const (append const (org-split-string value splitre))))
2949 ((equal key "STARTUP")
2950 (let ((opts (org-split-string value splitre))
2951 l var val)
2952 (while (setq l (pop opts))
2953 (when (setq l (assoc l org-startup-options))
2954 (setq var (nth 1 l) val (nth 2 l))
2955 (if (not (nth 3 l))
2956 (set (make-local-variable var) val)
2957 (if (not (listp (symbol-value var)))
2958 (set (make-local-variable var) nil))
2959 (set (make-local-variable var) (symbol-value var))
2960 (add-to-list var val))))))
2961 ((equal key "ARCHIVE")
2962 (string-match " *$" value)
2963 (setq arch (replace-match "" t t value))
2964 (remove-text-properties 0 (length arch)
2965 '(face t fontified t) arch))
2966 ((equal key "SETUPFILE")
2967 (setq setup-contents (org-file-contents
2968 (expand-file-name
2969 (org-remove-double-quotes value))
2970 'noerror))
2971 (if (not ext-setup-or-nil)
2972 (setq ext-setup-or-nil setup-contents start 0)
2973 (setq ext-setup-or-nil
2974 (concat (substring ext-setup-or-nil 0 start)
2975 "\n" setup-contents "\n"
2976 (substring ext-setup-or-nil start)))))
2977 ))))
2978 (when cat
2979 (org-set-local 'org-category (intern cat))
2980 (push (cons "CATEGORY" cat) props))
2981 (when prio
2982 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
2983 (setq prio (mapcar 'string-to-char prio))
2984 (org-set-local 'org-highest-priority (nth 0 prio))
2985 (org-set-local 'org-lowest-priority (nth 1 prio))
2986 (org-set-local 'org-default-priority (nth 2 prio)))
2987 (and props (org-set-local 'org-file-properties (nreverse props)))
2988 (and ftags (org-set-local 'org-file-tags ftags))
2989 (and drawers (org-set-local 'org-drawers drawers))
2990 (and arch (org-set-local 'org-archive-location arch))
2991 (and links (setq org-link-abbrev-alist-local (nreverse links)))
2992 ;; Process the TODO keywords
2993 (unless kwds
2994 ;; Use the global values as if they had been given locally.
2995 (setq kwds (default-value 'org-todo-keywords))
2996 (if (stringp (car kwds))
2997 (setq kwds (list (cons org-todo-interpretation
2998 (default-value 'org-todo-keywords)))))
2999 (setq kwds (reverse kwds)))
3000 (setq kwds (nreverse kwds))
3001 (let (inter kws kw)
3002 (while (setq kws (pop kwds))
3003 (setq inter (pop kws) sep (member "|" kws)
3004 kws0 (delete "|" (copy-sequence kws))
3005 kwsa nil
3006 kws1 (mapcar
3007 (lambda (x)
3008 ;; 1 2
3009 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3010 (progn
3011 (setq kw (match-string 1 x)
3012 key (and (match-end 2) (match-string 2 x))
3013 log (org-extract-log-state-settings x))
3014 (push (cons kw (and key (string-to-char key))) kwsa)
3015 (and log (push log org-todo-log-states))
3017 (error "Invalid TODO keyword %s" x)))
3018 kws0)
3019 kwsa (if kwsa (append '((:startgroup))
3020 (nreverse kwsa)
3021 '((:endgroup))))
3022 hw (car kws1)
3023 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3024 tail (list inter hw (car dws) (org-last dws)))
3025 (add-to-list 'org-todo-heads hw 'append)
3026 (push kws1 org-todo-sets)
3027 (setq org-done-keywords (append org-done-keywords dws nil))
3028 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3029 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3030 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3031 (setq org-todo-sets (nreverse org-todo-sets)
3032 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3033 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3034 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3035 ;; Process the constants
3036 (when const
3037 (let (e cst)
3038 (while (setq e (pop const))
3039 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3040 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3041 (setq org-table-formula-constants-local cst)))
3043 ;; Process the tags.
3044 (when tags
3045 (let (e tgs)
3046 (while (setq e (pop tags))
3047 (cond
3048 ((equal e "{") (push '(:startgroup) tgs))
3049 ((equal e "}") (push '(:endgroup) tgs))
3050 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3051 (push (cons (match-string 1 e)
3052 (string-to-char (match-string 2 e)))
3053 tgs))
3054 (t (push (list e) tgs))))
3055 (org-set-local 'org-tag-alist nil)
3056 (while (setq e (pop tgs))
3057 (or (and (stringp (car e))
3058 (assoc (car e) org-tag-alist))
3059 (push e org-tag-alist)))))
3061 ;; Compute the regular expressions and other local variables
3062 (if (not org-done-keywords)
3063 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
3064 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3065 (length org-scheduled-string)
3066 (length org-clock-string)
3067 (length org-closed-string)))
3068 org-drawer-regexp
3069 (concat "^[ \t]*:\\("
3070 (mapconcat 'regexp-quote org-drawers "\\|")
3071 "\\):[ \t]*$")
3072 org-not-done-keywords
3073 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3074 org-todo-regexp
3075 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3076 "\\|") "\\)\\>")
3077 org-not-done-regexp
3078 (concat "\\<\\("
3079 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3080 "\\)\\>")
3081 org-todo-line-regexp
3082 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3083 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3084 "\\)\\>\\)?[ \t]*\\(.*\\)")
3085 org-complex-heading-regexp
3086 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
3087 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3088 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3089 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3090 org-nl-done-regexp
3091 (concat "\n\\*+[ \t]+"
3092 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3093 "\\)" "\\>")
3094 org-todo-line-tags-regexp
3095 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3096 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3097 (org-re
3098 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3099 org-looking-at-done-regexp
3100 (concat "^" "\\(?:"
3101 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3102 "\\>")
3103 org-deadline-regexp (concat "\\<" org-deadline-string)
3104 org-deadline-time-regexp
3105 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3106 org-deadline-line-regexp
3107 (concat "\\<\\(" org-deadline-string "\\).*")
3108 org-scheduled-regexp
3109 (concat "\\<" org-scheduled-string)
3110 org-scheduled-time-regexp
3111 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3112 org-closed-time-regexp
3113 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3114 org-keyword-time-regexp
3115 (concat "\\<\\(" org-scheduled-string
3116 "\\|" org-deadline-string
3117 "\\|" org-closed-string
3118 "\\|" org-clock-string "\\)"
3119 " *[[<]\\([^]>]+\\)[]>]")
3120 org-keyword-time-not-clock-regexp
3121 (concat "\\<\\(" org-scheduled-string
3122 "\\|" org-deadline-string
3123 "\\|" org-closed-string
3124 "\\)"
3125 " *[[<]\\([^]>]+\\)[]>]")
3126 org-maybe-keyword-time-regexp
3127 (concat "\\(\\<\\(" org-scheduled-string
3128 "\\|" org-deadline-string
3129 "\\|" org-closed-string
3130 "\\|" org-clock-string "\\)\\)?"
3131 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3132 org-planning-or-clock-line-re
3133 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3134 "\\|" org-deadline-string
3135 "\\|" org-closed-string "\\|" org-clock-string
3136 "\\)\\>\\)")
3138 (org-compute-latex-and-specials-regexp)
3139 (org-set-font-lock-defaults))))
3141 (defun org-file-contents (file &optional noerror)
3142 "Return the contents of FILE, as a string."
3143 (if (or (not file)
3144 (not (file-readable-p file)))
3145 (if noerror
3146 (progn
3147 (message "Cannot read file %s" file)
3148 (ding) (sit-for 2)
3150 (error "Cannot read file %s" file))
3151 (with-temp-buffer
3152 (insert-file-contents file)
3153 (buffer-string))))
3155 (defun org-extract-log-state-settings (x)
3156 "Extract the log state setting from a TODO keyword string.
3157 This will extract info from a string like \"WAIT(w@/!)\"."
3158 (let (kw key log1 log2)
3159 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3160 (setq kw (match-string 1 x)
3161 key (and (match-end 2) (match-string 2 x))
3162 log1 (and (match-end 3) (match-string 3 x))
3163 log2 (and (match-end 4) (match-string 4 x)))
3164 (and (or log1 log2)
3165 (list kw
3166 (and log1 (if (equal log1 "!") 'time 'note))
3167 (and log2 (if (equal log2 "!") 'time 'note)))))))
3169 (defun org-remove-keyword-keys (list)
3170 "Remove a pair of parenthesis at the end of each string in LIST."
3171 (mapcar (lambda (x)
3172 (if (string-match "(.*)$" x)
3173 (substring x 0 (match-beginning 0))
3175 list))
3177 ;; FIXME: this could be done much better, using second characters etc.
3178 (defun org-assign-fast-keys (alist)
3179 "Assign fast keys to a keyword-key alist.
3180 Respect keys that are already there."
3181 (let (new e k c c1 c2 (char ?a))
3182 (while (setq e (pop alist))
3183 (cond
3184 ((equal e '(:startgroup)) (push e new))
3185 ((equal e '(:endgroup)) (push e new))
3187 (setq k (car e) c2 nil)
3188 (if (cdr e)
3189 (setq c (cdr e))
3190 ;; automatically assign a character.
3191 (setq c1 (string-to-char
3192 (downcase (substring
3193 k (if (= (string-to-char k) ?@) 1 0)))))
3194 (if (or (rassoc c1 new) (rassoc c1 alist))
3195 (while (or (rassoc char new) (rassoc char alist))
3196 (setq char (1+ char)))
3197 (setq c2 c1))
3198 (setq c (or c2 char)))
3199 (push (cons k c) new))))
3200 (nreverse new)))
3202 ;;; Some variables used in various places
3204 (defvar org-window-configuration nil
3205 "Used in various places to store a window configuration.")
3206 (defvar org-finish-function nil
3207 "Function to be called when `C-c C-c' is used.
3208 This is for getting out of special buffers like remember.")
3211 ;; FIXME: Occasionally check by commenting these, to make sure
3212 ;; no other functions uses these, forgetting to let-bind them.
3213 (defvar entry)
3214 (defvar state)
3215 (defvar last-state)
3216 (defvar date)
3217 (defvar description)
3219 ;; Defined somewhere in this file, but used before definition.
3220 (defvar org-html-entities)
3221 (defvar org-struct-menu)
3222 (defvar org-org-menu)
3223 (defvar org-tbl-menu)
3224 (defvar org-agenda-keymap)
3226 ;;;; Define the Org-mode
3228 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3229 (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."))
3232 ;; We use a before-change function to check if a table might need
3233 ;; an update.
3234 (defvar org-table-may-need-update t
3235 "Indicates that a table might need an update.
3236 This variable is set by `org-before-change-function'.
3237 `org-table-align' sets it back to nil.")
3238 (defun org-before-change-function (beg end)
3239 "Every change indicates that a table might need an update."
3240 (setq org-table-may-need-update t))
3241 (defvar org-mode-map)
3242 (defvar org-mode-hook nil)
3243 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3244 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3245 (defvar org-table-buffer-is-an nil)
3246 (defconst org-outline-regexp "\\*+ ")
3248 ;;;###autoload
3249 (define-derived-mode org-mode outline-mode "Org"
3250 "Outline-based notes management and organizer, alias
3251 \"Carsten's outline-mode for keeping track of everything.\"
3253 Org-mode develops organizational tasks around a NOTES file which
3254 contains information about projects as plain text. Org-mode is
3255 implemented on top of outline-mode, which is ideal to keep the content
3256 of large files well structured. It supports ToDo items, deadlines and
3257 time stamps, which magically appear in the diary listing of the Emacs
3258 calendar. Tables are easily created with a built-in table editor.
3259 Plain text URL-like links connect to websites, emails (VM), Usenet
3260 messages (Gnus), BBDB entries, and any files related to the project.
3261 For printing and sharing of notes, an Org-mode file (or a part of it)
3262 can be exported as a structured ASCII or HTML file.
3264 The following commands are available:
3266 \\{org-mode-map}"
3268 ;; Get rid of Outline menus, they are not needed
3269 ;; Need to do this here because define-derived-mode sets up
3270 ;; the keymap so late. Still, it is a waste to call this each time
3271 ;; we switch another buffer into org-mode.
3272 (if (featurep 'xemacs)
3273 (when (boundp 'outline-mode-menu-heading)
3274 ;; Assume this is Greg's port, it used easymenu
3275 (easy-menu-remove outline-mode-menu-heading)
3276 (easy-menu-remove outline-mode-menu-show)
3277 (easy-menu-remove outline-mode-menu-hide))
3278 (define-key org-mode-map [menu-bar headings] 'undefined)
3279 (define-key org-mode-map [menu-bar hide] 'undefined)
3280 (define-key org-mode-map [menu-bar show] 'undefined))
3282 (org-load-modules-maybe)
3283 (easy-menu-add org-org-menu)
3284 (easy-menu-add org-tbl-menu)
3285 (org-install-agenda-files-menu)
3286 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3287 (org-add-to-invisibility-spec '(org-cwidth))
3288 (when (featurep 'xemacs)
3289 (org-set-local 'line-move-ignore-invisible t))
3290 (org-set-local 'outline-regexp org-outline-regexp)
3291 (org-set-local 'outline-level 'org-outline-level)
3292 (when (and org-ellipsis
3293 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3294 (fboundp 'make-glyph-code))
3295 (unless org-display-table
3296 (setq org-display-table (make-display-table)))
3297 (set-display-table-slot
3298 org-display-table 4
3299 (vconcat (mapcar
3300 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3301 org-ellipsis)))
3302 (if (stringp org-ellipsis) org-ellipsis "..."))))
3303 (setq buffer-display-table org-display-table))
3304 (org-set-regexps-and-options)
3305 ;; Calc embedded
3306 (org-set-local 'calc-embedded-open-mode "# ")
3307 (modify-syntax-entry ?# "<")
3308 (modify-syntax-entry ?@ "w")
3309 (if org-startup-truncated (setq truncate-lines t))
3310 (org-set-local 'font-lock-unfontify-region-function
3311 'org-unfontify-region)
3312 ;; Activate before-change-function
3313 (org-set-local 'org-table-may-need-update t)
3314 (org-add-hook 'before-change-functions 'org-before-change-function nil
3315 'local)
3316 ;; Check for running clock before killing a buffer
3317 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3318 ;; Paragraphs and auto-filling
3319 (org-set-autofill-regexps)
3320 (setq indent-line-function 'org-indent-line-function)
3321 (org-update-radio-target-regexp)
3323 ;; Comment characters
3324 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3325 (org-set-local 'comment-padding " ")
3327 ;; Align options lines
3328 (org-set-local
3329 'align-mode-rules-list
3330 '((org-in-buffer-settings
3331 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3332 (modes . '(org-mode)))))
3334 ;; Imenu
3335 (org-set-local 'imenu-create-index-function
3336 'org-imenu-get-tree)
3338 ;; Make isearch reveal context
3339 (if (or (featurep 'xemacs)
3340 (not (boundp 'outline-isearch-open-invisible-function)))
3341 ;; Emacs 21 and XEmacs make use of the hook
3342 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3343 ;; Emacs 22 deals with this through a special variable
3344 (org-set-local 'outline-isearch-open-invisible-function
3345 (lambda (&rest ignore) (org-show-context 'isearch))))
3347 ;; If empty file that did not turn on org-mode automatically, make it to.
3348 (if (and org-insert-mode-line-in-empty-file
3349 (interactive-p)
3350 (= (point-min) (point-max)))
3351 (insert "# -*- mode: org -*-\n\n"))
3353 (unless org-inhibit-startup
3354 (when org-startup-align-all-tables
3355 (let ((bmp (buffer-modified-p)))
3356 (org-table-map-tables 'org-table-align)
3357 (set-buffer-modified-p bmp)))
3358 (org-set-startup-visibility)))
3360 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3362 (defun org-current-time ()
3363 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3364 (if (> (car org-time-stamp-rounding-minutes) 1)
3365 (let ((r (car org-time-stamp-rounding-minutes))
3366 (time (decode-time)))
3367 (apply 'encode-time
3368 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3369 (nthcdr 2 time))))
3370 (current-time)))
3372 ;;;; Font-Lock stuff, including the activators
3374 (defvar org-mouse-map (make-sparse-keymap))
3375 (org-defkey org-mouse-map
3376 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3377 (org-defkey org-mouse-map
3378 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3379 (when org-mouse-1-follows-link
3380 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3381 (when org-tab-follows-link
3382 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3383 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3384 (when org-return-follows-link
3385 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
3386 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
3388 (require 'font-lock)
3390 (defconst org-non-link-chars "]\t\n\r<>")
3391 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3392 "shell" "elisp"))
3393 (defvar org-link-types-re nil
3394 "Matches a link that has a url-like prefix like \"http:\"")
3395 (defvar org-link-re-with-space nil
3396 "Matches a link with spaces, optional angular brackets around it.")
3397 (defvar org-link-re-with-space2 nil
3398 "Matches a link with spaces, optional angular brackets around it.")
3399 (defvar org-angle-link-re nil
3400 "Matches link with angular brackets, spaces are allowed.")
3401 (defvar org-plain-link-re nil
3402 "Matches plain link, without spaces.")
3403 (defvar org-bracket-link-regexp nil
3404 "Matches a link in double brackets.")
3405 (defvar org-bracket-link-analytic-regexp nil
3406 "Regular expression used to analyze links.
3407 Here is what the match groups contain after a match:
3408 1: http:
3409 2: http
3410 3: path
3411 4: [desc]
3412 5: desc")
3413 (defvar org-any-link-re nil
3414 "Regular expression matching any link.")
3416 (defun org-make-link-regexps ()
3417 "Update the link regular expressions.
3418 This should be called after the variable `org-link-types' has changed."
3419 (setq org-link-types-re
3420 (concat
3421 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3422 org-link-re-with-space
3423 (concat
3424 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3425 "\\([^" org-non-link-chars " ]"
3426 "[^" org-non-link-chars "]*"
3427 "[^" org-non-link-chars " ]\\)>?")
3428 org-link-re-with-space2
3429 (concat
3430 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3431 "\\([^" org-non-link-chars " ]"
3432 "[^]\t\n\r]*"
3433 "[^" org-non-link-chars " ]\\)>?")
3434 org-angle-link-re
3435 (concat
3436 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3437 "\\([^" org-non-link-chars " ]"
3438 "[^" org-non-link-chars "]*"
3439 "\\)>")
3440 org-plain-link-re
3441 (concat
3442 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3443 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3444 org-bracket-link-regexp
3445 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3446 org-bracket-link-analytic-regexp
3447 (concat
3448 "\\[\\["
3449 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3450 "\\([^]]+\\)"
3451 "\\]"
3452 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3453 "\\]")
3454 org-any-link-re
3455 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3456 org-angle-link-re "\\)\\|\\("
3457 org-plain-link-re "\\)")))
3459 (org-make-link-regexps)
3461 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
3462 "Regular expression for fast time stamp matching.")
3463 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
3464 "Regular expression for fast time stamp matching.")
3465 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3466 "Regular expression matching time strings for analysis.
3467 This one does not require the space after the date, so it can be used
3468 on a string that terminates immediately after the date.")
3469 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3470 "Regular expression matching time strings for analysis.")
3471 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
3472 "Regular expression matching time stamps, with groups.")
3473 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
3474 "Regular expression matching time stamps (also [..]), with groups.")
3475 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3476 "Regular expression matching a time stamp range.")
3477 (defconst org-tr-regexp-both
3478 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3479 "Regular expression matching a time stamp range.")
3480 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3481 org-ts-regexp "\\)?")
3482 "Regular expression matching a time stamp or time stamp range.")
3483 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3484 org-ts-regexp-both "\\)?")
3485 "Regular expression matching a time stamp or time stamp range.
3486 The time stamps may be either active or inactive.")
3488 (defvar org-emph-face nil)
3490 (defun org-do-emphasis-faces (limit)
3491 "Run through the buffer and add overlays to links."
3492 (let (rtn)
3493 (while (and (not rtn) (re-search-forward org-emph-re limit t))
3494 (if (not (= (char-after (match-beginning 3))
3495 (char-after (match-beginning 4))))
3496 (progn
3497 (setq rtn t)
3498 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3499 'face
3500 (nth 1 (assoc (match-string 3)
3501 org-emphasis-alist)))
3502 (add-text-properties (match-beginning 2) (match-end 2)
3503 '(font-lock-multiline t))
3504 (when org-hide-emphasis-markers
3505 (add-text-properties (match-end 4) (match-beginning 5)
3506 '(invisible org-link))
3507 (add-text-properties (match-beginning 3) (match-end 3)
3508 '(invisible org-link)))))
3509 (backward-char 1))
3510 rtn))
3512 (defun org-emphasize (&optional char)
3513 "Insert or change an emphasis, i.e. a font like bold or italic.
3514 If there is an active region, change that region to a new emphasis.
3515 If there is no region, just insert the marker characters and position
3516 the cursor between them.
3517 CHAR should be either the marker character, or the first character of the
3518 HTML tag associated with that emphasis. If CHAR is a space, the means
3519 to remove the emphasis of the selected region.
3520 If char is not given (for example in an interactive call) it
3521 will be prompted for."
3522 (interactive)
3523 (let ((eal org-emphasis-alist) e det
3524 (erc org-emphasis-regexp-components)
3525 (prompt "")
3526 (string "") beg end move tag c s)
3527 (if (org-region-active-p)
3528 (setq beg (region-beginning) end (region-end)
3529 string (buffer-substring beg end))
3530 (setq move t))
3532 (while (setq e (pop eal))
3533 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
3534 c (aref tag 0))
3535 (push (cons c (string-to-char (car e))) det)
3536 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
3537 (substring tag 1)))))
3538 (setq det (nreverse det))
3539 (unless char
3540 (message "%s" (concat "Emphasis marker or tag:" prompt))
3541 (setq char (read-char-exclusive)))
3542 (setq char (or (cdr (assoc char det)) char))
3543 (if (equal char ?\ )
3544 (setq s "" move nil)
3545 (unless (assoc (char-to-string char) org-emphasis-alist)
3546 (error "No such emphasis marker: \"%c\"" char))
3547 (setq s (char-to-string char)))
3548 (while (and (> (length string) 1)
3549 (equal (substring string 0 1) (substring string -1))
3550 (assoc (substring string 0 1) org-emphasis-alist))
3551 (setq string (substring string 1 -1)))
3552 (setq string (concat s string s))
3553 (if beg (delete-region beg end))
3554 (unless (or (bolp)
3555 (string-match (concat "[" (nth 0 erc) "\n]")
3556 (char-to-string (char-before (point)))))
3557 (insert " "))
3558 (unless (string-match (concat "[" (nth 1 erc) "\n]")
3559 (char-to-string (char-after (point))))
3560 (insert " ") (backward-char 1))
3561 (insert string)
3562 (and move (backward-char 1))))
3564 (defconst org-nonsticky-props
3565 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
3568 (defun org-activate-plain-links (limit)
3569 "Run through the buffer and add overlays to links."
3570 (catch 'exit
3571 (let (f)
3572 (while (re-search-forward org-plain-link-re limit t)
3573 (setq f (get-text-property (match-beginning 0) 'face))
3574 (if (or (eq f 'org-tag)
3575 (and (listp f) (memq 'org-tag f)))
3577 (add-text-properties (match-beginning 0) (match-end 0)
3578 (list 'mouse-face 'highlight
3579 'rear-nonsticky org-nonsticky-props
3580 'keymap org-mouse-map
3582 (throw 'exit t))))))
3584 (defun org-activate-code (limit)
3585 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
3586 (progn
3587 (remove-text-properties (match-beginning 0) (match-end 0)
3588 '(display t invisible t intangible t))
3589 t)))
3591 (defun org-activate-angle-links (limit)
3592 "Run through the buffer and add overlays to links."
3593 (if (re-search-forward org-angle-link-re limit t)
3594 (progn
3595 (add-text-properties (match-beginning 0) (match-end 0)
3596 (list 'mouse-face 'highlight
3597 'rear-nonsticky org-nonsticky-props
3598 'keymap org-mouse-map
3600 t)))
3602 (defun org-activate-bracket-links (limit)
3603 "Run through the buffer and add overlays to bracketed links."
3604 (if (re-search-forward org-bracket-link-regexp limit t)
3605 (let* ((help (concat "LINK: "
3606 (org-match-string-no-properties 1)))
3607 ;; FIXME: above we should remove the escapes.
3608 ;; but that requires another match, protecting match data,
3609 ;; a lot of overhead for font-lock.
3610 (ip (org-maybe-intangible
3611 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
3612 'keymap org-mouse-map 'mouse-face 'highlight
3613 'font-lock-multiline t 'help-echo help)))
3614 (vp (list 'rear-nonsticky org-nonsticky-props
3615 'keymap org-mouse-map 'mouse-face 'highlight
3616 ' font-lock-multiline t 'help-echo help)))
3617 ;; We need to remove the invisible property here. Table narrowing
3618 ;; may have made some of this invisible.
3619 (remove-text-properties (match-beginning 0) (match-end 0)
3620 '(invisible nil))
3621 (if (match-end 3)
3622 (progn
3623 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3624 (add-text-properties (match-beginning 3) (match-end 3) vp)
3625 (add-text-properties (match-end 3) (match-end 0) ip))
3626 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3627 (add-text-properties (match-beginning 1) (match-end 1) vp)
3628 (add-text-properties (match-end 1) (match-end 0) ip))
3629 t)))
3631 (defun org-activate-dates (limit)
3632 "Run through the buffer and add overlays to dates."
3633 (if (re-search-forward org-tsr-regexp-both limit t)
3634 (progn
3635 (add-text-properties (match-beginning 0) (match-end 0)
3636 (list 'mouse-face 'highlight
3637 'rear-nonsticky org-nonsticky-props
3638 'keymap org-mouse-map))
3639 (when org-display-custom-times
3640 (if (match-end 3)
3641 (org-display-custom-time (match-beginning 3) (match-end 3)))
3642 (org-display-custom-time (match-beginning 1) (match-end 1)))
3643 t)))
3645 (defvar org-target-link-regexp nil
3646 "Regular expression matching radio targets in plain text.")
3647 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3648 "Regular expression matching a link target.")
3649 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3650 "Regular expression matching a radio target.")
3651 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
3652 "Regular expression matching any target.")
3654 (defun org-activate-target-links (limit)
3655 "Run through the buffer and add overlays to target matches."
3656 (when org-target-link-regexp
3657 (let ((case-fold-search t))
3658 (if (re-search-forward org-target-link-regexp limit t)
3659 (progn
3660 (add-text-properties (match-beginning 0) (match-end 0)
3661 (list 'mouse-face 'highlight
3662 'rear-nonsticky org-nonsticky-props
3663 'keymap org-mouse-map
3664 'help-echo "Radio target link"
3665 'org-linked-text t))
3666 t)))))
3668 (defun org-update-radio-target-regexp ()
3669 "Find all radio targets in this file and update the regular expression."
3670 (interactive)
3671 (when (memq 'radio org-activate-links)
3672 (setq org-target-link-regexp
3673 (org-make-target-link-regexp (org-all-targets 'radio)))
3674 (org-restart-font-lock)))
3676 (defun org-hide-wide-columns (limit)
3677 (let (s e)
3678 (setq s (text-property-any (point) (or limit (point-max))
3679 'org-cwidth t))
3680 (when s
3681 (setq e (next-single-property-change s 'org-cwidth))
3682 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
3683 (goto-char e)
3684 t)))
3686 (defvar org-latex-and-specials-regexp nil
3687 "Regular expression for highlighting export special stuff.")
3688 (defvar org-match-substring-regexp)
3689 (defvar org-match-substring-with-braces-regexp)
3690 (defvar org-export-html-special-string-regexps)
3692 (defun org-compute-latex-and-specials-regexp ()
3693 "Compute regular expression for stuff treated specially by exporters."
3694 (if (not org-highlight-latex-fragments-and-specials)
3695 (org-set-local 'org-latex-and-specials-regexp nil)
3696 (require 'org-exp)
3697 (let*
3698 ((matchers (plist-get org-format-latex-options :matchers))
3699 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
3700 org-latex-regexps)))
3701 (options (org-combine-plists (org-default-export-plist)
3702 (org-infile-export-plist)))
3703 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
3704 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
3705 (org-export-with-TeX-macros (plist-get options :TeX-macros))
3706 (org-export-html-expand (plist-get options :expand-quoted-html))
3707 (org-export-with-special-strings (plist-get options :special-strings))
3708 (re-sub
3709 (cond
3710 ((equal org-export-with-sub-superscripts '{})
3711 (list org-match-substring-with-braces-regexp))
3712 (org-export-with-sub-superscripts
3713 (list org-match-substring-regexp))
3714 (t nil)))
3715 (re-latex
3716 (if org-export-with-LaTeX-fragments
3717 (mapcar (lambda (x) (nth 1 x)) latexs)))
3718 (re-macros
3719 (if org-export-with-TeX-macros
3720 (list (concat "\\\\"
3721 (regexp-opt
3722 (append (mapcar 'car org-html-entities)
3723 (if (boundp 'org-latex-entities)
3724 org-latex-entities nil))
3725 'words))) ; FIXME
3727 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
3728 (re-special (if org-export-with-special-strings
3729 (mapcar (lambda (x) (car x))
3730 org-export-html-special-string-regexps)))
3731 (re-rest
3732 (delq nil
3733 (list
3734 (if org-export-html-expand "@<[^>\n]+>")
3735 ))))
3736 (org-set-local
3737 'org-latex-and-specials-regexp
3738 (mapconcat 'identity (append re-latex re-sub re-macros re-special
3739 re-rest) "\\|")))))
3741 (defun org-do-latex-and-special-faces (limit)
3742 "Run through the buffer and add overlays to links."
3743 (when org-latex-and-specials-regexp
3744 (let (rtn d)
3745 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
3746 limit t))
3747 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
3748 'face))
3749 '(org-code org-verbatim underline)))
3750 (progn
3751 (setq rtn t
3752 d (cond ((member (char-after (1+ (match-beginning 0)))
3753 '(?_ ?^)) 1)
3754 (t 0)))
3755 (font-lock-prepend-text-property
3756 (+ d (match-beginning 0)) (match-end 0)
3757 'face 'org-latex-and-export-specials)
3758 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
3759 '(font-lock-multiline t)))))
3760 rtn)))
3762 (defun org-restart-font-lock ()
3763 "Restart font-lock-mode, to force refontification."
3764 (when (and (boundp 'font-lock-mode) font-lock-mode)
3765 (font-lock-mode -1)
3766 (font-lock-mode 1)))
3768 (defun org-all-targets (&optional radio)
3769 "Return a list of all targets in this file.
3770 With optional argument RADIO, only find radio targets."
3771 (let ((re (if radio org-radio-target-regexp org-target-regexp))
3772 rtn)
3773 (save-excursion
3774 (goto-char (point-min))
3775 (while (re-search-forward re nil t)
3776 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
3777 rtn)))
3779 (defun org-make-target-link-regexp (targets)
3780 "Make regular expression matching all strings in TARGETS.
3781 The regular expression finds the targets also if there is a line break
3782 between words."
3783 (and targets
3784 (concat
3785 "\\<\\("
3786 (mapconcat
3787 (lambda (x)
3788 (while (string-match " +" x)
3789 (setq x (replace-match "\\s-+" t t x)))
3791 targets
3792 "\\|")
3793 "\\)\\>")))
3795 (defun org-activate-tags (limit)
3796 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
3797 (progn
3798 (add-text-properties (match-beginning 1) (match-end 1)
3799 (list 'mouse-face 'highlight
3800 'rear-nonsticky org-nonsticky-props
3801 'keymap org-mouse-map))
3802 t)))
3804 (defun org-outline-level ()
3805 (save-excursion
3806 (looking-at outline-regexp)
3807 (if (match-beginning 1)
3808 (+ (org-get-string-indentation (match-string 1)) 1000)
3809 (1- (- (match-end 0) (match-beginning 0))))))
3811 (defvar org-font-lock-keywords nil)
3813 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
3814 "Regular expression matching a property line.")
3816 (defvar org-font-lock-hook nil
3817 "Functions to be called for special font lock stuff.")
3819 (defun org-font-lock-hook (limit)
3820 (run-hook-with-args 'org-font-lock-hook limit))
3822 (defun org-set-font-lock-defaults ()
3823 (let* ((em org-fontify-emphasized-text)
3824 (lk org-activate-links)
3825 (org-font-lock-extra-keywords
3826 (list
3827 ;; Call the hook
3828 '(org-font-lock-hook)
3829 ;; Headlines
3830 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
3831 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
3832 ;; Table lines
3833 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
3834 (1 'org-table t))
3835 ;; Table internals
3836 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
3837 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
3838 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
3839 ;; Drawers
3840 (list org-drawer-regexp '(0 'org-special-keyword t))
3841 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
3842 ;; Properties
3843 (list org-property-re
3844 '(1 'org-special-keyword t)
3845 '(3 'org-property-value t))
3846 (if org-format-transports-properties-p
3847 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
3848 ;; Links
3849 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
3850 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
3851 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
3852 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
3853 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
3854 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
3855 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
3856 '(org-hide-wide-columns (0 nil append))
3857 ;; TODO lines
3858 (list (concat "^\\*+[ \t]+" org-todo-regexp)
3859 '(1 (org-get-todo-face 1) t))
3860 ;; DONE
3861 (if org-fontify-done-headline
3862 (list (concat "^[*]+ +\\<\\("
3863 (mapconcat 'regexp-quote org-done-keywords "\\|")
3864 "\\)\\(.*\\)")
3865 '(2 'org-headline-done t))
3866 nil)
3867 ;; Priorities
3868 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
3869 ;; Special keywords
3870 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
3871 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
3872 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
3873 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
3874 ;; Emphasis
3875 (if em
3876 (if (featurep 'xemacs)
3877 '(org-do-emphasis-faces (0 nil append))
3878 '(org-do-emphasis-faces)))
3879 ;; Checkboxes
3880 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
3881 2 'bold prepend)
3882 (if org-provide-checkbox-statistics
3883 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
3884 (0 (org-get-checkbox-statistics-face) t)))
3885 ;; Description list items
3886 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
3887 2 'bold prepend)
3888 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
3889 '(1 'org-archived prepend))
3890 ;; Specials
3891 '(org-do-latex-and-special-faces)
3892 ;; Code
3893 '(org-activate-code (1 'org-code t))
3894 ;; COMMENT
3895 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
3896 "\\|" org-quote-string "\\)\\>")
3897 '(1 'org-special-keyword t))
3898 '("^#.*" (0 'font-lock-comment-face t))
3900 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
3901 ;; Now set the full font-lock-keywords
3902 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
3903 (org-set-local 'font-lock-defaults
3904 '(org-font-lock-keywords t nil nil backward-paragraph))
3905 (kill-local-variable 'font-lock-keywords) nil))
3907 (defvar org-m nil)
3908 (defvar org-l nil)
3909 (defvar org-f nil)
3910 (defun org-get-level-face (n)
3911 "Get the right face for match N in font-lock matching of healdines."
3912 (setq org-l (- (match-end 2) (match-beginning 1) 1))
3913 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
3914 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
3915 (cond
3916 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
3917 ((eq n 2) org-f)
3918 (t (if org-level-color-stars-only nil org-f))))
3920 (defun org-get-todo-face (kwd)
3921 "Get the right face for a TODO keyword KWD.
3922 If KWD is a number, get the corresponding match group."
3923 (if (numberp kwd) (setq kwd (match-string kwd)))
3924 (or (cdr (assoc kwd org-todo-keyword-faces))
3925 (and (member kwd org-done-keywords) 'org-done)
3926 'org-todo))
3928 (defun org-unfontify-region (beg end &optional maybe_loudly)
3929 "Remove fontification and activation overlays from links."
3930 (font-lock-default-unfontify-region beg end)
3931 (let* ((buffer-undo-list t)
3932 (inhibit-read-only t) (inhibit-point-motion-hooks t)
3933 (inhibit-modification-hooks t)
3934 deactivate-mark buffer-file-name buffer-file-truename)
3935 (remove-text-properties beg end
3936 '(mouse-face t keymap t org-linked-text t
3937 invisible t intangible t))))
3939 ;;;; Visibility cycling, including org-goto and indirect buffer
3941 ;;; Cycling
3943 (defvar org-cycle-global-status nil)
3944 (make-variable-buffer-local 'org-cycle-global-status)
3945 (defvar org-cycle-subtree-status nil)
3946 (make-variable-buffer-local 'org-cycle-subtree-status)
3948 ;;;###autoload
3949 (defun org-cycle (&optional arg)
3950 "Visibility cycling for Org-mode.
3952 - When this function is called with a prefix argument, rotate the entire
3953 buffer through 3 states (global cycling)
3954 1. OVERVIEW: Show only top-level headlines.
3955 2. CONTENTS: Show all headlines of all levels, but no body text.
3956 3. SHOW ALL: Show everything.
3957 When called with two C-u C-u prefixes, switch to the startup visibility,
3958 determined by the variable `org-startup-folded', and by any VISIBILITY
3959 properties in the buffer.
3960 When called with three C-u C-u C-u prefixed, show the entire buffer,
3961 including drawers.
3963 - When point is at the beginning of a headline, rotate the subtree started
3964 by this line through 3 different states (local cycling)
3965 1. FOLDED: Only the main headline is shown.
3966 2. CHILDREN: The main headline and the direct children are shown.
3967 From this state, you can move to one of the children
3968 and zoom in further.
3969 3. SUBTREE: Show the entire subtree, including body text.
3971 - When there is a numeric prefix, go up to a heading with level ARG, do
3972 a `show-subtree' and return to the previous cursor position. If ARG
3973 is negative, go up that many levels.
3975 - When point is not at the beginning of a headline, execute the global
3976 binding for TAB, which is re-indenting the line. See the option
3977 `org-cycle-emulate-tab' for details.
3979 - Special case: if point is at the beginning of the buffer and there is
3980 no headline in line 1, this function will act as if called with prefix arg.
3981 But only if also the variable `org-cycle-global-at-bob' is t."
3982 (interactive "P")
3983 (org-load-modules-maybe)
3984 (let* ((outline-regexp
3985 (if (and (org-mode-p) org-cycle-include-plain-lists)
3986 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
3987 outline-regexp))
3988 (bob-special (and org-cycle-global-at-bob (bobp)
3989 (not (looking-at outline-regexp))))
3990 (org-cycle-hook
3991 (if bob-special
3992 (delq 'org-optimize-window-after-visibility-change
3993 (copy-sequence org-cycle-hook))
3994 org-cycle-hook))
3995 (pos (point)))
3997 (if (or bob-special (equal arg '(4)))
3998 ;; special case: use global cycling
3999 (setq arg t))
4001 (cond
4003 ((equal arg '(16))
4004 (org-set-startup-visibility)
4005 (message "Startup visibility, plus VISIBILITY properties"))
4007 ((equal arg '(64))
4008 (show-all)
4009 (message "Entire buffer visible, including drawers"))
4011 ((org-at-table-p 'any)
4012 ;; Enter the table or move to the next field in the table
4013 (or (org-table-recognize-table.el)
4014 (progn
4015 (if arg (org-table-edit-field t)
4016 (org-table-justify-field-maybe)
4017 (call-interactively 'org-table-next-field)))))
4019 ((eq arg t) ;; Global cycling
4021 (cond
4022 ((and (eq last-command this-command)
4023 (eq org-cycle-global-status 'overview))
4024 ;; We just created the overview - now do table of contents
4025 ;; This can be slow in very large buffers, so indicate action
4026 (message "CONTENTS...")
4027 (org-content)
4028 (message "CONTENTS...done")
4029 (setq org-cycle-global-status 'contents)
4030 (run-hook-with-args 'org-cycle-hook 'contents))
4032 ((and (eq last-command this-command)
4033 (eq org-cycle-global-status 'contents))
4034 ;; We just showed the table of contents - now show everything
4035 (show-all)
4036 (message "SHOW ALL")
4037 (setq org-cycle-global-status 'all)
4038 (run-hook-with-args 'org-cycle-hook 'all))
4041 ;; Default action: go to overview
4042 (org-overview)
4043 (message "OVERVIEW")
4044 (setq org-cycle-global-status 'overview)
4045 (run-hook-with-args 'org-cycle-hook 'overview))))
4047 ((and org-drawers org-drawer-regexp
4048 (save-excursion
4049 (beginning-of-line 1)
4050 (looking-at org-drawer-regexp)))
4051 ;; Toggle block visibility
4052 (org-flag-drawer
4053 (not (get-char-property (match-end 0) 'invisible))))
4055 ((integerp arg)
4056 ;; Show-subtree, ARG levels up from here.
4057 (save-excursion
4058 (org-back-to-heading)
4059 (outline-up-heading (if (< arg 0) (- arg)
4060 (- (funcall outline-level) arg)))
4061 (org-show-subtree)))
4063 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4064 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4065 ;; At a heading: rotate between three different views
4066 (org-back-to-heading)
4067 (let ((goal-column 0) eoh eol eos)
4068 ;; First, some boundaries
4069 (save-excursion
4070 (org-back-to-heading)
4071 (save-excursion
4072 (beginning-of-line 2)
4073 (while (and (not (eobp)) ;; this is like `next-line'
4074 (get-char-property (1- (point)) 'invisible))
4075 (beginning-of-line 2)) (setq eol (point)))
4076 (outline-end-of-heading) (setq eoh (point))
4077 (org-end-of-subtree t)
4078 (unless (eobp)
4079 (skip-chars-forward " \t\n")
4080 (beginning-of-line 1) ; in case this is an item
4082 (setq eos (1- (point))))
4083 ;; Find out what to do next and set `this-command'
4084 (cond
4085 ((= eos eoh)
4086 ;; Nothing is hidden behind this heading
4087 (message "EMPTY ENTRY")
4088 (setq org-cycle-subtree-status nil)
4089 (save-excursion
4090 (goto-char eos)
4091 (outline-next-heading)
4092 (if (org-invisible-p) (org-flag-heading nil))))
4093 ((or (>= eol eos)
4094 (not (string-match "\\S-" (buffer-substring eol eos))))
4095 ;; Entire subtree is hidden in one line: open it
4096 (org-show-entry)
4097 (show-children)
4098 (message "CHILDREN")
4099 (save-excursion
4100 (goto-char eos)
4101 (outline-next-heading)
4102 (if (org-invisible-p) (org-flag-heading nil)))
4103 (setq org-cycle-subtree-status 'children)
4104 (run-hook-with-args 'org-cycle-hook 'children))
4105 ((and (eq last-command this-command)
4106 (eq org-cycle-subtree-status 'children))
4107 ;; We just showed the children, now show everything.
4108 (org-show-subtree)
4109 (message "SUBTREE")
4110 (setq org-cycle-subtree-status 'subtree)
4111 (run-hook-with-args 'org-cycle-hook 'subtree))
4113 ;; Default action: hide the subtree.
4114 (hide-subtree)
4115 (message "FOLDED")
4116 (setq org-cycle-subtree-status 'folded)
4117 (run-hook-with-args 'org-cycle-hook 'folded)))))
4119 ;; TAB emulation and template completion
4120 (buffer-read-only (org-back-to-heading))
4122 ((org-try-structure-completion))
4124 ((org-try-cdlatex-tab))
4126 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4127 (or (not (bolp))
4128 (not (looking-at outline-regexp))))
4129 (call-interactively (global-key-binding "\t")))
4131 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4132 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4133 (or (and (eq org-cycle-emulate-tab 'white)
4134 (= (match-end 0) (point-at-eol)))
4135 (and (eq org-cycle-emulate-tab 'whitestart)
4136 (>= (match-end 0) pos))))
4138 (eq org-cycle-emulate-tab t))
4139 (call-interactively (global-key-binding "\t")))
4141 (t (save-excursion
4142 (org-back-to-heading)
4143 (org-cycle))))))
4145 ;;;###autoload
4146 (defun org-global-cycle (&optional arg)
4147 "Cycle the global visibility. For details see `org-cycle'.
4148 With C-u prefix arg, switch to startup visibility.
4149 With a numeric prefix, show all headlines up to that level."
4150 (interactive "P")
4151 (let ((org-cycle-include-plain-lists
4152 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4153 (cond
4154 ((integerp arg)
4155 (show-all)
4156 (hide-sublevels arg)
4157 (setq org-cycle-global-status 'contents))
4158 ((equal arg '(4))
4159 (org-set-startup-visibility)
4160 (message "Startup visibility, plus VISIBILITY properties."))
4162 (org-cycle '(4))))))
4164 (defun org-set-startup-visibility ()
4165 "Set the visibility required by startup options and properties."
4166 (cond
4167 ((eq org-startup-folded t)
4168 (org-cycle '(4)))
4169 ((eq org-startup-folded 'content)
4170 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4171 (org-cycle '(4)) (org-cycle '(4)))))
4172 (org-set-visibility-according-to-property 'no-cleanup)
4173 (org-cycle-hide-archived-subtrees 'all)
4174 (org-cycle-hide-drawers 'all)
4175 (org-cycle-show-empty-lines 'all))
4177 (defun org-set-visibility-according-to-property (&optional no-cleanup)
4178 "Switch subtree visibilities according to :VISIBILITY: property."
4179 (interactive)
4180 (let (state)
4181 (save-excursion
4182 (goto-char (point-min))
4183 (while (re-search-forward
4184 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
4185 nil t)
4186 (setq state (match-string 1))
4187 (save-excursion
4188 (org-back-to-heading t)
4189 (hide-subtree)
4190 (org-reveal)
4191 (cond
4192 ((equal state '("fold" "folded"))
4193 (hide-subtree))
4194 ((equal state "children")
4195 (org-show-hidden-entry)
4196 (show-children))
4197 ((equal state "content")
4198 (save-excursion
4199 (save-restriction
4200 (org-narrow-to-subtree)
4201 (org-content))))
4202 ((member state '("all" "showall"))
4203 (show-subtree)))))
4204 (unless no-cleanup
4205 (org-cycle-hide-archived-subtrees 'all)
4206 (org-cycle-hide-drawers 'all)
4207 (org-cycle-show-empty-lines 'all)))))
4209 (defun org-overview ()
4210 "Switch to overview mode, shoing only top-level headlines.
4211 Really, this shows all headlines with level equal or greater than the level
4212 of the first headline in the buffer. This is important, because if the
4213 first headline is not level one, then (hide-sublevels 1) gives confusing
4214 results."
4215 (interactive)
4216 (let ((level (save-excursion
4217 (goto-char (point-min))
4218 (if (re-search-forward (concat "^" outline-regexp) nil t)
4219 (progn
4220 (goto-char (match-beginning 0))
4221 (funcall outline-level))))))
4222 (and level (hide-sublevels level))))
4224 (defun org-content (&optional arg)
4225 "Show all headlines in the buffer, like a table of contents.
4226 With numerical argument N, show content up to level N."
4227 (interactive "P")
4228 (save-excursion
4229 ;; Visit all headings and show their offspring
4230 (and (integerp arg) (org-overview))
4231 (goto-char (point-max))
4232 (catch 'exit
4233 (while (and (progn (condition-case nil
4234 (outline-previous-visible-heading 1)
4235 (error (goto-char (point-min))))
4237 (looking-at outline-regexp))
4238 (if (integerp arg)
4239 (show-children (1- arg))
4240 (show-branches))
4241 (if (bobp) (throw 'exit nil))))))
4244 (defun org-optimize-window-after-visibility-change (state)
4245 "Adjust the window after a change in outline visibility.
4246 This function is the default value of the hook `org-cycle-hook'."
4247 (when (get-buffer-window (current-buffer))
4248 (cond
4249 ; ((eq state 'overview) (org-first-headline-recenter 1))
4250 ; ((eq state 'overview) (org-beginning-of-line))
4251 ((eq state 'content) nil)
4252 ((eq state 'all) nil)
4253 ((eq state 'folded) nil)
4254 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4255 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4257 (defun org-compact-display-after-subtree-move ()
4258 (let (beg end)
4259 (save-excursion
4260 (if (org-up-heading-safe)
4261 (progn
4262 (hide-subtree)
4263 (show-entry)
4264 (show-children)
4265 (org-cycle-show-empty-lines 'children)
4266 (org-cycle-hide-drawers 'children))
4267 (org-overview)))))
4269 (defun org-cycle-show-empty-lines (state)
4270 "Show empty lines above all visible headlines.
4271 The region to be covered depends on STATE when called through
4272 `org-cycle-hook'. Lisp program can use t for STATE to get the
4273 entire buffer covered. Note that an empty line is only shown if there
4274 are at least `org-cycle-separator-lines' empty lines before the headeline."
4275 (when (> org-cycle-separator-lines 0)
4276 (save-excursion
4277 (let* ((n org-cycle-separator-lines)
4278 (re (cond
4279 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
4280 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
4281 (t (let ((ns (number-to-string (- n 2))))
4282 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
4283 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
4284 beg end)
4285 (cond
4286 ((memq state '(overview contents t))
4287 (setq beg (point-min) end (point-max)))
4288 ((memq state '(children folded))
4289 (setq beg (point) end (progn (org-end-of-subtree t t)
4290 (beginning-of-line 2)
4291 (point)))))
4292 (when beg
4293 (goto-char beg)
4294 (while (re-search-forward re end t)
4295 (if (not (get-char-property (match-end 1) 'invisible))
4296 (outline-flag-region
4297 (match-beginning 1) (match-end 1) nil)))))))
4298 ;; Never hide empty lines at the end of the file.
4299 (save-excursion
4300 (goto-char (point-max))
4301 (outline-previous-heading)
4302 (outline-end-of-heading)
4303 (if (and (looking-at "[ \t\n]+")
4304 (= (match-end 0) (point-max)))
4305 (outline-flag-region (point) (match-end 0) nil))))
4307 (defun org-show-empty-lines-in-parent ()
4308 "Move to the parent and re-show empty lines before visible headlines."
4309 (save-excursion
4310 (let ((context (if (org-up-heading-safe) 'children 'overview)))
4311 (org-cycle-show-empty-lines context))))
4313 (defun org-cycle-hide-drawers (state)
4314 "Re-hide all drawers after a visibility state change."
4315 (when (and (org-mode-p)
4316 (not (memq state '(overview folded))))
4317 (save-excursion
4318 (let* ((globalp (memq state '(contents all)))
4319 (beg (if globalp (point-min) (point)))
4320 (end (if globalp (point-max) (org-end-of-subtree t))))
4321 (goto-char beg)
4322 (while (re-search-forward org-drawer-regexp end t)
4323 (org-flag-drawer t))))))
4325 (defun org-flag-drawer (flag)
4326 (save-excursion
4327 (beginning-of-line 1)
4328 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
4329 (let ((b (match-end 0))
4330 (outline-regexp org-outline-regexp))
4331 (if (re-search-forward
4332 "^[ \t]*:END:"
4333 (save-excursion (outline-next-heading) (point)) t)
4334 (outline-flag-region b (point-at-eol) flag)
4335 (error ":END: line missing"))))))
4337 (defun org-subtree-end-visible-p ()
4338 "Is the end of the current subtree visible?"
4339 (pos-visible-in-window-p
4340 (save-excursion (org-end-of-subtree t) (point))))
4342 (defun org-first-headline-recenter (&optional N)
4343 "Move cursor to the first headline and recenter the headline.
4344 Optional argument N means, put the headline into the Nth line of the window."
4345 (goto-char (point-min))
4346 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4347 (beginning-of-line)
4348 (recenter (prefix-numeric-value N))))
4350 ;;; Org-goto
4352 (defvar org-goto-window-configuration nil)
4353 (defvar org-goto-marker nil)
4354 (defvar org-goto-map
4355 (let ((map (make-sparse-keymap)))
4356 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
4357 (while (setq cmd (pop cmds))
4358 (substitute-key-definition cmd cmd map global-map)))
4359 (suppress-keymap map)
4360 (org-defkey map "\C-m" 'org-goto-ret)
4361 (org-defkey map [(return)] 'org-goto-ret)
4362 (org-defkey map [(left)] 'org-goto-left)
4363 (org-defkey map [(right)] 'org-goto-right)
4364 (org-defkey map [(control ?g)] 'org-goto-quit)
4365 (org-defkey map "\C-i" 'org-cycle)
4366 (org-defkey map [(tab)] 'org-cycle)
4367 (org-defkey map [(down)] 'outline-next-visible-heading)
4368 (org-defkey map [(up)] 'outline-previous-visible-heading)
4369 (if org-goto-auto-isearch
4370 (if (fboundp 'define-key-after)
4371 (define-key-after map [t] 'org-goto-local-auto-isearch)
4372 nil)
4373 (org-defkey map "q" 'org-goto-quit)
4374 (org-defkey map "n" 'outline-next-visible-heading)
4375 (org-defkey map "p" 'outline-previous-visible-heading)
4376 (org-defkey map "f" 'outline-forward-same-level)
4377 (org-defkey map "b" 'outline-backward-same-level)
4378 (org-defkey map "u" 'outline-up-heading))
4379 (org-defkey map "/" 'org-occur)
4380 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4381 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4382 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
4383 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
4384 (org-defkey map "\C-c\C-u" 'outline-up-heading)
4385 map))
4387 (defconst org-goto-help
4388 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4389 RET=jump to location [Q]uit and return to previous location
4390 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4392 (defvar org-goto-start-pos) ; dynamically scoped parameter
4394 ;; FIXME: Docstring doe not mention both interfaces
4395 (defun org-goto (&optional alternative-interface)
4396 "Look up a different location in the current file, keeping current visibility.
4398 When you want look-up or go to a different location in a document, the
4399 fastest way is often to fold the entire buffer and then dive into the tree.
4400 This method has the disadvantage, that the previous location will be folded,
4401 which may not be what you want.
4403 This command works around this by showing a copy of the current buffer
4404 in an indirect buffer, in overview mode. You can dive into the tree in
4405 that copy, use org-occur and incremental search to find a location.
4406 When pressing RET or `Q', the command returns to the original buffer in
4407 which the visibility is still unchanged. After RET is will also jump to
4408 the location selected in the indirect buffer and expose the
4409 the headline hierarchy above."
4410 (interactive "P")
4411 (let* ((org-refile-targets '((nil . (:maxlevel . 10))))
4412 (org-refile-use-outline-path t)
4413 (interface
4414 (if (not alternative-interface)
4415 org-goto-interface
4416 (if (eq org-goto-interface 'outline)
4417 'outline-path-completion
4418 'outline)))
4419 (org-goto-start-pos (point))
4420 (selected-point
4421 (if (eq interface 'outline)
4422 (car (org-get-location (current-buffer) org-goto-help))
4423 (nth 3 (org-refile-get-location "Goto: ")))))
4424 (if selected-point
4425 (progn
4426 (org-mark-ring-push org-goto-start-pos)
4427 (goto-char selected-point)
4428 (if (or (org-invisible-p) (org-invisible-p2))
4429 (org-show-context 'org-goto)))
4430 (message "Quit"))))
4432 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
4433 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
4434 (defvar org-goto-local-auto-isearch-map) ; defined below
4436 (defun org-get-location (buf help)
4437 "Let the user select a location in the Org-mode buffer BUF.
4438 This function uses a recursive edit. It returns the selected position
4439 or nil."
4440 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
4441 (isearch-hide-immediately nil)
4442 (isearch-search-fun-function
4443 (lambda () 'org-goto-local-search-headings))
4444 (org-goto-selected-point org-goto-exit-command))
4445 (save-excursion
4446 (save-window-excursion
4447 (delete-other-windows)
4448 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
4449 (switch-to-buffer
4450 (condition-case nil
4451 (make-indirect-buffer (current-buffer) "*org-goto*")
4452 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
4453 (with-output-to-temp-buffer "*Help*"
4454 (princ help))
4455 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
4456 (setq buffer-read-only nil)
4457 (let ((org-startup-truncated t)
4458 (org-startup-folded nil)
4459 (org-startup-align-all-tables nil))
4460 (org-mode)
4461 (org-overview))
4462 (setq buffer-read-only t)
4463 (if (and (boundp 'org-goto-start-pos)
4464 (integer-or-marker-p org-goto-start-pos))
4465 (let ((org-show-hierarchy-above t)
4466 (org-show-siblings t)
4467 (org-show-following-heading t))
4468 (goto-char org-goto-start-pos)
4469 (and (org-invisible-p) (org-show-context)))
4470 (goto-char (point-min)))
4471 (org-beginning-of-line)
4472 (message "Select location and press RET")
4473 (use-local-map org-goto-map)
4474 (recursive-edit)
4476 (kill-buffer "*org-goto*")
4477 (cons org-goto-selected-point org-goto-exit-command)))
4479 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
4480 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
4481 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
4482 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
4484 (defun org-goto-local-search-headings (string bound noerror)
4485 "Search and make sure that any matches are in headlines."
4486 (catch 'return
4487 (while (if isearch-forward
4488 (search-forward string bound noerror)
4489 (search-backward string bound noerror))
4490 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
4491 (and (member :headline context)
4492 (not (member :tags context))))
4493 (throw 'return (point))))))
4495 (defun org-goto-local-auto-isearch ()
4496 "Start isearch."
4497 (interactive)
4498 (goto-char (point-min))
4499 (let ((keys (this-command-keys)))
4500 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
4501 (isearch-mode t)
4502 (isearch-process-search-char (string-to-char keys)))))
4504 (defun org-goto-ret (&optional arg)
4505 "Finish `org-goto' by going to the new location."
4506 (interactive "P")
4507 (setq org-goto-selected-point (point)
4508 org-goto-exit-command 'return)
4509 (throw 'exit nil))
4511 (defun org-goto-left ()
4512 "Finish `org-goto' by going to the new location."
4513 (interactive)
4514 (if (org-on-heading-p)
4515 (progn
4516 (beginning-of-line 1)
4517 (setq org-goto-selected-point (point)
4518 org-goto-exit-command 'left)
4519 (throw 'exit nil))
4520 (error "Not on a heading")))
4522 (defun org-goto-right ()
4523 "Finish `org-goto' by going to the new location."
4524 (interactive)
4525 (if (org-on-heading-p)
4526 (progn
4527 (setq org-goto-selected-point (point)
4528 org-goto-exit-command 'right)
4529 (throw 'exit nil))
4530 (error "Not on a heading")))
4532 (defun org-goto-quit ()
4533 "Finish `org-goto' without cursor motion."
4534 (interactive)
4535 (setq org-goto-selected-point nil)
4536 (setq org-goto-exit-command 'quit)
4537 (throw 'exit nil))
4539 ;;; Indirect buffer display of subtrees
4541 (defvar org-indirect-dedicated-frame nil
4542 "This is the frame being used for indirect tree display.")
4543 (defvar org-last-indirect-buffer nil)
4545 (defun org-tree-to-indirect-buffer (&optional arg)
4546 "Create indirect buffer and narrow it to current subtree.
4547 With numerical prefix ARG, go up to this level and then take that tree.
4548 If ARG is negative, go up that many levels.
4549 If `org-indirect-buffer-display' is not `new-frame', the command removes the
4550 indirect buffer previously made with this command, to avoid proliferation of
4551 indirect buffers. However, when you call the command with a `C-u' prefix, or
4552 when `org-indirect-buffer-display' is `new-frame', the last buffer
4553 is kept so that you can work with several indirect buffers at the same time.
4554 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
4555 requests that a new frame be made for the new buffer, so that the dedicated
4556 frame is not changed."
4557 (interactive "P")
4558 (let ((cbuf (current-buffer))
4559 (cwin (selected-window))
4560 (pos (point))
4561 beg end level heading ibuf)
4562 (save-excursion
4563 (org-back-to-heading t)
4564 (when (numberp arg)
4565 (setq level (org-outline-level))
4566 (if (< arg 0) (setq arg (+ level arg)))
4567 (while (> (setq level (org-outline-level)) arg)
4568 (outline-up-heading 1 t)))
4569 (setq beg (point)
4570 heading (org-get-heading))
4571 (org-end-of-subtree t) (setq end (point)))
4572 (if (and (buffer-live-p org-last-indirect-buffer)
4573 (not (eq org-indirect-buffer-display 'new-frame))
4574 (not arg))
4575 (kill-buffer org-last-indirect-buffer))
4576 (setq ibuf (org-get-indirect-buffer cbuf)
4577 org-last-indirect-buffer ibuf)
4578 (cond
4579 ((or (eq org-indirect-buffer-display 'new-frame)
4580 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
4581 (select-frame (make-frame))
4582 (delete-other-windows)
4583 (switch-to-buffer ibuf)
4584 (org-set-frame-title heading))
4585 ((eq org-indirect-buffer-display 'dedicated-frame)
4586 (raise-frame
4587 (select-frame (or (and org-indirect-dedicated-frame
4588 (frame-live-p org-indirect-dedicated-frame)
4589 org-indirect-dedicated-frame)
4590 (setq org-indirect-dedicated-frame (make-frame)))))
4591 (delete-other-windows)
4592 (switch-to-buffer ibuf)
4593 (org-set-frame-title (concat "Indirect: " heading)))
4594 ((eq org-indirect-buffer-display 'current-window)
4595 (switch-to-buffer ibuf))
4596 ((eq org-indirect-buffer-display 'other-window)
4597 (pop-to-buffer ibuf))
4598 (t (error "Invalid value.")))
4599 (if (featurep 'xemacs)
4600 (save-excursion (org-mode) (turn-on-font-lock)))
4601 (narrow-to-region beg end)
4602 (show-all)
4603 (goto-char pos)
4604 (and (window-live-p cwin) (select-window cwin))))
4606 (defun org-get-indirect-buffer (&optional buffer)
4607 (setq buffer (or buffer (current-buffer)))
4608 (let ((n 1) (base (buffer-name buffer)) bname)
4609 (while (buffer-live-p
4610 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
4611 (setq n (1+ n)))
4612 (condition-case nil
4613 (make-indirect-buffer buffer bname 'clone)
4614 (error (make-indirect-buffer buffer bname)))))
4616 (defun org-set-frame-title (title)
4617 "Set the title of the current frame to the string TITLE."
4618 ;; FIXME: how to name a single frame in XEmacs???
4619 (unless (featurep 'xemacs)
4620 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
4622 ;;;; Structure editing
4624 ;;; Inserting headlines
4626 (defun org-insert-heading (&optional force-heading)
4627 "Insert a new heading or item with same depth at point.
4628 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
4629 If point is at the beginning of a headline, insert a sibling before the
4630 current headline. If point is not at the beginning, do not split the line,
4631 but create the new headline after the current line."
4632 (interactive "P")
4633 (if (= (buffer-size) 0)
4634 (insert "\n* ")
4635 (when (or force-heading (not (org-insert-item)))
4636 (let* ((head (save-excursion
4637 (condition-case nil
4638 (progn
4639 (org-back-to-heading)
4640 (match-string 0))
4641 (error "*"))))
4642 (blank (cdr (assq 'heading org-blank-before-new-entry)))
4643 pos hide-previous previous-pos)
4644 (cond
4645 ((and (org-on-heading-p) (bolp)
4646 (or (bobp)
4647 (save-excursion (backward-char 1) (not (org-invisible-p)))))
4648 ;; insert before the current line
4649 (open-line (if blank 2 1)))
4650 ((and (bolp)
4651 (or (bobp)
4652 (save-excursion
4653 (backward-char 1) (not (org-invisible-p)))))
4654 ;; insert right here
4655 nil)
4657 ;; somewhere in the line
4658 (save-excursion
4659 (setq previous-pos (point-at-bol))
4660 (end-of-line)
4661 (setq hide-previous (org-invisible-p)))
4662 (and org-insert-heading-respect-content (org-show-subtree))
4663 (let ((split
4664 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
4665 (save-excursion
4666 (let ((p (point)))
4667 (goto-char (point-at-bol))
4668 (and (looking-at org-complex-heading-regexp)
4669 (> p (match-beginning 4)))))))
4670 tags pos)
4671 (cond
4672 (org-insert-heading-respect-content
4673 (org-end-of-subtree nil t)
4674 (or (bolp) (newline))
4675 (open-line 1))
4676 ((org-on-heading-p)
4677 (when hide-previous
4678 (show-children)
4679 (org-show-entry))
4680 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4681 (setq tags (and (match-end 2) (match-string 2)))
4682 (and (match-end 1)
4683 (delete-region (match-beginning 1) (match-end 1)))
4684 (setq pos (point-at-bol))
4685 (or split (end-of-line 1))
4686 (delete-horizontal-space)
4687 (newline (if blank 2 1))
4688 (when tags
4689 (save-excursion
4690 (goto-char pos)
4691 (end-of-line 1)
4692 (insert " " tags)
4693 (org-set-tags nil 'align))))
4695 (or split (end-of-line 1))
4696 (newline (if blank 2 1)))))))
4697 (insert head) (just-one-space)
4698 (setq pos (point))
4699 (end-of-line 1)
4700 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
4701 (when (and org-insert-heading-respect-content hide-previous)
4702 (save-excursion
4703 (goto-char previous-pos)
4704 (hide-subtree)))
4705 (run-hooks 'org-insert-heading-hook)))))
4707 (defun org-get-heading (&optional no-tags)
4708 "Return the heading of the current entry, without the stars."
4709 (save-excursion
4710 (org-back-to-heading t)
4711 (if (looking-at
4712 (if no-tags
4713 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
4714 "\\*+[ \t]+\\([^\r\n]*\\)"))
4715 (match-string 1) "")))
4717 (defun org-insert-heading-after-current ()
4718 "Insert a new heading with same level as current, after current subtree."
4719 (interactive)
4720 (org-back-to-heading)
4721 (org-insert-heading)
4722 (org-move-subtree-down)
4723 (end-of-line 1))
4725 (defun org-insert-heading-respect-content ()
4726 (interactive)
4727 (let ((org-insert-heading-respect-content t))
4728 (org-insert-heading t)))
4730 (defun org-insert-todo-heading-respect-content (&optional force-state)
4731 (interactive "P")
4732 (let ((org-insert-heading-respect-content t))
4733 (org-insert-todo-heading force-state t)))
4735 (defun org-insert-todo-heading (arg &optional force-heading)
4736 "Insert a new heading with the same level and TODO state as current heading.
4737 If the heading has no TODO state, or if the state is DONE, use the first
4738 state (TODO by default). Also with prefix arg, force first state."
4739 (interactive "P")
4740 (when (or force-heading (not (org-insert-item 'checkbox)))
4741 (org-insert-heading force-heading)
4742 (save-excursion
4743 (org-back-to-heading)
4744 (outline-previous-heading)
4745 (looking-at org-todo-line-regexp))
4746 (if (or arg
4747 (not (match-beginning 2))
4748 (member (match-string 2) org-done-keywords))
4749 (insert (car org-todo-keywords-1) " ")
4750 (insert (match-string 2) " "))
4751 (when org-provide-todo-statistics
4752 (org-update-parent-todo-statistics))))
4754 (defun org-insert-subheading (arg)
4755 "Insert a new subheading and demote it.
4756 Works for outline headings and for plain lists alike."
4757 (interactive "P")
4758 (org-insert-heading arg)
4759 (cond
4760 ((org-on-heading-p) (org-do-demote))
4761 ((org-at-item-p) (org-indent-item 1))))
4763 (defun org-insert-todo-subheading (arg)
4764 "Insert a new subheading with TODO keyword or checkbox and demote it.
4765 Works for outline headings and for plain lists alike."
4766 (interactive "P")
4767 (org-insert-todo-heading arg)
4768 (cond
4769 ((org-on-heading-p) (org-do-demote))
4770 ((org-at-item-p) (org-indent-item 1))))
4772 ;;; Promotion and Demotion
4774 (defun org-promote-subtree ()
4775 "Promote the entire subtree.
4776 See also `org-promote'."
4777 (interactive)
4778 (save-excursion
4779 (org-map-tree 'org-promote))
4780 (org-fix-position-after-promote))
4782 (defun org-demote-subtree ()
4783 "Demote the entire subtree. See `org-demote'.
4784 See also `org-promote'."
4785 (interactive)
4786 (save-excursion
4787 (org-map-tree 'org-demote))
4788 (org-fix-position-after-promote))
4791 (defun org-do-promote ()
4792 "Promote the current heading higher up the tree.
4793 If the region is active in `transient-mark-mode', promote all headings
4794 in the region."
4795 (interactive)
4796 (save-excursion
4797 (if (org-region-active-p)
4798 (org-map-region 'org-promote (region-beginning) (region-end))
4799 (org-promote)))
4800 (org-fix-position-after-promote))
4802 (defun org-do-demote ()
4803 "Demote the current heading lower down the tree.
4804 If the region is active in `transient-mark-mode', demote all headings
4805 in the region."
4806 (interactive)
4807 (save-excursion
4808 (if (org-region-active-p)
4809 (org-map-region 'org-demote (region-beginning) (region-end))
4810 (org-demote)))
4811 (org-fix-position-after-promote))
4813 (defun org-fix-position-after-promote ()
4814 "Make sure that after pro/demotion cursor position is right."
4815 (let ((pos (point)))
4816 (when (save-excursion
4817 (beginning-of-line 1)
4818 (looking-at org-todo-line-regexp)
4819 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
4820 (cond ((eobp) (insert " "))
4821 ((eolp) (insert " "))
4822 ((equal (char-after) ?\ ) (forward-char 1))))))
4824 (defun org-reduced-level (l)
4825 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
4827 (defun org-get-valid-level (level &optional change)
4828 "Rectify a level change under the influence of `org-odd-levels-only'
4829 LEVEL is a current level, CHANGE is by how much the level should be
4830 modified. Even if CHANGE is nil, LEVEL may be returned modified because
4831 even level numbers will become the next higher odd number."
4832 (if org-odd-levels-only
4833 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
4834 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
4835 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
4836 (max 1 (+ level change))))
4838 (if (boundp 'define-obsolete-function-alias)
4839 (if (or (featurep 'xemacs) (< emacs-major-version 23))
4840 (define-obsolete-function-alias 'org-get-legal-level
4841 'org-get-valid-level)
4842 (define-obsolete-function-alias 'org-get-legal-level
4843 'org-get-valid-level "23.1")))
4845 (defun org-promote ()
4846 "Promote the current heading higher up the tree.
4847 If the region is active in `transient-mark-mode', promote all headings
4848 in the region."
4849 (org-back-to-heading t)
4850 (let* ((level (save-match-data (funcall outline-level)))
4851 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
4852 (diff (abs (- level (length up-head) -1))))
4853 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
4854 (replace-match up-head nil t)
4855 ;; Fixup tag positioning
4856 (and org-auto-align-tags (org-set-tags nil t))
4857 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
4859 (defun org-demote ()
4860 "Demote the current heading lower down the tree.
4861 If the region is active in `transient-mark-mode', demote all headings
4862 in the region."
4863 (org-back-to-heading t)
4864 (let* ((level (save-match-data (funcall outline-level)))
4865 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
4866 (diff (abs (- level (length down-head) -1))))
4867 (replace-match down-head nil t)
4868 ;; Fixup tag positioning
4869 (and org-auto-align-tags (org-set-tags nil t))
4870 (if org-adapt-indentation (org-fixup-indentation diff))))
4872 (defun org-map-tree (fun)
4873 "Call FUN for every heading underneath the current one."
4874 (org-back-to-heading)
4875 (let ((level (funcall outline-level)))
4876 (save-excursion
4877 (funcall fun)
4878 (while (and (progn
4879 (outline-next-heading)
4880 (> (funcall outline-level) level))
4881 (not (eobp)))
4882 (funcall fun)))))
4884 (defun org-map-region (fun beg end)
4885 "Call FUN for every heading between BEG and END."
4886 (let ((org-ignore-region t))
4887 (save-excursion
4888 (setq end (copy-marker end))
4889 (goto-char beg)
4890 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
4891 (< (point) end))
4892 (funcall fun))
4893 (while (and (progn
4894 (outline-next-heading)
4895 (< (point) end))
4896 (not (eobp)))
4897 (funcall fun)))))
4899 (defun org-fixup-indentation (diff)
4900 "Change the indentation in the current entry by DIFF
4901 However, if any line in the current entry has no indentation, or if it
4902 would end up with no indentation after the change, nothing at all is done."
4903 (save-excursion
4904 (let ((end (save-excursion (outline-next-heading)
4905 (point-marker)))
4906 (prohibit (if (> diff 0)
4907 "^\\S-"
4908 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
4909 col)
4910 (unless (save-excursion (end-of-line 1)
4911 (re-search-forward prohibit end t))
4912 (while (and (< (point) end)
4913 (re-search-forward "^[ \t]+" end t))
4914 (goto-char (match-end 0))
4915 (setq col (current-column))
4916 (if (< diff 0) (replace-match ""))
4917 (indent-to (+ diff col))))
4918 (move-marker end nil))))
4920 (defun org-convert-to-odd-levels ()
4921 "Convert an org-mode file with all levels allowed to one with odd levels.
4922 This will leave level 1 alone, convert level 2 to level 3, level 3 to
4923 level 5 etc."
4924 (interactive)
4925 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
4926 (let ((org-odd-levels-only nil) n)
4927 (save-excursion
4928 (goto-char (point-min))
4929 (while (re-search-forward "^\\*\\*+ " nil t)
4930 (setq n (- (length (match-string 0)) 2))
4931 (while (>= (setq n (1- n)) 0)
4932 (org-demote))
4933 (end-of-line 1))))))
4936 (defun org-convert-to-oddeven-levels ()
4937 "Convert an org-mode file with only odd levels to one with odd and even levels.
4938 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
4939 section with an even level, conversion would destroy the structure of the file. An error
4940 is signaled in this case."
4941 (interactive)
4942 (goto-char (point-min))
4943 ;; First check if there are no even levels
4944 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
4945 (org-show-context t)
4946 (error "Not all levels are odd in this file. Conversion not possible."))
4947 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
4948 (let ((org-odd-levels-only nil) n)
4949 (save-excursion
4950 (goto-char (point-min))
4951 (while (re-search-forward "^\\*\\*+ " nil t)
4952 (setq n (/ (1- (length (match-string 0))) 2))
4953 (while (>= (setq n (1- n)) 0)
4954 (org-promote))
4955 (end-of-line 1))))))
4957 (defun org-tr-level (n)
4958 "Make N odd if required."
4959 (if org-odd-levels-only (1+ (/ n 2)) n))
4961 ;;; Vertical tree motion, cutting and pasting of subtrees
4963 (defun org-move-subtree-up (&optional arg)
4964 "Move the current subtree up past ARG headlines of the same level."
4965 (interactive "p")
4966 (org-move-subtree-down (- (prefix-numeric-value arg))))
4968 (defun org-move-subtree-down (&optional arg)
4969 "Move the current subtree down past ARG headlines of the same level."
4970 (interactive "p")
4971 (setq arg (prefix-numeric-value arg))
4972 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
4973 'outline-get-last-sibling))
4974 (ins-point (make-marker))
4975 (cnt (abs arg))
4976 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
4977 ;; Select the tree
4978 (org-back-to-heading)
4979 (setq beg0 (point))
4980 (save-excursion
4981 (setq ne-beg (org-back-over-empty-lines))
4982 (setq beg (point)))
4983 (save-match-data
4984 (save-excursion (outline-end-of-heading)
4985 (setq folded (org-invisible-p)))
4986 (outline-end-of-subtree))
4987 (outline-next-heading)
4988 (setq ne-end (org-back-over-empty-lines))
4989 (setq end (point))
4990 (goto-char beg0)
4991 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
4992 ;; include less whitespace
4993 (save-excursion
4994 (goto-char beg)
4995 (forward-line (- ne-beg ne-end))
4996 (setq beg (point))))
4997 ;; Find insertion point, with error handling
4998 (while (> cnt 0)
4999 (or (and (funcall movfunc) (looking-at outline-regexp))
5000 (progn (goto-char beg0)
5001 (error "Cannot move past superior level or buffer limit")))
5002 (setq cnt (1- cnt)))
5003 (if (> arg 0)
5004 ;; Moving forward - still need to move over subtree
5005 (progn (org-end-of-subtree t t)
5006 (save-excursion
5007 (org-back-over-empty-lines)
5008 (or (bolp) (newline)))))
5009 (setq ne-ins (org-back-over-empty-lines))
5010 (move-marker ins-point (point))
5011 (setq txt (buffer-substring beg end))
5012 (org-save-markers-in-region beg end)
5013 (delete-region beg end)
5014 (outline-flag-region (1- beg) beg nil)
5015 (outline-flag-region (1- (point)) (point) nil)
5016 (let ((bbb (point)))
5017 (insert-before-markers txt)
5018 (org-reinstall-markers-in-region bbb)
5019 (move-marker ins-point bbb))
5020 (or (bolp) (insert "\n"))
5021 (setq ins-end (point))
5022 (goto-char ins-point)
5023 (org-skip-whitespace)
5024 (when (and (< arg 0)
5025 (org-first-sibling-p)
5026 (> ne-ins ne-beg))
5027 ;; Move whitespace back to beginning
5028 (save-excursion
5029 (goto-char ins-end)
5030 (let ((kill-whole-line t))
5031 (kill-line (- ne-ins ne-beg)) (point)))
5032 (insert (make-string (- ne-ins ne-beg) ?\n)))
5033 (move-marker ins-point nil)
5034 (org-compact-display-after-subtree-move)
5035 (org-show-empty-lines-in-parent)
5036 (unless folded
5037 (org-show-entry)
5038 (show-children)
5039 (org-cycle-hide-drawers 'children))))
5041 (defvar org-subtree-clip ""
5042 "Clipboard for cut and paste of subtrees.
5043 This is actually only a copy of the kill, because we use the normal kill
5044 ring. We need it to check if the kill was created by `org-copy-subtree'.")
5046 (defvar org-subtree-clip-folded nil
5047 "Was the last copied subtree folded?
5048 This is used to fold the tree back after pasting.")
5050 (defun org-cut-subtree (&optional n)
5051 "Cut the current subtree into the clipboard.
5052 With prefix arg N, cut this many sequential subtrees.
5053 This is a short-hand for marking the subtree and then cutting it."
5054 (interactive "p")
5055 (org-copy-subtree n 'cut))
5057 (defun org-copy-subtree (&optional n cut force-store-markers)
5058 "Cut the current subtree into the clipboard.
5059 With prefix arg N, cut this many sequential subtrees.
5060 This is a short-hand for marking the subtree and then copying it.
5061 If CUT is non-nil, actually cut the subtree.
5062 If FORCE-STORE-MARKERS is non-nil, store the relative locations
5063 of some markers in the region, even if CUT is non-nil. This is
5064 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
5065 (interactive "p")
5066 (let (beg end folded (beg0 (point)))
5067 (if (interactive-p)
5068 (org-back-to-heading nil) ; take what looks like a subtree
5069 (org-back-to-heading t)) ; take what is really there
5070 (org-back-over-empty-lines)
5071 (setq beg (point))
5072 (skip-chars-forward " \t\r\n")
5073 (save-match-data
5074 (save-excursion (outline-end-of-heading)
5075 (setq folded (org-invisible-p)))
5076 (condition-case nil
5077 (outline-forward-same-level (1- n))
5078 (error nil))
5079 (org-end-of-subtree t t))
5080 (org-back-over-empty-lines)
5081 (setq end (point))
5082 (goto-char beg0)
5083 (when (> end beg)
5084 (setq org-subtree-clip-folded folded)
5085 (when (or cut force-store-markers)
5086 (org-save-markers-in-region beg end))
5087 (if cut (kill-region beg end) (copy-region-as-kill beg end))
5088 (setq org-subtree-clip (current-kill 0))
5089 (message "%s: Subtree(s) with %d characters"
5090 (if cut "Cut" "Copied")
5091 (length org-subtree-clip)))))
5093 (defun org-paste-subtree (&optional level tree for-yank)
5094 "Paste the clipboard as a subtree, with modification of headline level.
5095 The entire subtree is promoted or demoted in order to match a new headline
5096 level.
5098 If the cursor is at the beginning of a headline, the same level as
5099 that headline is used to paste the tree
5101 If not, the new level is derived from the *visible* headings
5102 before and after the insertion point, and taken to be the inferior headline
5103 level of the two. So if the previous visible heading is level 3 and the
5104 next is level 4 (or vice versa), level 4 will be used for insertion.
5105 This makes sure that the subtree remains an independent subtree and does
5106 not swallow low level entries.
5108 You can also force a different level, either by using a numeric prefix
5109 argument, or by inserting the heading marker by hand. For example, if the
5110 cursor is after \"*****\", then the tree will be shifted to level 5.
5112 If optional TREE is given, use this text instead of the kill ring.
5114 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
5115 move back over whitespace before inserting, and move point to the end of
5116 the inserted text when done."
5117 (interactive "P")
5118 (unless (org-kill-is-subtree-p tree)
5119 (error "%s"
5120 (substitute-command-keys
5121 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
5122 (let* ((visp (not (org-invisible-p)))
5123 (txt (or tree (and kill-ring (current-kill 0))))
5124 (^re (concat "^\\(" outline-regexp "\\)"))
5125 (re (concat "\\(" outline-regexp "\\)"))
5126 (^re_ (concat "\\(\\*+\\)[ \t]*"))
5128 (old-level (if (string-match ^re txt)
5129 (- (match-end 0) (match-beginning 0) 1)
5130 -1))
5131 (force-level (cond (level (prefix-numeric-value level))
5132 ((and (looking-at "[ \t]*$")
5133 (string-match
5134 ^re_ (buffer-substring
5135 (point-at-bol) (point))))
5136 (- (match-end 1) (match-beginning 1)))
5137 ((and (bolp)
5138 (looking-at org-outline-regexp))
5139 (- (match-end 0) (point) 1))
5140 (t nil)))
5141 (previous-level (save-excursion
5142 (condition-case nil
5143 (progn
5144 (outline-previous-visible-heading 1)
5145 (if (looking-at re)
5146 (- (match-end 0) (match-beginning 0) 1)
5148 (error 1))))
5149 (next-level (save-excursion
5150 (condition-case nil
5151 (progn
5152 (or (looking-at outline-regexp)
5153 (outline-next-visible-heading 1))
5154 (if (looking-at re)
5155 (- (match-end 0) (match-beginning 0) 1)
5157 (error 1))))
5158 (new-level (or force-level (max previous-level next-level)))
5159 (shift (if (or (= old-level -1)
5160 (= new-level -1)
5161 (= old-level new-level))
5163 (- new-level old-level)))
5164 (delta (if (> shift 0) -1 1))
5165 (func (if (> shift 0) 'org-demote 'org-promote))
5166 (org-odd-levels-only nil)
5167 beg end newend)
5168 ;; Remove the forced level indicator
5169 (if force-level
5170 (delete-region (point-at-bol) (point)))
5171 ;; Paste
5172 (beginning-of-line 1)
5173 (unless for-yank (org-back-over-empty-lines))
5174 (setq beg (point))
5175 (insert-before-markers txt)
5176 (unless (string-match "\n\\'" txt) (insert "\n"))
5177 (setq newend (point))
5178 (org-reinstall-markers-in-region beg)
5179 (setq end (point))
5180 (goto-char beg)
5181 (skip-chars-forward " \t\n\r")
5182 (setq beg (point))
5183 (if (and (org-invisible-p) visp)
5184 (save-excursion (outline-show-heading)))
5185 ;; Shift if necessary
5186 (unless (= shift 0)
5187 (save-restriction
5188 (narrow-to-region beg end)
5189 (while (not (= shift 0))
5190 (org-map-region func (point-min) (point-max))
5191 (setq shift (+ delta shift)))
5192 (goto-char (point-min))
5193 (setq newend (point-max))))
5194 (when (or (interactive-p) for-yank)
5195 (message "Clipboard pasted as level %d subtree" new-level))
5196 (if (and (not for-yank) ; in this case, org-yank will decide about folding
5197 kill-ring
5198 (eq org-subtree-clip (current-kill 0))
5199 org-subtree-clip-folded)
5200 ;; The tree was folded before it was killed/copied
5201 (hide-subtree))
5202 (and for-yank (goto-char newend))))
5204 (defun org-kill-is-subtree-p (&optional txt)
5205 "Check if the current kill is an outline subtree, or a set of trees.
5206 Returns nil if kill does not start with a headline, or if the first
5207 headline level is not the largest headline level in the tree.
5208 So this will actually accept several entries of equal levels as well,
5209 which is OK for `org-paste-subtree'.
5210 If optional TXT is given, check this string instead of the current kill."
5211 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
5212 (start-level (and kill
5213 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
5214 org-outline-regexp "\\)")
5215 kill)
5216 (- (match-end 2) (match-beginning 2) 1)))
5217 (re (concat "^" org-outline-regexp))
5218 (start (1+ (or (match-beginning 2) -1))))
5219 (if (not start-level)
5220 (progn
5221 nil) ;; does not even start with a heading
5222 (catch 'exit
5223 (while (setq start (string-match re kill (1+ start)))
5224 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
5225 (throw 'exit nil)))
5226 t))))
5228 (defvar org-markers-to-move nil
5229 "Markers that should be moved with a cut-and-paste operation.
5230 Those markers are stored together with their positions relative to
5231 the start of the region.")
5233 (defun org-save-markers-in-region (beg end)
5234 "Check markers in region.
5235 If these markers are between BEG and END, record their position relative
5236 to BEG, so that after moving the block of text, we can put the markers back
5237 into place.
5238 This function gets called just before an entry or tree gets cut from the
5239 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
5240 called immediately, to move the markers with the entries."
5241 (setq org-markers-to-move nil)
5242 (when (featurep 'org-clock)
5243 (org-clock-save-markers-for-cut-and-paste beg end))
5244 (when (featurep 'org-agenda)
5245 (org-agenda-save-markers-for-cut-and-paste beg end)))
5247 (defun org-check-and-save-marker (marker beg end)
5248 "Check if MARKER is between BEG and END.
5249 If yes, remember the marker and the distance to BEG."
5250 (when (and (marker-buffer marker)
5251 (equal (marker-buffer marker) (current-buffer)))
5252 (if (and (>= marker beg) (< marker end))
5253 (push (cons marker (- marker beg)) org-markers-to-move))))
5255 (defun org-reinstall-markers-in-region (beg)
5256 "Move all remembered markers to their position relative to BEG."
5257 (mapc (lambda (x)
5258 (move-marker (car x) (+ beg (cdr x))))
5259 org-markers-to-move)
5260 (setq org-markers-to-move nil))
5262 (defun org-narrow-to-subtree ()
5263 "Narrow buffer to the current subtree."
5264 (interactive)
5265 (save-excursion
5266 (save-match-data
5267 (narrow-to-region
5268 (progn (org-back-to-heading) (point))
5269 (progn (org-end-of-subtree t) (point))))))
5272 ;;; Outline Sorting
5274 (defun org-sort (with-case)
5275 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
5276 Optional argument WITH-CASE means sort case-sensitively."
5277 (interactive "P")
5278 (if (org-at-table-p)
5279 (org-call-with-arg 'org-table-sort-lines with-case)
5280 (org-call-with-arg 'org-sort-entries-or-items with-case)))
5282 (defun org-sort-remove-invisible (s)
5283 (remove-text-properties 0 (length s) org-rm-props s)
5284 (while (string-match org-bracket-link-regexp s)
5285 (setq s (replace-match (if (match-end 2)
5286 (match-string 3 s)
5287 (match-string 1 s)) t t s)))
5290 (defvar org-priority-regexp) ; defined later in the file
5292 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
5293 "Sort entries on a certain level of an outline tree.
5294 If there is an active region, the entries in the region are sorted.
5295 Else, if the cursor is before the first entry, sort the top-level items.
5296 Else, the children of the entry at point are sorted.
5298 Sorting can be alphabetically, numerically, and by date/time as given by
5299 the first time stamp in the entry. The command prompts for the sorting
5300 type unless it has been given to the function through the SORTING-TYPE
5301 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
5302 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
5303 called with point at the beginning of the record. It must return either
5304 a string or a number that should serve as the sorting key for that record.
5306 Comparing entries ignores case by default. However, with an optional argument
5307 WITH-CASE, the sorting considers case as well."
5308 (interactive "P")
5309 (let ((case-func (if with-case 'identity 'downcase))
5310 start beg end stars re re2
5311 txt what tmp plain-list-p)
5312 ;; Find beginning and end of region to sort
5313 (cond
5314 ((org-region-active-p)
5315 ;; we will sort the region
5316 (setq end (region-end)
5317 what "region")
5318 (goto-char (region-beginning))
5319 (if (not (org-on-heading-p)) (outline-next-heading))
5320 (setq start (point)))
5321 ((org-at-item-p)
5322 ;; we will sort this plain list
5323 (org-beginning-of-item-list) (setq start (point))
5324 (org-end-of-item-list) (setq end (point))
5325 (goto-char start)
5326 (setq plain-list-p t
5327 what "plain list"))
5328 ((or (org-on-heading-p)
5329 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
5330 ;; we will sort the children of the current headline
5331 (org-back-to-heading)
5332 (setq start (point)
5333 end (progn (org-end-of-subtree t t)
5334 (org-back-over-empty-lines)
5335 (point))
5336 what "children")
5337 (goto-char start)
5338 (show-subtree)
5339 (outline-next-heading))
5341 ;; we will sort the top-level entries in this file
5342 (goto-char (point-min))
5343 (or (org-on-heading-p) (outline-next-heading))
5344 (setq start (point) end (point-max) what "top-level")
5345 (goto-char start)
5346 (show-all)))
5348 (setq beg (point))
5349 (if (>= beg end) (error "Nothing to sort"))
5351 (unless plain-list-p
5352 (looking-at "\\(\\*+\\)")
5353 (setq stars (match-string 1)
5354 re (concat "^" (regexp-quote stars) " +")
5355 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
5356 txt (buffer-substring beg end))
5357 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
5358 (if (and (not (equal stars "*")) (string-match re2 txt))
5359 (error "Region to sort contains a level above the first entry")))
5361 (unless sorting-type
5362 (message
5363 (if plain-list-p
5364 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
5365 "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:")
5366 what)
5367 (setq sorting-type (read-char-exclusive))
5369 (and (= (downcase sorting-type) ?f)
5370 (setq getkey-func
5371 (completing-read "Sort using function: "
5372 obarray 'fboundp t nil nil))
5373 (setq getkey-func (intern getkey-func)))
5375 (and (= (downcase sorting-type) ?r)
5376 (setq property
5377 (completing-read "Property: "
5378 (mapcar 'list (org-buffer-property-keys t))
5379 nil t))))
5381 (message "Sorting entries...")
5383 (save-restriction
5384 (narrow-to-region start end)
5386 (let ((dcst (downcase sorting-type))
5387 (now (current-time)))
5388 (sort-subr
5389 (/= dcst sorting-type)
5390 ;; This function moves to the beginning character of the "record" to
5391 ;; be sorted.
5392 (if plain-list-p
5393 (lambda nil
5394 (if (org-at-item-p) t (goto-char (point-max))))
5395 (lambda nil
5396 (if (re-search-forward re nil t)
5397 (goto-char (match-beginning 0))
5398 (goto-char (point-max)))))
5399 ;; This function moves to the last character of the "record" being
5400 ;; sorted.
5401 (if plain-list-p
5402 'org-end-of-item
5403 (lambda nil
5404 (save-match-data
5405 (condition-case nil
5406 (outline-forward-same-level 1)
5407 (error
5408 (goto-char (point-max)))))))
5410 ;; This function returns the value that gets sorted against.
5411 (if plain-list-p
5412 (lambda nil
5413 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
5414 (cond
5415 ((= dcst ?n)
5416 (string-to-number (buffer-substring (match-end 0)
5417 (point-at-eol))))
5418 ((= dcst ?a)
5419 (buffer-substring (match-end 0) (point-at-eol)))
5420 ((= dcst ?t)
5421 (if (re-search-forward org-ts-regexp
5422 (point-at-eol) t)
5423 (org-time-string-to-time (match-string 0))
5424 now))
5425 ((= dcst ?f)
5426 (if getkey-func
5427 (progn
5428 (setq tmp (funcall getkey-func))
5429 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5430 tmp)
5431 (error "Invalid key function `%s'" getkey-func)))
5432 (t (error "Invalid sorting type `%c'" sorting-type)))))
5433 (lambda nil
5434 (cond
5435 ((= dcst ?n)
5436 (if (looking-at org-complex-heading-regexp)
5437 (string-to-number (match-string 4))
5438 nil))
5439 ((= dcst ?a)
5440 (if (looking-at org-complex-heading-regexp)
5441 (funcall case-func (match-string 4))
5442 nil))
5443 ((= dcst ?t)
5444 (if (re-search-forward org-ts-regexp
5445 (save-excursion
5446 (forward-line 2)
5447 (point)) t)
5448 (org-time-string-to-time (match-string 0))
5449 now))
5450 ((= dcst ?p)
5451 (if (re-search-forward org-priority-regexp (point-at-eol) t)
5452 (string-to-char (match-string 2))
5453 org-default-priority))
5454 ((= dcst ?r)
5455 (or (org-entry-get nil property) ""))
5456 ((= dcst ?o)
5457 (if (looking-at org-complex-heading-regexp)
5458 (- 9999 (length (member (match-string 2)
5459 org-todo-keywords-1)))))
5460 ((= dcst ?f)
5461 (if getkey-func
5462 (progn
5463 (setq tmp (funcall getkey-func))
5464 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5465 tmp)
5466 (error "Invalid key function `%s'" getkey-func)))
5467 (t (error "Invalid sorting type `%c'" sorting-type)))))
5469 (cond
5470 ((= dcst ?a) 'string<)
5471 ((= dcst ?t) 'time-less-p)
5472 (t nil)))))
5473 (message "Sorting entries...done")))
5475 (defun org-do-sort (table what &optional with-case sorting-type)
5476 "Sort TABLE of WHAT according to SORTING-TYPE.
5477 The user will be prompted for the SORTING-TYPE if the call to this
5478 function does not specify it. WHAT is only for the prompt, to indicate
5479 what is being sorted. The sorting key will be extracted from
5480 the car of the elements of the table.
5481 If WITH-CASE is non-nil, the sorting will be case-sensitive."
5482 (unless sorting-type
5483 (message
5484 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
5485 what)
5486 (setq sorting-type (read-char-exclusive)))
5487 (let ((dcst (downcase sorting-type))
5488 extractfun comparefun)
5489 ;; Define the appropriate functions
5490 (cond
5491 ((= dcst ?n)
5492 (setq extractfun 'string-to-number
5493 comparefun (if (= dcst sorting-type) '< '>)))
5494 ((= dcst ?a)
5495 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
5496 (lambda(x) (downcase (org-sort-remove-invisible x))))
5497 comparefun (if (= dcst sorting-type)
5498 'string<
5499 (lambda (a b) (and (not (string< a b))
5500 (not (string= a b)))))))
5501 ((= dcst ?t)
5502 (setq extractfun
5503 (lambda (x)
5504 (if (string-match org-ts-regexp x)
5505 (time-to-seconds
5506 (org-time-string-to-time (match-string 0 x)))
5508 comparefun (if (= dcst sorting-type) '< '>)))
5509 (t (error "Invalid sorting type `%c'" sorting-type)))
5511 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5512 table)
5513 (lambda (a b) (funcall comparefun (car a) (car b))))))
5515 ;;; Editing source examples
5517 (defvar org-exit-edit-mode-map (make-sparse-keymap))
5518 (define-key org-exit-edit-mode-map "\C-c'" 'org-edit-src-exit)
5519 (defvar org-edit-src-force-single-line nil)
5520 (defvar org-edit-src-from-org-mode nil)
5521 (defvar org-edit-src-picture nil)
5523 (define-minor-mode org-exit-edit-mode
5524 "Minor mode installing a single key binding, \"C-c '\" to exit special edit.")
5526 (defun org-edit-src-code ()
5527 "Edit the source code example at point.
5528 An indirect buffer is created, and that buffer is then narrowed to the
5529 example at point and switched to the correct language mode. When done,
5530 exit by killing the buffer with \\[org-edit-src-exit]."
5531 (interactive)
5532 (let ((line (org-current-line))
5533 (case-fold-search t)
5534 (msg (substitute-command-keys
5535 "Edit, then exit with C-c ' (C-c and single quote)"))
5536 (info (org-edit-src-find-region-and-lang))
5537 (org-mode-p (eq major-mode 'org-mode))
5538 beg end lang lang-f single)
5539 (if (not info)
5541 (setq beg (nth 0 info)
5542 end (nth 1 info)
5543 lang (nth 2 info)
5544 single (nth 3 info)
5545 lang-f (intern (concat lang "-mode")))
5546 (unless (functionp lang-f)
5547 (error "No such language mode: %s" lang-f))
5548 (goto-line line)
5549 (if (get-buffer "*Org Edit Src Example*")
5550 (kill-buffer "*Org Edit Src Example*"))
5551 (switch-to-buffer (make-indirect-buffer (current-buffer)
5552 "*Org Edit Src Example*"))
5553 (narrow-to-region beg end)
5554 (remove-text-properties beg end '(display nil invisible nil
5555 intangible nil))
5556 (let ((org-inhibit-startup t))
5557 (funcall lang-f))
5558 (set (make-local-variable 'org-edit-src-force-single-line) single)
5559 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5560 (when org-mode-p
5561 (goto-char (point-min))
5562 (while (re-search-forward "^," nil t)
5563 (replace-match "")))
5564 (goto-line line)
5565 (org-exit-edit-mode)
5566 (org-set-local 'header-line-format msg)
5567 (message "%s" msg)
5568 t)))
5570 (defun org-edit-fixed-width-region ()
5571 "Edit the fixed-width ascii drawing at point.
5572 This must be a region where each line starts with ca colon followed by
5573 a space character.
5574 An indirect buffer is created, and that buffer is then narrowed to the
5575 example at point and switched to artist-mode. When done,
5576 exit by killing the buffer with \\[org-edit-src-exit]."
5577 (interactive)
5578 (let ((line (org-current-line))
5579 (case-fold-search t)
5580 (msg (substitute-command-keys
5581 "Edit, then exit with C-c ' (C-c and single quote)"))
5582 (org-mode-p (eq major-mode 'org-mode))
5583 beg end lang lang-f)
5584 (beginning-of-line 1)
5585 (if (looking-at "[ \t]*[^:\n \t]")
5587 (if (looking-at "[ \t]*\\(\n\\|\\'\\)]")
5588 (setq beg (point) end (match-end 0))
5589 (save-excursion
5590 (if (re-search-backward "^[ \t]*[^:]" nil 'move)
5591 (setq beg (point-at-bol 2))
5592 (setq beg (point))))
5593 (save-excursion
5594 (if (re-search-forward "^[ \t]*[^:]" nil 'move)
5595 (setq end (1- (match-beginning 0)))
5596 (setq end (point))))
5597 (goto-line line)
5598 (if (get-buffer "*Org Edit Picture*")
5599 (kill-buffer "*Org Edit Picture*"))
5600 (switch-to-buffer (make-indirect-buffer (current-buffer)
5601 "*Org Edit Picture*"))
5602 (narrow-to-region beg end)
5603 (remove-text-properties beg end '(display nil invisible nil
5604 intangible nil))
5605 (when (fboundp 'font-lock-unfontify-region)
5606 (font-lock-unfontify-region (point-min) (point-max)))
5607 (cond
5608 ((eq org-edit-fixed-width-region-mode 'artist-mode)
5609 (fundamental-mode)
5610 (artist-mode 1))
5611 (t (funcall org-edit-fixed-width-region-mode)))
5612 (set (make-local-variable 'org-edit-src-force-single-line) nil)
5613 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5614 (set (make-local-variable 'org-edit-src-picture) t)
5615 (goto-char (point-min))
5616 (while (re-search-forward "^[ \t]*: " nil t)
5617 (replace-match ""))
5618 (goto-line line)
5619 (org-exit-edit-mode)
5620 (org-set-local 'header-line-format msg)
5621 (message "%s" msg)
5622 t))))
5625 (defun org-edit-src-find-region-and-lang ()
5626 "Find the region and language for a local edit.
5627 Return a list with beginning and end of the region, a string representing
5628 the language, a switch telling of the content should be in a single line."
5629 (let ((re-list
5630 (append
5631 org-edit-src-region-extra
5633 ("<src\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</src>" lang)
5634 ("<literal\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</literal>" style)
5635 ("<example>[ \t]*\n?" "\n?[ \t]*</example>" "fundamental")
5636 ("<lisp>[ \t]*\n?" "\n?[ \t]*</lisp>" "emacs-lisp")
5637 ("<perl>[ \t]*\n?" "\n?[ \t]*</perl>" "perl")
5638 ("<python>[ \t]*\n?" "\n?[ \t]*</python>" "python")
5639 ("<ruby>[ \t]*\n?" "\n?[ \t]*</ruby>" "ruby")
5640 ("^#\\+begin_src\\( \\([^ \t\n]+\\)\\)?.*\n" "\n#\\+end_src" 2)
5641 ("^#\\+begin_example.*\n" "\n#\\+end_example" "fundamental")
5642 ("^#\\+html:" "\n" "html" single-line)
5643 ("^#\\+begin_html.*\n" "\n#\\+end_html" "html")
5644 ("^#\\+begin_latex.*\n" "\n#\\+end_latex" "latex")
5645 ("^#\\+latex:" "\n" "latex" single-line)
5646 ("^#\\+begin_ascii.*\n" "\n#\\+end_ascii" "fundamental")
5647 ("^#\\+ascii:" "\n" "ascii" single-line)
5649 (pos (point))
5650 re re1 re2 single beg end lang)
5651 (catch 'exit
5652 (while (setq entry (pop re-list))
5653 (setq re1 (car entry) re2 (nth 1 entry) lang (nth 2 entry)
5654 single (nth 3 entry))
5655 (save-excursion
5656 (if (or (looking-at re1)
5657 (re-search-backward re1 nil t))
5658 (progn
5659 (setq beg (match-end 0) lang (org-edit-src-get-lang lang))
5660 (if (and (re-search-forward re2 nil t)
5661 (>= (match-end 0) pos))
5662 (throw 'exit (list beg (match-beginning 0) lang single))))
5663 (if (or (looking-at re2)
5664 (re-search-forward re2 nil t))
5665 (progn
5666 (setq end (match-beginning 0))
5667 (if (and (re-search-backward re1 nil t)
5668 (<= (match-beginning 0) pos))
5669 (throw 'exit
5670 (list (match-end 0) end
5671 (org-edit-src-get-lang lang) single)))))))))))
5673 (defun org-edit-src-get-lang (lang)
5674 "Extract the src language."
5675 (let ((m (match-string 0)))
5676 (cond
5677 ((stringp lang) lang)
5678 ((integerp lang) (match-string lang))
5679 ((and (eq lang 'lang)
5680 (string-match "\\<lang=\"\\([^ \t\n\"]+\\)\"" m))
5681 (match-string 1 m))
5682 ((and (eq lang 'style)
5683 (string-match "\\<style=\"\\([^ \t\n\"]+\\)\"" m))
5684 (match-string 1 m))
5685 (t "fundamental"))))
5687 (defun org-edit-src-exit ()
5688 "Exit special edit and protect problematic lines."
5689 (interactive)
5690 (unless (buffer-base-buffer (current-buffer))
5691 (error "This is not an indirect buffer, something is wrong..."))
5692 (unless (> (point-min) 1)
5693 (error "This buffer is not narrowed, something is wrong..."))
5694 (goto-char (point-min))
5695 (if (looking-at "[ \t\n]*\n") (replace-match ""))
5696 (if (re-search-forward "\n[ \t\n]*\\'" nil t) (replace-match ""))
5697 (when (org-bound-and-true-p org-edit-src-force-single-line)
5698 (goto-char (point-min))
5699 (while (re-search-forward "\n" nil t)
5700 (replace-match " "))
5701 (goto-char (point-min))
5702 (if (looking-at "\\s-*") (replace-match " "))
5703 (if (re-search-forward "\\s-+\\'" nil t)
5704 (replace-match "")))
5705 (when (org-bound-and-true-p org-edit-src-from-org-mode)
5706 (goto-char (point-min))
5707 (while (re-search-forward (if (org-mode-p) "^\\(.\\)" "^\\([*#]\\)") nil t)
5708 (replace-match ",\\1"))
5709 (when font-lock-mode
5710 (font-lock-unfontify-region (point-min) (point-max)))
5711 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
5712 (when (org-bound-and-true-p org-edit-src-picture)
5713 (goto-char (point-min))
5714 (while (re-search-forward "^" nil t)
5715 (replace-match ": "))
5716 (when font-lock-mode
5717 (font-lock-unfontify-region (point-min) (point-max)))
5718 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
5719 (kill-buffer (current-buffer))
5720 (and (org-mode-p) (org-restart-font-lock)))
5723 ;;; The orgstruct minor mode
5725 ;; Define a minor mode which can be used in other modes in order to
5726 ;; integrate the org-mode structure editing commands.
5728 ;; This is really a hack, because the org-mode structure commands use
5729 ;; keys which normally belong to the major mode. Here is how it
5730 ;; works: The minor mode defines all the keys necessary to operate the
5731 ;; structure commands, but wraps the commands into a function which
5732 ;; tests if the cursor is currently at a headline or a plain list
5733 ;; item. If that is the case, the structure command is used,
5734 ;; temporarily setting many Org-mode variables like regular
5735 ;; expressions for filling etc. However, when any of those keys is
5736 ;; used at a different location, function uses `key-binding' to look
5737 ;; up if the key has an associated command in another currently active
5738 ;; keymap (minor modes, major mode, global), and executes that
5739 ;; command. There might be problems if any of the keys is otherwise
5740 ;; used as a prefix key.
5742 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
5743 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
5744 ;; addresses this by checking explicitly for both bindings.
5746 (defvar orgstruct-mode-map (make-sparse-keymap)
5747 "Keymap for the minor `orgstruct-mode'.")
5749 (defvar org-local-vars nil
5750 "List of local variables, for use by `orgstruct-mode'")
5752 ;;;###autoload
5753 (define-minor-mode orgstruct-mode
5754 "Toggle the minor more `orgstruct-mode'.
5755 This mode is for using Org-mode structure commands in other modes.
5756 The following key behave as if Org-mode was active, if the cursor
5757 is on a headline, or on a plain list item (both in the definition
5758 of Org-mode).
5760 M-up Move entry/item up
5761 M-down Move entry/item down
5762 M-left Promote
5763 M-right Demote
5764 M-S-up Move entry/item up
5765 M-S-down Move entry/item down
5766 M-S-left Promote subtree
5767 M-S-right Demote subtree
5768 M-q Fill paragraph and items like in Org-mode
5769 C-c ^ Sort entries
5770 C-c - Cycle list bullet
5771 TAB Cycle item visibility
5772 M-RET Insert new heading/item
5773 S-M-RET Insert new TODO heading / Chekbox item
5774 C-c C-c Set tags / toggle checkbox"
5775 nil " OrgStruct" nil
5776 (org-load-modules-maybe)
5777 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
5779 ;;;###autoload
5780 (defun turn-on-orgstruct ()
5781 "Unconditionally turn on `orgstruct-mode'."
5782 (orgstruct-mode 1))
5784 ;;;###autoload
5785 (defun turn-on-orgstruct++ ()
5786 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
5787 In addition to setting orgstruct-mode, this also exports all indentation and
5788 autofilling variables from org-mode into the buffer. Note that turning
5789 off orgstruct-mode will *not* remove these additional settings."
5790 (orgstruct-mode 1)
5791 (let (var val)
5792 (mapc
5793 (lambda (x)
5794 (when (string-match
5795 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
5796 (symbol-name (car x)))
5797 (setq var (car x) val (nth 1 x))
5798 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
5799 org-local-vars)))
5801 (defun orgstruct-error ()
5802 "Error when there is no default binding for a structure key."
5803 (interactive)
5804 (error "This key has no function outside structure elements"))
5806 (defun orgstruct-setup ()
5807 "Setup orgstruct keymaps."
5808 (let ((nfunc 0)
5809 (bindings
5810 (list
5811 '([(meta up)] org-metaup)
5812 '([(meta down)] org-metadown)
5813 '([(meta left)] org-metaleft)
5814 '([(meta right)] org-metaright)
5815 '([(meta shift up)] org-shiftmetaup)
5816 '([(meta shift down)] org-shiftmetadown)
5817 '([(meta shift left)] org-shiftmetaleft)
5818 '([(meta shift right)] org-shiftmetaright)
5819 '([(shift up)] org-shiftup)
5820 '([(shift down)] org-shiftdown)
5821 '("\C-c\C-c" org-ctrl-c-ctrl-c)
5822 '("\M-q" fill-paragraph)
5823 '("\C-c^" org-sort)
5824 '("\C-c-" org-cycle-list-bullet)))
5825 elt key fun cmd)
5826 (while (setq elt (pop bindings))
5827 (setq nfunc (1+ nfunc))
5828 (setq key (org-key (car elt))
5829 fun (nth 1 elt)
5830 cmd (orgstruct-make-binding fun nfunc key))
5831 (org-defkey orgstruct-mode-map key cmd))
5833 ;; Special treatment needed for TAB and RET
5834 (org-defkey orgstruct-mode-map [(tab)]
5835 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
5836 (org-defkey orgstruct-mode-map "\C-i"
5837 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
5839 (org-defkey orgstruct-mode-map "\M-\C-m"
5840 (orgstruct-make-binding 'org-insert-heading 105
5841 "\M-\C-m" [(meta return)]))
5842 (org-defkey orgstruct-mode-map [(meta return)]
5843 (orgstruct-make-binding 'org-insert-heading 106
5844 [(meta return)] "\M-\C-m"))
5846 (org-defkey orgstruct-mode-map [(shift meta return)]
5847 (orgstruct-make-binding 'org-insert-todo-heading 107
5848 [(meta return)] "\M-\C-m"))
5850 (unless org-local-vars
5851 (setq org-local-vars (org-get-local-variables)))
5855 (defun orgstruct-make-binding (fun n &rest keys)
5856 "Create a function for binding in the structure minor mode.
5857 FUN is the command to call inside a table. N is used to create a unique
5858 command name. KEYS are keys that should be checked in for a command
5859 to execute outside of tables."
5860 (eval
5861 (list 'defun
5862 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
5863 '(arg)
5864 (concat "In Structure, run `" (symbol-name fun) "'.\n"
5865 "Outside of structure, run the binding of `"
5866 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
5867 "'.")
5868 '(interactive "p")
5869 (list 'if
5870 '(org-context-p 'headline 'item)
5871 (list 'org-run-like-in-org-mode (list 'quote fun))
5872 (list 'let '(orgstruct-mode)
5873 (list 'call-interactively
5874 (append '(or)
5875 (mapcar (lambda (k)
5876 (list 'key-binding k))
5877 keys)
5878 '('orgstruct-error))))))))
5880 (defun org-context-p (&rest contexts)
5881 "Check if local context is any of CONTEXTS.
5882 Possible values in the list of contexts are `table', `headline', and `item'."
5883 (let ((pos (point)))
5884 (goto-char (point-at-bol))
5885 (prog1 (or (and (memq 'table contexts)
5886 (looking-at "[ \t]*|"))
5887 (and (memq 'headline contexts)
5888 ;;????????? (looking-at "\\*+"))
5889 (looking-at outline-regexp))
5890 (and (memq 'item contexts)
5891 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
5892 (goto-char pos))))
5894 (defun org-get-local-variables ()
5895 "Return a list of all local variables in an org-mode buffer."
5896 (let (varlist)
5897 (with-current-buffer (get-buffer-create "*Org tmp*")
5898 (erase-buffer)
5899 (org-mode)
5900 (setq varlist (buffer-local-variables)))
5901 (kill-buffer "*Org tmp*")
5902 (delq nil
5903 (mapcar
5904 (lambda (x)
5905 (setq x
5906 (if (symbolp x)
5907 (list x)
5908 (list (car x) (list 'quote (cdr x)))))
5909 (if (string-match
5910 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
5911 (symbol-name (car x)))
5912 x nil))
5913 varlist))))
5915 ;;;###autoload
5916 (defun org-run-like-in-org-mode (cmd)
5917 (org-load-modules-maybe)
5918 (unless org-local-vars
5919 (setq org-local-vars (org-get-local-variables)))
5920 (eval (list 'let org-local-vars
5921 (list 'call-interactively (list 'quote cmd)))))
5923 ;;;; Archiving
5925 (defun org-get-category (&optional pos)
5926 "Get the category applying to position POS."
5927 (get-text-property (or pos (point)) 'org-category))
5929 (defun org-refresh-category-properties ()
5930 "Refresh category text properties in the buffer."
5931 (let ((def-cat (cond
5932 ((null org-category)
5933 (if buffer-file-name
5934 (file-name-sans-extension
5935 (file-name-nondirectory buffer-file-name))
5936 "???"))
5937 ((symbolp org-category) (symbol-name org-category))
5938 (t org-category)))
5939 beg end cat pos optionp)
5940 (org-unmodified
5941 (save-excursion
5942 (save-restriction
5943 (widen)
5944 (goto-char (point-min))
5945 (put-text-property (point) (point-max) 'org-category def-cat)
5946 (while (re-search-forward
5947 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
5948 (setq pos (match-end 0)
5949 optionp (equal (char-after (match-beginning 0)) ?#)
5950 cat (org-trim (match-string 2)))
5951 (if optionp
5952 (setq beg (point-at-bol) end (point-max))
5953 (org-back-to-heading t)
5954 (setq beg (point) end (org-end-of-subtree t t)))
5955 (put-text-property beg end 'org-category cat)
5956 (goto-char pos)))))))
5959 ;;;; Link Stuff
5961 ;;; Link abbreviations
5963 (defun org-link-expand-abbrev (link)
5964 "Apply replacements as defined in `org-link-abbrev-alist."
5965 (debug)
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 (let ((minibuffer-local-completion-map
6534 (copy-keymap minibuffer-local-completion-map)))
6535 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
6536 (apply 'completing-read args)))
6538 (defun org-extract-attributes (s)
6539 "Extract the attributes cookie from a string and set as text property."
6540 (let (a attr (start 0) key value)
6541 (save-match-data
6542 (when (string-match "{{\\([^}]+\\)}}$" s)
6543 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
6544 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
6545 (setq key (match-string 1 a) value (match-string 2 a)
6546 start (match-end 0)
6547 attr (plist-put attr (intern key) value))))
6548 (org-add-props s nil 'org-attributes attr))
6551 (defun org-attributes-to-string (plist)
6552 "Format a property list into an HTML attribute list."
6553 (let ((s "") key value)
6554 (while plist
6555 (setq key (pop plist) value (pop plist))
6556 (setq s (concat s " "(symbol-name key) "=\"" value "\"")))
6559 ;;; Opening/following a link
6561 (defvar org-link-search-failed nil)
6563 (defun org-next-link ()
6564 "Move forward to the next link.
6565 If the link is in hidden text, expose it."
6566 (interactive)
6567 (when (and org-link-search-failed (eq this-command last-command))
6568 (goto-char (point-min))
6569 (message "Link search wrapped back to beginning of buffer"))
6570 (setq org-link-search-failed nil)
6571 (let* ((pos (point))
6572 (ct (org-context))
6573 (a (assoc :link ct)))
6574 (if a (goto-char (nth 2 a)))
6575 (if (re-search-forward org-any-link-re nil t)
6576 (progn
6577 (goto-char (match-beginning 0))
6578 (if (org-invisible-p) (org-show-context)))
6579 (goto-char pos)
6580 (setq org-link-search-failed t)
6581 (error "No further link found"))))
6583 (defun org-previous-link ()
6584 "Move backward to the previous link.
6585 If the link is in hidden text, expose it."
6586 (interactive)
6587 (when (and org-link-search-failed (eq this-command last-command))
6588 (goto-char (point-max))
6589 (message "Link search wrapped back to end of buffer"))
6590 (setq org-link-search-failed nil)
6591 (let* ((pos (point))
6592 (ct (org-context))
6593 (a (assoc :link ct)))
6594 (if a (goto-char (nth 1 a)))
6595 (if (re-search-backward org-any-link-re nil t)
6596 (progn
6597 (goto-char (match-beginning 0))
6598 (if (org-invisible-p) (org-show-context)))
6599 (goto-char pos)
6600 (setq org-link-search-failed t)
6601 (error "No further link found"))))
6603 (defun org-find-file-at-mouse (ev)
6604 "Open file link or URL at mouse."
6605 (interactive "e")
6606 (mouse-set-point ev)
6607 (org-open-at-point 'in-emacs))
6609 (defun org-open-at-mouse (ev)
6610 "Open file link or URL at mouse."
6611 (interactive "e")
6612 (mouse-set-point ev)
6613 (org-open-at-point))
6615 (defvar org-window-config-before-follow-link nil
6616 "The window configuration before following a link.
6617 This is saved in case the need arises to restore it.")
6619 (defvar org-open-link-marker (make-marker)
6620 "Marker pointing to the location where `org-open-at-point; was called.")
6622 ;;;###autoload
6623 (defun org-open-at-point-global ()
6624 "Follow a link like Org-mode does.
6625 This command can be called in any mode to follow a link that has
6626 Org-mode syntax."
6627 (interactive)
6628 (org-run-like-in-org-mode 'org-open-at-point))
6630 ;;;###autoload
6631 (defun org-open-link-from-string (s &optional arg)
6632 "Open a link in the string S, as if it was in Org-mode."
6633 (interactive "sLink: \nP")
6634 (with-temp-buffer
6635 (let ((org-inhibit-startup t))
6636 (org-mode)
6637 (insert s)
6638 (goto-char (point-min))
6639 (org-open-at-point arg))))
6641 (defun org-open-at-point (&optional in-emacs)
6642 "Open link at or after point.
6643 If there is no link at point, this function will search forward up to
6644 the end of the current subtree.
6645 Normally, files will be opened by an appropriate application. If the
6646 optional argument IN-EMACS is non-nil, Emacs will visit the file.
6647 With a double prefix argument, try to open outside of Emacs, in the
6648 application the system uses for this file type."
6649 (interactive "P")
6650 (org-load-modules-maybe)
6651 (move-marker org-open-link-marker (point))
6652 (setq org-window-config-before-follow-link (current-window-configuration))
6653 (org-remove-occur-highlights nil nil t)
6654 (if (org-at-timestamp-p t)
6655 (org-follow-timestamp-link)
6656 (let (type path link line search (pos (point)))
6657 (catch 'match
6658 (save-excursion
6659 (skip-chars-forward "^]\n\r")
6660 (when (org-in-regexp org-bracket-link-regexp)
6661 (setq link (org-extract-attributes
6662 (org-link-unescape (org-match-string-no-properties 1))))
6663 (while (string-match " *\n *" link)
6664 (setq link (replace-match " " t t link)))
6665 (setq link (org-link-expand-abbrev link))
6666 (cond
6667 ((or (file-name-absolute-p link)
6668 (string-match "^\\.\\.?/" link))
6669 (setq type "file" path link))
6670 ((string-match org-link-re-with-space2 link)
6671 (setq type (match-string 1 link) path (match-string 2 link)))
6672 (t (setq type "thisfile" path link)))
6673 (throw 'match t)))
6675 (when (get-text-property (point) 'org-linked-text)
6676 (setq type "thisfile"
6677 pos (if (get-text-property (1+ (point)) 'org-linked-text)
6678 (1+ (point)) (point))
6679 path (buffer-substring
6680 (previous-single-property-change pos 'org-linked-text)
6681 (next-single-property-change pos 'org-linked-text)))
6682 (throw 'match t))
6684 (save-excursion
6685 (when (or (org-in-regexp org-angle-link-re)
6686 (org-in-regexp org-plain-link-re))
6687 (setq type (match-string 1) path (match-string 2))
6688 (throw 'match t)))
6689 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
6690 (setq type "tree-match"
6691 path (match-string 1))
6692 (throw 'match t))
6693 (save-excursion
6694 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
6695 (setq type "tags"
6696 path (match-string 1))
6697 (while (string-match ":" path)
6698 (setq path (replace-match "+" t t path)))
6699 (throw 'match t))))
6700 (unless path
6701 (error "No link found"))
6702 ;; Remove any trailing spaces in path
6703 (if (string-match " +\\'" path)
6704 (setq path (replace-match "" t t path)))
6706 (cond
6708 ((assoc type org-link-protocols)
6709 (funcall (nth 1 (assoc type org-link-protocols)) path))
6711 ((equal type "mailto")
6712 (let ((cmd (car org-link-mailto-program))
6713 (args (cdr org-link-mailto-program)) args1
6714 (address path) (subject "") a)
6715 (if (string-match "\\(.*\\)::\\(.*\\)" path)
6716 (setq address (match-string 1 path)
6717 subject (org-link-escape (match-string 2 path))))
6718 (while args
6719 (cond
6720 ((not (stringp (car args))) (push (pop args) args1))
6721 (t (setq a (pop args))
6722 (if (string-match "%a" a)
6723 (setq a (replace-match address t t a)))
6724 (if (string-match "%s" a)
6725 (setq a (replace-match subject t t a)))
6726 (push a args1))))
6727 (apply cmd (nreverse args1))))
6729 ((member type '("http" "https" "ftp" "news"))
6730 (browse-url (concat type ":" (org-link-escape
6731 path org-link-escape-chars-browser))))
6733 ((member type '("message"))
6734 (browse-url (concat type ":" path)))
6736 ((string= type "tags")
6737 (org-tags-view in-emacs path))
6738 ((string= type "thisfile")
6739 (if in-emacs
6740 (switch-to-buffer-other-window
6741 (org-get-buffer-for-internal-link (current-buffer)))
6742 (org-mark-ring-push))
6743 (let ((cmd `(org-link-search
6744 ,path
6745 ,(cond ((equal in-emacs '(4)) 'occur)
6746 ((equal in-emacs '(16)) 'org-occur)
6747 (t nil))
6748 ,pos)))
6749 (condition-case nil (eval cmd)
6750 (error (progn (widen) (eval cmd))))))
6752 ((string= type "tree-match")
6753 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
6755 ((string= type "file")
6756 (if (string-match "::\\([0-9]+\\)\\'" path)
6757 (setq line (string-to-number (match-string 1 path))
6758 path (substring path 0 (match-beginning 0)))
6759 (if (string-match "::\\(.+\\)\\'" path)
6760 (setq search (match-string 1 path)
6761 path (substring path 0 (match-beginning 0)))))
6762 (if (string-match "[*?{]" (file-name-nondirectory path))
6763 (dired path)
6764 (org-open-file path in-emacs line search)))
6766 ((string= type "news")
6767 (require 'org-gnus)
6768 (org-gnus-follow-link path))
6770 ((string= type "shell")
6771 (let ((cmd path))
6772 (if (or (not org-confirm-shell-link-function)
6773 (funcall org-confirm-shell-link-function
6774 (format "Execute \"%s\" in shell? "
6775 (org-add-props cmd nil
6776 'face 'org-warning))))
6777 (progn
6778 (message "Executing %s" cmd)
6779 (shell-command cmd))
6780 (error "Abort"))))
6782 ((string= type "elisp")
6783 (let ((cmd path))
6784 (if (or (not org-confirm-elisp-link-function)
6785 (funcall org-confirm-elisp-link-function
6786 (format "Execute \"%s\" as elisp? "
6787 (org-add-props cmd nil
6788 'face 'org-warning))))
6789 (message "%s => %s" cmd (eval (read cmd)))
6790 (error "Abort"))))
6793 (browse-url-at-point)))))
6794 (move-marker org-open-link-marker nil)
6795 (run-hook-with-args 'org-follow-link-hook))
6797 ;;;; Time estimates
6799 (defun org-get-effort (&optional pom)
6800 "Get the effort estimate for the current entry."
6801 (org-entry-get pom org-effort-property))
6803 ;;; File search
6805 (defvar org-create-file-search-functions nil
6806 "List of functions to construct the right search string for a file link.
6807 These functions are called in turn with point at the location to
6808 which the link should point.
6810 A function in the hook should first test if it would like to
6811 handle this file type, for example by checking the major-mode or
6812 the file extension. If it decides not to handle this file, it
6813 should just return nil to give other functions a chance. If it
6814 does handle the file, it must return the search string to be used
6815 when following the link. The search string will be part of the
6816 file link, given after a double colon, and `org-open-at-point'
6817 will automatically search for it. If special measures must be
6818 taken to make the search successful, another function should be
6819 added to the companion hook `org-execute-file-search-functions',
6820 which see.
6822 A function in this hook may also use `setq' to set the variable
6823 `description' to provide a suggestion for the descriptive text to
6824 be used for this link when it gets inserted into an Org-mode
6825 buffer with \\[org-insert-link].")
6827 (defvar org-execute-file-search-functions nil
6828 "List of functions to execute a file search triggered by a link.
6830 Functions added to this hook must accept a single argument, the
6831 search string that was part of the file link, the part after the
6832 double colon. The function must first check if it would like to
6833 handle this search, for example by checking the major-mode or the
6834 file extension. If it decides not to handle this search, it
6835 should just return nil to give other functions a chance. If it
6836 does handle the search, it must return a non-nil value to keep
6837 other functions from trying.
6839 Each function can access the current prefix argument through the
6840 variable `current-prefix-argument'. Note that a single prefix is
6841 used to force opening a link in Emacs, so it may be good to only
6842 use a numeric or double prefix to guide the search function.
6844 In case this is needed, a function in this hook can also restore
6845 the window configuration before `org-open-at-point' was called using:
6847 (set-window-configuration org-window-config-before-follow-link)")
6849 (defun org-link-search (s &optional type avoid-pos)
6850 "Search for a link search option.
6851 If S is surrounded by forward slashes, it is interpreted as a
6852 regular expression. In org-mode files, this will create an `org-occur'
6853 sparse tree. In ordinary files, `occur' will be used to list matches.
6854 If the current buffer is in `dired-mode', grep will be used to search
6855 in all files. If AVOID-POS is given, ignore matches near that position."
6856 (let ((case-fold-search t)
6857 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
6858 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
6859 (append '(("") (" ") ("\t") ("\n"))
6860 org-emphasis-alist)
6861 "\\|") "\\)"))
6862 (pos (point))
6863 (pre nil) (post nil)
6864 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
6865 (cond
6866 ;; First check if there are any special
6867 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
6868 ;; Now try the builtin stuff
6869 ((save-excursion
6870 (goto-char (point-min))
6871 (and
6872 (re-search-forward
6873 (concat "<<" (regexp-quote s0) ">>") nil t)
6874 (setq type 'dedicated
6875 pos (match-beginning 0))))
6876 ;; There is an exact target for this
6877 (goto-char pos))
6878 ((string-match "^/\\(.*\\)/$" s)
6879 ;; A regular expression
6880 (cond
6881 ((org-mode-p)
6882 (org-occur (match-string 1 s)))
6883 ;;((eq major-mode 'dired-mode)
6884 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
6885 (t (org-do-occur (match-string 1 s)))))
6887 ;; A normal search strings
6888 (when (equal (string-to-char s) ?*)
6889 ;; Anchor on headlines, post may include tags.
6890 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
6891 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
6892 s (substring s 1)))
6893 (remove-text-properties
6894 0 (length s)
6895 '(face nil mouse-face nil keymap nil fontified nil) s)
6896 ;; Make a series of regular expressions to find a match
6897 (setq words (org-split-string s "[ \n\r\t]+")
6899 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
6900 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
6901 "\\)" markers)
6902 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
6903 re2a (concat "[ \t\r\n]" re2a_)
6904 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
6905 re4 (concat "[^a-zA-Z_]" re4_)
6907 re1 (concat pre re2 post)
6908 re3 (concat pre (if pre re4_ re4) post)
6909 re5 (concat pre ".*" re4)
6910 re2 (concat pre re2)
6911 re2a (concat pre (if pre re2a_ re2a))
6912 re4 (concat pre (if pre re4_ re4))
6913 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
6914 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
6915 re5 "\\)"
6917 (cond
6918 ((eq type 'org-occur) (org-occur reall))
6919 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
6920 (t (goto-char (point-min))
6921 (setq type 'fuzzy)
6922 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
6923 (org-search-not-self 1 re1 nil t)
6924 (org-search-not-self 1 re2 nil t)
6925 (org-search-not-self 1 re2a nil t)
6926 (org-search-not-self 1 re3 nil t)
6927 (org-search-not-self 1 re4 nil t)
6928 (org-search-not-self 1 re5 nil t)
6930 (goto-char (match-beginning 1))
6931 (goto-char pos)
6932 (error "No match")))))
6934 ;; Normal string-search
6935 (goto-char (point-min))
6936 (if (search-forward s nil t)
6937 (goto-char (match-beginning 0))
6938 (error "No match"))))
6939 (and (org-mode-p) (org-show-context 'link-search))
6940 type))
6942 (defun org-search-not-self (group &rest args)
6943 "Execute `re-search-forward', but only accept matches that do not
6944 enclose the position of `org-open-link-marker'."
6945 (let ((m org-open-link-marker))
6946 (catch 'exit
6947 (while (apply 're-search-forward args)
6948 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
6949 (goto-char (match-end group))
6950 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
6951 (> (match-beginning 0) (marker-position m))
6952 (< (match-end 0) (marker-position m)))
6953 (save-match-data
6954 (or (not (org-in-regexp
6955 org-bracket-link-analytic-regexp 1))
6956 (not (match-end 4)) ; no description
6957 (and (<= (match-beginning 4) (point))
6958 (>= (match-end 4) (point))))))
6959 (throw 'exit (point))))))))
6961 (defun org-get-buffer-for-internal-link (buffer)
6962 "Return a buffer to be used for displaying the link target of internal links."
6963 (cond
6964 ((not org-display-internal-link-with-indirect-buffer)
6965 buffer)
6966 ((string-match "(Clone)$" (buffer-name buffer))
6967 (message "Buffer is already a clone, not making another one")
6968 ;; we also do not modify visibility in this case
6969 buffer)
6970 (t ; make a new indirect buffer for displaying the link
6971 (let* ((bn (buffer-name buffer))
6972 (ibn (concat bn "(Clone)"))
6973 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
6974 (with-current-buffer ib (org-overview))
6975 ib))))
6977 (defun org-do-occur (regexp &optional cleanup)
6978 "Call the Emacs command `occur'.
6979 If CLEANUP is non-nil, remove the printout of the regular expression
6980 in the *Occur* buffer. This is useful if the regex is long and not useful
6981 to read."
6982 (occur regexp)
6983 (when cleanup
6984 (let ((cwin (selected-window)) win beg end)
6985 (when (setq win (get-buffer-window "*Occur*"))
6986 (select-window win))
6987 (goto-char (point-min))
6988 (when (re-search-forward "match[a-z]+" nil t)
6989 (setq beg (match-end 0))
6990 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
6991 (setq end (1- (match-beginning 0)))))
6992 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
6993 (goto-char (point-min))
6994 (select-window cwin))))
6996 ;;; The mark ring for links jumps
6998 (defvar org-mark-ring nil
6999 "Mark ring for positions before jumps in Org-mode.")
7000 (defvar org-mark-ring-last-goto nil
7001 "Last position in the mark ring used to go back.")
7002 ;; Fill and close the ring
7003 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7004 (loop for i from 1 to org-mark-ring-length do
7005 (push (make-marker) org-mark-ring))
7006 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7007 org-mark-ring)
7009 (defun org-mark-ring-push (&optional pos buffer)
7010 "Put the current position or POS into the mark ring and rotate it."
7011 (interactive)
7012 (setq pos (or pos (point)))
7013 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7014 (move-marker (car org-mark-ring)
7015 (or pos (point))
7016 (or buffer (current-buffer)))
7017 (message "%s"
7018 (substitute-command-keys
7019 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7021 (defun org-mark-ring-goto (&optional n)
7022 "Jump to the previous position in the mark ring.
7023 With prefix arg N, jump back that many stored positions. When
7024 called several times in succession, walk through the entire ring.
7025 Org-mode commands jumping to a different position in the current file,
7026 or to another Org-mode file, automatically push the old position
7027 onto the ring."
7028 (interactive "p")
7029 (let (p m)
7030 (if (eq last-command this-command)
7031 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7032 (setq p org-mark-ring))
7033 (setq org-mark-ring-last-goto p)
7034 (setq m (car p))
7035 (switch-to-buffer (marker-buffer m))
7036 (goto-char m)
7037 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
7039 (defun org-remove-angle-brackets (s)
7040 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7041 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7043 (defun org-add-angle-brackets (s)
7044 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7045 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7047 (defun org-remove-double-quotes (s)
7048 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
7049 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
7052 ;;; Following specific links
7054 (defun org-follow-timestamp-link ()
7055 (cond
7056 ((org-at-date-range-p t)
7057 (let ((org-agenda-start-on-weekday)
7058 (t1 (match-string 1))
7059 (t2 (match-string 2)))
7060 (setq t1 (time-to-days (org-time-string-to-time t1))
7061 t2 (time-to-days (org-time-string-to-time t2)))
7062 (org-agenda-list nil t1 (1+ (- t2 t1)))))
7063 ((org-at-timestamp-p t)
7064 (org-agenda-list nil (time-to-days (org-time-string-to-time
7065 (substring (match-string 1) 0 10)))
7067 (t (error "This should not happen"))))
7070 ;;; Following file links
7071 (defvar org-wait nil)
7072 (defun org-open-file (path &optional in-emacs line search)
7073 "Open the file at PATH.
7074 First, this expands any special file name abbreviations. Then the
7075 configuration variable `org-file-apps' is checked if it contains an
7076 entry for this file type, and if yes, the corresponding command is launched.
7078 If no application is found, Emacs simply visits the file.
7080 With optional prefix argument IN-EMACS, Emacs will visit the file.
7081 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
7082 and o use an external application to visit the file.
7084 Optional LINE specifies a line to go to, optional SEARCH a string to
7085 search for. If LINE or SEARCH is given, the file will always be
7086 opened in Emacs.
7087 If the file does not exist, an error is thrown."
7088 (setq in-emacs (or in-emacs line search))
7089 (let* ((file (if (equal path "")
7090 buffer-file-name
7091 (substitute-in-file-name (expand-file-name path))))
7092 (apps (append org-file-apps (org-default-apps)))
7093 (remp (and (assq 'remote apps) (org-file-remote-p file)))
7094 (dirp (if remp nil (file-directory-p file)))
7095 (file (if (and dirp org-open-directory-means-index-dot-org)
7096 (concat (file-name-as-directory file) "index.org")
7097 file))
7098 (a-m-a-p (assq 'auto-mode apps))
7099 (dfile (downcase file))
7100 (old-buffer (current-buffer))
7101 (old-pos (point))
7102 (old-mode major-mode)
7103 ext cmd)
7104 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7105 (setq ext (match-string 1 dfile))
7106 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7107 (setq ext (match-string 1 dfile))))
7108 (cond
7109 ((equal in-emacs '(16))
7110 (setq cmd (cdr (assoc 'system apps))))
7111 (in-emacs (setq cmd 'emacs))
7113 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
7114 (and dirp (cdr (assoc 'directory apps)))
7115 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
7116 'string-match)
7117 (cdr (assoc ext apps))
7118 (cdr (assoc t apps))))))
7119 (when (eq cmd 'system)
7120 (setq cmd (cdr (assoc 'system apps))))
7121 (when (eq cmd 'default)
7122 (setq cmd (cdr (assoc t apps))))
7123 (when (eq cmd 'mailcap)
7124 (require 'mailcap)
7125 (mailcap-parse-mailcaps)
7126 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7127 (command (mailcap-mime-info mime-type)))
7128 (if (stringp command)
7129 (setq cmd command)
7130 (setq cmd 'emacs))))
7131 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
7132 (not (file-exists-p file))
7133 (not org-open-non-existing-files))
7134 (error "No such file: %s" file))
7135 (cond
7136 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7137 ;; Remove quotes around the file name - we'll use shell-quote-argument.
7138 (while (string-match "['\"]%s['\"]" cmd)
7139 (setq cmd (replace-match "%s" t t cmd)))
7140 (while (string-match "%s" cmd)
7141 (setq cmd (replace-match
7142 (save-match-data
7143 (shell-quote-argument
7144 (convert-standard-filename file)))
7145 t t cmd)))
7146 (save-window-excursion
7147 (start-process-shell-command cmd nil cmd)
7148 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
7150 ((or (stringp cmd)
7151 (eq cmd 'emacs))
7152 (funcall (cdr (assq 'file org-link-frame-setup)) file)
7153 (widen)
7154 (if line (goto-line line)
7155 (if search (org-link-search search))))
7156 ((consp cmd)
7157 (let ((file (convert-standard-filename file)))
7158 (eval cmd)))
7159 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7160 (and (org-mode-p) (eq old-mode 'org-mode)
7161 (or (not (equal old-buffer (current-buffer)))
7162 (not (equal old-pos (point))))
7163 (org-mark-ring-push old-pos old-buffer))))
7165 (defun org-default-apps ()
7166 "Return the default applications for this operating system."
7167 (cond
7168 ((eq system-type 'darwin)
7169 org-file-apps-defaults-macosx)
7170 ((eq system-type 'windows-nt)
7171 org-file-apps-defaults-windowsnt)
7172 (t org-file-apps-defaults-gnu)))
7174 (defun org-apps-regexp-alist (list &optional add-auto-mode)
7175 "Convert extensions to regular expressions in the cars of LIST.
7176 Also, weed out any non-string entries, because the return value is used
7177 only for regexp matching.
7178 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
7179 point to the symbol `emacs', indicating that the file should
7180 be opened in Emacs."
7181 (append
7182 (delq nil
7183 (mapcar (lambda (x)
7184 (if (not (stringp (car x)))
7186 (if (string-match "\\W" (car x))
7188 (cons (concat "\\." (car x) "\\'") (cdr x)))))
7189 list))
7190 (if add-auto-mode
7191 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
7193 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
7194 (defun org-file-remote-p (file)
7195 "Test whether FILE specifies a location on a remote system.
7196 Return non-nil if the location is indeed remote.
7198 For example, the filename \"/user@host:/foo\" specifies a location
7199 on the system \"/user@host:\"."
7200 (cond ((fboundp 'file-remote-p)
7201 (file-remote-p file))
7202 ((fboundp 'tramp-handle-file-remote-p)
7203 (tramp-handle-file-remote-p file))
7204 ((and (boundp 'ange-ftp-name-format)
7205 (string-match (car ange-ftp-name-format) file))
7207 (t nil)))
7210 ;;;; Refiling
7212 (defun org-get-org-file ()
7213 "Read a filename, with default directory `org-directory'."
7214 (let ((default (or org-default-notes-file remember-data-file)))
7215 (read-file-name (format "File name [%s]: " default)
7216 (file-name-as-directory org-directory)
7217 default)))
7219 (defun org-notes-order-reversed-p ()
7220 "Check if the current file should receive notes in reversed order."
7221 (cond
7222 ((not org-reverse-note-order) nil)
7223 ((eq t org-reverse-note-order) t)
7224 ((not (listp org-reverse-note-order)) nil)
7225 (t (catch 'exit
7226 (let ((all org-reverse-note-order)
7227 entry)
7228 (while (setq entry (pop all))
7229 (if (string-match (car entry) buffer-file-name)
7230 (throw 'exit (cdr entry))))
7231 nil)))))
7233 (defvar org-refile-target-table nil
7234 "The list of refile targets, created by `org-refile'.")
7236 (defvar org-agenda-new-buffers nil
7237 "Buffers created to visit agenda files.")
7239 (defun org-get-refile-targets (&optional default-buffer)
7240 "Produce a table with refile targets."
7241 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
7242 targets txt re files f desc descre)
7243 (with-current-buffer (or default-buffer (current-buffer))
7244 (while (setq entry (pop entries))
7245 (setq files (car entry) desc (cdr entry))
7246 (cond
7247 ((null files) (setq files (list (current-buffer))))
7248 ((eq files 'org-agenda-files)
7249 (setq files (org-agenda-files 'unrestricted)))
7250 ((and (symbolp files) (fboundp files))
7251 (setq files (funcall files)))
7252 ((and (symbolp files) (boundp files))
7253 (setq files (symbol-value files))))
7254 (if (stringp files) (setq files (list files)))
7255 (cond
7256 ((eq (car desc) :tag)
7257 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
7258 ((eq (car desc) :todo)
7259 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
7260 ((eq (car desc) :regexp)
7261 (setq descre (cdr desc)))
7262 ((eq (car desc) :level)
7263 (setq descre (concat "^\\*\\{" (number-to-string
7264 (if org-odd-levels-only
7265 (1- (* 2 (cdr desc)))
7266 (cdr desc)))
7267 "\\}[ \t]")))
7268 ((eq (car desc) :maxlevel)
7269 (setq descre (concat "^\\*\\{1," (number-to-string
7270 (if org-odd-levels-only
7271 (1- (* 2 (cdr desc)))
7272 (cdr desc)))
7273 "\\}[ \t]")))
7274 (t (error "Bad refiling target description %s" desc)))
7275 (while (setq f (pop files))
7276 (save-excursion
7277 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
7278 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
7279 (save-excursion
7280 (save-restriction
7281 (widen)
7282 (goto-char (point-min))
7283 (while (re-search-forward descre nil t)
7284 (goto-char (point-at-bol))
7285 (when (looking-at org-complex-heading-regexp)
7286 (setq txt (org-link-display-format (match-string 4))
7287 re (concat "^" (regexp-quote
7288 (buffer-substring (match-beginning 1)
7289 (match-end 4)))))
7290 (if (match-end 5) (setq re (concat re "[ \t]+"
7291 (regexp-quote
7292 (match-string 5)))))
7293 (setq re (concat re "[ \t]*$"))
7294 (when org-refile-use-outline-path
7295 (setq txt (mapconcat 'org-protect-slash
7296 (append
7297 (if (eq org-refile-use-outline-path 'file)
7298 (list (file-name-nondirectory
7299 (buffer-file-name (buffer-base-buffer))))
7300 (if (eq org-refile-use-outline-path 'full-file-path)
7301 (list (buffer-file-name (buffer-base-buffer)))))
7302 (org-get-outline-path)
7303 (list txt))
7304 "/")))
7305 (push (list txt f re (point)) targets))
7306 (goto-char (point-at-eol))))))))
7307 (nreverse targets))))
7309 (defun org-protect-slash (s)
7310 (while (string-match "/" s)
7311 (setq s (replace-match "\\" t t s)))
7314 (defun org-get-outline-path ()
7315 "Return the outline path to the current entry, as a list."
7316 (let (rtn)
7317 (save-excursion
7318 (while (org-up-heading-safe)
7319 (when (looking-at org-complex-heading-regexp)
7320 (push (org-match-string-no-properties 4) rtn)))
7321 rtn)))
7323 (defvar org-refile-history nil
7324 "History for refiling operations.")
7326 (defun org-refile (&optional goto default-buffer)
7327 "Move the entry at point to another heading.
7328 The list of target headings is compiled using the information in
7329 `org-refile-targets', which see. This list is created before each use
7330 and will therefore always be up-to-date.
7332 At the target location, the entry is filed as a subitem of the target heading.
7333 Depending on `org-reverse-note-order', the new subitem will either be the
7334 first or the last subitem.
7336 With prefix arg GOTO, the command will only visit the target location,
7337 not actually move anything.
7338 With a double prefix `C-u C-u', go to the location where the last refiling
7339 operation has put the subtree."
7340 (interactive "P")
7341 (let* ((cbuf (current-buffer))
7342 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7343 pos it nbuf file re level reversed)
7344 (if (equal goto '(16))
7345 (org-refile-goto-last-stored)
7346 (when (setq it (org-refile-get-location
7347 (if goto "Goto: " "Refile to: ") default-buffer))
7348 (setq file (nth 1 it)
7349 re (nth 2 it)
7350 pos (nth 3 it))
7351 (setq nbuf (or (find-buffer-visiting file)
7352 (find-file-noselect file)))
7353 (if goto
7354 (progn
7355 (switch-to-buffer nbuf)
7356 (goto-char pos)
7357 (org-show-context 'org-goto))
7358 (org-copy-subtree 1 nil t)
7359 (save-excursion
7360 (set-buffer (setq nbuf (or (find-buffer-visiting file)
7361 (find-file-noselect file))))
7362 (setq reversed (org-notes-order-reversed-p))
7363 (save-excursion
7364 (save-restriction
7365 (widen)
7366 (goto-char pos)
7367 (looking-at outline-regexp)
7368 (setq level (org-get-valid-level (funcall outline-level) 1))
7369 (goto-char
7370 (if reversed
7371 (or (outline-next-heading) (point-max))
7372 (or (save-excursion (outline-get-next-sibling))
7373 (org-end-of-subtree t t)
7374 (point-max))))
7375 (if (not (bolp)) (newline))
7376 (bookmark-set "org-refile-last-stored")
7377 (org-paste-subtree level))))
7378 (org-cut-subtree)
7379 (setq org-markers-to-move nil)
7380 (message "Entry refiled to \"%s\"" (car it)))))))
7382 (defun org-refile-goto-last-stored ()
7383 "Go to the location where the last refile was stored."
7384 (interactive)
7385 (bookmark-jump "org-refile-last-stored")
7386 (message "This is the location of the last refile"))
7388 (defun org-refile-get-location (&optional prompt default-buffer)
7389 "Prompt the user for a refile location, using PROMPT."
7390 (let ((org-refile-targets org-refile-targets)
7391 (org-refile-use-outline-path org-refile-use-outline-path))
7392 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
7393 (unless org-refile-target-table
7394 (error "No refile targets"))
7395 (let* ((cbuf (current-buffer))
7396 (cfunc (if org-refile-use-outline-path
7397 'org-olpath-completing-read
7398 'completing-read))
7399 (extra (if org-refile-use-outline-path "/" ""))
7400 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7401 (fname (and filename (file-truename filename)))
7402 (tbl (mapcar
7403 (lambda (x)
7404 (if (not (equal fname (file-truename (nth 1 x))))
7405 (cons (concat (car x) extra " ("
7406 (file-name-nondirectory (nth 1 x)) ")")
7407 (cdr x))
7408 (cons (concat (car x) extra) (cdr x))))
7409 org-refile-target-table))
7410 (completion-ignore-case t))
7411 (assoc (funcall cfunc prompt tbl nil t nil 'org-refile-history)
7412 tbl)))
7414 (defun org-olpath-completing-read (prompt collection &rest args)
7415 "Read an outline path like a file name."
7416 (let ((thetable collection))
7417 (apply
7418 'completing-read prompt
7419 (lambda (string predicate &optional flag)
7420 (let (rtn r s f (l (length string)))
7421 (cond
7422 ((eq flag nil)
7423 ;; try completion
7424 (try-completion string thetable))
7425 ((eq flag t)
7426 ;; all-completions
7427 (setq rtn (all-completions string thetable predicate))
7428 (mapcar
7429 (lambda (x)
7430 (setq r (substring x l))
7431 (if (string-match " ([^)]*)$" x)
7432 (setq f (match-string 0 x))
7433 (setq f ""))
7434 (if (string-match "/" r)
7435 (concat string (substring r 0 (match-end 0)) f)
7437 rtn))
7438 ((eq flag 'lambda)
7439 ;; exact match?
7440 (assoc string thetable)))
7442 args)))
7444 ;;;; Dynamic blocks
7446 (defun org-find-dblock (name)
7447 "Find the first dynamic block with name NAME in the buffer.
7448 If not found, stay at current position and return nil."
7449 (let (pos)
7450 (save-excursion
7451 (goto-char (point-min))
7452 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
7453 nil t)
7454 (match-beginning 0))))
7455 (if pos (goto-char pos))
7456 pos))
7458 (defconst org-dblock-start-re
7459 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
7460 "Matches the startline of a dynamic block, with parameters.")
7462 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
7463 "Matches the end of a dyhamic block.")
7465 (defun org-create-dblock (plist)
7466 "Create a dynamic block section, with parameters taken from PLIST.
7467 PLIST must containe a :name entry which is used as name of the block."
7468 (unless (bolp) (newline))
7469 (let ((name (plist-get plist :name)))
7470 (insert "#+BEGIN: " name)
7471 (while plist
7472 (if (eq (car plist) :name)
7473 (setq plist (cddr plist))
7474 (insert " " (prin1-to-string (pop plist)))))
7475 (insert "\n\n#+END:\n")
7476 (beginning-of-line -2)))
7478 (defun org-prepare-dblock ()
7479 "Prepare dynamic block for refresh.
7480 This empties the block, puts the cursor at the insert position and returns
7481 the property list including an extra property :name with the block name."
7482 (unless (looking-at org-dblock-start-re)
7483 (error "Not at a dynamic block"))
7484 (let* ((begdel (1+ (match-end 0)))
7485 (name (org-no-properties (match-string 1)))
7486 (params (append (list :name name)
7487 (read (concat "(" (match-string 3) ")")))))
7488 (unless (re-search-forward org-dblock-end-re nil t)
7489 (error "Dynamic block not terminated"))
7490 (setq params
7491 (append params
7492 (list :content (buffer-substring
7493 begdel (match-beginning 0)))))
7494 (delete-region begdel (match-beginning 0))
7495 (goto-char begdel)
7496 (open-line 1)
7497 params))
7499 (defun org-map-dblocks (&optional command)
7500 "Apply COMMAND to all dynamic blocks in the current buffer.
7501 If COMMAND is not given, use `org-update-dblock'."
7502 (let ((cmd (or command 'org-update-dblock))
7503 pos)
7504 (save-excursion
7505 (goto-char (point-min))
7506 (while (re-search-forward org-dblock-start-re nil t)
7507 (goto-char (setq pos (match-beginning 0)))
7508 (condition-case nil
7509 (funcall cmd)
7510 (error (message "Error during update of dynamic block")))
7511 (goto-char pos)
7512 (unless (re-search-forward org-dblock-end-re nil t)
7513 (error "Dynamic block not terminated"))))))
7515 (defun org-dblock-update (&optional arg)
7516 "User command for updating dynamic blocks.
7517 Update the dynamic block at point. With prefix ARG, update all dynamic
7518 blocks in the buffer."
7519 (interactive "P")
7520 (if arg
7521 (org-update-all-dblocks)
7522 (or (looking-at org-dblock-start-re)
7523 (org-beginning-of-dblock))
7524 (org-update-dblock)))
7526 (defun org-update-dblock ()
7527 "Update the dynamic block at point
7528 This means to empty the block, parse for parameters and then call
7529 the correct writing function."
7530 (save-window-excursion
7531 (let* ((pos (point))
7532 (line (org-current-line))
7533 (params (org-prepare-dblock))
7534 (name (plist-get params :name))
7535 (cmd (intern (concat "org-dblock-write:" name))))
7536 (message "Updating dynamic block `%s' at line %d..." name line)
7537 (funcall cmd params)
7538 (message "Updating dynamic block `%s' at line %d...done" name line)
7539 (goto-char pos))))
7541 (defun org-beginning-of-dblock ()
7542 "Find the beginning of the dynamic block at point.
7543 Error if there is no scuh block at point."
7544 (let ((pos (point))
7545 beg)
7546 (end-of-line 1)
7547 (if (and (re-search-backward org-dblock-start-re nil t)
7548 (setq beg (match-beginning 0))
7549 (re-search-forward org-dblock-end-re nil t)
7550 (> (match-end 0) pos))
7551 (goto-char beg)
7552 (goto-char pos)
7553 (error "Not in a dynamic block"))))
7555 (defun org-update-all-dblocks ()
7556 "Update all dynamic blocks in the buffer.
7557 This function can be used in a hook."
7558 (when (org-mode-p)
7559 (org-map-dblocks 'org-update-dblock)))
7562 ;;;; Completion
7564 (defconst org-additional-option-like-keywords
7565 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
7566 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
7567 "BEGIN_EXAMPLE" "END_EXAMPLE"
7568 "BEGIN_QUOTE" "END_QUOTE"
7569 "BEGIN_VERSE" "END_VERSE"
7570 "BEGIN_SRC" "END_SRC"))
7572 (defcustom org-structure-template-alist
7574 ("s" "#+begin_src ?\n\n#+end_src"
7575 "<src lang=\"?\">\n\n</src>")
7576 ("e" "#+begin_example\n?\n#+end_example"
7577 "<example>\n?\n</example>")
7578 ("q" "#+begin_quote\n?\n#+end_quote"
7579 "<quote>\n?\n</quote>")
7580 ("v" "#+begin_verse\n?\n#+end_verse"
7581 "<verse>\n?\n/verse>")
7582 ("l" "#+begin_latex\n?\n#+end_latex"
7583 "<literal style=\"latex\">\n?\n</literal>")
7584 ("L" "#+latex: "
7585 "<literal style=\"latex\">?</literal>")
7586 ("h" "#+begin_html\n?\n#+end_html"
7587 "<literal style=\"html\">\n?\n</literal>")
7588 ("H" "#+html: "
7589 "<literal style=\"html\">?</literal>")
7590 ("a" "#+begin_ascii\n?\n#+end_ascii")
7591 ("A" "#+ascii: ")
7592 ("i" "#+include %file ?"
7593 "<include file=%file markup=\"?\">")
7595 "Structure completion elements.
7596 This is a list of abbreviation keys and values. The value gets inserted
7597 it you type @samp{.} followed by the key and then the completion key,
7598 usually `M-TAB'. %file will be replaced by a file name after prompting
7599 for the file uning completion.
7600 There are two templates for each key, the first uses the original Org syntax,
7601 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
7602 the default when the /org-mtags.el/ module has been loaded. See also the
7603 variable `org-mtags-prefere-muse-templates'.
7604 This is an experimental feature, it is undecided if it is going to stay in."
7605 :group 'org-completion
7606 :type '(repeat
7607 (string :tag "Key")
7608 (string :tag "Template")
7609 (string :tag "Muse Template")))
7611 (defun org-try-structure-completion ()
7612 "Try to complete a structure template before point.
7613 This looks for strings like \"<e\" on an otherwise empty line and
7614 expands them."
7615 (let ((l (buffer-substring (point-at-bol) (point)))
7617 (when (and (looking-at "[ \t]*$")
7618 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
7619 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
7620 (org-complete-expand-structure-template (+ -1 (point-at-bol)
7621 (match-beginning 1)) a)
7622 t)))
7624 (defun org-complete-expand-structure-template (start cell)
7625 "Expand a structure template."
7626 (let* ((musep (org-bound-and-true-p org-mtags-prefere-muse-templates))
7627 (rpl (nth (if musep 2 1) cell)))
7628 (delete-region start (point))
7629 (when (string-match "\\`#\\+" rpl)
7630 (cond
7631 ((bolp))
7632 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
7633 (delete-region (point-at-bol) (point)))
7634 (t (newline))))
7635 (setq start (point))
7636 (if (string-match "%file" rpl)
7637 (setq rpl (replace-match
7638 (concat
7639 "\""
7640 (save-match-data
7641 (abbreviate-file-name (read-file-name "Include file: ")))
7642 "\"")
7643 t t rpl)))
7644 (insert rpl)
7645 (if (re-search-backward "\\?" start t) (delete-char 1))))
7648 (defun org-complete (&optional arg)
7649 "Perform completion on word at point.
7650 At the beginning of a headline, this completes TODO keywords as given in
7651 `org-todo-keywords'.
7652 If the current word is preceded by a backslash, completes the TeX symbols
7653 that are supported for HTML support.
7654 If the current word is preceded by \"#+\", completes special words for
7655 setting file options.
7656 In the line after \"#+STARTUP:, complete valid keywords.\"
7657 At all other locations, this simply calls the value of
7658 `org-completion-fallback-command'."
7659 (interactive "P")
7660 (org-without-partial-completion
7661 (catch 'exit
7662 (let* ((a nil)
7663 (end (point))
7664 (beg1 (save-excursion
7665 (skip-chars-backward (org-re "[:alnum:]_@"))
7666 (point)))
7667 (beg (save-excursion
7668 (skip-chars-backward "a-zA-Z0-9_:$")
7669 (point)))
7670 (confirm (lambda (x) (stringp (car x))))
7671 (searchhead (equal (char-before beg) ?*))
7672 (struct
7673 (when (and (member (char-before beg1) '(?. ?<))
7674 (setq a (assoc (buffer-substring beg1 (point))
7675 org-structure-template-alist)))
7676 (org-complete-expand-structure-template (1- beg1) a)
7677 (throw 'exit t)))
7678 (tag (and (equal (char-before beg1) ?:)
7679 (equal (char-after (point-at-bol)) ?*)))
7680 (prop (and (equal (char-before beg1) ?:)
7681 (not (equal (char-after (point-at-bol)) ?*))))
7682 (texp (equal (char-before beg) ?\\))
7683 (link (equal (char-before beg) ?\[))
7684 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
7685 beg)
7686 "#+"))
7687 (startup (string-match "^#\\+STARTUP:.*"
7688 (buffer-substring (point-at-bol) (point))))
7689 (completion-ignore-case opt)
7690 (type nil)
7691 (tbl nil)
7692 (table (cond
7693 (opt
7694 (setq type :opt)
7695 (require 'org-exp)
7696 (append
7697 (mapcar
7698 (lambda (x)
7699 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
7700 (cons (match-string 2 x) (match-string 1 x)))
7701 (org-split-string (org-get-current-options) "\n"))
7702 (mapcar 'list org-additional-option-like-keywords)))
7703 (startup
7704 (setq type :startup)
7705 org-startup-options)
7706 (link (append org-link-abbrev-alist-local
7707 org-link-abbrev-alist))
7708 (texp
7709 (setq type :tex)
7710 org-html-entities)
7711 ((string-match "\\`\\*+[ \t]+\\'"
7712 (buffer-substring (point-at-bol) beg))
7713 (setq type :todo)
7714 (mapcar 'list org-todo-keywords-1))
7715 (searchhead
7716 (setq type :searchhead)
7717 (save-excursion
7718 (goto-char (point-min))
7719 (while (re-search-forward org-todo-line-regexp nil t)
7720 (push (list
7721 (org-make-org-heading-search-string
7722 (match-string 3) t))
7723 tbl)))
7724 tbl)
7725 (tag (setq type :tag beg beg1)
7726 (or org-tag-alist (org-get-buffer-tags)))
7727 (prop (setq type :prop beg beg1)
7728 (mapcar 'list (org-buffer-property-keys nil t t)))
7729 (t (progn
7730 (call-interactively org-completion-fallback-command)
7731 (throw 'exit nil)))))
7732 (pattern (buffer-substring-no-properties beg end))
7733 (completion (try-completion pattern table confirm)))
7734 (cond ((eq completion t)
7735 (if (not (assoc (upcase pattern) table))
7736 (message "Already complete")
7737 (if (and (equal type :opt)
7738 (not (member (car (assoc (upcase pattern) table))
7739 org-additional-option-like-keywords)))
7740 (insert (substring (cdr (assoc (upcase pattern) table))
7741 (length pattern)))
7742 (if (memq type '(:tag :prop)) (insert ":")))))
7743 ((null completion)
7744 (message "Can't find completion for \"%s\"" pattern)
7745 (ding))
7746 ((not (string= pattern completion))
7747 (delete-region beg end)
7748 (if (string-match " +$" completion)
7749 (setq completion (replace-match "" t t completion)))
7750 (insert completion)
7751 (if (get-buffer-window "*Completions*")
7752 (delete-window (get-buffer-window "*Completions*")))
7753 (if (assoc completion table)
7754 (if (eq type :todo) (insert " ")
7755 (if (memq type '(:tag :prop)) (insert ":"))))
7756 (if (and (equal type :opt) (assoc completion table))
7757 (message "%s" (substitute-command-keys
7758 "Press \\[org-complete] again to insert example settings"))))
7760 (message "Making completion list...")
7761 (let ((list (sort (all-completions pattern table confirm)
7762 'string<)))
7763 (with-output-to-temp-buffer "*Completions*"
7764 (condition-case nil
7765 ;; Protection needed for XEmacs and emacs 21
7766 (display-completion-list list pattern)
7767 (error (display-completion-list list)))))
7768 (message "Making completion list...%s" "done")))))))
7770 ;;;; TODO, DEADLINE, Comments
7772 (defun org-toggle-comment ()
7773 "Change the COMMENT state of an entry."
7774 (interactive)
7775 (save-excursion
7776 (org-back-to-heading)
7777 (let (case-fold-search)
7778 (if (looking-at (concat outline-regexp
7779 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
7780 (replace-match "" t t nil 1)
7781 (if (looking-at outline-regexp)
7782 (progn
7783 (goto-char (match-end 0))
7784 (insert org-comment-string " ")))))))
7786 (defvar org-last-todo-state-is-todo nil
7787 "This is non-nil when the last TODO state change led to a TODO state.
7788 If the last change removed the TODO tag or switched to DONE, then
7789 this is nil.")
7791 (defvar org-setting-tags nil) ; dynamically skiped
7793 (defun org-parse-local-options (string var)
7794 "Parse STRING for startup setting relevant for variable VAR."
7795 (let ((rtn (symbol-value var))
7796 e opts)
7797 (save-match-data
7798 (if (or (not string) (not (string-match "\\S-" string)))
7800 (setq opts (delq nil (mapcar (lambda (x)
7801 (setq e (assoc x org-startup-options))
7802 (if (eq (nth 1 e) var) e nil))
7803 (org-split-string string "[ \t]+"))))
7804 (if (not opts)
7806 (setq rtn nil)
7807 (while (setq e (pop opts))
7808 (if (not (nth 3 e))
7809 (setq rtn (nth 2 e))
7810 (if (not (listp rtn)) (setq rtn nil))
7811 (push (nth 2 e) rtn)))
7812 rtn)))))
7814 (defvar org-blocker-hook nil
7815 "Hook for functions that are allowed to block a state change.
7817 Each function gets as its single argument a property list, see
7818 `org-trigger-hook' for more information about this list.
7820 If any of the functions in this hook returns nil, the state change
7821 is blocked.")
7823 (defvar org-trigger-hook nil
7824 "Hook for functions that are triggered by a state change.
7826 Each function gets as its single argument a property list with at least
7827 the following elements:
7829 (:type type-of-change :position pos-at-entry-start
7830 :from old-state :to new-state)
7832 Depending on the type, more properties may be present.
7834 This mechanism is currently implemented for:
7836 TODO state changes
7837 ------------------
7838 :type todo-state-change
7839 :from previous state (keyword as a string), or nil
7840 :to new state (keyword as a string), or nil")
7842 (defvar org-agenda-headline-snapshot-before-repeat)
7843 (defun org-todo (&optional arg)
7844 "Change the TODO state of an item.
7845 The state of an item is given by a keyword at the start of the heading,
7846 like
7847 *** TODO Write paper
7848 *** DONE Call mom
7850 The different keywords are specified in the variable `org-todo-keywords'.
7851 By default the available states are \"TODO\" and \"DONE\".
7852 So for this example: when the item starts with TODO, it is changed to DONE.
7853 When it starts with DONE, the DONE is removed. And when neither TODO nor
7854 DONE are present, add TODO at the beginning of the heading.
7856 With C-u prefix arg, use completion to determine the new state.
7857 With numeric prefix arg, switch to that state.
7859 For calling through lisp, arg is also interpreted in the following way:
7860 'none -> empty state
7861 \"\"(empty string) -> switch to empty state
7862 'done -> switch to DONE
7863 'nextset -> switch to the next set of keywords
7864 'previousset -> switch to the previous set of keywords
7865 \"WAITING\" -> switch to the specified keyword, but only if it
7866 really is a member of `org-todo-keywords'."
7867 (interactive "P")
7868 (save-excursion
7869 (catch 'exit
7870 (org-back-to-heading)
7871 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
7872 (or (looking-at (concat " +" org-todo-regexp " *"))
7873 (looking-at " *"))
7874 (let* ((match-data (match-data))
7875 (startpos (point-at-bol))
7876 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
7877 (org-log-done org-log-done)
7878 (org-log-repeat org-log-repeat)
7879 (org-todo-log-states org-todo-log-states)
7880 (this (match-string 1))
7881 (hl-pos (match-beginning 0))
7882 (head (org-get-todo-sequence-head this))
7883 (ass (assoc head org-todo-kwd-alist))
7884 (interpret (nth 1 ass))
7885 (done-word (nth 3 ass))
7886 (final-done-word (nth 4 ass))
7887 (last-state (or this ""))
7888 (completion-ignore-case t)
7889 (member (member this org-todo-keywords-1))
7890 (tail (cdr member))
7891 (state (cond
7892 ((and org-todo-key-trigger
7893 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
7894 (and (not arg) org-use-fast-todo-selection
7895 (not (eq org-use-fast-todo-selection 'prefix)))))
7896 ;; Use fast selection
7897 (org-fast-todo-selection))
7898 ((and (equal arg '(4))
7899 (or (not org-use-fast-todo-selection)
7900 (not org-todo-key-trigger)))
7901 ;; Read a state with completion
7902 (completing-read "State: " (mapcar (lambda(x) (list x))
7903 org-todo-keywords-1)
7904 nil t))
7905 ((eq arg 'right)
7906 (if this
7907 (if tail (car tail) nil)
7908 (car org-todo-keywords-1)))
7909 ((eq arg 'left)
7910 (if (equal member org-todo-keywords-1)
7912 (if this
7913 (nth (- (length org-todo-keywords-1) (length tail) 2)
7914 org-todo-keywords-1)
7915 (org-last org-todo-keywords-1))))
7916 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
7917 (setq arg nil))) ; hack to fall back to cycling
7918 (arg
7919 ;; user or caller requests a specific state
7920 (cond
7921 ((equal arg "") nil)
7922 ((eq arg 'none) nil)
7923 ((eq arg 'done) (or done-word (car org-done-keywords)))
7924 ((eq arg 'nextset)
7925 (or (car (cdr (member head org-todo-heads)))
7926 (car org-todo-heads)))
7927 ((eq arg 'previousset)
7928 (let ((org-todo-heads (reverse org-todo-heads)))
7929 (or (car (cdr (member head org-todo-heads)))
7930 (car org-todo-heads))))
7931 ((car (member arg org-todo-keywords-1)))
7932 ((nth (1- (prefix-numeric-value arg))
7933 org-todo-keywords-1))))
7934 ((null member) (or head (car org-todo-keywords-1)))
7935 ((equal this final-done-word) nil) ;; -> make empty
7936 ((null tail) nil) ;; -> first entry
7937 ((eq interpret 'sequence)
7938 (car tail))
7939 ((memq interpret '(type priority))
7940 (if (eq this-command last-command)
7941 (car tail)
7942 (if (> (length tail) 0)
7943 (or done-word (car org-done-keywords))
7944 nil)))
7945 (t nil)))
7946 (next (if state (concat " " state " ") " "))
7947 (change-plist (list :type 'todo-state-change :from this :to state
7948 :position startpos))
7949 dolog now-done-p)
7950 (when org-blocker-hook
7951 (unless (save-excursion
7952 (save-match-data
7953 (run-hook-with-args-until-failure
7954 'org-blocker-hook change-plist)))
7955 (if (interactive-p)
7956 (error "TODO state change from %s to %s blocked" this state)
7957 ;; fail silently
7958 (message "TODO state change from %s to %s blocked" this state)
7959 (throw 'exit nil))))
7960 (store-match-data match-data)
7961 (replace-match next t t)
7962 (unless (pos-visible-in-window-p hl-pos)
7963 (message "TODO state changed to %s" (org-trim next)))
7964 (unless head
7965 (setq head (org-get-todo-sequence-head state)
7966 ass (assoc head org-todo-kwd-alist)
7967 interpret (nth 1 ass)
7968 done-word (nth 3 ass)
7969 final-done-word (nth 4 ass)))
7970 (when (memq arg '(nextset previousset))
7971 (message "Keyword-Set %d/%d: %s"
7972 (- (length org-todo-sets) -1
7973 (length (memq (assoc state org-todo-sets) org-todo-sets)))
7974 (length org-todo-sets)
7975 (mapconcat 'identity (assoc state org-todo-sets) " ")))
7976 (setq org-last-todo-state-is-todo
7977 (not (member state org-done-keywords)))
7978 (setq now-done-p (and (member state org-done-keywords)
7979 (not (member this org-done-keywords))))
7980 (and logging (org-local-logging logging))
7981 (when (and (or org-todo-log-states org-log-done)
7982 (not (memq arg '(nextset previousset))))
7983 ;; we need to look at recording a time and note
7984 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
7985 (nth 2 (assoc this org-todo-log-states))))
7986 (when (and state
7987 (member state org-not-done-keywords)
7988 (not (member this org-not-done-keywords)))
7989 ;; This is now a todo state and was not one before
7990 ;; If there was a CLOSED time stamp, get rid of it.
7991 (org-add-planning-info nil nil 'closed))
7992 (when (and now-done-p org-log-done)
7993 ;; It is now done, and it was not done before
7994 (org-add-planning-info 'closed (org-current-time))
7995 (if (and (not dolog) (eq 'note org-log-done))
7996 (org-add-log-setup 'done state 'findpos 'note)))
7997 (when (and state dolog)
7998 ;; This is a non-nil state, and we need to log it
7999 (org-add-log-setup 'state state 'findpos dolog)))
8000 ;; Fixup tag positioning
8001 (org-todo-trigger-tag-changes state)
8002 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
8003 (when org-provide-todo-statistics
8004 (org-update-parent-todo-statistics))
8005 (run-hooks 'org-after-todo-state-change-hook)
8006 (if (and arg (not (member state org-done-keywords)))
8007 (setq head (org-get-todo-sequence-head state)))
8008 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
8009 ;; Do we need to trigger a repeat?
8010 (when now-done-p
8011 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
8012 ;; This is for the agenda, take a snapshot of the headline.
8013 (save-match-data
8014 (setq org-agenda-headline-snapshot-before-repeat
8015 (org-get-heading))))
8016 (org-auto-repeat-maybe state))
8017 ;; Fixup cursor location if close to the keyword
8018 (if (and (outline-on-heading-p)
8019 (not (bolp))
8020 (save-excursion (beginning-of-line 1)
8021 (looking-at org-todo-line-regexp))
8022 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
8023 (progn
8024 (goto-char (or (match-end 2) (match-end 1)))
8025 (just-one-space)))
8026 (when org-trigger-hook
8027 (save-excursion
8028 (run-hook-with-args 'org-trigger-hook change-plist)))))))
8030 (defun org-update-parent-todo-statistics ()
8031 "Update any statistics cookie in the parent of the current headline."
8032 (interactive)
8033 (let ((box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
8034 level (cnt-all 0) (cnt-done 0) is-percent kwd)
8035 (catch 'exit
8036 (save-excursion
8037 (setq level (org-up-heading-safe))
8038 (unless (and level
8039 (re-search-forward box-re (point-at-eol) t))
8040 (throw 'exit nil))
8041 (setq is-percent (match-end 2))
8042 (save-match-data
8043 (unless (outline-next-heading) (throw 'exit nil))
8044 (while (looking-at org-todo-line-regexp)
8045 (setq kwd (match-string 2))
8046 (and kwd (setq cnt-all (1+ cnt-all)))
8047 (and (member kwd org-done-keywords)
8048 (setq cnt-done (1+ cnt-done)))
8049 (condition-case nil
8050 (org-forward-same-level 1)
8051 (error (end-of-line 1)))))
8052 (replace-match
8053 (if is-percent
8054 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
8055 (format "[%d/%d]" cnt-done cnt-all)))
8056 (run-hook-with-args 'org-after-todo-statistics-hook
8057 cnt-done (- cnt-all cnt-done))))))
8059 (defvar org-after-todo-statistics-hook nil
8060 "Hook that is called after a TODO statistics cookie has been updated.
8061 Each function is called with two arguments: the number of not-done entries
8062 and the number of done entries.
8064 For example, the following function, when added to this hook, will switch
8065 an entry to DONE when all children are done, and back to TODO when new
8066 entries are set to a TODO status. Note that this hook is only called
8067 when there is a statistics cookie in the headline!
8069 (defun org-summary-todo (n-done n-not-done)
8070 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
8071 (let (org-log-done org-log-states) ; turn off logging
8072 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
8075 (defun org-todo-trigger-tag-changes (state)
8076 "Apply the changes defined in `org-todo-state-tags-triggers'."
8077 (let ((l org-todo-state-tags-triggers)
8078 changes)
8079 (when (or (not state) (equal state ""))
8080 (setq changes (append changes (cdr (assoc "" l)))))
8081 (when (and (stringp state) (> (length state) 0))
8082 (setq changes (append changes (cdr (assoc state l)))))
8083 (when (member state org-not-done-keywords)
8084 (setq changes (append changes (cdr (assoc 'todo l)))))
8085 (when (member state org-done-keywords)
8086 (setq changes (append changes (cdr (assoc 'done l)))))
8087 (dolist (c changes)
8088 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
8090 (defun org-local-logging (value)
8091 "Get logging settings from a property VALUE."
8092 (let* (words w a)
8093 ;; directly set the variables, they are already local.
8094 (setq org-log-done nil
8095 org-log-repeat nil
8096 org-todo-log-states nil)
8097 (setq words (org-split-string value))
8098 (while (setq w (pop words))
8099 (cond
8100 ((setq a (assoc w org-startup-options))
8101 (and (member (nth 1 a) '(org-log-done org-log-repeat))
8102 (set (nth 1 a) (nth 2 a))))
8103 ((setq a (org-extract-log-state-settings w))
8104 (and (member (car a) org-todo-keywords-1)
8105 (push a org-todo-log-states)))))))
8107 (defun org-get-todo-sequence-head (kwd)
8108 "Return the head of the TODO sequence to which KWD belongs.
8109 If KWD is not set, check if there is a text property remembering the
8110 right sequence."
8111 (let (p)
8112 (cond
8113 ((not kwd)
8114 (or (get-text-property (point-at-bol) 'org-todo-head)
8115 (progn
8116 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
8117 nil (point-at-eol)))
8118 (get-text-property p 'org-todo-head))))
8119 ((not (member kwd org-todo-keywords-1))
8120 (car org-todo-keywords-1))
8121 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
8123 (defun org-fast-todo-selection ()
8124 "Fast TODO keyword selection with single keys.
8125 Returns the new TODO keyword, or nil if no state change should occur."
8126 (let* ((fulltable org-todo-key-alist)
8127 (done-keywords org-done-keywords) ;; needed for the faces.
8128 (maxlen (apply 'max (mapcar
8129 (lambda (x)
8130 (if (stringp (car x)) (string-width (car x)) 0))
8131 fulltable)))
8132 (expert nil)
8133 (fwidth (+ maxlen 3 1 3))
8134 (ncol (/ (- (window-width) 4) fwidth))
8135 tg cnt e c tbl
8136 groups ingroup)
8137 (save-window-excursion
8138 (if expert
8139 (set-buffer (get-buffer-create " *Org todo*"))
8140 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
8141 (erase-buffer)
8142 (org-set-local 'org-done-keywords done-keywords)
8143 (setq tbl fulltable cnt 0)
8144 (while (setq e (pop tbl))
8145 (cond
8146 ((equal e '(:startgroup))
8147 (push '() groups) (setq ingroup t)
8148 (when (not (= cnt 0))
8149 (setq cnt 0)
8150 (insert "\n"))
8151 (insert "{ "))
8152 ((equal e '(:endgroup))
8153 (setq ingroup nil cnt 0)
8154 (insert "}\n"))
8156 (setq tg (car e) c (cdr e))
8157 (if ingroup (push tg (car groups)))
8158 (setq tg (org-add-props tg nil 'face
8159 (org-get-todo-face tg)))
8160 (if (and (= cnt 0) (not ingroup)) (insert " "))
8161 (insert "[" c "] " tg (make-string
8162 (- fwidth 4 (length tg)) ?\ ))
8163 (when (= (setq cnt (1+ cnt)) ncol)
8164 (insert "\n")
8165 (if ingroup (insert " "))
8166 (setq cnt 0)))))
8167 (insert "\n")
8168 (goto-char (point-min))
8169 (if (not expert) (org-fit-window-to-buffer))
8170 (message "[a-z..]:Set [SPC]:clear")
8171 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
8172 (cond
8173 ((or (= c ?\C-g)
8174 (and (= c ?q) (not (rassoc c fulltable))))
8175 (setq quit-flag t))
8176 ((= c ?\ ) nil)
8177 ((setq e (rassoc c fulltable) tg (car e))
8179 (t (setq quit-flag t))))))
8181 (defun org-entry-is-todo-p ()
8182 (member (org-get-todo-state) org-not-done-keywords))
8184 (defun org-entry-is-done-p ()
8185 (member (org-get-todo-state) org-done-keywords))
8187 (defun org-get-todo-state ()
8188 (save-excursion
8189 (org-back-to-heading t)
8190 (and (looking-at org-todo-line-regexp)
8191 (match-end 2)
8192 (match-string 2))))
8194 (defun org-at-date-range-p (&optional inactive-ok)
8195 "Is the cursor inside a date range?"
8196 (interactive)
8197 (save-excursion
8198 (catch 'exit
8199 (let ((pos (point)))
8200 (skip-chars-backward "^[<\r\n")
8201 (skip-chars-backward "<[")
8202 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8203 (>= (match-end 0) pos)
8204 (throw 'exit t))
8205 (skip-chars-backward "^<[\r\n")
8206 (skip-chars-backward "<[")
8207 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8208 (>= (match-end 0) pos)
8209 (throw 'exit t)))
8210 nil)))
8212 (defun org-get-repeat ()
8213 "Check if there is a deadline/schedule with repeater in this entry."
8214 (save-match-data
8215 (save-excursion
8216 (org-back-to-heading t)
8217 (if (re-search-forward
8218 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
8219 (match-string 1)))))
8221 (defvar org-last-changed-timestamp)
8222 (defvar org-last-inserted-timestamp)
8223 (defvar org-log-post-message)
8224 (defvar org-log-note-purpose)
8225 (defvar org-log-note-how)
8226 (defvar org-log-note-extra)
8227 (defun org-auto-repeat-maybe (done-word)
8228 "Check if the current headline contains a repeated deadline/schedule.
8229 If yes, set TODO state back to what it was and change the base date
8230 of repeating deadline/scheduled time stamps to new date.
8231 This function is run automatically after each state change to a DONE state."
8232 ;; last-state is dynamically scoped into this function
8233 (let* ((repeat (org-get-repeat))
8234 (aa (assoc last-state org-todo-kwd-alist))
8235 (interpret (nth 1 aa))
8236 (head (nth 2 aa))
8237 (whata '(("d" . day) ("m" . month) ("y" . year)))
8238 (msg "Entry repeats: ")
8239 (org-log-done nil)
8240 (org-todo-log-states nil)
8241 (nshiftmax 10) (nshift 0)
8242 re type n what ts mb0 time)
8243 (when repeat
8244 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
8245 (org-todo (if (eq interpret 'type) last-state head))
8246 (when org-log-repeat
8247 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
8248 (memq 'org-add-log-note post-command-hook))
8249 ;; OK, we are already setup for some record
8250 (if (eq org-log-repeat 'note)
8251 ;; make sure we take a note, not only a time stamp
8252 (setq org-log-note-how 'note))
8253 ;; Set up for taking a record
8254 (org-add-log-setup 'state (or done-word (car org-done-keywords))
8255 'findpos org-log-repeat)))
8256 (org-back-to-heading t)
8257 (org-add-planning-info nil nil 'closed)
8258 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
8259 org-deadline-time-regexp "\\)\\|\\("
8260 org-ts-regexp "\\)"))
8261 (while (re-search-forward
8262 re (save-excursion (outline-next-heading) (point)) t)
8263 (setq type (if (match-end 1) org-scheduled-string
8264 (if (match-end 3) org-deadline-string "Plain:"))
8265 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0)))
8266 mb0 (match-beginning 0))
8267 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
8268 (setq n (string-to-number (match-string 2 ts))
8269 what (match-string 3 ts))
8270 (if (equal what "w") (setq n (* n 7) what "d"))
8271 ;; Preparation, see if we need to modify the start date for the change
8272 (when (match-end 1)
8273 (setq time (save-match-data (org-time-string-to-time ts)))
8274 (cond
8275 ((equal (match-string 1 ts) ".")
8276 ;; Shift starting date to today
8277 (org-timestamp-change
8278 (- (time-to-days (current-time)) (time-to-days time))
8279 'day))
8280 ((equal (match-string 1 ts) "+")
8281 (while (or (= nshift 0)
8282 (<= (time-to-days time) (time-to-days (current-time))))
8283 (when (= (incf nshift) nshiftmax)
8284 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
8285 (error "Abort")))
8286 (org-timestamp-change n (cdr (assoc what whata)))
8287 (org-at-timestamp-p t)
8288 (setq ts (match-string 1))
8289 (setq time (save-match-data (org-time-string-to-time ts))))
8290 (org-timestamp-change (- n) (cdr (assoc what whata)))
8291 ;; rematch, so that we have everything in place for the real shift
8292 (org-at-timestamp-p t)
8293 (setq ts (match-string 1))
8294 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
8295 (org-timestamp-change n (cdr (assoc what whata)))
8296 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
8297 (setq org-log-post-message msg)
8298 (message "%s" msg))))
8300 (defun org-show-todo-tree (arg)
8301 "Make a compact tree which shows all headlines marked with TODO.
8302 The tree will show the lines where the regexp matches, and all higher
8303 headlines above the match.
8304 With a \\[universal-argument] prefix, also show the DONE entries.
8305 With a numeric prefix N, construct a sparse tree for the Nth element
8306 of `org-todo-keywords-1'."
8307 (interactive "P")
8308 (let ((case-fold-search nil)
8309 (kwd-re
8310 (cond ((null arg) org-not-done-regexp)
8311 ((equal arg '(4))
8312 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
8313 (mapcar 'list org-todo-keywords-1))))
8314 (concat "\\("
8315 (mapconcat 'identity (org-split-string kwd "|") "\\|")
8316 "\\)\\>")))
8317 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
8318 (regexp-quote (nth (1- (prefix-numeric-value arg))
8319 org-todo-keywords-1)))
8320 (t (error "Invalid prefix argument: %s" arg)))))
8321 (message "%d TODO entries found"
8322 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
8324 (defun org-deadline (&optional remove time)
8325 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
8326 With argument REMOVE, remove any deadline from the item.
8327 When TIME is set, it should be an internal time specification, and the
8328 scheduling will use the corresponding date."
8329 (interactive "P")
8330 (if remove
8331 (progn
8332 (org-remove-timestamp-with-keyword org-deadline-string)
8333 (message "Item no longer has a deadline."))
8334 (if (org-get-repeat)
8335 (error "Cannot change deadline on task with repeater, please do that by hand")
8336 (org-add-planning-info 'deadline time 'closed)
8337 (message "Deadline on %s" org-last-inserted-timestamp))))
8339 (defun org-schedule (&optional remove time)
8340 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
8341 With argument REMOVE, remove any scheduling date from the item.
8342 When TIME is set, it should be an internal time specification, and the
8343 scheduling will use the corresponding date."
8344 (interactive "P")
8345 (if remove
8346 (progn
8347 (org-remove-timestamp-with-keyword org-scheduled-string)
8348 (message "Item is no longer scheduled."))
8349 (if (org-get-repeat)
8350 (error "Cannot reschedule task with repeater, please do that by hand")
8351 (org-add-planning-info 'scheduled time 'closed)
8352 (message "Scheduled to %s" org-last-inserted-timestamp))))
8354 (defun org-remove-timestamp-with-keyword (keyword)
8355 "Remove all time stamps with KEYWORD in the current entry."
8356 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
8357 beg)
8358 (save-excursion
8359 (org-back-to-heading t)
8360 (setq beg (point))
8361 (org-end-of-subtree t t)
8362 (while (re-search-backward re beg t)
8363 (replace-match "")
8364 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
8365 (equal (char-before) ?\ ))
8366 (backward-delete-char 1)
8367 (if (string-match "^[ \t]*$" (buffer-substring
8368 (point-at-bol) (point-at-eol)))
8369 (delete-region (point-at-bol)
8370 (min (point-max) (1+ (point-at-eol))))))))))
8372 (defun org-add-planning-info (what &optional time &rest remove)
8373 "Insert new timestamp with keyword in the line directly after the headline.
8374 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
8375 If non is given, the user is prompted for a date.
8376 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
8377 be removed."
8378 (interactive)
8379 (let (org-time-was-given org-end-time-was-given ts
8380 end default-time default-input)
8382 (when (and (not time) (memq what '(scheduled deadline)))
8383 ;; Try to get a default date/time from existing timestamp
8384 (save-excursion
8385 (org-back-to-heading t)
8386 (setq end (save-excursion (outline-next-heading) (point)))
8387 (when (re-search-forward (if (eq what 'scheduled)
8388 org-scheduled-time-regexp
8389 org-deadline-time-regexp)
8390 end t)
8391 (setq ts (match-string 1)
8392 default-time
8393 (apply 'encode-time (org-parse-time-string ts))
8394 default-input (and ts (org-get-compact-tod ts))))))
8395 (when what
8396 ;; If necessary, get the time from the user
8397 (setq time (or time (org-read-date nil 'to-time nil nil
8398 default-time default-input))))
8400 (when (and org-insert-labeled-timestamps-at-point
8401 (member what '(scheduled deadline)))
8402 (insert
8403 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
8404 (org-insert-time-stamp time org-time-was-given
8405 nil nil nil (list org-end-time-was-given))
8406 (setq what nil))
8407 (save-excursion
8408 (save-restriction
8409 (let (col list elt ts buffer-invisibility-spec)
8410 (org-back-to-heading t)
8411 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
8412 (goto-char (match-end 1))
8413 (setq col (current-column))
8414 (goto-char (match-end 0))
8415 (if (eobp) (insert "\n") (forward-char 1))
8416 (if (and (not (looking-at outline-regexp))
8417 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
8418 "[^\r\n]*"))
8419 (not (equal (match-string 1) org-clock-string)))
8420 (narrow-to-region (match-beginning 0) (match-end 0))
8421 (insert-before-markers "\n")
8422 (backward-char 1)
8423 (narrow-to-region (point) (point))
8424 (and org-adapt-indentation (org-indent-to-column col)))
8425 ;; Check if we have to remove something.
8426 (setq list (cons what remove))
8427 (while list
8428 (setq elt (pop list))
8429 (goto-char (point-min))
8430 (when (or (and (eq elt 'scheduled)
8431 (re-search-forward org-scheduled-time-regexp nil t))
8432 (and (eq elt 'deadline)
8433 (re-search-forward org-deadline-time-regexp nil t))
8434 (and (eq elt 'closed)
8435 (re-search-forward org-closed-time-regexp nil t)))
8436 (replace-match "")
8437 (if (looking-at "--+<[^>]+>") (replace-match ""))
8438 (if (looking-at " +") (replace-match ""))))
8439 (goto-char (point-max))
8440 (when what
8441 (insert
8442 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
8443 (cond ((eq what 'scheduled) org-scheduled-string)
8444 ((eq what 'deadline) org-deadline-string)
8445 ((eq what 'closed) org-closed-string))
8446 " ")
8447 (setq ts (org-insert-time-stamp
8448 time
8449 (or org-time-was-given
8450 (and (eq what 'closed) org-log-done-with-time))
8451 (eq what 'closed)
8452 nil nil (list org-end-time-was-given)))
8453 (end-of-line 1))
8454 (goto-char (point-min))
8455 (widen)
8456 (if (and (looking-at "[ \t]+\n")
8457 (equal (char-before) ?\n))
8458 (delete-region (1- (point)) (point-at-eol)))
8459 ts)))))
8461 (defvar org-log-note-marker (make-marker))
8462 (defvar org-log-note-purpose nil)
8463 (defvar org-log-note-state nil)
8464 (defvar org-log-note-how nil)
8465 (defvar org-log-note-extra nil)
8466 (defvar org-log-note-window-configuration nil)
8467 (defvar org-log-note-return-to (make-marker))
8468 (defvar org-log-post-message nil
8469 "Message to be displayed after a log note has been stored.
8470 The auto-repeater uses this.")
8472 (defun org-add-note ()
8473 "Add a note to the current entry.
8474 This is done in the same way as adding a state change note."
8475 (interactive)
8476 (org-add-log-setup 'note nil 'findpos nil))
8478 (defvar org-property-end-re)
8479 (defun org-add-log-setup (&optional purpose state findpos how &optional extra)
8480 "Set up the post command hook to take a note.
8481 If this is about to TODO state change, the new state is expected in STATE.
8482 When FINDPOS is non-nil, find the correct position for the note in
8483 the current entry. If not, assume that it can be inserted at point.
8484 HOW is an indicator what kind of note should be created.
8485 EXTRA is additional text that will be inserted into the notes buffer."
8486 (save-restriction
8487 (save-excursion
8488 (when findpos
8489 (org-back-to-heading t)
8490 (narrow-to-region (point) (save-excursion
8491 (outline-next-heading) (point)))
8492 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
8493 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
8494 "[^\r\n]*\\)?"))
8495 (goto-char (match-end 0))
8496 (when (and org-log-state-notes-insert-after-drawers
8497 (save-excursion
8498 (forward-line) (looking-at org-drawer-regexp)))
8499 (progn (forward-line)
8500 (while (looking-at org-drawer-regexp)
8501 (goto-char (match-end 0))
8502 (re-search-forward org-property-end-re (point-max) t)
8503 (forward-line))
8504 (forward-line -1)))
8505 (unless org-log-states-order-reversed
8506 (and (= (char-after) ?\n) (forward-char 1))
8507 (org-skip-over-state-notes)
8508 (skip-chars-backward " \t\n\r")))
8509 (move-marker org-log-note-marker (point))
8510 (setq org-log-note-purpose purpose
8511 org-log-note-state state
8512 org-log-note-how how
8513 org-log-note-extra extra)
8514 (add-hook 'post-command-hook 'org-add-log-note 'append))))
8516 (defun org-skip-over-state-notes ()
8517 "Skip past the list of State notes in an entry."
8518 (if (looking-at "\n[ \t]*- State") (forward-char 1))
8519 (while (looking-at "[ \t]*- State")
8520 (condition-case nil
8521 (org-next-item)
8522 (error (org-end-of-item)))))
8524 (defun org-add-log-note (&optional purpose)
8525 "Pop up a window for taking a note, and add this note later at point."
8526 (remove-hook 'post-command-hook 'org-add-log-note)
8527 (setq org-log-note-window-configuration (current-window-configuration))
8528 (delete-other-windows)
8529 (move-marker org-log-note-return-to (point))
8530 (switch-to-buffer (marker-buffer org-log-note-marker))
8531 (goto-char org-log-note-marker)
8532 (org-switch-to-buffer-other-window "*Org Note*")
8533 (erase-buffer)
8534 (if (memq org-log-note-how '(time state))
8535 (let (current-prefix-arg) (org-store-log-note))
8536 (let ((org-inhibit-startup t)) (org-mode))
8537 (insert (format "# Insert note for %s.
8538 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
8539 (cond
8540 ((eq org-log-note-purpose 'clock-out) "stopped clock")
8541 ((eq org-log-note-purpose 'done) "closed todo item")
8542 ((eq org-log-note-purpose 'state)
8543 (format "state change to \"%s\"" org-log-note-state))
8544 ((eq org-log-note-purpose 'note)
8545 "this entry")
8546 (t (error "This should not happen")))))
8547 (if org-log-note-extra (insert org-log-note-extra))
8548 (org-set-local 'org-finish-function 'org-store-log-note)))
8550 (defvar org-note-abort nil) ; dynamically scoped
8551 (defun org-store-log-note ()
8552 "Finish taking a log note, and insert it to where it belongs."
8553 (let ((txt (buffer-string))
8554 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
8555 lines ind)
8556 (kill-buffer (current-buffer))
8557 (while (string-match "\\`#.*\n[ \t\n]*" txt)
8558 (setq txt (replace-match "" t t txt)))
8559 (if (string-match "\\s-+\\'" txt)
8560 (setq txt (replace-match "" t t txt)))
8561 (setq lines (org-split-string txt "\n"))
8562 (when (and note (string-match "\\S-" note))
8563 (setq note
8564 (org-replace-escapes
8565 note
8566 (list (cons "%u" (user-login-name))
8567 (cons "%U" user-full-name)
8568 (cons "%t" (format-time-string
8569 (org-time-stamp-format 'long 'inactive)
8570 (current-time)))
8571 (cons "%s" (if org-log-note-state
8572 (concat "\"" org-log-note-state "\"")
8573 "")))))
8574 (if lines (setq note (concat note " \\\\")))
8575 (push note lines))
8576 (when (or current-prefix-arg org-note-abort) (setq lines nil))
8577 (when lines
8578 (save-excursion
8579 (set-buffer (marker-buffer org-log-note-marker))
8580 (save-excursion
8581 (goto-char org-log-note-marker)
8582 (move-marker org-log-note-marker nil)
8583 (end-of-line 1)
8584 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
8585 (indent-relative nil)
8586 (insert "- " (pop lines))
8587 (org-indent-line-function)
8588 (beginning-of-line 1)
8589 (looking-at "[ \t]*")
8590 (setq ind (concat (match-string 0) " "))
8591 (end-of-line 1)
8592 (while lines (insert "\n" ind (pop lines)))))))
8593 (set-window-configuration org-log-note-window-configuration)
8594 (with-current-buffer (marker-buffer org-log-note-return-to)
8595 (goto-char org-log-note-return-to))
8596 (move-marker org-log-note-return-to nil)
8597 (and org-log-post-message (message "%s" org-log-post-message)))
8599 (defun org-sparse-tree (&optional arg)
8600 "Create a sparse tree, prompt for the details.
8601 This command can create sparse trees. You first need to select the type
8602 of match used to create the tree:
8604 t Show entries with a specific TODO keyword.
8605 T Show entries selected by a tags match.
8606 p Enter a property name and its value (both with completion on existing
8607 names/values) and show entries with that property.
8608 r Show entries matching a regular expression
8609 d Show deadlines due within `org-deadline-warning-days'."
8610 (interactive "P")
8611 (let (ans kwd value)
8612 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
8613 (setq ans (read-char-exclusive))
8614 (cond
8615 ((equal ans ?d)
8616 (call-interactively 'org-check-deadlines))
8617 ((equal ans ?b)
8618 (call-interactively 'org-check-before-date))
8619 ((equal ans ?t)
8620 (org-show-todo-tree '(4)))
8621 ((equal ans ?T)
8622 (call-interactively 'org-tags-sparse-tree))
8623 ((member ans '(?p ?P))
8624 (setq kwd (completing-read "Property: "
8625 (mapcar 'list (org-buffer-property-keys))))
8626 (setq value (completing-read "Value: "
8627 (mapcar 'list (org-property-values kwd))))
8628 (unless (string-match "\\`{.*}\\'" value)
8629 (setq value (concat "\"" value "\"")))
8630 (org-tags-sparse-tree arg (concat kwd "=" value)))
8631 ((member ans '(?r ?R ?/))
8632 (call-interactively 'org-occur))
8633 (t (error "No such sparse tree command \"%c\"" ans)))))
8635 (defvar org-occur-highlights nil
8636 "List of overlays used for occur matches.")
8637 (make-variable-buffer-local 'org-occur-highlights)
8638 (defvar org-occur-parameters nil
8639 "Parameters of the active org-occur calls.
8640 This is a list, each call to org-occur pushes as cons cell,
8641 containing the regular expression and the callback, onto the list.
8642 The list can contain several entries if `org-occur' has been called
8643 several time with the KEEP-PREVIOUS argument. Otherwise, this list
8644 will only contain one set of parameters. When the highlights are
8645 removed (for example with `C-c C-c', or with the next edit (depending
8646 on `org-remove-highlights-with-change'), this variable is emptied
8647 as well.")
8648 (make-variable-buffer-local 'org-occur-parameters)
8650 (defun org-occur (regexp &optional keep-previous callback)
8651 "Make a compact tree which shows all matches of REGEXP.
8652 The tree will show the lines where the regexp matches, and all higher
8653 headlines above the match. It will also show the heading after the match,
8654 to make sure editing the matching entry is easy.
8655 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
8656 call to `org-occur' will be kept, to allow stacking of calls to this
8657 command.
8658 If CALLBACK is non-nil, it is a function which is called to confirm
8659 that the match should indeed be shown."
8660 (interactive "sRegexp: \nP")
8661 (unless keep-previous
8662 (org-remove-occur-highlights nil nil t))
8663 (push (cons regexp callback) org-occur-parameters)
8664 (let ((cnt 0))
8665 (save-excursion
8666 (goto-char (point-min))
8667 (if (or (not keep-previous) ; do not want to keep
8668 (not org-occur-highlights)) ; no previous matches
8669 ;; hide everything
8670 (org-overview))
8671 (while (re-search-forward regexp nil t)
8672 (when (or (not callback)
8673 (save-match-data (funcall callback)))
8674 (setq cnt (1+ cnt))
8675 (when org-highlight-sparse-tree-matches
8676 (org-highlight-new-match (match-beginning 0) (match-end 0)))
8677 (org-show-context 'occur-tree))))
8678 (when org-remove-highlights-with-change
8679 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
8680 nil 'local))
8681 (unless org-sparse-tree-open-archived-trees
8682 (org-hide-archived-subtrees (point-min) (point-max)))
8683 (run-hooks 'org-occur-hook)
8684 (if (interactive-p)
8685 (message "%d match(es) for regexp %s" cnt regexp))
8686 cnt))
8688 (defun org-show-context (&optional key)
8689 "Make sure point and context and visible.
8690 How much context is shown depends upon the variables
8691 `org-show-hierarchy-above', `org-show-following-heading'. and
8692 `org-show-siblings'."
8693 (let ((heading-p (org-on-heading-p t))
8694 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
8695 (following-p (org-get-alist-option org-show-following-heading key))
8696 (entry-p (org-get-alist-option org-show-entry-below key))
8697 (siblings-p (org-get-alist-option org-show-siblings key)))
8698 (catch 'exit
8699 ;; Show heading or entry text
8700 (if (and heading-p (not entry-p))
8701 (org-flag-heading nil) ; only show the heading
8702 (and (or entry-p (org-invisible-p) (org-invisible-p2))
8703 (org-show-hidden-entry))) ; show entire entry
8704 (when following-p
8705 ;; Show next sibling, or heading below text
8706 (save-excursion
8707 (and (if heading-p (org-goto-sibling) (outline-next-heading))
8708 (org-flag-heading nil))))
8709 (when siblings-p (org-show-siblings))
8710 (when hierarchy-p
8711 ;; show all higher headings, possibly with siblings
8712 (save-excursion
8713 (while (and (condition-case nil
8714 (progn (org-up-heading-all 1) t)
8715 (error nil))
8716 (not (bobp)))
8717 (org-flag-heading nil)
8718 (when siblings-p (org-show-siblings))))))))
8720 (defun org-reveal (&optional siblings)
8721 "Show current entry, hierarchy above it, and the following headline.
8722 This can be used to show a consistent set of context around locations
8723 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
8724 not t for the search context.
8726 With optional argument SIBLINGS, on each level of the hierarchy all
8727 siblings are shown. This repairs the tree structure to what it would
8728 look like when opened with hierarchical calls to `org-cycle'."
8729 (interactive "P")
8730 (let ((org-show-hierarchy-above t)
8731 (org-show-following-heading t)
8732 (org-show-siblings (if siblings t org-show-siblings)))
8733 (org-show-context nil)))
8735 (defun org-highlight-new-match (beg end)
8736 "Highlight from BEG to END and mark the highlight is an occur headline."
8737 (let ((ov (org-make-overlay beg end)))
8738 (org-overlay-put ov 'face 'secondary-selection)
8739 (push ov org-occur-highlights)))
8741 (defun org-remove-occur-highlights (&optional beg end noremove)
8742 "Remove the occur highlights from the buffer.
8743 BEG and END are ignored. If NOREMOVE is nil, remove this function
8744 from the `before-change-functions' in the current buffer."
8745 (interactive)
8746 (unless org-inhibit-highlight-removal
8747 (mapc 'org-delete-overlay org-occur-highlights)
8748 (setq org-occur-highlights nil)
8749 (setq org-occur-parameters nil)
8750 (unless noremove
8751 (remove-hook 'before-change-functions
8752 'org-remove-occur-highlights 'local))))
8754 ;;;; Priorities
8756 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
8757 "Regular expression matching the priority indicator.")
8759 (defvar org-remove-priority-next-time nil)
8761 (defun org-priority-up ()
8762 "Increase the priority of the current item."
8763 (interactive)
8764 (org-priority 'up))
8766 (defun org-priority-down ()
8767 "Decrease the priority of the current item."
8768 (interactive)
8769 (org-priority 'down))
8771 (defun org-priority (&optional action)
8772 "Change the priority of an item by ARG.
8773 ACTION can be `set', `up', `down', or a character."
8774 (interactive)
8775 (setq action (or action 'set))
8776 (let (current new news have remove)
8777 (save-excursion
8778 (org-back-to-heading)
8779 (if (looking-at org-priority-regexp)
8780 (setq current (string-to-char (match-string 2))
8781 have t)
8782 (setq current org-default-priority))
8783 (cond
8784 ((or (eq action 'set)
8785 (if (featurep 'xemacs) (characterp action) (integerp action)))
8786 (if (not (eq action 'set))
8787 (setq new action)
8788 (message "Priority %c-%c, SPC to remove: "
8789 org-highest-priority org-lowest-priority)
8790 (setq new (read-char-exclusive)))
8791 (if (and (= (upcase org-highest-priority) org-highest-priority)
8792 (= (upcase org-lowest-priority) org-lowest-priority))
8793 (setq new (upcase new)))
8794 (cond ((equal new ?\ ) (setq remove t))
8795 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
8796 (error "Priority must be between `%c' and `%c'"
8797 org-highest-priority org-lowest-priority))))
8798 ((eq action 'up)
8799 (if (and (not have) (eq last-command this-command))
8800 (setq new org-lowest-priority)
8801 (setq new (if (and org-priority-start-cycle-with-default (not have))
8802 org-default-priority (1- current)))))
8803 ((eq action 'down)
8804 (if (and (not have) (eq last-command this-command))
8805 (setq new org-highest-priority)
8806 (setq new (if (and org-priority-start-cycle-with-default (not have))
8807 org-default-priority (1+ current)))))
8808 (t (error "Invalid action")))
8809 (if (or (< (upcase new) org-highest-priority)
8810 (> (upcase new) org-lowest-priority))
8811 (setq remove t))
8812 (setq news (format "%c" new))
8813 (if have
8814 (if remove
8815 (replace-match "" t t nil 1)
8816 (replace-match news t t nil 2))
8817 (if remove
8818 (error "No priority cookie found in line")
8819 (looking-at org-todo-line-regexp)
8820 (if (match-end 2)
8821 (progn
8822 (goto-char (match-end 2))
8823 (insert " [#" news "]"))
8824 (goto-char (match-beginning 3))
8825 (insert "[#" news "] ")))))
8826 (org-preserve-lc (org-set-tags nil 'align))
8827 (if remove
8828 (message "Priority removed")
8829 (message "Priority of current item set to %s" news))))
8832 (defun org-get-priority (s)
8833 "Find priority cookie and return priority."
8834 (save-match-data
8835 (if (not (string-match org-priority-regexp s))
8836 (* 1000 (- org-lowest-priority org-default-priority))
8837 (* 1000 (- org-lowest-priority
8838 (string-to-char (match-string 2 s)))))))
8840 ;;;; Tags
8842 (defvar org-agenda-archives-mode)
8843 (defun org-scan-tags (action matcher &optional todo-only)
8844 "Scan headline tags with inheritance and produce output ACTION.
8846 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
8847 or `agenda' to produce an entry list for an agenda view. It can also be
8848 a Lisp form or a function that should be called at each matched headline, in
8849 this case the return value is a list of all return values from these calls.
8851 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
8852 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
8853 only lines with a TODO keyword are included in the output."
8854 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
8855 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
8856 (org-re
8857 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
8858 (props (list 'face 'default
8859 'done-face 'org-done
8860 'undone-face 'default
8861 'mouse-face 'highlight
8862 'org-not-done-regexp org-not-done-regexp
8863 'org-todo-regexp org-todo-regexp
8864 'keymap org-agenda-keymap
8865 'help-echo
8866 (format "mouse-2 or RET jump to org file %s"
8867 (abbreviate-file-name
8868 (or (buffer-file-name (buffer-base-buffer))
8869 (buffer-name (buffer-base-buffer)))))))
8870 (case-fold-search nil)
8871 lspos tags tags-list
8872 (tags-alist (list (cons 0 (mapcar 'downcase org-file-tags))))
8873 (llast 0) rtn rtn1 level category i txt
8874 todo marker entry priority)
8875 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
8876 (setq action (list 'lambda nil action)))
8877 (save-excursion
8878 (goto-char (point-min))
8879 (when (eq action 'sparse-tree)
8880 (org-overview)
8881 (org-remove-occur-highlights))
8882 (while (re-search-forward re nil t)
8883 (catch :skip
8884 (setq todo (if (match-end 1) (match-string 2))
8885 tags (if (match-end 4) (match-string 4)))
8886 (goto-char (setq lspos (1+ (match-beginning 0))))
8887 (setq level (org-reduced-level (funcall outline-level))
8888 category (org-get-category))
8889 (setq i llast llast level)
8890 ;; remove tag lists from same and sublevels
8891 (while (>= i level)
8892 (when (setq entry (assoc i tags-alist))
8893 (setq tags-alist (delete entry tags-alist)))
8894 (setq i (1- i)))
8895 ;; add the next tags
8896 (when tags
8897 (setq tags (mapcar 'downcase (org-split-string tags ":"))
8898 tags-alist
8899 (cons (cons level tags) tags-alist)))
8900 ;; compile tags for current headline
8901 (setq tags-list
8902 (if org-use-tag-inheritance
8903 (apply 'append (mapcar 'cdr tags-alist))
8904 tags))
8905 (when (and tags org-use-tag-inheritance
8906 (not (eq t org-use-tag-inheritance)))
8907 ;; selective inheritance, remove uninherited ones
8908 (setcdr (car tags-alist)
8909 (org-remove-uniherited-tags (cdar tags-alist))))
8910 (when (and (or (not todo-only) (member todo org-not-done-keywords))
8911 (let ((case-fold-search t)) (eval matcher))
8913 (not (member org-archive-tag tags-list))
8914 ;; we have an archive tag, should we use this anyway?
8915 (or (not org-agenda-skip-archived-trees)
8916 (and (eq action 'agenda) org-agenda-archives-mode))))
8917 (unless (eq action 'sparse-tree) (org-agenda-skip))
8919 ;; select this headline
8921 (cond
8922 ((eq action 'sparse-tree)
8923 (and org-highlight-sparse-tree-matches
8924 (org-get-heading) (match-end 0)
8925 (org-highlight-new-match
8926 (match-beginning 0) (match-beginning 1)))
8927 (org-show-context 'tags-tree))
8928 ((eq action 'agenda)
8929 (setq txt (org-format-agenda-item
8931 (concat
8932 (if org-tags-match-list-sublevels
8933 (make-string (1- level) ?.) "")
8934 (org-get-heading))
8935 category tags-list)
8936 priority (org-get-priority txt))
8937 (goto-char lspos)
8938 (setq marker (org-agenda-new-marker))
8939 (org-add-props txt props
8940 'org-marker marker 'org-hd-marker marker 'org-category category
8941 'priority priority 'type "tagsmatch")
8942 (push txt rtn))
8943 ((functionp action)
8944 (save-excursion
8945 (setq rtn1 (funcall action))
8946 (push rtn1 rtn))
8947 (goto-char (point-at-eol)))
8948 (t (error "Invalid action")))
8950 ;; if we are to skip sublevels, jump to end of subtree
8951 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
8952 (when (and (eq action 'sparse-tree)
8953 (not org-sparse-tree-open-archived-trees))
8954 (org-hide-archived-subtrees (point-min) (point-max)))
8955 (nreverse rtn)))
8957 (defun org-remove-uniherited-tags (tags)
8958 "Remove all tags that are not inherited from the list TAGS."
8959 (cond
8960 ((eq org-use-tag-inheritance t) tags)
8961 ((not org-use-tag-inheritance) nil)
8962 ((stringp org-use-tag-inheritance)
8963 (delq nil (mapcar
8964 (lambda (x) (if (string-match org-use-tag-inheritance x) x nil))
8965 tags)))
8966 ((listp org-use-tag-inheritance)
8967 (delq nil (mapcar
8968 (lambda (x) (if (member x org-use-tag-inheritance) x nil))
8969 tags)))))
8971 (defvar todo-only) ;; dynamically scoped
8973 (defun org-tags-sparse-tree (&optional todo-only match)
8974 "Create a sparse tree according to tags string MATCH.
8975 MATCH can contain positive and negative selection of tags, like
8976 \"+WORK+URGENT-WITHBOSS\".
8977 If optional argument TODO_ONLY is non-nil, only select lines that are
8978 also TODO lines."
8979 (interactive "P")
8980 (org-prepare-agenda-buffers (list (current-buffer)))
8981 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
8983 (defvar org-cached-props nil)
8984 (defun org-cached-entry-get (pom property)
8985 (if (or (eq t org-use-property-inheritance)
8986 (and (stringp org-use-property-inheritance)
8987 (string-match org-use-property-inheritance property))
8988 (and (listp org-use-property-inheritance)
8989 (member property org-use-property-inheritance)))
8990 ;; Caching is not possible, check it directly
8991 (org-entry-get pom property 'inherit)
8992 ;; Get all properties, so that we can do complicated checks easily
8993 (cdr (assoc property (or org-cached-props
8994 (setq org-cached-props
8995 (org-entry-properties pom)))))))
8997 (defun org-global-tags-completion-table (&optional files)
8998 "Return the list of all tags in all agenda buffer/files."
8999 (save-excursion
9000 (org-uniquify
9001 (delq nil
9002 (apply 'append
9003 (mapcar
9004 (lambda (file)
9005 (set-buffer (find-file-noselect file))
9006 (append (org-get-buffer-tags)
9007 (mapcar (lambda (x) (if (stringp (car-safe x))
9008 (list (car-safe x)) nil))
9009 org-tag-alist)))
9010 (if (and files (car files))
9011 files
9012 (org-agenda-files))))))))
9014 (defun org-make-tags-matcher (match)
9015 "Create the TAGS//TODO matcher form for the selection string MATCH."
9016 ;; todo-only is scoped dynamically into this function, and the function
9017 ;; may change it it the matcher asksk for it.
9018 (unless match
9019 ;; Get a new match request, with completion
9020 (let ((org-last-tags-completion-table
9021 (org-global-tags-completion-table)))
9022 (setq match (completing-read
9023 "Match: " 'org-tags-completion-function nil nil nil
9024 'org-tags-history))))
9026 ;; Parse the string and create a lisp form
9027 (let ((match0 match)
9028 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
9029 minus tag mm
9030 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
9031 orterms term orlist re-p str-p level-p level-op time-p
9032 prop-p pn pv po cat-p gv rest)
9033 (if (string-match "/+" match)
9034 ;; match contains also a todo-matching request
9035 (progn
9036 (setq tagsmatch (substring match 0 (match-beginning 0))
9037 todomatch (substring match (match-end 0)))
9038 (if (string-match "^!" todomatch)
9039 (setq todo-only t todomatch (substring todomatch 1)))
9040 (if (string-match "^\\s-*$" todomatch)
9041 (setq todomatch nil)))
9042 ;; only matching tags
9043 (setq tagsmatch match todomatch nil))
9045 ;; Make the tags matcher
9046 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
9047 (setq tagsmatcher t)
9048 (setq orterms (org-split-string tagsmatch "|") orlist nil)
9049 (while (setq term (pop orterms))
9050 (while (and (equal (substring term -1) "\\") orterms)
9051 (setq term (concat term "|" (pop orterms)))) ; repair bad split
9052 (while (string-match re term)
9053 (setq rest (substring term (match-end 0))
9054 minus (and (match-end 1)
9055 (equal (match-string 1 term) "-"))
9056 tag (match-string 2 term)
9057 re-p (equal (string-to-char tag) ?{)
9058 level-p (match-end 4)
9059 prop-p (match-end 5)
9060 mm (cond
9061 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
9062 (level-p
9063 (setq level-op (org-op-to-function (match-string 3 term)))
9064 `(,level-op level ,(string-to-number
9065 (match-string 4 term))))
9066 (prop-p
9067 (setq pn (match-string 5 term)
9068 po (match-string 6 term)
9069 pv (match-string 7 term)
9070 cat-p (equal pn "CATEGORY")
9071 re-p (equal (string-to-char pv) ?{)
9072 str-p (equal (string-to-char pv) ?\")
9073 time-p (save-match-data
9074 (string-match "^\"[[<].*[]>]\"$" pv))
9075 pv (if (or re-p str-p) (substring pv 1 -1) pv))
9076 (if time-p (setq pv (org-matcher-time pv)))
9077 (setq po (org-op-to-function po (if time-p 'time str-p)))
9078 (cond
9079 ((equal pn "CATEGORY")
9080 (setq gv '(get-text-property (point) 'org-category)))
9081 ((equal pn "TODO")
9082 (setq gv 'todo))
9084 (setq gv `(org-cached-entry-get nil ,pn))))
9085 (if re-p
9086 (if (eq po 'org<>)
9087 `(not (string-match ,pv (or ,gv "")))
9088 `(string-match ,pv (or ,gv "")))
9089 (if str-p
9090 `(,po (or ,gv "") ,pv)
9091 `(,po (string-to-number (or ,gv ""))
9092 ,(string-to-number pv) ))))
9093 (t `(member ,(downcase tag) tags-list)))
9094 mm (if minus (list 'not mm) mm)
9095 term rest)
9096 (push mm tagsmatcher))
9097 (push (if (> (length tagsmatcher) 1)
9098 (cons 'and tagsmatcher)
9099 (car tagsmatcher))
9100 orlist)
9101 (setq tagsmatcher nil))
9102 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
9103 (setq tagsmatcher
9104 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
9105 ;; Make the todo matcher
9106 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
9107 (setq todomatcher t)
9108 (setq orterms (org-split-string todomatch "|") orlist nil)
9109 (while (setq term (pop orterms))
9110 (while (string-match re term)
9111 (setq minus (and (match-end 1)
9112 (equal (match-string 1 term) "-"))
9113 kwd (match-string 2 term)
9114 re-p (equal (string-to-char kwd) ?{)
9115 term (substring term (match-end 0))
9116 mm (if re-p
9117 `(string-match ,(substring kwd 1 -1) todo)
9118 (list 'equal 'todo kwd))
9119 mm (if minus (list 'not mm) mm))
9120 (push mm todomatcher))
9121 (push (if (> (length todomatcher) 1)
9122 (cons 'and todomatcher)
9123 (car todomatcher))
9124 orlist)
9125 (setq todomatcher nil))
9126 (setq todomatcher (if (> (length orlist) 1)
9127 (cons 'or orlist) (car orlist))))
9129 ;; Return the string and lisp forms of the matcher
9130 (setq matcher (if todomatcher
9131 (list 'and tagsmatcher todomatcher)
9132 tagsmatcher))
9133 (cons match0 matcher)))
9135 (defun org-op-to-function (op &optional stringp)
9136 "Turn an operator into the appropriate function."
9137 (setq op
9138 (cond
9139 ((equal op "<" ) '(< string< org-time<))
9140 ((equal op ">" ) '(> org-string> org-time>))
9141 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
9142 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
9143 ((member op '("=" "==")) '(= string= org-time=))
9144 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
9145 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
9147 (defun org<> (a b) (not (= a b)))
9148 (defun org-string<= (a b) (or (string= a b) (string< a b)))
9149 (defun org-string>= (a b) (not (string< a b)))
9150 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
9151 (defun org-string<> (a b) (not (string= a b)))
9152 (defun org-time= (a b) (= (org-2ft a) (org-2ft b)))
9153 (defun org-time< (a b) (< (org-2ft a) (org-2ft b)))
9154 (defun org-time<= (a b) (<= (org-2ft a) (org-2ft b)))
9155 (defun org-time> (a b) (> (org-2ft a) (org-2ft b)))
9156 (defun org-time>= (a b) (>= (org-2ft a) (org-2ft b)))
9157 (defun org-time<> (a b) (org<> (org-2ft a) (org-2ft b)))
9158 (defun org-2ft (s)
9159 "Convert S to a floating point time.
9160 If S is already a number, just return it. If it is a string, parse
9161 it as a time string and apply `float-time' to it. f S is nil, just return 0."
9162 (cond
9163 ((numberp s) s)
9164 ((stringp s)
9165 (condition-case nil
9166 (float-time (apply 'encode-time (org-parse-time-string s)))
9167 (error 0.)))
9168 (t 0.)))
9170 (defun org-matcher-time (s)
9171 (cond
9172 ((equal s "<now>") (float-time))
9173 ((equal s "<today>")
9174 (float-time (append '(0 0 0) (nthcdr 3 (decode-time)))))
9175 (t (org-2ft s))))
9177 (defun org-match-any-p (re list)
9178 "Does re match any element of list?"
9179 (setq list (mapcar (lambda (x) (string-match re x)) list))
9180 (delq nil list))
9182 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
9183 (defvar org-tags-overlay (org-make-overlay 1 1))
9184 (org-detach-overlay org-tags-overlay)
9186 (defun org-get-local-tags-at (&optional pos)
9187 "Get a list of tags defined in the current headline."
9188 (org-get-tags-at pos 'local))
9190 (defun org-get-local-tags ()
9191 "Get a list of tags defined in the current headline."
9192 (org-get-tags-at nil 'local))
9194 (defun org-get-tags-at (&optional pos local)
9195 "Get a list of all headline tags applicable at POS.
9196 POS defaults to point. If tags are inherited, the list contains
9197 the targets in the same sequence as the headlines appear, i.e.
9198 the tags of the current headline come last.
9199 When LOCAL is non-nil, only return tags from the current headline,
9200 ignore inherited ones."
9201 (interactive)
9202 (let (tags ltags lastpos parent)
9203 (save-excursion
9204 (save-restriction
9205 (widen)
9206 (goto-char (or pos (point)))
9207 (save-match-data
9208 (catch 'done
9209 (condition-case nil
9210 (progn
9211 (org-back-to-heading t)
9212 (while (not (equal lastpos (point)))
9213 (setq lastpos (point))
9214 (when (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
9215 (setq ltags (org-split-string
9216 (org-match-string-no-properties 1) ":"))
9217 (setq tags (append
9218 (if parent
9219 (org-remove-uniherited-tags ltags)
9220 ltags)
9221 tags)))
9222 (or org-use-tag-inheritance (throw 'done t))
9223 (if local (throw 'done t))
9224 (org-up-heading-all 1)
9225 (setq parent t)))
9226 (error nil)))))
9227 (append (org-remove-uniherited-tags org-file-tags) tags))))
9229 (defun org-toggle-tag (tag &optional onoff)
9230 "Toggle the tag TAG for the current line.
9231 If ONOFF is `on' or `off', don't toggle but set to this state."
9232 (unless (org-on-heading-p t) (error "Not on headling"))
9233 (let (res current)
9234 (save-excursion
9235 (beginning-of-line)
9236 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
9237 (point-at-eol) t)
9238 (progn
9239 (setq current (match-string 1))
9240 (replace-match ""))
9241 (setq current ""))
9242 (setq current (nreverse (org-split-string current ":")))
9243 (cond
9244 ((eq onoff 'on)
9245 (setq res t)
9246 (or (member tag current) (push tag current)))
9247 ((eq onoff 'off)
9248 (or (not (member tag current)) (setq current (delete tag current))))
9249 (t (if (member tag current)
9250 (setq current (delete tag current))
9251 (setq res t)
9252 (push tag current))))
9253 (end-of-line 1)
9254 (if current
9255 (progn
9256 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
9257 (org-set-tags nil t))
9258 (delete-horizontal-space))
9259 (run-hooks 'org-after-tags-change-hook))
9260 res))
9262 (defun org-align-tags-here (to-col)
9263 ;; Assumes that this is a headline
9264 (let ((pos (point)) (col (current-column)) ncol tags-l p)
9265 (beginning-of-line 1)
9266 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9267 (< pos (match-beginning 2)))
9268 (progn
9269 (setq tags-l (- (match-end 2) (match-beginning 2)))
9270 (goto-char (match-beginning 1))
9271 (insert " ")
9272 (delete-region (point) (1+ (match-beginning 2)))
9273 (setq ncol (max (1+ (current-column))
9274 (1+ col)
9275 (if (> to-col 0)
9276 to-col
9277 (- (abs to-col) tags-l))))
9278 (setq p (point))
9279 (insert (make-string (- ncol (current-column)) ?\ ))
9280 (setq ncol (current-column))
9281 (when indent-tabs-mode (tabify p (point-at-eol)))
9282 (org-move-to-column (min ncol col) t))
9283 (goto-char pos))))
9285 (defun org-set-tags-command (&optional arg just-align)
9286 "Call the set-tags command for the current entry."
9287 (interactive "P")
9288 (if (org-on-heading-p)
9289 (org-set-tags arg just-align)
9290 (save-excursion
9291 (org-back-to-heading t)
9292 (org-set-tags arg just-align))))
9294 (defun org-set-tags (&optional arg just-align)
9295 "Set the tags for the current headline.
9296 With prefix ARG, realign all tags in headings in the current buffer."
9297 (interactive "P")
9298 (let* ((re (concat "^" outline-regexp))
9299 (current (org-get-tags-string))
9300 (col (current-column))
9301 (org-setting-tags t)
9302 table current-tags inherited-tags ; computed below when needed
9303 tags p0 c0 c1 rpl)
9304 (if arg
9305 (save-excursion
9306 (goto-char (point-min))
9307 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
9308 (while (re-search-forward re nil t)
9309 (org-set-tags nil t)
9310 (end-of-line 1)))
9311 (message "All tags realigned to column %d" org-tags-column))
9312 (if just-align
9313 (setq tags current)
9314 ;; Get a new set of tags from the user
9315 (save-excursion
9316 (setq table (or org-tag-alist (org-get-buffer-tags))
9317 org-last-tags-completion-table table
9318 current-tags (org-split-string current ":")
9319 inherited-tags (nreverse
9320 (nthcdr (length current-tags)
9321 (nreverse (org-get-tags-at))))
9322 tags
9323 (if (or (eq t org-use-fast-tag-selection)
9324 (and org-use-fast-tag-selection
9325 (delq nil (mapcar 'cdr table))))
9326 (org-fast-tag-selection
9327 current-tags inherited-tags table
9328 (if org-fast-tag-selection-include-todo org-todo-key-alist))
9329 (let ((org-add-colon-after-tag-completion t))
9330 (org-trim
9331 (org-without-partial-completion
9332 (completing-read "Tags: " 'org-tags-completion-function
9333 nil nil current 'org-tags-history)))))))
9334 (while (string-match "[-+&]+" tags)
9335 ;; No boolean logic, just a list
9336 (setq tags (replace-match ":" t t tags))))
9338 (if (string-match "\\`[\t ]*\\'" tags)
9339 (setq tags "")
9340 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
9341 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
9343 ;; Insert new tags at the correct column
9344 (beginning-of-line 1)
9345 (cond
9346 ((and (equal current "") (equal tags "")))
9347 ((re-search-forward
9348 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
9349 (point-at-eol) t)
9350 (if (equal tags "")
9351 (setq rpl "")
9352 (goto-char (match-beginning 0))
9353 (setq c0 (current-column) p0 (point)
9354 c1 (max (1+ c0) (if (> org-tags-column 0)
9355 org-tags-column
9356 (- (- org-tags-column) (length tags))))
9357 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
9358 (replace-match rpl t t)
9359 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
9360 tags)
9361 (t (error "Tags alignment failed")))
9362 (org-move-to-column col)
9363 (unless just-align
9364 (run-hooks 'org-after-tags-change-hook)))))
9366 (defun org-change-tag-in-region (beg end tag off)
9367 "Add or remove TAG for each entry in the region.
9368 This works in the agenda, and also in an org-mode buffer."
9369 (interactive
9370 (list (region-beginning) (region-end)
9371 (let ((org-last-tags-completion-table
9372 (if (org-mode-p)
9373 (org-get-buffer-tags)
9374 (org-global-tags-completion-table))))
9375 (completing-read
9376 "Tag: " 'org-tags-completion-function nil nil nil
9377 'org-tags-history))
9378 (progn
9379 (message "[s]et or [r]emove? ")
9380 (equal (read-char-exclusive) ?r))))
9381 (if (fboundp 'deactivate-mark) (deactivate-mark))
9382 (let ((agendap (equal major-mode 'org-agenda-mode))
9383 l1 l2 m buf pos newhead (cnt 0))
9384 (goto-char end)
9385 (setq l2 (1- (org-current-line)))
9386 (goto-char beg)
9387 (setq l1 (org-current-line))
9388 (loop for l from l1 to l2 do
9389 (goto-line l)
9390 (setq m (get-text-property (point) 'org-hd-marker))
9391 (when (or (and (org-mode-p) (org-on-heading-p))
9392 (and agendap m))
9393 (setq buf (if agendap (marker-buffer m) (current-buffer))
9394 pos (if agendap m (point)))
9395 (with-current-buffer buf
9396 (save-excursion
9397 (save-restriction
9398 (goto-char pos)
9399 (setq cnt (1+ cnt))
9400 (org-toggle-tag tag (if off 'off 'on))
9401 (setq newhead (org-get-heading)))))
9402 (and agendap (org-agenda-change-all-lines newhead m))))
9403 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
9405 (defun org-tags-completion-function (string predicate &optional flag)
9406 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
9407 (confirm (lambda (x) (stringp (car x)))))
9408 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
9409 (setq s1 (match-string 1 string)
9410 s2 (match-string 2 string))
9411 (setq s1 "" s2 string))
9412 (cond
9413 ((eq flag nil)
9414 ;; try completion
9415 (setq rtn (try-completion s2 ctable confirm))
9416 (if (stringp rtn)
9417 (setq rtn
9418 (concat s1 s2 (substring rtn (length s2))
9419 (if (and org-add-colon-after-tag-completion
9420 (assoc rtn ctable))
9421 ":" ""))))
9422 rtn)
9423 ((eq flag t)
9424 ;; all-completions
9425 (all-completions s2 ctable confirm)
9427 ((eq flag 'lambda)
9428 ;; exact match?
9429 (assoc s2 ctable)))
9432 (defun org-fast-tag-insert (kwd tags face &optional end)
9433 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
9434 (insert (format "%-12s" (concat kwd ":"))
9435 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
9436 (or end "")))
9438 (defun org-fast-tag-show-exit (flag)
9439 (save-excursion
9440 (goto-line 3)
9441 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
9442 (replace-match ""))
9443 (when flag
9444 (end-of-line 1)
9445 (org-move-to-column (- (window-width) 19) t)
9446 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
9448 (defun org-set-current-tags-overlay (current prefix)
9449 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
9450 (if (featurep 'xemacs)
9451 (org-overlay-display org-tags-overlay (concat prefix s)
9452 'secondary-selection)
9453 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
9454 (org-overlay-display org-tags-overlay (concat prefix s)))))
9456 (defun org-fast-tag-selection (current inherited table &optional todo-table)
9457 "Fast tag selection with single keys.
9458 CURRENT is the current list of tags in the headline, INHERITED is the
9459 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
9460 possibly with grouping information. TODO-TABLE is a similar table with
9461 TODO keywords, should these have keys assigned to them.
9462 If the keys are nil, a-z are automatically assigned.
9463 Returns the new tags string, or nil to not change the current settings."
9464 (let* ((fulltable (append table todo-table))
9465 (maxlen (apply 'max (mapcar
9466 (lambda (x)
9467 (if (stringp (car x)) (string-width (car x)) 0))
9468 fulltable)))
9469 (buf (current-buffer))
9470 (expert (eq org-fast-tag-selection-single-key 'expert))
9471 (buffer-tags nil)
9472 (fwidth (+ maxlen 3 1 3))
9473 (ncol (/ (- (window-width) 4) fwidth))
9474 (i-face 'org-done)
9475 (c-face 'org-todo)
9476 tg cnt e c char c1 c2 ntable tbl rtn
9477 ov-start ov-end ov-prefix
9478 (exit-after-next org-fast-tag-selection-single-key)
9479 (done-keywords org-done-keywords)
9480 groups ingroup)
9481 (save-excursion
9482 (beginning-of-line 1)
9483 (if (looking-at
9484 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9485 (setq ov-start (match-beginning 1)
9486 ov-end (match-end 1)
9487 ov-prefix "")
9488 (setq ov-start (1- (point-at-eol))
9489 ov-end (1+ ov-start))
9490 (skip-chars-forward "^\n\r")
9491 (setq ov-prefix
9492 (concat
9493 (buffer-substring (1- (point)) (point))
9494 (if (> (current-column) org-tags-column)
9496 (make-string (- org-tags-column (current-column)) ?\ ))))))
9497 (org-move-overlay org-tags-overlay ov-start ov-end)
9498 (save-window-excursion
9499 (if expert
9500 (set-buffer (get-buffer-create " *Org tags*"))
9501 (delete-other-windows)
9502 (split-window-vertically)
9503 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
9504 (erase-buffer)
9505 (org-set-local 'org-done-keywords done-keywords)
9506 (org-fast-tag-insert "Inherited" inherited i-face "\n")
9507 (org-fast-tag-insert "Current" current c-face "\n\n")
9508 (org-fast-tag-show-exit exit-after-next)
9509 (org-set-current-tags-overlay current ov-prefix)
9510 (setq tbl fulltable char ?a cnt 0)
9511 (while (setq e (pop tbl))
9512 (cond
9513 ((equal e '(:startgroup))
9514 (push '() groups) (setq ingroup t)
9515 (when (not (= cnt 0))
9516 (setq cnt 0)
9517 (insert "\n"))
9518 (insert "{ "))
9519 ((equal e '(:endgroup))
9520 (setq ingroup nil cnt 0)
9521 (insert "}\n"))
9523 (setq tg (car e) c2 nil)
9524 (if (cdr e)
9525 (setq c (cdr e))
9526 ;; automatically assign a character.
9527 (setq c1 (string-to-char
9528 (downcase (substring
9529 tg (if (= (string-to-char tg) ?@) 1 0)))))
9530 (if (or (rassoc c1 ntable) (rassoc c1 table))
9531 (while (or (rassoc char ntable) (rassoc char table))
9532 (setq char (1+ char)))
9533 (setq c2 c1))
9534 (setq c (or c2 char)))
9535 (if ingroup (push tg (car groups)))
9536 (setq tg (org-add-props tg nil 'face
9537 (cond
9538 ((not (assoc tg table))
9539 (org-get-todo-face tg))
9540 ((member tg current) c-face)
9541 ((member tg inherited) i-face)
9542 (t nil))))
9543 (if (and (= cnt 0) (not ingroup)) (insert " "))
9544 (insert "[" c "] " tg (make-string
9545 (- fwidth 4 (length tg)) ?\ ))
9546 (push (cons tg c) ntable)
9547 (when (= (setq cnt (1+ cnt)) ncol)
9548 (insert "\n")
9549 (if ingroup (insert " "))
9550 (setq cnt 0)))))
9551 (setq ntable (nreverse ntable))
9552 (insert "\n")
9553 (goto-char (point-min))
9554 (if (not expert) (org-fit-window-to-buffer))
9555 (setq rtn
9556 (catch 'exit
9557 (while t
9558 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
9559 (if groups " [!] no groups" " [!]groups")
9560 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
9561 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9562 (cond
9563 ((= c ?\r) (throw 'exit t))
9564 ((= c ?!)
9565 (setq groups (not groups))
9566 (goto-char (point-min))
9567 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
9568 ((= c ?\C-c)
9569 (if (not expert)
9570 (org-fast-tag-show-exit
9571 (setq exit-after-next (not exit-after-next)))
9572 (setq expert nil)
9573 (delete-other-windows)
9574 (split-window-vertically)
9575 (org-switch-to-buffer-other-window " *Org tags*")
9576 (org-fit-window-to-buffer)))
9577 ((or (= c ?\C-g)
9578 (and (= c ?q) (not (rassoc c ntable))))
9579 (org-detach-overlay org-tags-overlay)
9580 (setq quit-flag t))
9581 ((= c ?\ )
9582 (setq current nil)
9583 (if exit-after-next (setq exit-after-next 'now)))
9584 ((= c ?\t)
9585 (condition-case nil
9586 (setq tg (completing-read
9587 "Tag: "
9588 (or buffer-tags
9589 (with-current-buffer buf
9590 (org-get-buffer-tags)))))
9591 (quit (setq tg "")))
9592 (when (string-match "\\S-" tg)
9593 (add-to-list 'buffer-tags (list tg))
9594 (if (member tg current)
9595 (setq current (delete tg current))
9596 (push tg current)))
9597 (if exit-after-next (setq exit-after-next 'now)))
9598 ((setq e (rassoc c todo-table) tg (car e))
9599 (with-current-buffer buf
9600 (save-excursion (org-todo tg)))
9601 (if exit-after-next (setq exit-after-next 'now)))
9602 ((setq e (rassoc c ntable) tg (car e))
9603 (if (member tg current)
9604 (setq current (delete tg current))
9605 (loop for g in groups do
9606 (if (member tg g)
9607 (mapc (lambda (x)
9608 (setq current (delete x current)))
9609 g)))
9610 (push tg current))
9611 (if exit-after-next (setq exit-after-next 'now))))
9613 ;; Create a sorted list
9614 (setq current
9615 (sort current
9616 (lambda (a b)
9617 (assoc b (cdr (memq (assoc a ntable) ntable))))))
9618 (if (eq exit-after-next 'now) (throw 'exit t))
9619 (goto-char (point-min))
9620 (beginning-of-line 2)
9621 (delete-region (point) (point-at-eol))
9622 (org-fast-tag-insert "Current" current c-face)
9623 (org-set-current-tags-overlay current ov-prefix)
9624 (while (re-search-forward
9625 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
9626 (setq tg (match-string 1))
9627 (add-text-properties
9628 (match-beginning 1) (match-end 1)
9629 (list 'face
9630 (cond
9631 ((member tg current) c-face)
9632 ((member tg inherited) i-face)
9633 (t (get-text-property (match-beginning 1) 'face))))))
9634 (goto-char (point-min)))))
9635 (org-detach-overlay org-tags-overlay)
9636 (if rtn
9637 (mapconcat 'identity current ":")
9638 nil))))
9640 (defun org-get-tags-string ()
9641 "Get the TAGS string in the current headline."
9642 (unless (org-on-heading-p t)
9643 (error "Not on a heading"))
9644 (save-excursion
9645 (beginning-of-line 1)
9646 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9647 (org-match-string-no-properties 1)
9648 "")))
9650 (defun org-get-tags ()
9651 "Get the list of tags specified in the current headline."
9652 (org-split-string (org-get-tags-string) ":"))
9654 (defun org-get-buffer-tags ()
9655 "Get a table of all tags used in the buffer, for completion."
9656 (let (tags)
9657 (save-excursion
9658 (goto-char (point-min))
9659 (while (re-search-forward
9660 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
9661 (when (equal (char-after (point-at-bol 0)) ?*)
9662 (mapc (lambda (x) (add-to-list 'tags x))
9663 (org-split-string (org-match-string-no-properties 1) ":")))))
9664 (mapcar 'list tags)))
9666 ;;;; The mapping API
9668 ;;;###autoload
9669 (defun org-map-entries (func &optional match scope &rest skip)
9670 "Call FUNC at each headline selected by MATCH in SCOPE.
9672 FUNC is a function or a lisp form. The function will be called without
9673 arguments, with the cursor positioned at the beginning of the headline.
9674 The return values of all calls to the function will be collected and
9675 returned as a list.
9677 MATCH is a tags/property/todo match as it is used in the agenda tags view.
9678 Only headlines that are matched by this query will be considered during
9679 the iteration. When MATCH is nil or t, all headlines will be
9680 visited by the iteration.
9682 SCOPE determines the scope of this command. It can be any of:
9684 nil The current buffer, respecting the restriction if any
9685 tree The subtree started with the entry at point
9686 file The current buffer, without restriction
9687 file-with-archives
9688 The current buffer, and any archives associated with it
9689 agenda All agenda files
9690 agenda-with-archives
9691 All agenda files with any archive files associated with them
9692 \(file1 file2 ...)
9693 If this is a list, all files in the list will be scanned
9695 The remaining args are treated as settings for the skipping facilities of
9696 the scanner. The following items can be given here:
9698 archive skip trees with the archive tag.
9699 comment skip trees with the COMMENT keyword
9700 function or Emacs Lisp form:
9701 will be used as value for `org-agenda-skip-function', so whenever
9702 the the function returns t, FUNC will not be called for that
9703 entry and search will continue from the point where the
9704 function leaves it."
9705 (let* ((org-agenda-archives-mode nil) ; just to make sure
9706 (org-agenda-skip-archived-trees (memq 'archive skip))
9707 (org-agenda-skip-comment-trees (memq 'comment skip))
9708 (org-agenda-skip-function
9709 (car (org-delete-all '(comment archive) skip)))
9710 (org-tags-match-list-sublevels t)
9711 matcher pos file
9712 org-todo-keywords-for-agenda
9713 org-done-keywords-for-agenda
9714 org-todo-keyword-alist-for-agenda
9715 org-tag-alist-for-agenda)
9717 (cond
9718 ((eq match t) (setq matcher t))
9719 ((eq match nil) (setq matcher t))
9720 (t (setq matcher (if match (org-make-tags-matcher match) t))))
9722 (when (eq scope 'tree)
9723 (org-back-to-heading t)
9724 (org-narrow-to-subtree)
9725 (setq scope nil))
9727 (if (not scope)
9728 (progn
9729 (org-prepare-agenda-buffers
9730 (list (buffer-file-name (current-buffer))))
9731 (org-scan-tags func matcher))
9732 ;; Get the right scope
9733 (setq pos (point))
9734 (cond
9735 ((and scope (listp scope) (symbolp (car scope)))
9736 (setq scope (eval scope)))
9737 ((eq scope 'agenda)
9738 (setq scope (org-agenda-files t)))
9739 ((eq scope 'agenda-with-archives)
9740 (setq scope (org-agenda-files t))
9741 (setq scope (org-add-archive-files scope)))
9742 ((eq scope 'file)
9743 (setq scope (list (buffer-file-name))))
9744 ((eq scope 'file-with-archives)
9745 (setq scope (org-add-archive-files (list (buffer-file-name))))))
9746 (org-prepare-agenda-buffers scope)
9747 (while (setq file (pop scope))
9748 (with-current-buffer (org-find-base-buffer-visiting file)
9749 (save-excursion
9750 (save-restriction
9751 (widen)
9752 (goto-char (point-min))
9753 (org-scan-tags func matcher))))))))
9755 ;;;; Properties
9757 ;;; Setting and retrieving properties
9759 (defconst org-special-properties
9760 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
9761 "TIMESTAMP" "TIMESTAMP_IA")
9762 "The special properties valid in Org-mode.
9764 These are properties that are not defined in the property drawer,
9765 but in some other way.")
9767 (defconst org-default-properties
9768 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
9769 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
9770 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
9771 "EXPORT_FILE_NAME" "EXPORT_TITLE")
9772 "Some properties that are used by Org-mode for various purposes.
9773 Being in this list makes sure that they are offered for completion.")
9775 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
9776 "Regular expression matching the first line of a property drawer.")
9778 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
9779 "Regular expression matching the first line of a property drawer.")
9781 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
9782 "Regular expression matching the first line of a property drawer.")
9784 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
9785 "Regular expression matching the first line of a property drawer.")
9787 (defconst org-property-drawer-re
9788 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
9789 org-property-end-re "\\)\n?")
9790 "Matches an entire property drawer.")
9792 (defconst org-clock-drawer-re
9793 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
9794 org-property-end-re "\\)\n?")
9795 "Matches an entire clock drawer.")
9797 (defun org-property-action ()
9798 "Do an action on properties."
9799 (interactive)
9800 (let (c)
9801 (org-at-property-p)
9802 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
9803 (setq c (read-char-exclusive))
9804 (cond
9805 ((equal c ?s)
9806 (call-interactively 'org-set-property))
9807 ((equal c ?d)
9808 (call-interactively 'org-delete-property))
9809 ((equal c ?D)
9810 (call-interactively 'org-delete-property-globally))
9811 ((equal c ?c)
9812 (call-interactively 'org-compute-property-at-point))
9813 (t (error "No such property action %c" c)))))
9815 (defun org-at-property-p ()
9816 "Is the cursor in a property line?"
9817 ;; FIXME: Does not check if we are actually in the drawer.
9818 ;; FIXME: also returns true on any drawers.....
9819 ;; This is used by C-c C-c for property action.
9820 (save-excursion
9821 (beginning-of-line 1)
9822 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
9824 (defun org-get-property-block (&optional beg end force)
9825 "Return the (beg . end) range of the body of the property drawer.
9826 BEG and END can be beginning and end of subtree, if not given
9827 they will be found.
9828 If the drawer does not exist and FORCE is non-nil, create the drawer."
9829 (catch 'exit
9830 (save-excursion
9831 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
9832 (end (or end (progn (outline-next-heading) (point)))))
9833 (goto-char beg)
9834 (if (re-search-forward org-property-start-re end t)
9835 (setq beg (1+ (match-end 0)))
9836 (if force
9837 (save-excursion
9838 (org-insert-property-drawer)
9839 (setq end (progn (outline-next-heading) (point))))
9840 (throw 'exit nil))
9841 (goto-char beg)
9842 (if (re-search-forward org-property-start-re end t)
9843 (setq beg (1+ (match-end 0)))))
9844 (if (re-search-forward org-property-end-re end t)
9845 (setq end (match-beginning 0))
9846 (or force (throw 'exit nil))
9847 (goto-char beg)
9848 (setq end beg)
9849 (org-indent-line-function)
9850 (insert ":END:\n"))
9851 (cons beg end)))))
9853 (defun org-entry-properties (&optional pom which)
9854 "Get all properties of the entry at point-or-marker POM.
9855 This includes the TODO keyword, the tags, time strings for deadline,
9856 scheduled, and clocking, and any additional properties defined in the
9857 entry. The return value is an alist, keys may occur multiple times
9858 if the property key was used several times.
9859 POM may also be nil, in which case the current entry is used.
9860 If WHICH is nil or `all', get all properties. If WHICH is
9861 `special' or `standard', only get that subclass."
9862 (setq which (or which 'all))
9863 (org-with-point-at pom
9864 (let ((clockstr (substring org-clock-string 0 -1))
9865 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
9866 beg end range props sum-props key value string clocksum)
9867 (save-excursion
9868 (when (condition-case nil (org-back-to-heading t) (error nil))
9869 (setq beg (point))
9870 (setq sum-props (get-text-property (point) 'org-summaries))
9871 (setq clocksum (get-text-property (point) :org-clock-minutes))
9872 (outline-next-heading)
9873 (setq end (point))
9874 (when (memq which '(all special))
9875 ;; Get the special properties, like TODO and tags
9876 (goto-char beg)
9877 (when (and (looking-at org-todo-line-regexp) (match-end 2))
9878 (push (cons "TODO" (org-match-string-no-properties 2)) props))
9879 (when (looking-at org-priority-regexp)
9880 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
9881 (when (and (setq value (org-get-tags-string))
9882 (string-match "\\S-" value))
9883 (push (cons "TAGS" value) props))
9884 (when (setq value (org-get-tags-at))
9885 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
9886 props))
9887 (while (re-search-forward org-maybe-keyword-time-regexp end t)
9888 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
9889 string (if (equal key clockstr)
9890 (org-no-properties
9891 (org-trim
9892 (buffer-substring
9893 (match-beginning 3) (goto-char (point-at-eol)))))
9894 (substring (org-match-string-no-properties 3) 1 -1)))
9895 (unless key
9896 (if (= (char-after (match-beginning 3)) ?\[)
9897 (setq key "TIMESTAMP_IA")
9898 (setq key "TIMESTAMP")))
9899 (when (or (equal key clockstr) (not (assoc key props)))
9900 (push (cons key string) props)))
9904 (when (memq which '(all standard))
9905 ;; Get the standard properties, like :PORP: ...
9906 (setq range (org-get-property-block beg end))
9907 (when range
9908 (goto-char (car range))
9909 (while (re-search-forward
9910 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
9911 (cdr range) t)
9912 (setq key (org-match-string-no-properties 1)
9913 value (org-trim (or (org-match-string-no-properties 2) "")))
9914 (unless (member key excluded)
9915 (push (cons key (or value "")) props)))))
9916 (if clocksum
9917 (push (cons "CLOCKSUM"
9918 (org-columns-number-to-string (/ (float clocksum) 60.)
9919 'add_times))
9920 props))
9921 (unless (assoc "CATEGORY" props)
9922 (setq value (or (org-get-category)
9923 (progn (org-refresh-category-properties)
9924 (org-get-category))))
9925 (push (cons "CATEGORY" value) props))
9926 (append sum-props (nreverse props)))))))
9928 (defun org-entry-get (pom property &optional inherit)
9929 "Get value of PROPERTY for entry at point-or-marker POM.
9930 If INHERIT is non-nil and the entry does not have the property,
9931 then also check higher levels of the hierarchy.
9932 If INHERIT is the symbol `selective', use inheritance only if the setting
9933 in `org-use-property-inheritance' selects PROPERTY for inheritance.
9934 If the property is present but empty, the return value is the empty string.
9935 If the property is not present at all, nil is returned."
9936 (org-with-point-at pom
9937 (if (and inherit (if (eq inherit 'selective)
9938 (org-property-inherit-p property)
9940 (org-entry-get-with-inheritance property)
9941 (if (member property org-special-properties)
9942 ;; We need a special property. Use brute force, get all properties.
9943 (cdr (assoc property (org-entry-properties nil 'special)))
9944 (let ((range (org-get-property-block)))
9945 (if (and range
9946 (goto-char (car range))
9947 (re-search-forward
9948 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
9949 (cdr range) t))
9950 ;; Found the property, return it.
9951 (if (match-end 1)
9952 (org-match-string-no-properties 1)
9953 "")))))))
9955 (defun org-property-or-variable-value (var &optional inherit)
9956 "Check if there is a property fixing the value of VAR.
9957 If yes, return this value. If not, return the current value of the variable."
9958 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
9959 (if (and prop (stringp prop) (string-match "\\S-" prop))
9960 (read prop)
9961 (symbol-value var))))
9963 (defun org-entry-delete (pom property)
9964 "Delete the property PROPERTY from entry at point-or-marker POM."
9965 (org-with-point-at pom
9966 (if (member property org-special-properties)
9967 nil ; cannot delete these properties.
9968 (let ((range (org-get-property-block)))
9969 (if (and range
9970 (goto-char (car range))
9971 (re-search-forward
9972 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
9973 (cdr range) t))
9974 (progn
9975 (delete-region (match-beginning 0) (1+ (point-at-eol)))
9977 nil)))))
9979 ;; Multi-values properties are properties that contain multiple values
9980 ;; These values are assumed to be single words, separated by whitespace.
9981 (defun org-entry-add-to-multivalued-property (pom property value)
9982 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
9983 (let* ((old (org-entry-get pom property))
9984 (values (and old (org-split-string old "[ \t]"))))
9985 (setq value (org-entry-protect-space value))
9986 (unless (member value values)
9987 (setq values (cons value values))
9988 (org-entry-put pom property
9989 (mapconcat 'identity values " ")))))
9991 (defun org-entry-remove-from-multivalued-property (pom property value)
9992 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
9993 (let* ((old (org-entry-get pom property))
9994 (values (and old (org-split-string old "[ \t]"))))
9995 (setq value (org-entry-protect-space value))
9996 (when (member value values)
9997 (setq values (delete value values))
9998 (org-entry-put pom property
9999 (mapconcat 'identity values " ")))))
10001 (defun org-entry-member-in-multivalued-property (pom property value)
10002 "Is VALUE one of 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 (member value values)))
10008 (defun org-entry-get-multivalued-property (pom property)
10009 "Return a list of values in a multivalued property."
10010 (let* ((value (org-entry-get pom property))
10011 (values (and value (org-split-string value "[ \t]"))))
10012 (mapcar 'org-entry-restore-space values)))
10014 (defun org-entry-put-multivalued-property (pom property &rest values)
10015 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
10016 VALUES should be a list of strings. Spaces will be protected."
10017 (org-entry-put pom property
10018 (mapconcat 'org-entry-protect-space values " "))
10019 (let* ((value (org-entry-get pom property))
10020 (values (and value (org-split-string value "[ \t]"))))
10021 (mapcar 'org-entry-restore-space values)))
10023 (defun org-entry-protect-space (s)
10024 "Protect spaces and newline in string S."
10025 (while (string-match " " s)
10026 (setq s (replace-match "%20" t t s)))
10027 (while (string-match "\n" s)
10028 (setq s (replace-match "%0A" t t s)))
10031 (defun org-entry-restore-space (s)
10032 "Restore spaces and newline in string S."
10033 (while (string-match "%20" s)
10034 (setq s (replace-match " " t t s)))
10035 (while (string-match "%0A" s)
10036 (setq s (replace-match "\n" t t s)))
10039 (defvar org-entry-property-inherited-from (make-marker)
10040 "Marker pointing to the entry from where a proerty was inherited.
10041 Each call to `org-entry-get-with-inheritance' will set this marker to the
10042 location of the entry where the inheriance search matched. If there was
10043 no match, the marker will point nowhere.
10044 Note that also `org-entry-get' calls this function, if the INHERIT flag
10045 is set.")
10047 (defun org-entry-get-with-inheritance (property)
10048 "Get entry property, and search higher levels if not present."
10049 (move-marker org-entry-property-inherited-from nil)
10050 (let (tmp)
10051 (save-excursion
10052 (save-restriction
10053 (widen)
10054 (catch 'ex
10055 (while t
10056 (when (setq tmp (org-entry-get nil property))
10057 (org-back-to-heading t)
10058 (move-marker org-entry-property-inherited-from (point))
10059 (throw 'ex tmp))
10060 (or (org-up-heading-safe) (throw 'ex nil)))))
10061 (or tmp
10062 (cdr (assoc property org-file-properties))
10063 (cdr (assoc property org-global-properties))
10064 (cdr (assoc property org-global-properties-fixed))))))
10066 (defun org-entry-put (pom property value)
10067 "Set PROPERTY to VALUE for entry at point-or-marker POM."
10068 (org-with-point-at pom
10069 (org-back-to-heading t)
10070 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
10071 range)
10072 (cond
10073 ((equal property "TODO")
10074 (when (and (stringp value) (string-match "\\S-" value)
10075 (not (member value org-todo-keywords-1)))
10076 (error "\"%s\" is not a valid TODO state" value))
10077 (if (or (not value)
10078 (not (string-match "\\S-" value)))
10079 (setq value 'none))
10080 (org-todo value)
10081 (org-set-tags nil 'align))
10082 ((equal property "PRIORITY")
10083 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
10084 (string-to-char value) ?\ ))
10085 (org-set-tags nil 'align))
10086 ((equal property "SCHEDULED")
10087 (if (re-search-forward org-scheduled-time-regexp end t)
10088 (cond
10089 ((eq value 'earlier) (org-timestamp-change -1 'day))
10090 ((eq value 'later) (org-timestamp-change 1 'day))
10091 (t (call-interactively 'org-schedule)))
10092 (call-interactively 'org-schedule)))
10093 ((equal property "DEADLINE")
10094 (if (re-search-forward org-deadline-time-regexp end t)
10095 (cond
10096 ((eq value 'earlier) (org-timestamp-change -1 'day))
10097 ((eq value 'later) (org-timestamp-change 1 'day))
10098 (t (call-interactively 'org-deadline)))
10099 (call-interactively 'org-deadline)))
10100 ((member property org-special-properties)
10101 (error "The %s property can not yet be set with `org-entry-put'"
10102 property))
10103 (t ; a non-special property
10104 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
10105 (setq range (org-get-property-block beg end 'force))
10106 (goto-char (car range))
10107 (if (re-search-forward
10108 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
10109 (progn
10110 (delete-region (match-beginning 1) (match-end 1))
10111 (goto-char (match-beginning 1)))
10112 (goto-char (cdr range))
10113 (insert "\n")
10114 (backward-char 1)
10115 (org-indent-line-function)
10116 (insert ":" property ":"))
10117 (and value (insert " " value))
10118 (org-indent-line-function)))))))
10120 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
10121 "Get all property keys in the current buffer.
10122 With INCLUDE-SPECIALS, also list the special properties that relect things
10123 like tags and TODO state.
10124 With INCLUDE-DEFAULTS, also include properties that has special meaning
10125 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
10126 With INCLUDE-COLUMNS, also include property names given in COLUMN
10127 formats in the current buffer."
10128 (let (rtn range cfmt cols s p)
10129 (save-excursion
10130 (save-restriction
10131 (widen)
10132 (goto-char (point-min))
10133 (while (re-search-forward org-property-start-re nil t)
10134 (setq range (org-get-property-block))
10135 (goto-char (car range))
10136 (while (re-search-forward
10137 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
10138 (cdr range) t)
10139 (add-to-list 'rtn (org-match-string-no-properties 1)))
10140 (outline-next-heading))))
10142 (when include-specials
10143 (setq rtn (append org-special-properties rtn)))
10145 (when include-defaults
10146 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
10148 (when include-columns
10149 (save-excursion
10150 (save-restriction
10151 (widen)
10152 (goto-char (point-min))
10153 (while (re-search-forward
10154 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
10155 nil t)
10156 (setq cfmt (match-string 2) s 0)
10157 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
10158 cfmt s)
10159 (setq s (match-end 0)
10160 p (match-string 1 cfmt))
10161 (unless (or (equal p "ITEM")
10162 (member p org-special-properties))
10163 (add-to-list 'rtn (match-string 1 cfmt))))))))
10165 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
10167 (defun org-property-values (key)
10168 "Return a list of all values of property KEY."
10169 (save-excursion
10170 (save-restriction
10171 (widen)
10172 (goto-char (point-min))
10173 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
10174 values)
10175 (while (re-search-forward re nil t)
10176 (add-to-list 'values (org-trim (match-string 1))))
10177 (delete "" values)))))
10179 (defun org-insert-property-drawer ()
10180 "Insert a property drawer into the current entry."
10181 (interactive)
10182 (org-back-to-heading t)
10183 (looking-at outline-regexp)
10184 (let ((indent (- (match-end 0)(match-beginning 0)))
10185 (beg (point))
10186 (re (concat "^[ \t]*" org-keyword-time-regexp))
10187 end hiddenp)
10188 (outline-next-heading)
10189 (setq end (point))
10190 (goto-char beg)
10191 (while (re-search-forward re end t))
10192 (setq hiddenp (org-invisible-p))
10193 (end-of-line 1)
10194 (and (equal (char-after) ?\n) (forward-char 1))
10195 (while (looking-at "^[ \t]*\\(:CLOCK:\\|CLOCK\\|:END:\\)")
10196 (beginning-of-line 2))
10197 (org-skip-over-state-notes)
10198 (skip-chars-backward " \t\n\r")
10199 (if (eq (char-before) ?*) (forward-char 1))
10200 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
10201 (beginning-of-line 0)
10202 (org-indent-to-column indent)
10203 (beginning-of-line 2)
10204 (org-indent-to-column indent)
10205 (beginning-of-line 0)
10206 (if hiddenp
10207 (save-excursion
10208 (org-back-to-heading t)
10209 (hide-entry))
10210 (org-flag-drawer t))))
10212 (defun org-set-property (property value)
10213 "In the current entry, set PROPERTY to VALUE.
10214 When called interactively, this will prompt for a property name, offering
10215 completion on existing and default properties. And then it will prompt
10216 for a value, offering competion either on allowed values (via an inherited
10217 xxx_ALL property) or on existing values in other instances of this property
10218 in the current file."
10219 (interactive
10220 (let* ((completion-ignore-case t)
10221 (keys (org-buffer-property-keys nil t t))
10222 (prop0 (completing-read "Property: " (mapcar 'list keys)))
10223 (prop (if (member prop0 keys)
10224 prop0
10225 (or (cdr (assoc (downcase prop0)
10226 (mapcar (lambda (x) (cons (downcase x) x))
10227 keys)))
10228 prop0)))
10229 (cur (org-entry-get nil prop))
10230 (allowed (org-property-get-allowed-values nil prop 'table))
10231 (existing (mapcar 'list (org-property-values prop)))
10232 (val (if allowed
10233 (org-completing-read "Value: " allowed nil 'req-match)
10234 (org-completing-read
10235 (concat "Value" (if (and cur (string-match "\\S-" cur))
10236 (concat "[" cur "]") "")
10237 ": ")
10238 existing nil nil "" nil cur))))
10239 (list prop (if (equal val "") cur val))))
10240 (unless (equal (org-entry-get nil property) value)
10241 (org-entry-put nil property value)))
10243 (defun org-delete-property (property)
10244 "In the current entry, delete PROPERTY."
10245 (interactive
10246 (let* ((completion-ignore-case t)
10247 (prop (completing-read
10248 "Property: " (org-entry-properties nil 'standard))))
10249 (list prop)))
10250 (message "Property %s %s" property
10251 (if (org-entry-delete nil property)
10252 "deleted"
10253 "was not present in the entry")))
10255 (defun org-delete-property-globally (property)
10256 "Remove PROPERTY globally, from all entries."
10257 (interactive
10258 (let* ((completion-ignore-case t)
10259 (prop (completing-read
10260 "Globally remove property: "
10261 (mapcar 'list (org-buffer-property-keys)))))
10262 (list prop)))
10263 (save-excursion
10264 (save-restriction
10265 (widen)
10266 (goto-char (point-min))
10267 (let ((cnt 0))
10268 (while (re-search-forward
10269 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
10270 nil t)
10271 (setq cnt (1+ cnt))
10272 (replace-match ""))
10273 (message "Property \"%s\" removed from %d entries" property cnt)))))
10275 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
10277 (defun org-compute-property-at-point ()
10278 "Compute the property at point.
10279 This looks for an enclosing column format, extracts the operator and
10280 then applies it to the proerty in the column format's scope."
10281 (interactive)
10282 (unless (org-at-property-p)
10283 (error "Not at a property"))
10284 (let ((prop (org-match-string-no-properties 2)))
10285 (org-columns-get-format-and-top-level)
10286 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
10287 (error "No operator defined for property %s" prop))
10288 (org-columns-compute prop)))
10290 (defun org-property-get-allowed-values (pom property &optional table)
10291 "Get allowed values for the property PROPERTY.
10292 When TABLE is non-nil, return an alist that can directly be used for
10293 completion."
10294 (let (vals)
10295 (cond
10296 ((equal property "TODO")
10297 (setq vals (org-with-point-at pom
10298 (append org-todo-keywords-1 '("")))))
10299 ((equal property "PRIORITY")
10300 (let ((n org-lowest-priority))
10301 (while (>= n org-highest-priority)
10302 (push (char-to-string n) vals)
10303 (setq n (1- n)))))
10304 ((member property org-special-properties))
10306 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
10308 (when (and vals (string-match "\\S-" vals))
10309 (setq vals (car (read-from-string (concat "(" vals ")"))))
10310 (setq vals (mapcar (lambda (x)
10311 (cond ((stringp x) x)
10312 ((numberp x) (number-to-string x))
10313 ((symbolp x) (symbol-name x))
10314 (t "???")))
10315 vals)))))
10316 (if table (mapcar 'list vals) vals)))
10318 (defun org-property-previous-allowed-value (&optional previous)
10319 "Switch to the next allowed value for this property."
10320 (interactive)
10321 (org-property-next-allowed-value t))
10323 (defun org-property-next-allowed-value (&optional previous)
10324 "Switch to the next allowed value for this property."
10325 (interactive)
10326 (unless (org-at-property-p)
10327 (error "Not at a property"))
10328 (let* ((key (match-string 2))
10329 (value (match-string 3))
10330 (allowed (or (org-property-get-allowed-values (point) key)
10331 (and (member value '("[ ]" "[-]" "[X]"))
10332 '("[ ]" "[X]"))))
10333 nval)
10334 (unless allowed
10335 (error "Allowed values for this property have not been defined"))
10336 (if previous (setq allowed (reverse allowed)))
10337 (if (member value allowed)
10338 (setq nval (car (cdr (member value allowed)))))
10339 (setq nval (or nval (car allowed)))
10340 (if (equal nval value)
10341 (error "Only one allowed value for this property"))
10342 (org-at-property-p)
10343 (replace-match (concat " :" key ": " nval) t t)
10344 (org-indent-line-function)
10345 (beginning-of-line 1)
10346 (skip-chars-forward " \t")))
10348 (defun org-find-entry-with-id (ident)
10349 "Locate the entry that contains the ID property with exact value IDENT.
10350 IDENT can be a string, a symbol or a number, this function will search for
10351 the string representation of it.
10352 Return the position where this entry starts, or nil if there is no such entry."
10353 (let ((id (cond
10354 ((stringp ident) ident)
10355 ((symbol-name ident) (symbol-name ident))
10356 ((numberp ident) (number-to-string ident))
10357 (t (error "IDENT %s must be a string, symbol or number" ident))))
10358 (case-fold-search nil))
10359 (save-excursion
10360 (save-restriction
10361 (widen)
10362 (goto-char (point-min))
10363 (when (re-search-forward
10364 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
10365 nil t)
10366 (org-back-to-heading)
10367 (point))))))
10369 ;;;; Timestamps
10371 (defvar org-last-changed-timestamp nil)
10372 (defvar org-last-inserted-timestamp nil
10373 "The last time stamp inserted with `org-insert-time-stamp'.")
10374 (defvar org-time-was-given) ; dynamically scoped parameter
10375 (defvar org-end-time-was-given) ; dynamically scoped parameter
10376 (defvar org-ts-what) ; dynamically scoped parameter
10378 (defun org-time-stamp (arg &optional inactive)
10379 "Prompt for a date/time and insert a time stamp.
10380 If the user specifies a time like HH:MM, or if this command is called
10381 with a prefix argument, the time stamp will contain date and time.
10382 Otherwise, only the date will be included. All parts of a date not
10383 specified by the user will be filled in from the current date/time.
10384 So if you press just return without typing anything, the time stamp
10385 will represent the current date/time. If there is already a timestamp
10386 at the cursor, it will be modified."
10387 (interactive "P")
10388 (let* ((ts nil)
10389 (default-time
10390 ;; Default time is either today, or, when entering a range,
10391 ;; the range start.
10392 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
10393 (save-excursion
10394 (re-search-backward
10395 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
10396 (- (point) 20) t)))
10397 (apply 'encode-time (org-parse-time-string (match-string 1)))
10398 (current-time)))
10399 (default-input (and ts (org-get-compact-tod ts)))
10400 org-time-was-given org-end-time-was-given time)
10401 (cond
10402 ((and (org-at-timestamp-p t)
10403 (memq last-command '(org-time-stamp org-time-stamp-inactive))
10404 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
10405 (insert "--")
10406 (setq time (let ((this-command this-command))
10407 (org-read-date arg 'totime nil nil
10408 default-time default-input)))
10409 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
10410 ((org-at-timestamp-p t)
10411 (setq time (let ((this-command this-command))
10412 (org-read-date arg 'totime nil nil default-time default-input)))
10413 (when (org-at-timestamp-p t) ; just to get the match data
10414 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
10415 (replace-match "")
10416 (setq org-last-changed-timestamp
10417 (org-insert-time-stamp
10418 time (or org-time-was-given arg)
10419 inactive nil nil (list org-end-time-was-given))))
10420 (message "Timestamp updated"))
10422 (setq time (let ((this-command this-command))
10423 (org-read-date arg 'totime nil nil default-time default-input)))
10424 (org-insert-time-stamp time (or org-time-was-given arg) inactive
10425 nil nil (list org-end-time-was-given))))))
10427 ;; FIXME: can we use this for something else, like computing time differences?
10428 (defun org-get-compact-tod (s)
10429 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
10430 (let* ((t1 (match-string 1 s))
10431 (h1 (string-to-number (match-string 2 s)))
10432 (m1 (string-to-number (match-string 3 s)))
10433 (t2 (and (match-end 4) (match-string 5 s)))
10434 (h2 (and t2 (string-to-number (match-string 6 s))))
10435 (m2 (and t2 (string-to-number (match-string 7 s))))
10436 dh dm)
10437 (if (not t2)
10439 (setq dh (- h2 h1) dm (- m2 m1))
10440 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
10441 (concat t1 "+" (number-to-string dh)
10442 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
10444 (defun org-time-stamp-inactive (&optional arg)
10445 "Insert an inactive time stamp.
10446 An inactive time stamp is enclosed in square brackets instead of angle
10447 brackets. It is inactive in the sense that it does not trigger agenda entries,
10448 does not link to the calendar and cannot be changed with the S-cursor keys.
10449 So these are more for recording a certain time/date."
10450 (interactive "P")
10451 (org-time-stamp arg 'inactive))
10453 (defvar org-date-ovl (org-make-overlay 1 1))
10454 (org-overlay-put org-date-ovl 'face 'org-warning)
10455 (org-detach-overlay org-date-ovl)
10457 (defvar org-ans1) ; dynamically scoped parameter
10458 (defvar org-ans2) ; dynamically scoped parameter
10460 (defvar org-plain-time-of-day-regexp) ; defined below
10462 (defvar org-overriding-default-time nil) ; dynamically scoped
10463 (defvar org-read-date-overlay nil)
10464 (defvar org-dcst nil) ; dynamically scoped
10466 (defun org-read-date (&optional with-time to-time from-string prompt
10467 default-time default-input)
10468 "Read a date, possibly a time, and make things smooth for the user.
10469 The prompt will suggest to enter an ISO date, but you can also enter anything
10470 which will at least partially be understood by `parse-time-string'.
10471 Unrecognized parts of the date will default to the current day, month, year,
10472 hour and minute. If this command is called to replace a timestamp at point,
10473 of to enter the second timestamp of a range, the default time is taken from the
10474 existing stamp. For example,
10475 3-2-5 --> 2003-02-05
10476 feb 15 --> currentyear-02-15
10477 sep 12 9 --> 2009-09-12
10478 12:45 --> today 12:45
10479 22 sept 0:34 --> currentyear-09-22 0:34
10480 12 --> currentyear-currentmonth-12
10481 Fri --> nearest Friday (today or later)
10482 etc.
10484 Furthermore you can specify a relative date by giving, as the *first* thing
10485 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
10486 change in days weeks, months, years.
10487 With a single plus or minus, the date is relative to today. With a double
10488 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
10489 +4d --> four days from today
10490 +4 --> same as above
10491 +2w --> two weeks from today
10492 ++5 --> five days from default date
10494 The function understands only English month and weekday abbreviations,
10495 but this can be configured with the variables `parse-time-months' and
10496 `parse-time-weekdays'.
10498 While prompting, a calendar is popped up - you can also select the
10499 date with the mouse (button 1). The calendar shows a period of three
10500 months. To scroll it to other months, use the keys `>' and `<'.
10501 If you don't like the calendar, turn it off with
10502 \(setq org-read-date-popup-calendar nil)
10504 With optional argument TO-TIME, the date will immediately be converted
10505 to an internal time.
10506 With an optional argument WITH-TIME, the prompt will suggest to also
10507 insert a time. Note that when WITH-TIME is not set, you can still
10508 enter a time, and this function will inform the calling routine about
10509 this change. The calling routine may then choose to change the format
10510 used to insert the time stamp into the buffer to include the time.
10511 With optional argument FROM-STRING, read from this string instead from
10512 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
10513 the time/date that is used for everything that is not specified by the
10514 user."
10515 (require 'parse-time)
10516 (let* ((org-time-stamp-rounding-minutes
10517 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
10518 (org-dcst org-display-custom-times)
10519 (ct (org-current-time))
10520 (def (or org-overriding-default-time default-time ct))
10521 (defdecode (decode-time def))
10522 (dummy (progn
10523 (when (< (nth 2 defdecode) org-extend-today-until)
10524 (setcar (nthcdr 2 defdecode) -1)
10525 (setcar (nthcdr 1 defdecode) 59)
10526 (setq def (apply 'encode-time defdecode)
10527 defdecode (decode-time def)))))
10528 (calendar-move-hook nil)
10529 (calendar-view-diary-initially-flag nil)
10530 (view-diary-entries-initially nil)
10531 (calendar-view-holidays-initially-flag nil)
10532 (view-calendar-holidays-initially nil)
10533 (timestr (format-time-string
10534 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
10535 (prompt (concat (if prompt (concat prompt " ") "")
10536 (format "Date+time [%s]: " timestr)))
10537 ans (org-ans0 "") org-ans1 org-ans2 final)
10539 (cond
10540 (from-string (setq ans from-string))
10541 (org-read-date-popup-calendar
10542 (save-excursion
10543 (save-window-excursion
10544 (calendar)
10545 (calendar-forward-day (- (time-to-days def)
10546 (calendar-absolute-from-gregorian
10547 (calendar-current-date))))
10548 (org-eval-in-calendar nil t)
10549 (let* ((old-map (current-local-map))
10550 (map (copy-keymap calendar-mode-map))
10551 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
10552 (org-defkey map (kbd "RET") 'org-calendar-select)
10553 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
10554 'org-calendar-select-mouse)
10555 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
10556 'org-calendar-select-mouse)
10557 (org-defkey minibuffer-local-map [(meta shift left)]
10558 (lambda () (interactive)
10559 (org-eval-in-calendar '(calendar-backward-month 1))))
10560 (org-defkey minibuffer-local-map [(meta shift right)]
10561 (lambda () (interactive)
10562 (org-eval-in-calendar '(calendar-forward-month 1))))
10563 (org-defkey minibuffer-local-map [(meta shift up)]
10564 (lambda () (interactive)
10565 (org-eval-in-calendar '(calendar-backward-year 1))))
10566 (org-defkey minibuffer-local-map [(meta shift down)]
10567 (lambda () (interactive)
10568 (org-eval-in-calendar '(calendar-forward-year 1))))
10569 (org-defkey minibuffer-local-map [(shift up)]
10570 (lambda () (interactive)
10571 (org-eval-in-calendar '(calendar-backward-week 1))))
10572 (org-defkey minibuffer-local-map [(shift down)]
10573 (lambda () (interactive)
10574 (org-eval-in-calendar '(calendar-forward-week 1))))
10575 (org-defkey minibuffer-local-map [(shift left)]
10576 (lambda () (interactive)
10577 (org-eval-in-calendar '(calendar-backward-day 1))))
10578 (org-defkey minibuffer-local-map [(shift right)]
10579 (lambda () (interactive)
10580 (org-eval-in-calendar '(calendar-forward-day 1))))
10581 (org-defkey minibuffer-local-map ">"
10582 (lambda () (interactive)
10583 (org-eval-in-calendar '(scroll-calendar-left 1))))
10584 (org-defkey minibuffer-local-map "<"
10585 (lambda () (interactive)
10586 (org-eval-in-calendar '(scroll-calendar-right 1))))
10587 (unwind-protect
10588 (progn
10589 (use-local-map map)
10590 (add-hook 'post-command-hook 'org-read-date-display)
10591 (setq org-ans0 (read-string prompt default-input nil nil))
10592 ;; org-ans0: from prompt
10593 ;; org-ans1: from mouse click
10594 ;; org-ans2: from calendar motion
10595 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
10596 (remove-hook 'post-command-hook 'org-read-date-display)
10597 (use-local-map old-map)
10598 (when org-read-date-overlay
10599 (org-delete-overlay org-read-date-overlay)
10600 (setq org-read-date-overlay nil)))))))
10602 (t ; Naked prompt only
10603 (unwind-protect
10604 (setq ans (read-string prompt default-input nil timestr))
10605 (when org-read-date-overlay
10606 (org-delete-overlay org-read-date-overlay)
10607 (setq org-read-date-overlay nil)))))
10609 (setq final (org-read-date-analyze ans def defdecode))
10611 (if to-time
10612 (apply 'encode-time final)
10613 (if (and (boundp 'org-time-was-given) org-time-was-given)
10614 (format "%04d-%02d-%02d %02d:%02d"
10615 (nth 5 final) (nth 4 final) (nth 3 final)
10616 (nth 2 final) (nth 1 final))
10617 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
10618 (defvar def)
10619 (defvar defdecode)
10620 (defvar with-time)
10621 (defun org-read-date-display ()
10622 "Display the currrent date prompt interpretation in the minibuffer."
10623 (when org-read-date-display-live
10624 (when org-read-date-overlay
10625 (org-delete-overlay org-read-date-overlay))
10626 (let ((p (point)))
10627 (end-of-line 1)
10628 (while (not (equal (buffer-substring
10629 (max (point-min) (- (point) 4)) (point))
10630 " "))
10631 (insert " "))
10632 (goto-char p))
10633 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
10634 " " (or org-ans1 org-ans2)))
10635 (org-end-time-was-given nil)
10636 (f (org-read-date-analyze ans def defdecode))
10637 (fmts (if org-dcst
10638 org-time-stamp-custom-formats
10639 org-time-stamp-formats))
10640 (fmt (if (or with-time
10641 (and (boundp 'org-time-was-given) org-time-was-given))
10642 (cdr fmts)
10643 (car fmts)))
10644 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
10645 (when (and org-end-time-was-given
10646 (string-match org-plain-time-of-day-regexp txt))
10647 (setq txt (concat (substring txt 0 (match-end 0)) "-"
10648 org-end-time-was-given
10649 (substring txt (match-end 0)))))
10650 (setq org-read-date-overlay
10651 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
10652 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
10654 (defun org-read-date-analyze (ans def defdecode)
10655 "Analyze the combined answer of the date prompt."
10656 ;; FIXME: cleanup and comment
10657 (let (delta deltan deltaw deltadef year month day
10658 hour minute second wday pm h2 m2 tl wday1
10659 iso-year iso-weekday iso-week iso-year iso-date)
10661 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
10662 (setq ans "+0"))
10664 (when (setq delta (org-read-date-get-relative ans (current-time) def))
10665 (setq ans (replace-match "" t t ans)
10666 deltan (car delta)
10667 deltaw (nth 1 delta)
10668 deltadef (nth 2 delta)))
10670 ;; Check if there is an iso week date in there
10671 ;; If yes, sore the info and ostpone interpreting it until the rest
10672 ;; of the parsing is done
10673 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
10674 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
10675 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
10676 iso-week (string-to-number (match-string 2 ans)))
10677 (setq ans (replace-match "" t t ans)))
10679 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
10680 (when (string-match
10681 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
10682 (setq year (if (match-end 2)
10683 (string-to-number (match-string 2 ans))
10684 (string-to-number (format-time-string "%Y")))
10685 month (string-to-number (match-string 3 ans))
10686 day (string-to-number (match-string 4 ans)))
10687 (if (< year 100) (setq year (+ 2000 year)))
10688 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
10689 t nil ans)))
10690 ;; Help matching am/pm times, because `parse-time-string' does not do that.
10691 ;; If there is a time with am/pm, and *no* time without it, we convert
10692 ;; so that matching will be successful.
10693 (loop for i from 1 to 2 do ; twice, for end time as well
10694 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
10695 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
10696 (setq hour (string-to-number (match-string 1 ans))
10697 minute (if (match-end 3)
10698 (string-to-number (match-string 3 ans))
10700 pm (equal ?p
10701 (string-to-char (downcase (match-string 4 ans)))))
10702 (if (and (= hour 12) (not pm))
10703 (setq hour 0)
10704 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
10705 (setq ans (replace-match (format "%02d:%02d" hour minute)
10706 t t ans))))
10708 ;; Check if a time range is given as a duration
10709 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
10710 (setq hour (string-to-number (match-string 1 ans))
10711 h2 (+ hour (string-to-number (match-string 3 ans)))
10712 minute (string-to-number (match-string 2 ans))
10713 m2 (+ minute (if (match-end 5) (string-to-number
10714 (match-string 5 ans))0)))
10715 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
10716 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
10717 t t ans)))
10719 ;; Check if there is a time range
10720 (when (boundp 'org-end-time-was-given)
10721 (setq org-time-was-given nil)
10722 (when (and (string-match org-plain-time-of-day-regexp ans)
10723 (match-end 8))
10724 (setq org-end-time-was-given (match-string 8 ans))
10725 (setq ans (concat (substring ans 0 (match-beginning 7))
10726 (substring ans (match-end 7))))))
10728 (setq tl (parse-time-string ans)
10729 day (or (nth 3 tl) (nth 3 defdecode))
10730 month (or (nth 4 tl)
10731 (if (and org-read-date-prefer-future
10732 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
10733 (1+ (nth 4 defdecode))
10734 (nth 4 defdecode)))
10735 year (or (nth 5 tl)
10736 (if (and org-read-date-prefer-future
10737 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
10738 (1+ (nth 5 defdecode))
10739 (nth 5 defdecode)))
10740 hour (or (nth 2 tl) (nth 2 defdecode))
10741 minute (or (nth 1 tl) (nth 1 defdecode))
10742 second (or (nth 0 tl) 0)
10743 wday (nth 6 tl))
10745 ;; Special date definitions below
10746 (cond
10747 (iso-week
10748 ;; There was an iso week
10749 (setq year (or iso-year year)
10750 day (or iso-weekday wday 1)
10751 wday nil ; to make sure that the trigger below does not match
10752 iso-date (calendar-gregorian-from-absolute
10753 (calendar-absolute-from-iso
10754 (list iso-week day year))))
10755 ; FIXME: Should we also push ISO weeks into the future?
10756 ; (when (and org-read-date-prefer-future
10757 ; (not iso-year)
10758 ; (< (calendar-absolute-from-gregorian iso-date)
10759 ; (time-to-days (current-time))))
10760 ; (setq year (1+ year)
10761 ; iso-date (calendar-gregorian-from-absolute
10762 ; (calendar-absolute-from-iso
10763 ; (list iso-week day year)))))
10764 (setq month (car iso-date)
10765 year (nth 2 iso-date)
10766 day (nth 1 iso-date)))
10767 (deltan
10768 (unless deltadef
10769 (let ((now (decode-time (current-time))))
10770 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
10771 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
10772 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
10773 ((equal deltaw "m") (setq month (+ month deltan)))
10774 ((equal deltaw "y") (setq year (+ year deltan)))))
10775 ((and wday (not (nth 3 tl)))
10776 ;; Weekday was given, but no day, so pick that day in the week
10777 ;; on or after the derived date.
10778 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
10779 (unless (equal wday wday1)
10780 (setq day (+ day (% (- wday wday1 -7) 7))))))
10781 (if (and (boundp 'org-time-was-given)
10782 (nth 2 tl))
10783 (setq org-time-was-given t))
10784 (if (< year 100) (setq year (+ 2000 year)))
10785 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
10786 (list second minute hour day month year)))
10788 (defvar parse-time-weekdays)
10790 (defun org-read-date-get-relative (s today default)
10791 "Check string S for special relative date string.
10792 TODAY and DEFAULT are internal times, for today and for a default.
10793 Return shift list (N what def-flag)
10794 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
10795 N is the number of WHATs to shift.
10796 DEF-FLAG is t when a double ++ or -- indicates shift relative to
10797 the DEFAULT date rather than TODAY."
10798 (when (and
10799 (string-match
10800 (concat
10801 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
10802 "\\([0-9]+\\)?"
10803 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
10804 "\\([ \t]\\|$\\)") s)
10805 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
10806 (let* ((dir (if (> (match-end 1) (match-beginning 1))
10807 (string-to-char (substring (match-string 1 s) -1))
10808 ?+))
10809 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
10810 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
10811 (what (if (match-end 3) (match-string 3 s) "d"))
10812 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
10813 (date (if rel default today))
10814 (wday (nth 6 (decode-time date)))
10815 delta)
10816 (if wday1
10817 (progn
10818 (setq delta (mod (+ 7 (- wday1 wday)) 7))
10819 (if (= dir ?-) (setq delta (- delta 7)))
10820 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
10821 (list delta "d" rel))
10822 (list (* n (if (= dir ?-) -1 1)) what rel)))))
10824 (defun org-eval-in-calendar (form &optional keepdate)
10825 "Eval FORM in the calendar window and return to current window.
10826 Also, store the cursor date in variable org-ans2."
10827 (let ((sw (selected-window)))
10828 (select-window (get-buffer-window "*Calendar*"))
10829 (eval form)
10830 (when (and (not keepdate) (calendar-cursor-to-date))
10831 (let* ((date (calendar-cursor-to-date))
10832 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10833 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
10834 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
10835 (select-window sw)))
10837 (defun org-calendar-select ()
10838 "Return to `org-read-date' with the date currently selected.
10839 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
10840 (interactive)
10841 (when (calendar-cursor-to-date)
10842 (let* ((date (calendar-cursor-to-date))
10843 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10844 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
10845 (if (active-minibuffer-window) (exit-minibuffer))))
10847 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
10848 "Insert a date stamp for the date given by the internal TIME.
10849 WITH-HM means, use the stamp format that includes the time of the day.
10850 INACTIVE means use square brackets instead of angular ones, so that the
10851 stamp will not contribute to the agenda.
10852 PRE and POST are optional strings to be inserted before and after the
10853 stamp.
10854 The command returns the inserted time stamp."
10855 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
10856 stamp)
10857 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
10858 (insert-before-markers (or pre ""))
10859 (insert-before-markers (setq stamp (format-time-string fmt time)))
10860 (when (listp extra)
10861 (setq extra (car extra))
10862 (if (and (stringp extra)
10863 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
10864 (setq extra (format "-%02d:%02d"
10865 (string-to-number (match-string 1 extra))
10866 (string-to-number (match-string 2 extra))))
10867 (setq extra nil)))
10868 (when extra
10869 (backward-char 1)
10870 (insert-before-markers extra)
10871 (forward-char 1))
10872 (insert-before-markers (or post ""))
10873 (setq org-last-inserted-timestamp stamp)))
10875 (defun org-toggle-time-stamp-overlays ()
10876 "Toggle the use of custom time stamp formats."
10877 (interactive)
10878 (setq org-display-custom-times (not org-display-custom-times))
10879 (unless org-display-custom-times
10880 (let ((p (point-min)) (bmp (buffer-modified-p)))
10881 (while (setq p (next-single-property-change p 'display))
10882 (if (and (get-text-property p 'display)
10883 (eq (get-text-property p 'face) 'org-date))
10884 (remove-text-properties
10885 p (setq p (next-single-property-change p 'display))
10886 '(display t))))
10887 (set-buffer-modified-p bmp)))
10888 (if (featurep 'xemacs)
10889 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
10890 (org-restart-font-lock)
10891 (setq org-table-may-need-update t)
10892 (if org-display-custom-times
10893 (message "Time stamps are overlayed with custom format")
10894 (message "Time stamp overlays removed")))
10896 (defun org-display-custom-time (beg end)
10897 "Overlay modified time stamp format over timestamp between BEG and END."
10898 (let* ((ts (buffer-substring beg end))
10899 t1 w1 with-hm tf time str w2 (off 0))
10900 (save-match-data
10901 (setq t1 (org-parse-time-string ts t))
10902 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
10903 (setq off (- (match-end 0) (match-beginning 0)))))
10904 (setq end (- end off))
10905 (setq w1 (- end beg)
10906 with-hm (and (nth 1 t1) (nth 2 t1))
10907 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
10908 time (org-fix-decoded-time t1)
10909 str (org-add-props
10910 (format-time-string
10911 (substring tf 1 -1) (apply 'encode-time time))
10912 nil 'mouse-face 'highlight)
10913 w2 (length str))
10914 (if (not (= w2 w1))
10915 (add-text-properties (1+ beg) (+ 2 beg)
10916 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
10917 (if (featurep 'xemacs)
10918 (progn
10919 (put-text-property beg end 'invisible t)
10920 (put-text-property beg end 'end-glyph (make-glyph str)))
10921 (put-text-property beg end 'display str))))
10923 (defun org-translate-time (string)
10924 "Translate all timestamps in STRING to custom format.
10925 But do this only if the variable `org-display-custom-times' is set."
10926 (when org-display-custom-times
10927 (save-match-data
10928 (let* ((start 0)
10929 (re org-ts-regexp-both)
10930 t1 with-hm inactive tf time str beg end)
10931 (while (setq start (string-match re string start))
10932 (setq beg (match-beginning 0)
10933 end (match-end 0)
10934 t1 (save-match-data
10935 (org-parse-time-string (substring string beg end) t))
10936 with-hm (and (nth 1 t1) (nth 2 t1))
10937 inactive (equal (substring string beg (1+ beg)) "[")
10938 tf (funcall (if with-hm 'cdr 'car)
10939 org-time-stamp-custom-formats)
10940 time (org-fix-decoded-time t1)
10941 str (format-time-string
10942 (concat
10943 (if inactive "[" "<") (substring tf 1 -1)
10944 (if inactive "]" ">"))
10945 (apply 'encode-time time))
10946 string (replace-match str t t string)
10947 start (+ start (length str)))))))
10948 string)
10950 (defun org-fix-decoded-time (time)
10951 "Set 0 instead of nil for the first 6 elements of time.
10952 Don't touch the rest."
10953 (let ((n 0))
10954 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
10956 (defun org-days-to-time (timestamp-string)
10957 "Difference between TIMESTAMP-STRING and now in days."
10958 (- (time-to-days (org-time-string-to-time timestamp-string))
10959 (time-to-days (current-time))))
10961 (defun org-deadline-close (timestamp-string &optional ndays)
10962 "Is the time in TIMESTAMP-STRING close to the current date?"
10963 (setq ndays (or ndays (org-get-wdays timestamp-string)))
10964 (and (< (org-days-to-time timestamp-string) ndays)
10965 (not (org-entry-is-done-p))))
10967 (defun org-get-wdays (ts)
10968 "Get the deadline lead time appropriate for timestring TS."
10969 (cond
10970 ((<= org-deadline-warning-days 0)
10971 ;; 0 or negative, enforce this value no matter what
10972 (- org-deadline-warning-days))
10973 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
10974 ;; lead time is specified.
10975 (floor (* (string-to-number (match-string 1 ts))
10976 (cdr (assoc (match-string 2 ts)
10977 '(("d" . 1) ("w" . 7)
10978 ("m" . 30.4) ("y" . 365.25)))))))
10979 ;; go for the default.
10980 (t org-deadline-warning-days)))
10982 (defun org-calendar-select-mouse (ev)
10983 "Return to `org-read-date' with the date currently selected.
10984 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
10985 (interactive "e")
10986 (mouse-set-point ev)
10987 (when (calendar-cursor-to-date)
10988 (let* ((date (calendar-cursor-to-date))
10989 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10990 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
10991 (if (active-minibuffer-window) (exit-minibuffer))))
10993 (defun org-check-deadlines (ndays)
10994 "Check if there are any deadlines due or past due.
10995 A deadline is considered due if it happens within `org-deadline-warning-days'
10996 days from today's date. If the deadline appears in an entry marked DONE,
10997 it is not shown. The prefix arg NDAYS can be used to test that many
10998 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
10999 (interactive "P")
11000 (let* ((org-warn-days
11001 (cond
11002 ((equal ndays '(4)) 100000)
11003 (ndays (prefix-numeric-value ndays))
11004 (t (abs org-deadline-warning-days))))
11005 (case-fold-search nil)
11006 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
11007 (callback
11008 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
11010 (message "%d deadlines past-due or due within %d days"
11011 (org-occur regexp nil callback)
11012 org-warn-days)))
11014 (defun org-check-before-date (date)
11015 "Check if there are deadlines or scheduled entries before DATE."
11016 (interactive (list (org-read-date)))
11017 (let ((case-fold-search nil)
11018 (regexp (concat "\\<\\(" org-deadline-string
11019 "\\|" org-scheduled-string
11020 "\\) *<\\([^>]+\\)>"))
11021 (callback
11022 (lambda () (time-less-p
11023 (org-time-string-to-time (match-string 2))
11024 (org-time-string-to-time date)))))
11025 (message "%d entries before %s"
11026 (org-occur regexp nil callback) date)))
11028 (defun org-evaluate-time-range (&optional to-buffer)
11029 "Evaluate a time range by computing the difference between start and end.
11030 Normally the result is just printed in the echo area, but with prefix arg
11031 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
11032 If the time range is actually in a table, the result is inserted into the
11033 next column.
11034 For time difference computation, a year is assumed to be exactly 365
11035 days in order to avoid rounding problems."
11036 (interactive "P")
11038 (org-clock-update-time-maybe)
11039 (save-excursion
11040 (unless (org-at-date-range-p t)
11041 (goto-char (point-at-bol))
11042 (re-search-forward org-tr-regexp-both (point-at-eol) t))
11043 (if (not (org-at-date-range-p t))
11044 (error "Not at a time-stamp range, and none found in current line")))
11045 (let* ((ts1 (match-string 1))
11046 (ts2 (match-string 2))
11047 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
11048 (match-end (match-end 0))
11049 (time1 (org-time-string-to-time ts1))
11050 (time2 (org-time-string-to-time ts2))
11051 (t1 (time-to-seconds time1))
11052 (t2 (time-to-seconds time2))
11053 (diff (abs (- t2 t1)))
11054 (negative (< (- t2 t1) 0))
11055 ;; (ys (floor (* 365 24 60 60)))
11056 (ds (* 24 60 60))
11057 (hs (* 60 60))
11058 (fy "%dy %dd %02d:%02d")
11059 (fy1 "%dy %dd")
11060 (fd "%dd %02d:%02d")
11061 (fd1 "%dd")
11062 (fh "%02d:%02d")
11063 y d h m align)
11064 (if havetime
11065 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11067 d (floor (/ diff ds)) diff (mod diff ds)
11068 h (floor (/ diff hs)) diff (mod diff hs)
11069 m (floor (/ diff 60)))
11070 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11072 d (floor (+ (/ diff ds) 0.5))
11073 h 0 m 0))
11074 (if (not to-buffer)
11075 (message "%s" (org-make-tdiff-string y d h m))
11076 (if (org-at-table-p)
11077 (progn
11078 (goto-char match-end)
11079 (setq align t)
11080 (and (looking-at " *|") (goto-char (match-end 0))))
11081 (goto-char match-end))
11082 (if (looking-at
11083 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
11084 (replace-match ""))
11085 (if negative (insert " -"))
11086 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
11087 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
11088 (insert " " (format fh h m))))
11089 (if align (org-table-align))
11090 (message "Time difference inserted")))))
11092 (defun org-make-tdiff-string (y d h m)
11093 (let ((fmt "")
11094 (l nil))
11095 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
11096 l (push y l)))
11097 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
11098 l (push d l)))
11099 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
11100 l (push h l)))
11101 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
11102 l (push m l)))
11103 (apply 'format fmt (nreverse l))))
11105 (defun org-time-string-to-time (s)
11106 (apply 'encode-time (org-parse-time-string s)))
11108 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
11109 "Convert a time stamp to an absolute day number.
11110 If there is a specifyer for a cyclic time stamp, get the closest date to
11111 DAYNR.
11112 PREFER and SHOW_ALL are passed through to `org-closest-date'."
11113 (cond
11114 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
11115 (if (org-diary-sexp-entry (match-string 1 s) "" date)
11116 daynr
11117 (+ daynr 1000)))
11118 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
11119 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
11120 (time-to-days (current-time))) (match-string 0 s)
11121 prefer show-all))
11122 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
11124 (defun org-days-to-iso-week (days)
11125 "Return the iso week number."
11126 (require 'cal-iso)
11127 (car (calendar-iso-from-absolute days)))
11129 (defun org-small-year-to-year (year)
11130 "Convert 2-digit years into 4-digit years.
11131 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
11132 The year 2000 cannot be abbreviated. Any year lager than 99
11133 is retrned unchanged."
11134 (if (< year 38)
11135 (setq year (+ 2000 year))
11136 (if (< year 100)
11137 (setq year (+ 1900 year))))
11138 year)
11140 (defun org-time-from-absolute (d)
11141 "Return the time corresponding to date D.
11142 D may be an absolute day number, or a calendar-type list (month day year)."
11143 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
11144 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
11146 (defun org-calendar-holiday ()
11147 "List of holidays, for Diary display in Org-mode."
11148 (require 'holidays)
11149 (let ((hl (funcall
11150 (if (fboundp 'calendar-check-holidays)
11151 'calendar-check-holidays 'check-calendar-holidays) date)))
11152 (if hl (mapconcat 'identity hl "; "))))
11154 (defun org-diary-sexp-entry (sexp entry date)
11155 "Process a SEXP diary ENTRY for DATE."
11156 (require 'diary-lib)
11157 (let ((result (if calendar-debug-sexp
11158 (let ((stack-trace-on-error t))
11159 (eval (car (read-from-string sexp))))
11160 (condition-case nil
11161 (eval (car (read-from-string sexp)))
11162 (error
11163 (beep)
11164 (message "Bad sexp at line %d in %s: %s"
11165 (org-current-line)
11166 (buffer-file-name) sexp)
11167 (sleep-for 2))))))
11168 (cond ((stringp result) result)
11169 ((and (consp result)
11170 (stringp (cdr result))) (cdr result))
11171 (result entry)
11172 (t nil))))
11174 (defun org-diary-to-ical-string (frombuf)
11175 "Get iCalendar entries from diary entries in buffer FROMBUF.
11176 This uses the icalendar.el library."
11177 (let* ((tmpdir (if (featurep 'xemacs)
11178 (temp-directory)
11179 temporary-file-directory))
11180 (tmpfile (make-temp-name
11181 (expand-file-name "orgics" tmpdir)))
11182 buf rtn b e)
11183 (save-excursion
11184 (set-buffer frombuf)
11185 (icalendar-export-region (point-min) (point-max) tmpfile)
11186 (setq buf (find-buffer-visiting tmpfile))
11187 (set-buffer buf)
11188 (goto-char (point-min))
11189 (if (re-search-forward "^BEGIN:VEVENT" nil t)
11190 (setq b (match-beginning 0)))
11191 (goto-char (point-max))
11192 (if (re-search-backward "^END:VEVENT" nil t)
11193 (setq e (match-end 0)))
11194 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
11195 (kill-buffer buf)
11196 (delete-file tmpfile)
11197 rtn))
11199 (defun org-closest-date (start current change prefer show-all)
11200 "Find the date closest to CURRENT that is consistent with START and CHANGE.
11201 When PREFER is `past' return a date that is either CURRENT or past.
11202 When PREFER is `future', return a date that is either CURRENT or future.
11203 When SHOW-ALL is nil, only return the current occurence of a time stamp."
11204 ;; Make the proper lists from the dates
11205 (catch 'exit
11206 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
11207 dn dw sday cday n1 n2
11208 d m y y1 y2 date1 date2 nmonths nm ny m2)
11210 (setq start (org-date-to-gregorian start)
11211 current (org-date-to-gregorian
11212 (if show-all
11213 current
11214 (time-to-days (current-time))))
11215 sday (calendar-absolute-from-gregorian start)
11216 cday (calendar-absolute-from-gregorian current))
11218 (if (<= cday sday) (throw 'exit sday))
11220 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
11221 (setq dn (string-to-number (match-string 1 change))
11222 dw (cdr (assoc (match-string 2 change) a1)))
11223 (error "Invalid change specifyer: %s" change))
11224 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
11225 (cond
11226 ((eq dw 'day)
11227 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
11228 n2 (+ n1 dn)))
11229 ((eq dw 'year)
11230 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
11231 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
11232 (setq date1 (list m d y1)
11233 n1 (calendar-absolute-from-gregorian date1)
11234 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
11235 n2 (calendar-absolute-from-gregorian date2)))
11236 ((eq dw 'month)
11237 ;; approx number of month between the two dates
11238 (setq nmonths (floor (/ (- cday sday) 30.436875)))
11239 ;; How often does dn fit in there?
11240 (setq d (nth 1 start) m (car start) y (nth 2 start)
11241 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
11242 m (+ m nm)
11243 ny (floor (/ m 12))
11244 y (+ y ny)
11245 m (- m (* ny 12)))
11246 (while (> m 12) (setq m (- m 12) y (1+ y)))
11247 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
11248 (setq m2 (+ m dn) y2 y)
11249 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11250 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
11251 (while (<= n2 cday)
11252 (setq n1 n2 m m2 y y2)
11253 (setq m2 (+ m dn) y2 y)
11254 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11255 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
11256 (if show-all
11257 (cond
11258 ((eq prefer 'past) n1)
11259 ((eq prefer 'future) (if (= cday n1) n1 n2))
11260 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
11261 (cond
11262 ((eq prefer 'past) n1)
11263 ((eq prefer 'future) (if (= cday n1) n1 n2))
11264 (t (if (= cday n1) n1 n2)))))))
11266 (defun org-date-to-gregorian (date)
11267 "Turn any specification of DATE into a gregorian date for the calendar."
11268 (cond ((integerp date) (calendar-gregorian-from-absolute date))
11269 ((and (listp date) (= (length date) 3)) date)
11270 ((stringp date)
11271 (setq date (org-parse-time-string date))
11272 (list (nth 4 date) (nth 3 date) (nth 5 date)))
11273 ((listp date)
11274 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
11276 (defun org-parse-time-string (s &optional nodefault)
11277 "Parse the standard Org-mode time string.
11278 This should be a lot faster than the normal `parse-time-string'.
11279 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
11280 hour and minute fields will be nil if not given."
11281 (if (string-match org-ts-regexp0 s)
11282 (list 0
11283 (if (or (match-beginning 8) (not nodefault))
11284 (string-to-number (or (match-string 8 s) "0")))
11285 (if (or (match-beginning 7) (not nodefault))
11286 (string-to-number (or (match-string 7 s) "0")))
11287 (string-to-number (match-string 4 s))
11288 (string-to-number (match-string 3 s))
11289 (string-to-number (match-string 2 s))
11290 nil nil nil)
11291 (make-list 9 0)))
11293 (defun org-timestamp-up (&optional arg)
11294 "Increase the date item at the cursor by one.
11295 If the cursor is on the year, change the year. If it is on the month or
11296 the day, change that.
11297 With prefix ARG, change by that many units."
11298 (interactive "p")
11299 (org-timestamp-change (prefix-numeric-value arg)))
11301 (defun org-timestamp-down (&optional arg)
11302 "Decrease the date item at the cursor by one.
11303 If the cursor is on the year, change the year. If it is on the month or
11304 the day, change that.
11305 With prefix ARG, change by that many units."
11306 (interactive "p")
11307 (org-timestamp-change (- (prefix-numeric-value arg))))
11309 (defun org-timestamp-up-day (&optional arg)
11310 "Increase the date in the time stamp by one day.
11311 With prefix ARG, change that many days."
11312 (interactive "p")
11313 (if (and (not (org-at-timestamp-p t))
11314 (org-on-heading-p))
11315 (org-todo 'up)
11316 (org-timestamp-change (prefix-numeric-value arg) 'day)))
11318 (defun org-timestamp-down-day (&optional arg)
11319 "Decrease the date in the time stamp by one day.
11320 With prefix ARG, change that many days."
11321 (interactive "p")
11322 (if (and (not (org-at-timestamp-p t))
11323 (org-on-heading-p))
11324 (org-todo 'down)
11325 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
11327 (defun org-at-timestamp-p (&optional inactive-ok)
11328 "Determine if the cursor is in or at a timestamp."
11329 (interactive)
11330 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
11331 (pos (point))
11332 (ans (or (looking-at tsr)
11333 (save-excursion
11334 (skip-chars-backward "^[<\n\r\t")
11335 (if (> (point) (point-min)) (backward-char 1))
11336 (and (looking-at tsr)
11337 (> (- (match-end 0) pos) -1))))))
11338 (and ans
11339 (boundp 'org-ts-what)
11340 (setq org-ts-what
11341 (cond
11342 ((= pos (match-beginning 0)) 'bracket)
11343 ((= pos (1- (match-end 0))) 'bracket)
11344 ((org-pos-in-match-range pos 2) 'year)
11345 ((org-pos-in-match-range pos 3) 'month)
11346 ((org-pos-in-match-range pos 7) 'hour)
11347 ((org-pos-in-match-range pos 8) 'minute)
11348 ((or (org-pos-in-match-range pos 4)
11349 (org-pos-in-match-range pos 5)) 'day)
11350 ((and (> pos (or (match-end 8) (match-end 5)))
11351 (< pos (match-end 0)))
11352 (- pos (or (match-end 8) (match-end 5))))
11353 (t 'day))))
11354 ans))
11356 (defun org-toggle-timestamp-type ()
11357 "Toggle the type (<active> or [inactive]) of a time stamp."
11358 (interactive)
11359 (when (org-at-timestamp-p t)
11360 (let ((beg (match-beginning 0)) (end (match-end 0))
11361 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
11362 (save-excursion
11363 (goto-char beg)
11364 (while (re-search-forward "[][<>]" end t)
11365 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
11366 t t)))
11367 (message "Timestamp is now %sactive"
11368 (if (equal (char-after beg) ?<) "" "in")))))
11370 (defun org-timestamp-change (n &optional what)
11371 "Change the date in the time stamp at point.
11372 The date will be changed by N times WHAT. WHAT can be `day', `month',
11373 `year', `minute', `second'. If WHAT is not given, the cursor position
11374 in the timestamp determines what will be changed."
11375 (let ((pos (point))
11376 with-hm inactive
11377 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
11378 org-ts-what
11379 extra rem
11380 ts time time0)
11381 (if (not (org-at-timestamp-p t))
11382 (error "Not at a timestamp"))
11383 (if (and (not what) (eq org-ts-what 'bracket))
11384 (org-toggle-timestamp-type)
11385 (if (and (not what) (not (eq org-ts-what 'day))
11386 org-display-custom-times
11387 (get-text-property (point) 'display)
11388 (not (get-text-property (1- (point)) 'display)))
11389 (setq org-ts-what 'day))
11390 (setq org-ts-what (or what org-ts-what)
11391 inactive (= (char-after (match-beginning 0)) ?\[)
11392 ts (match-string 0))
11393 (replace-match "")
11394 (if (string-match
11395 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
11397 (setq extra (match-string 1 ts)))
11398 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
11399 (setq with-hm t))
11400 (setq time0 (org-parse-time-string ts))
11401 (when (and (eq org-ts-what 'minute)
11402 (eq current-prefix-arg nil))
11403 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
11404 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
11405 (setcar (cdr time0) (+ (nth 1 time0)
11406 (if (> n 0) (- rem) (- dm rem))))))
11407 (setq time
11408 (encode-time (or (car time0) 0)
11409 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
11410 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
11411 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
11412 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
11413 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
11414 (nthcdr 6 time0)))
11415 (when (integerp org-ts-what)
11416 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
11417 (if (eq what 'calendar)
11418 (let ((cal-date (org-get-date-from-calendar)))
11419 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
11420 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
11421 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
11422 (setcar time0 (or (car time0) 0))
11423 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
11424 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
11425 (setq time (apply 'encode-time time0))))
11426 (setq org-last-changed-timestamp
11427 (org-insert-time-stamp time with-hm inactive nil nil extra))
11428 (org-clock-update-time-maybe)
11429 (goto-char pos)
11430 ;; Try to recenter the calendar window, if any
11431 (if (and org-calendar-follow-timestamp-change
11432 (get-buffer-window "*Calendar*" t)
11433 (memq org-ts-what '(day month year)))
11434 (org-recenter-calendar (time-to-days time))))))
11436 (defun org-modify-ts-extra (s pos n dm)
11437 "Change the different parts of the lead-time and repeat fields in timestamp."
11438 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
11439 ng h m new rem)
11440 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
11441 (cond
11442 ((or (org-pos-in-match-range pos 2)
11443 (org-pos-in-match-range pos 3))
11444 (setq m (string-to-number (match-string 3 s))
11445 h (string-to-number (match-string 2 s)))
11446 (if (org-pos-in-match-range pos 2)
11447 (setq h (+ h n))
11448 (setq n (* dm (org-no-warnings (signum n))))
11449 (when (not (= 0 (setq rem (% m dm))))
11450 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
11451 (setq m (+ m n)))
11452 (if (< m 0) (setq m (+ m 60) h (1- h)))
11453 (if (> m 59) (setq m (- m 60) h (1+ h)))
11454 (setq h (min 24 (max 0 h)))
11455 (setq ng 1 new (format "-%02d:%02d" h m)))
11456 ((org-pos-in-match-range pos 6)
11457 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
11458 ((org-pos-in-match-range pos 5)
11459 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
11461 ((org-pos-in-match-range pos 9)
11462 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
11463 ((org-pos-in-match-range pos 8)
11464 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
11466 (when ng
11467 (setq s (concat
11468 (substring s 0 (match-beginning ng))
11470 (substring s (match-end ng))))))
11473 (defun org-recenter-calendar (date)
11474 "If the calendar is visible, recenter it to DATE."
11475 (let* ((win (selected-window))
11476 (cwin (get-buffer-window "*Calendar*" t))
11477 (calendar-move-hook nil))
11478 (when cwin
11479 (select-window cwin)
11480 (calendar-goto-date (if (listp date) date
11481 (calendar-gregorian-from-absolute date)))
11482 (select-window win))))
11484 (defun org-goto-calendar (&optional arg)
11485 "Go to the Emacs calendar at the current date.
11486 If there is a time stamp in the current line, go to that date.
11487 A prefix ARG can be used to force the current date."
11488 (interactive "P")
11489 (let ((tsr org-ts-regexp) diff
11490 (calendar-move-hook nil)
11491 (calendar-view-holidays-initially-flag nil)
11492 (view-calendar-holidays-initially nil)
11493 (calendar-view-diary-initially-flag nil)
11494 (view-diary-entries-initially nil))
11495 (if (or (org-at-timestamp-p)
11496 (save-excursion
11497 (beginning-of-line 1)
11498 (looking-at (concat ".*" tsr))))
11499 (let ((d1 (time-to-days (current-time)))
11500 (d2 (time-to-days
11501 (org-time-string-to-time (match-string 1)))))
11502 (setq diff (- d2 d1))))
11503 (calendar)
11504 (calendar-goto-today)
11505 (if (and diff (not arg)) (calendar-forward-day diff))))
11507 (defun org-get-date-from-calendar ()
11508 "Return a list (month day year) of date at point in calendar."
11509 (with-current-buffer "*Calendar*"
11510 (save-match-data
11511 (calendar-cursor-to-date))))
11513 (defun org-date-from-calendar ()
11514 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
11515 If there is already a time stamp at the cursor position, update it."
11516 (interactive)
11517 (if (org-at-timestamp-p t)
11518 (org-timestamp-change 0 'calendar)
11519 (let ((cal-date (org-get-date-from-calendar)))
11520 (org-insert-time-stamp
11521 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
11523 (defun org-minutes-to-hh:mm-string (m)
11524 "Compute H:MM from a number of minutes."
11525 (let ((h (/ m 60)))
11526 (setq m (- m (* 60 h)))
11527 (format org-time-clocksum-format h m)))
11529 (defun org-hh:mm-string-to-minutes (s)
11530 "Convert a string H:MM to a number of minutes."
11531 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
11532 (+ (* (string-to-number (match-string 1 s)) 60)
11533 (string-to-number (match-string 2 s)))
11536 ;;;; Agenda files
11538 ;;;###autoload
11539 (defun org-iswitchb (&optional arg)
11540 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
11541 With a prefix argument, restrict available to files.
11542 With two prefix arguments, restrict available buffers to agenda files.
11544 Due to some yet unresolved reason, the global function
11545 `iswitchb-mode' needs to be active for this function to work."
11546 (interactive "P")
11547 (require 'iswitchb)
11548 (let ((enabled iswitchb-mode) blist)
11549 (or enabled (iswitchb-mode 1))
11550 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
11551 ((equal arg '(16)) (org-buffer-list 'agenda))
11552 (t (org-buffer-list))))
11553 (unwind-protect
11554 (let ((iswitchb-make-buflist-hook
11555 (lambda ()
11556 (setq iswitchb-temp-buflist
11557 (mapcar 'buffer-name blist)))))
11558 (switch-to-buffer
11559 (iswitchb-read-buffer
11560 "Switch-to: " nil t))
11561 (or enabled (iswitchb-mode -1))))))
11563 (defun org-buffer-list (&optional predicate exclude-tmp)
11564 "Return a list of Org buffers.
11565 PREDICATE can be `export', `files' or `agenda'.
11567 export restrict the list to Export buffers.
11568 files restrict the list to buffers visiting Org files.
11569 agenda restrict the list to buffers visiting agenda files.
11571 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
11572 (let* ((bfn nil)
11573 (agenda-files (and (eq predicate 'agenda)
11574 (mapcar 'file-truename (org-agenda-files t))))
11575 (filter
11576 (cond
11577 ((eq predicate 'files)
11578 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
11579 ((eq predicate 'export)
11580 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
11581 ((eq predicate 'agenda)
11582 (lambda (b)
11583 (with-current-buffer b
11584 (and (eq major-mode 'org-mode)
11585 (setq bfn (buffer-file-name b))
11586 (member (file-truename bfn) agenda-files)))))
11587 (t (lambda (b) (with-current-buffer b
11588 (or (eq major-mode 'org-mode)
11589 (string-match "\*Org .*Export"
11590 (buffer-name b)))))))))
11591 (delq nil
11592 (mapcar
11593 (lambda(b)
11594 (if (and (funcall filter b)
11595 (or (not exclude-tmp)
11596 (not (string-match "tmp" (buffer-name b)))))
11598 nil))
11599 (buffer-list)))))
11601 (defun org-agenda-files (&optional unrestricted archives)
11602 "Get the list of agenda files.
11603 Optional UNRESTRICTED means return the full list even if a restriction
11604 is currently in place.
11605 When ARCHIVES is t, include all archive files hat are really being
11606 used by the agenda files. If ARCHIVE is `ifmode', do this only if
11607 `org-agenda-archives-mode' is t."
11608 (let ((files
11609 (cond
11610 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
11611 ((stringp org-agenda-files) (org-read-agenda-file-list))
11612 ((listp org-agenda-files) org-agenda-files)
11613 (t (error "Invalid value of `org-agenda-files'")))))
11614 (setq files (apply 'append
11615 (mapcar (lambda (f)
11616 (if (file-directory-p f)
11617 (directory-files
11618 f t org-agenda-file-regexp)
11619 (list f)))
11620 files)))
11621 (when org-agenda-skip-unavailable-files
11622 (setq files (delq nil
11623 (mapcar (function
11624 (lambda (file)
11625 (and (file-readable-p file) file)))
11626 files))))
11627 (when (or (eq archives t)
11628 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
11629 (setq files (org-add-archive-files files)))
11630 files))
11632 (defun org-edit-agenda-file-list ()
11633 "Edit the list of agenda files.
11634 Depending on setup, this either uses customize to edit the variable
11635 `org-agenda-files', or it visits the file that is holding the list. In the
11636 latter case, the buffer is set up in a way that saving it automatically kills
11637 the buffer and restores the previous window configuration."
11638 (interactive)
11639 (if (stringp org-agenda-files)
11640 (let ((cw (current-window-configuration)))
11641 (find-file org-agenda-files)
11642 (org-set-local 'org-window-configuration cw)
11643 (org-add-hook 'after-save-hook
11644 (lambda ()
11645 (set-window-configuration
11646 (prog1 org-window-configuration
11647 (kill-buffer (current-buffer))))
11648 (org-install-agenda-files-menu)
11649 (message "New agenda file list installed"))
11650 nil 'local)
11651 (message "%s" (substitute-command-keys
11652 "Edit list and finish with \\[save-buffer]")))
11653 (customize-variable 'org-agenda-files)))
11655 (defun org-store-new-agenda-file-list (list)
11656 "Set new value for the agenda file list and save it correcly."
11657 (if (stringp org-agenda-files)
11658 (let ((f org-agenda-files) b)
11659 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
11660 (with-temp-file f
11661 (insert (mapconcat 'identity list "\n") "\n")))
11662 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
11663 (setq org-agenda-files list)
11664 (customize-save-variable 'org-agenda-files org-agenda-files))))
11666 (defun org-read-agenda-file-list ()
11667 "Read the list of agenda files from a file."
11668 (when (file-directory-p org-agenda-files)
11669 (error "`org-agenda-files' cannot be a single directory"))
11670 (when (stringp org-agenda-files)
11671 (with-temp-buffer
11672 (insert-file-contents org-agenda-files)
11673 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
11676 ;;;###autoload
11677 (defun org-cycle-agenda-files ()
11678 "Cycle through the files in `org-agenda-files'.
11679 If the current buffer visits an agenda file, find the next one in the list.
11680 If the current buffer does not, find the first agenda file."
11681 (interactive)
11682 (let* ((fs (org-agenda-files t))
11683 (files (append fs (list (car fs))))
11684 (tcf (if buffer-file-name (file-truename buffer-file-name)))
11685 file)
11686 (unless files (error "No agenda files"))
11687 (catch 'exit
11688 (while (setq file (pop files))
11689 (if (equal (file-truename file) tcf)
11690 (when (car files)
11691 (find-file (car files))
11692 (throw 'exit t))))
11693 (find-file (car fs)))
11694 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
11696 (defun org-agenda-file-to-front (&optional to-end)
11697 "Move/add the current file to the top of the agenda file list.
11698 If the file is not present in the list, it is added to the front. If it is
11699 present, it is moved there. With optional argument TO-END, add/move to the
11700 end of the list."
11701 (interactive "P")
11702 (let ((org-agenda-skip-unavailable-files nil)
11703 (file-alist (mapcar (lambda (x)
11704 (cons (file-truename x) x))
11705 (org-agenda-files t)))
11706 (ctf (file-truename buffer-file-name))
11707 x had)
11708 (setq x (assoc ctf file-alist) had x)
11710 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
11711 (if to-end
11712 (setq file-alist (append (delq x file-alist) (list x)))
11713 (setq file-alist (cons x (delq x file-alist))))
11714 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
11715 (org-install-agenda-files-menu)
11716 (message "File %s to %s of agenda file list"
11717 (if had "moved" "added") (if to-end "end" "front"))))
11719 (defun org-remove-file (&optional file)
11720 "Remove current file from the list of files in variable `org-agenda-files'.
11721 These are the files which are being checked for agenda entries.
11722 Optional argument FILE means, use this file instead of the current."
11723 (interactive)
11724 (let* ((org-agenda-skip-unavailable-files nil)
11725 (file (or file buffer-file-name))
11726 (true-file (file-truename file))
11727 (afile (abbreviate-file-name file))
11728 (files (delq nil (mapcar
11729 (lambda (x)
11730 (if (equal true-file
11731 (file-truename x))
11732 nil x))
11733 (org-agenda-files t)))))
11734 (if (not (= (length files) (length (org-agenda-files t))))
11735 (progn
11736 (org-store-new-agenda-file-list files)
11737 (org-install-agenda-files-menu)
11738 (message "Removed file: %s" afile))
11739 (message "File was not in list: %s (not removed)" afile))))
11741 (defun org-file-menu-entry (file)
11742 (vector file (list 'find-file file) t))
11744 (defun org-check-agenda-file (file)
11745 "Make sure FILE exists. If not, ask user what to do."
11746 (when (not (file-exists-p file))
11747 (message "non-existent file %s. [R]emove from list or [A]bort?"
11748 (abbreviate-file-name file))
11749 (let ((r (downcase (read-char-exclusive))))
11750 (cond
11751 ((equal r ?r)
11752 (org-remove-file file)
11753 (throw 'nextfile t))
11754 (t (error "Abort"))))))
11756 (defun org-get-agenda-file-buffer (file)
11757 "Get a buffer visiting FILE. If the buffer needs to be created, add
11758 it to the list of buffers which might be released later."
11759 (let ((buf (org-find-base-buffer-visiting file)))
11760 (if buf
11761 buf ; just return it
11762 ;; Make a new buffer and remember it
11763 (setq buf (find-file-noselect file))
11764 (if buf (push buf org-agenda-new-buffers))
11765 buf)))
11767 (defun org-release-buffers (blist)
11768 "Release all buffers in list, asking the user for confirmation when needed.
11769 When a buffer is unmodified, it is just killed. When modified, it is saved
11770 \(if the user agrees) and then killed."
11771 (let (buf file)
11772 (while (setq buf (pop blist))
11773 (setq file (buffer-file-name buf))
11774 (when (and (buffer-modified-p buf)
11775 file
11776 (y-or-n-p (format "Save file %s? " file)))
11777 (with-current-buffer buf (save-buffer)))
11778 (kill-buffer buf))))
11780 (defun org-prepare-agenda-buffers (files)
11781 "Create buffers for all agenda files, protect archived trees and comments."
11782 (interactive)
11783 (let ((pa '(:org-archived t))
11784 (pc '(:org-comment t))
11785 (pall '(:org-archived t :org-comment t))
11786 (inhibit-read-only t)
11787 (rea (concat ":" org-archive-tag ":"))
11788 bmp file re)
11789 (save-excursion
11790 (save-restriction
11791 (while (setq file (pop files))
11792 (if (bufferp file)
11793 (set-buffer file)
11794 (org-check-agenda-file file)
11795 (set-buffer (org-get-agenda-file-buffer file)))
11796 (widen)
11797 (setq bmp (buffer-modified-p))
11798 (org-refresh-category-properties)
11799 (setq org-todo-keywords-for-agenda
11800 (append org-todo-keywords-for-agenda org-todo-keywords-1))
11801 (setq org-done-keywords-for-agenda
11802 (append org-done-keywords-for-agenda org-done-keywords))
11803 (setq org-todo-keyword-alist-for-agenda
11804 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
11805 (setq org-tag-alist-for-agenda
11806 (append org-tag-alist-for-agenda org-tag-alist))
11808 (save-excursion
11809 (remove-text-properties (point-min) (point-max) pall)
11810 (when org-agenda-skip-archived-trees
11811 (goto-char (point-min))
11812 (while (re-search-forward rea nil t)
11813 (if (org-on-heading-p t)
11814 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
11815 (goto-char (point-min))
11816 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
11817 (while (re-search-forward re nil t)
11818 (add-text-properties
11819 (match-beginning 0) (org-end-of-subtree t) pc)))
11820 (set-buffer-modified-p bmp))))
11821 (setq org-todo-keyword-alist-for-agenda
11822 (org-uniquify org-todo-keyword-alist-for-agenda)
11823 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
11825 ;;;; Embedded LaTeX
11827 (defvar org-cdlatex-mode-map (make-sparse-keymap)
11828 "Keymap for the minor `org-cdlatex-mode'.")
11830 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
11831 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
11832 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
11833 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
11834 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
11836 (defvar org-cdlatex-texmathp-advice-is-done nil
11837 "Flag remembering if we have applied the advice to texmathp already.")
11839 (define-minor-mode org-cdlatex-mode
11840 "Toggle the minor `org-cdlatex-mode'.
11841 This mode supports entering LaTeX environment and math in LaTeX fragments
11842 in Org-mode.
11843 \\{org-cdlatex-mode-map}"
11844 nil " OCDL" nil
11845 (when org-cdlatex-mode (require 'cdlatex))
11846 (unless org-cdlatex-texmathp-advice-is-done
11847 (setq org-cdlatex-texmathp-advice-is-done t)
11848 (defadvice texmathp (around org-math-always-on activate)
11849 "Always return t in org-mode buffers.
11850 This is because we want to insert math symbols without dollars even outside
11851 the LaTeX math segments. If Orgmode thinks that point is actually inside
11852 en embedded LaTeX fragement, let texmathp do its job.
11853 \\[org-cdlatex-mode-map]"
11854 (interactive)
11855 (let (p)
11856 (cond
11857 ((not (org-mode-p)) ad-do-it)
11858 ((eq this-command 'cdlatex-math-symbol)
11859 (setq ad-return-value t
11860 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
11862 (let ((p (org-inside-LaTeX-fragment-p)))
11863 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
11864 (setq ad-return-value t
11865 texmathp-why '("Org-mode embedded math" . 0))
11866 (if p ad-do-it)))))))))
11868 (defun turn-on-org-cdlatex ()
11869 "Unconditionally turn on `org-cdlatex-mode'."
11870 (org-cdlatex-mode 1))
11872 (defun org-inside-LaTeX-fragment-p ()
11873 "Test if point is inside a LaTeX fragment.
11874 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
11875 sequence appearing also before point.
11876 Even though the matchers for math are configurable, this function assumes
11877 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
11878 delimiters are skipped when they have been removed by customization.
11879 The return value is nil, or a cons cell with the delimiter and
11880 and the position of this delimiter.
11882 This function does a reasonably good job, but can locally be fooled by
11883 for example currency specifications. For example it will assume being in
11884 inline math after \"$22.34\". The LaTeX fragment formatter will only format
11885 fragments that are properly closed, but during editing, we have to live
11886 with the uncertainty caused by missing closing delimiters. This function
11887 looks only before point, not after."
11888 (catch 'exit
11889 (let ((pos (point))
11890 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
11891 (lim (progn
11892 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
11893 (point)))
11894 dd-on str (start 0) m re)
11895 (goto-char pos)
11896 (when dodollar
11897 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
11898 re (nth 1 (assoc "$" org-latex-regexps)))
11899 (while (string-match re str start)
11900 (cond
11901 ((= (match-end 0) (length str))
11902 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
11903 ((= (match-end 0) (- (length str) 5))
11904 (throw 'exit nil))
11905 (t (setq start (match-end 0))))))
11906 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
11907 (goto-char pos)
11908 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
11909 (and (match-beginning 2) (throw 'exit nil))
11910 ;; count $$
11911 (while (re-search-backward "\\$\\$" lim t)
11912 (setq dd-on (not dd-on)))
11913 (goto-char pos)
11914 (if dd-on (cons "$$" m))))))
11917 (defun org-try-cdlatex-tab ()
11918 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
11919 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
11920 - inside a LaTeX fragment, or
11921 - after the first word in a line, where an abbreviation expansion could
11922 insert a LaTeX environment."
11923 (when org-cdlatex-mode
11924 (cond
11925 ((save-excursion
11926 (skip-chars-backward "a-zA-Z0-9*")
11927 (skip-chars-backward " \t")
11928 (bolp))
11929 (cdlatex-tab) t)
11930 ((org-inside-LaTeX-fragment-p)
11931 (cdlatex-tab) t)
11932 (t nil))))
11934 (defun org-cdlatex-underscore-caret (&optional arg)
11935 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
11936 Revert to the normal definition outside of these fragments."
11937 (interactive "P")
11938 (if (org-inside-LaTeX-fragment-p)
11939 (call-interactively 'cdlatex-sub-superscript)
11940 (let (org-cdlatex-mode)
11941 (call-interactively (key-binding (vector last-input-event))))))
11943 (defun org-cdlatex-math-modify (&optional arg)
11944 "Execute `cdlatex-math-modify' in LaTeX fragments.
11945 Revert to the normal definition outside of these fragments."
11946 (interactive "P")
11947 (if (org-inside-LaTeX-fragment-p)
11948 (call-interactively 'cdlatex-math-modify)
11949 (let (org-cdlatex-mode)
11950 (call-interactively (key-binding (vector last-input-event))))))
11952 (defvar org-latex-fragment-image-overlays nil
11953 "List of overlays carrying the images of latex fragments.")
11954 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
11956 (defun org-remove-latex-fragment-image-overlays ()
11957 "Remove all overlays with LaTeX fragment images in current buffer."
11958 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
11959 (setq org-latex-fragment-image-overlays nil))
11961 (defun org-preview-latex-fragment (&optional subtree)
11962 "Preview the LaTeX fragment at point, or all locally or globally.
11963 If the cursor is in a LaTeX fragment, create the image and overlay
11964 it over the source code. If there is no fragment at point, display
11965 all fragments in the current text, from one headline to the next. With
11966 prefix SUBTREE, display all fragments in the current subtree. With a
11967 double prefix `C-u C-u', or when the cursor is before the first headline,
11968 display all fragments in the buffer.
11969 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
11970 (interactive "P")
11971 (org-remove-latex-fragment-image-overlays)
11972 (save-excursion
11973 (save-restriction
11974 (let (beg end at msg)
11975 (cond
11976 ((or (equal subtree '(16))
11977 (not (save-excursion
11978 (re-search-backward (concat "^" outline-regexp) nil t))))
11979 (setq beg (point-min) end (point-max)
11980 msg "Creating images for buffer...%s"))
11981 ((equal subtree '(4))
11982 (org-back-to-heading)
11983 (setq beg (point) end (org-end-of-subtree t)
11984 msg "Creating images for subtree...%s"))
11986 (if (setq at (org-inside-LaTeX-fragment-p))
11987 (goto-char (max (point-min) (- (cdr at) 2)))
11988 (org-back-to-heading))
11989 (setq beg (point) end (progn (outline-next-heading) (point))
11990 msg (if at "Creating image...%s"
11991 "Creating images for entry...%s"))))
11992 (message msg "")
11993 (narrow-to-region beg end)
11994 (goto-char beg)
11995 (org-format-latex
11996 (concat "ltxpng/" (file-name-sans-extension
11997 (file-name-nondirectory
11998 buffer-file-name)))
11999 default-directory 'overlays msg at 'forbuffer)
12000 (message msg "done. Use `C-c C-c' to remove images.")))))
12002 (defvar org-latex-regexps
12003 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
12004 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
12005 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
12006 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
12007 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
12008 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
12009 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
12010 "Regular expressions for matching embedded LaTeX.")
12012 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
12013 "Replace LaTeX fragments with links to an image, and produce images."
12014 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
12015 (let* ((prefixnodir (file-name-nondirectory prefix))
12016 (absprefix (expand-file-name prefix dir))
12017 (todir (file-name-directory absprefix))
12018 (opt org-format-latex-options)
12019 (matchers (plist-get opt :matchers))
12020 (re-list org-latex-regexps)
12021 (cnt 0) txt link beg end re e checkdir
12022 m n block linkfile movefile ov)
12023 ;; Check if there are old images files with this prefix, and remove them
12024 (when (file-directory-p todir)
12025 (mapc 'delete-file
12026 (directory-files
12027 todir 'full
12028 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
12029 ;; Check the different regular expressions
12030 (while (setq e (pop re-list))
12031 (setq m (car e) re (nth 1 e) n (nth 2 e)
12032 block (if (nth 3 e) "\n\n" ""))
12033 (when (member m matchers)
12034 (goto-char (point-min))
12035 (while (re-search-forward re nil t)
12036 (when (or (not at) (equal (cdr at) (match-beginning n)))
12037 (setq txt (match-string n)
12038 beg (match-beginning n) end (match-end n)
12039 cnt (1+ cnt)
12040 linkfile (format "%s_%04d.png" prefix cnt)
12041 movefile (format "%s_%04d.png" absprefix cnt)
12042 link (concat block "[[file:" linkfile "]]" block))
12043 (if msg (message msg cnt))
12044 (goto-char beg)
12045 (unless checkdir ; make sure the directory exists
12046 (setq checkdir t)
12047 (or (file-directory-p todir) (make-directory todir)))
12048 (org-create-formula-image
12049 txt movefile opt forbuffer)
12050 (if overlays
12051 (progn
12052 (setq ov (org-make-overlay beg end))
12053 (if (featurep 'xemacs)
12054 (progn
12055 (org-overlay-put ov 'invisible t)
12056 (org-overlay-put
12057 ov 'end-glyph
12058 (make-glyph (vector 'png :file movefile))))
12059 (org-overlay-put
12060 ov 'display
12061 (list 'image :type 'png :file movefile :ascent 'center)))
12062 (push ov org-latex-fragment-image-overlays)
12063 (goto-char end))
12064 (delete-region beg end)
12065 (insert link))))))))
12067 ;; This function borrows from Ganesh Swami's latex2png.el
12068 (defun org-create-formula-image (string tofile options buffer)
12069 (let* ((tmpdir (if (featurep 'xemacs)
12070 (temp-directory)
12071 temporary-file-directory))
12072 (texfilebase (make-temp-name
12073 (expand-file-name "orgtex" tmpdir)))
12074 (texfile (concat texfilebase ".tex"))
12075 (dvifile (concat texfilebase ".dvi"))
12076 (pngfile (concat texfilebase ".png"))
12077 (fnh (if (featurep 'xemacs)
12078 (font-height (get-face-font 'default))
12079 (face-attribute 'default :height nil)))
12080 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
12081 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
12082 (fg (or (plist-get options (if buffer :foreground :html-foreground))
12083 "Black"))
12084 (bg (or (plist-get options (if buffer :background :html-background))
12085 "Transparent")))
12086 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
12087 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
12088 (with-temp-file texfile
12089 (insert org-format-latex-header
12090 "\n\\begin{document}\n" string "\n\\end{document}\n"))
12091 (let ((dir default-directory))
12092 (condition-case nil
12093 (progn
12094 (cd tmpdir)
12095 (call-process "latex" nil nil nil texfile))
12096 (error nil))
12097 (cd dir))
12098 (if (not (file-exists-p dvifile))
12099 (progn (message "Failed to create dvi file from %s" texfile) nil)
12100 (condition-case nil
12101 (call-process "dvipng" nil nil nil
12102 "-E" "-fg" fg "-bg" bg
12103 "-D" dpi
12104 ;;"-x" scale "-y" scale
12105 "-T" "tight"
12106 "-o" pngfile
12107 dvifile)
12108 (error nil))
12109 (if (not (file-exists-p pngfile))
12110 (progn (message "Failed to create png file from %s" texfile) nil)
12111 ;; Use the requested file name and clean up
12112 (copy-file pngfile tofile 'replace)
12113 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
12114 (delete-file (concat texfilebase e)))
12115 pngfile))))
12117 (defun org-dvipng-color (attr)
12118 "Return an rgb color specification for dvipng."
12119 (apply 'format "rgb %s %s %s"
12120 (mapcar 'org-normalize-color
12121 (color-values (face-attribute 'default attr nil)))))
12123 (defun org-normalize-color (value)
12124 "Return string to be used as color value for an RGB component."
12125 (format "%g" (/ value 65535.0)))
12128 ;;;; Key bindings
12130 ;; Make `C-c C-x' a prefix key
12131 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
12133 ;; TAB key with modifiers
12134 (org-defkey org-mode-map "\C-i" 'org-cycle)
12135 (org-defkey org-mode-map [(tab)] 'org-cycle)
12136 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
12137 (org-defkey org-mode-map [(meta tab)] 'org-complete)
12138 (org-defkey org-mode-map "\M-\t" 'org-complete)
12139 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
12140 ;; The following line is necessary under Suse GNU/Linux
12141 (unless (featurep 'xemacs)
12142 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
12143 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
12144 (define-key org-mode-map [backtab] 'org-shifttab)
12146 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
12147 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
12148 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
12150 ;; Cursor keys with modifiers
12151 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
12152 (org-defkey org-mode-map [(meta right)] 'org-metaright)
12153 (org-defkey org-mode-map [(meta up)] 'org-metaup)
12154 (org-defkey org-mode-map [(meta down)] 'org-metadown)
12156 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
12157 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
12158 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
12159 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
12161 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
12162 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
12163 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
12164 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
12166 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
12167 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
12169 ;;; Extra keys for tty access.
12170 ;; We only set them when really needed because otherwise the
12171 ;; menus don't show the simple keys
12173 (when (or org-use-extra-keys
12174 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
12175 (not window-system))
12176 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
12177 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
12178 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
12179 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
12180 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
12181 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
12182 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
12183 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
12184 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
12185 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
12186 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
12187 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
12188 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
12189 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
12190 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
12191 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
12192 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
12193 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
12194 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
12195 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
12196 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
12197 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
12199 ;; All the other keys
12201 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
12202 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
12203 (if (boundp 'narrow-map)
12204 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
12205 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
12206 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
12207 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
12208 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
12209 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
12210 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
12211 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
12212 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
12213 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
12214 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
12215 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
12216 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
12217 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
12218 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
12219 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
12220 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
12221 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
12222 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
12223 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
12224 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
12225 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
12226 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
12227 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
12228 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
12229 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
12230 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
12231 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
12232 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
12233 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
12234 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
12235 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
12236 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
12237 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
12238 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
12239 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
12240 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
12241 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
12242 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
12243 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
12244 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
12245 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
12246 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
12247 (org-defkey org-mode-map "\C-c^" 'org-sort)
12248 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
12249 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
12250 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
12251 (org-defkey org-mode-map "\C-m" 'org-return)
12252 (org-defkey org-mode-map "\C-j" 'org-return-indent)
12253 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
12254 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
12255 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
12256 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
12257 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
12258 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
12259 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
12260 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
12261 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
12262 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
12263 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
12264 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
12265 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
12266 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
12267 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
12269 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
12270 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
12271 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
12272 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
12274 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
12275 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
12276 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
12277 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
12278 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
12279 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
12280 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
12281 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
12282 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
12283 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
12284 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
12285 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
12287 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
12289 (when (featurep 'xemacs)
12290 (org-defkey org-mode-map 'button3 'popup-mode-menu))
12292 (defvar org-table-auto-blank-field) ; defined in org-table.el
12293 (defun org-self-insert-command (N)
12294 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
12295 If the cursor is in a table looking at whitespace, the whitespace is
12296 overwritten, and the table is not marked as requiring realignment."
12297 (interactive "p")
12298 (if (and (org-table-p)
12299 (progn
12300 ;; check if we blank the field, and if that triggers align
12301 (and (featurep 'org-table) org-table-auto-blank-field
12302 (member last-command
12303 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
12304 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
12305 ;; got extra space, this field does not determine column width
12306 (let (org-table-may-need-update) (org-table-blank-field))
12307 ;; no extra space, this field may determine column width
12308 (org-table-blank-field)))
12310 (eq N 1)
12311 (looking-at "[^|\n]* |"))
12312 (let (org-table-may-need-update)
12313 (goto-char (1- (match-end 0)))
12314 (delete-backward-char 1)
12315 (goto-char (match-beginning 0))
12316 (self-insert-command N))
12317 (setq org-table-may-need-update t)
12318 (self-insert-command N)
12319 (org-fix-tags-on-the-fly)))
12321 (defun org-fix-tags-on-the-fly ()
12322 (when (and (equal (char-after (point-at-bol)) ?*)
12323 (org-on-heading-p))
12324 (org-align-tags-here org-tags-column)))
12326 (defun org-delete-backward-char (N)
12327 "Like `delete-backward-char', insert whitespace at field end in tables.
12328 When deleting backwards, in tables this function will insert whitespace in
12329 front of the next \"|\" separator, to keep the table aligned. The table will
12330 still be marked for re-alignment if the field did fill the entire column,
12331 because, in this case the deletion might narrow the column."
12332 (interactive "p")
12333 (if (and (org-table-p)
12334 (eq N 1)
12335 (string-match "|" (buffer-substring (point-at-bol) (point)))
12336 (looking-at ".*?|"))
12337 (let ((pos (point))
12338 (noalign (looking-at "[^|\n\r]* |"))
12339 (c org-table-may-need-update))
12340 (backward-delete-char N)
12341 (skip-chars-forward "^|")
12342 (insert " ")
12343 (goto-char (1- pos))
12344 ;; noalign: if there were two spaces at the end, this field
12345 ;; does not determine the width of the column.
12346 (if noalign (setq org-table-may-need-update c)))
12347 (backward-delete-char N)
12348 (org-fix-tags-on-the-fly)))
12350 (defun org-delete-char (N)
12351 "Like `delete-char', but insert whitespace at field end in tables.
12352 When deleting characters, in tables this function will insert whitespace in
12353 front of the next \"|\" separator, to keep the table aligned. The table will
12354 still be marked for re-alignment if the field did fill the entire column,
12355 because, in this case the deletion might narrow the column."
12356 (interactive "p")
12357 (if (and (org-table-p)
12358 (not (bolp))
12359 (not (= (char-after) ?|))
12360 (eq N 1))
12361 (if (looking-at ".*?|")
12362 (let ((pos (point))
12363 (noalign (looking-at "[^|\n\r]* |"))
12364 (c org-table-may-need-update))
12365 (replace-match (concat
12366 (substring (match-string 0) 1 -1)
12367 " |"))
12368 (goto-char pos)
12369 ;; noalign: if there were two spaces at the end, this field
12370 ;; does not determine the width of the column.
12371 (if noalign (setq org-table-may-need-update c)))
12372 (delete-char N))
12373 (delete-char N)
12374 (org-fix-tags-on-the-fly)))
12376 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
12377 (put 'org-self-insert-command 'delete-selection t)
12378 (put 'orgtbl-self-insert-command 'delete-selection t)
12379 (put 'org-delete-char 'delete-selection 'supersede)
12380 (put 'org-delete-backward-char 'delete-selection 'supersede)
12382 ;; Make `flyspell-mode' delay after some commands
12383 (put 'org-self-insert-command 'flyspell-delayed t)
12384 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
12385 (put 'org-delete-char 'flyspell-delayed t)
12386 (put 'org-delete-backward-char 'flyspell-delayed t)
12388 ;; Make pabbrev-mode expand after org-mode commands
12389 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
12390 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
12392 ;; How to do this: Measure non-white length of current string
12393 ;; If equal to column width, we should realign.
12395 (defun org-remap (map &rest commands)
12396 "In MAP, remap the functions given in COMMANDS.
12397 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
12398 (let (new old)
12399 (while commands
12400 (setq old (pop commands) new (pop commands))
12401 (if (fboundp 'command-remapping)
12402 (org-defkey map (vector 'remap old) new)
12403 (substitute-key-definition old new map global-map)))))
12405 (when (eq org-enable-table-editor 'optimized)
12406 ;; If the user wants maximum table support, we need to hijack
12407 ;; some standard editing functions
12408 (org-remap org-mode-map
12409 'self-insert-command 'org-self-insert-command
12410 'delete-char 'org-delete-char
12411 'delete-backward-char 'org-delete-backward-char)
12412 (org-defkey org-mode-map "|" 'org-force-self-insert))
12414 (defun org-shiftcursor-error ()
12415 "Throw an error because Shift-Cursor command was applied in wrong context."
12416 (error "This command is active in special context like tables, headlines or timestamps"))
12418 (defun org-shifttab (&optional arg)
12419 "Global visibility cycling or move to previous table field.
12420 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
12421 on context.
12422 See the individual commands for more information."
12423 (interactive "P")
12424 (cond
12425 ((org-at-table-p) (call-interactively 'org-table-previous-field))
12426 ((integerp arg)
12427 (message "Content view to level: %d" arg)
12428 (org-content (prefix-numeric-value arg))
12429 (setq org-cycle-global-status 'overview))
12430 (t (call-interactively 'org-global-cycle))))
12432 (defun org-shiftmetaleft ()
12433 "Promote subtree or delete table column.
12434 Calls `org-promote-subtree', `org-outdent-item',
12435 or `org-table-delete-column', depending on context.
12436 See the individual commands for more information."
12437 (interactive)
12438 (cond
12439 ((org-at-table-p) (call-interactively 'org-table-delete-column))
12440 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
12441 ((org-at-item-p) (call-interactively 'org-outdent-item))
12442 (t (org-shiftcursor-error))))
12444 (defun org-shiftmetaright ()
12445 "Demote subtree or insert table column.
12446 Calls `org-demote-subtree', `org-indent-item',
12447 or `org-table-insert-column', depending on context.
12448 See the individual commands for more information."
12449 (interactive)
12450 (cond
12451 ((org-at-table-p) (call-interactively 'org-table-insert-column))
12452 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
12453 ((org-at-item-p) (call-interactively 'org-indent-item))
12454 (t (org-shiftcursor-error))))
12456 (defun org-shiftmetaup (&optional arg)
12457 "Move subtree up or kill table row.
12458 Calls `org-move-subtree-up' or `org-table-kill-row' or
12459 `org-move-item-up' depending on context. See the individual commands
12460 for more information."
12461 (interactive "P")
12462 (cond
12463 ((org-at-table-p) (call-interactively 'org-table-kill-row))
12464 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12465 ((org-at-item-p) (call-interactively 'org-move-item-up))
12466 (t (org-shiftcursor-error))))
12467 (defun org-shiftmetadown (&optional arg)
12468 "Move subtree down or insert table row.
12469 Calls `org-move-subtree-down' or `org-table-insert-row' or
12470 `org-move-item-down', depending on context. See the individual
12471 commands for more information."
12472 (interactive "P")
12473 (cond
12474 ((org-at-table-p) (call-interactively 'org-table-insert-row))
12475 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12476 ((org-at-item-p) (call-interactively 'org-move-item-down))
12477 (t (org-shiftcursor-error))))
12479 (defun org-metaleft (&optional arg)
12480 "Promote heading or move table column to left.
12481 Calls `org-do-promote' or `org-table-move-column', depending on context.
12482 With no specific context, calls the Emacs default `backward-word'.
12483 See the individual commands for more information."
12484 (interactive "P")
12485 (cond
12486 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
12487 ((or (org-on-heading-p) (org-region-active-p))
12488 (call-interactively 'org-do-promote))
12489 ((org-at-item-p) (call-interactively 'org-outdent-item))
12490 (t (call-interactively 'backward-word))))
12492 (defun org-metaright (&optional arg)
12493 "Demote subtree or move table column to right.
12494 Calls `org-do-demote' or `org-table-move-column', depending on context.
12495 With no specific context, calls the Emacs default `forward-word'.
12496 See the individual commands for more information."
12497 (interactive "P")
12498 (cond
12499 ((org-at-table-p) (call-interactively 'org-table-move-column))
12500 ((or (org-on-heading-p) (org-region-active-p))
12501 (call-interactively 'org-do-demote))
12502 ((org-at-item-p) (call-interactively 'org-indent-item))
12503 (t (call-interactively 'forward-word))))
12505 (defun org-metaup (&optional arg)
12506 "Move subtree up or move table row up.
12507 Calls `org-move-subtree-up' or `org-table-move-row' or
12508 `org-move-item-up', depending on context. See the individual commands
12509 for more information."
12510 (interactive "P")
12511 (cond
12512 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
12513 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12514 ((org-at-item-p) (call-interactively 'org-move-item-up))
12515 (t (transpose-lines 1) (beginning-of-line -1))))
12517 (defun org-metadown (&optional arg)
12518 "Move subtree down or move table row down.
12519 Calls `org-move-subtree-down' or `org-table-move-row' or
12520 `org-move-item-down', depending on context. See the individual
12521 commands for more information."
12522 (interactive "P")
12523 (cond
12524 ((org-at-table-p) (call-interactively 'org-table-move-row))
12525 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12526 ((org-at-item-p) (call-interactively 'org-move-item-down))
12527 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
12529 (defun org-shiftup (&optional arg)
12530 "Increase item in timestamp or increase priority of current headline.
12531 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
12532 depending on context. See the individual commands for more information."
12533 (interactive "P")
12534 (cond
12535 ((org-at-timestamp-p t)
12536 (call-interactively (if org-edit-timestamp-down-means-later
12537 'org-timestamp-down 'org-timestamp-up)))
12538 ((org-on-heading-p) (call-interactively 'org-priority-up))
12539 ((org-at-item-p) (call-interactively 'org-previous-item))
12540 ((org-clocktable-try-shift 'up arg))
12541 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
12543 (defun org-shiftdown (&optional arg)
12544 "Decrease item in timestamp or decrease priority of current headline.
12545 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
12546 depending on context. See the individual commands for more information."
12547 (interactive "P")
12548 (cond
12549 ((org-at-timestamp-p t)
12550 (call-interactively (if org-edit-timestamp-down-means-later
12551 'org-timestamp-up 'org-timestamp-down)))
12552 ((org-on-heading-p) (call-interactively 'org-priority-down))
12553 ((org-clocktable-try-shift 'down arg))
12554 (t (call-interactively 'org-next-item))))
12556 (defun org-shiftright (&optional arg)
12557 "Next TODO keyword or timestamp one day later, depending on context."
12558 (interactive "P")
12559 (cond
12560 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
12561 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
12562 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
12563 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
12564 ((org-clocktable-try-shift 'right arg))
12565 (t (org-shiftcursor-error))))
12567 (defun org-shiftleft (&optional arg)
12568 "Previous TODO keyword or timestamp one day earlier, depending on context."
12569 (interactive "P")
12570 (cond
12571 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
12572 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
12573 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
12574 ((org-at-property-p)
12575 (call-interactively 'org-property-previous-allowed-value))
12576 ((org-clocktable-try-shift 'left arg))
12577 (t (org-shiftcursor-error))))
12579 (defun org-shiftcontrolright ()
12580 "Switch to next TODO set."
12581 (interactive)
12582 (cond
12583 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
12584 (t (org-shiftcursor-error))))
12586 (defun org-shiftcontrolleft ()
12587 "Switch to previous TODO set."
12588 (interactive)
12589 (cond
12590 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
12591 (t (org-shiftcursor-error))))
12593 (defun org-ctrl-c-ret ()
12594 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
12595 (interactive)
12596 (cond
12597 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
12598 (t (call-interactively 'org-insert-heading))))
12600 (defun org-copy-special ()
12601 "Copy region in table or copy current subtree.
12602 Calls `org-table-copy' or `org-copy-subtree', depending on context.
12603 See the individual commands for more information."
12604 (interactive)
12605 (call-interactively
12606 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
12608 (defun org-cut-special ()
12609 "Cut region in table or cut current subtree.
12610 Calls `org-table-copy' or `org-cut-subtree', depending on context.
12611 See the individual commands for more information."
12612 (interactive)
12613 (call-interactively
12614 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
12616 (defun org-paste-special (arg)
12617 "Paste rectangular region into table, or past subtree relative to level.
12618 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
12619 See the individual commands for more information."
12620 (interactive "P")
12621 (if (org-at-table-p)
12622 (org-table-paste-rectangle)
12623 (org-paste-subtree arg)))
12625 (defun org-edit-special ()
12626 "Call a special editor for the stuff at point.
12627 When at a table, call the formula editor with `org-table-edit-formulas'.
12628 When at the first line of an src example, call `org-edit-src-code'.
12629 When in an #+include line, visit the include file. Otherwise call
12630 `ffap' to visit the file at point."
12631 (interactive)
12632 (cond
12633 ((org-at-table-p)
12634 (call-interactively 'org-table-edit-formulas))
12635 ((save-excursion
12636 (beginning-of-line 1)
12637 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
12638 (find-file (org-trim (match-string 1))))
12639 ((org-edit-src-code))
12640 ((org-edit-fixed-width-region))
12641 (t (call-interactively 'ffap))))
12643 (defun org-ctrl-c-ctrl-c (&optional arg)
12644 "Set tags in headline, or update according to changed information at point.
12646 This command does many different things, depending on context:
12648 - If the cursor is in a headline, prompt for tags and insert them
12649 into the current line, aligned to `org-tags-column'. When called
12650 with prefix arg, realign all tags in the current buffer.
12652 - If the cursor is in one of the special #+KEYWORD lines, this
12653 triggers scanning the buffer for these lines and updating the
12654 information.
12656 - If the cursor is inside a table, realign the table. This command
12657 works even if the automatic table editor has been turned off.
12659 - If the cursor is on a #+TBLFM line, re-apply the formulas to
12660 the entire table.
12662 - If the cursor is a the beginning of a dynamic block, update it.
12664 - If the cursor is inside a table created by the table.el package,
12665 activate that table.
12667 - If the current buffer is a remember buffer, close note and file
12668 it. A prefix argument of 1 files to the default location
12669 without further interaction. A prefix argument of 2 files to
12670 the currently clocking task.
12672 - If the cursor is on a <<<target>>>, update radio targets and corresponding
12673 links in this buffer.
12675 - If the cursor is on a numbered item in a plain list, renumber the
12676 ordered list.
12678 - If the cursor is on a checkbox, toggle it."
12679 (interactive "P")
12680 (let ((org-enable-table-editor t))
12681 (cond
12682 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
12683 org-occur-highlights
12684 org-latex-fragment-image-overlays)
12685 (and (boundp 'org-clock-overlays) (org-remove-clock-overlays))
12686 (org-remove-occur-highlights)
12687 (org-remove-latex-fragment-image-overlays)
12688 (message "Temporary highlights/overlays removed from current buffer"))
12689 ((and (local-variable-p 'org-finish-function (current-buffer))
12690 (fboundp org-finish-function))
12691 (funcall org-finish-function))
12692 ((org-at-property-p)
12693 (call-interactively 'org-property-action))
12694 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
12695 ((org-on-heading-p) (call-interactively 'org-set-tags))
12696 ((org-at-table.el-p)
12697 (require 'table)
12698 (beginning-of-line 1)
12699 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
12700 (call-interactively 'table-recognize-table))
12701 ((org-at-table-p)
12702 (org-table-maybe-eval-formula)
12703 (if arg
12704 (call-interactively 'org-table-recalculate)
12705 (org-table-maybe-recalculate-line))
12706 (call-interactively 'org-table-align))
12707 ((org-at-item-checkbox-p)
12708 (call-interactively 'org-toggle-checkbox))
12709 ((org-at-item-p)
12710 (call-interactively 'org-maybe-renumber-ordered-list))
12711 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
12712 ;; Dynamic block
12713 (beginning-of-line 1)
12714 (save-excursion (org-update-dblock)))
12715 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
12716 (cond
12717 ((equal (match-string 1) "TBLFM")
12718 ;; Recalculate the table before this line
12719 (save-excursion
12720 (beginning-of-line 1)
12721 (skip-chars-backward " \r\n\t")
12722 (if (org-at-table-p)
12723 (org-call-with-arg 'org-table-recalculate t))))
12725 ; (org-set-regexps-and-options)
12726 ; (org-restart-font-lock)
12727 (let ((org-inhibit-startup t)) (org-mode-restart))
12728 (message "Local setup has been refreshed"))))
12729 (t (error "C-c C-c can do nothing useful at this location.")))))
12731 (defun org-mode-restart ()
12732 "Restart Org-mode, to scan again for special lines.
12733 Also updates the keyword regular expressions."
12734 (interactive)
12735 (org-mode)
12736 (message "Org-mode restarted"))
12738 (defun org-kill-note-or-show-branches ()
12739 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
12740 (interactive)
12741 (if (not org-finish-function)
12742 (call-interactively 'show-branches)
12743 (let ((org-note-abort t))
12744 (funcall org-finish-function))))
12746 (defun org-return (&optional indent)
12747 "Goto next table row or insert a newline.
12748 Calls `org-table-next-row' or `newline', depending on context.
12749 See the individual commands for more information."
12750 (interactive)
12751 (cond
12752 ((bobp) (if indent (newline-and-indent) (newline)))
12753 ((and (org-at-heading-p)
12754 (looking-at
12755 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
12756 (org-show-entry)
12757 (end-of-line 1)
12758 (newline))
12759 ((org-at-table-p)
12760 (org-table-justify-field-maybe)
12761 (call-interactively 'org-table-next-row))
12762 (t (if indent (newline-and-indent) (newline)))))
12764 (defun org-return-indent ()
12765 "Goto next table row or insert a newline and indent.
12766 Calls `org-table-next-row' or `newline-and-indent', depending on
12767 context. See the individual commands for more information."
12768 (interactive)
12769 (org-return t))
12771 (defun org-ctrl-c-star ()
12772 "Compute table, or change heading status of lines.
12773 Calls `org-table-recalculate' or `org-toggle-region-headings',
12774 depending on context. This will also turn a plain list item or a normal
12775 line into a subheading."
12776 (interactive)
12777 (cond
12778 ((org-at-table-p)
12779 (call-interactively 'org-table-recalculate))
12780 ((org-region-active-p)
12781 ;; Convert all lines in region to list items
12782 (call-interactively 'org-toggle-region-headings))
12783 ((org-on-heading-p)
12784 (org-toggle-region-headings (point-at-bol)
12785 (min (1+ (point-at-eol)) (point-max))))
12786 ((org-at-item-p)
12787 ;; Convert to heading
12788 (let ((level (save-match-data
12789 (save-excursion
12790 (condition-case nil
12791 (progn
12792 (org-back-to-heading t)
12793 (funcall outline-level))
12794 (error 0))))))
12795 (replace-match
12796 (concat (make-string (org-get-valid-level level 1) ?*) " ") t t)))
12797 (t (org-toggle-region-headings (point-at-bol)
12798 (min (1+ (point-at-eol)) (point-max))))))
12800 (defun org-ctrl-c-minus ()
12801 "Insert separator line in table or modify bullet status of line.
12802 Also turns a plain line or a region of lines into list items.
12803 Calls `org-table-insert-hline', `org-toggle-region-items', or
12804 `org-cycle-list-bullet', depending on context."
12805 (interactive)
12806 (cond
12807 ((org-at-table-p)
12808 (call-interactively 'org-table-insert-hline))
12809 ((org-on-heading-p)
12810 ;; Convert to item
12811 (save-excursion
12812 (beginning-of-line 1)
12813 (if (looking-at "\\*+ ")
12814 (replace-match (concat (make-string (- (match-end 0) (point) 1) ?\ ) "- ")))))
12815 ((org-region-active-p)
12816 ;; Convert all lines in region to list items
12817 (call-interactively 'org-toggle-region-items))
12818 ((org-in-item-p)
12819 (call-interactively 'org-cycle-list-bullet))
12820 (t (org-toggle-region-items (point-at-bol)
12821 (min (1+ (point-at-eol)) (point-max))))))
12823 (defun org-toggle-region-items (beg end)
12824 "Convert all lines in region to list items.
12825 If the first line is already an item, convert all list items in the region
12826 to normal lines."
12827 (interactive "r")
12828 (let (l2 l)
12829 (save-excursion
12830 (goto-char end)
12831 (setq l2 (org-current-line))
12832 (goto-char beg)
12833 (beginning-of-line 1)
12834 (setq l (1- (org-current-line)))
12835 (if (org-at-item-p)
12836 ;; We already have items, de-itemize
12837 (while (< (setq l (1+ l)) l2)
12838 (when (org-at-item-p)
12839 (goto-char (match-beginning 2))
12840 (delete-region (match-beginning 2) (match-end 2))
12841 (and (looking-at "[ \t]+") (replace-match "")))
12842 (beginning-of-line 2))
12843 (while (< (setq l (1+ l)) l2)
12844 (unless (org-at-item-p)
12845 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
12846 (replace-match "\\1- \\2")))
12847 (beginning-of-line 2))))))
12849 (defun org-toggle-region-headings (beg end)
12850 "Convert all lines in region to list items.
12851 If the first line is already an item, convert all list items in the region
12852 to normal lines."
12853 (interactive "r")
12854 (let (l2 l)
12855 (save-excursion
12856 (goto-char end)
12857 (setq l2 (org-current-line))
12858 (goto-char beg)
12859 (beginning-of-line 1)
12860 (setq l (1- (org-current-line)))
12861 (if (org-on-heading-p)
12862 ;; We already have headlines, de-star them
12863 (while (< (setq l (1+ l)) l2)
12864 (when (org-on-heading-p t)
12865 (and (looking-at outline-regexp) (replace-match "")))
12866 (beginning-of-line 2))
12867 (let* ((stars (save-excursion
12868 (re-search-backward org-complex-heading-regexp nil t)
12869 (or (match-string 1) "*")))
12870 (add-stars (if org-odd-levels-only "**" "*"))
12871 (rpl (concat stars add-stars " \\2")))
12872 (while (< (setq l (1+ l)) l2)
12873 (unless (org-on-heading-p)
12874 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
12875 (replace-match rpl)))
12876 (beginning-of-line 2)))))))
12878 (defun org-meta-return (&optional arg)
12879 "Insert a new heading or wrap a region in a table.
12880 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
12881 See the individual commands for more information."
12882 (interactive "P")
12883 (cond
12884 ((org-at-table-p)
12885 (call-interactively 'org-table-wrap-region))
12886 (t (call-interactively 'org-insert-heading))))
12888 ;;; Menu entries
12890 ;; Define the Org-mode menus
12891 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
12892 '("Tbl"
12893 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
12894 ["Next Field" org-cycle (org-at-table-p)]
12895 ["Previous Field" org-shifttab (org-at-table-p)]
12896 ["Next Row" org-return (org-at-table-p)]
12897 "--"
12898 ["Blank Field" org-table-blank-field (org-at-table-p)]
12899 ["Edit Field" org-table-edit-field (org-at-table-p)]
12900 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
12901 "--"
12902 ("Column"
12903 ["Move Column Left" org-metaleft (org-at-table-p)]
12904 ["Move Column Right" org-metaright (org-at-table-p)]
12905 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
12906 ["Insert Column" org-shiftmetaright (org-at-table-p)])
12907 ("Row"
12908 ["Move Row Up" org-metaup (org-at-table-p)]
12909 ["Move Row Down" org-metadown (org-at-table-p)]
12910 ["Delete Row" org-shiftmetaup (org-at-table-p)]
12911 ["Insert Row" org-shiftmetadown (org-at-table-p)]
12912 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
12913 "--"
12914 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
12915 ("Rectangle"
12916 ["Copy Rectangle" org-copy-special (org-at-table-p)]
12917 ["Cut Rectangle" org-cut-special (org-at-table-p)]
12918 ["Paste Rectangle" org-paste-special (org-at-table-p)]
12919 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
12920 "--"
12921 ("Calculate"
12922 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
12923 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
12924 ["Edit Formulas" org-edit-special (org-at-table-p)]
12925 "--"
12926 ["Recalculate line" org-table-recalculate (org-at-table-p)]
12927 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
12928 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
12929 "--"
12930 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
12931 "--"
12932 ["Sum Column/Rectangle" org-table-sum
12933 (or (org-at-table-p) (org-region-active-p))]
12934 ["Which Column?" org-table-current-column (org-at-table-p)])
12935 ["Debug Formulas"
12936 org-table-toggle-formula-debugger
12937 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
12938 ["Show Col/Row Numbers"
12939 org-table-toggle-coordinate-overlays
12940 :style toggle
12941 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
12942 "--"
12943 ["Create" org-table-create (and (not (org-at-table-p))
12944 org-enable-table-editor)]
12945 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
12946 ["Import from File" org-table-import (not (org-at-table-p))]
12947 ["Export to File" org-table-export (org-at-table-p)]
12948 "--"
12949 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
12951 (easy-menu-define org-org-menu org-mode-map "Org menu"
12952 '("Org"
12953 ("Show/Hide"
12954 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
12955 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
12956 ["Sparse Tree..." org-sparse-tree t]
12957 ["Reveal Context" org-reveal t]
12958 ["Show All" show-all t]
12959 "--"
12960 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
12961 "--"
12962 ["New Heading" org-insert-heading t]
12963 ("Navigate Headings"
12964 ["Up" outline-up-heading t]
12965 ["Next" outline-next-visible-heading t]
12966 ["Previous" outline-previous-visible-heading t]
12967 ["Next Same Level" outline-forward-same-level t]
12968 ["Previous Same Level" outline-backward-same-level t]
12969 "--"
12970 ["Jump" org-goto t])
12971 ("Edit Structure"
12972 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
12973 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
12974 "--"
12975 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
12976 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
12977 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
12978 "--"
12979 ["Promote Heading" org-metaleft (not (org-at-table-p))]
12980 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
12981 ["Demote Heading" org-metaright (not (org-at-table-p))]
12982 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
12983 "--"
12984 ["Sort Region/Children" org-sort (not (org-at-table-p))]
12985 "--"
12986 ["Convert to odd levels" org-convert-to-odd-levels t]
12987 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
12988 ("Editing"
12989 ["Emphasis..." org-emphasize t]
12990 ["Edit Source Example" org-edit-special t])
12991 ("Archive"
12992 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
12993 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
12994 ; :active t :keys "C-u C-c C-x C-a"]
12995 ["Sparse trees open ARCHIVE trees"
12996 (setq org-sparse-tree-open-archived-trees
12997 (not org-sparse-tree-open-archived-trees))
12998 :style toggle :selected org-sparse-tree-open-archived-trees]
12999 ["Cycling opens ARCHIVE trees"
13000 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
13001 :style toggle :selected org-cycle-open-archived-trees]
13002 "--"
13003 ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
13004 ["Move Subtree to Archive" org-advertized-archive-subtree t]
13005 ; ["Check and Move Children" (org-archive-subtree '(4))
13006 ; :active t :keys "C-u C-c C-x C-s"]
13008 "--"
13009 ("TODO Lists"
13010 ["TODO/DONE/-" org-todo t]
13011 ("Select keyword"
13012 ["Next keyword" org-shiftright (org-on-heading-p)]
13013 ["Previous keyword" org-shiftleft (org-on-heading-p)]
13014 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
13015 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
13016 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
13017 ["Show TODO Tree" org-show-todo-tree t]
13018 ["Global TODO list" org-todo-list t]
13019 "--"
13020 ["Set Priority" org-priority t]
13021 ["Priority Up" org-shiftup t]
13022 ["Priority Down" org-shiftdown t])
13023 ("TAGS and Properties"
13024 ["Set Tags" 'org-set-tags-command t]
13025 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
13026 "--"
13027 ["Set property" 'org-set-property t]
13028 ["Column view of properties" org-columns t]
13029 ["Insert Column View DBlock" org-insert-columns-dblock t])
13030 ("Dates and Scheduling"
13031 ["Timestamp" org-time-stamp t]
13032 ["Timestamp (inactive)" org-time-stamp-inactive t]
13033 ("Change Date"
13034 ["1 Day Later" org-shiftright t]
13035 ["1 Day Earlier" org-shiftleft t]
13036 ["1 ... Later" org-shiftup t]
13037 ["1 ... Earlier" org-shiftdown t])
13038 ["Compute Time Range" org-evaluate-time-range t]
13039 ["Schedule Item" org-schedule t]
13040 ["Deadline" org-deadline t]
13041 "--"
13042 ["Custom time format" org-toggle-time-stamp-overlays
13043 :style radio :selected org-display-custom-times]
13044 "--"
13045 ["Goto Calendar" org-goto-calendar t]
13046 ["Date from Calendar" org-date-from-calendar t])
13047 ("Logging work"
13048 ["Clock in" org-clock-in t]
13049 ["Clock out" org-clock-out t]
13050 ["Clock cancel" org-clock-cancel t]
13051 ["Goto running clock" org-clock-goto t]
13052 ["Display times" org-clock-display t]
13053 ["Create clock table" org-clock-report t]
13054 "--"
13055 ["Record DONE time"
13056 (progn (setq org-log-done (not org-log-done))
13057 (message "Switching to %s will %s record a timestamp"
13058 (car org-done-keywords)
13059 (if org-log-done "automatically" "not")))
13060 :style toggle :selected org-log-done])
13061 "--"
13062 ["Agenda Command..." org-agenda t]
13063 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
13064 ("File List for Agenda")
13065 ("Special views current file"
13066 ["TODO Tree" org-show-todo-tree t]
13067 ["Check Deadlines" org-check-deadlines t]
13068 ["Timeline" org-timeline t]
13069 ["Tags Tree" org-tags-sparse-tree t])
13070 "--"
13071 ("Hyperlinks"
13072 ["Store Link (Global)" org-store-link t]
13073 ["Insert Link" org-insert-link t]
13074 ["Follow Link" org-open-at-point t]
13075 "--"
13076 ["Next link" org-next-link t]
13077 ["Previous link" org-previous-link t]
13078 "--"
13079 ["Descriptive Links"
13080 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
13081 :style radio
13082 :selected (member '(org-link) buffer-invisibility-spec)]
13083 ["Literal Links"
13084 (progn
13085 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
13086 :style radio
13087 :selected (not (member '(org-link) buffer-invisibility-spec))])
13088 "--"
13089 ["Export/Publish..." org-export t]
13090 ("LaTeX"
13091 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
13092 :selected org-cdlatex-mode]
13093 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
13094 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
13095 ["Modify math symbol" org-cdlatex-math-modify
13096 (org-inside-LaTeX-fragment-p)]
13097 ["Export LaTeX fragments as images"
13098 (if (featurep 'org-exp)
13099 (setq org-export-with-LaTeX-fragments
13100 (not org-export-with-LaTeX-fragments))
13101 (require 'org-exp))
13102 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
13103 org-export-with-LaTeX-fragments)])
13104 "--"
13105 ("Documentation"
13106 ["Show Version" org-version t]
13107 ["Info Documentation" org-info t])
13108 ("Customize"
13109 ["Browse Org Group" org-customize t]
13110 "--"
13111 ["Expand This Menu" org-create-customize-menu
13112 (fboundp 'customize-menu-create)])
13113 "--"
13114 ["Refresh setup" org-mode-restart t]
13117 (defun org-info (&optional node)
13118 "Read documentation for Org-mode in the info system.
13119 With optional NODE, go directly to that node."
13120 (interactive)
13121 (info (format "(org)%s" (or node ""))))
13123 (defun org-install-agenda-files-menu ()
13124 (let ((bl (buffer-list)))
13125 (save-excursion
13126 (while bl
13127 (set-buffer (pop bl))
13128 (if (org-mode-p) (setq bl nil)))
13129 (when (org-mode-p)
13130 (easy-menu-change
13131 '("Org") "File List for Agenda"
13132 (append
13133 (list
13134 ["Edit File List" (org-edit-agenda-file-list) t]
13135 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
13136 ["Remove Current File from List" org-remove-file t]
13137 ["Cycle through agenda files" org-cycle-agenda-files t]
13138 ["Occur in all agenda files" org-occur-in-agenda-files t]
13139 "--")
13140 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
13142 ;;;; Documentation
13144 ;;;###autoload
13145 (defun org-require-autoloaded-modules ()
13146 (interactive)
13147 (mapc 'require
13148 '(org-agenda org-archive org-clock org-colview
13149 org-exp org-id org-export-latex org-publish
13150 org-remember org-table)))
13152 ;;;###autoload
13153 (defun org-customize ()
13154 "Call the customize function with org as argument."
13155 (interactive)
13156 (org-load-modules-maybe)
13157 (org-require-autoloaded-modules)
13158 (customize-browse 'org))
13160 (defun org-create-customize-menu ()
13161 "Create a full customization menu for Org-mode, insert it into the menu."
13162 (interactive)
13163 (org-load-modules-maybe)
13164 (org-require-autoloaded-modules)
13165 (if (fboundp 'customize-menu-create)
13166 (progn
13167 (easy-menu-change
13168 '("Org") "Customize"
13169 `(["Browse Org group" org-customize t]
13170 "--"
13171 ,(customize-menu-create 'org)
13172 ["Set" Custom-set t]
13173 ["Save" Custom-save t]
13174 ["Reset to Current" Custom-reset-current t]
13175 ["Reset to Saved" Custom-reset-saved t]
13176 ["Reset to Standard Settings" Custom-reset-standard t]))
13177 (message "\"Org\"-menu now contains full customization menu"))
13178 (error "Cannot expand menu (outdated version of cus-edit.el)")))
13180 ;;;; Miscellaneous stuff
13182 ;;; Generally useful functions
13184 (defun org-display-warning (message) ;; Copied from Emacs-Muse
13185 "Display the given MESSAGE as a warning."
13186 (if (fboundp 'display-warning)
13187 (display-warning 'org message
13188 (if (featurep 'xemacs)
13189 'warning
13190 :warning))
13191 (let ((buf (get-buffer-create "*Org warnings*")))
13192 (with-current-buffer buf
13193 (goto-char (point-max))
13194 (insert "Warning (Org): " message)
13195 (unless (bolp)
13196 (newline)))
13197 (display-buffer buf)
13198 (sit-for 0))))
13200 (defun org-goto-marker-or-bmk (marker &optional bookmark)
13201 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
13202 (if (and marker (marker-buffer marker)
13203 (buffer-live-p (marker-buffer marker)))
13204 (progn
13205 (switch-to-buffer (marker-buffer marker))
13206 (if (or (> marker (point-max)) (< marker (point-min)))
13207 (widen))
13208 (goto-char marker))
13209 (if bookmark
13210 (bookmark-jump bookmark)
13211 (error "Cannot find location"))))
13213 (defun org-quote-csv-field (s)
13214 "Quote field for inclusion in CSV material."
13215 (if (string-match "[\",]" s)
13216 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
13219 (defun org-plist-delete (plist property)
13220 "Delete PROPERTY from PLIST.
13221 This is in contrast to merely setting it to 0."
13222 (let (p)
13223 (while plist
13224 (if (not (eq property (car plist)))
13225 (setq p (plist-put p (car plist) (nth 1 plist))))
13226 (setq plist (cddr plist)))
13229 (defun org-force-self-insert (N)
13230 "Needed to enforce self-insert under remapping."
13231 (interactive "p")
13232 (self-insert-command N))
13234 (defun org-string-width (s)
13235 "Compute width of string, ignoring invisible characters.
13236 This ignores character with invisibility property `org-link', and also
13237 characters with property `org-cwidth', because these will become invisible
13238 upon the next fontification round."
13239 (let (b l)
13240 (when (or (eq t buffer-invisibility-spec)
13241 (assq 'org-link buffer-invisibility-spec))
13242 (while (setq b (text-property-any 0 (length s)
13243 'invisible 'org-link s))
13244 (setq s (concat (substring s 0 b)
13245 (substring s (or (next-single-property-change
13246 b 'invisible s) (length s)))))))
13247 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
13248 (setq s (concat (substring s 0 b)
13249 (substring s (or (next-single-property-change
13250 b 'org-cwidth s) (length s))))))
13251 (setq l (string-width s) b -1)
13252 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
13253 (setq l (- l (get-text-property b 'org-dwidth-n s))))
13256 (defun org-get-indentation (&optional line)
13257 "Get the indentation of the current line, interpreting tabs.
13258 When LINE is given, assume it represents a line and compute its indentation."
13259 (if line
13260 (if (string-match "^ *" (org-remove-tabs line))
13261 (match-end 0))
13262 (save-excursion
13263 (beginning-of-line 1)
13264 (skip-chars-forward " \t")
13265 (current-column))))
13267 (defun org-remove-tabs (s &optional width)
13268 "Replace tabulators in S with spaces.
13269 Assumes that s is a single line, starting in column 0."
13270 (setq width (or width tab-width))
13271 (while (string-match "\t" s)
13272 (setq s (replace-match
13273 (make-string
13274 (- (* width (/ (+ (match-beginning 0) width) width))
13275 (match-beginning 0)) ?\ )
13276 t t s)))
13279 (defun org-fix-indentation (line ind)
13280 "Fix indentation in LINE.
13281 IND is a cons cell with target and minimum indentation.
13282 If the current indenation in LINE is smaller than the minimum,
13283 leave it alone. If it is larger than ind, set it to the target."
13284 (let* ((l (org-remove-tabs line))
13285 (i (org-get-indentation l))
13286 (i1 (car ind)) (i2 (cdr ind)))
13287 (if (>= i i2) (setq l (substring line i2)))
13288 (if (> i1 0)
13289 (concat (make-string i1 ?\ ) l)
13290 l)))
13292 (defun org-base-buffer (buffer)
13293 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
13294 (if (not buffer)
13295 buffer
13296 (or (buffer-base-buffer buffer)
13297 buffer)))
13299 (defun org-trim (s)
13300 "Remove whitespace at beginning and end of string."
13301 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
13302 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
13305 (defun org-wrap (string &optional width lines)
13306 "Wrap string to either a number of lines, or a width in characters.
13307 If WIDTH is non-nil, the string is wrapped to that width, however many lines
13308 that costs. If there is a word longer than WIDTH, the text is actually
13309 wrapped to the length of that word.
13310 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
13311 many lines, whatever width that takes.
13312 The return value is a list of lines, without newlines at the end."
13313 (let* ((words (org-split-string string "[ \t\n]+"))
13314 (maxword (apply 'max (mapcar 'org-string-width words)))
13315 w ll)
13316 (cond (width
13317 (org-do-wrap words (max maxword width)))
13318 (lines
13319 (setq w maxword)
13320 (setq ll (org-do-wrap words maxword))
13321 (if (<= (length ll) lines)
13323 (setq ll words)
13324 (while (> (length ll) lines)
13325 (setq w (1+ w))
13326 (setq ll (org-do-wrap words w)))
13327 ll))
13328 (t (error "Cannot wrap this")))))
13330 (defun org-do-wrap (words width)
13331 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
13332 (let (lines line)
13333 (while words
13334 (setq line (pop words))
13335 (while (and words (< (+ (length line) (length (car words))) width))
13336 (setq line (concat line " " (pop words))))
13337 (setq lines (push line lines)))
13338 (nreverse lines)))
13340 (defun org-split-string (string &optional separators)
13341 "Splits STRING into substrings at SEPARATORS.
13342 No empty strings are returned if there are matches at the beginning
13343 and end of string."
13344 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
13345 (start 0)
13346 notfirst
13347 (list nil))
13348 (while (and (string-match rexp string
13349 (if (and notfirst
13350 (= start (match-beginning 0))
13351 (< start (length string)))
13352 (1+ start) start))
13353 (< (match-beginning 0) (length string)))
13354 (setq notfirst t)
13355 (or (eq (match-beginning 0) 0)
13356 (and (eq (match-beginning 0) (match-end 0))
13357 (eq (match-beginning 0) start))
13358 (setq list
13359 (cons (substring string start (match-beginning 0))
13360 list)))
13361 (setq start (match-end 0)))
13362 (or (eq start (length string))
13363 (setq list
13364 (cons (substring string start)
13365 list)))
13366 (nreverse list)))
13368 (defun org-context ()
13369 "Return a list of contexts of the current cursor position.
13370 If several contexts apply, all are returned.
13371 Each context entry is a list with a symbol naming the context, and
13372 two positions indicating start and end of the context. Possible
13373 contexts are:
13375 :headline anywhere in a headline
13376 :headline-stars on the leading stars in a headline
13377 :todo-keyword on a TODO keyword (including DONE) in a headline
13378 :tags on the TAGS in a headline
13379 :priority on the priority cookie in a headline
13380 :item on the first line of a plain list item
13381 :item-bullet on the bullet/number of a plain list item
13382 :checkbox on the checkbox in a plain list item
13383 :table in an org-mode table
13384 :table-special on a special filed in a table
13385 :table-table in a table.el table
13386 :link on a hyperlink
13387 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
13388 :target on a <<target>>
13389 :radio-target on a <<<radio-target>>>
13390 :latex-fragment on a LaTeX fragment
13391 :latex-preview on a LaTeX fragment with overlayed preview image
13393 This function expects the position to be visible because it uses font-lock
13394 faces as a help to recognize the following contexts: :table-special, :link,
13395 and :keyword."
13396 (let* ((f (get-text-property (point) 'face))
13397 (faces (if (listp f) f (list f)))
13398 (p (point)) clist o)
13399 ;; First the large context
13400 (cond
13401 ((org-on-heading-p t)
13402 (push (list :headline (point-at-bol) (point-at-eol)) clist)
13403 (when (progn
13404 (beginning-of-line 1)
13405 (looking-at org-todo-line-tags-regexp))
13406 (push (org-point-in-group p 1 :headline-stars) clist)
13407 (push (org-point-in-group p 2 :todo-keyword) clist)
13408 (push (org-point-in-group p 4 :tags) clist))
13409 (goto-char p)
13410 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
13411 (if (looking-at "\\[#[A-Z0-9]\\]")
13412 (push (org-point-in-group p 0 :priority) clist)))
13414 ((org-at-item-p)
13415 (push (org-point-in-group p 2 :item-bullet) clist)
13416 (push (list :item (point-at-bol)
13417 (save-excursion (org-end-of-item) (point)))
13418 clist)
13419 (and (org-at-item-checkbox-p)
13420 (push (org-point-in-group p 0 :checkbox) clist)))
13422 ((org-at-table-p)
13423 (push (list :table (org-table-begin) (org-table-end)) clist)
13424 (if (memq 'org-formula faces)
13425 (push (list :table-special
13426 (previous-single-property-change p 'face)
13427 (next-single-property-change p 'face)) clist)))
13428 ((org-at-table-p 'any)
13429 (push (list :table-table) clist)))
13430 (goto-char p)
13432 ;; Now the small context
13433 (cond
13434 ((org-at-timestamp-p)
13435 (push (org-point-in-group p 0 :timestamp) clist))
13436 ((memq 'org-link faces)
13437 (push (list :link
13438 (previous-single-property-change p 'face)
13439 (next-single-property-change p 'face)) clist))
13440 ((memq 'org-special-keyword faces)
13441 (push (list :keyword
13442 (previous-single-property-change p 'face)
13443 (next-single-property-change p 'face)) clist))
13444 ((org-on-target-p)
13445 (push (org-point-in-group p 0 :target) clist)
13446 (goto-char (1- (match-beginning 0)))
13447 (if (looking-at org-radio-target-regexp)
13448 (push (org-point-in-group p 0 :radio-target) clist))
13449 (goto-char p))
13450 ((setq o (car (delq nil
13451 (mapcar
13452 (lambda (x)
13453 (if (memq x org-latex-fragment-image-overlays) x))
13454 (org-overlays-at (point))))))
13455 (push (list :latex-fragment
13456 (org-overlay-start o) (org-overlay-end o)) clist)
13457 (push (list :latex-preview
13458 (org-overlay-start o) (org-overlay-end o)) clist))
13459 ((org-inside-LaTeX-fragment-p)
13460 ;; FIXME: positions wrong.
13461 (push (list :latex-fragment (point) (point)) clist)))
13463 (setq clist (nreverse (delq nil clist)))
13464 clist))
13466 ;; FIXME: Compare with at-regexp-p Do we need both?
13467 (defun org-in-regexp (re &optional nlines visually)
13468 "Check if point is inside a match of regexp.
13469 Normally only the current line is checked, but you can include NLINES extra
13470 lines both before and after point into the search.
13471 If VISUALLY is set, require that the cursor is not after the match but
13472 really on, so that the block visually is on the match."
13473 (catch 'exit
13474 (let ((pos (point))
13475 (eol (point-at-eol (+ 1 (or nlines 0))))
13476 (inc (if visually 1 0)))
13477 (save-excursion
13478 (beginning-of-line (- 1 (or nlines 0)))
13479 (while (re-search-forward re eol t)
13480 (if (and (<= (match-beginning 0) pos)
13481 (>= (+ inc (match-end 0)) pos))
13482 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
13484 (defun org-at-regexp-p (regexp)
13485 "Is point inside a match of REGEXP in the current line?"
13486 (catch 'exit
13487 (save-excursion
13488 (let ((pos (point)) (end (point-at-eol)))
13489 (beginning-of-line 1)
13490 (while (re-search-forward regexp end t)
13491 (if (and (<= (match-beginning 0) pos)
13492 (>= (match-end 0) pos))
13493 (throw 'exit t)))
13494 nil))))
13496 (defun org-occur-in-agenda-files (regexp &optional nlines)
13497 "Call `multi-occur' with buffers for all agenda files."
13498 (interactive "sOrg-files matching: \np")
13499 (let* ((files (org-agenda-files))
13500 (tnames (mapcar 'file-truename files))
13501 (extra org-agenda-text-search-extra-files)
13503 (when (eq (car extra) 'agenda-archives)
13504 (setq extra (cdr extra))
13505 (setq files (org-add-archive-files files)))
13506 (while (setq f (pop extra))
13507 (unless (member (file-truename f) tnames)
13508 (add-to-list 'files f 'append)
13509 (add-to-list 'tnames (file-truename f) 'append)))
13510 (multi-occur
13511 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
13512 regexp)))
13514 (if (boundp 'occur-mode-find-occurrence-hook)
13515 ;; Emacs 23
13516 (add-hook 'occur-mode-find-occurrence-hook
13517 (lambda ()
13518 (when (org-mode-p)
13519 (org-reveal))))
13520 ;; Emacs 22
13521 (defadvice occur-mode-goto-occurrence
13522 (after org-occur-reveal activate)
13523 (and (org-mode-p) (org-reveal)))
13524 (defadvice occur-mode-goto-occurrence-other-window
13525 (after org-occur-reveal activate)
13526 (and (org-mode-p) (org-reveal)))
13527 (defadvice occur-mode-display-occurrence
13528 (after org-occur-reveal activate)
13529 (when (org-mode-p)
13530 (let ((pos (occur-mode-find-occurrence)))
13531 (with-current-buffer (marker-buffer pos)
13532 (save-excursion
13533 (goto-char pos)
13534 (org-reveal)))))))
13536 (defun org-uniquify (list)
13537 "Remove duplicate elements from LIST."
13538 (let (res)
13539 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
13540 res))
13542 (defun org-delete-all (elts list)
13543 "Remove all elements in ELTS from LIST."
13544 (while elts
13545 (setq list (delete (pop elts) list)))
13546 list)
13548 (defun org-back-over-empty-lines ()
13549 "Move backwards over witespace, to the beginning of the first empty line.
13550 Returns the number of empty lines passed."
13551 (let ((pos (point)))
13552 (skip-chars-backward " \t\n\r")
13553 (beginning-of-line 2)
13554 (goto-char (min (point) pos))
13555 (count-lines (point) pos)))
13557 (defun org-skip-whitespace ()
13558 (skip-chars-forward " \t\n\r"))
13560 (defun org-point-in-group (point group &optional context)
13561 "Check if POINT is in match-group GROUP.
13562 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
13563 match. If the match group does ot exist or point is not inside it,
13564 return nil."
13565 (and (match-beginning group)
13566 (>= point (match-beginning group))
13567 (<= point (match-end group))
13568 (if context
13569 (list context (match-beginning group) (match-end group))
13570 t)))
13572 (defun org-switch-to-buffer-other-window (&rest args)
13573 "Switch to buffer in a second window on the current frame.
13574 In particular, do not allow pop-up frames."
13575 (let (pop-up-frames special-display-buffer-names special-display-regexps
13576 special-display-function)
13577 (apply 'switch-to-buffer-other-window args)))
13579 (defun org-combine-plists (&rest plists)
13580 "Create a single property list from all plists in PLISTS.
13581 The process starts by copying the first list, and then setting properties
13582 from the other lists. Settings in the last list are the most significant
13583 ones and overrule settings in the other lists."
13584 (let ((rtn (copy-sequence (pop plists)))
13585 p v ls)
13586 (while plists
13587 (setq ls (pop plists))
13588 (while ls
13589 (setq p (pop ls) v (pop ls))
13590 (setq rtn (plist-put rtn p v))))
13591 rtn))
13593 (defun org-move-line-down (arg)
13594 "Move the current line down. With prefix argument, move it past ARG lines."
13595 (interactive "p")
13596 (let ((col (current-column))
13597 beg end pos)
13598 (beginning-of-line 1) (setq beg (point))
13599 (beginning-of-line 2) (setq end (point))
13600 (beginning-of-line (+ 1 arg))
13601 (setq pos (move-marker (make-marker) (point)))
13602 (insert (delete-and-extract-region beg end))
13603 (goto-char pos)
13604 (org-move-to-column col)))
13606 (defun org-move-line-up (arg)
13607 "Move the current line up. With prefix argument, move it past ARG lines."
13608 (interactive "p")
13609 (let ((col (current-column))
13610 beg end pos)
13611 (beginning-of-line 1) (setq beg (point))
13612 (beginning-of-line 2) (setq end (point))
13613 (beginning-of-line (- arg))
13614 (setq pos (move-marker (make-marker) (point)))
13615 (insert (delete-and-extract-region beg end))
13616 (goto-char pos)
13617 (org-move-to-column col)))
13619 (defun org-replace-escapes (string table)
13620 "Replace %-escapes in STRING with values in TABLE.
13621 TABLE is an association list with keys like \"%a\" and string values.
13622 The sequences in STRING may contain normal field width and padding information,
13623 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
13624 so values can contain further %-escapes if they are define later in TABLE."
13625 (let ((case-fold-search nil)
13626 e re rpl)
13627 (while (setq e (pop table))
13628 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
13629 (while (string-match re string)
13630 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
13631 (cdr e)))
13632 (setq string (replace-match rpl t t string))))
13633 string))
13636 (defun org-sublist (list start end)
13637 "Return a section of LIST, from START to END.
13638 Counting starts at 1."
13639 (let (rtn (c start))
13640 (setq list (nthcdr (1- start) list))
13641 (while (and list (<= c end))
13642 (push (pop list) rtn)
13643 (setq c (1+ c)))
13644 (nreverse rtn)))
13646 (defun org-find-base-buffer-visiting (file)
13647 "Like `find-buffer-visiting' but alway return the base buffer and
13648 not an indirect buffer."
13649 (let ((buf (find-buffer-visiting file)))
13650 (if buf
13651 (or (buffer-base-buffer buf) buf)
13652 nil)))
13654 (defun org-image-file-name-regexp ()
13655 "Return regexp matching the file names of images."
13656 (if (fboundp 'image-file-name-regexp)
13657 (image-file-name-regexp)
13658 (let ((image-file-name-extensions
13659 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
13660 "xbm" "xpm" "pbm" "pgm" "ppm")))
13661 (concat "\\."
13662 (regexp-opt (nconc (mapcar 'upcase
13663 image-file-name-extensions)
13664 image-file-name-extensions)
13666 "\\'"))))
13668 (defun org-file-image-p (file)
13669 "Return non-nil if FILE is an image."
13670 (save-match-data
13671 (string-match (org-image-file-name-regexp) file)))
13673 (defun org-get-cursor-date ()
13674 "Return the date at cursor in as a time.
13675 This works in the calendar and in the agenda, anywhere else it just
13676 returns the current time."
13677 (let (date day defd)
13678 (cond
13679 ((eq major-mode 'calendar-mode)
13680 (setq date (calendar-cursor-to-date)
13681 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13682 ((eq major-mode 'org-agenda-mode)
13683 (setq day (get-text-property (point) 'day))
13684 (if day
13685 (setq date (calendar-gregorian-from-absolute day)
13686 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
13687 (nth 2 date))))))
13688 (or defd (current-time))))
13690 (defvar org-agenda-action-marker (make-marker)
13691 "Marker pointing to the entry for the next agenda action.")
13693 (defun org-mark-entry-for-agenda-action ()
13694 "Mark the current entry as target of an agenda action.
13695 Agenda actions are actions executed from the agenda with the key `k',
13696 which make use of the date at the cursor."
13697 (interactive)
13698 (move-marker org-agenda-action-marker
13699 (save-excursion (org-back-to-heading t) (point))
13700 (current-buffer))
13701 (message
13702 "Entry marked for action; press `k' at desired date in agenda or calendar"))
13704 ;;; Paragraph filling stuff.
13705 ;; We want this to be just right, so use the full arsenal.
13707 (defun org-indent-line-function ()
13708 "Indent line like previous, but further if previous was headline or item."
13709 (interactive)
13710 (let* ((pos (point))
13711 (itemp (org-at-item-p))
13712 column bpos bcol tpos tcol bullet btype bullet-type)
13713 ;; Find the previous relevant line
13714 (beginning-of-line 1)
13715 (cond
13716 ((looking-at "#") (setq column 0))
13717 ((looking-at "\\*+ ") (setq column 0))
13719 (beginning-of-line 0)
13720 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
13721 (beginning-of-line 0))
13722 (cond
13723 ((looking-at "\\*+[ \t]+")
13724 (if (not org-adapt-indentation)
13725 (setq column 0)
13726 (goto-char (match-end 0))
13727 (setq column (current-column))))
13728 ((org-in-item-p)
13729 (org-beginning-of-item)
13730 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
13731 (setq bpos (match-beginning 1) tpos (match-end 0)
13732 bcol (progn (goto-char bpos) (current-column))
13733 tcol (progn (goto-char tpos) (current-column))
13734 bullet (match-string 1)
13735 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
13736 (if (> tcol (+ bcol org-description-max-indent))
13737 (setq tcol (+ bcol 5)))
13738 (if (not itemp)
13739 (setq column tcol)
13740 (goto-char pos)
13741 (beginning-of-line 1)
13742 (if (looking-at "\\S-")
13743 (progn
13744 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
13745 (setq bullet (match-string 1)
13746 btype (if (string-match "[0-9]" bullet) "n" bullet))
13747 (setq column (if (equal btype bullet-type) bcol tcol)))
13748 (setq column (org-get-indentation)))))
13749 (t (setq column (org-get-indentation))))))
13750 (goto-char pos)
13751 (if (<= (current-column) (current-indentation))
13752 (org-indent-line-to column)
13753 (save-excursion (org-indent-line-to column)))
13754 (setq column (current-column))
13755 (beginning-of-line 1)
13756 (if (looking-at
13757 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
13758 (replace-match (concat "\\1" (format org-property-format
13759 (match-string 2) (match-string 3)))
13760 t nil))
13761 (org-move-to-column column)))
13763 (defun org-set-autofill-regexps ()
13764 (interactive)
13765 ;; In the paragraph separator we include headlines, because filling
13766 ;; text in a line directly attached to a headline would otherwise
13767 ;; fill the headline as well.
13768 (org-set-local 'comment-start-skip "^#+[ \t]*")
13769 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
13770 ;; The paragraph starter includes hand-formatted lists.
13771 (org-set-local 'paragraph-start
13772 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
13773 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
13774 ;; But only if the user has not turned off tables or fixed-width regions
13775 (org-set-local
13776 'auto-fill-inhibit-regexp
13777 (concat "\\*+ \\|#\\+"
13778 "\\|[ \t]*" org-keyword-time-regexp
13779 (if (or org-enable-table-editor org-enable-fixed-width-editor)
13780 (concat
13781 "\\|[ \t]*["
13782 (if org-enable-table-editor "|" "")
13783 (if org-enable-fixed-width-editor ":" "")
13784 "]"))))
13785 ;; We use our own fill-paragraph function, to make sure that tables
13786 ;; and fixed-width regions are not wrapped. That function will pass
13787 ;; through to `fill-paragraph' when appropriate.
13788 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
13789 ; Adaptive filling: To get full control, first make sure that
13790 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
13791 (org-set-local 'adaptive-fill-regexp "\000")
13792 (org-set-local 'adaptive-fill-function
13793 'org-adaptive-fill-function)
13794 (org-set-local
13795 'align-mode-rules-list
13796 '((org-in-buffer-settings
13797 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
13798 (modes . '(org-mode))))))
13800 (defun org-fill-paragraph (&optional justify)
13801 "Re-align a table, pass through to fill-paragraph if no table."
13802 (let ((table-p (org-at-table-p))
13803 (table.el-p (org-at-table.el-p)))
13804 (cond ((and (equal (char-after (point-at-bol)) ?*)
13805 (save-excursion (goto-char (point-at-bol))
13806 (looking-at outline-regexp)))
13807 t) ; skip headlines
13808 (table.el-p t) ; skip table.el tables
13809 (table-p (org-table-align) t) ; align org-mode tables
13810 (t nil)))) ; call paragraph-fill
13812 ;; For reference, this is the default value of adaptive-fill-regexp
13813 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
13815 (defun org-adaptive-fill-function ()
13816 "Return a fill prefix for org-mode files.
13817 In particular, this makes sure hanging paragraphs for hand-formatted lists
13818 work correctly."
13819 (cond ((looking-at "#[ \t]+")
13820 (match-string 0))
13821 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
13822 (save-excursion
13823 (if (> (match-end 1) (+ (match-beginning 1)
13824 org-description-max-indent))
13825 (goto-char (+ (match-beginning 1) 5))
13826 (goto-char (match-end 0)))
13827 (make-string (current-column) ?\ )))
13828 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
13829 (save-excursion
13830 (goto-char (match-end 0))
13831 (make-string (current-column) ?\ )))
13832 (t nil)))
13834 ;;; Other stuff.
13836 (defun org-toggle-fixed-width-section (arg)
13837 "Toggle the fixed-width export.
13838 If there is no active region, the QUOTE keyword at the current headline is
13839 inserted or removed. When present, it causes the text between this headline
13840 and the next to be exported as fixed-width text, and unmodified.
13841 If there is an active region, this command adds or removes a colon as the
13842 first character of this line. If the first character of a line is a colon,
13843 this line is also exported in fixed-width font."
13844 (interactive "P")
13845 (let* ((cc 0)
13846 (regionp (org-region-active-p))
13847 (beg (if regionp (region-beginning) (point)))
13848 (end (if regionp (region-end)))
13849 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
13850 (case-fold-search nil)
13851 (re "[ \t]*\\(:\\)")
13852 off)
13853 (if regionp
13854 (save-excursion
13855 (goto-char beg)
13856 (setq cc (current-column))
13857 (beginning-of-line 1)
13858 (setq off (looking-at re))
13859 (while (> nlines 0)
13860 (setq nlines (1- nlines))
13861 (beginning-of-line 1)
13862 (cond
13863 (arg
13864 (org-move-to-column cc t)
13865 (insert ":\n")
13866 (forward-line -1))
13867 ((and off (looking-at re))
13868 (replace-match "" t t nil 1))
13869 ((not off) (org-move-to-column cc t) (insert ":")))
13870 (forward-line 1)))
13871 (save-excursion
13872 (org-back-to-heading)
13873 (if (looking-at (concat outline-regexp
13874 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
13875 (replace-match "" t t nil 1)
13876 (if (looking-at outline-regexp)
13877 (progn
13878 (goto-char (match-end 0))
13879 (insert org-quote-string " "))))))))
13881 ;;;; Functions extending outline functionality
13883 (defun org-beginning-of-line (&optional arg)
13884 "Go to the beginning of the current line. If that is invisible, continue
13885 to a visible line beginning. This makes the function of C-a more intuitive.
13886 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
13887 first attempt, and only move to after the tags when the cursor is already
13888 beyond the end of the headline."
13889 (interactive "P")
13890 (let ((pos (point)) refpos)
13891 (beginning-of-line 1)
13892 (if (bobp)
13894 (backward-char 1)
13895 (if (org-invisible-p)
13896 (while (and (not (bobp)) (org-invisible-p))
13897 (backward-char 1)
13898 (beginning-of-line 1))
13899 (forward-char 1)))
13900 (when org-special-ctrl-a/e
13901 (cond
13902 ((and (looking-at org-complex-heading-regexp)
13903 (= (char-after (match-end 1)) ?\ ))
13904 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
13905 (point-at-eol)))
13906 (goto-char
13907 (if (eq org-special-ctrl-a/e t)
13908 (cond ((> pos refpos) refpos)
13909 ((= pos (point)) refpos)
13910 (t (point)))
13911 (cond ((> pos (point)) (point))
13912 ((not (eq last-command this-command)) (point))
13913 (t refpos)))))
13914 ((org-at-item-p)
13915 (goto-char
13916 (if (eq org-special-ctrl-a/e t)
13917 (cond ((> pos (match-end 4)) (match-end 4))
13918 ((= pos (point)) (match-end 4))
13919 (t (point)))
13920 (cond ((> pos (point)) (point))
13921 ((not (eq last-command this-command)) (point))
13922 (t (match-end 4))))))))
13923 (org-no-warnings
13924 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
13926 (defun org-end-of-line (&optional arg)
13927 "Go to the end of the line.
13928 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
13929 first attempt, and only move to after the tags when the cursor is already
13930 beyond the end of the headline."
13931 (interactive "P")
13932 (if (or (not org-special-ctrl-a/e)
13933 (not (org-on-heading-p)))
13934 (end-of-line arg)
13935 (let ((pos (point)))
13936 (beginning-of-line 1)
13937 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
13938 (if (eq org-special-ctrl-a/e t)
13939 (if (or (< pos (match-beginning 1))
13940 (= pos (match-end 0)))
13941 (goto-char (match-beginning 1))
13942 (goto-char (match-end 0)))
13943 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
13944 (goto-char (match-end 0))
13945 (goto-char (match-beginning 1))))
13946 (end-of-line arg))))
13947 (org-no-warnings
13948 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
13951 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
13952 (define-key org-mode-map "\C-e" 'org-end-of-line)
13954 (defun org-kill-line (&optional arg)
13955 "Kill line, to tags or end of line."
13956 (interactive "P")
13957 (cond
13958 ((or (not org-special-ctrl-k)
13959 (bolp)
13960 (not (org-on-heading-p)))
13961 (call-interactively 'kill-line))
13962 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
13963 (kill-region (point) (match-beginning 1))
13964 (org-set-tags nil t))
13965 (t (kill-region (point) (point-at-eol)))))
13967 (define-key org-mode-map "\C-k" 'org-kill-line)
13969 (defun org-yank ()
13970 "Yank. If the kill is a subtree, treat it specially.
13971 This command will look at the current kill and check it is a single
13972 subtree, or a series of subtrees[1]. If it passes the test, it is
13973 treated specially, depending on the value of the following variables, both
13974 set by default.
13976 org-yank-folded-subtrees
13977 When set, the subree(s) wiil be folded after insertion.
13979 org-yank-adjusted-subtrees
13980 When set, the subtree will be promoted or demoted in order to
13981 fit into the local outline tree structure.
13984 \[1] Basically, the test checks if the first non-white line is a heading
13985 and if there are no other headings with fewer stars."
13986 (interactive)
13987 (let ((subtreep (org-kill-is-subtree-p)))
13988 (if org-yank-folded-subtrees
13989 (let ((beg (point))
13990 end)
13991 (if (and subtreep org-yank-adjusted-subtrees)
13992 (org-paste-subtree nil nil 'for-yank)
13993 (call-interactively 'yank))
13994 (setq end (point))
13995 (goto-char beg)
13996 (when (and (bolp) subtreep)
13997 (or (looking-at outline-regexp)
13998 (re-search-forward (concat "^" outline-regexp) end t))
13999 (while (and (< (point) end) (looking-at outline-regexp))
14000 (hide-subtree)
14001 (org-cycle-show-empty-lines 'folded)
14002 (condition-case nil
14003 (outline-forward-same-level 1)
14004 (error (goto-char end)))))
14005 (goto-char end)
14006 (skip-chars-forward " \t\n\r"))
14007 (if (and subtreep org-yank-adjusted-subtrees)
14008 (org-paste-subtree nil nil 'for-yank)
14009 (call-interactively 'yank)))))
14011 (define-key org-mode-map "\C-y" 'org-yank)
14013 (defun org-invisible-p ()
14014 "Check if point is at a character currently not visible."
14015 ;; Early versions of noutline don't have `outline-invisible-p'.
14016 (if (fboundp 'outline-invisible-p)
14017 (outline-invisible-p)
14018 (get-char-property (point) 'invisible)))
14020 (defun org-invisible-p2 ()
14021 "Check if point is at a character currently not visible."
14022 (save-excursion
14023 (if (and (eolp) (not (bobp))) (backward-char 1))
14024 ;; Early versions of noutline don't have `outline-invisible-p'.
14025 (if (fboundp 'outline-invisible-p)
14026 (outline-invisible-p)
14027 (get-char-property (point) 'invisible))))
14029 (defalias 'org-back-to-heading 'outline-back-to-heading)
14030 (defalias 'org-on-heading-p 'outline-on-heading-p)
14031 (defalias 'org-at-heading-p 'outline-on-heading-p)
14032 (defun org-at-heading-or-item-p ()
14033 (or (org-on-heading-p) (org-at-item-p)))
14035 (defun org-on-target-p ()
14036 (or (org-in-regexp org-radio-target-regexp)
14037 (org-in-regexp org-target-regexp)))
14039 (defun org-up-heading-all (arg)
14040 "Move to the heading line of which the present line is a subheading.
14041 This function considers both visible and invisible heading lines.
14042 With argument, move up ARG levels."
14043 (if (fboundp 'outline-up-heading-all)
14044 (outline-up-heading-all arg) ; emacs 21 version of outline.el
14045 (outline-up-heading arg t))) ; emacs 22 version of outline.el
14047 (defun org-up-heading-safe ()
14048 "Move to the heading line of which the present line is a subheading.
14049 This version will not throw an error. It will return the level of the
14050 headline found, or nil if no higher level is found."
14051 (let ((pos (point)) start-level level
14052 (re (concat "^" outline-regexp)))
14053 (catch 'exit
14054 (outline-back-to-heading t)
14055 (setq start-level (funcall outline-level))
14056 (if (equal start-level 1) (throw 'exit nil))
14057 (while (re-search-backward re nil t)
14058 (setq level (funcall outline-level))
14059 (if (< level start-level) (throw 'exit level)))
14060 nil)))
14062 (defun org-first-sibling-p ()
14063 "Is this heading the first child of its parents?"
14064 (interactive)
14065 (let ((re (concat "^" outline-regexp))
14066 level l)
14067 (unless (org-at-heading-p t)
14068 (error "Not at a heading"))
14069 (setq level (funcall outline-level))
14070 (save-excursion
14071 (if (not (re-search-backward re nil t))
14073 (setq l (funcall outline-level))
14074 (< l level)))))
14076 (defun org-goto-sibling (&optional previous)
14077 "Goto the next sibling, even if it is invisible.
14078 When PREVIOUS is set, go to the previous sibling instead. Returns t
14079 when a sibling was found. When none is found, return nil and don't
14080 move point."
14081 (let ((fun (if previous 're-search-backward 're-search-forward))
14082 (pos (point))
14083 (re (concat "^" outline-regexp))
14084 level l)
14085 (when (condition-case nil (org-back-to-heading t) (error nil))
14086 (setq level (funcall outline-level))
14087 (catch 'exit
14088 (or previous (forward-char 1))
14089 (while (funcall fun re nil t)
14090 (setq l (funcall outline-level))
14091 (when (< l level) (goto-char pos) (throw 'exit nil))
14092 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
14093 (goto-char pos)
14094 nil))))
14096 (defun org-show-siblings ()
14097 "Show all siblings of the current headline."
14098 (save-excursion
14099 (while (org-goto-sibling) (org-flag-heading nil)))
14100 (save-excursion
14101 (while (org-goto-sibling 'previous)
14102 (org-flag-heading nil))))
14104 (defun org-show-hidden-entry ()
14105 "Show an entry where even the heading is hidden."
14106 (save-excursion
14107 (org-show-entry)))
14109 (defun org-flag-heading (flag &optional entry)
14110 "Flag the current heading. FLAG non-nil means make invisible.
14111 When ENTRY is non-nil, show the entire entry."
14112 (save-excursion
14113 (org-back-to-heading t)
14114 ;; Check if we should show the entire entry
14115 (if entry
14116 (progn
14117 (org-show-entry)
14118 (save-excursion
14119 (and (outline-next-heading)
14120 (org-flag-heading nil))))
14121 (outline-flag-region (max (point-min) (1- (point)))
14122 (save-excursion (outline-end-of-heading) (point))
14123 flag))))
14125 (defun org-forward-same-level (arg)
14126 "Move forward to the ARG'th subheading at same level as this one.
14127 Stop at the first and last subheadings of a superior heading.
14128 This is like outline-forward-same-level, but invisible headings are ok."
14129 (interactive "p")
14130 (outline-back-to-heading t)
14131 (while (> arg 0)
14132 (let ((point-to-move-to (save-excursion
14133 (org-get-next-sibling))))
14134 (if point-to-move-to
14135 (progn
14136 (goto-char point-to-move-to)
14137 (setq arg (1- arg)))
14138 (progn
14139 (setq arg 0)
14140 (error "No following same-level heading"))))))
14142 (defun org-get-next-sibling ()
14143 "Move to next heading of the same level, and return point.
14144 If there is no such heading, return nil.
14145 This is like outline-next-sibling, but invisible headings are ok."
14146 (let ((level (funcall outline-level)))
14147 (outline-next-heading)
14148 (while (and (not (eobp)) (> (funcall outline-level) level))
14149 (outline-next-heading))
14150 (if (or (eobp) (< (funcall outline-level) level))
14152 (point))))
14154 (defun org-end-of-subtree (&optional invisible-OK to-heading)
14155 ;; This is an exact copy of the original function, but it uses
14156 ;; `org-back-to-heading', to make it work also in invisible
14157 ;; trees. And is uses an invisible-OK argument.
14158 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
14159 (org-back-to-heading invisible-OK)
14160 (let ((first t)
14161 (level (funcall outline-level)))
14162 (while (and (not (eobp))
14163 (or first (> (funcall outline-level) level)))
14164 (setq first nil)
14165 (outline-next-heading))
14166 (unless to-heading
14167 (if (memq (preceding-char) '(?\n ?\^M))
14168 (progn
14169 ;; Go to end of line before heading
14170 (forward-char -1)
14171 (if (memq (preceding-char) '(?\n ?\^M))
14172 ;; leave blank line before heading
14173 (forward-char -1))))))
14174 (point))
14176 (defun org-show-subtree ()
14177 "Show everything after this heading at deeper levels."
14178 (outline-flag-region
14179 (point)
14180 (save-excursion
14181 (outline-end-of-subtree) (outline-next-heading) (point))
14182 nil))
14184 (defun org-show-entry ()
14185 "Show the body directly following this heading.
14186 Show the heading too, if it is currently invisible."
14187 (interactive)
14188 (save-excursion
14189 (condition-case nil
14190 (progn
14191 (org-back-to-heading t)
14192 (outline-flag-region
14193 (max (point-min) (1- (point)))
14194 (save-excursion
14195 (re-search-forward
14196 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
14197 (or (match-beginning 1) (point-max)))
14198 nil))
14199 (error nil))))
14201 (defun org-make-options-regexp (kwds)
14202 "Make a regular expression for keyword lines."
14203 (concat
14205 "#?[ \t]*\\+\\("
14206 (mapconcat 'regexp-quote kwds "\\|")
14207 "\\):[ \t]*"
14208 "\\(.+\\)"))
14210 ;; Make isearch reveal the necessary context
14211 (defun org-isearch-end ()
14212 "Reveal context after isearch exits."
14213 (when isearch-success ; only if search was successful
14214 (if (featurep 'xemacs)
14215 ;; Under XEmacs, the hook is run in the correct place,
14216 ;; we directly show the context.
14217 (org-show-context 'isearch)
14218 ;; In Emacs the hook runs *before* restoring the overlays.
14219 ;; So we have to use a one-time post-command-hook to do this.
14220 ;; (Emacs 22 has a special variable, see function `org-mode')
14221 (unless (and (boundp 'isearch-mode-end-hook-quit)
14222 isearch-mode-end-hook-quit)
14223 ;; Only when the isearch was not quitted.
14224 (org-add-hook 'post-command-hook 'org-isearch-post-command
14225 'append 'local)))))
14227 (defun org-isearch-post-command ()
14228 "Remove self from hook, and show context."
14229 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
14230 (org-show-context 'isearch))
14233 ;;;; Integration with and fixes for other packages
14235 ;;; Imenu support
14237 (defvar org-imenu-markers nil
14238 "All markers currently used by Imenu.")
14239 (make-variable-buffer-local 'org-imenu-markers)
14241 (defun org-imenu-new-marker (&optional pos)
14242 "Return a new marker for use by Imenu, and remember the marker."
14243 (let ((m (make-marker)))
14244 (move-marker m (or pos (point)))
14245 (push m org-imenu-markers)
14248 (defun org-imenu-get-tree ()
14249 "Produce the index for Imenu."
14250 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
14251 (setq org-imenu-markers nil)
14252 (let* ((n org-imenu-depth)
14253 (re (concat "^" outline-regexp))
14254 (subs (make-vector (1+ n) nil))
14255 (last-level 0)
14256 m tree level head)
14257 (save-excursion
14258 (save-restriction
14259 (widen)
14260 (goto-char (point-max))
14261 (while (re-search-backward re nil t)
14262 (setq level (org-reduced-level (funcall outline-level)))
14263 (when (<= level n)
14264 (looking-at org-complex-heading-regexp)
14265 (setq head (org-link-display-format
14266 (org-match-string-no-properties 4))
14267 m (org-imenu-new-marker))
14268 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
14269 (if (>= level last-level)
14270 (push (cons head m) (aref subs level))
14271 (push (cons head (aref subs (1+ level))) (aref subs level))
14272 (loop for i from (1+ level) to n do (aset subs i nil)))
14273 (setq last-level level)))))
14274 (aref subs 1)))
14276 (eval-after-load "imenu"
14277 '(progn
14278 (add-hook 'imenu-after-jump-hook
14279 (lambda ()
14280 (if (eq major-mode 'org-mode)
14281 (org-show-context 'org-goto))))))
14283 (defun org-link-display-format (link)
14284 "Replace a link with either the description, or the link target
14285 if no description is present"
14286 (save-match-data
14287 (if (string-match org-bracket-link-analytic-regexp link)
14288 (replace-match (or (match-string 5 link)
14289 (concat (match-string 1 link)
14290 (match-string 3 link)))
14291 nil nil link)
14292 link)))
14294 ;; Speedbar support
14296 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
14297 "Overlay marking the agenda restriction line in speedbar.")
14298 (org-overlay-put org-speedbar-restriction-lock-overlay
14299 'face 'org-agenda-restriction-lock)
14300 (org-overlay-put org-speedbar-restriction-lock-overlay
14301 'help-echo "Agendas are currently limited to this item.")
14302 (org-detach-overlay org-speedbar-restriction-lock-overlay)
14304 (defun org-speedbar-set-agenda-restriction ()
14305 "Restrict future agenda commands to the location at point in speedbar.
14306 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
14307 (interactive)
14308 (require 'org-agenda)
14309 (let (p m tp np dir txt w)
14310 (cond
14311 ((setq p (text-property-any (point-at-bol) (point-at-eol)
14312 'org-imenu t))
14313 (setq m (get-text-property p 'org-imenu-marker))
14314 (save-excursion
14315 (save-restriction
14316 (set-buffer (marker-buffer m))
14317 (goto-char m)
14318 (org-agenda-set-restriction-lock 'subtree))))
14319 ((setq p (text-property-any (point-at-bol) (point-at-eol)
14320 'speedbar-function 'speedbar-find-file))
14321 (setq tp (previous-single-property-change
14322 (1+ p) 'speedbar-function)
14323 np (next-single-property-change
14324 tp 'speedbar-function)
14325 dir (speedbar-line-directory)
14326 txt (buffer-substring-no-properties (or tp (point-min))
14327 (or np (point-max))))
14328 (save-excursion
14329 (save-restriction
14330 (set-buffer (find-file-noselect
14331 (let ((default-directory dir))
14332 (expand-file-name txt))))
14333 (unless (org-mode-p)
14334 (error "Cannot restrict to non-Org-mode file"))
14335 (org-agenda-set-restriction-lock 'file))))
14336 (t (error "Don't know how to restrict Org-mode's agenda")))
14337 (org-move-overlay org-speedbar-restriction-lock-overlay
14338 (point-at-bol) (point-at-eol))
14339 (setq current-prefix-arg nil)
14340 (org-agenda-maybe-redo)))
14342 (eval-after-load "speedbar"
14343 '(progn
14344 (speedbar-add-supported-extension ".org")
14345 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
14346 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
14347 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
14348 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
14349 (add-hook 'speedbar-visiting-tag-hook
14350 (lambda () (org-show-context 'org-goto)))))
14353 ;;; Fixes and Hacks for problems with other packages
14355 ;; Make flyspell not check words in links, to not mess up our keymap
14356 (defun org-mode-flyspell-verify ()
14357 "Don't let flyspell put overlays at active buttons."
14358 (not (get-text-property (point) 'keymap)))
14360 ;; Make `bookmark-jump' show the jump location if it was hidden.
14361 (eval-after-load "bookmark"
14362 '(if (boundp 'bookmark-after-jump-hook)
14363 ;; We can use the hook
14364 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
14365 ;; Hook not available, use advice
14366 (defadvice bookmark-jump (after org-make-visible activate)
14367 "Make the position visible."
14368 (org-bookmark-jump-unhide))))
14370 ;; Make sure saveplace show the location if it was hidden
14371 (eval-after-load "saveplace"
14372 '(defadvice save-place-find-file-hook (after org-make-visible activate)
14373 "Make the position visible."
14374 (org-bookmark-jump-unhide)))
14376 (defun org-bookmark-jump-unhide ()
14377 "Unhide the current position, to show the bookmark location."
14378 (and (org-mode-p)
14379 (or (org-invisible-p)
14380 (save-excursion (goto-char (max (point-min) (1- (point))))
14381 (org-invisible-p)))
14382 (org-show-context 'bookmark-jump)))
14384 ;; Make session.el ignore our circular variable
14385 (eval-after-load "session"
14386 '(add-to-list 'session-globals-exclude 'org-mark-ring))
14388 ;;;; Experimental code
14390 (defun org-closed-in-range ()
14391 "Sparse tree of items closed in a certain time range.
14392 Still experimental, may disappear in the future."
14393 (interactive)
14394 ;; Get the time interval from the user.
14395 (let* ((time1 (time-to-seconds
14396 (org-read-date nil 'to-time nil "Starting date: ")))
14397 (time2 (time-to-seconds
14398 (org-read-date nil 'to-time nil "End date:")))
14399 ;; callback function
14400 (callback (lambda ()
14401 (let ((time
14402 (time-to-seconds
14403 (apply 'encode-time
14404 (org-parse-time-string
14405 (match-string 1))))))
14406 ;; check if time in interval
14407 (and (>= time time1) (<= time time2))))))
14408 ;; make tree, check each match with the callback
14409 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
14412 ;;;; Finish up
14414 (provide 'org)
14416 (run-hooks 'org-load-hook)
14418 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
14420 ;;; org.el ends here