Use safer regexps to retrieve property values.
[org-mode.git] / lisp / org.el
blob4305a08c37afe4d1088082fc664c6868b3f233d8
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.11c
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.11c"
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 arguments:
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 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
5966 (let* ((key (match-string 1 link))
5967 (as (or (assoc key org-link-abbrev-alist-local)
5968 (assoc key org-link-abbrev-alist)))
5969 (tag (and (match-end 2) (match-string 3 link)))
5970 rpl)
5971 (if (not as)
5972 link
5973 (setq rpl (cdr as))
5974 (cond
5975 ((symbolp rpl) (funcall rpl tag))
5976 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
5977 (t (concat rpl tag)))))
5978 link))
5980 ;;; Storing and inserting links
5982 (defvar org-insert-link-history nil
5983 "Minibuffer history for links inserted with `org-insert-link'.")
5985 (defvar org-stored-links nil
5986 "Contains the links stored with `org-store-link'.")
5988 (defvar org-store-link-plist nil
5989 "Plist with info about the most recently link created with `org-store-link'.")
5991 (defvar org-link-protocols nil
5992 "Link protocols added to Org-mode using `org-add-link-type'.")
5994 (defvar org-store-link-functions nil
5995 "List of functions that are called to create and store a link.
5996 Each function will be called in turn until one returns a non-nil
5997 value. Each function should check if it is responsible for creating
5998 this link (for example by looking at the major mode).
5999 If not, it must exit and return nil.
6000 If yes, it should return a non-nil value after a calling
6001 `org-store-link-props' with a list of properties and values.
6002 Special properties are:
6004 :type The link prefix. like \"http\". This must be given.
6005 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6006 This is obligatory as well.
6007 :description Optional default description for the second pair
6008 of brackets in an Org-mode link. The user can still change
6009 this when inserting this link into an Org-mode buffer.
6011 In addition to these, any additional properties can be specified
6012 and then used in remember templates.")
6014 (defun org-add-link-type (type &optional follow export)
6015 "Add TYPE to the list of `org-link-types'.
6016 Re-compute all regular expressions depending on `org-link-types'
6018 FOLLOW and EXPORT are two functions.
6020 FOLLOW should take the link path as the single argument and do whatever
6021 is necessary to follow the link, for example find a file or display
6022 a mail message.
6024 EXPORT should format the link path for export to one of the export formats.
6025 It should be a function accepting three arguments:
6027 path the path of the link, the text after the prefix (like \"http:\")
6028 desc the description of the link, if any, nil if there was no descripton
6029 format the export format, a symbol like `html' or `latex'.
6031 The function may use the FORMAT information to return different values
6032 depending on the format. The return value will be put literally into
6033 the exported file.
6034 Org-mode has a built-in default for exporting links. If you are happy with
6035 this default, there is no need to define an export function for the link
6036 type. For a simple example of an export function, see `org-bbdb.el'."
6037 (add-to-list 'org-link-types type t)
6038 (org-make-link-regexps)
6039 (if (assoc type org-link-protocols)
6040 (setcdr (assoc type org-link-protocols) (list follow export))
6041 (push (list type follow export) org-link-protocols)))
6044 ;;;###autoload
6045 (defun org-store-link (arg)
6046 "\\<org-mode-map>Store an org-link to the current location.
6047 This link is added to `org-stored-links' and can later be inserted
6048 into an org-buffer with \\[org-insert-link].
6050 For some link types, a prefix arg is interpreted:
6051 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
6052 For file links, arg negates `org-context-in-file-links'."
6053 (interactive "P")
6054 (org-load-modules-maybe)
6055 (setq org-store-link-plist nil) ; reset
6056 (let (link cpltxt desc description search txt)
6057 (cond
6059 ((run-hook-with-args-until-success 'org-store-link-functions)
6060 (setq link (plist-get org-store-link-plist :link)
6061 desc (or (plist-get org-store-link-plist :description) link)))
6063 ((eq major-mode 'calendar-mode)
6064 (let ((cd (calendar-cursor-to-date)))
6065 (setq link
6066 (format-time-string
6067 (car org-time-stamp-formats)
6068 (apply 'encode-time
6069 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6070 nil nil nil))))
6071 (org-store-link-props :type "calendar" :date cd)))
6073 ((eq major-mode 'w3-mode)
6074 (setq cpltxt (url-view-url t)
6075 link (org-make-link cpltxt))
6076 (org-store-link-props :type "w3" :url (url-view-url t)))
6078 ((eq major-mode 'w3m-mode)
6079 (setq cpltxt (or w3m-current-title w3m-current-url)
6080 link (org-make-link w3m-current-url))
6081 (org-store-link-props :type "w3m" :url (url-view-url t)))
6083 ((setq search (run-hook-with-args-until-success
6084 'org-create-file-search-functions))
6085 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6086 "::" search))
6087 (setq cpltxt (or description link)))
6089 ((eq major-mode 'image-mode)
6090 (setq cpltxt (concat "file:"
6091 (abbreviate-file-name buffer-file-name))
6092 link (org-make-link cpltxt))
6093 (org-store-link-props :type "image" :file buffer-file-name))
6095 ((eq major-mode 'dired-mode)
6096 ;; link to the file in the current line
6097 (setq cpltxt (concat "file:"
6098 (abbreviate-file-name
6099 (expand-file-name
6100 (dired-get-filename nil t))))
6101 link (org-make-link cpltxt)))
6103 ((and buffer-file-name (org-mode-p))
6104 ;; Just link to current headline
6105 (setq cpltxt (concat "file:"
6106 (abbreviate-file-name buffer-file-name)))
6107 ;; Add a context search string
6108 (when (org-xor org-context-in-file-links arg)
6109 ;; Check if we are on a target
6110 (if (org-in-regexp "<<\\(.*?\\)>>")
6111 (setq cpltxt (concat cpltxt "::" (match-string 1)))
6112 (setq txt (cond
6113 ((org-on-heading-p) nil)
6114 ((org-region-active-p)
6115 (buffer-substring (region-beginning) (region-end)))
6116 (t nil)))
6117 (when (or (null txt) (string-match "\\S-" txt))
6118 (setq cpltxt
6119 (concat cpltxt "::"
6120 (condition-case nil
6121 (org-make-org-heading-search-string txt)
6122 (error "")))
6123 desc "NONE"))))
6124 (if (string-match "::\\'" cpltxt)
6125 (setq cpltxt (substring cpltxt 0 -2)))
6126 (setq link (org-make-link cpltxt)))
6128 ((buffer-file-name (buffer-base-buffer))
6129 ;; Just link to this file here.
6130 (setq cpltxt (concat "file:"
6131 (abbreviate-file-name
6132 (buffer-file-name (buffer-base-buffer)))))
6133 ;; Add a context string
6134 (when (org-xor org-context-in-file-links arg)
6135 (setq txt (if (org-region-active-p)
6136 (buffer-substring (region-beginning) (region-end))
6137 (buffer-substring (point-at-bol) (point-at-eol))))
6138 ;; Only use search option if there is some text.
6139 (when (string-match "\\S-" txt)
6140 (setq cpltxt
6141 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6142 desc "NONE")))
6143 (setq link (org-make-link cpltxt)))
6145 ((interactive-p)
6146 (error "Cannot link to a buffer which is not visiting a file"))
6148 (t (setq link nil)))
6150 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6151 (setq link (or link cpltxt)
6152 desc (or desc cpltxt))
6153 (if (equal desc "NONE") (setq desc nil))
6155 (if (and (interactive-p) link)
6156 (progn
6157 (setq org-stored-links
6158 (cons (list link desc) org-stored-links))
6159 (message "Stored: %s" (or desc link)))
6160 (and link (org-make-link-string link desc)))))
6162 (defun org-store-link-props (&rest plist)
6163 "Store link properties, extract names and addresses."
6164 (let (x adr)
6165 (when (setq x (plist-get plist :from))
6166 (setq adr (mail-extract-address-components x))
6167 (setq plist (plist-put plist :fromname (car adr)))
6168 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
6169 (when (setq x (plist-get plist :to))
6170 (setq adr (mail-extract-address-components x))
6171 (setq plist (plist-put plist :toname (car adr)))
6172 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
6173 (let ((from (plist-get plist :from))
6174 (to (plist-get plist :to)))
6175 (when (and from to org-from-is-user-regexp)
6176 (setq plist
6177 (plist-put plist :fromto
6178 (if (string-match org-from-is-user-regexp from)
6179 (concat "to %t")
6180 (concat "from %f"))))))
6181 (setq org-store-link-plist plist))
6183 (defun org-add-link-props (&rest plist)
6184 "Add these properties to the link property list."
6185 (let (key value)
6186 (while plist
6187 (setq key (pop plist) value (pop plist))
6188 (setq org-store-link-plist
6189 (plist-put org-store-link-plist key value)))))
6191 (defun org-email-link-description (&optional fmt)
6192 "Return the description part of an email link.
6193 This takes information from `org-store-link-plist' and formats it
6194 according to FMT (default from `org-email-link-description-format')."
6195 (setq fmt (or fmt org-email-link-description-format))
6196 (let* ((p org-store-link-plist)
6197 (to (plist-get p :toaddress))
6198 (from (plist-get p :fromaddress))
6199 (table
6200 (list
6201 (cons "%c" (plist-get p :fromto))
6202 (cons "%F" (plist-get p :from))
6203 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
6204 (cons "%T" (plist-get p :to))
6205 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
6206 (cons "%s" (plist-get p :subject))
6207 (cons "%m" (plist-get p :message-id)))))
6208 (when (string-match "%c" fmt)
6209 ;; Check if the user wrote this message
6210 (if (and org-from-is-user-regexp from to
6211 (save-match-data (string-match org-from-is-user-regexp from)))
6212 (setq fmt (replace-match "to %t" t t fmt))
6213 (setq fmt (replace-match "from %f" t t fmt))))
6214 (org-replace-escapes fmt table)))
6216 (defun org-make-org-heading-search-string (&optional string heading)
6217 "Make search string for STRING or current headline."
6218 (interactive)
6219 (let ((s (or string (org-get-heading))))
6220 (unless (and string (not heading))
6221 ;; We are using a headline, clean up garbage in there.
6222 (if (string-match org-todo-regexp s)
6223 (setq s (replace-match "" t t s)))
6224 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
6225 (setq s (replace-match "" t t s)))
6226 (setq s (org-trim s))
6227 (if (string-match (concat "^\\(" org-quote-string "\\|"
6228 org-comment-string "\\)") s)
6229 (setq s (replace-match "" t t s)))
6230 (while (string-match org-ts-regexp s)
6231 (setq s (replace-match "" t t s))))
6232 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
6233 (setq s (replace-match " " t t s)))
6234 (or string (setq s (concat "*" s))) ; Add * for headlines
6235 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
6237 (defun org-make-link (&rest strings)
6238 "Concatenate STRINGS."
6239 (apply 'concat strings))
6241 (defun org-make-link-string (link &optional description)
6242 "Make a link with brackets, consisting of LINK and DESCRIPTION."
6243 (unless (string-match "\\S-" link)
6244 (error "Empty link"))
6245 (when (stringp description)
6246 ;; Remove brackets from the description, they are fatal.
6247 (while (string-match "\\[" description)
6248 (setq description (replace-match "{" t t description)))
6249 (while (string-match "\\]" description)
6250 (setq description (replace-match "}" t t description))))
6251 (when (equal (org-link-escape link) description)
6252 ;; No description needed, it is identical
6253 (setq description nil))
6254 (when (and (not description)
6255 (not (equal link (org-link-escape link))))
6256 (setq description (org-extract-attributes link)))
6257 (concat "[[" (org-link-escape link) "]"
6258 (if description (concat "[" description "]") "")
6259 "]"))
6261 (defconst org-link-escape-chars
6262 '((?\ . "%20")
6263 (?\[ . "%5B")
6264 (?\] . "%5D")
6265 (?\340 . "%E0") ; `a
6266 (?\342 . "%E2") ; ^a
6267 (?\347 . "%E7") ; ,c
6268 (?\350 . "%E8") ; `e
6269 (?\351 . "%E9") ; 'e
6270 (?\352 . "%EA") ; ^e
6271 (?\356 . "%EE") ; ^i
6272 (?\364 . "%F4") ; ^o
6273 (?\371 . "%F9") ; `u
6274 (?\373 . "%FB") ; ^u
6275 (?\; . "%3B")
6276 (?? . "%3F")
6277 (?= . "%3D")
6278 (?+ . "%2B")
6280 "Association list of escapes for some characters problematic in links.
6281 This is the list that is used for internal purposes.")
6283 (defconst org-link-escape-chars-browser
6284 '((?\ . "%20")) ; 32 for the SPC char
6285 "Association list of escapes for some characters problematic in links.
6286 This is the list that is used before handing over to the browser.")
6288 (defun org-link-escape (text &optional table)
6289 "Escape charaters in TEXT that are problematic for links."
6290 (setq table (or table org-link-escape-chars))
6291 (when text
6292 (let ((re (mapconcat (lambda (x) (regexp-quote
6293 (char-to-string (car x))))
6294 table "\\|")))
6295 (while (string-match re text)
6296 (setq text
6297 (replace-match
6298 (cdr (assoc (string-to-char (match-string 0 text))
6299 table))
6300 t t text)))
6301 text)))
6303 (defun org-link-unescape (text &optional table)
6304 "Reverse the action of `org-link-escape'."
6305 (setq table (or table org-link-escape-chars))
6306 (when text
6307 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
6308 table "\\|")))
6309 (while (string-match re text)
6310 (setq text
6311 (replace-match
6312 (char-to-string (car (rassoc (match-string 0 text) table)))
6313 t t text)))
6314 text)))
6316 (defun org-xor (a b)
6317 "Exclusive or."
6318 (if a (not b) b))
6320 (defun org-get-header (header)
6321 "Find a header field in the current buffer."
6322 (save-excursion
6323 (goto-char (point-min))
6324 (let ((case-fold-search t) s)
6325 (cond
6326 ((eq header 'from)
6327 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
6328 (setq s (match-string 1)))
6329 (while (string-match "\"" s)
6330 (setq s (replace-match "" t t s)))
6331 (if (string-match "[<(].*" s)
6332 (setq s (replace-match "" t t s))))
6333 ((eq header 'message-id)
6334 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
6335 (setq s (match-string 1))))
6336 ((eq header 'subject)
6337 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
6338 (setq s (match-string 1)))))
6339 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
6340 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
6341 s)))
6344 (defun org-fixup-message-id-for-http (s)
6345 "Replace special characters in a message id, so it can be used in an http query."
6346 (while (string-match "<" s)
6347 (setq s (replace-match "%3C" t t s)))
6348 (while (string-match ">" s)
6349 (setq s (replace-match "%3E" t t s)))
6350 (while (string-match "@" s)
6351 (setq s (replace-match "%40" t t s)))
6354 ;;;###autoload
6355 (defun org-insert-link-global ()
6356 "Insert a link like Org-mode does.
6357 This command can be called in any mode to insert a link in Org-mode syntax."
6358 (interactive)
6359 (org-load-modules-maybe)
6360 (org-run-like-in-org-mode 'org-insert-link))
6362 (defun org-insert-link (&optional complete-file link-location)
6363 "Insert a link. At the prompt, enter the link.
6365 Completion can be used to insert any of the link protocol prefixes like
6366 http or ftp in use.
6368 The history can be used to select a link previously stored with
6369 `org-store-link'. When the empty string is entered (i.e. if you just
6370 press RET at the prompt), the link defaults to the most recently
6371 stored link. As SPC triggers completion in the minibuffer, you need to
6372 use M-SPC or C-q SPC to force the insertion of a space character.
6374 You will also be prompted for a description, and if one is given, it will
6375 be displayed in the buffer instead of the link.
6377 If there is already a link at point, this command will allow you to edit link
6378 and description parts.
6380 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
6381 be selected using completion. The path to the file will be relative to the
6382 current directory if the file is in the current directory or a subdirectory.
6383 Otherwise, the link will be the absolute path as completed in the minibuffer
6384 \(i.e. normally ~/path/to/file). You can configure this behavior using the
6385 option `org-link-file-path-type'.
6387 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
6388 the current directory or below.
6390 With three \\[universal-argument] prefixes, negate the meaning of
6391 `org-keep-stored-link-after-insertion'.
6393 If `org-make-link-description-function' is non-nil, this function will be
6394 called with the link target, and the result will be the default
6395 link description.
6397 If the LINK-LOCATION parameter is non-nil, this value will be
6398 used as the link location instead of reading one interactively."
6399 (interactive "P")
6400 (let* ((wcf (current-window-configuration))
6401 (region (if (org-region-active-p)
6402 (buffer-substring (region-beginning) (region-end))))
6403 (remove (and region (list (region-beginning) (region-end))))
6404 (desc region)
6405 tmphist ; byte-compile incorrectly complains about this
6406 (link link-location)
6407 entry file)
6408 (cond
6409 (link-location) ; specified by arg, just use it.
6410 ((org-in-regexp org-bracket-link-regexp 1)
6411 ;; We do have a link at point, and we are going to edit it.
6412 (setq remove (list (match-beginning 0) (match-end 0)))
6413 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
6414 (setq link (read-string "Link: "
6415 (org-link-unescape
6416 (org-match-string-no-properties 1)))))
6417 ((or (org-in-regexp org-angle-link-re)
6418 (org-in-regexp org-plain-link-re))
6419 ;; Convert to bracket link
6420 (setq remove (list (match-beginning 0) (match-end 0))
6421 link (read-string "Link: "
6422 (org-remove-angle-brackets (match-string 0)))))
6423 ((member complete-file '((4) (16)))
6424 ;; Completing read for file names.
6425 (setq file (read-file-name "File: "))
6426 (let ((pwd (file-name-as-directory (expand-file-name ".")))
6427 (pwd1 (file-name-as-directory (abbreviate-file-name
6428 (expand-file-name ".")))))
6429 (cond
6430 ((equal complete-file '(16))
6431 (setq link (org-make-link
6432 "file:"
6433 (abbreviate-file-name (expand-file-name file)))))
6434 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
6435 (setq link (org-make-link "file:" (match-string 1 file))))
6436 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
6437 (expand-file-name file))
6438 (setq link (org-make-link
6439 "file:" (match-string 1 (expand-file-name file)))))
6440 (t (setq link (org-make-link "file:" file))))))
6442 ;; Read link, with completion for stored links.
6443 (with-output-to-temp-buffer "*Org Links*"
6444 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
6445 (when org-stored-links
6446 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
6447 (princ (mapconcat
6448 (lambda (x)
6449 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
6450 (reverse org-stored-links) "\n"))))
6451 (let ((cw (selected-window)))
6452 (select-window (get-buffer-window "*Org Links*"))
6453 (org-fit-window-to-buffer)
6454 (setq truncate-lines t)
6455 (select-window cw))
6456 ;; Fake a link history, containing the stored links.
6457 (setq tmphist (append (mapcar 'car org-stored-links)
6458 org-insert-link-history))
6459 (unwind-protect
6460 (setq link (org-completing-read
6461 "Link: "
6462 (append
6463 (mapcar (lambda (x) (list (concat (car x) ":")))
6464 (append org-link-abbrev-alist-local org-link-abbrev-alist))
6465 (mapcar (lambda (x) (list (concat x ":")))
6466 org-link-types))
6467 nil nil nil
6468 'tmphist
6469 (or (car (car org-stored-links)))))
6470 (set-window-configuration wcf)
6471 (kill-buffer "*Org Links*"))
6472 (setq entry (assoc link org-stored-links))
6473 (or entry (push link org-insert-link-history))
6474 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
6475 (not org-keep-stored-link-after-insertion))
6476 (setq org-stored-links (delq (assoc link org-stored-links)
6477 org-stored-links)))
6478 (setq desc (or desc (nth 1 entry)))))
6480 (if (string-match org-plain-link-re link)
6481 ;; URL-like link, normalize the use of angular brackets.
6482 (setq link (org-make-link (org-remove-angle-brackets link))))
6484 ;; Check if we are linking to the current file with a search option
6485 ;; If yes, simplify the link by using only the search option.
6486 (when (and buffer-file-name
6487 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
6488 (let* ((path (match-string 1 link))
6489 (case-fold-search nil)
6490 (search (match-string 2 link)))
6491 (save-match-data
6492 (if (equal (file-truename buffer-file-name) (file-truename path))
6493 ;; We are linking to this same file, with a search option
6494 (setq link search)))))
6496 ;; Check if we can/should use a relative path. If yes, simplify the link
6497 (when (string-match "\\<file:\\(.*\\)" link)
6498 (let* ((path (match-string 1 link))
6499 (origpath path)
6500 (case-fold-search nil))
6501 (cond
6502 ((or (eq org-link-file-path-type 'absolute)
6503 (equal complete-file '(16)))
6504 (setq path (abbreviate-file-name (expand-file-name path))))
6505 ((eq org-link-file-path-type 'noabbrev)
6506 (setq path (expand-file-name path)))
6507 ((eq org-link-file-path-type 'relative)
6508 (setq path (file-relative-name path)))
6510 (save-match-data
6511 (if (string-match (concat "^" (regexp-quote
6512 (file-name-as-directory
6513 (expand-file-name "."))))
6514 (expand-file-name path))
6515 ;; We are linking a file with relative path name.
6516 (setq path (substring (expand-file-name path)
6517 (match-end 0)))
6518 (setq path (abbreviate-file-name (expand-file-name path)))))))
6519 (setq link (concat "file:" path))
6520 (if (equal desc origpath)
6521 (setq desc path))))
6523 (if org-make-link-description-function
6524 (setq desc (funcall org-make-link-description-function link desc)))
6526 (setq desc (read-string "Description: " desc))
6527 (unless (string-match "\\S-" desc) (setq desc nil))
6528 (if remove (apply 'delete-region remove))
6529 (insert (org-make-link-string link desc))))
6531 (defun org-completing-read (&rest args)
6532 (let ((minibuffer-local-completion-map
6533 (copy-keymap minibuffer-local-completion-map)))
6534 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
6535 (apply 'completing-read args)))
6537 (defun org-extract-attributes (s)
6538 "Extract the attributes cookie from a string and set as text property."
6539 (let (a attr (start 0) key value)
6540 (save-match-data
6541 (when (string-match "{{\\([^}]+\\)}}$" s)
6542 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
6543 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
6544 (setq key (match-string 1 a) value (match-string 2 a)
6545 start (match-end 0)
6546 attr (plist-put attr (intern key) value))))
6547 (org-add-props s nil 'org-attributes attr))
6550 (defun org-attributes-to-string (plist)
6551 "Format a property list into an HTML attribute list."
6552 (let ((s "") key value)
6553 (while plist
6554 (setq key (pop plist) value (pop plist))
6555 (setq s (concat s " "(symbol-name key) "=\"" value "\"")))
6558 ;;; Opening/following a link
6560 (defvar org-link-search-failed nil)
6562 (defun org-next-link ()
6563 "Move forward to the next link.
6564 If the link is in hidden text, expose it."
6565 (interactive)
6566 (when (and org-link-search-failed (eq this-command last-command))
6567 (goto-char (point-min))
6568 (message "Link search wrapped back to beginning of buffer"))
6569 (setq org-link-search-failed nil)
6570 (let* ((pos (point))
6571 (ct (org-context))
6572 (a (assoc :link ct)))
6573 (if a (goto-char (nth 2 a)))
6574 (if (re-search-forward org-any-link-re nil t)
6575 (progn
6576 (goto-char (match-beginning 0))
6577 (if (org-invisible-p) (org-show-context)))
6578 (goto-char pos)
6579 (setq org-link-search-failed t)
6580 (error "No further link found"))))
6582 (defun org-previous-link ()
6583 "Move backward to the previous link.
6584 If the link is in hidden text, expose it."
6585 (interactive)
6586 (when (and org-link-search-failed (eq this-command last-command))
6587 (goto-char (point-max))
6588 (message "Link search wrapped back to end of buffer"))
6589 (setq org-link-search-failed nil)
6590 (let* ((pos (point))
6591 (ct (org-context))
6592 (a (assoc :link ct)))
6593 (if a (goto-char (nth 1 a)))
6594 (if (re-search-backward org-any-link-re nil t)
6595 (progn
6596 (goto-char (match-beginning 0))
6597 (if (org-invisible-p) (org-show-context)))
6598 (goto-char pos)
6599 (setq org-link-search-failed t)
6600 (error "No further link found"))))
6602 (defun org-find-file-at-mouse (ev)
6603 "Open file link or URL at mouse."
6604 (interactive "e")
6605 (mouse-set-point ev)
6606 (org-open-at-point 'in-emacs))
6608 (defun org-open-at-mouse (ev)
6609 "Open file link or URL at mouse."
6610 (interactive "e")
6611 (mouse-set-point ev)
6612 (org-open-at-point))
6614 (defvar org-window-config-before-follow-link nil
6615 "The window configuration before following a link.
6616 This is saved in case the need arises to restore it.")
6618 (defvar org-open-link-marker (make-marker)
6619 "Marker pointing to the location where `org-open-at-point; was called.")
6621 ;;;###autoload
6622 (defun org-open-at-point-global ()
6623 "Follow a link like Org-mode does.
6624 This command can be called in any mode to follow a link that has
6625 Org-mode syntax."
6626 (interactive)
6627 (org-run-like-in-org-mode 'org-open-at-point))
6629 ;;;###autoload
6630 (defun org-open-link-from-string (s &optional arg)
6631 "Open a link in the string S, as if it was in Org-mode."
6632 (interactive "sLink: \nP")
6633 (with-temp-buffer
6634 (let ((org-inhibit-startup t))
6635 (org-mode)
6636 (insert s)
6637 (goto-char (point-min))
6638 (org-open-at-point arg))))
6640 (defun org-open-at-point (&optional in-emacs)
6641 "Open link at or after point.
6642 If there is no link at point, this function will search forward up to
6643 the end of the current subtree.
6644 Normally, files will be opened by an appropriate application. If the
6645 optional argument IN-EMACS is non-nil, Emacs will visit the file.
6646 With a double prefix argument, try to open outside of Emacs, in the
6647 application the system uses for this file type."
6648 (interactive "P")
6649 (org-load-modules-maybe)
6650 (move-marker org-open-link-marker (point))
6651 (setq org-window-config-before-follow-link (current-window-configuration))
6652 (org-remove-occur-highlights nil nil t)
6653 (if (org-at-timestamp-p t)
6654 (org-follow-timestamp-link)
6655 (let (type path link line search (pos (point)))
6656 (catch 'match
6657 (save-excursion
6658 (skip-chars-forward "^]\n\r")
6659 (when (org-in-regexp org-bracket-link-regexp)
6660 (setq link (org-extract-attributes
6661 (org-link-unescape (org-match-string-no-properties 1))))
6662 (while (string-match " *\n *" link)
6663 (setq link (replace-match " " t t link)))
6664 (setq link (org-link-expand-abbrev link))
6665 (cond
6666 ((or (file-name-absolute-p link)
6667 (string-match "^\\.\\.?/" link))
6668 (setq type "file" path link))
6669 ((string-match org-link-re-with-space2 link)
6670 (setq type (match-string 1 link) path (match-string 2 link)))
6671 (t (setq type "thisfile" path link)))
6672 (throw 'match t)))
6674 (when (get-text-property (point) 'org-linked-text)
6675 (setq type "thisfile"
6676 pos (if (get-text-property (1+ (point)) 'org-linked-text)
6677 (1+ (point)) (point))
6678 path (buffer-substring
6679 (previous-single-property-change pos 'org-linked-text)
6680 (next-single-property-change pos 'org-linked-text)))
6681 (throw 'match t))
6683 (save-excursion
6684 (when (or (org-in-regexp org-angle-link-re)
6685 (org-in-regexp org-plain-link-re))
6686 (setq type (match-string 1) path (match-string 2))
6687 (throw 'match t)))
6688 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
6689 (setq type "tree-match"
6690 path (match-string 1))
6691 (throw 'match t))
6692 (save-excursion
6693 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
6694 (setq type "tags"
6695 path (match-string 1))
6696 (while (string-match ":" path)
6697 (setq path (replace-match "+" t t path)))
6698 (throw 'match t))))
6699 (unless path
6700 (error "No link found"))
6701 ;; Remove any trailing spaces in path
6702 (if (string-match " +\\'" path)
6703 (setq path (replace-match "" t t path)))
6705 (cond
6707 ((assoc type org-link-protocols)
6708 (funcall (nth 1 (assoc type org-link-protocols)) path))
6710 ((equal type "mailto")
6711 (let ((cmd (car org-link-mailto-program))
6712 (args (cdr org-link-mailto-program)) args1
6713 (address path) (subject "") a)
6714 (if (string-match "\\(.*\\)::\\(.*\\)" path)
6715 (setq address (match-string 1 path)
6716 subject (org-link-escape (match-string 2 path))))
6717 (while args
6718 (cond
6719 ((not (stringp (car args))) (push (pop args) args1))
6720 (t (setq a (pop args))
6721 (if (string-match "%a" a)
6722 (setq a (replace-match address t t a)))
6723 (if (string-match "%s" a)
6724 (setq a (replace-match subject t t a)))
6725 (push a args1))))
6726 (apply cmd (nreverse args1))))
6728 ((member type '("http" "https" "ftp" "news"))
6729 (browse-url (concat type ":" (org-link-escape
6730 path org-link-escape-chars-browser))))
6732 ((member type '("message"))
6733 (browse-url (concat type ":" path)))
6735 ((string= type "tags")
6736 (org-tags-view in-emacs path))
6737 ((string= type "thisfile")
6738 (if in-emacs
6739 (switch-to-buffer-other-window
6740 (org-get-buffer-for-internal-link (current-buffer)))
6741 (org-mark-ring-push))
6742 (let ((cmd `(org-link-search
6743 ,path
6744 ,(cond ((equal in-emacs '(4)) 'occur)
6745 ((equal in-emacs '(16)) 'org-occur)
6746 (t nil))
6747 ,pos)))
6748 (condition-case nil (eval cmd)
6749 (error (progn (widen) (eval cmd))))))
6751 ((string= type "tree-match")
6752 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
6754 ((string= type "file")
6755 (if (string-match "::\\([0-9]+\\)\\'" path)
6756 (setq line (string-to-number (match-string 1 path))
6757 path (substring path 0 (match-beginning 0)))
6758 (if (string-match "::\\(.+\\)\\'" path)
6759 (setq search (match-string 1 path)
6760 path (substring path 0 (match-beginning 0)))))
6761 (if (string-match "[*?{]" (file-name-nondirectory path))
6762 (dired path)
6763 (org-open-file path in-emacs line search)))
6765 ((string= type "news")
6766 (require 'org-gnus)
6767 (org-gnus-follow-link path))
6769 ((string= type "shell")
6770 (let ((cmd path))
6771 (if (or (not org-confirm-shell-link-function)
6772 (funcall org-confirm-shell-link-function
6773 (format "Execute \"%s\" in shell? "
6774 (org-add-props cmd nil
6775 'face 'org-warning))))
6776 (progn
6777 (message "Executing %s" cmd)
6778 (shell-command cmd))
6779 (error "Abort"))))
6781 ((string= type "elisp")
6782 (let ((cmd path))
6783 (if (or (not org-confirm-elisp-link-function)
6784 (funcall org-confirm-elisp-link-function
6785 (format "Execute \"%s\" as elisp? "
6786 (org-add-props cmd nil
6787 'face 'org-warning))))
6788 (message "%s => %s" cmd (eval (read cmd)))
6789 (error "Abort"))))
6792 (browse-url-at-point)))))
6793 (move-marker org-open-link-marker nil)
6794 (run-hook-with-args 'org-follow-link-hook))
6796 ;;;; Time estimates
6798 (defun org-get-effort (&optional pom)
6799 "Get the effort estimate for the current entry."
6800 (org-entry-get pom org-effort-property))
6802 ;;; File search
6804 (defvar org-create-file-search-functions nil
6805 "List of functions to construct the right search string for a file link.
6806 These functions are called in turn with point at the location to
6807 which the link should point.
6809 A function in the hook should first test if it would like to
6810 handle this file type, for example by checking the major-mode or
6811 the file extension. If it decides not to handle this file, it
6812 should just return nil to give other functions a chance. If it
6813 does handle the file, it must return the search string to be used
6814 when following the link. The search string will be part of the
6815 file link, given after a double colon, and `org-open-at-point'
6816 will automatically search for it. If special measures must be
6817 taken to make the search successful, another function should be
6818 added to the companion hook `org-execute-file-search-functions',
6819 which see.
6821 A function in this hook may also use `setq' to set the variable
6822 `description' to provide a suggestion for the descriptive text to
6823 be used for this link when it gets inserted into an Org-mode
6824 buffer with \\[org-insert-link].")
6826 (defvar org-execute-file-search-functions nil
6827 "List of functions to execute a file search triggered by a link.
6829 Functions added to this hook must accept a single argument, the
6830 search string that was part of the file link, the part after the
6831 double colon. The function must first check if it would like to
6832 handle this search, for example by checking the major-mode or the
6833 file extension. If it decides not to handle this search, it
6834 should just return nil to give other functions a chance. If it
6835 does handle the search, it must return a non-nil value to keep
6836 other functions from trying.
6838 Each function can access the current prefix argument through the
6839 variable `current-prefix-argument'. Note that a single prefix is
6840 used to force opening a link in Emacs, so it may be good to only
6841 use a numeric or double prefix to guide the search function.
6843 In case this is needed, a function in this hook can also restore
6844 the window configuration before `org-open-at-point' was called using:
6846 (set-window-configuration org-window-config-before-follow-link)")
6848 (defun org-link-search (s &optional type avoid-pos)
6849 "Search for a link search option.
6850 If S is surrounded by forward slashes, it is interpreted as a
6851 regular expression. In org-mode files, this will create an `org-occur'
6852 sparse tree. In ordinary files, `occur' will be used to list matches.
6853 If the current buffer is in `dired-mode', grep will be used to search
6854 in all files. If AVOID-POS is given, ignore matches near that position."
6855 (let ((case-fold-search t)
6856 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
6857 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
6858 (append '(("") (" ") ("\t") ("\n"))
6859 org-emphasis-alist)
6860 "\\|") "\\)"))
6861 (pos (point))
6862 (pre nil) (post nil)
6863 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
6864 (cond
6865 ;; First check if there are any special
6866 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
6867 ;; Now try the builtin stuff
6868 ((save-excursion
6869 (goto-char (point-min))
6870 (and
6871 (re-search-forward
6872 (concat "<<" (regexp-quote s0) ">>") nil t)
6873 (setq type 'dedicated
6874 pos (match-beginning 0))))
6875 ;; There is an exact target for this
6876 (goto-char pos))
6877 ((string-match "^/\\(.*\\)/$" s)
6878 ;; A regular expression
6879 (cond
6880 ((org-mode-p)
6881 (org-occur (match-string 1 s)))
6882 ;;((eq major-mode 'dired-mode)
6883 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
6884 (t (org-do-occur (match-string 1 s)))))
6886 ;; A normal search strings
6887 (when (equal (string-to-char s) ?*)
6888 ;; Anchor on headlines, post may include tags.
6889 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
6890 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
6891 s (substring s 1)))
6892 (remove-text-properties
6893 0 (length s)
6894 '(face nil mouse-face nil keymap nil fontified nil) s)
6895 ;; Make a series of regular expressions to find a match
6896 (setq words (org-split-string s "[ \n\r\t]+")
6898 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
6899 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
6900 "\\)" markers)
6901 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
6902 re2a (concat "[ \t\r\n]" re2a_)
6903 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
6904 re4 (concat "[^a-zA-Z_]" re4_)
6906 re1 (concat pre re2 post)
6907 re3 (concat pre (if pre re4_ re4) post)
6908 re5 (concat pre ".*" re4)
6909 re2 (concat pre re2)
6910 re2a (concat pre (if pre re2a_ re2a))
6911 re4 (concat pre (if pre re4_ re4))
6912 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
6913 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
6914 re5 "\\)"
6916 (cond
6917 ((eq type 'org-occur) (org-occur reall))
6918 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
6919 (t (goto-char (point-min))
6920 (setq type 'fuzzy)
6921 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
6922 (org-search-not-self 1 re1 nil t)
6923 (org-search-not-self 1 re2 nil t)
6924 (org-search-not-self 1 re2a nil t)
6925 (org-search-not-self 1 re3 nil t)
6926 (org-search-not-self 1 re4 nil t)
6927 (org-search-not-self 1 re5 nil t)
6929 (goto-char (match-beginning 1))
6930 (goto-char pos)
6931 (error "No match")))))
6933 ;; Normal string-search
6934 (goto-char (point-min))
6935 (if (search-forward s nil t)
6936 (goto-char (match-beginning 0))
6937 (error "No match"))))
6938 (and (org-mode-p) (org-show-context 'link-search))
6939 type))
6941 (defun org-search-not-self (group &rest args)
6942 "Execute `re-search-forward', but only accept matches that do not
6943 enclose the position of `org-open-link-marker'."
6944 (let ((m org-open-link-marker))
6945 (catch 'exit
6946 (while (apply 're-search-forward args)
6947 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
6948 (goto-char (match-end group))
6949 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
6950 (> (match-beginning 0) (marker-position m))
6951 (< (match-end 0) (marker-position m)))
6952 (save-match-data
6953 (or (not (org-in-regexp
6954 org-bracket-link-analytic-regexp 1))
6955 (not (match-end 4)) ; no description
6956 (and (<= (match-beginning 4) (point))
6957 (>= (match-end 4) (point))))))
6958 (throw 'exit (point))))))))
6960 (defun org-get-buffer-for-internal-link (buffer)
6961 "Return a buffer to be used for displaying the link target of internal links."
6962 (cond
6963 ((not org-display-internal-link-with-indirect-buffer)
6964 buffer)
6965 ((string-match "(Clone)$" (buffer-name buffer))
6966 (message "Buffer is already a clone, not making another one")
6967 ;; we also do not modify visibility in this case
6968 buffer)
6969 (t ; make a new indirect buffer for displaying the link
6970 (let* ((bn (buffer-name buffer))
6971 (ibn (concat bn "(Clone)"))
6972 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
6973 (with-current-buffer ib (org-overview))
6974 ib))))
6976 (defun org-do-occur (regexp &optional cleanup)
6977 "Call the Emacs command `occur'.
6978 If CLEANUP is non-nil, remove the printout of the regular expression
6979 in the *Occur* buffer. This is useful if the regex is long and not useful
6980 to read."
6981 (occur regexp)
6982 (when cleanup
6983 (let ((cwin (selected-window)) win beg end)
6984 (when (setq win (get-buffer-window "*Occur*"))
6985 (select-window win))
6986 (goto-char (point-min))
6987 (when (re-search-forward "match[a-z]+" nil t)
6988 (setq beg (match-end 0))
6989 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
6990 (setq end (1- (match-beginning 0)))))
6991 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
6992 (goto-char (point-min))
6993 (select-window cwin))))
6995 ;;; The mark ring for links jumps
6997 (defvar org-mark-ring nil
6998 "Mark ring for positions before jumps in Org-mode.")
6999 (defvar org-mark-ring-last-goto nil
7000 "Last position in the mark ring used to go back.")
7001 ;; Fill and close the ring
7002 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7003 (loop for i from 1 to org-mark-ring-length do
7004 (push (make-marker) org-mark-ring))
7005 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7006 org-mark-ring)
7008 (defun org-mark-ring-push (&optional pos buffer)
7009 "Put the current position or POS into the mark ring and rotate it."
7010 (interactive)
7011 (setq pos (or pos (point)))
7012 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7013 (move-marker (car org-mark-ring)
7014 (or pos (point))
7015 (or buffer (current-buffer)))
7016 (message "%s"
7017 (substitute-command-keys
7018 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7020 (defun org-mark-ring-goto (&optional n)
7021 "Jump to the previous position in the mark ring.
7022 With prefix arg N, jump back that many stored positions. When
7023 called several times in succession, walk through the entire ring.
7024 Org-mode commands jumping to a different position in the current file,
7025 or to another Org-mode file, automatically push the old position
7026 onto the ring."
7027 (interactive "p")
7028 (let (p m)
7029 (if (eq last-command this-command)
7030 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7031 (setq p org-mark-ring))
7032 (setq org-mark-ring-last-goto p)
7033 (setq m (car p))
7034 (switch-to-buffer (marker-buffer m))
7035 (goto-char m)
7036 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
7038 (defun org-remove-angle-brackets (s)
7039 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7040 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7042 (defun org-add-angle-brackets (s)
7043 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7044 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7046 (defun org-remove-double-quotes (s)
7047 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
7048 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
7051 ;;; Following specific links
7053 (defun org-follow-timestamp-link ()
7054 (cond
7055 ((org-at-date-range-p t)
7056 (let ((org-agenda-start-on-weekday)
7057 (t1 (match-string 1))
7058 (t2 (match-string 2)))
7059 (setq t1 (time-to-days (org-time-string-to-time t1))
7060 t2 (time-to-days (org-time-string-to-time t2)))
7061 (org-agenda-list nil t1 (1+ (- t2 t1)))))
7062 ((org-at-timestamp-p t)
7063 (org-agenda-list nil (time-to-days (org-time-string-to-time
7064 (substring (match-string 1) 0 10)))
7066 (t (error "This should not happen"))))
7069 ;;; Following file links
7070 (defvar org-wait nil)
7071 (defun org-open-file (path &optional in-emacs line search)
7072 "Open the file at PATH.
7073 First, this expands any special file name abbreviations. Then the
7074 configuration variable `org-file-apps' is checked if it contains an
7075 entry for this file type, and if yes, the corresponding command is launched.
7077 If no application is found, Emacs simply visits the file.
7079 With optional prefix argument IN-EMACS, Emacs will visit the file.
7080 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
7081 and o use an external application to visit the file.
7083 Optional LINE specifies a line to go to, optional SEARCH a string to
7084 search for. If LINE or SEARCH is given, the file will always be
7085 opened in Emacs.
7086 If the file does not exist, an error is thrown."
7087 (setq in-emacs (or in-emacs line search))
7088 (let* ((file (if (equal path "")
7089 buffer-file-name
7090 (substitute-in-file-name (expand-file-name path))))
7091 (apps (append org-file-apps (org-default-apps)))
7092 (remp (and (assq 'remote apps) (org-file-remote-p file)))
7093 (dirp (if remp nil (file-directory-p file)))
7094 (file (if (and dirp org-open-directory-means-index-dot-org)
7095 (concat (file-name-as-directory file) "index.org")
7096 file))
7097 (a-m-a-p (assq 'auto-mode apps))
7098 (dfile (downcase file))
7099 (old-buffer (current-buffer))
7100 (old-pos (point))
7101 (old-mode major-mode)
7102 ext cmd)
7103 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7104 (setq ext (match-string 1 dfile))
7105 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7106 (setq ext (match-string 1 dfile))))
7107 (cond
7108 ((equal in-emacs '(16))
7109 (setq cmd (cdr (assoc 'system apps))))
7110 (in-emacs (setq cmd 'emacs))
7112 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
7113 (and dirp (cdr (assoc 'directory apps)))
7114 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
7115 'string-match)
7116 (cdr (assoc ext apps))
7117 (cdr (assoc t apps))))))
7118 (when (eq cmd 'system)
7119 (setq cmd (cdr (assoc 'system apps))))
7120 (when (eq cmd 'default)
7121 (setq cmd (cdr (assoc t apps))))
7122 (when (eq cmd 'mailcap)
7123 (require 'mailcap)
7124 (mailcap-parse-mailcaps)
7125 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7126 (command (mailcap-mime-info mime-type)))
7127 (if (stringp command)
7128 (setq cmd command)
7129 (setq cmd 'emacs))))
7130 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
7131 (not (file-exists-p file))
7132 (not org-open-non-existing-files))
7133 (error "No such file: %s" file))
7134 (cond
7135 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7136 ;; Remove quotes around the file name - we'll use shell-quote-argument.
7137 (while (string-match "['\"]%s['\"]" cmd)
7138 (setq cmd (replace-match "%s" t t cmd)))
7139 (while (string-match "%s" cmd)
7140 (setq cmd (replace-match
7141 (save-match-data
7142 (shell-quote-argument
7143 (convert-standard-filename file)))
7144 t t cmd)))
7145 (save-window-excursion
7146 (start-process-shell-command cmd nil cmd)
7147 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
7149 ((or (stringp cmd)
7150 (eq cmd 'emacs))
7151 (funcall (cdr (assq 'file org-link-frame-setup)) file)
7152 (widen)
7153 (if line (goto-line line)
7154 (if search (org-link-search search))))
7155 ((consp cmd)
7156 (let ((file (convert-standard-filename file)))
7157 (eval cmd)))
7158 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7159 (and (org-mode-p) (eq old-mode 'org-mode)
7160 (or (not (equal old-buffer (current-buffer)))
7161 (not (equal old-pos (point))))
7162 (org-mark-ring-push old-pos old-buffer))))
7164 (defun org-default-apps ()
7165 "Return the default applications for this operating system."
7166 (cond
7167 ((eq system-type 'darwin)
7168 org-file-apps-defaults-macosx)
7169 ((eq system-type 'windows-nt)
7170 org-file-apps-defaults-windowsnt)
7171 (t org-file-apps-defaults-gnu)))
7173 (defun org-apps-regexp-alist (list &optional add-auto-mode)
7174 "Convert extensions to regular expressions in the cars of LIST.
7175 Also, weed out any non-string entries, because the return value is used
7176 only for regexp matching.
7177 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
7178 point to the symbol `emacs', indicating that the file should
7179 be opened in Emacs."
7180 (append
7181 (delq nil
7182 (mapcar (lambda (x)
7183 (if (not (stringp (car x)))
7185 (if (string-match "\\W" (car x))
7187 (cons (concat "\\." (car x) "\\'") (cdr x)))))
7188 list))
7189 (if add-auto-mode
7190 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
7192 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
7193 (defun org-file-remote-p (file)
7194 "Test whether FILE specifies a location on a remote system.
7195 Return non-nil if the location is indeed remote.
7197 For example, the filename \"/user@host:/foo\" specifies a location
7198 on the system \"/user@host:\"."
7199 (cond ((fboundp 'file-remote-p)
7200 (file-remote-p file))
7201 ((fboundp 'tramp-handle-file-remote-p)
7202 (tramp-handle-file-remote-p file))
7203 ((and (boundp 'ange-ftp-name-format)
7204 (string-match (car ange-ftp-name-format) file))
7206 (t nil)))
7209 ;;;; Refiling
7211 (defun org-get-org-file ()
7212 "Read a filename, with default directory `org-directory'."
7213 (let ((default (or org-default-notes-file remember-data-file)))
7214 (read-file-name (format "File name [%s]: " default)
7215 (file-name-as-directory org-directory)
7216 default)))
7218 (defun org-notes-order-reversed-p ()
7219 "Check if the current file should receive notes in reversed order."
7220 (cond
7221 ((not org-reverse-note-order) nil)
7222 ((eq t org-reverse-note-order) t)
7223 ((not (listp org-reverse-note-order)) nil)
7224 (t (catch 'exit
7225 (let ((all org-reverse-note-order)
7226 entry)
7227 (while (setq entry (pop all))
7228 (if (string-match (car entry) buffer-file-name)
7229 (throw 'exit (cdr entry))))
7230 nil)))))
7232 (defvar org-refile-target-table nil
7233 "The list of refile targets, created by `org-refile'.")
7235 (defvar org-agenda-new-buffers nil
7236 "Buffers created to visit agenda files.")
7238 (defun org-get-refile-targets (&optional default-buffer)
7239 "Produce a table with refile targets."
7240 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
7241 targets txt re files f desc descre)
7242 (with-current-buffer (or default-buffer (current-buffer))
7243 (while (setq entry (pop entries))
7244 (setq files (car entry) desc (cdr entry))
7245 (cond
7246 ((null files) (setq files (list (current-buffer))))
7247 ((eq files 'org-agenda-files)
7248 (setq files (org-agenda-files 'unrestricted)))
7249 ((and (symbolp files) (fboundp files))
7250 (setq files (funcall files)))
7251 ((and (symbolp files) (boundp files))
7252 (setq files (symbol-value files))))
7253 (if (stringp files) (setq files (list files)))
7254 (cond
7255 ((eq (car desc) :tag)
7256 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
7257 ((eq (car desc) :todo)
7258 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
7259 ((eq (car desc) :regexp)
7260 (setq descre (cdr desc)))
7261 ((eq (car desc) :level)
7262 (setq descre (concat "^\\*\\{" (number-to-string
7263 (if org-odd-levels-only
7264 (1- (* 2 (cdr desc)))
7265 (cdr desc)))
7266 "\\}[ \t]")))
7267 ((eq (car desc) :maxlevel)
7268 (setq descre (concat "^\\*\\{1," (number-to-string
7269 (if org-odd-levels-only
7270 (1- (* 2 (cdr desc)))
7271 (cdr desc)))
7272 "\\}[ \t]")))
7273 (t (error "Bad refiling target description %s" desc)))
7274 (while (setq f (pop files))
7275 (save-excursion
7276 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
7277 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
7278 (save-excursion
7279 (save-restriction
7280 (widen)
7281 (goto-char (point-min))
7282 (while (re-search-forward descre nil t)
7283 (goto-char (point-at-bol))
7284 (when (looking-at org-complex-heading-regexp)
7285 (setq txt (org-link-display-format (match-string 4))
7286 re (concat "^" (regexp-quote
7287 (buffer-substring (match-beginning 1)
7288 (match-end 4)))))
7289 (if (match-end 5) (setq re (concat re "[ \t]+"
7290 (regexp-quote
7291 (match-string 5)))))
7292 (setq re (concat re "[ \t]*$"))
7293 (when org-refile-use-outline-path
7294 (setq txt (mapconcat 'org-protect-slash
7295 (append
7296 (if (eq org-refile-use-outline-path 'file)
7297 (list (file-name-nondirectory
7298 (buffer-file-name (buffer-base-buffer))))
7299 (if (eq org-refile-use-outline-path 'full-file-path)
7300 (list (buffer-file-name (buffer-base-buffer)))))
7301 (org-get-outline-path)
7302 (list txt))
7303 "/")))
7304 (push (list txt f re (point)) targets))
7305 (goto-char (point-at-eol))))))))
7306 (nreverse targets))))
7308 (defun org-protect-slash (s)
7309 (while (string-match "/" s)
7310 (setq s (replace-match "\\" t t s)))
7313 (defun org-get-outline-path ()
7314 "Return the outline path to the current entry, as a list."
7315 (let (rtn)
7316 (save-excursion
7317 (while (org-up-heading-safe)
7318 (when (looking-at org-complex-heading-regexp)
7319 (push (org-match-string-no-properties 4) rtn)))
7320 rtn)))
7322 (defvar org-refile-history nil
7323 "History for refiling operations.")
7325 (defun org-refile (&optional goto default-buffer)
7326 "Move the entry at point to another heading.
7327 The list of target headings is compiled using the information in
7328 `org-refile-targets', which see. This list is created before each use
7329 and will therefore always be up-to-date.
7331 At the target location, the entry is filed as a subitem of the target heading.
7332 Depending on `org-reverse-note-order', the new subitem will either be the
7333 first or the last subitem.
7335 With prefix arg GOTO, the command will only visit the target location,
7336 not actually move anything.
7337 With a double prefix `C-u C-u', go to the location where the last refiling
7338 operation has put the subtree."
7339 (interactive "P")
7340 (let* ((cbuf (current-buffer))
7341 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7342 pos it nbuf file re level reversed)
7343 (if (equal goto '(16))
7344 (org-refile-goto-last-stored)
7345 (when (setq it (org-refile-get-location
7346 (if goto "Goto: " "Refile to: ") default-buffer))
7347 (setq file (nth 1 it)
7348 re (nth 2 it)
7349 pos (nth 3 it))
7350 (setq nbuf (or (find-buffer-visiting file)
7351 (find-file-noselect file)))
7352 (if goto
7353 (progn
7354 (switch-to-buffer nbuf)
7355 (goto-char pos)
7356 (org-show-context 'org-goto))
7357 (org-copy-subtree 1 nil t)
7358 (save-excursion
7359 (set-buffer (setq nbuf (or (find-buffer-visiting file)
7360 (find-file-noselect file))))
7361 (setq reversed (org-notes-order-reversed-p))
7362 (save-excursion
7363 (save-restriction
7364 (widen)
7365 (goto-char pos)
7366 (looking-at outline-regexp)
7367 (setq level (org-get-valid-level (funcall outline-level) 1))
7368 (goto-char
7369 (if reversed
7370 (or (outline-next-heading) (point-max))
7371 (or (save-excursion (outline-get-next-sibling))
7372 (org-end-of-subtree t t)
7373 (point-max))))
7374 (if (not (bolp)) (newline))
7375 (bookmark-set "org-refile-last-stored")
7376 (org-paste-subtree level))))
7377 (org-cut-subtree)
7378 (setq org-markers-to-move nil)
7379 (message "Entry refiled to \"%s\"" (car it)))))))
7381 (defun org-refile-goto-last-stored ()
7382 "Go to the location where the last refile was stored."
7383 (interactive)
7384 (bookmark-jump "org-refile-last-stored")
7385 (message "This is the location of the last refile"))
7387 (defun org-refile-get-location (&optional prompt default-buffer)
7388 "Prompt the user for a refile location, using PROMPT."
7389 (let ((org-refile-targets org-refile-targets)
7390 (org-refile-use-outline-path org-refile-use-outline-path))
7391 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
7392 (unless org-refile-target-table
7393 (error "No refile targets"))
7394 (let* ((cbuf (current-buffer))
7395 (cfunc (if org-refile-use-outline-path
7396 'org-olpath-completing-read
7397 'completing-read))
7398 (extra (if org-refile-use-outline-path "/" ""))
7399 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7400 (fname (and filename (file-truename filename)))
7401 (tbl (mapcar
7402 (lambda (x)
7403 (if (not (equal fname (file-truename (nth 1 x))))
7404 (cons (concat (car x) extra " ("
7405 (file-name-nondirectory (nth 1 x)) ")")
7406 (cdr x))
7407 (cons (concat (car x) extra) (cdr x))))
7408 org-refile-target-table))
7409 (completion-ignore-case t))
7410 (assoc (funcall cfunc prompt tbl nil t nil 'org-refile-history)
7411 tbl)))
7413 (defun org-olpath-completing-read (prompt collection &rest args)
7414 "Read an outline path like a file name."
7415 (let ((thetable collection))
7416 (apply
7417 'completing-read prompt
7418 (lambda (string predicate &optional flag)
7419 (let (rtn r s f (l (length string)))
7420 (cond
7421 ((eq flag nil)
7422 ;; try completion
7423 (try-completion string thetable))
7424 ((eq flag t)
7425 ;; all-completions
7426 (setq rtn (all-completions string thetable predicate))
7427 (mapcar
7428 (lambda (x)
7429 (setq r (substring x l))
7430 (if (string-match " ([^)]*)$" x)
7431 (setq f (match-string 0 x))
7432 (setq f ""))
7433 (if (string-match "/" r)
7434 (concat string (substring r 0 (match-end 0)) f)
7436 rtn))
7437 ((eq flag 'lambda)
7438 ;; exact match?
7439 (assoc string thetable)))
7441 args)))
7443 ;;;; Dynamic blocks
7445 (defun org-find-dblock (name)
7446 "Find the first dynamic block with name NAME in the buffer.
7447 If not found, stay at current position and return nil."
7448 (let (pos)
7449 (save-excursion
7450 (goto-char (point-min))
7451 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
7452 nil t)
7453 (match-beginning 0))))
7454 (if pos (goto-char pos))
7455 pos))
7457 (defconst org-dblock-start-re
7458 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
7459 "Matches the startline of a dynamic block, with parameters.")
7461 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
7462 "Matches the end of a dyhamic block.")
7464 (defun org-create-dblock (plist)
7465 "Create a dynamic block section, with parameters taken from PLIST.
7466 PLIST must containe a :name entry which is used as name of the block."
7467 (unless (bolp) (newline))
7468 (let ((name (plist-get plist :name)))
7469 (insert "#+BEGIN: " name)
7470 (while plist
7471 (if (eq (car plist) :name)
7472 (setq plist (cddr plist))
7473 (insert " " (prin1-to-string (pop plist)))))
7474 (insert "\n\n#+END:\n")
7475 (beginning-of-line -2)))
7477 (defun org-prepare-dblock ()
7478 "Prepare dynamic block for refresh.
7479 This empties the block, puts the cursor at the insert position and returns
7480 the property list including an extra property :name with the block name."
7481 (unless (looking-at org-dblock-start-re)
7482 (error "Not at a dynamic block"))
7483 (let* ((begdel (1+ (match-end 0)))
7484 (name (org-no-properties (match-string 1)))
7485 (params (append (list :name name)
7486 (read (concat "(" (match-string 3) ")")))))
7487 (unless (re-search-forward org-dblock-end-re nil t)
7488 (error "Dynamic block not terminated"))
7489 (setq params
7490 (append params
7491 (list :content (buffer-substring
7492 begdel (match-beginning 0)))))
7493 (delete-region begdel (match-beginning 0))
7494 (goto-char begdel)
7495 (open-line 1)
7496 params))
7498 (defun org-map-dblocks (&optional command)
7499 "Apply COMMAND to all dynamic blocks in the current buffer.
7500 If COMMAND is not given, use `org-update-dblock'."
7501 (let ((cmd (or command 'org-update-dblock))
7502 pos)
7503 (save-excursion
7504 (goto-char (point-min))
7505 (while (re-search-forward org-dblock-start-re nil t)
7506 (goto-char (setq pos (match-beginning 0)))
7507 (condition-case nil
7508 (funcall cmd)
7509 (error (message "Error during update of dynamic block")))
7510 (goto-char pos)
7511 (unless (re-search-forward org-dblock-end-re nil t)
7512 (error "Dynamic block not terminated"))))))
7514 (defun org-dblock-update (&optional arg)
7515 "User command for updating dynamic blocks.
7516 Update the dynamic block at point. With prefix ARG, update all dynamic
7517 blocks in the buffer."
7518 (interactive "P")
7519 (if arg
7520 (org-update-all-dblocks)
7521 (or (looking-at org-dblock-start-re)
7522 (org-beginning-of-dblock))
7523 (org-update-dblock)))
7525 (defun org-update-dblock ()
7526 "Update the dynamic block at point
7527 This means to empty the block, parse for parameters and then call
7528 the correct writing function."
7529 (save-window-excursion
7530 (let* ((pos (point))
7531 (line (org-current-line))
7532 (params (org-prepare-dblock))
7533 (name (plist-get params :name))
7534 (cmd (intern (concat "org-dblock-write:" name))))
7535 (message "Updating dynamic block `%s' at line %d..." name line)
7536 (funcall cmd params)
7537 (message "Updating dynamic block `%s' at line %d...done" name line)
7538 (goto-char pos))))
7540 (defun org-beginning-of-dblock ()
7541 "Find the beginning of the dynamic block at point.
7542 Error if there is no scuh block at point."
7543 (let ((pos (point))
7544 beg)
7545 (end-of-line 1)
7546 (if (and (re-search-backward org-dblock-start-re nil t)
7547 (setq beg (match-beginning 0))
7548 (re-search-forward org-dblock-end-re nil t)
7549 (> (match-end 0) pos))
7550 (goto-char beg)
7551 (goto-char pos)
7552 (error "Not in a dynamic block"))))
7554 (defun org-update-all-dblocks ()
7555 "Update all dynamic blocks in the buffer.
7556 This function can be used in a hook."
7557 (when (org-mode-p)
7558 (org-map-dblocks 'org-update-dblock)))
7561 ;;;; Completion
7563 (defconst org-additional-option-like-keywords
7564 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
7565 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
7566 "BEGIN_EXAMPLE" "END_EXAMPLE"
7567 "BEGIN_QUOTE" "END_QUOTE"
7568 "BEGIN_VERSE" "END_VERSE"
7569 "BEGIN_SRC" "END_SRC"))
7571 (defcustom org-structure-template-alist
7573 ("s" "#+begin_src ?\n\n#+end_src"
7574 "<src lang=\"?\">\n\n</src>")
7575 ("e" "#+begin_example\n?\n#+end_example"
7576 "<example>\n?\n</example>")
7577 ("q" "#+begin_quote\n?\n#+end_quote"
7578 "<quote>\n?\n</quote>")
7579 ("v" "#+begin_verse\n?\n#+end_verse"
7580 "<verse>\n?\n/verse>")
7581 ("l" "#+begin_latex\n?\n#+end_latex"
7582 "<literal style=\"latex\">\n?\n</literal>")
7583 ("L" "#+latex: "
7584 "<literal style=\"latex\">?</literal>")
7585 ("h" "#+begin_html\n?\n#+end_html"
7586 "<literal style=\"html\">\n?\n</literal>")
7587 ("H" "#+html: "
7588 "<literal style=\"html\">?</literal>")
7589 ("a" "#+begin_ascii\n?\n#+end_ascii")
7590 ("A" "#+ascii: ")
7591 ("i" "#+include %file ?"
7592 "<include file=%file markup=\"?\">")
7594 "Structure completion elements.
7595 This is a list of abbreviation keys and values. The value gets inserted
7596 it you type @samp{.} followed by the key and then the completion key,
7597 usually `M-TAB'. %file will be replaced by a file name after prompting
7598 for the file uning completion.
7599 There are two templates for each key, the first uses the original Org syntax,
7600 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
7601 the default when the /org-mtags.el/ module has been loaded. See also the
7602 variable `org-mtags-prefere-muse-templates'.
7603 This is an experimental feature, it is undecided if it is going to stay in."
7604 :group 'org-completion
7605 :type '(repeat
7606 (string :tag "Key")
7607 (string :tag "Template")
7608 (string :tag "Muse Template")))
7610 (defun org-try-structure-completion ()
7611 "Try to complete a structure template before point.
7612 This looks for strings like \"<e\" on an otherwise empty line and
7613 expands them."
7614 (let ((l (buffer-substring (point-at-bol) (point)))
7616 (when (and (looking-at "[ \t]*$")
7617 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
7618 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
7619 (org-complete-expand-structure-template (+ -1 (point-at-bol)
7620 (match-beginning 1)) a)
7621 t)))
7623 (defun org-complete-expand-structure-template (start cell)
7624 "Expand a structure template."
7625 (let* ((musep (org-bound-and-true-p org-mtags-prefere-muse-templates))
7626 (rpl (nth (if musep 2 1) cell)))
7627 (delete-region start (point))
7628 (when (string-match "\\`#\\+" rpl)
7629 (cond
7630 ((bolp))
7631 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
7632 (delete-region (point-at-bol) (point)))
7633 (t (newline))))
7634 (setq start (point))
7635 (if (string-match "%file" rpl)
7636 (setq rpl (replace-match
7637 (concat
7638 "\""
7639 (save-match-data
7640 (abbreviate-file-name (read-file-name "Include file: ")))
7641 "\"")
7642 t t rpl)))
7643 (insert rpl)
7644 (if (re-search-backward "\\?" start t) (delete-char 1))))
7647 (defun org-complete (&optional arg)
7648 "Perform completion on word at point.
7649 At the beginning of a headline, this completes TODO keywords as given in
7650 `org-todo-keywords'.
7651 If the current word is preceded by a backslash, completes the TeX symbols
7652 that are supported for HTML support.
7653 If the current word is preceded by \"#+\", completes special words for
7654 setting file options.
7655 In the line after \"#+STARTUP:, complete valid keywords.\"
7656 At all other locations, this simply calls the value of
7657 `org-completion-fallback-command'."
7658 (interactive "P")
7659 (org-without-partial-completion
7660 (catch 'exit
7661 (let* ((a nil)
7662 (end (point))
7663 (beg1 (save-excursion
7664 (skip-chars-backward (org-re "[:alnum:]_@"))
7665 (point)))
7666 (beg (save-excursion
7667 (skip-chars-backward "a-zA-Z0-9_:$")
7668 (point)))
7669 (confirm (lambda (x) (stringp (car x))))
7670 (searchhead (equal (char-before beg) ?*))
7671 (struct
7672 (when (and (member (char-before beg1) '(?. ?<))
7673 (setq a (assoc (buffer-substring beg1 (point))
7674 org-structure-template-alist)))
7675 (org-complete-expand-structure-template (1- beg1) a)
7676 (throw 'exit t)))
7677 (tag (and (equal (char-before beg1) ?:)
7678 (equal (char-after (point-at-bol)) ?*)))
7679 (prop (and (equal (char-before beg1) ?:)
7680 (not (equal (char-after (point-at-bol)) ?*))))
7681 (texp (equal (char-before beg) ?\\))
7682 (link (equal (char-before beg) ?\[))
7683 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
7684 beg)
7685 "#+"))
7686 (startup (string-match "^#\\+STARTUP:.*"
7687 (buffer-substring (point-at-bol) (point))))
7688 (completion-ignore-case opt)
7689 (type nil)
7690 (tbl nil)
7691 (table (cond
7692 (opt
7693 (setq type :opt)
7694 (require 'org-exp)
7695 (append
7696 (mapcar
7697 (lambda (x)
7698 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
7699 (cons (match-string 2 x) (match-string 1 x)))
7700 (org-split-string (org-get-current-options) "\n"))
7701 (mapcar 'list org-additional-option-like-keywords)))
7702 (startup
7703 (setq type :startup)
7704 org-startup-options)
7705 (link (append org-link-abbrev-alist-local
7706 org-link-abbrev-alist))
7707 (texp
7708 (setq type :tex)
7709 org-html-entities)
7710 ((string-match "\\`\\*+[ \t]+\\'"
7711 (buffer-substring (point-at-bol) beg))
7712 (setq type :todo)
7713 (mapcar 'list org-todo-keywords-1))
7714 (searchhead
7715 (setq type :searchhead)
7716 (save-excursion
7717 (goto-char (point-min))
7718 (while (re-search-forward org-todo-line-regexp nil t)
7719 (push (list
7720 (org-make-org-heading-search-string
7721 (match-string 3) t))
7722 tbl)))
7723 tbl)
7724 (tag (setq type :tag beg beg1)
7725 (or org-tag-alist (org-get-buffer-tags)))
7726 (prop (setq type :prop beg beg1)
7727 (mapcar 'list (org-buffer-property-keys nil t t)))
7728 (t (progn
7729 (call-interactively org-completion-fallback-command)
7730 (throw 'exit nil)))))
7731 (pattern (buffer-substring-no-properties beg end))
7732 (completion (try-completion pattern table confirm)))
7733 (cond ((eq completion t)
7734 (if (not (assoc (upcase pattern) table))
7735 (message "Already complete")
7736 (if (and (equal type :opt)
7737 (not (member (car (assoc (upcase pattern) table))
7738 org-additional-option-like-keywords)))
7739 (insert (substring (cdr (assoc (upcase pattern) table))
7740 (length pattern)))
7741 (if (memq type '(:tag :prop)) (insert ":")))))
7742 ((null completion)
7743 (message "Can't find completion for \"%s\"" pattern)
7744 (ding))
7745 ((not (string= pattern completion))
7746 (delete-region beg end)
7747 (if (string-match " +$" completion)
7748 (setq completion (replace-match "" t t completion)))
7749 (insert completion)
7750 (if (get-buffer-window "*Completions*")
7751 (delete-window (get-buffer-window "*Completions*")))
7752 (if (assoc completion table)
7753 (if (eq type :todo) (insert " ")
7754 (if (memq type '(:tag :prop)) (insert ":"))))
7755 (if (and (equal type :opt) (assoc completion table))
7756 (message "%s" (substitute-command-keys
7757 "Press \\[org-complete] again to insert example settings"))))
7759 (message "Making completion list...")
7760 (let ((list (sort (all-completions pattern table confirm)
7761 'string<)))
7762 (with-output-to-temp-buffer "*Completions*"
7763 (condition-case nil
7764 ;; Protection needed for XEmacs and emacs 21
7765 (display-completion-list list pattern)
7766 (error (display-completion-list list)))))
7767 (message "Making completion list...%s" "done")))))))
7769 ;;;; TODO, DEADLINE, Comments
7771 (defun org-toggle-comment ()
7772 "Change the COMMENT state of an entry."
7773 (interactive)
7774 (save-excursion
7775 (org-back-to-heading)
7776 (let (case-fold-search)
7777 (if (looking-at (concat outline-regexp
7778 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
7779 (replace-match "" t t nil 1)
7780 (if (looking-at outline-regexp)
7781 (progn
7782 (goto-char (match-end 0))
7783 (insert org-comment-string " ")))))))
7785 (defvar org-last-todo-state-is-todo nil
7786 "This is non-nil when the last TODO state change led to a TODO state.
7787 If the last change removed the TODO tag or switched to DONE, then
7788 this is nil.")
7790 (defvar org-setting-tags nil) ; dynamically skiped
7792 (defun org-parse-local-options (string var)
7793 "Parse STRING for startup setting relevant for variable VAR."
7794 (let ((rtn (symbol-value var))
7795 e opts)
7796 (save-match-data
7797 (if (or (not string) (not (string-match "\\S-" string)))
7799 (setq opts (delq nil (mapcar (lambda (x)
7800 (setq e (assoc x org-startup-options))
7801 (if (eq (nth 1 e) var) e nil))
7802 (org-split-string string "[ \t]+"))))
7803 (if (not opts)
7805 (setq rtn nil)
7806 (while (setq e (pop opts))
7807 (if (not (nth 3 e))
7808 (setq rtn (nth 2 e))
7809 (if (not (listp rtn)) (setq rtn nil))
7810 (push (nth 2 e) rtn)))
7811 rtn)))))
7813 (defvar org-blocker-hook nil
7814 "Hook for functions that are allowed to block a state change.
7816 Each function gets as its single argument a property list, see
7817 `org-trigger-hook' for more information about this list.
7819 If any of the functions in this hook returns nil, the state change
7820 is blocked.")
7822 (defvar org-trigger-hook nil
7823 "Hook for functions that are triggered by a state change.
7825 Each function gets as its single argument a property list with at least
7826 the following elements:
7828 (:type type-of-change :position pos-at-entry-start
7829 :from old-state :to new-state)
7831 Depending on the type, more properties may be present.
7833 This mechanism is currently implemented for:
7835 TODO state changes
7836 ------------------
7837 :type todo-state-change
7838 :from previous state (keyword as a string), or nil
7839 :to new state (keyword as a string), or nil")
7841 (defvar org-agenda-headline-snapshot-before-repeat)
7842 (defun org-todo (&optional arg)
7843 "Change the TODO state of an item.
7844 The state of an item is given by a keyword at the start of the heading,
7845 like
7846 *** TODO Write paper
7847 *** DONE Call mom
7849 The different keywords are specified in the variable `org-todo-keywords'.
7850 By default the available states are \"TODO\" and \"DONE\".
7851 So for this example: when the item starts with TODO, it is changed to DONE.
7852 When it starts with DONE, the DONE is removed. And when neither TODO nor
7853 DONE are present, add TODO at the beginning of the heading.
7855 With C-u prefix arg, use completion to determine the new state.
7856 With numeric prefix arg, switch to that state.
7858 For calling through lisp, arg is also interpreted in the following way:
7859 'none -> empty state
7860 \"\"(empty string) -> switch to empty state
7861 'done -> switch to DONE
7862 'nextset -> switch to the next set of keywords
7863 'previousset -> switch to the previous set of keywords
7864 \"WAITING\" -> switch to the specified keyword, but only if it
7865 really is a member of `org-todo-keywords'."
7866 (interactive "P")
7867 (save-excursion
7868 (catch 'exit
7869 (org-back-to-heading)
7870 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
7871 (or (looking-at (concat " +" org-todo-regexp " *"))
7872 (looking-at " *"))
7873 (let* ((match-data (match-data))
7874 (startpos (point-at-bol))
7875 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
7876 (org-log-done org-log-done)
7877 (org-log-repeat org-log-repeat)
7878 (org-todo-log-states org-todo-log-states)
7879 (this (match-string 1))
7880 (hl-pos (match-beginning 0))
7881 (head (org-get-todo-sequence-head this))
7882 (ass (assoc head org-todo-kwd-alist))
7883 (interpret (nth 1 ass))
7884 (done-word (nth 3 ass))
7885 (final-done-word (nth 4 ass))
7886 (last-state (or this ""))
7887 (completion-ignore-case t)
7888 (member (member this org-todo-keywords-1))
7889 (tail (cdr member))
7890 (state (cond
7891 ((and org-todo-key-trigger
7892 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
7893 (and (not arg) org-use-fast-todo-selection
7894 (not (eq org-use-fast-todo-selection 'prefix)))))
7895 ;; Use fast selection
7896 (org-fast-todo-selection))
7897 ((and (equal arg '(4))
7898 (or (not org-use-fast-todo-selection)
7899 (not org-todo-key-trigger)))
7900 ;; Read a state with completion
7901 (completing-read "State: " (mapcar (lambda(x) (list x))
7902 org-todo-keywords-1)
7903 nil t))
7904 ((eq arg 'right)
7905 (if this
7906 (if tail (car tail) nil)
7907 (car org-todo-keywords-1)))
7908 ((eq arg 'left)
7909 (if (equal member org-todo-keywords-1)
7911 (if this
7912 (nth (- (length org-todo-keywords-1) (length tail) 2)
7913 org-todo-keywords-1)
7914 (org-last org-todo-keywords-1))))
7915 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
7916 (setq arg nil))) ; hack to fall back to cycling
7917 (arg
7918 ;; user or caller requests a specific state
7919 (cond
7920 ((equal arg "") nil)
7921 ((eq arg 'none) nil)
7922 ((eq arg 'done) (or done-word (car org-done-keywords)))
7923 ((eq arg 'nextset)
7924 (or (car (cdr (member head org-todo-heads)))
7925 (car org-todo-heads)))
7926 ((eq arg 'previousset)
7927 (let ((org-todo-heads (reverse org-todo-heads)))
7928 (or (car (cdr (member head org-todo-heads)))
7929 (car org-todo-heads))))
7930 ((car (member arg org-todo-keywords-1)))
7931 ((nth (1- (prefix-numeric-value arg))
7932 org-todo-keywords-1))))
7933 ((null member) (or head (car org-todo-keywords-1)))
7934 ((equal this final-done-word) nil) ;; -> make empty
7935 ((null tail) nil) ;; -> first entry
7936 ((eq interpret 'sequence)
7937 (car tail))
7938 ((memq interpret '(type priority))
7939 (if (eq this-command last-command)
7940 (car tail)
7941 (if (> (length tail) 0)
7942 (or done-word (car org-done-keywords))
7943 nil)))
7944 (t nil)))
7945 (next (if state (concat " " state " ") " "))
7946 (change-plist (list :type 'todo-state-change :from this :to state
7947 :position startpos))
7948 dolog now-done-p)
7949 (when org-blocker-hook
7950 (unless (save-excursion
7951 (save-match-data
7952 (run-hook-with-args-until-failure
7953 'org-blocker-hook change-plist)))
7954 (if (interactive-p)
7955 (error "TODO state change from %s to %s blocked" this state)
7956 ;; fail silently
7957 (message "TODO state change from %s to %s blocked" this state)
7958 (throw 'exit nil))))
7959 (store-match-data match-data)
7960 (replace-match next t t)
7961 (unless (pos-visible-in-window-p hl-pos)
7962 (message "TODO state changed to %s" (org-trim next)))
7963 (unless head
7964 (setq head (org-get-todo-sequence-head state)
7965 ass (assoc head org-todo-kwd-alist)
7966 interpret (nth 1 ass)
7967 done-word (nth 3 ass)
7968 final-done-word (nth 4 ass)))
7969 (when (memq arg '(nextset previousset))
7970 (message "Keyword-Set %d/%d: %s"
7971 (- (length org-todo-sets) -1
7972 (length (memq (assoc state org-todo-sets) org-todo-sets)))
7973 (length org-todo-sets)
7974 (mapconcat 'identity (assoc state org-todo-sets) " ")))
7975 (setq org-last-todo-state-is-todo
7976 (not (member state org-done-keywords)))
7977 (setq now-done-p (and (member state org-done-keywords)
7978 (not (member this org-done-keywords))))
7979 (and logging (org-local-logging logging))
7980 (when (and (or org-todo-log-states org-log-done)
7981 (not (memq arg '(nextset previousset))))
7982 ;; we need to look at recording a time and note
7983 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
7984 (nth 2 (assoc this org-todo-log-states))))
7985 (when (and state
7986 (member state org-not-done-keywords)
7987 (not (member this org-not-done-keywords)))
7988 ;; This is now a todo state and was not one before
7989 ;; If there was a CLOSED time stamp, get rid of it.
7990 (org-add-planning-info nil nil 'closed))
7991 (when (and now-done-p org-log-done)
7992 ;; It is now done, and it was not done before
7993 (org-add-planning-info 'closed (org-current-time))
7994 (if (and (not dolog) (eq 'note org-log-done))
7995 (org-add-log-setup 'done state 'findpos 'note)))
7996 (when (and state dolog)
7997 ;; This is a non-nil state, and we need to log it
7998 (org-add-log-setup 'state state 'findpos dolog)))
7999 ;; Fixup tag positioning
8000 (org-todo-trigger-tag-changes state)
8001 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
8002 (when org-provide-todo-statistics
8003 (org-update-parent-todo-statistics))
8004 (run-hooks 'org-after-todo-state-change-hook)
8005 (if (and arg (not (member state org-done-keywords)))
8006 (setq head (org-get-todo-sequence-head state)))
8007 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
8008 ;; Do we need to trigger a repeat?
8009 (when now-done-p
8010 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
8011 ;; This is for the agenda, take a snapshot of the headline.
8012 (save-match-data
8013 (setq org-agenda-headline-snapshot-before-repeat
8014 (org-get-heading))))
8015 (org-auto-repeat-maybe state))
8016 ;; Fixup cursor location if close to the keyword
8017 (if (and (outline-on-heading-p)
8018 (not (bolp))
8019 (save-excursion (beginning-of-line 1)
8020 (looking-at org-todo-line-regexp))
8021 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
8022 (progn
8023 (goto-char (or (match-end 2) (match-end 1)))
8024 (just-one-space)))
8025 (when org-trigger-hook
8026 (save-excursion
8027 (run-hook-with-args 'org-trigger-hook change-plist)))))))
8029 (defun org-update-parent-todo-statistics ()
8030 "Update any statistics cookie in the parent of the current headline."
8031 (interactive)
8032 (let ((box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
8033 level (cnt-all 0) (cnt-done 0) is-percent kwd)
8034 (catch 'exit
8035 (save-excursion
8036 (setq level (org-up-heading-safe))
8037 (unless (and level
8038 (re-search-forward box-re (point-at-eol) t))
8039 (throw 'exit nil))
8040 (setq is-percent (match-end 2))
8041 (save-match-data
8042 (unless (outline-next-heading) (throw 'exit nil))
8043 (while (looking-at org-todo-line-regexp)
8044 (setq kwd (match-string 2))
8045 (and kwd (setq cnt-all (1+ cnt-all)))
8046 (and (member kwd org-done-keywords)
8047 (setq cnt-done (1+ cnt-done)))
8048 (condition-case nil
8049 (org-forward-same-level 1)
8050 (error (end-of-line 1)))))
8051 (replace-match
8052 (if is-percent
8053 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
8054 (format "[%d/%d]" cnt-done cnt-all)))
8055 (run-hook-with-args 'org-after-todo-statistics-hook
8056 cnt-done (- cnt-all cnt-done))))))
8058 (defvar org-after-todo-statistics-hook nil
8059 "Hook that is called after a TODO statistics cookie has been updated.
8060 Each function is called with two arguments: the number of not-done entries
8061 and the number of done entries.
8063 For example, the following function, when added to this hook, will switch
8064 an entry to DONE when all children are done, and back to TODO when new
8065 entries are set to a TODO status. Note that this hook is only called
8066 when there is a statistics cookie in the headline!
8068 (defun org-summary-todo (n-done n-not-done)
8069 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
8070 (let (org-log-done org-log-states) ; turn off logging
8071 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
8074 (defun org-todo-trigger-tag-changes (state)
8075 "Apply the changes defined in `org-todo-state-tags-triggers'."
8076 (let ((l org-todo-state-tags-triggers)
8077 changes)
8078 (when (or (not state) (equal state ""))
8079 (setq changes (append changes (cdr (assoc "" l)))))
8080 (when (and (stringp state) (> (length state) 0))
8081 (setq changes (append changes (cdr (assoc state l)))))
8082 (when (member state org-not-done-keywords)
8083 (setq changes (append changes (cdr (assoc 'todo l)))))
8084 (when (member state org-done-keywords)
8085 (setq changes (append changes (cdr (assoc 'done l)))))
8086 (dolist (c changes)
8087 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
8089 (defun org-local-logging (value)
8090 "Get logging settings from a property VALUE."
8091 (let* (words w a)
8092 ;; directly set the variables, they are already local.
8093 (setq org-log-done nil
8094 org-log-repeat nil
8095 org-todo-log-states nil)
8096 (setq words (org-split-string value))
8097 (while (setq w (pop words))
8098 (cond
8099 ((setq a (assoc w org-startup-options))
8100 (and (member (nth 1 a) '(org-log-done org-log-repeat))
8101 (set (nth 1 a) (nth 2 a))))
8102 ((setq a (org-extract-log-state-settings w))
8103 (and (member (car a) org-todo-keywords-1)
8104 (push a org-todo-log-states)))))))
8106 (defun org-get-todo-sequence-head (kwd)
8107 "Return the head of the TODO sequence to which KWD belongs.
8108 If KWD is not set, check if there is a text property remembering the
8109 right sequence."
8110 (let (p)
8111 (cond
8112 ((not kwd)
8113 (or (get-text-property (point-at-bol) 'org-todo-head)
8114 (progn
8115 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
8116 nil (point-at-eol)))
8117 (get-text-property p 'org-todo-head))))
8118 ((not (member kwd org-todo-keywords-1))
8119 (car org-todo-keywords-1))
8120 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
8122 (defun org-fast-todo-selection ()
8123 "Fast TODO keyword selection with single keys.
8124 Returns the new TODO keyword, or nil if no state change should occur."
8125 (let* ((fulltable org-todo-key-alist)
8126 (done-keywords org-done-keywords) ;; needed for the faces.
8127 (maxlen (apply 'max (mapcar
8128 (lambda (x)
8129 (if (stringp (car x)) (string-width (car x)) 0))
8130 fulltable)))
8131 (expert nil)
8132 (fwidth (+ maxlen 3 1 3))
8133 (ncol (/ (- (window-width) 4) fwidth))
8134 tg cnt e c tbl
8135 groups ingroup)
8136 (save-window-excursion
8137 (if expert
8138 (set-buffer (get-buffer-create " *Org todo*"))
8139 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
8140 (erase-buffer)
8141 (org-set-local 'org-done-keywords done-keywords)
8142 (setq tbl fulltable cnt 0)
8143 (while (setq e (pop tbl))
8144 (cond
8145 ((equal e '(:startgroup))
8146 (push '() groups) (setq ingroup t)
8147 (when (not (= cnt 0))
8148 (setq cnt 0)
8149 (insert "\n"))
8150 (insert "{ "))
8151 ((equal e '(:endgroup))
8152 (setq ingroup nil cnt 0)
8153 (insert "}\n"))
8155 (setq tg (car e) c (cdr e))
8156 (if ingroup (push tg (car groups)))
8157 (setq tg (org-add-props tg nil 'face
8158 (org-get-todo-face tg)))
8159 (if (and (= cnt 0) (not ingroup)) (insert " "))
8160 (insert "[" c "] " tg (make-string
8161 (- fwidth 4 (length tg)) ?\ ))
8162 (when (= (setq cnt (1+ cnt)) ncol)
8163 (insert "\n")
8164 (if ingroup (insert " "))
8165 (setq cnt 0)))))
8166 (insert "\n")
8167 (goto-char (point-min))
8168 (if (not expert) (org-fit-window-to-buffer))
8169 (message "[a-z..]:Set [SPC]:clear")
8170 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
8171 (cond
8172 ((or (= c ?\C-g)
8173 (and (= c ?q) (not (rassoc c fulltable))))
8174 (setq quit-flag t))
8175 ((= c ?\ ) nil)
8176 ((setq e (rassoc c fulltable) tg (car e))
8178 (t (setq quit-flag t))))))
8180 (defun org-entry-is-todo-p ()
8181 (member (org-get-todo-state) org-not-done-keywords))
8183 (defun org-entry-is-done-p ()
8184 (member (org-get-todo-state) org-done-keywords))
8186 (defun org-get-todo-state ()
8187 (save-excursion
8188 (org-back-to-heading t)
8189 (and (looking-at org-todo-line-regexp)
8190 (match-end 2)
8191 (match-string 2))))
8193 (defun org-at-date-range-p (&optional inactive-ok)
8194 "Is the cursor inside a date range?"
8195 (interactive)
8196 (save-excursion
8197 (catch 'exit
8198 (let ((pos (point)))
8199 (skip-chars-backward "^[<\r\n")
8200 (skip-chars-backward "<[")
8201 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8202 (>= (match-end 0) pos)
8203 (throw 'exit t))
8204 (skip-chars-backward "^<[\r\n")
8205 (skip-chars-backward "<[")
8206 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8207 (>= (match-end 0) pos)
8208 (throw 'exit t)))
8209 nil)))
8211 (defun org-get-repeat ()
8212 "Check if there is a deadline/schedule with repeater in this entry."
8213 (save-match-data
8214 (save-excursion
8215 (org-back-to-heading t)
8216 (if (re-search-forward
8217 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
8218 (match-string 1)))))
8220 (defvar org-last-changed-timestamp)
8221 (defvar org-last-inserted-timestamp)
8222 (defvar org-log-post-message)
8223 (defvar org-log-note-purpose)
8224 (defvar org-log-note-how)
8225 (defvar org-log-note-extra)
8226 (defun org-auto-repeat-maybe (done-word)
8227 "Check if the current headline contains a repeated deadline/schedule.
8228 If yes, set TODO state back to what it was and change the base date
8229 of repeating deadline/scheduled time stamps to new date.
8230 This function is run automatically after each state change to a DONE state."
8231 ;; last-state is dynamically scoped into this function
8232 (let* ((repeat (org-get-repeat))
8233 (aa (assoc last-state org-todo-kwd-alist))
8234 (interpret (nth 1 aa))
8235 (head (nth 2 aa))
8236 (whata '(("d" . day) ("m" . month) ("y" . year)))
8237 (msg "Entry repeats: ")
8238 (org-log-done nil)
8239 (org-todo-log-states nil)
8240 (nshiftmax 10) (nshift 0)
8241 re type n what ts mb0 time)
8242 (when repeat
8243 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
8244 (org-todo (if (eq interpret 'type) last-state head))
8245 (when org-log-repeat
8246 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
8247 (memq 'org-add-log-note post-command-hook))
8248 ;; OK, we are already setup for some record
8249 (if (eq org-log-repeat 'note)
8250 ;; make sure we take a note, not only a time stamp
8251 (setq org-log-note-how 'note))
8252 ;; Set up for taking a record
8253 (org-add-log-setup 'state (or done-word (car org-done-keywords))
8254 'findpos org-log-repeat)))
8255 (org-back-to-heading t)
8256 (org-add-planning-info nil nil 'closed)
8257 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
8258 org-deadline-time-regexp "\\)\\|\\("
8259 org-ts-regexp "\\)"))
8260 (while (re-search-forward
8261 re (save-excursion (outline-next-heading) (point)) t)
8262 (setq type (if (match-end 1) org-scheduled-string
8263 (if (match-end 3) org-deadline-string "Plain:"))
8264 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0)))
8265 mb0 (match-beginning 0))
8266 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
8267 (setq n (string-to-number (match-string 2 ts))
8268 what (match-string 3 ts))
8269 (if (equal what "w") (setq n (* n 7) what "d"))
8270 ;; Preparation, see if we need to modify the start date for the change
8271 (when (match-end 1)
8272 (setq time (save-match-data (org-time-string-to-time ts)))
8273 (cond
8274 ((equal (match-string 1 ts) ".")
8275 ;; Shift starting date to today
8276 (org-timestamp-change
8277 (- (time-to-days (current-time)) (time-to-days time))
8278 'day))
8279 ((equal (match-string 1 ts) "+")
8280 (while (or (= nshift 0)
8281 (<= (time-to-days time) (time-to-days (current-time))))
8282 (when (= (incf nshift) nshiftmax)
8283 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
8284 (error "Abort")))
8285 (org-timestamp-change n (cdr (assoc what whata)))
8286 (org-at-timestamp-p t)
8287 (setq ts (match-string 1))
8288 (setq time (save-match-data (org-time-string-to-time ts))))
8289 (org-timestamp-change (- n) (cdr (assoc what whata)))
8290 ;; rematch, so that we have everything in place for the real shift
8291 (org-at-timestamp-p t)
8292 (setq ts (match-string 1))
8293 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
8294 (org-timestamp-change n (cdr (assoc what whata)))
8295 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
8296 (setq org-log-post-message msg)
8297 (message "%s" msg))))
8299 (defun org-show-todo-tree (arg)
8300 "Make a compact tree which shows all headlines marked with TODO.
8301 The tree will show the lines where the regexp matches, and all higher
8302 headlines above the match.
8303 With a \\[universal-argument] prefix, also show the DONE entries.
8304 With a numeric prefix N, construct a sparse tree for the Nth element
8305 of `org-todo-keywords-1'."
8306 (interactive "P")
8307 (let ((case-fold-search nil)
8308 (kwd-re
8309 (cond ((null arg) org-not-done-regexp)
8310 ((equal arg '(4))
8311 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
8312 (mapcar 'list org-todo-keywords-1))))
8313 (concat "\\("
8314 (mapconcat 'identity (org-split-string kwd "|") "\\|")
8315 "\\)\\>")))
8316 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
8317 (regexp-quote (nth (1- (prefix-numeric-value arg))
8318 org-todo-keywords-1)))
8319 (t (error "Invalid prefix argument: %s" arg)))))
8320 (message "%d TODO entries found"
8321 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
8323 (defun org-deadline (&optional remove time)
8324 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
8325 With argument REMOVE, remove any deadline from the item.
8326 When TIME is set, it should be an internal time specification, and the
8327 scheduling will use the corresponding date."
8328 (interactive "P")
8329 (if remove
8330 (progn
8331 (org-remove-timestamp-with-keyword org-deadline-string)
8332 (message "Item no longer has a deadline."))
8333 (if (org-get-repeat)
8334 (error "Cannot change deadline on task with repeater, please do that by hand")
8335 (org-add-planning-info 'deadline time 'closed)
8336 (message "Deadline on %s" org-last-inserted-timestamp))))
8338 (defun org-schedule (&optional remove time)
8339 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
8340 With argument REMOVE, remove any scheduling date from the item.
8341 When TIME is set, it should be an internal time specification, and the
8342 scheduling will use the corresponding date."
8343 (interactive "P")
8344 (if remove
8345 (progn
8346 (org-remove-timestamp-with-keyword org-scheduled-string)
8347 (message "Item is no longer scheduled."))
8348 (if (org-get-repeat)
8349 (error "Cannot reschedule task with repeater, please do that by hand")
8350 (org-add-planning-info 'scheduled time 'closed)
8351 (message "Scheduled to %s" org-last-inserted-timestamp))))
8353 (defun org-remove-timestamp-with-keyword (keyword)
8354 "Remove all time stamps with KEYWORD in the current entry."
8355 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
8356 beg)
8357 (save-excursion
8358 (org-back-to-heading t)
8359 (setq beg (point))
8360 (org-end-of-subtree t t)
8361 (while (re-search-backward re beg t)
8362 (replace-match "")
8363 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
8364 (equal (char-before) ?\ ))
8365 (backward-delete-char 1)
8366 (if (string-match "^[ \t]*$" (buffer-substring
8367 (point-at-bol) (point-at-eol)))
8368 (delete-region (point-at-bol)
8369 (min (point-max) (1+ (point-at-eol))))))))))
8371 (defun org-add-planning-info (what &optional time &rest remove)
8372 "Insert new timestamp with keyword in the line directly after the headline.
8373 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
8374 If non is given, the user is prompted for a date.
8375 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
8376 be removed."
8377 (interactive)
8378 (let (org-time-was-given org-end-time-was-given ts
8379 end default-time default-input)
8381 (when (and (not time) (memq what '(scheduled deadline)))
8382 ;; Try to get a default date/time from existing timestamp
8383 (save-excursion
8384 (org-back-to-heading t)
8385 (setq end (save-excursion (outline-next-heading) (point)))
8386 (when (re-search-forward (if (eq what 'scheduled)
8387 org-scheduled-time-regexp
8388 org-deadline-time-regexp)
8389 end t)
8390 (setq ts (match-string 1)
8391 default-time
8392 (apply 'encode-time (org-parse-time-string ts))
8393 default-input (and ts (org-get-compact-tod ts))))))
8394 (when what
8395 ;; If necessary, get the time from the user
8396 (setq time (or time (org-read-date nil 'to-time nil nil
8397 default-time default-input))))
8399 (when (and org-insert-labeled-timestamps-at-point
8400 (member what '(scheduled deadline)))
8401 (insert
8402 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
8403 (org-insert-time-stamp time org-time-was-given
8404 nil nil nil (list org-end-time-was-given))
8405 (setq what nil))
8406 (save-excursion
8407 (save-restriction
8408 (let (col list elt ts buffer-invisibility-spec)
8409 (org-back-to-heading t)
8410 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
8411 (goto-char (match-end 1))
8412 (setq col (current-column))
8413 (goto-char (match-end 0))
8414 (if (eobp) (insert "\n") (forward-char 1))
8415 (if (and (not (looking-at outline-regexp))
8416 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
8417 "[^\r\n]*"))
8418 (not (equal (match-string 1) org-clock-string)))
8419 (narrow-to-region (match-beginning 0) (match-end 0))
8420 (insert-before-markers "\n")
8421 (backward-char 1)
8422 (narrow-to-region (point) (point))
8423 (and org-adapt-indentation (org-indent-to-column col)))
8424 ;; Check if we have to remove something.
8425 (setq list (cons what remove))
8426 (while list
8427 (setq elt (pop list))
8428 (goto-char (point-min))
8429 (when (or (and (eq elt 'scheduled)
8430 (re-search-forward org-scheduled-time-regexp nil t))
8431 (and (eq elt 'deadline)
8432 (re-search-forward org-deadline-time-regexp nil t))
8433 (and (eq elt 'closed)
8434 (re-search-forward org-closed-time-regexp nil t)))
8435 (replace-match "")
8436 (if (looking-at "--+<[^>]+>") (replace-match ""))
8437 (if (looking-at " +") (replace-match ""))))
8438 (goto-char (point-max))
8439 (when what
8440 (insert
8441 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
8442 (cond ((eq what 'scheduled) org-scheduled-string)
8443 ((eq what 'deadline) org-deadline-string)
8444 ((eq what 'closed) org-closed-string))
8445 " ")
8446 (setq ts (org-insert-time-stamp
8447 time
8448 (or org-time-was-given
8449 (and (eq what 'closed) org-log-done-with-time))
8450 (eq what 'closed)
8451 nil nil (list org-end-time-was-given)))
8452 (end-of-line 1))
8453 (goto-char (point-min))
8454 (widen)
8455 (if (and (looking-at "[ \t]+\n")
8456 (equal (char-before) ?\n))
8457 (delete-region (1- (point)) (point-at-eol)))
8458 ts)))))
8460 (defvar org-log-note-marker (make-marker))
8461 (defvar org-log-note-purpose nil)
8462 (defvar org-log-note-state nil)
8463 (defvar org-log-note-how nil)
8464 (defvar org-log-note-extra nil)
8465 (defvar org-log-note-window-configuration nil)
8466 (defvar org-log-note-return-to (make-marker))
8467 (defvar org-log-post-message nil
8468 "Message to be displayed after a log note has been stored.
8469 The auto-repeater uses this.")
8471 (defun org-add-note ()
8472 "Add a note to the current entry.
8473 This is done in the same way as adding a state change note."
8474 (interactive)
8475 (org-add-log-setup 'note nil 'findpos nil))
8477 (defvar org-property-end-re)
8478 (defun org-add-log-setup (&optional purpose state findpos how &optional extra)
8479 "Set up the post command hook to take a note.
8480 If this is about to TODO state change, the new state is expected in STATE.
8481 When FINDPOS is non-nil, find the correct position for the note in
8482 the current entry. If not, assume that it can be inserted at point.
8483 HOW is an indicator what kind of note should be created.
8484 EXTRA is additional text that will be inserted into the notes buffer."
8485 (save-restriction
8486 (save-excursion
8487 (when findpos
8488 (org-back-to-heading t)
8489 (narrow-to-region (point) (save-excursion
8490 (outline-next-heading) (point)))
8491 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
8492 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
8493 "[^\r\n]*\\)?"))
8494 (goto-char (match-end 0))
8495 (when (and org-log-state-notes-insert-after-drawers
8496 (save-excursion
8497 (forward-line) (looking-at org-drawer-regexp)))
8498 (progn (forward-line)
8499 (while (looking-at org-drawer-regexp)
8500 (goto-char (match-end 0))
8501 (re-search-forward org-property-end-re (point-max) t)
8502 (forward-line))
8503 (forward-line -1)))
8504 (unless org-log-states-order-reversed
8505 (and (= (char-after) ?\n) (forward-char 1))
8506 (org-skip-over-state-notes)
8507 (skip-chars-backward " \t\n\r")))
8508 (move-marker org-log-note-marker (point))
8509 (setq org-log-note-purpose purpose
8510 org-log-note-state state
8511 org-log-note-how how
8512 org-log-note-extra extra)
8513 (add-hook 'post-command-hook 'org-add-log-note 'append))))
8515 (defun org-skip-over-state-notes ()
8516 "Skip past the list of State notes in an entry."
8517 (if (looking-at "\n[ \t]*- State") (forward-char 1))
8518 (while (looking-at "[ \t]*- State")
8519 (condition-case nil
8520 (org-next-item)
8521 (error (org-end-of-item)))))
8523 (defun org-add-log-note (&optional purpose)
8524 "Pop up a window for taking a note, and add this note later at point."
8525 (remove-hook 'post-command-hook 'org-add-log-note)
8526 (setq org-log-note-window-configuration (current-window-configuration))
8527 (delete-other-windows)
8528 (move-marker org-log-note-return-to (point))
8529 (switch-to-buffer (marker-buffer org-log-note-marker))
8530 (goto-char org-log-note-marker)
8531 (org-switch-to-buffer-other-window "*Org Note*")
8532 (erase-buffer)
8533 (if (memq org-log-note-how '(time state))
8534 (let (current-prefix-arg) (org-store-log-note))
8535 (let ((org-inhibit-startup t)) (org-mode))
8536 (insert (format "# Insert note for %s.
8537 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
8538 (cond
8539 ((eq org-log-note-purpose 'clock-out) "stopped clock")
8540 ((eq org-log-note-purpose 'done) "closed todo item")
8541 ((eq org-log-note-purpose 'state)
8542 (format "state change to \"%s\"" org-log-note-state))
8543 ((eq org-log-note-purpose 'note)
8544 "this entry")
8545 (t (error "This should not happen")))))
8546 (if org-log-note-extra (insert org-log-note-extra))
8547 (org-set-local 'org-finish-function 'org-store-log-note)))
8549 (defvar org-note-abort nil) ; dynamically scoped
8550 (defun org-store-log-note ()
8551 "Finish taking a log note, and insert it to where it belongs."
8552 (let ((txt (buffer-string))
8553 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
8554 lines ind)
8555 (kill-buffer (current-buffer))
8556 (while (string-match "\\`#.*\n[ \t\n]*" txt)
8557 (setq txt (replace-match "" t t txt)))
8558 (if (string-match "\\s-+\\'" txt)
8559 (setq txt (replace-match "" t t txt)))
8560 (setq lines (org-split-string txt "\n"))
8561 (when (and note (string-match "\\S-" note))
8562 (setq note
8563 (org-replace-escapes
8564 note
8565 (list (cons "%u" (user-login-name))
8566 (cons "%U" user-full-name)
8567 (cons "%t" (format-time-string
8568 (org-time-stamp-format 'long 'inactive)
8569 (current-time)))
8570 (cons "%s" (if org-log-note-state
8571 (concat "\"" org-log-note-state "\"")
8572 "")))))
8573 (if lines (setq note (concat note " \\\\")))
8574 (push note lines))
8575 (when (or current-prefix-arg org-note-abort) (setq lines nil))
8576 (when lines
8577 (save-excursion
8578 (set-buffer (marker-buffer org-log-note-marker))
8579 (save-excursion
8580 (goto-char org-log-note-marker)
8581 (move-marker org-log-note-marker nil)
8582 (end-of-line 1)
8583 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
8584 (indent-relative nil)
8585 (insert "- " (pop lines))
8586 (org-indent-line-function)
8587 (beginning-of-line 1)
8588 (looking-at "[ \t]*")
8589 (setq ind (concat (match-string 0) " "))
8590 (end-of-line 1)
8591 (while lines (insert "\n" ind (pop lines)))))))
8592 (set-window-configuration org-log-note-window-configuration)
8593 (with-current-buffer (marker-buffer org-log-note-return-to)
8594 (goto-char org-log-note-return-to))
8595 (move-marker org-log-note-return-to nil)
8596 (and org-log-post-message (message "%s" org-log-post-message)))
8598 (defun org-sparse-tree (&optional arg)
8599 "Create a sparse tree, prompt for the details.
8600 This command can create sparse trees. You first need to select the type
8601 of match used to create the tree:
8603 t Show entries with a specific TODO keyword.
8604 T Show entries selected by a tags match.
8605 p Enter a property name and its value (both with completion on existing
8606 names/values) and show entries with that property.
8607 r Show entries matching a regular expression
8608 d Show deadlines due within `org-deadline-warning-days'."
8609 (interactive "P")
8610 (let (ans kwd value)
8611 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
8612 (setq ans (read-char-exclusive))
8613 (cond
8614 ((equal ans ?d)
8615 (call-interactively 'org-check-deadlines))
8616 ((equal ans ?b)
8617 (call-interactively 'org-check-before-date))
8618 ((equal ans ?t)
8619 (org-show-todo-tree '(4)))
8620 ((equal ans ?T)
8621 (call-interactively 'org-tags-sparse-tree))
8622 ((member ans '(?p ?P))
8623 (setq kwd (completing-read "Property: "
8624 (mapcar 'list (org-buffer-property-keys))))
8625 (setq value (completing-read "Value: "
8626 (mapcar 'list (org-property-values kwd))))
8627 (unless (string-match "\\`{.*}\\'" value)
8628 (setq value (concat "\"" value "\"")))
8629 (org-tags-sparse-tree arg (concat kwd "=" value)))
8630 ((member ans '(?r ?R ?/))
8631 (call-interactively 'org-occur))
8632 (t (error "No such sparse tree command \"%c\"" ans)))))
8634 (defvar org-occur-highlights nil
8635 "List of overlays used for occur matches.")
8636 (make-variable-buffer-local 'org-occur-highlights)
8637 (defvar org-occur-parameters nil
8638 "Parameters of the active org-occur calls.
8639 This is a list, each call to org-occur pushes as cons cell,
8640 containing the regular expression and the callback, onto the list.
8641 The list can contain several entries if `org-occur' has been called
8642 several time with the KEEP-PREVIOUS argument. Otherwise, this list
8643 will only contain one set of parameters. When the highlights are
8644 removed (for example with `C-c C-c', or with the next edit (depending
8645 on `org-remove-highlights-with-change'), this variable is emptied
8646 as well.")
8647 (make-variable-buffer-local 'org-occur-parameters)
8649 (defun org-occur (regexp &optional keep-previous callback)
8650 "Make a compact tree which shows all matches of REGEXP.
8651 The tree will show the lines where the regexp matches, and all higher
8652 headlines above the match. It will also show the heading after the match,
8653 to make sure editing the matching entry is easy.
8654 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
8655 call to `org-occur' will be kept, to allow stacking of calls to this
8656 command.
8657 If CALLBACK is non-nil, it is a function which is called to confirm
8658 that the match should indeed be shown."
8659 (interactive "sRegexp: \nP")
8660 (unless keep-previous
8661 (org-remove-occur-highlights nil nil t))
8662 (push (cons regexp callback) org-occur-parameters)
8663 (let ((cnt 0))
8664 (save-excursion
8665 (goto-char (point-min))
8666 (if (or (not keep-previous) ; do not want to keep
8667 (not org-occur-highlights)) ; no previous matches
8668 ;; hide everything
8669 (org-overview))
8670 (while (re-search-forward regexp nil t)
8671 (when (or (not callback)
8672 (save-match-data (funcall callback)))
8673 (setq cnt (1+ cnt))
8674 (when org-highlight-sparse-tree-matches
8675 (org-highlight-new-match (match-beginning 0) (match-end 0)))
8676 (org-show-context 'occur-tree))))
8677 (when org-remove-highlights-with-change
8678 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
8679 nil 'local))
8680 (unless org-sparse-tree-open-archived-trees
8681 (org-hide-archived-subtrees (point-min) (point-max)))
8682 (run-hooks 'org-occur-hook)
8683 (if (interactive-p)
8684 (message "%d match(es) for regexp %s" cnt regexp))
8685 cnt))
8687 (defun org-show-context (&optional key)
8688 "Make sure point and context and visible.
8689 How much context is shown depends upon the variables
8690 `org-show-hierarchy-above', `org-show-following-heading'. and
8691 `org-show-siblings'."
8692 (let ((heading-p (org-on-heading-p t))
8693 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
8694 (following-p (org-get-alist-option org-show-following-heading key))
8695 (entry-p (org-get-alist-option org-show-entry-below key))
8696 (siblings-p (org-get-alist-option org-show-siblings key)))
8697 (catch 'exit
8698 ;; Show heading or entry text
8699 (if (and heading-p (not entry-p))
8700 (org-flag-heading nil) ; only show the heading
8701 (and (or entry-p (org-invisible-p) (org-invisible-p2))
8702 (org-show-hidden-entry))) ; show entire entry
8703 (when following-p
8704 ;; Show next sibling, or heading below text
8705 (save-excursion
8706 (and (if heading-p (org-goto-sibling) (outline-next-heading))
8707 (org-flag-heading nil))))
8708 (when siblings-p (org-show-siblings))
8709 (when hierarchy-p
8710 ;; show all higher headings, possibly with siblings
8711 (save-excursion
8712 (while (and (condition-case nil
8713 (progn (org-up-heading-all 1) t)
8714 (error nil))
8715 (not (bobp)))
8716 (org-flag-heading nil)
8717 (when siblings-p (org-show-siblings))))))))
8719 (defun org-reveal (&optional siblings)
8720 "Show current entry, hierarchy above it, and the following headline.
8721 This can be used to show a consistent set of context around locations
8722 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
8723 not t for the search context.
8725 With optional argument SIBLINGS, on each level of the hierarchy all
8726 siblings are shown. This repairs the tree structure to what it would
8727 look like when opened with hierarchical calls to `org-cycle'."
8728 (interactive "P")
8729 (let ((org-show-hierarchy-above t)
8730 (org-show-following-heading t)
8731 (org-show-siblings (if siblings t org-show-siblings)))
8732 (org-show-context nil)))
8734 (defun org-highlight-new-match (beg end)
8735 "Highlight from BEG to END and mark the highlight is an occur headline."
8736 (let ((ov (org-make-overlay beg end)))
8737 (org-overlay-put ov 'face 'secondary-selection)
8738 (push ov org-occur-highlights)))
8740 (defun org-remove-occur-highlights (&optional beg end noremove)
8741 "Remove the occur highlights from the buffer.
8742 BEG and END are ignored. If NOREMOVE is nil, remove this function
8743 from the `before-change-functions' in the current buffer."
8744 (interactive)
8745 (unless org-inhibit-highlight-removal
8746 (mapc 'org-delete-overlay org-occur-highlights)
8747 (setq org-occur-highlights nil)
8748 (setq org-occur-parameters nil)
8749 (unless noremove
8750 (remove-hook 'before-change-functions
8751 'org-remove-occur-highlights 'local))))
8753 ;;;; Priorities
8755 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
8756 "Regular expression matching the priority indicator.")
8758 (defvar org-remove-priority-next-time nil)
8760 (defun org-priority-up ()
8761 "Increase the priority of the current item."
8762 (interactive)
8763 (org-priority 'up))
8765 (defun org-priority-down ()
8766 "Decrease the priority of the current item."
8767 (interactive)
8768 (org-priority 'down))
8770 (defun org-priority (&optional action)
8771 "Change the priority of an item by ARG.
8772 ACTION can be `set', `up', `down', or a character."
8773 (interactive)
8774 (setq action (or action 'set))
8775 (let (current new news have remove)
8776 (save-excursion
8777 (org-back-to-heading)
8778 (if (looking-at org-priority-regexp)
8779 (setq current (string-to-char (match-string 2))
8780 have t)
8781 (setq current org-default-priority))
8782 (cond
8783 ((or (eq action 'set)
8784 (if (featurep 'xemacs) (characterp action) (integerp action)))
8785 (if (not (eq action 'set))
8786 (setq new action)
8787 (message "Priority %c-%c, SPC to remove: "
8788 org-highest-priority org-lowest-priority)
8789 (setq new (read-char-exclusive)))
8790 (if (and (= (upcase org-highest-priority) org-highest-priority)
8791 (= (upcase org-lowest-priority) org-lowest-priority))
8792 (setq new (upcase new)))
8793 (cond ((equal new ?\ ) (setq remove t))
8794 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
8795 (error "Priority must be between `%c' and `%c'"
8796 org-highest-priority org-lowest-priority))))
8797 ((eq action 'up)
8798 (if (and (not have) (eq last-command this-command))
8799 (setq new org-lowest-priority)
8800 (setq new (if (and org-priority-start-cycle-with-default (not have))
8801 org-default-priority (1- current)))))
8802 ((eq action 'down)
8803 (if (and (not have) (eq last-command this-command))
8804 (setq new org-highest-priority)
8805 (setq new (if (and org-priority-start-cycle-with-default (not have))
8806 org-default-priority (1+ current)))))
8807 (t (error "Invalid action")))
8808 (if (or (< (upcase new) org-highest-priority)
8809 (> (upcase new) org-lowest-priority))
8810 (setq remove t))
8811 (setq news (format "%c" new))
8812 (if have
8813 (if remove
8814 (replace-match "" t t nil 1)
8815 (replace-match news t t nil 2))
8816 (if remove
8817 (error "No priority cookie found in line")
8818 (looking-at org-todo-line-regexp)
8819 (if (match-end 2)
8820 (progn
8821 (goto-char (match-end 2))
8822 (insert " [#" news "]"))
8823 (goto-char (match-beginning 3))
8824 (insert "[#" news "] ")))))
8825 (org-preserve-lc (org-set-tags nil 'align))
8826 (if remove
8827 (message "Priority removed")
8828 (message "Priority of current item set to %s" news))))
8831 (defun org-get-priority (s)
8832 "Find priority cookie and return priority."
8833 (save-match-data
8834 (if (not (string-match org-priority-regexp s))
8835 (* 1000 (- org-lowest-priority org-default-priority))
8836 (* 1000 (- org-lowest-priority
8837 (string-to-char (match-string 2 s)))))))
8839 ;;;; Tags
8841 (defvar org-agenda-archives-mode)
8842 (defun org-scan-tags (action matcher &optional todo-only)
8843 "Scan headline tags with inheritance and produce output ACTION.
8845 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
8846 or `agenda' to produce an entry list for an agenda view. It can also be
8847 a Lisp form or a function that should be called at each matched headline, in
8848 this case the return value is a list of all return values from these calls.
8850 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
8851 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
8852 only lines with a TODO keyword are included in the output."
8853 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
8854 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
8855 (org-re
8856 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
8857 (props (list 'face 'default
8858 'done-face 'org-done
8859 'undone-face 'default
8860 'mouse-face 'highlight
8861 'org-not-done-regexp org-not-done-regexp
8862 'org-todo-regexp org-todo-regexp
8863 'keymap org-agenda-keymap
8864 'help-echo
8865 (format "mouse-2 or RET jump to org file %s"
8866 (abbreviate-file-name
8867 (or (buffer-file-name (buffer-base-buffer))
8868 (buffer-name (buffer-base-buffer)))))))
8869 (case-fold-search nil)
8870 lspos tags tags-list
8871 (tags-alist (list (cons 0 (mapcar 'downcase org-file-tags))))
8872 (llast 0) rtn rtn1 level category i txt
8873 todo marker entry priority)
8874 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
8875 (setq action (list 'lambda nil action)))
8876 (save-excursion
8877 (goto-char (point-min))
8878 (when (eq action 'sparse-tree)
8879 (org-overview)
8880 (org-remove-occur-highlights))
8881 (while (re-search-forward re nil t)
8882 (catch :skip
8883 (setq todo (if (match-end 1) (match-string 2))
8884 tags (if (match-end 4) (match-string 4)))
8885 (goto-char (setq lspos (1+ (match-beginning 0))))
8886 (setq level (org-reduced-level (funcall outline-level))
8887 category (org-get-category))
8888 (setq i llast llast level)
8889 ;; remove tag lists from same and sublevels
8890 (while (>= i level)
8891 (when (setq entry (assoc i tags-alist))
8892 (setq tags-alist (delete entry tags-alist)))
8893 (setq i (1- i)))
8894 ;; add the next tags
8895 (when tags
8896 (setq tags (mapcar 'downcase (org-split-string tags ":"))
8897 tags-alist
8898 (cons (cons level tags) tags-alist)))
8899 ;; compile tags for current headline
8900 (setq tags-list
8901 (if org-use-tag-inheritance
8902 (apply 'append (mapcar 'cdr tags-alist))
8903 tags))
8904 (when (and tags org-use-tag-inheritance
8905 (not (eq t org-use-tag-inheritance)))
8906 ;; selective inheritance, remove uninherited ones
8907 (setcdr (car tags-alist)
8908 (org-remove-uniherited-tags (cdar tags-alist))))
8909 (when (and (or (not todo-only) (member todo org-not-done-keywords))
8910 (let ((case-fold-search t)) (eval matcher))
8912 (not (member org-archive-tag tags-list))
8913 ;; we have an archive tag, should we use this anyway?
8914 (or (not org-agenda-skip-archived-trees)
8915 (and (eq action 'agenda) org-agenda-archives-mode))))
8916 (unless (eq action 'sparse-tree) (org-agenda-skip))
8918 ;; select this headline
8920 (cond
8921 ((eq action 'sparse-tree)
8922 (and org-highlight-sparse-tree-matches
8923 (org-get-heading) (match-end 0)
8924 (org-highlight-new-match
8925 (match-beginning 0) (match-beginning 1)))
8926 (org-show-context 'tags-tree))
8927 ((eq action 'agenda)
8928 (setq txt (org-format-agenda-item
8930 (concat
8931 (if org-tags-match-list-sublevels
8932 (make-string (1- level) ?.) "")
8933 (org-get-heading))
8934 category tags-list)
8935 priority (org-get-priority txt))
8936 (goto-char lspos)
8937 (setq marker (org-agenda-new-marker))
8938 (org-add-props txt props
8939 'org-marker marker 'org-hd-marker marker 'org-category category
8940 'priority priority 'type "tagsmatch")
8941 (push txt rtn))
8942 ((functionp action)
8943 (save-excursion
8944 (setq rtn1 (funcall action))
8945 (push rtn1 rtn))
8946 (goto-char (point-at-eol)))
8947 (t (error "Invalid action")))
8949 ;; if we are to skip sublevels, jump to end of subtree
8950 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
8951 (when (and (eq action 'sparse-tree)
8952 (not org-sparse-tree-open-archived-trees))
8953 (org-hide-archived-subtrees (point-min) (point-max)))
8954 (nreverse rtn)))
8956 (defun org-remove-uniherited-tags (tags)
8957 "Remove all tags that are not inherited from the list TAGS."
8958 (cond
8959 ((eq org-use-tag-inheritance t) tags)
8960 ((not org-use-tag-inheritance) nil)
8961 ((stringp org-use-tag-inheritance)
8962 (delq nil (mapcar
8963 (lambda (x) (if (string-match org-use-tag-inheritance x) x nil))
8964 tags)))
8965 ((listp org-use-tag-inheritance)
8966 (delq nil (mapcar
8967 (lambda (x) (if (member x org-use-tag-inheritance) x nil))
8968 tags)))))
8970 (defvar todo-only) ;; dynamically scoped
8972 (defun org-tags-sparse-tree (&optional todo-only match)
8973 "Create a sparse tree according to tags string MATCH.
8974 MATCH can contain positive and negative selection of tags, like
8975 \"+WORK+URGENT-WITHBOSS\".
8976 If optional argument TODO_ONLY is non-nil, only select lines that are
8977 also TODO lines."
8978 (interactive "P")
8979 (org-prepare-agenda-buffers (list (current-buffer)))
8980 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
8982 (defvar org-cached-props nil)
8983 (defun org-cached-entry-get (pom property)
8984 (if (or (eq t org-use-property-inheritance)
8985 (and (stringp org-use-property-inheritance)
8986 (string-match org-use-property-inheritance property))
8987 (and (listp org-use-property-inheritance)
8988 (member property org-use-property-inheritance)))
8989 ;; Caching is not possible, check it directly
8990 (org-entry-get pom property 'inherit)
8991 ;; Get all properties, so that we can do complicated checks easily
8992 (cdr (assoc property (or org-cached-props
8993 (setq org-cached-props
8994 (org-entry-properties pom)))))))
8996 (defun org-global-tags-completion-table (&optional files)
8997 "Return the list of all tags in all agenda buffer/files."
8998 (save-excursion
8999 (org-uniquify
9000 (delq nil
9001 (apply 'append
9002 (mapcar
9003 (lambda (file)
9004 (set-buffer (find-file-noselect file))
9005 (append (org-get-buffer-tags)
9006 (mapcar (lambda (x) (if (stringp (car-safe x))
9007 (list (car-safe x)) nil))
9008 org-tag-alist)))
9009 (if (and files (car files))
9010 files
9011 (org-agenda-files))))))))
9013 (defun org-make-tags-matcher (match)
9014 "Create the TAGS//TODO matcher form for the selection string MATCH."
9015 ;; todo-only is scoped dynamically into this function, and the function
9016 ;; may change it it the matcher asksk for it.
9017 (unless match
9018 ;; Get a new match request, with completion
9019 (let ((org-last-tags-completion-table
9020 (org-global-tags-completion-table)))
9021 (setq match (completing-read
9022 "Match: " 'org-tags-completion-function nil nil nil
9023 'org-tags-history))))
9025 ;; Parse the string and create a lisp form
9026 (let ((match0 match)
9027 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
9028 minus tag mm
9029 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
9030 orterms term orlist re-p str-p level-p level-op time-p
9031 prop-p pn pv po cat-p gv rest)
9032 (if (string-match "/+" match)
9033 ;; match contains also a todo-matching request
9034 (progn
9035 (setq tagsmatch (substring match 0 (match-beginning 0))
9036 todomatch (substring match (match-end 0)))
9037 (if (string-match "^!" todomatch)
9038 (setq todo-only t todomatch (substring todomatch 1)))
9039 (if (string-match "^\\s-*$" todomatch)
9040 (setq todomatch nil)))
9041 ;; only matching tags
9042 (setq tagsmatch match todomatch nil))
9044 ;; Make the tags matcher
9045 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
9046 (setq tagsmatcher t)
9047 (setq orterms (org-split-string tagsmatch "|") orlist nil)
9048 (while (setq term (pop orterms))
9049 (while (and (equal (substring term -1) "\\") orterms)
9050 (setq term (concat term "|" (pop orterms)))) ; repair bad split
9051 (while (string-match re term)
9052 (setq rest (substring term (match-end 0))
9053 minus (and (match-end 1)
9054 (equal (match-string 1 term) "-"))
9055 tag (match-string 2 term)
9056 re-p (equal (string-to-char tag) ?{)
9057 level-p (match-end 4)
9058 prop-p (match-end 5)
9059 mm (cond
9060 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
9061 (level-p
9062 (setq level-op (org-op-to-function (match-string 3 term)))
9063 `(,level-op level ,(string-to-number
9064 (match-string 4 term))))
9065 (prop-p
9066 (setq pn (match-string 5 term)
9067 po (match-string 6 term)
9068 pv (match-string 7 term)
9069 cat-p (equal pn "CATEGORY")
9070 re-p (equal (string-to-char pv) ?{)
9071 str-p (equal (string-to-char pv) ?\")
9072 time-p (save-match-data
9073 (string-match "^\"[[<].*[]>]\"$" pv))
9074 pv (if (or re-p str-p) (substring pv 1 -1) pv))
9075 (if time-p (setq pv (org-matcher-time pv)))
9076 (setq po (org-op-to-function po (if time-p 'time str-p)))
9077 (cond
9078 ((equal pn "CATEGORY")
9079 (setq gv '(get-text-property (point) 'org-category)))
9080 ((equal pn "TODO")
9081 (setq gv 'todo))
9083 (setq gv `(org-cached-entry-get nil ,pn))))
9084 (if re-p
9085 (if (eq po 'org<>)
9086 `(not (string-match ,pv (or ,gv "")))
9087 `(string-match ,pv (or ,gv "")))
9088 (if str-p
9089 `(,po (or ,gv "") ,pv)
9090 `(,po (string-to-number (or ,gv ""))
9091 ,(string-to-number pv) ))))
9092 (t `(member ,(downcase tag) tags-list)))
9093 mm (if minus (list 'not mm) mm)
9094 term rest)
9095 (push mm tagsmatcher))
9096 (push (if (> (length tagsmatcher) 1)
9097 (cons 'and tagsmatcher)
9098 (car tagsmatcher))
9099 orlist)
9100 (setq tagsmatcher nil))
9101 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
9102 (setq tagsmatcher
9103 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
9104 ;; Make the todo matcher
9105 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
9106 (setq todomatcher t)
9107 (setq orterms (org-split-string todomatch "|") orlist nil)
9108 (while (setq term (pop orterms))
9109 (while (string-match re term)
9110 (setq minus (and (match-end 1)
9111 (equal (match-string 1 term) "-"))
9112 kwd (match-string 2 term)
9113 re-p (equal (string-to-char kwd) ?{)
9114 term (substring term (match-end 0))
9115 mm (if re-p
9116 `(string-match ,(substring kwd 1 -1) todo)
9117 (list 'equal 'todo kwd))
9118 mm (if minus (list 'not mm) mm))
9119 (push mm todomatcher))
9120 (push (if (> (length todomatcher) 1)
9121 (cons 'and todomatcher)
9122 (car todomatcher))
9123 orlist)
9124 (setq todomatcher nil))
9125 (setq todomatcher (if (> (length orlist) 1)
9126 (cons 'or orlist) (car orlist))))
9128 ;; Return the string and lisp forms of the matcher
9129 (setq matcher (if todomatcher
9130 (list 'and tagsmatcher todomatcher)
9131 tagsmatcher))
9132 (cons match0 matcher)))
9134 (defun org-op-to-function (op &optional stringp)
9135 "Turn an operator into the appropriate function."
9136 (setq op
9137 (cond
9138 ((equal op "<" ) '(< string< org-time<))
9139 ((equal op ">" ) '(> org-string> org-time>))
9140 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
9141 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
9142 ((member op '("=" "==")) '(= string= org-time=))
9143 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
9144 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
9146 (defun org<> (a b) (not (= a b)))
9147 (defun org-string<= (a b) (or (string= a b) (string< a b)))
9148 (defun org-string>= (a b) (not (string< a b)))
9149 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
9150 (defun org-string<> (a b) (not (string= a b)))
9151 (defun org-time= (a b) (= (org-2ft a) (org-2ft 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<> (org-2ft a) (org-2ft b)))
9157 (defun org-2ft (s)
9158 "Convert S to a floating point time.
9159 If S is already a number, just return it. If it is a string, parse
9160 it as a time string and apply `float-time' to it. f S is nil, just return 0."
9161 (cond
9162 ((numberp s) s)
9163 ((stringp s)
9164 (condition-case nil
9165 (float-time (apply 'encode-time (org-parse-time-string s)))
9166 (error 0.)))
9167 (t 0.)))
9169 (defun org-matcher-time (s)
9170 (cond
9171 ((equal s "<now>") (float-time))
9172 ((equal s "<today>")
9173 (float-time (append '(0 0 0) (nthcdr 3 (decode-time)))))
9174 (t (org-2ft s))))
9176 (defun org-match-any-p (re list)
9177 "Does re match any element of list?"
9178 (setq list (mapcar (lambda (x) (string-match re x)) list))
9179 (delq nil list))
9181 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
9182 (defvar org-tags-overlay (org-make-overlay 1 1))
9183 (org-detach-overlay org-tags-overlay)
9185 (defun org-get-local-tags-at (&optional pos)
9186 "Get a list of tags defined in the current headline."
9187 (org-get-tags-at pos 'local))
9189 (defun org-get-local-tags ()
9190 "Get a list of tags defined in the current headline."
9191 (org-get-tags-at nil 'local))
9193 (defun org-get-tags-at (&optional pos local)
9194 "Get a list of all headline tags applicable at POS.
9195 POS defaults to point. If tags are inherited, the list contains
9196 the targets in the same sequence as the headlines appear, i.e.
9197 the tags of the current headline come last.
9198 When LOCAL is non-nil, only return tags from the current headline,
9199 ignore inherited ones."
9200 (interactive)
9201 (let (tags ltags lastpos parent)
9202 (save-excursion
9203 (save-restriction
9204 (widen)
9205 (goto-char (or pos (point)))
9206 (save-match-data
9207 (catch 'done
9208 (condition-case nil
9209 (progn
9210 (org-back-to-heading t)
9211 (while (not (equal lastpos (point)))
9212 (setq lastpos (point))
9213 (when (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
9214 (setq ltags (org-split-string
9215 (org-match-string-no-properties 1) ":"))
9216 (setq tags (append
9217 (if parent
9218 (org-remove-uniherited-tags ltags)
9219 ltags)
9220 tags)))
9221 (or org-use-tag-inheritance (throw 'done t))
9222 (if local (throw 'done t))
9223 (org-up-heading-all 1)
9224 (setq parent t)))
9225 (error nil)))))
9226 (append (org-remove-uniherited-tags org-file-tags) tags))))
9228 (defun org-toggle-tag (tag &optional onoff)
9229 "Toggle the tag TAG for the current line.
9230 If ONOFF is `on' or `off', don't toggle but set to this state."
9231 (unless (org-on-heading-p t) (error "Not on headling"))
9232 (let (res current)
9233 (save-excursion
9234 (beginning-of-line)
9235 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
9236 (point-at-eol) t)
9237 (progn
9238 (setq current (match-string 1))
9239 (replace-match ""))
9240 (setq current ""))
9241 (setq current (nreverse (org-split-string current ":")))
9242 (cond
9243 ((eq onoff 'on)
9244 (setq res t)
9245 (or (member tag current) (push tag current)))
9246 ((eq onoff 'off)
9247 (or (not (member tag current)) (setq current (delete tag current))))
9248 (t (if (member tag current)
9249 (setq current (delete tag current))
9250 (setq res t)
9251 (push tag current))))
9252 (end-of-line 1)
9253 (if current
9254 (progn
9255 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
9256 (org-set-tags nil t))
9257 (delete-horizontal-space))
9258 (run-hooks 'org-after-tags-change-hook))
9259 res))
9261 (defun org-align-tags-here (to-col)
9262 ;; Assumes that this is a headline
9263 (let ((pos (point)) (col (current-column)) ncol tags-l p)
9264 (beginning-of-line 1)
9265 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9266 (< pos (match-beginning 2)))
9267 (progn
9268 (setq tags-l (- (match-end 2) (match-beginning 2)))
9269 (goto-char (match-beginning 1))
9270 (insert " ")
9271 (delete-region (point) (1+ (match-beginning 2)))
9272 (setq ncol (max (1+ (current-column))
9273 (1+ col)
9274 (if (> to-col 0)
9275 to-col
9276 (- (abs to-col) tags-l))))
9277 (setq p (point))
9278 (insert (make-string (- ncol (current-column)) ?\ ))
9279 (setq ncol (current-column))
9280 (when indent-tabs-mode (tabify p (point-at-eol)))
9281 (org-move-to-column (min ncol col) t))
9282 (goto-char pos))))
9284 (defun org-set-tags-command (&optional arg just-align)
9285 "Call the set-tags command for the current entry."
9286 (interactive "P")
9287 (if (org-on-heading-p)
9288 (org-set-tags arg just-align)
9289 (save-excursion
9290 (org-back-to-heading t)
9291 (org-set-tags arg just-align))))
9293 (defun org-set-tags (&optional arg just-align)
9294 "Set the tags for the current headline.
9295 With prefix ARG, realign all tags in headings in the current buffer."
9296 (interactive "P")
9297 (let* ((re (concat "^" outline-regexp))
9298 (current (org-get-tags-string))
9299 (col (current-column))
9300 (org-setting-tags t)
9301 table current-tags inherited-tags ; computed below when needed
9302 tags p0 c0 c1 rpl)
9303 (if arg
9304 (save-excursion
9305 (goto-char (point-min))
9306 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
9307 (while (re-search-forward re nil t)
9308 (org-set-tags nil t)
9309 (end-of-line 1)))
9310 (message "All tags realigned to column %d" org-tags-column))
9311 (if just-align
9312 (setq tags current)
9313 ;; Get a new set of tags from the user
9314 (save-excursion
9315 (setq table (or org-tag-alist (org-get-buffer-tags))
9316 org-last-tags-completion-table table
9317 current-tags (org-split-string current ":")
9318 inherited-tags (nreverse
9319 (nthcdr (length current-tags)
9320 (nreverse (org-get-tags-at))))
9321 tags
9322 (if (or (eq t org-use-fast-tag-selection)
9323 (and org-use-fast-tag-selection
9324 (delq nil (mapcar 'cdr table))))
9325 (org-fast-tag-selection
9326 current-tags inherited-tags table
9327 (if org-fast-tag-selection-include-todo org-todo-key-alist))
9328 (let ((org-add-colon-after-tag-completion t))
9329 (org-trim
9330 (org-without-partial-completion
9331 (completing-read "Tags: " 'org-tags-completion-function
9332 nil nil current 'org-tags-history)))))))
9333 (while (string-match "[-+&]+" tags)
9334 ;; No boolean logic, just a list
9335 (setq tags (replace-match ":" t t tags))))
9337 (if (string-match "\\`[\t ]*\\'" tags)
9338 (setq tags "")
9339 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
9340 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
9342 ;; Insert new tags at the correct column
9343 (beginning-of-line 1)
9344 (cond
9345 ((and (equal current "") (equal tags "")))
9346 ((re-search-forward
9347 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
9348 (point-at-eol) t)
9349 (if (equal tags "")
9350 (setq rpl "")
9351 (goto-char (match-beginning 0))
9352 (setq c0 (current-column) p0 (point)
9353 c1 (max (1+ c0) (if (> org-tags-column 0)
9354 org-tags-column
9355 (- (- org-tags-column) (length tags))))
9356 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
9357 (replace-match rpl t t)
9358 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
9359 tags)
9360 (t (error "Tags alignment failed")))
9361 (org-move-to-column col)
9362 (unless just-align
9363 (run-hooks 'org-after-tags-change-hook)))))
9365 (defun org-change-tag-in-region (beg end tag off)
9366 "Add or remove TAG for each entry in the region.
9367 This works in the agenda, and also in an org-mode buffer."
9368 (interactive
9369 (list (region-beginning) (region-end)
9370 (let ((org-last-tags-completion-table
9371 (if (org-mode-p)
9372 (org-get-buffer-tags)
9373 (org-global-tags-completion-table))))
9374 (completing-read
9375 "Tag: " 'org-tags-completion-function nil nil nil
9376 'org-tags-history))
9377 (progn
9378 (message "[s]et or [r]emove? ")
9379 (equal (read-char-exclusive) ?r))))
9380 (if (fboundp 'deactivate-mark) (deactivate-mark))
9381 (let ((agendap (equal major-mode 'org-agenda-mode))
9382 l1 l2 m buf pos newhead (cnt 0))
9383 (goto-char end)
9384 (setq l2 (1- (org-current-line)))
9385 (goto-char beg)
9386 (setq l1 (org-current-line))
9387 (loop for l from l1 to l2 do
9388 (goto-line l)
9389 (setq m (get-text-property (point) 'org-hd-marker))
9390 (when (or (and (org-mode-p) (org-on-heading-p))
9391 (and agendap m))
9392 (setq buf (if agendap (marker-buffer m) (current-buffer))
9393 pos (if agendap m (point)))
9394 (with-current-buffer buf
9395 (save-excursion
9396 (save-restriction
9397 (goto-char pos)
9398 (setq cnt (1+ cnt))
9399 (org-toggle-tag tag (if off 'off 'on))
9400 (setq newhead (org-get-heading)))))
9401 (and agendap (org-agenda-change-all-lines newhead m))))
9402 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
9404 (defun org-tags-completion-function (string predicate &optional flag)
9405 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
9406 (confirm (lambda (x) (stringp (car x)))))
9407 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
9408 (setq s1 (match-string 1 string)
9409 s2 (match-string 2 string))
9410 (setq s1 "" s2 string))
9411 (cond
9412 ((eq flag nil)
9413 ;; try completion
9414 (setq rtn (try-completion s2 ctable confirm))
9415 (if (stringp rtn)
9416 (setq rtn
9417 (concat s1 s2 (substring rtn (length s2))
9418 (if (and org-add-colon-after-tag-completion
9419 (assoc rtn ctable))
9420 ":" ""))))
9421 rtn)
9422 ((eq flag t)
9423 ;; all-completions
9424 (all-completions s2 ctable confirm)
9426 ((eq flag 'lambda)
9427 ;; exact match?
9428 (assoc s2 ctable)))
9431 (defun org-fast-tag-insert (kwd tags face &optional end)
9432 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
9433 (insert (format "%-12s" (concat kwd ":"))
9434 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
9435 (or end "")))
9437 (defun org-fast-tag-show-exit (flag)
9438 (save-excursion
9439 (goto-line 3)
9440 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
9441 (replace-match ""))
9442 (when flag
9443 (end-of-line 1)
9444 (org-move-to-column (- (window-width) 19) t)
9445 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
9447 (defun org-set-current-tags-overlay (current prefix)
9448 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
9449 (if (featurep 'xemacs)
9450 (org-overlay-display org-tags-overlay (concat prefix s)
9451 'secondary-selection)
9452 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
9453 (org-overlay-display org-tags-overlay (concat prefix s)))))
9455 (defun org-fast-tag-selection (current inherited table &optional todo-table)
9456 "Fast tag selection with single keys.
9457 CURRENT is the current list of tags in the headline, INHERITED is the
9458 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
9459 possibly with grouping information. TODO-TABLE is a similar table with
9460 TODO keywords, should these have keys assigned to them.
9461 If the keys are nil, a-z are automatically assigned.
9462 Returns the new tags string, or nil to not change the current settings."
9463 (let* ((fulltable (append table todo-table))
9464 (maxlen (apply 'max (mapcar
9465 (lambda (x)
9466 (if (stringp (car x)) (string-width (car x)) 0))
9467 fulltable)))
9468 (buf (current-buffer))
9469 (expert (eq org-fast-tag-selection-single-key 'expert))
9470 (buffer-tags nil)
9471 (fwidth (+ maxlen 3 1 3))
9472 (ncol (/ (- (window-width) 4) fwidth))
9473 (i-face 'org-done)
9474 (c-face 'org-todo)
9475 tg cnt e c char c1 c2 ntable tbl rtn
9476 ov-start ov-end ov-prefix
9477 (exit-after-next org-fast-tag-selection-single-key)
9478 (done-keywords org-done-keywords)
9479 groups ingroup)
9480 (save-excursion
9481 (beginning-of-line 1)
9482 (if (looking-at
9483 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9484 (setq ov-start (match-beginning 1)
9485 ov-end (match-end 1)
9486 ov-prefix "")
9487 (setq ov-start (1- (point-at-eol))
9488 ov-end (1+ ov-start))
9489 (skip-chars-forward "^\n\r")
9490 (setq ov-prefix
9491 (concat
9492 (buffer-substring (1- (point)) (point))
9493 (if (> (current-column) org-tags-column)
9495 (make-string (- org-tags-column (current-column)) ?\ ))))))
9496 (org-move-overlay org-tags-overlay ov-start ov-end)
9497 (save-window-excursion
9498 (if expert
9499 (set-buffer (get-buffer-create " *Org tags*"))
9500 (delete-other-windows)
9501 (split-window-vertically)
9502 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
9503 (erase-buffer)
9504 (org-set-local 'org-done-keywords done-keywords)
9505 (org-fast-tag-insert "Inherited" inherited i-face "\n")
9506 (org-fast-tag-insert "Current" current c-face "\n\n")
9507 (org-fast-tag-show-exit exit-after-next)
9508 (org-set-current-tags-overlay current ov-prefix)
9509 (setq tbl fulltable char ?a cnt 0)
9510 (while (setq e (pop tbl))
9511 (cond
9512 ((equal e '(:startgroup))
9513 (push '() groups) (setq ingroup t)
9514 (when (not (= cnt 0))
9515 (setq cnt 0)
9516 (insert "\n"))
9517 (insert "{ "))
9518 ((equal e '(:endgroup))
9519 (setq ingroup nil cnt 0)
9520 (insert "}\n"))
9522 (setq tg (car e) c2 nil)
9523 (if (cdr e)
9524 (setq c (cdr e))
9525 ;; automatically assign a character.
9526 (setq c1 (string-to-char
9527 (downcase (substring
9528 tg (if (= (string-to-char tg) ?@) 1 0)))))
9529 (if (or (rassoc c1 ntable) (rassoc c1 table))
9530 (while (or (rassoc char ntable) (rassoc char table))
9531 (setq char (1+ char)))
9532 (setq c2 c1))
9533 (setq c (or c2 char)))
9534 (if ingroup (push tg (car groups)))
9535 (setq tg (org-add-props tg nil 'face
9536 (cond
9537 ((not (assoc tg table))
9538 (org-get-todo-face tg))
9539 ((member tg current) c-face)
9540 ((member tg inherited) i-face)
9541 (t nil))))
9542 (if (and (= cnt 0) (not ingroup)) (insert " "))
9543 (insert "[" c "] " tg (make-string
9544 (- fwidth 4 (length tg)) ?\ ))
9545 (push (cons tg c) ntable)
9546 (when (= (setq cnt (1+ cnt)) ncol)
9547 (insert "\n")
9548 (if ingroup (insert " "))
9549 (setq cnt 0)))))
9550 (setq ntable (nreverse ntable))
9551 (insert "\n")
9552 (goto-char (point-min))
9553 (if (not expert) (org-fit-window-to-buffer))
9554 (setq rtn
9555 (catch 'exit
9556 (while t
9557 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
9558 (if groups " [!] no groups" " [!]groups")
9559 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
9560 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9561 (cond
9562 ((= c ?\r) (throw 'exit t))
9563 ((= c ?!)
9564 (setq groups (not groups))
9565 (goto-char (point-min))
9566 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
9567 ((= c ?\C-c)
9568 (if (not expert)
9569 (org-fast-tag-show-exit
9570 (setq exit-after-next (not exit-after-next)))
9571 (setq expert nil)
9572 (delete-other-windows)
9573 (split-window-vertically)
9574 (org-switch-to-buffer-other-window " *Org tags*")
9575 (org-fit-window-to-buffer)))
9576 ((or (= c ?\C-g)
9577 (and (= c ?q) (not (rassoc c ntable))))
9578 (org-detach-overlay org-tags-overlay)
9579 (setq quit-flag t))
9580 ((= c ?\ )
9581 (setq current nil)
9582 (if exit-after-next (setq exit-after-next 'now)))
9583 ((= c ?\t)
9584 (condition-case nil
9585 (setq tg (completing-read
9586 "Tag: "
9587 (or buffer-tags
9588 (with-current-buffer buf
9589 (org-get-buffer-tags)))))
9590 (quit (setq tg "")))
9591 (when (string-match "\\S-" tg)
9592 (add-to-list 'buffer-tags (list tg))
9593 (if (member tg current)
9594 (setq current (delete tg current))
9595 (push tg current)))
9596 (if exit-after-next (setq exit-after-next 'now)))
9597 ((setq e (rassoc c todo-table) tg (car e))
9598 (with-current-buffer buf
9599 (save-excursion (org-todo tg)))
9600 (if exit-after-next (setq exit-after-next 'now)))
9601 ((setq e (rassoc c ntable) tg (car e))
9602 (if (member tg current)
9603 (setq current (delete tg current))
9604 (loop for g in groups do
9605 (if (member tg g)
9606 (mapc (lambda (x)
9607 (setq current (delete x current)))
9608 g)))
9609 (push tg current))
9610 (if exit-after-next (setq exit-after-next 'now))))
9612 ;; Create a sorted list
9613 (setq current
9614 (sort current
9615 (lambda (a b)
9616 (assoc b (cdr (memq (assoc a ntable) ntable))))))
9617 (if (eq exit-after-next 'now) (throw 'exit t))
9618 (goto-char (point-min))
9619 (beginning-of-line 2)
9620 (delete-region (point) (point-at-eol))
9621 (org-fast-tag-insert "Current" current c-face)
9622 (org-set-current-tags-overlay current ov-prefix)
9623 (while (re-search-forward
9624 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
9625 (setq tg (match-string 1))
9626 (add-text-properties
9627 (match-beginning 1) (match-end 1)
9628 (list 'face
9629 (cond
9630 ((member tg current) c-face)
9631 ((member tg inherited) i-face)
9632 (t (get-text-property (match-beginning 1) 'face))))))
9633 (goto-char (point-min)))))
9634 (org-detach-overlay org-tags-overlay)
9635 (if rtn
9636 (mapconcat 'identity current ":")
9637 nil))))
9639 (defun org-get-tags-string ()
9640 "Get the TAGS string in the current headline."
9641 (unless (org-on-heading-p t)
9642 (error "Not on a heading"))
9643 (save-excursion
9644 (beginning-of-line 1)
9645 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9646 (org-match-string-no-properties 1)
9647 "")))
9649 (defun org-get-tags ()
9650 "Get the list of tags specified in the current headline."
9651 (org-split-string (org-get-tags-string) ":"))
9653 (defun org-get-buffer-tags ()
9654 "Get a table of all tags used in the buffer, for completion."
9655 (let (tags)
9656 (save-excursion
9657 (goto-char (point-min))
9658 (while (re-search-forward
9659 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
9660 (when (equal (char-after (point-at-bol 0)) ?*)
9661 (mapc (lambda (x) (add-to-list 'tags x))
9662 (org-split-string (org-match-string-no-properties 1) ":")))))
9663 (mapcar 'list tags)))
9665 ;;;; The mapping API
9667 ;;;###autoload
9668 (defun org-map-entries (func &optional match scope &rest skip)
9669 "Call FUNC at each headline selected by MATCH in SCOPE.
9671 FUNC is a function or a lisp form. The function will be called without
9672 arguments, with the cursor positioned at the beginning of the headline.
9673 The return values of all calls to the function will be collected and
9674 returned as a list.
9676 MATCH is a tags/property/todo match as it is used in the agenda tags view.
9677 Only headlines that are matched by this query will be considered during
9678 the iteration. When MATCH is nil or t, all headlines will be
9679 visited by the iteration.
9681 SCOPE determines the scope of this command. It can be any of:
9683 nil The current buffer, respecting the restriction if any
9684 tree The subtree started with the entry at point
9685 file The current buffer, without restriction
9686 file-with-archives
9687 The current buffer, and any archives associated with it
9688 agenda All agenda files
9689 agenda-with-archives
9690 All agenda files with any archive files associated with them
9691 \(file1 file2 ...)
9692 If this is a list, all files in the list will be scanned
9694 The remaining args are treated as settings for the skipping facilities of
9695 the scanner. The following items can be given here:
9697 archive skip trees with the archive tag.
9698 comment skip trees with the COMMENT keyword
9699 function or Emacs Lisp form:
9700 will be used as value for `org-agenda-skip-function', so whenever
9701 the the function returns t, FUNC will not be called for that
9702 entry and search will continue from the point where the
9703 function leaves it."
9704 (let* ((org-agenda-archives-mode nil) ; just to make sure
9705 (org-agenda-skip-archived-trees (memq 'archive skip))
9706 (org-agenda-skip-comment-trees (memq 'comment skip))
9707 (org-agenda-skip-function
9708 (car (org-delete-all '(comment archive) skip)))
9709 (org-tags-match-list-sublevels t)
9710 matcher pos file
9711 org-todo-keywords-for-agenda
9712 org-done-keywords-for-agenda
9713 org-todo-keyword-alist-for-agenda
9714 org-tag-alist-for-agenda)
9716 (cond
9717 ((eq match t) (setq matcher t))
9718 ((eq match nil) (setq matcher t))
9719 (t (setq matcher (if match (org-make-tags-matcher match) t))))
9721 (when (eq scope 'tree)
9722 (org-back-to-heading t)
9723 (org-narrow-to-subtree)
9724 (setq scope nil))
9726 (if (not scope)
9727 (progn
9728 (org-prepare-agenda-buffers
9729 (list (buffer-file-name (current-buffer))))
9730 (org-scan-tags func matcher))
9731 ;; Get the right scope
9732 (setq pos (point))
9733 (cond
9734 ((and scope (listp scope) (symbolp (car scope)))
9735 (setq scope (eval scope)))
9736 ((eq scope 'agenda)
9737 (setq scope (org-agenda-files t)))
9738 ((eq scope 'agenda-with-archives)
9739 (setq scope (org-agenda-files t))
9740 (setq scope (org-add-archive-files scope)))
9741 ((eq scope 'file)
9742 (setq scope (list (buffer-file-name))))
9743 ((eq scope 'file-with-archives)
9744 (setq scope (org-add-archive-files (list (buffer-file-name))))))
9745 (org-prepare-agenda-buffers scope)
9746 (while (setq file (pop scope))
9747 (with-current-buffer (org-find-base-buffer-visiting file)
9748 (save-excursion
9749 (save-restriction
9750 (widen)
9751 (goto-char (point-min))
9752 (org-scan-tags func matcher))))))))
9754 ;;;; Properties
9756 ;;; Setting and retrieving properties
9758 (defconst org-special-properties
9759 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
9760 "TIMESTAMP" "TIMESTAMP_IA")
9761 "The special properties valid in Org-mode.
9763 These are properties that are not defined in the property drawer,
9764 but in some other way.")
9766 (defconst org-default-properties
9767 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
9768 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
9769 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
9770 "EXPORT_FILE_NAME" "EXPORT_TITLE")
9771 "Some properties that are used by Org-mode for various purposes.
9772 Being in this list makes sure that they are offered for completion.")
9774 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
9775 "Regular expression matching the first line of a property drawer.")
9777 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
9778 "Regular expression matching the first line of a property drawer.")
9780 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
9781 "Regular expression matching the first line of a property drawer.")
9783 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
9784 "Regular expression matching the first line of a property drawer.")
9786 (defconst org-property-drawer-re
9787 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
9788 org-property-end-re "\\)\n?")
9789 "Matches an entire property drawer.")
9791 (defconst org-clock-drawer-re
9792 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
9793 org-property-end-re "\\)\n?")
9794 "Matches an entire clock drawer.")
9796 (defun org-property-action ()
9797 "Do an action on properties."
9798 (interactive)
9799 (let (c)
9800 (org-at-property-p)
9801 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
9802 (setq c (read-char-exclusive))
9803 (cond
9804 ((equal c ?s)
9805 (call-interactively 'org-set-property))
9806 ((equal c ?d)
9807 (call-interactively 'org-delete-property))
9808 ((equal c ?D)
9809 (call-interactively 'org-delete-property-globally))
9810 ((equal c ?c)
9811 (call-interactively 'org-compute-property-at-point))
9812 (t (error "No such property action %c" c)))))
9814 (defun org-at-property-p ()
9815 "Is the cursor in a property line?"
9816 ;; FIXME: Does not check if we are actually in the drawer.
9817 ;; FIXME: also returns true on any drawers.....
9818 ;; This is used by C-c C-c for property action.
9819 (save-excursion
9820 (beginning-of-line 1)
9821 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
9823 (defun org-get-property-block (&optional beg end force)
9824 "Return the (beg . end) range of the body of the property drawer.
9825 BEG and END can be beginning and end of subtree, if not given
9826 they will be found.
9827 If the drawer does not exist and FORCE is non-nil, create the drawer."
9828 (catch 'exit
9829 (save-excursion
9830 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
9831 (end (or end (progn (outline-next-heading) (point)))))
9832 (goto-char beg)
9833 (if (re-search-forward org-property-start-re end t)
9834 (setq beg (1+ (match-end 0)))
9835 (if force
9836 (save-excursion
9837 (org-insert-property-drawer)
9838 (setq end (progn (outline-next-heading) (point))))
9839 (throw 'exit nil))
9840 (goto-char beg)
9841 (if (re-search-forward org-property-start-re end t)
9842 (setq beg (1+ (match-end 0)))))
9843 (if (re-search-forward org-property-end-re end t)
9844 (setq end (match-beginning 0))
9845 (or force (throw 'exit nil))
9846 (goto-char beg)
9847 (setq end beg)
9848 (org-indent-line-function)
9849 (insert ":END:\n"))
9850 (cons beg end)))))
9852 (defun org-entry-properties (&optional pom which)
9853 "Get all properties of the entry at point-or-marker POM.
9854 This includes the TODO keyword, the tags, time strings for deadline,
9855 scheduled, and clocking, and any additional properties defined in the
9856 entry. The return value is an alist, keys may occur multiple times
9857 if the property key was used several times.
9858 POM may also be nil, in which case the current entry is used.
9859 If WHICH is nil or `all', get all properties. If WHICH is
9860 `special' or `standard', only get that subclass."
9861 (setq which (or which 'all))
9862 (org-with-point-at pom
9863 (let ((clockstr (substring org-clock-string 0 -1))
9864 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
9865 beg end range props sum-props key value string clocksum)
9866 (save-excursion
9867 (when (condition-case nil (org-back-to-heading t) (error nil))
9868 (setq beg (point))
9869 (setq sum-props (get-text-property (point) 'org-summaries))
9870 (setq clocksum (get-text-property (point) :org-clock-minutes))
9871 (outline-next-heading)
9872 (setq end (point))
9873 (when (memq which '(all special))
9874 ;; Get the special properties, like TODO and tags
9875 (goto-char beg)
9876 (when (and (looking-at org-todo-line-regexp) (match-end 2))
9877 (push (cons "TODO" (org-match-string-no-properties 2)) props))
9878 (when (looking-at org-priority-regexp)
9879 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
9880 (when (and (setq value (org-get-tags-string))
9881 (string-match "\\S-" value))
9882 (push (cons "TAGS" value) props))
9883 (when (setq value (org-get-tags-at))
9884 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
9885 props))
9886 (while (re-search-forward org-maybe-keyword-time-regexp end t)
9887 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
9888 string (if (equal key clockstr)
9889 (org-no-properties
9890 (org-trim
9891 (buffer-substring
9892 (match-beginning 3) (goto-char (point-at-eol)))))
9893 (substring (org-match-string-no-properties 3) 1 -1)))
9894 (unless key
9895 (if (= (char-after (match-beginning 3)) ?\[)
9896 (setq key "TIMESTAMP_IA")
9897 (setq key "TIMESTAMP")))
9898 (when (or (equal key clockstr) (not (assoc key props)))
9899 (push (cons key string) props)))
9903 (when (memq which '(all standard))
9904 ;; Get the standard properties, like :PORP: ...
9905 (setq range (org-get-property-block beg end))
9906 (when range
9907 (goto-char (car range))
9908 (while (re-search-forward
9909 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
9910 (cdr range) t)
9911 (setq key (org-match-string-no-properties 1)
9912 value (org-trim (or (org-match-string-no-properties 2) "")))
9913 (unless (member key excluded)
9914 (push (cons key (or value "")) props)))))
9915 (if clocksum
9916 (push (cons "CLOCKSUM"
9917 (org-columns-number-to-string (/ (float clocksum) 60.)
9918 'add_times))
9919 props))
9920 (unless (assoc "CATEGORY" props)
9921 (setq value (or (org-get-category)
9922 (progn (org-refresh-category-properties)
9923 (org-get-category))))
9924 (push (cons "CATEGORY" value) props))
9925 (append sum-props (nreverse props)))))))
9927 (defun org-entry-get (pom property &optional inherit)
9928 "Get value of PROPERTY for entry at point-or-marker POM.
9929 If INHERIT is non-nil and the entry does not have the property,
9930 then also check higher levels of the hierarchy.
9931 If INHERIT is the symbol `selective', use inheritance only if the setting
9932 in `org-use-property-inheritance' selects PROPERTY for inheritance.
9933 If the property is present but empty, the return value is the empty string.
9934 If the property is not present at all, nil is returned."
9935 (org-with-point-at pom
9936 (if (and inherit (if (eq inherit 'selective)
9937 (org-property-inherit-p property)
9939 (org-entry-get-with-inheritance property)
9940 (if (member property org-special-properties)
9941 ;; We need a special property. Use brute force, get all properties.
9942 (cdr (assoc property (org-entry-properties nil 'special)))
9943 (let ((range (org-get-property-block)))
9944 (if (and range
9945 (goto-char (car range))
9946 (re-search-forward
9947 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
9948 (cdr range) t))
9949 ;; Found the property, return it.
9950 (if (match-end 1)
9951 (org-match-string-no-properties 1)
9952 "")))))))
9954 (defun org-property-or-variable-value (var &optional inherit)
9955 "Check if there is a property fixing the value of VAR.
9956 If yes, return this value. If not, return the current value of the variable."
9957 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
9958 (if (and prop (stringp prop) (string-match "\\S-" prop))
9959 (read prop)
9960 (symbol-value var))))
9962 (defun org-entry-delete (pom property)
9963 "Delete the property PROPERTY from entry at point-or-marker POM."
9964 (org-with-point-at pom
9965 (if (member property org-special-properties)
9966 nil ; cannot delete these properties.
9967 (let ((range (org-get-property-block)))
9968 (if (and range
9969 (goto-char (car range))
9970 (re-search-forward
9971 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
9972 (cdr range) t))
9973 (progn
9974 (delete-region (match-beginning 0) (1+ (point-at-eol)))
9976 nil)))))
9978 ;; Multi-values properties are properties that contain multiple values
9979 ;; These values are assumed to be single words, separated by whitespace.
9980 (defun org-entry-add-to-multivalued-property (pom property value)
9981 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
9982 (let* ((old (org-entry-get pom property))
9983 (values (and old (org-split-string old "[ \t]"))))
9984 (setq value (org-entry-protect-space value))
9985 (unless (member value values)
9986 (setq values (cons value values))
9987 (org-entry-put pom property
9988 (mapconcat 'identity values " ")))))
9990 (defun org-entry-remove-from-multivalued-property (pom property value)
9991 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
9992 (let* ((old (org-entry-get pom property))
9993 (values (and old (org-split-string old "[ \t]"))))
9994 (setq value (org-entry-protect-space value))
9995 (when (member value values)
9996 (setq values (delete value values))
9997 (org-entry-put pom property
9998 (mapconcat 'identity values " ")))))
10000 (defun org-entry-member-in-multivalued-property (pom property value)
10001 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
10002 (let* ((old (org-entry-get pom property))
10003 (values (and old (org-split-string old "[ \t]"))))
10004 (setq value (org-entry-protect-space value))
10005 (member value values)))
10007 (defun org-entry-get-multivalued-property (pom property)
10008 "Return a list of values in a multivalued property."
10009 (let* ((value (org-entry-get pom property))
10010 (values (and value (org-split-string value "[ \t]"))))
10011 (mapcar 'org-entry-restore-space values)))
10013 (defun org-entry-put-multivalued-property (pom property &rest values)
10014 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
10015 VALUES should be a list of strings. Spaces will be protected."
10016 (org-entry-put pom property
10017 (mapconcat 'org-entry-protect-space values " "))
10018 (let* ((value (org-entry-get pom property))
10019 (values (and value (org-split-string value "[ \t]"))))
10020 (mapcar 'org-entry-restore-space values)))
10022 (defun org-entry-protect-space (s)
10023 "Protect spaces and newline in string S."
10024 (while (string-match " " s)
10025 (setq s (replace-match "%20" t t s)))
10026 (while (string-match "\n" s)
10027 (setq s (replace-match "%0A" t t s)))
10030 (defun org-entry-restore-space (s)
10031 "Restore spaces and newline in string S."
10032 (while (string-match "%20" s)
10033 (setq s (replace-match " " t t s)))
10034 (while (string-match "%0A" s)
10035 (setq s (replace-match "\n" t t s)))
10038 (defvar org-entry-property-inherited-from (make-marker)
10039 "Marker pointing to the entry from where a proerty was inherited.
10040 Each call to `org-entry-get-with-inheritance' will set this marker to the
10041 location of the entry where the inheriance search matched. If there was
10042 no match, the marker will point nowhere.
10043 Note that also `org-entry-get' calls this function, if the INHERIT flag
10044 is set.")
10046 (defun org-entry-get-with-inheritance (property)
10047 "Get entry property, and search higher levels if not present."
10048 (move-marker org-entry-property-inherited-from nil)
10049 (let (tmp)
10050 (save-excursion
10051 (save-restriction
10052 (widen)
10053 (catch 'ex
10054 (while t
10055 (when (setq tmp (org-entry-get nil property))
10056 (org-back-to-heading t)
10057 (move-marker org-entry-property-inherited-from (point))
10058 (throw 'ex tmp))
10059 (or (org-up-heading-safe) (throw 'ex nil)))))
10060 (or tmp
10061 (cdr (assoc property org-file-properties))
10062 (cdr (assoc property org-global-properties))
10063 (cdr (assoc property org-global-properties-fixed))))))
10065 (defun org-entry-put (pom property value)
10066 "Set PROPERTY to VALUE for entry at point-or-marker POM."
10067 (org-with-point-at pom
10068 (org-back-to-heading t)
10069 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
10070 range)
10071 (cond
10072 ((equal property "TODO")
10073 (when (and (stringp value) (string-match "\\S-" value)
10074 (not (member value org-todo-keywords-1)))
10075 (error "\"%s\" is not a valid TODO state" value))
10076 (if (or (not value)
10077 (not (string-match "\\S-" value)))
10078 (setq value 'none))
10079 (org-todo value)
10080 (org-set-tags nil 'align))
10081 ((equal property "PRIORITY")
10082 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
10083 (string-to-char value) ?\ ))
10084 (org-set-tags nil 'align))
10085 ((equal property "SCHEDULED")
10086 (if (re-search-forward org-scheduled-time-regexp end t)
10087 (cond
10088 ((eq value 'earlier) (org-timestamp-change -1 'day))
10089 ((eq value 'later) (org-timestamp-change 1 'day))
10090 (t (call-interactively 'org-schedule)))
10091 (call-interactively 'org-schedule)))
10092 ((equal property "DEADLINE")
10093 (if (re-search-forward org-deadline-time-regexp end t)
10094 (cond
10095 ((eq value 'earlier) (org-timestamp-change -1 'day))
10096 ((eq value 'later) (org-timestamp-change 1 'day))
10097 (t (call-interactively 'org-deadline)))
10098 (call-interactively 'org-deadline)))
10099 ((member property org-special-properties)
10100 (error "The %s property can not yet be set with `org-entry-put'"
10101 property))
10102 (t ; a non-special property
10103 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
10104 (setq range (org-get-property-block beg end 'force))
10105 (goto-char (car range))
10106 (if (re-search-forward
10107 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
10108 (progn
10109 (delete-region (match-beginning 1) (match-end 1))
10110 (goto-char (match-beginning 1)))
10111 (goto-char (cdr range))
10112 (insert "\n")
10113 (backward-char 1)
10114 (org-indent-line-function)
10115 (insert ":" property ":"))
10116 (and value (insert " " value))
10117 (org-indent-line-function)))))))
10119 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
10120 "Get all property keys in the current buffer.
10121 With INCLUDE-SPECIALS, also list the special properties that relect things
10122 like tags and TODO state.
10123 With INCLUDE-DEFAULTS, also include properties that has special meaning
10124 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
10125 With INCLUDE-COLUMNS, also include property names given in COLUMN
10126 formats in the current buffer."
10127 (let (rtn range cfmt cols s p)
10128 (save-excursion
10129 (save-restriction
10130 (widen)
10131 (goto-char (point-min))
10132 (while (re-search-forward org-property-start-re nil t)
10133 (setq range (org-get-property-block))
10134 (goto-char (car range))
10135 (while (re-search-forward
10136 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
10137 (cdr range) t)
10138 (add-to-list 'rtn (org-match-string-no-properties 1)))
10139 (outline-next-heading))))
10141 (when include-specials
10142 (setq rtn (append org-special-properties rtn)))
10144 (when include-defaults
10145 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
10147 (when include-columns
10148 (save-excursion
10149 (save-restriction
10150 (widen)
10151 (goto-char (point-min))
10152 (while (re-search-forward
10153 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
10154 nil t)
10155 (setq cfmt (match-string 2) s 0)
10156 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
10157 cfmt s)
10158 (setq s (match-end 0)
10159 p (match-string 1 cfmt))
10160 (unless (or (equal p "ITEM")
10161 (member p org-special-properties))
10162 (add-to-list 'rtn (match-string 1 cfmt))))))))
10164 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
10166 (defun org-property-values (key)
10167 "Return a list of all values of property KEY."
10168 (save-excursion
10169 (save-restriction
10170 (widen)
10171 (goto-char (point-min))
10172 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
10173 values)
10174 (while (re-search-forward re nil t)
10175 (add-to-list 'values (org-trim (match-string 1))))
10176 (delete "" values)))))
10178 (defun org-insert-property-drawer ()
10179 "Insert a property drawer into the current entry."
10180 (interactive)
10181 (org-back-to-heading t)
10182 (looking-at outline-regexp)
10183 (let ((indent (- (match-end 0)(match-beginning 0)))
10184 (beg (point))
10185 (re (concat "^[ \t]*" org-keyword-time-regexp))
10186 end hiddenp)
10187 (outline-next-heading)
10188 (setq end (point))
10189 (goto-char beg)
10190 (while (re-search-forward re end t))
10191 (setq hiddenp (org-invisible-p))
10192 (end-of-line 1)
10193 (and (equal (char-after) ?\n) (forward-char 1))
10194 (while (looking-at "^[ \t]*\\(:CLOCK:\\|CLOCK\\|:END:\\)")
10195 (beginning-of-line 2))
10196 (org-skip-over-state-notes)
10197 (skip-chars-backward " \t\n\r")
10198 (if (eq (char-before) ?*) (forward-char 1))
10199 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
10200 (beginning-of-line 0)
10201 (org-indent-to-column indent)
10202 (beginning-of-line 2)
10203 (org-indent-to-column indent)
10204 (beginning-of-line 0)
10205 (if hiddenp
10206 (save-excursion
10207 (org-back-to-heading t)
10208 (hide-entry))
10209 (org-flag-drawer t))))
10211 (defun org-set-property (property value)
10212 "In the current entry, set PROPERTY to VALUE.
10213 When called interactively, this will prompt for a property name, offering
10214 completion on existing and default properties. And then it will prompt
10215 for a value, offering competion either on allowed values (via an inherited
10216 xxx_ALL property) or on existing values in other instances of this property
10217 in the current file."
10218 (interactive
10219 (let* ((completion-ignore-case t)
10220 (keys (org-buffer-property-keys nil t t))
10221 (prop0 (completing-read "Property: " (mapcar 'list keys)))
10222 (prop (if (member prop0 keys)
10223 prop0
10224 (or (cdr (assoc (downcase prop0)
10225 (mapcar (lambda (x) (cons (downcase x) x))
10226 keys)))
10227 prop0)))
10228 (cur (org-entry-get nil prop))
10229 (allowed (org-property-get-allowed-values nil prop 'table))
10230 (existing (mapcar 'list (org-property-values prop)))
10231 (val (if allowed
10232 (org-completing-read "Value: " allowed nil 'req-match)
10233 (org-completing-read
10234 (concat "Value" (if (and cur (string-match "\\S-" cur))
10235 (concat "[" cur "]") "")
10236 ": ")
10237 existing nil nil "" nil cur))))
10238 (list prop (if (equal val "") cur val))))
10239 (unless (equal (org-entry-get nil property) value)
10240 (org-entry-put nil property value)))
10242 (defun org-delete-property (property)
10243 "In the current entry, delete PROPERTY."
10244 (interactive
10245 (let* ((completion-ignore-case t)
10246 (prop (completing-read
10247 "Property: " (org-entry-properties nil 'standard))))
10248 (list prop)))
10249 (message "Property %s %s" property
10250 (if (org-entry-delete nil property)
10251 "deleted"
10252 "was not present in the entry")))
10254 (defun org-delete-property-globally (property)
10255 "Remove PROPERTY globally, from all entries."
10256 (interactive
10257 (let* ((completion-ignore-case t)
10258 (prop (completing-read
10259 "Globally remove property: "
10260 (mapcar 'list (org-buffer-property-keys)))))
10261 (list prop)))
10262 (save-excursion
10263 (save-restriction
10264 (widen)
10265 (goto-char (point-min))
10266 (let ((cnt 0))
10267 (while (re-search-forward
10268 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
10269 nil t)
10270 (setq cnt (1+ cnt))
10271 (replace-match ""))
10272 (message "Property \"%s\" removed from %d entries" property cnt)))))
10274 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
10276 (defun org-compute-property-at-point ()
10277 "Compute the property at point.
10278 This looks for an enclosing column format, extracts the operator and
10279 then applies it to the proerty in the column format's scope."
10280 (interactive)
10281 (unless (org-at-property-p)
10282 (error "Not at a property"))
10283 (let ((prop (org-match-string-no-properties 2)))
10284 (org-columns-get-format-and-top-level)
10285 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
10286 (error "No operator defined for property %s" prop))
10287 (org-columns-compute prop)))
10289 (defun org-property-get-allowed-values (pom property &optional table)
10290 "Get allowed values for the property PROPERTY.
10291 When TABLE is non-nil, return an alist that can directly be used for
10292 completion."
10293 (let (vals)
10294 (cond
10295 ((equal property "TODO")
10296 (setq vals (org-with-point-at pom
10297 (append org-todo-keywords-1 '("")))))
10298 ((equal property "PRIORITY")
10299 (let ((n org-lowest-priority))
10300 (while (>= n org-highest-priority)
10301 (push (char-to-string n) vals)
10302 (setq n (1- n)))))
10303 ((member property org-special-properties))
10305 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
10307 (when (and vals (string-match "\\S-" vals))
10308 (setq vals (car (read-from-string (concat "(" vals ")"))))
10309 (setq vals (mapcar (lambda (x)
10310 (cond ((stringp x) x)
10311 ((numberp x) (number-to-string x))
10312 ((symbolp x) (symbol-name x))
10313 (t "???")))
10314 vals)))))
10315 (if table (mapcar 'list vals) vals)))
10317 (defun org-property-previous-allowed-value (&optional previous)
10318 "Switch to the next allowed value for this property."
10319 (interactive)
10320 (org-property-next-allowed-value t))
10322 (defun org-property-next-allowed-value (&optional previous)
10323 "Switch to the next allowed value for this property."
10324 (interactive)
10325 (unless (org-at-property-p)
10326 (error "Not at a property"))
10327 (let* ((key (match-string 2))
10328 (value (match-string 3))
10329 (allowed (or (org-property-get-allowed-values (point) key)
10330 (and (member value '("[ ]" "[-]" "[X]"))
10331 '("[ ]" "[X]"))))
10332 nval)
10333 (unless allowed
10334 (error "Allowed values for this property have not been defined"))
10335 (if previous (setq allowed (reverse allowed)))
10336 (if (member value allowed)
10337 (setq nval (car (cdr (member value allowed)))))
10338 (setq nval (or nval (car allowed)))
10339 (if (equal nval value)
10340 (error "Only one allowed value for this property"))
10341 (org-at-property-p)
10342 (replace-match (concat " :" key ": " nval) t t)
10343 (org-indent-line-function)
10344 (beginning-of-line 1)
10345 (skip-chars-forward " \t")))
10347 (defun org-find-entry-with-id (ident)
10348 "Locate the entry that contains the ID property with exact value IDENT.
10349 IDENT can be a string, a symbol or a number, this function will search for
10350 the string representation of it.
10351 Return the position where this entry starts, or nil if there is no such entry."
10352 (let ((id (cond
10353 ((stringp ident) ident)
10354 ((symbol-name ident) (symbol-name ident))
10355 ((numberp ident) (number-to-string ident))
10356 (t (error "IDENT %s must be a string, symbol or number" ident))))
10357 (case-fold-search nil))
10358 (save-excursion
10359 (save-restriction
10360 (widen)
10361 (goto-char (point-min))
10362 (when (re-search-forward
10363 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
10364 nil t)
10365 (org-back-to-heading)
10366 (point))))))
10368 ;;;; Timestamps
10370 (defvar org-last-changed-timestamp nil)
10371 (defvar org-last-inserted-timestamp nil
10372 "The last time stamp inserted with `org-insert-time-stamp'.")
10373 (defvar org-time-was-given) ; dynamically scoped parameter
10374 (defvar org-end-time-was-given) ; dynamically scoped parameter
10375 (defvar org-ts-what) ; dynamically scoped parameter
10377 (defun org-time-stamp (arg &optional inactive)
10378 "Prompt for a date/time and insert a time stamp.
10379 If the user specifies a time like HH:MM, or if this command is called
10380 with a prefix argument, the time stamp will contain date and time.
10381 Otherwise, only the date will be included. All parts of a date not
10382 specified by the user will be filled in from the current date/time.
10383 So if you press just return without typing anything, the time stamp
10384 will represent the current date/time. If there is already a timestamp
10385 at the cursor, it will be modified."
10386 (interactive "P")
10387 (let* ((ts nil)
10388 (default-time
10389 ;; Default time is either today, or, when entering a range,
10390 ;; the range start.
10391 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
10392 (save-excursion
10393 (re-search-backward
10394 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
10395 (- (point) 20) t)))
10396 (apply 'encode-time (org-parse-time-string (match-string 1)))
10397 (current-time)))
10398 (default-input (and ts (org-get-compact-tod ts)))
10399 org-time-was-given org-end-time-was-given time)
10400 (cond
10401 ((and (org-at-timestamp-p t)
10402 (memq last-command '(org-time-stamp org-time-stamp-inactive))
10403 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
10404 (insert "--")
10405 (setq time (let ((this-command this-command))
10406 (org-read-date arg 'totime nil nil
10407 default-time default-input)))
10408 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
10409 ((org-at-timestamp-p t)
10410 (setq time (let ((this-command this-command))
10411 (org-read-date arg 'totime nil nil default-time default-input)))
10412 (when (org-at-timestamp-p t) ; just to get the match data
10413 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
10414 (replace-match "")
10415 (setq org-last-changed-timestamp
10416 (org-insert-time-stamp
10417 time (or org-time-was-given arg)
10418 inactive nil nil (list org-end-time-was-given))))
10419 (message "Timestamp updated"))
10421 (setq time (let ((this-command this-command))
10422 (org-read-date arg 'totime nil nil default-time default-input)))
10423 (org-insert-time-stamp time (or org-time-was-given arg) inactive
10424 nil nil (list org-end-time-was-given))))))
10426 ;; FIXME: can we use this for something else, like computing time differences?
10427 (defun org-get-compact-tod (s)
10428 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
10429 (let* ((t1 (match-string 1 s))
10430 (h1 (string-to-number (match-string 2 s)))
10431 (m1 (string-to-number (match-string 3 s)))
10432 (t2 (and (match-end 4) (match-string 5 s)))
10433 (h2 (and t2 (string-to-number (match-string 6 s))))
10434 (m2 (and t2 (string-to-number (match-string 7 s))))
10435 dh dm)
10436 (if (not t2)
10438 (setq dh (- h2 h1) dm (- m2 m1))
10439 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
10440 (concat t1 "+" (number-to-string dh)
10441 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
10443 (defun org-time-stamp-inactive (&optional arg)
10444 "Insert an inactive time stamp.
10445 An inactive time stamp is enclosed in square brackets instead of angle
10446 brackets. It is inactive in the sense that it does not trigger agenda entries,
10447 does not link to the calendar and cannot be changed with the S-cursor keys.
10448 So these are more for recording a certain time/date."
10449 (interactive "P")
10450 (org-time-stamp arg 'inactive))
10452 (defvar org-date-ovl (org-make-overlay 1 1))
10453 (org-overlay-put org-date-ovl 'face 'org-warning)
10454 (org-detach-overlay org-date-ovl)
10456 (defvar org-ans1) ; dynamically scoped parameter
10457 (defvar org-ans2) ; dynamically scoped parameter
10459 (defvar org-plain-time-of-day-regexp) ; defined below
10461 (defvar org-overriding-default-time nil) ; dynamically scoped
10462 (defvar org-read-date-overlay nil)
10463 (defvar org-dcst nil) ; dynamically scoped
10465 (defun org-read-date (&optional with-time to-time from-string prompt
10466 default-time default-input)
10467 "Read a date, possibly a time, and make things smooth for the user.
10468 The prompt will suggest to enter an ISO date, but you can also enter anything
10469 which will at least partially be understood by `parse-time-string'.
10470 Unrecognized parts of the date will default to the current day, month, year,
10471 hour and minute. If this command is called to replace a timestamp at point,
10472 of to enter the second timestamp of a range, the default time is taken from the
10473 existing stamp. For example,
10474 3-2-5 --> 2003-02-05
10475 feb 15 --> currentyear-02-15
10476 sep 12 9 --> 2009-09-12
10477 12:45 --> today 12:45
10478 22 sept 0:34 --> currentyear-09-22 0:34
10479 12 --> currentyear-currentmonth-12
10480 Fri --> nearest Friday (today or later)
10481 etc.
10483 Furthermore you can specify a relative date by giving, as the *first* thing
10484 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
10485 change in days weeks, months, years.
10486 With a single plus or minus, the date is relative to today. With a double
10487 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
10488 +4d --> four days from today
10489 +4 --> same as above
10490 +2w --> two weeks from today
10491 ++5 --> five days from default date
10493 The function understands only English month and weekday abbreviations,
10494 but this can be configured with the variables `parse-time-months' and
10495 `parse-time-weekdays'.
10497 While prompting, a calendar is popped up - you can also select the
10498 date with the mouse (button 1). The calendar shows a period of three
10499 months. To scroll it to other months, use the keys `>' and `<'.
10500 If you don't like the calendar, turn it off with
10501 \(setq org-read-date-popup-calendar nil)
10503 With optional argument TO-TIME, the date will immediately be converted
10504 to an internal time.
10505 With an optional argument WITH-TIME, the prompt will suggest to also
10506 insert a time. Note that when WITH-TIME is not set, you can still
10507 enter a time, and this function will inform the calling routine about
10508 this change. The calling routine may then choose to change the format
10509 used to insert the time stamp into the buffer to include the time.
10510 With optional argument FROM-STRING, read from this string instead from
10511 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
10512 the time/date that is used for everything that is not specified by the
10513 user."
10514 (require 'parse-time)
10515 (let* ((org-time-stamp-rounding-minutes
10516 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
10517 (org-dcst org-display-custom-times)
10518 (ct (org-current-time))
10519 (def (or org-overriding-default-time default-time ct))
10520 (defdecode (decode-time def))
10521 (dummy (progn
10522 (when (< (nth 2 defdecode) org-extend-today-until)
10523 (setcar (nthcdr 2 defdecode) -1)
10524 (setcar (nthcdr 1 defdecode) 59)
10525 (setq def (apply 'encode-time defdecode)
10526 defdecode (decode-time def)))))
10527 (calendar-move-hook nil)
10528 (calendar-view-diary-initially-flag nil)
10529 (view-diary-entries-initially nil)
10530 (calendar-view-holidays-initially-flag nil)
10531 (view-calendar-holidays-initially nil)
10532 (timestr (format-time-string
10533 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
10534 (prompt (concat (if prompt (concat prompt " ") "")
10535 (format "Date+time [%s]: " timestr)))
10536 ans (org-ans0 "") org-ans1 org-ans2 final)
10538 (cond
10539 (from-string (setq ans from-string))
10540 (org-read-date-popup-calendar
10541 (save-excursion
10542 (save-window-excursion
10543 (calendar)
10544 (calendar-forward-day (- (time-to-days def)
10545 (calendar-absolute-from-gregorian
10546 (calendar-current-date))))
10547 (org-eval-in-calendar nil t)
10548 (let* ((old-map (current-local-map))
10549 (map (copy-keymap calendar-mode-map))
10550 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
10551 (org-defkey map (kbd "RET") 'org-calendar-select)
10552 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
10553 'org-calendar-select-mouse)
10554 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
10555 'org-calendar-select-mouse)
10556 (org-defkey minibuffer-local-map [(meta shift left)]
10557 (lambda () (interactive)
10558 (org-eval-in-calendar '(calendar-backward-month 1))))
10559 (org-defkey minibuffer-local-map [(meta shift right)]
10560 (lambda () (interactive)
10561 (org-eval-in-calendar '(calendar-forward-month 1))))
10562 (org-defkey minibuffer-local-map [(meta shift up)]
10563 (lambda () (interactive)
10564 (org-eval-in-calendar '(calendar-backward-year 1))))
10565 (org-defkey minibuffer-local-map [(meta shift down)]
10566 (lambda () (interactive)
10567 (org-eval-in-calendar '(calendar-forward-year 1))))
10568 (org-defkey minibuffer-local-map [(shift up)]
10569 (lambda () (interactive)
10570 (org-eval-in-calendar '(calendar-backward-week 1))))
10571 (org-defkey minibuffer-local-map [(shift down)]
10572 (lambda () (interactive)
10573 (org-eval-in-calendar '(calendar-forward-week 1))))
10574 (org-defkey minibuffer-local-map [(shift left)]
10575 (lambda () (interactive)
10576 (org-eval-in-calendar '(calendar-backward-day 1))))
10577 (org-defkey minibuffer-local-map [(shift right)]
10578 (lambda () (interactive)
10579 (org-eval-in-calendar '(calendar-forward-day 1))))
10580 (org-defkey minibuffer-local-map ">"
10581 (lambda () (interactive)
10582 (org-eval-in-calendar '(scroll-calendar-left 1))))
10583 (org-defkey minibuffer-local-map "<"
10584 (lambda () (interactive)
10585 (org-eval-in-calendar '(scroll-calendar-right 1))))
10586 (unwind-protect
10587 (progn
10588 (use-local-map map)
10589 (add-hook 'post-command-hook 'org-read-date-display)
10590 (setq org-ans0 (read-string prompt default-input nil nil))
10591 ;; org-ans0: from prompt
10592 ;; org-ans1: from mouse click
10593 ;; org-ans2: from calendar motion
10594 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
10595 (remove-hook 'post-command-hook 'org-read-date-display)
10596 (use-local-map old-map)
10597 (when org-read-date-overlay
10598 (org-delete-overlay org-read-date-overlay)
10599 (setq org-read-date-overlay nil)))))))
10601 (t ; Naked prompt only
10602 (unwind-protect
10603 (setq ans (read-string prompt default-input nil timestr))
10604 (when org-read-date-overlay
10605 (org-delete-overlay org-read-date-overlay)
10606 (setq org-read-date-overlay nil)))))
10608 (setq final (org-read-date-analyze ans def defdecode))
10610 (if to-time
10611 (apply 'encode-time final)
10612 (if (and (boundp 'org-time-was-given) org-time-was-given)
10613 (format "%04d-%02d-%02d %02d:%02d"
10614 (nth 5 final) (nth 4 final) (nth 3 final)
10615 (nth 2 final) (nth 1 final))
10616 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
10617 (defvar def)
10618 (defvar defdecode)
10619 (defvar with-time)
10620 (defun org-read-date-display ()
10621 "Display the currrent date prompt interpretation in the minibuffer."
10622 (when org-read-date-display-live
10623 (when org-read-date-overlay
10624 (org-delete-overlay org-read-date-overlay))
10625 (let ((p (point)))
10626 (end-of-line 1)
10627 (while (not (equal (buffer-substring
10628 (max (point-min) (- (point) 4)) (point))
10629 " "))
10630 (insert " "))
10631 (goto-char p))
10632 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
10633 " " (or org-ans1 org-ans2)))
10634 (org-end-time-was-given nil)
10635 (f (org-read-date-analyze ans def defdecode))
10636 (fmts (if org-dcst
10637 org-time-stamp-custom-formats
10638 org-time-stamp-formats))
10639 (fmt (if (or with-time
10640 (and (boundp 'org-time-was-given) org-time-was-given))
10641 (cdr fmts)
10642 (car fmts)))
10643 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
10644 (when (and org-end-time-was-given
10645 (string-match org-plain-time-of-day-regexp txt))
10646 (setq txt (concat (substring txt 0 (match-end 0)) "-"
10647 org-end-time-was-given
10648 (substring txt (match-end 0)))))
10649 (setq org-read-date-overlay
10650 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
10651 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
10653 (defun org-read-date-analyze (ans def defdecode)
10654 "Analyze the combined answer of the date prompt."
10655 ;; FIXME: cleanup and comment
10656 (let (delta deltan deltaw deltadef year month day
10657 hour minute second wday pm h2 m2 tl wday1
10658 iso-year iso-weekday iso-week iso-year iso-date)
10660 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
10661 (setq ans "+0"))
10663 (when (setq delta (org-read-date-get-relative ans (current-time) def))
10664 (setq ans (replace-match "" t t ans)
10665 deltan (car delta)
10666 deltaw (nth 1 delta)
10667 deltadef (nth 2 delta)))
10669 ;; Check if there is an iso week date in there
10670 ;; If yes, sore the info and ostpone interpreting it until the rest
10671 ;; of the parsing is done
10672 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
10673 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
10674 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
10675 iso-week (string-to-number (match-string 2 ans)))
10676 (setq ans (replace-match "" t t ans)))
10678 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
10679 (when (string-match
10680 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
10681 (setq year (if (match-end 2)
10682 (string-to-number (match-string 2 ans))
10683 (string-to-number (format-time-string "%Y")))
10684 month (string-to-number (match-string 3 ans))
10685 day (string-to-number (match-string 4 ans)))
10686 (if (< year 100) (setq year (+ 2000 year)))
10687 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
10688 t nil ans)))
10689 ;; Help matching am/pm times, because `parse-time-string' does not do that.
10690 ;; If there is a time with am/pm, and *no* time without it, we convert
10691 ;; so that matching will be successful.
10692 (loop for i from 1 to 2 do ; twice, for end time as well
10693 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
10694 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
10695 (setq hour (string-to-number (match-string 1 ans))
10696 minute (if (match-end 3)
10697 (string-to-number (match-string 3 ans))
10699 pm (equal ?p
10700 (string-to-char (downcase (match-string 4 ans)))))
10701 (if (and (= hour 12) (not pm))
10702 (setq hour 0)
10703 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
10704 (setq ans (replace-match (format "%02d:%02d" hour minute)
10705 t t ans))))
10707 ;; Check if a time range is given as a duration
10708 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
10709 (setq hour (string-to-number (match-string 1 ans))
10710 h2 (+ hour (string-to-number (match-string 3 ans)))
10711 minute (string-to-number (match-string 2 ans))
10712 m2 (+ minute (if (match-end 5) (string-to-number
10713 (match-string 5 ans))0)))
10714 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
10715 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
10716 t t ans)))
10718 ;; Check if there is a time range
10719 (when (boundp 'org-end-time-was-given)
10720 (setq org-time-was-given nil)
10721 (when (and (string-match org-plain-time-of-day-regexp ans)
10722 (match-end 8))
10723 (setq org-end-time-was-given (match-string 8 ans))
10724 (setq ans (concat (substring ans 0 (match-beginning 7))
10725 (substring ans (match-end 7))))))
10727 (setq tl (parse-time-string ans)
10728 day (or (nth 3 tl) (nth 3 defdecode))
10729 month (or (nth 4 tl)
10730 (if (and org-read-date-prefer-future
10731 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
10732 (1+ (nth 4 defdecode))
10733 (nth 4 defdecode)))
10734 year (or (nth 5 tl)
10735 (if (and org-read-date-prefer-future
10736 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
10737 (1+ (nth 5 defdecode))
10738 (nth 5 defdecode)))
10739 hour (or (nth 2 tl) (nth 2 defdecode))
10740 minute (or (nth 1 tl) (nth 1 defdecode))
10741 second (or (nth 0 tl) 0)
10742 wday (nth 6 tl))
10744 ;; Special date definitions below
10745 (cond
10746 (iso-week
10747 ;; There was an iso week
10748 (setq year (or iso-year year)
10749 day (or iso-weekday wday 1)
10750 wday nil ; to make sure that the trigger below does not match
10751 iso-date (calendar-gregorian-from-absolute
10752 (calendar-absolute-from-iso
10753 (list iso-week day year))))
10754 ; FIXME: Should we also push ISO weeks into the future?
10755 ; (when (and org-read-date-prefer-future
10756 ; (not iso-year)
10757 ; (< (calendar-absolute-from-gregorian iso-date)
10758 ; (time-to-days (current-time))))
10759 ; (setq year (1+ year)
10760 ; iso-date (calendar-gregorian-from-absolute
10761 ; (calendar-absolute-from-iso
10762 ; (list iso-week day year)))))
10763 (setq month (car iso-date)
10764 year (nth 2 iso-date)
10765 day (nth 1 iso-date)))
10766 (deltan
10767 (unless deltadef
10768 (let ((now (decode-time (current-time))))
10769 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
10770 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
10771 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
10772 ((equal deltaw "m") (setq month (+ month deltan)))
10773 ((equal deltaw "y") (setq year (+ year deltan)))))
10774 ((and wday (not (nth 3 tl)))
10775 ;; Weekday was given, but no day, so pick that day in the week
10776 ;; on or after the derived date.
10777 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
10778 (unless (equal wday wday1)
10779 (setq day (+ day (% (- wday wday1 -7) 7))))))
10780 (if (and (boundp 'org-time-was-given)
10781 (nth 2 tl))
10782 (setq org-time-was-given t))
10783 (if (< year 100) (setq year (+ 2000 year)))
10784 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
10785 (list second minute hour day month year)))
10787 (defvar parse-time-weekdays)
10789 (defun org-read-date-get-relative (s today default)
10790 "Check string S for special relative date string.
10791 TODAY and DEFAULT are internal times, for today and for a default.
10792 Return shift list (N what def-flag)
10793 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
10794 N is the number of WHATs to shift.
10795 DEF-FLAG is t when a double ++ or -- indicates shift relative to
10796 the DEFAULT date rather than TODAY."
10797 (when (and
10798 (string-match
10799 (concat
10800 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
10801 "\\([0-9]+\\)?"
10802 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
10803 "\\([ \t]\\|$\\)") s)
10804 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
10805 (let* ((dir (if (> (match-end 1) (match-beginning 1))
10806 (string-to-char (substring (match-string 1 s) -1))
10807 ?+))
10808 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
10809 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
10810 (what (if (match-end 3) (match-string 3 s) "d"))
10811 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
10812 (date (if rel default today))
10813 (wday (nth 6 (decode-time date)))
10814 delta)
10815 (if wday1
10816 (progn
10817 (setq delta (mod (+ 7 (- wday1 wday)) 7))
10818 (if (= dir ?-) (setq delta (- delta 7)))
10819 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
10820 (list delta "d" rel))
10821 (list (* n (if (= dir ?-) -1 1)) what rel)))))
10823 (defun org-eval-in-calendar (form &optional keepdate)
10824 "Eval FORM in the calendar window and return to current window.
10825 Also, store the cursor date in variable org-ans2."
10826 (let ((sw (selected-window)))
10827 (select-window (get-buffer-window "*Calendar*"))
10828 (eval form)
10829 (when (and (not keepdate) (calendar-cursor-to-date))
10830 (let* ((date (calendar-cursor-to-date))
10831 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10832 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
10833 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
10834 (select-window sw)))
10836 (defun org-calendar-select ()
10837 "Return to `org-read-date' with the date currently selected.
10838 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
10839 (interactive)
10840 (when (calendar-cursor-to-date)
10841 (let* ((date (calendar-cursor-to-date))
10842 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10843 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
10844 (if (active-minibuffer-window) (exit-minibuffer))))
10846 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
10847 "Insert a date stamp for the date given by the internal TIME.
10848 WITH-HM means, use the stamp format that includes the time of the day.
10849 INACTIVE means use square brackets instead of angular ones, so that the
10850 stamp will not contribute to the agenda.
10851 PRE and POST are optional strings to be inserted before and after the
10852 stamp.
10853 The command returns the inserted time stamp."
10854 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
10855 stamp)
10856 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
10857 (insert-before-markers (or pre ""))
10858 (insert-before-markers (setq stamp (format-time-string fmt time)))
10859 (when (listp extra)
10860 (setq extra (car extra))
10861 (if (and (stringp extra)
10862 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
10863 (setq extra (format "-%02d:%02d"
10864 (string-to-number (match-string 1 extra))
10865 (string-to-number (match-string 2 extra))))
10866 (setq extra nil)))
10867 (when extra
10868 (backward-char 1)
10869 (insert-before-markers extra)
10870 (forward-char 1))
10871 (insert-before-markers (or post ""))
10872 (setq org-last-inserted-timestamp stamp)))
10874 (defun org-toggle-time-stamp-overlays ()
10875 "Toggle the use of custom time stamp formats."
10876 (interactive)
10877 (setq org-display-custom-times (not org-display-custom-times))
10878 (unless org-display-custom-times
10879 (let ((p (point-min)) (bmp (buffer-modified-p)))
10880 (while (setq p (next-single-property-change p 'display))
10881 (if (and (get-text-property p 'display)
10882 (eq (get-text-property p 'face) 'org-date))
10883 (remove-text-properties
10884 p (setq p (next-single-property-change p 'display))
10885 '(display t))))
10886 (set-buffer-modified-p bmp)))
10887 (if (featurep 'xemacs)
10888 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
10889 (org-restart-font-lock)
10890 (setq org-table-may-need-update t)
10891 (if org-display-custom-times
10892 (message "Time stamps are overlayed with custom format")
10893 (message "Time stamp overlays removed")))
10895 (defun org-display-custom-time (beg end)
10896 "Overlay modified time stamp format over timestamp between BEG and END."
10897 (let* ((ts (buffer-substring beg end))
10898 t1 w1 with-hm tf time str w2 (off 0))
10899 (save-match-data
10900 (setq t1 (org-parse-time-string ts t))
10901 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
10902 (setq off (- (match-end 0) (match-beginning 0)))))
10903 (setq end (- end off))
10904 (setq w1 (- end beg)
10905 with-hm (and (nth 1 t1) (nth 2 t1))
10906 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
10907 time (org-fix-decoded-time t1)
10908 str (org-add-props
10909 (format-time-string
10910 (substring tf 1 -1) (apply 'encode-time time))
10911 nil 'mouse-face 'highlight)
10912 w2 (length str))
10913 (if (not (= w2 w1))
10914 (add-text-properties (1+ beg) (+ 2 beg)
10915 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
10916 (if (featurep 'xemacs)
10917 (progn
10918 (put-text-property beg end 'invisible t)
10919 (put-text-property beg end 'end-glyph (make-glyph str)))
10920 (put-text-property beg end 'display str))))
10922 (defun org-translate-time (string)
10923 "Translate all timestamps in STRING to custom format.
10924 But do this only if the variable `org-display-custom-times' is set."
10925 (when org-display-custom-times
10926 (save-match-data
10927 (let* ((start 0)
10928 (re org-ts-regexp-both)
10929 t1 with-hm inactive tf time str beg end)
10930 (while (setq start (string-match re string start))
10931 (setq beg (match-beginning 0)
10932 end (match-end 0)
10933 t1 (save-match-data
10934 (org-parse-time-string (substring string beg end) t))
10935 with-hm (and (nth 1 t1) (nth 2 t1))
10936 inactive (equal (substring string beg (1+ beg)) "[")
10937 tf (funcall (if with-hm 'cdr 'car)
10938 org-time-stamp-custom-formats)
10939 time (org-fix-decoded-time t1)
10940 str (format-time-string
10941 (concat
10942 (if inactive "[" "<") (substring tf 1 -1)
10943 (if inactive "]" ">"))
10944 (apply 'encode-time time))
10945 string (replace-match str t t string)
10946 start (+ start (length str)))))))
10947 string)
10949 (defun org-fix-decoded-time (time)
10950 "Set 0 instead of nil for the first 6 elements of time.
10951 Don't touch the rest."
10952 (let ((n 0))
10953 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
10955 (defun org-days-to-time (timestamp-string)
10956 "Difference between TIMESTAMP-STRING and now in days."
10957 (- (time-to-days (org-time-string-to-time timestamp-string))
10958 (time-to-days (current-time))))
10960 (defun org-deadline-close (timestamp-string &optional ndays)
10961 "Is the time in TIMESTAMP-STRING close to the current date?"
10962 (setq ndays (or ndays (org-get-wdays timestamp-string)))
10963 (and (< (org-days-to-time timestamp-string) ndays)
10964 (not (org-entry-is-done-p))))
10966 (defun org-get-wdays (ts)
10967 "Get the deadline lead time appropriate for timestring TS."
10968 (cond
10969 ((<= org-deadline-warning-days 0)
10970 ;; 0 or negative, enforce this value no matter what
10971 (- org-deadline-warning-days))
10972 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
10973 ;; lead time is specified.
10974 (floor (* (string-to-number (match-string 1 ts))
10975 (cdr (assoc (match-string 2 ts)
10976 '(("d" . 1) ("w" . 7)
10977 ("m" . 30.4) ("y" . 365.25)))))))
10978 ;; go for the default.
10979 (t org-deadline-warning-days)))
10981 (defun org-calendar-select-mouse (ev)
10982 "Return to `org-read-date' with the date currently selected.
10983 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
10984 (interactive "e")
10985 (mouse-set-point ev)
10986 (when (calendar-cursor-to-date)
10987 (let* ((date (calendar-cursor-to-date))
10988 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10989 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
10990 (if (active-minibuffer-window) (exit-minibuffer))))
10992 (defun org-check-deadlines (ndays)
10993 "Check if there are any deadlines due or past due.
10994 A deadline is considered due if it happens within `org-deadline-warning-days'
10995 days from today's date. If the deadline appears in an entry marked DONE,
10996 it is not shown. The prefix arg NDAYS can be used to test that many
10997 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
10998 (interactive "P")
10999 (let* ((org-warn-days
11000 (cond
11001 ((equal ndays '(4)) 100000)
11002 (ndays (prefix-numeric-value ndays))
11003 (t (abs org-deadline-warning-days))))
11004 (case-fold-search nil)
11005 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
11006 (callback
11007 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
11009 (message "%d deadlines past-due or due within %d days"
11010 (org-occur regexp nil callback)
11011 org-warn-days)))
11013 (defun org-check-before-date (date)
11014 "Check if there are deadlines or scheduled entries before DATE."
11015 (interactive (list (org-read-date)))
11016 (let ((case-fold-search nil)
11017 (regexp (concat "\\<\\(" org-deadline-string
11018 "\\|" org-scheduled-string
11019 "\\) *<\\([^>]+\\)>"))
11020 (callback
11021 (lambda () (time-less-p
11022 (org-time-string-to-time (match-string 2))
11023 (org-time-string-to-time date)))))
11024 (message "%d entries before %s"
11025 (org-occur regexp nil callback) date)))
11027 (defun org-evaluate-time-range (&optional to-buffer)
11028 "Evaluate a time range by computing the difference between start and end.
11029 Normally the result is just printed in the echo area, but with prefix arg
11030 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
11031 If the time range is actually in a table, the result is inserted into the
11032 next column.
11033 For time difference computation, a year is assumed to be exactly 365
11034 days in order to avoid rounding problems."
11035 (interactive "P")
11037 (org-clock-update-time-maybe)
11038 (save-excursion
11039 (unless (org-at-date-range-p t)
11040 (goto-char (point-at-bol))
11041 (re-search-forward org-tr-regexp-both (point-at-eol) t))
11042 (if (not (org-at-date-range-p t))
11043 (error "Not at a time-stamp range, and none found in current line")))
11044 (let* ((ts1 (match-string 1))
11045 (ts2 (match-string 2))
11046 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
11047 (match-end (match-end 0))
11048 (time1 (org-time-string-to-time ts1))
11049 (time2 (org-time-string-to-time ts2))
11050 (t1 (time-to-seconds time1))
11051 (t2 (time-to-seconds time2))
11052 (diff (abs (- t2 t1)))
11053 (negative (< (- t2 t1) 0))
11054 ;; (ys (floor (* 365 24 60 60)))
11055 (ds (* 24 60 60))
11056 (hs (* 60 60))
11057 (fy "%dy %dd %02d:%02d")
11058 (fy1 "%dy %dd")
11059 (fd "%dd %02d:%02d")
11060 (fd1 "%dd")
11061 (fh "%02d:%02d")
11062 y d h m align)
11063 (if havetime
11064 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11066 d (floor (/ diff ds)) diff (mod diff ds)
11067 h (floor (/ diff hs)) diff (mod diff hs)
11068 m (floor (/ diff 60)))
11069 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11071 d (floor (+ (/ diff ds) 0.5))
11072 h 0 m 0))
11073 (if (not to-buffer)
11074 (message "%s" (org-make-tdiff-string y d h m))
11075 (if (org-at-table-p)
11076 (progn
11077 (goto-char match-end)
11078 (setq align t)
11079 (and (looking-at " *|") (goto-char (match-end 0))))
11080 (goto-char match-end))
11081 (if (looking-at
11082 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
11083 (replace-match ""))
11084 (if negative (insert " -"))
11085 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
11086 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
11087 (insert " " (format fh h m))))
11088 (if align (org-table-align))
11089 (message "Time difference inserted")))))
11091 (defun org-make-tdiff-string (y d h m)
11092 (let ((fmt "")
11093 (l nil))
11094 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
11095 l (push y l)))
11096 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
11097 l (push d l)))
11098 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
11099 l (push h l)))
11100 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
11101 l (push m l)))
11102 (apply 'format fmt (nreverse l))))
11104 (defun org-time-string-to-time (s)
11105 (apply 'encode-time (org-parse-time-string s)))
11107 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
11108 "Convert a time stamp to an absolute day number.
11109 If there is a specifyer for a cyclic time stamp, get the closest date to
11110 DAYNR.
11111 PREFER and SHOW_ALL are passed through to `org-closest-date'."
11112 (cond
11113 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
11114 (if (org-diary-sexp-entry (match-string 1 s) "" date)
11115 daynr
11116 (+ daynr 1000)))
11117 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
11118 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
11119 (time-to-days (current-time))) (match-string 0 s)
11120 prefer show-all))
11121 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
11123 (defun org-days-to-iso-week (days)
11124 "Return the iso week number."
11125 (require 'cal-iso)
11126 (car (calendar-iso-from-absolute days)))
11128 (defun org-small-year-to-year (year)
11129 "Convert 2-digit years into 4-digit years.
11130 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
11131 The year 2000 cannot be abbreviated. Any year lager than 99
11132 is retrned unchanged."
11133 (if (< year 38)
11134 (setq year (+ 2000 year))
11135 (if (< year 100)
11136 (setq year (+ 1900 year))))
11137 year)
11139 (defun org-time-from-absolute (d)
11140 "Return the time corresponding to date D.
11141 D may be an absolute day number, or a calendar-type list (month day year)."
11142 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
11143 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
11145 (defun org-calendar-holiday ()
11146 "List of holidays, for Diary display in Org-mode."
11147 (require 'holidays)
11148 (let ((hl (funcall
11149 (if (fboundp 'calendar-check-holidays)
11150 'calendar-check-holidays 'check-calendar-holidays) date)))
11151 (if hl (mapconcat 'identity hl "; "))))
11153 (defun org-diary-sexp-entry (sexp entry date)
11154 "Process a SEXP diary ENTRY for DATE."
11155 (require 'diary-lib)
11156 (let ((result (if calendar-debug-sexp
11157 (let ((stack-trace-on-error t))
11158 (eval (car (read-from-string sexp))))
11159 (condition-case nil
11160 (eval (car (read-from-string sexp)))
11161 (error
11162 (beep)
11163 (message "Bad sexp at line %d in %s: %s"
11164 (org-current-line)
11165 (buffer-file-name) sexp)
11166 (sleep-for 2))))))
11167 (cond ((stringp result) result)
11168 ((and (consp result)
11169 (stringp (cdr result))) (cdr result))
11170 (result entry)
11171 (t nil))))
11173 (defun org-diary-to-ical-string (frombuf)
11174 "Get iCalendar entries from diary entries in buffer FROMBUF.
11175 This uses the icalendar.el library."
11176 (let* ((tmpdir (if (featurep 'xemacs)
11177 (temp-directory)
11178 temporary-file-directory))
11179 (tmpfile (make-temp-name
11180 (expand-file-name "orgics" tmpdir)))
11181 buf rtn b e)
11182 (save-excursion
11183 (set-buffer frombuf)
11184 (icalendar-export-region (point-min) (point-max) tmpfile)
11185 (setq buf (find-buffer-visiting tmpfile))
11186 (set-buffer buf)
11187 (goto-char (point-min))
11188 (if (re-search-forward "^BEGIN:VEVENT" nil t)
11189 (setq b (match-beginning 0)))
11190 (goto-char (point-max))
11191 (if (re-search-backward "^END:VEVENT" nil t)
11192 (setq e (match-end 0)))
11193 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
11194 (kill-buffer buf)
11195 (delete-file tmpfile)
11196 rtn))
11198 (defun org-closest-date (start current change prefer show-all)
11199 "Find the date closest to CURRENT that is consistent with START and CHANGE.
11200 When PREFER is `past' return a date that is either CURRENT or past.
11201 When PREFER is `future', return a date that is either CURRENT or future.
11202 When SHOW-ALL is nil, only return the current occurence of a time stamp."
11203 ;; Make the proper lists from the dates
11204 (catch 'exit
11205 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
11206 dn dw sday cday n1 n2
11207 d m y y1 y2 date1 date2 nmonths nm ny m2)
11209 (setq start (org-date-to-gregorian start)
11210 current (org-date-to-gregorian
11211 (if show-all
11212 current
11213 (time-to-days (current-time))))
11214 sday (calendar-absolute-from-gregorian start)
11215 cday (calendar-absolute-from-gregorian current))
11217 (if (<= cday sday) (throw 'exit sday))
11219 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
11220 (setq dn (string-to-number (match-string 1 change))
11221 dw (cdr (assoc (match-string 2 change) a1)))
11222 (error "Invalid change specifyer: %s" change))
11223 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
11224 (cond
11225 ((eq dw 'day)
11226 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
11227 n2 (+ n1 dn)))
11228 ((eq dw 'year)
11229 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
11230 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
11231 (setq date1 (list m d y1)
11232 n1 (calendar-absolute-from-gregorian date1)
11233 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
11234 n2 (calendar-absolute-from-gregorian date2)))
11235 ((eq dw 'month)
11236 ;; approx number of month between the two dates
11237 (setq nmonths (floor (/ (- cday sday) 30.436875)))
11238 ;; How often does dn fit in there?
11239 (setq d (nth 1 start) m (car start) y (nth 2 start)
11240 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
11241 m (+ m nm)
11242 ny (floor (/ m 12))
11243 y (+ y ny)
11244 m (- m (* ny 12)))
11245 (while (> m 12) (setq m (- m 12) y (1+ y)))
11246 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
11247 (setq m2 (+ m dn) y2 y)
11248 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11249 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
11250 (while (<= n2 cday)
11251 (setq n1 n2 m m2 y y2)
11252 (setq m2 (+ m dn) y2 y)
11253 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11254 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
11255 (if show-all
11256 (cond
11257 ((eq prefer 'past) n1)
11258 ((eq prefer 'future) (if (= cday n1) n1 n2))
11259 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
11260 (cond
11261 ((eq prefer 'past) n1)
11262 ((eq prefer 'future) (if (= cday n1) n1 n2))
11263 (t (if (= cday n1) n1 n2)))))))
11265 (defun org-date-to-gregorian (date)
11266 "Turn any specification of DATE into a gregorian date for the calendar."
11267 (cond ((integerp date) (calendar-gregorian-from-absolute date))
11268 ((and (listp date) (= (length date) 3)) date)
11269 ((stringp date)
11270 (setq date (org-parse-time-string date))
11271 (list (nth 4 date) (nth 3 date) (nth 5 date)))
11272 ((listp date)
11273 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
11275 (defun org-parse-time-string (s &optional nodefault)
11276 "Parse the standard Org-mode time string.
11277 This should be a lot faster than the normal `parse-time-string'.
11278 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
11279 hour and minute fields will be nil if not given."
11280 (if (string-match org-ts-regexp0 s)
11281 (list 0
11282 (if (or (match-beginning 8) (not nodefault))
11283 (string-to-number (or (match-string 8 s) "0")))
11284 (if (or (match-beginning 7) (not nodefault))
11285 (string-to-number (or (match-string 7 s) "0")))
11286 (string-to-number (match-string 4 s))
11287 (string-to-number (match-string 3 s))
11288 (string-to-number (match-string 2 s))
11289 nil nil nil)
11290 (make-list 9 0)))
11292 (defun org-timestamp-up (&optional arg)
11293 "Increase the date item at the cursor by one.
11294 If the cursor is on the year, change the year. If it is on the month or
11295 the day, change that.
11296 With prefix ARG, change by that many units."
11297 (interactive "p")
11298 (org-timestamp-change (prefix-numeric-value arg)))
11300 (defun org-timestamp-down (&optional arg)
11301 "Decrease the date item at the cursor by one.
11302 If the cursor is on the year, change the year. If it is on the month or
11303 the day, change that.
11304 With prefix ARG, change by that many units."
11305 (interactive "p")
11306 (org-timestamp-change (- (prefix-numeric-value arg))))
11308 (defun org-timestamp-up-day (&optional arg)
11309 "Increase the date in the time stamp by one day.
11310 With prefix ARG, change that many days."
11311 (interactive "p")
11312 (if (and (not (org-at-timestamp-p t))
11313 (org-on-heading-p))
11314 (org-todo 'up)
11315 (org-timestamp-change (prefix-numeric-value arg) 'day)))
11317 (defun org-timestamp-down-day (&optional arg)
11318 "Decrease the date in the time stamp by one day.
11319 With prefix ARG, change that many days."
11320 (interactive "p")
11321 (if (and (not (org-at-timestamp-p t))
11322 (org-on-heading-p))
11323 (org-todo 'down)
11324 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
11326 (defun org-at-timestamp-p (&optional inactive-ok)
11327 "Determine if the cursor is in or at a timestamp."
11328 (interactive)
11329 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
11330 (pos (point))
11331 (ans (or (looking-at tsr)
11332 (save-excursion
11333 (skip-chars-backward "^[<\n\r\t")
11334 (if (> (point) (point-min)) (backward-char 1))
11335 (and (looking-at tsr)
11336 (> (- (match-end 0) pos) -1))))))
11337 (and ans
11338 (boundp 'org-ts-what)
11339 (setq org-ts-what
11340 (cond
11341 ((= pos (match-beginning 0)) 'bracket)
11342 ((= pos (1- (match-end 0))) 'bracket)
11343 ((org-pos-in-match-range pos 2) 'year)
11344 ((org-pos-in-match-range pos 3) 'month)
11345 ((org-pos-in-match-range pos 7) 'hour)
11346 ((org-pos-in-match-range pos 8) 'minute)
11347 ((or (org-pos-in-match-range pos 4)
11348 (org-pos-in-match-range pos 5)) 'day)
11349 ((and (> pos (or (match-end 8) (match-end 5)))
11350 (< pos (match-end 0)))
11351 (- pos (or (match-end 8) (match-end 5))))
11352 (t 'day))))
11353 ans))
11355 (defun org-toggle-timestamp-type ()
11356 "Toggle the type (<active> or [inactive]) of a time stamp."
11357 (interactive)
11358 (when (org-at-timestamp-p t)
11359 (let ((beg (match-beginning 0)) (end (match-end 0))
11360 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
11361 (save-excursion
11362 (goto-char beg)
11363 (while (re-search-forward "[][<>]" end t)
11364 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
11365 t t)))
11366 (message "Timestamp is now %sactive"
11367 (if (equal (char-after beg) ?<) "" "in")))))
11369 (defun org-timestamp-change (n &optional what)
11370 "Change the date in the time stamp at point.
11371 The date will be changed by N times WHAT. WHAT can be `day', `month',
11372 `year', `minute', `second'. If WHAT is not given, the cursor position
11373 in the timestamp determines what will be changed."
11374 (let ((pos (point))
11375 with-hm inactive
11376 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
11377 org-ts-what
11378 extra rem
11379 ts time time0)
11380 (if (not (org-at-timestamp-p t))
11381 (error "Not at a timestamp"))
11382 (if (and (not what) (eq org-ts-what 'bracket))
11383 (org-toggle-timestamp-type)
11384 (if (and (not what) (not (eq org-ts-what 'day))
11385 org-display-custom-times
11386 (get-text-property (point) 'display)
11387 (not (get-text-property (1- (point)) 'display)))
11388 (setq org-ts-what 'day))
11389 (setq org-ts-what (or what org-ts-what)
11390 inactive (= (char-after (match-beginning 0)) ?\[)
11391 ts (match-string 0))
11392 (replace-match "")
11393 (if (string-match
11394 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
11396 (setq extra (match-string 1 ts)))
11397 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
11398 (setq with-hm t))
11399 (setq time0 (org-parse-time-string ts))
11400 (when (and (eq org-ts-what 'minute)
11401 (eq current-prefix-arg nil))
11402 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
11403 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
11404 (setcar (cdr time0) (+ (nth 1 time0)
11405 (if (> n 0) (- rem) (- dm rem))))))
11406 (setq time
11407 (encode-time (or (car time0) 0)
11408 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
11409 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
11410 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
11411 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
11412 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
11413 (nthcdr 6 time0)))
11414 (when (integerp org-ts-what)
11415 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
11416 (if (eq what 'calendar)
11417 (let ((cal-date (org-get-date-from-calendar)))
11418 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
11419 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
11420 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
11421 (setcar time0 (or (car time0) 0))
11422 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
11423 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
11424 (setq time (apply 'encode-time time0))))
11425 (setq org-last-changed-timestamp
11426 (org-insert-time-stamp time with-hm inactive nil nil extra))
11427 (org-clock-update-time-maybe)
11428 (goto-char pos)
11429 ;; Try to recenter the calendar window, if any
11430 (if (and org-calendar-follow-timestamp-change
11431 (get-buffer-window "*Calendar*" t)
11432 (memq org-ts-what '(day month year)))
11433 (org-recenter-calendar (time-to-days time))))))
11435 (defun org-modify-ts-extra (s pos n dm)
11436 "Change the different parts of the lead-time and repeat fields in timestamp."
11437 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
11438 ng h m new rem)
11439 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
11440 (cond
11441 ((or (org-pos-in-match-range pos 2)
11442 (org-pos-in-match-range pos 3))
11443 (setq m (string-to-number (match-string 3 s))
11444 h (string-to-number (match-string 2 s)))
11445 (if (org-pos-in-match-range pos 2)
11446 (setq h (+ h n))
11447 (setq n (* dm (org-no-warnings (signum n))))
11448 (when (not (= 0 (setq rem (% m dm))))
11449 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
11450 (setq m (+ m n)))
11451 (if (< m 0) (setq m (+ m 60) h (1- h)))
11452 (if (> m 59) (setq m (- m 60) h (1+ h)))
11453 (setq h (min 24 (max 0 h)))
11454 (setq ng 1 new (format "-%02d:%02d" h m)))
11455 ((org-pos-in-match-range pos 6)
11456 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
11457 ((org-pos-in-match-range pos 5)
11458 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
11460 ((org-pos-in-match-range pos 9)
11461 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
11462 ((org-pos-in-match-range pos 8)
11463 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
11465 (when ng
11466 (setq s (concat
11467 (substring s 0 (match-beginning ng))
11469 (substring s (match-end ng))))))
11472 (defun org-recenter-calendar (date)
11473 "If the calendar is visible, recenter it to DATE."
11474 (let* ((win (selected-window))
11475 (cwin (get-buffer-window "*Calendar*" t))
11476 (calendar-move-hook nil))
11477 (when cwin
11478 (select-window cwin)
11479 (calendar-goto-date (if (listp date) date
11480 (calendar-gregorian-from-absolute date)))
11481 (select-window win))))
11483 (defun org-goto-calendar (&optional arg)
11484 "Go to the Emacs calendar at the current date.
11485 If there is a time stamp in the current line, go to that date.
11486 A prefix ARG can be used to force the current date."
11487 (interactive "P")
11488 (let ((tsr org-ts-regexp) diff
11489 (calendar-move-hook nil)
11490 (calendar-view-holidays-initially-flag nil)
11491 (view-calendar-holidays-initially nil)
11492 (calendar-view-diary-initially-flag nil)
11493 (view-diary-entries-initially nil))
11494 (if (or (org-at-timestamp-p)
11495 (save-excursion
11496 (beginning-of-line 1)
11497 (looking-at (concat ".*" tsr))))
11498 (let ((d1 (time-to-days (current-time)))
11499 (d2 (time-to-days
11500 (org-time-string-to-time (match-string 1)))))
11501 (setq diff (- d2 d1))))
11502 (calendar)
11503 (calendar-goto-today)
11504 (if (and diff (not arg)) (calendar-forward-day diff))))
11506 (defun org-get-date-from-calendar ()
11507 "Return a list (month day year) of date at point in calendar."
11508 (with-current-buffer "*Calendar*"
11509 (save-match-data
11510 (calendar-cursor-to-date))))
11512 (defun org-date-from-calendar ()
11513 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
11514 If there is already a time stamp at the cursor position, update it."
11515 (interactive)
11516 (if (org-at-timestamp-p t)
11517 (org-timestamp-change 0 'calendar)
11518 (let ((cal-date (org-get-date-from-calendar)))
11519 (org-insert-time-stamp
11520 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
11522 (defun org-minutes-to-hh:mm-string (m)
11523 "Compute H:MM from a number of minutes."
11524 (let ((h (/ m 60)))
11525 (setq m (- m (* 60 h)))
11526 (format org-time-clocksum-format h m)))
11528 (defun org-hh:mm-string-to-minutes (s)
11529 "Convert a string H:MM to a number of minutes."
11530 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
11531 (+ (* (string-to-number (match-string 1 s)) 60)
11532 (string-to-number (match-string 2 s)))
11535 ;;;; Agenda files
11537 ;;;###autoload
11538 (defun org-iswitchb (&optional arg)
11539 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
11540 With a prefix argument, restrict available to files.
11541 With two prefix arguments, restrict available buffers to agenda files.
11543 Due to some yet unresolved reason, the global function
11544 `iswitchb-mode' needs to be active for this function to work."
11545 (interactive "P")
11546 (require 'iswitchb)
11547 (let ((enabled iswitchb-mode) blist)
11548 (or enabled (iswitchb-mode 1))
11549 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
11550 ((equal arg '(16)) (org-buffer-list 'agenda))
11551 (t (org-buffer-list))))
11552 (unwind-protect
11553 (let ((iswitchb-make-buflist-hook
11554 (lambda ()
11555 (setq iswitchb-temp-buflist
11556 (mapcar 'buffer-name blist)))))
11557 (switch-to-buffer
11558 (iswitchb-read-buffer
11559 "Switch-to: " nil t))
11560 (or enabled (iswitchb-mode -1))))))
11562 (defun org-buffer-list (&optional predicate exclude-tmp)
11563 "Return a list of Org buffers.
11564 PREDICATE can be `export', `files' or `agenda'.
11566 export restrict the list to Export buffers.
11567 files restrict the list to buffers visiting Org files.
11568 agenda restrict the list to buffers visiting agenda files.
11570 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
11571 (let* ((bfn nil)
11572 (agenda-files (and (eq predicate 'agenda)
11573 (mapcar 'file-truename (org-agenda-files t))))
11574 (filter
11575 (cond
11576 ((eq predicate 'files)
11577 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
11578 ((eq predicate 'export)
11579 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
11580 ((eq predicate 'agenda)
11581 (lambda (b)
11582 (with-current-buffer b
11583 (and (eq major-mode 'org-mode)
11584 (setq bfn (buffer-file-name b))
11585 (member (file-truename bfn) agenda-files)))))
11586 (t (lambda (b) (with-current-buffer b
11587 (or (eq major-mode 'org-mode)
11588 (string-match "\*Org .*Export"
11589 (buffer-name b)))))))))
11590 (delq nil
11591 (mapcar
11592 (lambda(b)
11593 (if (and (funcall filter b)
11594 (or (not exclude-tmp)
11595 (not (string-match "tmp" (buffer-name b)))))
11597 nil))
11598 (buffer-list)))))
11600 (defun org-agenda-files (&optional unrestricted archives)
11601 "Get the list of agenda files.
11602 Optional UNRESTRICTED means return the full list even if a restriction
11603 is currently in place.
11604 When ARCHIVES is t, include all archive files hat are really being
11605 used by the agenda files. If ARCHIVE is `ifmode', do this only if
11606 `org-agenda-archives-mode' is t."
11607 (let ((files
11608 (cond
11609 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
11610 ((stringp org-agenda-files) (org-read-agenda-file-list))
11611 ((listp org-agenda-files) org-agenda-files)
11612 (t (error "Invalid value of `org-agenda-files'")))))
11613 (setq files (apply 'append
11614 (mapcar (lambda (f)
11615 (if (file-directory-p f)
11616 (directory-files
11617 f t org-agenda-file-regexp)
11618 (list f)))
11619 files)))
11620 (when org-agenda-skip-unavailable-files
11621 (setq files (delq nil
11622 (mapcar (function
11623 (lambda (file)
11624 (and (file-readable-p file) file)))
11625 files))))
11626 (when (or (eq archives t)
11627 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
11628 (setq files (org-add-archive-files files)))
11629 files))
11631 (defun org-edit-agenda-file-list ()
11632 "Edit the list of agenda files.
11633 Depending on setup, this either uses customize to edit the variable
11634 `org-agenda-files', or it visits the file that is holding the list. In the
11635 latter case, the buffer is set up in a way that saving it automatically kills
11636 the buffer and restores the previous window configuration."
11637 (interactive)
11638 (if (stringp org-agenda-files)
11639 (let ((cw (current-window-configuration)))
11640 (find-file org-agenda-files)
11641 (org-set-local 'org-window-configuration cw)
11642 (org-add-hook 'after-save-hook
11643 (lambda ()
11644 (set-window-configuration
11645 (prog1 org-window-configuration
11646 (kill-buffer (current-buffer))))
11647 (org-install-agenda-files-menu)
11648 (message "New agenda file list installed"))
11649 nil 'local)
11650 (message "%s" (substitute-command-keys
11651 "Edit list and finish with \\[save-buffer]")))
11652 (customize-variable 'org-agenda-files)))
11654 (defun org-store-new-agenda-file-list (list)
11655 "Set new value for the agenda file list and save it correcly."
11656 (if (stringp org-agenda-files)
11657 (let ((f org-agenda-files) b)
11658 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
11659 (with-temp-file f
11660 (insert (mapconcat 'identity list "\n") "\n")))
11661 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
11662 (setq org-agenda-files list)
11663 (customize-save-variable 'org-agenda-files org-agenda-files))))
11665 (defun org-read-agenda-file-list ()
11666 "Read the list of agenda files from a file."
11667 (when (file-directory-p org-agenda-files)
11668 (error "`org-agenda-files' cannot be a single directory"))
11669 (when (stringp org-agenda-files)
11670 (with-temp-buffer
11671 (insert-file-contents org-agenda-files)
11672 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
11675 ;;;###autoload
11676 (defun org-cycle-agenda-files ()
11677 "Cycle through the files in `org-agenda-files'.
11678 If the current buffer visits an agenda file, find the next one in the list.
11679 If the current buffer does not, find the first agenda file."
11680 (interactive)
11681 (let* ((fs (org-agenda-files t))
11682 (files (append fs (list (car fs))))
11683 (tcf (if buffer-file-name (file-truename buffer-file-name)))
11684 file)
11685 (unless files (error "No agenda files"))
11686 (catch 'exit
11687 (while (setq file (pop files))
11688 (if (equal (file-truename file) tcf)
11689 (when (car files)
11690 (find-file (car files))
11691 (throw 'exit t))))
11692 (find-file (car fs)))
11693 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
11695 (defun org-agenda-file-to-front (&optional to-end)
11696 "Move/add the current file to the top of the agenda file list.
11697 If the file is not present in the list, it is added to the front. If it is
11698 present, it is moved there. With optional argument TO-END, add/move to the
11699 end of the list."
11700 (interactive "P")
11701 (let ((org-agenda-skip-unavailable-files nil)
11702 (file-alist (mapcar (lambda (x)
11703 (cons (file-truename x) x))
11704 (org-agenda-files t)))
11705 (ctf (file-truename buffer-file-name))
11706 x had)
11707 (setq x (assoc ctf file-alist) had x)
11709 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
11710 (if to-end
11711 (setq file-alist (append (delq x file-alist) (list x)))
11712 (setq file-alist (cons x (delq x file-alist))))
11713 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
11714 (org-install-agenda-files-menu)
11715 (message "File %s to %s of agenda file list"
11716 (if had "moved" "added") (if to-end "end" "front"))))
11718 (defun org-remove-file (&optional file)
11719 "Remove current file from the list of files in variable `org-agenda-files'.
11720 These are the files which are being checked for agenda entries.
11721 Optional argument FILE means, use this file instead of the current."
11722 (interactive)
11723 (let* ((org-agenda-skip-unavailable-files nil)
11724 (file (or file buffer-file-name))
11725 (true-file (file-truename file))
11726 (afile (abbreviate-file-name file))
11727 (files (delq nil (mapcar
11728 (lambda (x)
11729 (if (equal true-file
11730 (file-truename x))
11731 nil x))
11732 (org-agenda-files t)))))
11733 (if (not (= (length files) (length (org-agenda-files t))))
11734 (progn
11735 (org-store-new-agenda-file-list files)
11736 (org-install-agenda-files-menu)
11737 (message "Removed file: %s" afile))
11738 (message "File was not in list: %s (not removed)" afile))))
11740 (defun org-file-menu-entry (file)
11741 (vector file (list 'find-file file) t))
11743 (defun org-check-agenda-file (file)
11744 "Make sure FILE exists. If not, ask user what to do."
11745 (when (not (file-exists-p file))
11746 (message "non-existent file %s. [R]emove from list or [A]bort?"
11747 (abbreviate-file-name file))
11748 (let ((r (downcase (read-char-exclusive))))
11749 (cond
11750 ((equal r ?r)
11751 (org-remove-file file)
11752 (throw 'nextfile t))
11753 (t (error "Abort"))))))
11755 (defun org-get-agenda-file-buffer (file)
11756 "Get a buffer visiting FILE. If the buffer needs to be created, add
11757 it to the list of buffers which might be released later."
11758 (let ((buf (org-find-base-buffer-visiting file)))
11759 (if buf
11760 buf ; just return it
11761 ;; Make a new buffer and remember it
11762 (setq buf (find-file-noselect file))
11763 (if buf (push buf org-agenda-new-buffers))
11764 buf)))
11766 (defun org-release-buffers (blist)
11767 "Release all buffers in list, asking the user for confirmation when needed.
11768 When a buffer is unmodified, it is just killed. When modified, it is saved
11769 \(if the user agrees) and then killed."
11770 (let (buf file)
11771 (while (setq buf (pop blist))
11772 (setq file (buffer-file-name buf))
11773 (when (and (buffer-modified-p buf)
11774 file
11775 (y-or-n-p (format "Save file %s? " file)))
11776 (with-current-buffer buf (save-buffer)))
11777 (kill-buffer buf))))
11779 (defun org-prepare-agenda-buffers (files)
11780 "Create buffers for all agenda files, protect archived trees and comments."
11781 (interactive)
11782 (let ((pa '(:org-archived t))
11783 (pc '(:org-comment t))
11784 (pall '(:org-archived t :org-comment t))
11785 (inhibit-read-only t)
11786 (rea (concat ":" org-archive-tag ":"))
11787 bmp file re)
11788 (save-excursion
11789 (save-restriction
11790 (while (setq file (pop files))
11791 (if (bufferp file)
11792 (set-buffer file)
11793 (org-check-agenda-file file)
11794 (set-buffer (org-get-agenda-file-buffer file)))
11795 (widen)
11796 (setq bmp (buffer-modified-p))
11797 (org-refresh-category-properties)
11798 (setq org-todo-keywords-for-agenda
11799 (append org-todo-keywords-for-agenda org-todo-keywords-1))
11800 (setq org-done-keywords-for-agenda
11801 (append org-done-keywords-for-agenda org-done-keywords))
11802 (setq org-todo-keyword-alist-for-agenda
11803 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
11804 (setq org-tag-alist-for-agenda
11805 (append org-tag-alist-for-agenda org-tag-alist))
11807 (save-excursion
11808 (remove-text-properties (point-min) (point-max) pall)
11809 (when org-agenda-skip-archived-trees
11810 (goto-char (point-min))
11811 (while (re-search-forward rea nil t)
11812 (if (org-on-heading-p t)
11813 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
11814 (goto-char (point-min))
11815 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
11816 (while (re-search-forward re nil t)
11817 (add-text-properties
11818 (match-beginning 0) (org-end-of-subtree t) pc)))
11819 (set-buffer-modified-p bmp))))
11820 (setq org-todo-keyword-alist-for-agenda
11821 (org-uniquify org-todo-keyword-alist-for-agenda)
11822 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
11824 ;;;; Embedded LaTeX
11826 (defvar org-cdlatex-mode-map (make-sparse-keymap)
11827 "Keymap for the minor `org-cdlatex-mode'.")
11829 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
11830 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
11831 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
11832 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
11833 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
11835 (defvar org-cdlatex-texmathp-advice-is-done nil
11836 "Flag remembering if we have applied the advice to texmathp already.")
11838 (define-minor-mode org-cdlatex-mode
11839 "Toggle the minor `org-cdlatex-mode'.
11840 This mode supports entering LaTeX environment and math in LaTeX fragments
11841 in Org-mode.
11842 \\{org-cdlatex-mode-map}"
11843 nil " OCDL" nil
11844 (when org-cdlatex-mode (require 'cdlatex))
11845 (unless org-cdlatex-texmathp-advice-is-done
11846 (setq org-cdlatex-texmathp-advice-is-done t)
11847 (defadvice texmathp (around org-math-always-on activate)
11848 "Always return t in org-mode buffers.
11849 This is because we want to insert math symbols without dollars even outside
11850 the LaTeX math segments. If Orgmode thinks that point is actually inside
11851 en embedded LaTeX fragement, let texmathp do its job.
11852 \\[org-cdlatex-mode-map]"
11853 (interactive)
11854 (let (p)
11855 (cond
11856 ((not (org-mode-p)) ad-do-it)
11857 ((eq this-command 'cdlatex-math-symbol)
11858 (setq ad-return-value t
11859 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
11861 (let ((p (org-inside-LaTeX-fragment-p)))
11862 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
11863 (setq ad-return-value t
11864 texmathp-why '("Org-mode embedded math" . 0))
11865 (if p ad-do-it)))))))))
11867 (defun turn-on-org-cdlatex ()
11868 "Unconditionally turn on `org-cdlatex-mode'."
11869 (org-cdlatex-mode 1))
11871 (defun org-inside-LaTeX-fragment-p ()
11872 "Test if point is inside a LaTeX fragment.
11873 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
11874 sequence appearing also before point.
11875 Even though the matchers for math are configurable, this function assumes
11876 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
11877 delimiters are skipped when they have been removed by customization.
11878 The return value is nil, or a cons cell with the delimiter and
11879 and the position of this delimiter.
11881 This function does a reasonably good job, but can locally be fooled by
11882 for example currency specifications. For example it will assume being in
11883 inline math after \"$22.34\". The LaTeX fragment formatter will only format
11884 fragments that are properly closed, but during editing, we have to live
11885 with the uncertainty caused by missing closing delimiters. This function
11886 looks only before point, not after."
11887 (catch 'exit
11888 (let ((pos (point))
11889 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
11890 (lim (progn
11891 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
11892 (point)))
11893 dd-on str (start 0) m re)
11894 (goto-char pos)
11895 (when dodollar
11896 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
11897 re (nth 1 (assoc "$" org-latex-regexps)))
11898 (while (string-match re str start)
11899 (cond
11900 ((= (match-end 0) (length str))
11901 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
11902 ((= (match-end 0) (- (length str) 5))
11903 (throw 'exit nil))
11904 (t (setq start (match-end 0))))))
11905 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
11906 (goto-char pos)
11907 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
11908 (and (match-beginning 2) (throw 'exit nil))
11909 ;; count $$
11910 (while (re-search-backward "\\$\\$" lim t)
11911 (setq dd-on (not dd-on)))
11912 (goto-char pos)
11913 (if dd-on (cons "$$" m))))))
11916 (defun org-try-cdlatex-tab ()
11917 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
11918 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
11919 - inside a LaTeX fragment, or
11920 - after the first word in a line, where an abbreviation expansion could
11921 insert a LaTeX environment."
11922 (when org-cdlatex-mode
11923 (cond
11924 ((save-excursion
11925 (skip-chars-backward "a-zA-Z0-9*")
11926 (skip-chars-backward " \t")
11927 (bolp))
11928 (cdlatex-tab) t)
11929 ((org-inside-LaTeX-fragment-p)
11930 (cdlatex-tab) t)
11931 (t nil))))
11933 (defun org-cdlatex-underscore-caret (&optional arg)
11934 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
11935 Revert to the normal definition outside of these fragments."
11936 (interactive "P")
11937 (if (org-inside-LaTeX-fragment-p)
11938 (call-interactively 'cdlatex-sub-superscript)
11939 (let (org-cdlatex-mode)
11940 (call-interactively (key-binding (vector last-input-event))))))
11942 (defun org-cdlatex-math-modify (&optional arg)
11943 "Execute `cdlatex-math-modify' in LaTeX fragments.
11944 Revert to the normal definition outside of these fragments."
11945 (interactive "P")
11946 (if (org-inside-LaTeX-fragment-p)
11947 (call-interactively 'cdlatex-math-modify)
11948 (let (org-cdlatex-mode)
11949 (call-interactively (key-binding (vector last-input-event))))))
11951 (defvar org-latex-fragment-image-overlays nil
11952 "List of overlays carrying the images of latex fragments.")
11953 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
11955 (defun org-remove-latex-fragment-image-overlays ()
11956 "Remove all overlays with LaTeX fragment images in current buffer."
11957 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
11958 (setq org-latex-fragment-image-overlays nil))
11960 (defun org-preview-latex-fragment (&optional subtree)
11961 "Preview the LaTeX fragment at point, or all locally or globally.
11962 If the cursor is in a LaTeX fragment, create the image and overlay
11963 it over the source code. If there is no fragment at point, display
11964 all fragments in the current text, from one headline to the next. With
11965 prefix SUBTREE, display all fragments in the current subtree. With a
11966 double prefix `C-u C-u', or when the cursor is before the first headline,
11967 display all fragments in the buffer.
11968 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
11969 (interactive "P")
11970 (org-remove-latex-fragment-image-overlays)
11971 (save-excursion
11972 (save-restriction
11973 (let (beg end at msg)
11974 (cond
11975 ((or (equal subtree '(16))
11976 (not (save-excursion
11977 (re-search-backward (concat "^" outline-regexp) nil t))))
11978 (setq beg (point-min) end (point-max)
11979 msg "Creating images for buffer...%s"))
11980 ((equal subtree '(4))
11981 (org-back-to-heading)
11982 (setq beg (point) end (org-end-of-subtree t)
11983 msg "Creating images for subtree...%s"))
11985 (if (setq at (org-inside-LaTeX-fragment-p))
11986 (goto-char (max (point-min) (- (cdr at) 2)))
11987 (org-back-to-heading))
11988 (setq beg (point) end (progn (outline-next-heading) (point))
11989 msg (if at "Creating image...%s"
11990 "Creating images for entry...%s"))))
11991 (message msg "")
11992 (narrow-to-region beg end)
11993 (goto-char beg)
11994 (org-format-latex
11995 (concat "ltxpng/" (file-name-sans-extension
11996 (file-name-nondirectory
11997 buffer-file-name)))
11998 default-directory 'overlays msg at 'forbuffer)
11999 (message msg "done. Use `C-c C-c' to remove images.")))))
12001 (defvar org-latex-regexps
12002 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
12003 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
12004 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
12005 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
12006 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
12007 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
12008 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
12009 "Regular expressions for matching embedded LaTeX.")
12011 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
12012 "Replace LaTeX fragments with links to an image, and produce images."
12013 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
12014 (let* ((prefixnodir (file-name-nondirectory prefix))
12015 (absprefix (expand-file-name prefix dir))
12016 (todir (file-name-directory absprefix))
12017 (opt org-format-latex-options)
12018 (matchers (plist-get opt :matchers))
12019 (re-list org-latex-regexps)
12020 (cnt 0) txt link beg end re e checkdir
12021 m n block linkfile movefile ov)
12022 ;; Check if there are old images files with this prefix, and remove them
12023 (when (file-directory-p todir)
12024 (mapc 'delete-file
12025 (directory-files
12026 todir 'full
12027 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
12028 ;; Check the different regular expressions
12029 (while (setq e (pop re-list))
12030 (setq m (car e) re (nth 1 e) n (nth 2 e)
12031 block (if (nth 3 e) "\n\n" ""))
12032 (when (member m matchers)
12033 (goto-char (point-min))
12034 (while (re-search-forward re nil t)
12035 (when (or (not at) (equal (cdr at) (match-beginning n)))
12036 (setq txt (match-string n)
12037 beg (match-beginning n) end (match-end n)
12038 cnt (1+ cnt)
12039 linkfile (format "%s_%04d.png" prefix cnt)
12040 movefile (format "%s_%04d.png" absprefix cnt)
12041 link (concat block "[[file:" linkfile "]]" block))
12042 (if msg (message msg cnt))
12043 (goto-char beg)
12044 (unless checkdir ; make sure the directory exists
12045 (setq checkdir t)
12046 (or (file-directory-p todir) (make-directory todir)))
12047 (org-create-formula-image
12048 txt movefile opt forbuffer)
12049 (if overlays
12050 (progn
12051 (setq ov (org-make-overlay beg end))
12052 (if (featurep 'xemacs)
12053 (progn
12054 (org-overlay-put ov 'invisible t)
12055 (org-overlay-put
12056 ov 'end-glyph
12057 (make-glyph (vector 'png :file movefile))))
12058 (org-overlay-put
12059 ov 'display
12060 (list 'image :type 'png :file movefile :ascent 'center)))
12061 (push ov org-latex-fragment-image-overlays)
12062 (goto-char end))
12063 (delete-region beg end)
12064 (insert link))))))))
12066 ;; This function borrows from Ganesh Swami's latex2png.el
12067 (defun org-create-formula-image (string tofile options buffer)
12068 (let* ((tmpdir (if (featurep 'xemacs)
12069 (temp-directory)
12070 temporary-file-directory))
12071 (texfilebase (make-temp-name
12072 (expand-file-name "orgtex" tmpdir)))
12073 (texfile (concat texfilebase ".tex"))
12074 (dvifile (concat texfilebase ".dvi"))
12075 (pngfile (concat texfilebase ".png"))
12076 (fnh (if (featurep 'xemacs)
12077 (font-height (get-face-font 'default))
12078 (face-attribute 'default :height nil)))
12079 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
12080 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
12081 (fg (or (plist-get options (if buffer :foreground :html-foreground))
12082 "Black"))
12083 (bg (or (plist-get options (if buffer :background :html-background))
12084 "Transparent")))
12085 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
12086 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
12087 (with-temp-file texfile
12088 (insert org-format-latex-header
12089 "\n\\begin{document}\n" string "\n\\end{document}\n"))
12090 (let ((dir default-directory))
12091 (condition-case nil
12092 (progn
12093 (cd tmpdir)
12094 (call-process "latex" nil nil nil texfile))
12095 (error nil))
12096 (cd dir))
12097 (if (not (file-exists-p dvifile))
12098 (progn (message "Failed to create dvi file from %s" texfile) nil)
12099 (condition-case nil
12100 (call-process "dvipng" nil nil nil
12101 "-E" "-fg" fg "-bg" bg
12102 "-D" dpi
12103 ;;"-x" scale "-y" scale
12104 "-T" "tight"
12105 "-o" pngfile
12106 dvifile)
12107 (error nil))
12108 (if (not (file-exists-p pngfile))
12109 (progn (message "Failed to create png file from %s" texfile) nil)
12110 ;; Use the requested file name and clean up
12111 (copy-file pngfile tofile 'replace)
12112 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
12113 (delete-file (concat texfilebase e)))
12114 pngfile))))
12116 (defun org-dvipng-color (attr)
12117 "Return an rgb color specification for dvipng."
12118 (apply 'format "rgb %s %s %s"
12119 (mapcar 'org-normalize-color
12120 (color-values (face-attribute 'default attr nil)))))
12122 (defun org-normalize-color (value)
12123 "Return string to be used as color value for an RGB component."
12124 (format "%g" (/ value 65535.0)))
12127 ;;;; Key bindings
12129 ;; Make `C-c C-x' a prefix key
12130 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
12132 ;; TAB key with modifiers
12133 (org-defkey org-mode-map "\C-i" 'org-cycle)
12134 (org-defkey org-mode-map [(tab)] 'org-cycle)
12135 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
12136 (org-defkey org-mode-map [(meta tab)] 'org-complete)
12137 (org-defkey org-mode-map "\M-\t" 'org-complete)
12138 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
12139 ;; The following line is necessary under Suse GNU/Linux
12140 (unless (featurep 'xemacs)
12141 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
12142 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
12143 (define-key org-mode-map [backtab] 'org-shifttab)
12145 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
12146 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
12147 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
12149 ;; Cursor keys with modifiers
12150 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
12151 (org-defkey org-mode-map [(meta right)] 'org-metaright)
12152 (org-defkey org-mode-map [(meta up)] 'org-metaup)
12153 (org-defkey org-mode-map [(meta down)] 'org-metadown)
12155 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
12156 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
12157 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
12158 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
12160 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
12161 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
12162 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
12163 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
12165 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
12166 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
12168 ;;; Extra keys for tty access.
12169 ;; We only set them when really needed because otherwise the
12170 ;; menus don't show the simple keys
12172 (when (or org-use-extra-keys
12173 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
12174 (not window-system))
12175 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
12176 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
12177 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
12178 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
12179 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
12180 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
12181 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
12182 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
12183 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
12184 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
12185 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
12186 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
12187 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
12188 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
12189 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
12190 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
12191 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
12192 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
12193 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
12194 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
12195 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
12196 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
12198 ;; All the other keys
12200 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
12201 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
12202 (if (boundp 'narrow-map)
12203 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
12204 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
12205 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
12206 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
12207 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
12208 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
12209 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
12210 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
12211 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
12212 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
12213 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
12214 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
12215 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
12216 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
12217 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
12218 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
12219 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
12220 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
12221 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
12222 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
12223 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
12224 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
12225 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
12226 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
12227 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
12228 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
12229 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
12230 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
12231 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
12232 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
12233 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
12234 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
12235 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
12236 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
12237 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
12238 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
12239 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
12240 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
12241 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
12242 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
12243 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
12244 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
12245 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
12246 (org-defkey org-mode-map "\C-c^" 'org-sort)
12247 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
12248 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
12249 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
12250 (org-defkey org-mode-map "\C-m" 'org-return)
12251 (org-defkey org-mode-map "\C-j" 'org-return-indent)
12252 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
12253 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
12254 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
12255 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
12256 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
12257 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
12258 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
12259 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
12260 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
12261 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
12262 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
12263 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
12264 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
12265 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
12266 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
12268 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
12269 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
12270 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
12271 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
12273 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
12274 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
12275 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
12276 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
12277 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
12278 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
12279 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
12280 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
12281 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
12282 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
12283 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
12284 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
12286 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
12288 (when (featurep 'xemacs)
12289 (org-defkey org-mode-map 'button3 'popup-mode-menu))
12291 (defvar org-table-auto-blank-field) ; defined in org-table.el
12292 (defun org-self-insert-command (N)
12293 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
12294 If the cursor is in a table looking at whitespace, the whitespace is
12295 overwritten, and the table is not marked as requiring realignment."
12296 (interactive "p")
12297 (if (and (org-table-p)
12298 (progn
12299 ;; check if we blank the field, and if that triggers align
12300 (and (featurep 'org-table) org-table-auto-blank-field
12301 (member last-command
12302 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
12303 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
12304 ;; got extra space, this field does not determine column width
12305 (let (org-table-may-need-update) (org-table-blank-field))
12306 ;; no extra space, this field may determine column width
12307 (org-table-blank-field)))
12309 (eq N 1)
12310 (looking-at "[^|\n]* |"))
12311 (let (org-table-may-need-update)
12312 (goto-char (1- (match-end 0)))
12313 (delete-backward-char 1)
12314 (goto-char (match-beginning 0))
12315 (self-insert-command N))
12316 (setq org-table-may-need-update t)
12317 (self-insert-command N)
12318 (org-fix-tags-on-the-fly)))
12320 (defun org-fix-tags-on-the-fly ()
12321 (when (and (equal (char-after (point-at-bol)) ?*)
12322 (org-on-heading-p))
12323 (org-align-tags-here org-tags-column)))
12325 (defun org-delete-backward-char (N)
12326 "Like `delete-backward-char', insert whitespace at field end in tables.
12327 When deleting backwards, in tables this function will insert whitespace in
12328 front of the next \"|\" separator, to keep the table aligned. The table will
12329 still be marked for re-alignment if the field did fill the entire column,
12330 because, in this case the deletion might narrow the column."
12331 (interactive "p")
12332 (if (and (org-table-p)
12333 (eq N 1)
12334 (string-match "|" (buffer-substring (point-at-bol) (point)))
12335 (looking-at ".*?|"))
12336 (let ((pos (point))
12337 (noalign (looking-at "[^|\n\r]* |"))
12338 (c org-table-may-need-update))
12339 (backward-delete-char N)
12340 (skip-chars-forward "^|")
12341 (insert " ")
12342 (goto-char (1- pos))
12343 ;; noalign: if there were two spaces at the end, this field
12344 ;; does not determine the width of the column.
12345 (if noalign (setq org-table-may-need-update c)))
12346 (backward-delete-char N)
12347 (org-fix-tags-on-the-fly)))
12349 (defun org-delete-char (N)
12350 "Like `delete-char', but insert whitespace at field end in tables.
12351 When deleting characters, in tables this function will insert whitespace in
12352 front of the next \"|\" separator, to keep the table aligned. The table will
12353 still be marked for re-alignment if the field did fill the entire column,
12354 because, in this case the deletion might narrow the column."
12355 (interactive "p")
12356 (if (and (org-table-p)
12357 (not (bolp))
12358 (not (= (char-after) ?|))
12359 (eq N 1))
12360 (if (looking-at ".*?|")
12361 (let ((pos (point))
12362 (noalign (looking-at "[^|\n\r]* |"))
12363 (c org-table-may-need-update))
12364 (replace-match (concat
12365 (substring (match-string 0) 1 -1)
12366 " |"))
12367 (goto-char pos)
12368 ;; noalign: if there were two spaces at the end, this field
12369 ;; does not determine the width of the column.
12370 (if noalign (setq org-table-may-need-update c)))
12371 (delete-char N))
12372 (delete-char N)
12373 (org-fix-tags-on-the-fly)))
12375 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
12376 (put 'org-self-insert-command 'delete-selection t)
12377 (put 'orgtbl-self-insert-command 'delete-selection t)
12378 (put 'org-delete-char 'delete-selection 'supersede)
12379 (put 'org-delete-backward-char 'delete-selection 'supersede)
12381 ;; Make `flyspell-mode' delay after some commands
12382 (put 'org-self-insert-command 'flyspell-delayed t)
12383 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
12384 (put 'org-delete-char 'flyspell-delayed t)
12385 (put 'org-delete-backward-char 'flyspell-delayed t)
12387 ;; Make pabbrev-mode expand after org-mode commands
12388 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
12389 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
12391 ;; How to do this: Measure non-white length of current string
12392 ;; If equal to column width, we should realign.
12394 (defun org-remap (map &rest commands)
12395 "In MAP, remap the functions given in COMMANDS.
12396 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
12397 (let (new old)
12398 (while commands
12399 (setq old (pop commands) new (pop commands))
12400 (if (fboundp 'command-remapping)
12401 (org-defkey map (vector 'remap old) new)
12402 (substitute-key-definition old new map global-map)))))
12404 (when (eq org-enable-table-editor 'optimized)
12405 ;; If the user wants maximum table support, we need to hijack
12406 ;; some standard editing functions
12407 (org-remap org-mode-map
12408 'self-insert-command 'org-self-insert-command
12409 'delete-char 'org-delete-char
12410 'delete-backward-char 'org-delete-backward-char)
12411 (org-defkey org-mode-map "|" 'org-force-self-insert))
12413 (defun org-shiftcursor-error ()
12414 "Throw an error because Shift-Cursor command was applied in wrong context."
12415 (error "This command is active in special context like tables, headlines or timestamps"))
12417 (defun org-shifttab (&optional arg)
12418 "Global visibility cycling or move to previous table field.
12419 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
12420 on context.
12421 See the individual commands for more information."
12422 (interactive "P")
12423 (cond
12424 ((org-at-table-p) (call-interactively 'org-table-previous-field))
12425 ((integerp arg)
12426 (message "Content view to level: %d" arg)
12427 (org-content (prefix-numeric-value arg))
12428 (setq org-cycle-global-status 'overview))
12429 (t (call-interactively 'org-global-cycle))))
12431 (defun org-shiftmetaleft ()
12432 "Promote subtree or delete table column.
12433 Calls `org-promote-subtree', `org-outdent-item',
12434 or `org-table-delete-column', depending on context.
12435 See the individual commands for more information."
12436 (interactive)
12437 (cond
12438 ((org-at-table-p) (call-interactively 'org-table-delete-column))
12439 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
12440 ((org-at-item-p) (call-interactively 'org-outdent-item))
12441 (t (org-shiftcursor-error))))
12443 (defun org-shiftmetaright ()
12444 "Demote subtree or insert table column.
12445 Calls `org-demote-subtree', `org-indent-item',
12446 or `org-table-insert-column', depending on context.
12447 See the individual commands for more information."
12448 (interactive)
12449 (cond
12450 ((org-at-table-p) (call-interactively 'org-table-insert-column))
12451 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
12452 ((org-at-item-p) (call-interactively 'org-indent-item))
12453 (t (org-shiftcursor-error))))
12455 (defun org-shiftmetaup (&optional arg)
12456 "Move subtree up or kill table row.
12457 Calls `org-move-subtree-up' or `org-table-kill-row' or
12458 `org-move-item-up' depending on context. See the individual commands
12459 for more information."
12460 (interactive "P")
12461 (cond
12462 ((org-at-table-p) (call-interactively 'org-table-kill-row))
12463 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12464 ((org-at-item-p) (call-interactively 'org-move-item-up))
12465 (t (org-shiftcursor-error))))
12466 (defun org-shiftmetadown (&optional arg)
12467 "Move subtree down or insert table row.
12468 Calls `org-move-subtree-down' or `org-table-insert-row' or
12469 `org-move-item-down', depending on context. See the individual
12470 commands for more information."
12471 (interactive "P")
12472 (cond
12473 ((org-at-table-p) (call-interactively 'org-table-insert-row))
12474 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12475 ((org-at-item-p) (call-interactively 'org-move-item-down))
12476 (t (org-shiftcursor-error))))
12478 (defun org-metaleft (&optional arg)
12479 "Promote heading or move table column to left.
12480 Calls `org-do-promote' or `org-table-move-column', depending on context.
12481 With no specific context, calls the Emacs default `backward-word'.
12482 See the individual commands for more information."
12483 (interactive "P")
12484 (cond
12485 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
12486 ((or (org-on-heading-p) (org-region-active-p))
12487 (call-interactively 'org-do-promote))
12488 ((org-at-item-p) (call-interactively 'org-outdent-item))
12489 (t (call-interactively 'backward-word))))
12491 (defun org-metaright (&optional arg)
12492 "Demote subtree or move table column to right.
12493 Calls `org-do-demote' or `org-table-move-column', depending on context.
12494 With no specific context, calls the Emacs default `forward-word'.
12495 See the individual commands for more information."
12496 (interactive "P")
12497 (cond
12498 ((org-at-table-p) (call-interactively 'org-table-move-column))
12499 ((or (org-on-heading-p) (org-region-active-p))
12500 (call-interactively 'org-do-demote))
12501 ((org-at-item-p) (call-interactively 'org-indent-item))
12502 (t (call-interactively 'forward-word))))
12504 (defun org-metaup (&optional arg)
12505 "Move subtree up or move table row up.
12506 Calls `org-move-subtree-up' or `org-table-move-row' or
12507 `org-move-item-up', depending on context. See the individual commands
12508 for more information."
12509 (interactive "P")
12510 (cond
12511 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
12512 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12513 ((org-at-item-p) (call-interactively 'org-move-item-up))
12514 (t (transpose-lines 1) (beginning-of-line -1))))
12516 (defun org-metadown (&optional arg)
12517 "Move subtree down or move table row down.
12518 Calls `org-move-subtree-down' or `org-table-move-row' or
12519 `org-move-item-down', depending on context. See the individual
12520 commands for more information."
12521 (interactive "P")
12522 (cond
12523 ((org-at-table-p) (call-interactively 'org-table-move-row))
12524 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12525 ((org-at-item-p) (call-interactively 'org-move-item-down))
12526 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
12528 (defun org-shiftup (&optional arg)
12529 "Increase item in timestamp or increase priority of current headline.
12530 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
12531 depending on context. See the individual commands for more information."
12532 (interactive "P")
12533 (cond
12534 ((org-at-timestamp-p t)
12535 (call-interactively (if org-edit-timestamp-down-means-later
12536 'org-timestamp-down 'org-timestamp-up)))
12537 ((org-on-heading-p) (call-interactively 'org-priority-up))
12538 ((org-at-item-p) (call-interactively 'org-previous-item))
12539 ((org-clocktable-try-shift 'up arg))
12540 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
12542 (defun org-shiftdown (&optional arg)
12543 "Decrease item in timestamp or decrease priority of current headline.
12544 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
12545 depending on context. See the individual commands for more information."
12546 (interactive "P")
12547 (cond
12548 ((org-at-timestamp-p t)
12549 (call-interactively (if org-edit-timestamp-down-means-later
12550 'org-timestamp-up 'org-timestamp-down)))
12551 ((org-on-heading-p) (call-interactively 'org-priority-down))
12552 ((org-clocktable-try-shift 'down arg))
12553 (t (call-interactively 'org-next-item))))
12555 (defun org-shiftright (&optional arg)
12556 "Next TODO keyword or timestamp one day later, depending on context."
12557 (interactive "P")
12558 (cond
12559 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
12560 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
12561 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
12562 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
12563 ((org-clocktable-try-shift 'right arg))
12564 (t (org-shiftcursor-error))))
12566 (defun org-shiftleft (&optional arg)
12567 "Previous TODO keyword or timestamp one day earlier, depending on context."
12568 (interactive "P")
12569 (cond
12570 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
12571 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
12572 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
12573 ((org-at-property-p)
12574 (call-interactively 'org-property-previous-allowed-value))
12575 ((org-clocktable-try-shift 'left arg))
12576 (t (org-shiftcursor-error))))
12578 (defun org-shiftcontrolright ()
12579 "Switch to next TODO set."
12580 (interactive)
12581 (cond
12582 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
12583 (t (org-shiftcursor-error))))
12585 (defun org-shiftcontrolleft ()
12586 "Switch to previous TODO set."
12587 (interactive)
12588 (cond
12589 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
12590 (t (org-shiftcursor-error))))
12592 (defun org-ctrl-c-ret ()
12593 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
12594 (interactive)
12595 (cond
12596 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
12597 (t (call-interactively 'org-insert-heading))))
12599 (defun org-copy-special ()
12600 "Copy region in table or copy current subtree.
12601 Calls `org-table-copy' or `org-copy-subtree', depending on context.
12602 See the individual commands for more information."
12603 (interactive)
12604 (call-interactively
12605 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
12607 (defun org-cut-special ()
12608 "Cut region in table or cut current subtree.
12609 Calls `org-table-copy' or `org-cut-subtree', depending on context.
12610 See the individual commands for more information."
12611 (interactive)
12612 (call-interactively
12613 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
12615 (defun org-paste-special (arg)
12616 "Paste rectangular region into table, or past subtree relative to level.
12617 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
12618 See the individual commands for more information."
12619 (interactive "P")
12620 (if (org-at-table-p)
12621 (org-table-paste-rectangle)
12622 (org-paste-subtree arg)))
12624 (defun org-edit-special ()
12625 "Call a special editor for the stuff at point.
12626 When at a table, call the formula editor with `org-table-edit-formulas'.
12627 When at the first line of an src example, call `org-edit-src-code'.
12628 When in an #+include line, visit the include file. Otherwise call
12629 `ffap' to visit the file at point."
12630 (interactive)
12631 (cond
12632 ((org-at-table-p)
12633 (call-interactively 'org-table-edit-formulas))
12634 ((save-excursion
12635 (beginning-of-line 1)
12636 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
12637 (find-file (org-trim (match-string 1))))
12638 ((org-edit-src-code))
12639 ((org-edit-fixed-width-region))
12640 (t (call-interactively 'ffap))))
12642 (defun org-ctrl-c-ctrl-c (&optional arg)
12643 "Set tags in headline, or update according to changed information at point.
12645 This command does many different things, depending on context:
12647 - If the cursor is in a headline, prompt for tags and insert them
12648 into the current line, aligned to `org-tags-column'. When called
12649 with prefix arg, realign all tags in the current buffer.
12651 - If the cursor is in one of the special #+KEYWORD lines, this
12652 triggers scanning the buffer for these lines and updating the
12653 information.
12655 - If the cursor is inside a table, realign the table. This command
12656 works even if the automatic table editor has been turned off.
12658 - If the cursor is on a #+TBLFM line, re-apply the formulas to
12659 the entire table.
12661 - If the cursor is a the beginning of a dynamic block, update it.
12663 - If the cursor is inside a table created by the table.el package,
12664 activate that table.
12666 - If the current buffer is a remember buffer, close note and file
12667 it. A prefix argument of 1 files to the default location
12668 without further interaction. A prefix argument of 2 files to
12669 the currently clocking task.
12671 - If the cursor is on a <<<target>>>, update radio targets and corresponding
12672 links in this buffer.
12674 - If the cursor is on a numbered item in a plain list, renumber the
12675 ordered list.
12677 - If the cursor is on a checkbox, toggle it."
12678 (interactive "P")
12679 (let ((org-enable-table-editor t))
12680 (cond
12681 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
12682 org-occur-highlights
12683 org-latex-fragment-image-overlays)
12684 (and (boundp 'org-clock-overlays) (org-remove-clock-overlays))
12685 (org-remove-occur-highlights)
12686 (org-remove-latex-fragment-image-overlays)
12687 (message "Temporary highlights/overlays removed from current buffer"))
12688 ((and (local-variable-p 'org-finish-function (current-buffer))
12689 (fboundp org-finish-function))
12690 (funcall org-finish-function))
12691 ((org-at-property-p)
12692 (call-interactively 'org-property-action))
12693 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
12694 ((org-on-heading-p) (call-interactively 'org-set-tags))
12695 ((org-at-table.el-p)
12696 (require 'table)
12697 (beginning-of-line 1)
12698 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
12699 (call-interactively 'table-recognize-table))
12700 ((org-at-table-p)
12701 (org-table-maybe-eval-formula)
12702 (if arg
12703 (call-interactively 'org-table-recalculate)
12704 (org-table-maybe-recalculate-line))
12705 (call-interactively 'org-table-align))
12706 ((org-at-item-checkbox-p)
12707 (call-interactively 'org-toggle-checkbox))
12708 ((org-at-item-p)
12709 (call-interactively 'org-maybe-renumber-ordered-list))
12710 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
12711 ;; Dynamic block
12712 (beginning-of-line 1)
12713 (save-excursion (org-update-dblock)))
12714 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
12715 (cond
12716 ((equal (match-string 1) "TBLFM")
12717 ;; Recalculate the table before this line
12718 (save-excursion
12719 (beginning-of-line 1)
12720 (skip-chars-backward " \r\n\t")
12721 (if (org-at-table-p)
12722 (org-call-with-arg 'org-table-recalculate t))))
12724 ; (org-set-regexps-and-options)
12725 ; (org-restart-font-lock)
12726 (let ((org-inhibit-startup t)) (org-mode-restart))
12727 (message "Local setup has been refreshed"))))
12728 (t (error "C-c C-c can do nothing useful at this location.")))))
12730 (defun org-mode-restart ()
12731 "Restart Org-mode, to scan again for special lines.
12732 Also updates the keyword regular expressions."
12733 (interactive)
12734 (org-mode)
12735 (message "Org-mode restarted"))
12737 (defun org-kill-note-or-show-branches ()
12738 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
12739 (interactive)
12740 (if (not org-finish-function)
12741 (call-interactively 'show-branches)
12742 (let ((org-note-abort t))
12743 (funcall org-finish-function))))
12745 (defun org-return (&optional indent)
12746 "Goto next table row or insert a newline.
12747 Calls `org-table-next-row' or `newline', depending on context.
12748 See the individual commands for more information."
12749 (interactive)
12750 (cond
12751 ((bobp) (if indent (newline-and-indent) (newline)))
12752 ((and (org-at-heading-p)
12753 (looking-at
12754 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
12755 (org-show-entry)
12756 (end-of-line 1)
12757 (newline))
12758 ((org-at-table-p)
12759 (org-table-justify-field-maybe)
12760 (call-interactively 'org-table-next-row))
12761 (t (if indent (newline-and-indent) (newline)))))
12763 (defun org-return-indent ()
12764 "Goto next table row or insert a newline and indent.
12765 Calls `org-table-next-row' or `newline-and-indent', depending on
12766 context. See the individual commands for more information."
12767 (interactive)
12768 (org-return t))
12770 (defun org-ctrl-c-star ()
12771 "Compute table, or change heading status of lines.
12772 Calls `org-table-recalculate' or `org-toggle-region-headings',
12773 depending on context. This will also turn a plain list item or a normal
12774 line into a subheading."
12775 (interactive)
12776 (cond
12777 ((org-at-table-p)
12778 (call-interactively 'org-table-recalculate))
12779 ((org-region-active-p)
12780 ;; Convert all lines in region to list items
12781 (call-interactively 'org-toggle-region-headings))
12782 ((org-on-heading-p)
12783 (org-toggle-region-headings (point-at-bol)
12784 (min (1+ (point-at-eol)) (point-max))))
12785 ((org-at-item-p)
12786 ;; Convert to heading
12787 (let ((level (save-match-data
12788 (save-excursion
12789 (condition-case nil
12790 (progn
12791 (org-back-to-heading t)
12792 (funcall outline-level))
12793 (error 0))))))
12794 (replace-match
12795 (concat (make-string (org-get-valid-level level 1) ?*) " ") t t)))
12796 (t (org-toggle-region-headings (point-at-bol)
12797 (min (1+ (point-at-eol)) (point-max))))))
12799 (defun org-ctrl-c-minus ()
12800 "Insert separator line in table or modify bullet status of line.
12801 Also turns a plain line or a region of lines into list items.
12802 Calls `org-table-insert-hline', `org-toggle-region-items', or
12803 `org-cycle-list-bullet', depending on context."
12804 (interactive)
12805 (cond
12806 ((org-at-table-p)
12807 (call-interactively 'org-table-insert-hline))
12808 ((org-on-heading-p)
12809 ;; Convert to item
12810 (save-excursion
12811 (beginning-of-line 1)
12812 (if (looking-at "\\*+ ")
12813 (replace-match (concat (make-string (- (match-end 0) (point) 1) ?\ ) "- ")))))
12814 ((org-region-active-p)
12815 ;; Convert all lines in region to list items
12816 (call-interactively 'org-toggle-region-items))
12817 ((org-in-item-p)
12818 (call-interactively 'org-cycle-list-bullet))
12819 (t (org-toggle-region-items (point-at-bol)
12820 (min (1+ (point-at-eol)) (point-max))))))
12822 (defun org-toggle-region-items (beg end)
12823 "Convert all lines in region to list items.
12824 If the first line is already an item, convert all list items in the region
12825 to normal lines."
12826 (interactive "r")
12827 (let (l2 l)
12828 (save-excursion
12829 (goto-char end)
12830 (setq l2 (org-current-line))
12831 (goto-char beg)
12832 (beginning-of-line 1)
12833 (setq l (1- (org-current-line)))
12834 (if (org-at-item-p)
12835 ;; We already have items, de-itemize
12836 (while (< (setq l (1+ l)) l2)
12837 (when (org-at-item-p)
12838 (goto-char (match-beginning 2))
12839 (delete-region (match-beginning 2) (match-end 2))
12840 (and (looking-at "[ \t]+") (replace-match "")))
12841 (beginning-of-line 2))
12842 (while (< (setq l (1+ l)) l2)
12843 (unless (org-at-item-p)
12844 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
12845 (replace-match "\\1- \\2")))
12846 (beginning-of-line 2))))))
12848 (defun org-toggle-region-headings (beg end)
12849 "Convert all lines in region to list items.
12850 If the first line is already an item, convert all list items in the region
12851 to normal lines."
12852 (interactive "r")
12853 (let (l2 l)
12854 (save-excursion
12855 (goto-char end)
12856 (setq l2 (org-current-line))
12857 (goto-char beg)
12858 (beginning-of-line 1)
12859 (setq l (1- (org-current-line)))
12860 (if (org-on-heading-p)
12861 ;; We already have headlines, de-star them
12862 (while (< (setq l (1+ l)) l2)
12863 (when (org-on-heading-p t)
12864 (and (looking-at outline-regexp) (replace-match "")))
12865 (beginning-of-line 2))
12866 (let* ((stars (save-excursion
12867 (re-search-backward org-complex-heading-regexp nil t)
12868 (or (match-string 1) "*")))
12869 (add-stars (if org-odd-levels-only "**" "*"))
12870 (rpl (concat stars add-stars " \\2")))
12871 (while (< (setq l (1+ l)) l2)
12872 (unless (org-on-heading-p)
12873 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
12874 (replace-match rpl)))
12875 (beginning-of-line 2)))))))
12877 (defun org-meta-return (&optional arg)
12878 "Insert a new heading or wrap a region in a table.
12879 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
12880 See the individual commands for more information."
12881 (interactive "P")
12882 (cond
12883 ((org-at-table-p)
12884 (call-interactively 'org-table-wrap-region))
12885 (t (call-interactively 'org-insert-heading))))
12887 ;;; Menu entries
12889 ;; Define the Org-mode menus
12890 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
12891 '("Tbl"
12892 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
12893 ["Next Field" org-cycle (org-at-table-p)]
12894 ["Previous Field" org-shifttab (org-at-table-p)]
12895 ["Next Row" org-return (org-at-table-p)]
12896 "--"
12897 ["Blank Field" org-table-blank-field (org-at-table-p)]
12898 ["Edit Field" org-table-edit-field (org-at-table-p)]
12899 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
12900 "--"
12901 ("Column"
12902 ["Move Column Left" org-metaleft (org-at-table-p)]
12903 ["Move Column Right" org-metaright (org-at-table-p)]
12904 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
12905 ["Insert Column" org-shiftmetaright (org-at-table-p)])
12906 ("Row"
12907 ["Move Row Up" org-metaup (org-at-table-p)]
12908 ["Move Row Down" org-metadown (org-at-table-p)]
12909 ["Delete Row" org-shiftmetaup (org-at-table-p)]
12910 ["Insert Row" org-shiftmetadown (org-at-table-p)]
12911 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
12912 "--"
12913 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
12914 ("Rectangle"
12915 ["Copy Rectangle" org-copy-special (org-at-table-p)]
12916 ["Cut Rectangle" org-cut-special (org-at-table-p)]
12917 ["Paste Rectangle" org-paste-special (org-at-table-p)]
12918 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
12919 "--"
12920 ("Calculate"
12921 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
12922 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
12923 ["Edit Formulas" org-edit-special (org-at-table-p)]
12924 "--"
12925 ["Recalculate line" org-table-recalculate (org-at-table-p)]
12926 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
12927 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
12928 "--"
12929 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
12930 "--"
12931 ["Sum Column/Rectangle" org-table-sum
12932 (or (org-at-table-p) (org-region-active-p))]
12933 ["Which Column?" org-table-current-column (org-at-table-p)])
12934 ["Debug Formulas"
12935 org-table-toggle-formula-debugger
12936 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
12937 ["Show Col/Row Numbers"
12938 org-table-toggle-coordinate-overlays
12939 :style toggle
12940 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
12941 "--"
12942 ["Create" org-table-create (and (not (org-at-table-p))
12943 org-enable-table-editor)]
12944 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
12945 ["Import from File" org-table-import (not (org-at-table-p))]
12946 ["Export to File" org-table-export (org-at-table-p)]
12947 "--"
12948 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
12950 (easy-menu-define org-org-menu org-mode-map "Org menu"
12951 '("Org"
12952 ("Show/Hide"
12953 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
12954 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
12955 ["Sparse Tree..." org-sparse-tree t]
12956 ["Reveal Context" org-reveal t]
12957 ["Show All" show-all t]
12958 "--"
12959 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
12960 "--"
12961 ["New Heading" org-insert-heading t]
12962 ("Navigate Headings"
12963 ["Up" outline-up-heading t]
12964 ["Next" outline-next-visible-heading t]
12965 ["Previous" outline-previous-visible-heading t]
12966 ["Next Same Level" outline-forward-same-level t]
12967 ["Previous Same Level" outline-backward-same-level t]
12968 "--"
12969 ["Jump" org-goto t])
12970 ("Edit Structure"
12971 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
12972 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
12973 "--"
12974 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
12975 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
12976 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
12977 "--"
12978 ["Promote Heading" org-metaleft (not (org-at-table-p))]
12979 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
12980 ["Demote Heading" org-metaright (not (org-at-table-p))]
12981 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
12982 "--"
12983 ["Sort Region/Children" org-sort (not (org-at-table-p))]
12984 "--"
12985 ["Convert to odd levels" org-convert-to-odd-levels t]
12986 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
12987 ("Editing"
12988 ["Emphasis..." org-emphasize t]
12989 ["Edit Source Example" org-edit-special t])
12990 ("Archive"
12991 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
12992 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
12993 ; :active t :keys "C-u C-c C-x C-a"]
12994 ["Sparse trees open ARCHIVE trees"
12995 (setq org-sparse-tree-open-archived-trees
12996 (not org-sparse-tree-open-archived-trees))
12997 :style toggle :selected org-sparse-tree-open-archived-trees]
12998 ["Cycling opens ARCHIVE trees"
12999 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
13000 :style toggle :selected org-cycle-open-archived-trees]
13001 "--"
13002 ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
13003 ["Move Subtree to Archive" org-advertized-archive-subtree t]
13004 ; ["Check and Move Children" (org-archive-subtree '(4))
13005 ; :active t :keys "C-u C-c C-x C-s"]
13007 "--"
13008 ("TODO Lists"
13009 ["TODO/DONE/-" org-todo t]
13010 ("Select keyword"
13011 ["Next keyword" org-shiftright (org-on-heading-p)]
13012 ["Previous keyword" org-shiftleft (org-on-heading-p)]
13013 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
13014 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
13015 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
13016 ["Show TODO Tree" org-show-todo-tree t]
13017 ["Global TODO list" org-todo-list t]
13018 "--"
13019 ["Set Priority" org-priority t]
13020 ["Priority Up" org-shiftup t]
13021 ["Priority Down" org-shiftdown t])
13022 ("TAGS and Properties"
13023 ["Set Tags" 'org-set-tags-command t]
13024 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
13025 "--"
13026 ["Set property" 'org-set-property t]
13027 ["Column view of properties" org-columns t]
13028 ["Insert Column View DBlock" org-insert-columns-dblock t])
13029 ("Dates and Scheduling"
13030 ["Timestamp" org-time-stamp t]
13031 ["Timestamp (inactive)" org-time-stamp-inactive t]
13032 ("Change Date"
13033 ["1 Day Later" org-shiftright t]
13034 ["1 Day Earlier" org-shiftleft t]
13035 ["1 ... Later" org-shiftup t]
13036 ["1 ... Earlier" org-shiftdown t])
13037 ["Compute Time Range" org-evaluate-time-range t]
13038 ["Schedule Item" org-schedule t]
13039 ["Deadline" org-deadline t]
13040 "--"
13041 ["Custom time format" org-toggle-time-stamp-overlays
13042 :style radio :selected org-display-custom-times]
13043 "--"
13044 ["Goto Calendar" org-goto-calendar t]
13045 ["Date from Calendar" org-date-from-calendar t])
13046 ("Logging work"
13047 ["Clock in" org-clock-in t]
13048 ["Clock out" org-clock-out t]
13049 ["Clock cancel" org-clock-cancel t]
13050 ["Goto running clock" org-clock-goto t]
13051 ["Display times" org-clock-display t]
13052 ["Create clock table" org-clock-report t]
13053 "--"
13054 ["Record DONE time"
13055 (progn (setq org-log-done (not org-log-done))
13056 (message "Switching to %s will %s record a timestamp"
13057 (car org-done-keywords)
13058 (if org-log-done "automatically" "not")))
13059 :style toggle :selected org-log-done])
13060 "--"
13061 ["Agenda Command..." org-agenda t]
13062 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
13063 ("File List for Agenda")
13064 ("Special views current file"
13065 ["TODO Tree" org-show-todo-tree t]
13066 ["Check Deadlines" org-check-deadlines t]
13067 ["Timeline" org-timeline t]
13068 ["Tags Tree" org-tags-sparse-tree t])
13069 "--"
13070 ("Hyperlinks"
13071 ["Store Link (Global)" org-store-link t]
13072 ["Insert Link" org-insert-link t]
13073 ["Follow Link" org-open-at-point t]
13074 "--"
13075 ["Next link" org-next-link t]
13076 ["Previous link" org-previous-link t]
13077 "--"
13078 ["Descriptive Links"
13079 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
13080 :style radio
13081 :selected (member '(org-link) buffer-invisibility-spec)]
13082 ["Literal Links"
13083 (progn
13084 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
13085 :style radio
13086 :selected (not (member '(org-link) buffer-invisibility-spec))])
13087 "--"
13088 ["Export/Publish..." org-export t]
13089 ("LaTeX"
13090 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
13091 :selected org-cdlatex-mode]
13092 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
13093 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
13094 ["Modify math symbol" org-cdlatex-math-modify
13095 (org-inside-LaTeX-fragment-p)]
13096 ["Export LaTeX fragments as images"
13097 (if (featurep 'org-exp)
13098 (setq org-export-with-LaTeX-fragments
13099 (not org-export-with-LaTeX-fragments))
13100 (require 'org-exp))
13101 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
13102 org-export-with-LaTeX-fragments)])
13103 "--"
13104 ("Documentation"
13105 ["Show Version" org-version t]
13106 ["Info Documentation" org-info t])
13107 ("Customize"
13108 ["Browse Org Group" org-customize t]
13109 "--"
13110 ["Expand This Menu" org-create-customize-menu
13111 (fboundp 'customize-menu-create)])
13112 "--"
13113 ["Refresh setup" org-mode-restart t]
13116 (defun org-info (&optional node)
13117 "Read documentation for Org-mode in the info system.
13118 With optional NODE, go directly to that node."
13119 (interactive)
13120 (info (format "(org)%s" (or node ""))))
13122 (defun org-install-agenda-files-menu ()
13123 (let ((bl (buffer-list)))
13124 (save-excursion
13125 (while bl
13126 (set-buffer (pop bl))
13127 (if (org-mode-p) (setq bl nil)))
13128 (when (org-mode-p)
13129 (easy-menu-change
13130 '("Org") "File List for Agenda"
13131 (append
13132 (list
13133 ["Edit File List" (org-edit-agenda-file-list) t]
13134 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
13135 ["Remove Current File from List" org-remove-file t]
13136 ["Cycle through agenda files" org-cycle-agenda-files t]
13137 ["Occur in all agenda files" org-occur-in-agenda-files t]
13138 "--")
13139 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
13141 ;;;; Documentation
13143 ;;;###autoload
13144 (defun org-require-autoloaded-modules ()
13145 (interactive)
13146 (mapc 'require
13147 '(org-agenda org-archive org-clock org-colview
13148 org-exp org-id org-export-latex org-publish
13149 org-remember org-table)))
13151 ;;;###autoload
13152 (defun org-customize ()
13153 "Call the customize function with org as argument."
13154 (interactive)
13155 (org-load-modules-maybe)
13156 (org-require-autoloaded-modules)
13157 (customize-browse 'org))
13159 (defun org-create-customize-menu ()
13160 "Create a full customization menu for Org-mode, insert it into the menu."
13161 (interactive)
13162 (org-load-modules-maybe)
13163 (org-require-autoloaded-modules)
13164 (if (fboundp 'customize-menu-create)
13165 (progn
13166 (easy-menu-change
13167 '("Org") "Customize"
13168 `(["Browse Org group" org-customize t]
13169 "--"
13170 ,(customize-menu-create 'org)
13171 ["Set" Custom-set t]
13172 ["Save" Custom-save t]
13173 ["Reset to Current" Custom-reset-current t]
13174 ["Reset to Saved" Custom-reset-saved t]
13175 ["Reset to Standard Settings" Custom-reset-standard t]))
13176 (message "\"Org\"-menu now contains full customization menu"))
13177 (error "Cannot expand menu (outdated version of cus-edit.el)")))
13179 ;;;; Miscellaneous stuff
13181 ;;; Generally useful functions
13183 (defun org-display-warning (message) ;; Copied from Emacs-Muse
13184 "Display the given MESSAGE as a warning."
13185 (if (fboundp 'display-warning)
13186 (display-warning 'org message
13187 (if (featurep 'xemacs)
13188 'warning
13189 :warning))
13190 (let ((buf (get-buffer-create "*Org warnings*")))
13191 (with-current-buffer buf
13192 (goto-char (point-max))
13193 (insert "Warning (Org): " message)
13194 (unless (bolp)
13195 (newline)))
13196 (display-buffer buf)
13197 (sit-for 0))))
13199 (defun org-goto-marker-or-bmk (marker &optional bookmark)
13200 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
13201 (if (and marker (marker-buffer marker)
13202 (buffer-live-p (marker-buffer marker)))
13203 (progn
13204 (switch-to-buffer (marker-buffer marker))
13205 (if (or (> marker (point-max)) (< marker (point-min)))
13206 (widen))
13207 (goto-char marker))
13208 (if bookmark
13209 (bookmark-jump bookmark)
13210 (error "Cannot find location"))))
13212 (defun org-quote-csv-field (s)
13213 "Quote field for inclusion in CSV material."
13214 (if (string-match "[\",]" s)
13215 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
13218 (defun org-plist-delete (plist property)
13219 "Delete PROPERTY from PLIST.
13220 This is in contrast to merely setting it to 0."
13221 (let (p)
13222 (while plist
13223 (if (not (eq property (car plist)))
13224 (setq p (plist-put p (car plist) (nth 1 plist))))
13225 (setq plist (cddr plist)))
13228 (defun org-force-self-insert (N)
13229 "Needed to enforce self-insert under remapping."
13230 (interactive "p")
13231 (self-insert-command N))
13233 (defun org-string-width (s)
13234 "Compute width of string, ignoring invisible characters.
13235 This ignores character with invisibility property `org-link', and also
13236 characters with property `org-cwidth', because these will become invisible
13237 upon the next fontification round."
13238 (let (b l)
13239 (when (or (eq t buffer-invisibility-spec)
13240 (assq 'org-link buffer-invisibility-spec))
13241 (while (setq b (text-property-any 0 (length s)
13242 'invisible 'org-link s))
13243 (setq s (concat (substring s 0 b)
13244 (substring s (or (next-single-property-change
13245 b 'invisible s) (length s)))))))
13246 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
13247 (setq s (concat (substring s 0 b)
13248 (substring s (or (next-single-property-change
13249 b 'org-cwidth s) (length s))))))
13250 (setq l (string-width s) b -1)
13251 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
13252 (setq l (- l (get-text-property b 'org-dwidth-n s))))
13255 (defun org-get-indentation (&optional line)
13256 "Get the indentation of the current line, interpreting tabs.
13257 When LINE is given, assume it represents a line and compute its indentation."
13258 (if line
13259 (if (string-match "^ *" (org-remove-tabs line))
13260 (match-end 0))
13261 (save-excursion
13262 (beginning-of-line 1)
13263 (skip-chars-forward " \t")
13264 (current-column))))
13266 (defun org-remove-tabs (s &optional width)
13267 "Replace tabulators in S with spaces.
13268 Assumes that s is a single line, starting in column 0."
13269 (setq width (or width tab-width))
13270 (while (string-match "\t" s)
13271 (setq s (replace-match
13272 (make-string
13273 (- (* width (/ (+ (match-beginning 0) width) width))
13274 (match-beginning 0)) ?\ )
13275 t t s)))
13278 (defun org-fix-indentation (line ind)
13279 "Fix indentation in LINE.
13280 IND is a cons cell with target and minimum indentation.
13281 If the current indenation in LINE is smaller than the minimum,
13282 leave it alone. If it is larger than ind, set it to the target."
13283 (let* ((l (org-remove-tabs line))
13284 (i (org-get-indentation l))
13285 (i1 (car ind)) (i2 (cdr ind)))
13286 (if (>= i i2) (setq l (substring line i2)))
13287 (if (> i1 0)
13288 (concat (make-string i1 ?\ ) l)
13289 l)))
13291 (defun org-base-buffer (buffer)
13292 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
13293 (if (not buffer)
13294 buffer
13295 (or (buffer-base-buffer buffer)
13296 buffer)))
13298 (defun org-trim (s)
13299 "Remove whitespace at beginning and end of string."
13300 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
13301 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
13304 (defun org-wrap (string &optional width lines)
13305 "Wrap string to either a number of lines, or a width in characters.
13306 If WIDTH is non-nil, the string is wrapped to that width, however many lines
13307 that costs. If there is a word longer than WIDTH, the text is actually
13308 wrapped to the length of that word.
13309 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
13310 many lines, whatever width that takes.
13311 The return value is a list of lines, without newlines at the end."
13312 (let* ((words (org-split-string string "[ \t\n]+"))
13313 (maxword (apply 'max (mapcar 'org-string-width words)))
13314 w ll)
13315 (cond (width
13316 (org-do-wrap words (max maxword width)))
13317 (lines
13318 (setq w maxword)
13319 (setq ll (org-do-wrap words maxword))
13320 (if (<= (length ll) lines)
13322 (setq ll words)
13323 (while (> (length ll) lines)
13324 (setq w (1+ w))
13325 (setq ll (org-do-wrap words w)))
13326 ll))
13327 (t (error "Cannot wrap this")))))
13329 (defun org-do-wrap (words width)
13330 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
13331 (let (lines line)
13332 (while words
13333 (setq line (pop words))
13334 (while (and words (< (+ (length line) (length (car words))) width))
13335 (setq line (concat line " " (pop words))))
13336 (setq lines (push line lines)))
13337 (nreverse lines)))
13339 (defun org-split-string (string &optional separators)
13340 "Splits STRING into substrings at SEPARATORS.
13341 No empty strings are returned if there are matches at the beginning
13342 and end of string."
13343 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
13344 (start 0)
13345 notfirst
13346 (list nil))
13347 (while (and (string-match rexp string
13348 (if (and notfirst
13349 (= start (match-beginning 0))
13350 (< start (length string)))
13351 (1+ start) start))
13352 (< (match-beginning 0) (length string)))
13353 (setq notfirst t)
13354 (or (eq (match-beginning 0) 0)
13355 (and (eq (match-beginning 0) (match-end 0))
13356 (eq (match-beginning 0) start))
13357 (setq list
13358 (cons (substring string start (match-beginning 0))
13359 list)))
13360 (setq start (match-end 0)))
13361 (or (eq start (length string))
13362 (setq list
13363 (cons (substring string start)
13364 list)))
13365 (nreverse list)))
13367 (defun org-context ()
13368 "Return a list of contexts of the current cursor position.
13369 If several contexts apply, all are returned.
13370 Each context entry is a list with a symbol naming the context, and
13371 two positions indicating start and end of the context. Possible
13372 contexts are:
13374 :headline anywhere in a headline
13375 :headline-stars on the leading stars in a headline
13376 :todo-keyword on a TODO keyword (including DONE) in a headline
13377 :tags on the TAGS in a headline
13378 :priority on the priority cookie in a headline
13379 :item on the first line of a plain list item
13380 :item-bullet on the bullet/number of a plain list item
13381 :checkbox on the checkbox in a plain list item
13382 :table in an org-mode table
13383 :table-special on a special filed in a table
13384 :table-table in a table.el table
13385 :link on a hyperlink
13386 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
13387 :target on a <<target>>
13388 :radio-target on a <<<radio-target>>>
13389 :latex-fragment on a LaTeX fragment
13390 :latex-preview on a LaTeX fragment with overlayed preview image
13392 This function expects the position to be visible because it uses font-lock
13393 faces as a help to recognize the following contexts: :table-special, :link,
13394 and :keyword."
13395 (let* ((f (get-text-property (point) 'face))
13396 (faces (if (listp f) f (list f)))
13397 (p (point)) clist o)
13398 ;; First the large context
13399 (cond
13400 ((org-on-heading-p t)
13401 (push (list :headline (point-at-bol) (point-at-eol)) clist)
13402 (when (progn
13403 (beginning-of-line 1)
13404 (looking-at org-todo-line-tags-regexp))
13405 (push (org-point-in-group p 1 :headline-stars) clist)
13406 (push (org-point-in-group p 2 :todo-keyword) clist)
13407 (push (org-point-in-group p 4 :tags) clist))
13408 (goto-char p)
13409 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
13410 (if (looking-at "\\[#[A-Z0-9]\\]")
13411 (push (org-point-in-group p 0 :priority) clist)))
13413 ((org-at-item-p)
13414 (push (org-point-in-group p 2 :item-bullet) clist)
13415 (push (list :item (point-at-bol)
13416 (save-excursion (org-end-of-item) (point)))
13417 clist)
13418 (and (org-at-item-checkbox-p)
13419 (push (org-point-in-group p 0 :checkbox) clist)))
13421 ((org-at-table-p)
13422 (push (list :table (org-table-begin) (org-table-end)) clist)
13423 (if (memq 'org-formula faces)
13424 (push (list :table-special
13425 (previous-single-property-change p 'face)
13426 (next-single-property-change p 'face)) clist)))
13427 ((org-at-table-p 'any)
13428 (push (list :table-table) clist)))
13429 (goto-char p)
13431 ;; Now the small context
13432 (cond
13433 ((org-at-timestamp-p)
13434 (push (org-point-in-group p 0 :timestamp) clist))
13435 ((memq 'org-link faces)
13436 (push (list :link
13437 (previous-single-property-change p 'face)
13438 (next-single-property-change p 'face)) clist))
13439 ((memq 'org-special-keyword faces)
13440 (push (list :keyword
13441 (previous-single-property-change p 'face)
13442 (next-single-property-change p 'face)) clist))
13443 ((org-on-target-p)
13444 (push (org-point-in-group p 0 :target) clist)
13445 (goto-char (1- (match-beginning 0)))
13446 (if (looking-at org-radio-target-regexp)
13447 (push (org-point-in-group p 0 :radio-target) clist))
13448 (goto-char p))
13449 ((setq o (car (delq nil
13450 (mapcar
13451 (lambda (x)
13452 (if (memq x org-latex-fragment-image-overlays) x))
13453 (org-overlays-at (point))))))
13454 (push (list :latex-fragment
13455 (org-overlay-start o) (org-overlay-end o)) clist)
13456 (push (list :latex-preview
13457 (org-overlay-start o) (org-overlay-end o)) clist))
13458 ((org-inside-LaTeX-fragment-p)
13459 ;; FIXME: positions wrong.
13460 (push (list :latex-fragment (point) (point)) clist)))
13462 (setq clist (nreverse (delq nil clist)))
13463 clist))
13465 ;; FIXME: Compare with at-regexp-p Do we need both?
13466 (defun org-in-regexp (re &optional nlines visually)
13467 "Check if point is inside a match of regexp.
13468 Normally only the current line is checked, but you can include NLINES extra
13469 lines both before and after point into the search.
13470 If VISUALLY is set, require that the cursor is not after the match but
13471 really on, so that the block visually is on the match."
13472 (catch 'exit
13473 (let ((pos (point))
13474 (eol (point-at-eol (+ 1 (or nlines 0))))
13475 (inc (if visually 1 0)))
13476 (save-excursion
13477 (beginning-of-line (- 1 (or nlines 0)))
13478 (while (re-search-forward re eol t)
13479 (if (and (<= (match-beginning 0) pos)
13480 (>= (+ inc (match-end 0)) pos))
13481 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
13483 (defun org-at-regexp-p (regexp)
13484 "Is point inside a match of REGEXP in the current line?"
13485 (catch 'exit
13486 (save-excursion
13487 (let ((pos (point)) (end (point-at-eol)))
13488 (beginning-of-line 1)
13489 (while (re-search-forward regexp end t)
13490 (if (and (<= (match-beginning 0) pos)
13491 (>= (match-end 0) pos))
13492 (throw 'exit t)))
13493 nil))))
13495 (defun org-occur-in-agenda-files (regexp &optional nlines)
13496 "Call `multi-occur' with buffers for all agenda files."
13497 (interactive "sOrg-files matching: \np")
13498 (let* ((files (org-agenda-files))
13499 (tnames (mapcar 'file-truename files))
13500 (extra org-agenda-text-search-extra-files)
13502 (when (eq (car extra) 'agenda-archives)
13503 (setq extra (cdr extra))
13504 (setq files (org-add-archive-files files)))
13505 (while (setq f (pop extra))
13506 (unless (member (file-truename f) tnames)
13507 (add-to-list 'files f 'append)
13508 (add-to-list 'tnames (file-truename f) 'append)))
13509 (multi-occur
13510 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
13511 regexp)))
13513 (if (boundp 'occur-mode-find-occurrence-hook)
13514 ;; Emacs 23
13515 (add-hook 'occur-mode-find-occurrence-hook
13516 (lambda ()
13517 (when (org-mode-p)
13518 (org-reveal))))
13519 ;; Emacs 22
13520 (defadvice occur-mode-goto-occurrence
13521 (after org-occur-reveal activate)
13522 (and (org-mode-p) (org-reveal)))
13523 (defadvice occur-mode-goto-occurrence-other-window
13524 (after org-occur-reveal activate)
13525 (and (org-mode-p) (org-reveal)))
13526 (defadvice occur-mode-display-occurrence
13527 (after org-occur-reveal activate)
13528 (when (org-mode-p)
13529 (let ((pos (occur-mode-find-occurrence)))
13530 (with-current-buffer (marker-buffer pos)
13531 (save-excursion
13532 (goto-char pos)
13533 (org-reveal)))))))
13535 (defun org-uniquify (list)
13536 "Remove duplicate elements from LIST."
13537 (let (res)
13538 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
13539 res))
13541 (defun org-delete-all (elts list)
13542 "Remove all elements in ELTS from LIST."
13543 (while elts
13544 (setq list (delete (pop elts) list)))
13545 list)
13547 (defun org-back-over-empty-lines ()
13548 "Move backwards over witespace, to the beginning of the first empty line.
13549 Returns the number of empty lines passed."
13550 (let ((pos (point)))
13551 (skip-chars-backward " \t\n\r")
13552 (beginning-of-line 2)
13553 (goto-char (min (point) pos))
13554 (count-lines (point) pos)))
13556 (defun org-skip-whitespace ()
13557 (skip-chars-forward " \t\n\r"))
13559 (defun org-point-in-group (point group &optional context)
13560 "Check if POINT is in match-group GROUP.
13561 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
13562 match. If the match group does ot exist or point is not inside it,
13563 return nil."
13564 (and (match-beginning group)
13565 (>= point (match-beginning group))
13566 (<= point (match-end group))
13567 (if context
13568 (list context (match-beginning group) (match-end group))
13569 t)))
13571 (defun org-switch-to-buffer-other-window (&rest args)
13572 "Switch to buffer in a second window on the current frame.
13573 In particular, do not allow pop-up frames."
13574 (let (pop-up-frames special-display-buffer-names special-display-regexps
13575 special-display-function)
13576 (apply 'switch-to-buffer-other-window args)))
13578 (defun org-combine-plists (&rest plists)
13579 "Create a single property list from all plists in PLISTS.
13580 The process starts by copying the first list, and then setting properties
13581 from the other lists. Settings in the last list are the most significant
13582 ones and overrule settings in the other lists."
13583 (let ((rtn (copy-sequence (pop plists)))
13584 p v ls)
13585 (while plists
13586 (setq ls (pop plists))
13587 (while ls
13588 (setq p (pop ls) v (pop ls))
13589 (setq rtn (plist-put rtn p v))))
13590 rtn))
13592 (defun org-move-line-down (arg)
13593 "Move the current line down. With prefix argument, move it past ARG lines."
13594 (interactive "p")
13595 (let ((col (current-column))
13596 beg end pos)
13597 (beginning-of-line 1) (setq beg (point))
13598 (beginning-of-line 2) (setq end (point))
13599 (beginning-of-line (+ 1 arg))
13600 (setq pos (move-marker (make-marker) (point)))
13601 (insert (delete-and-extract-region beg end))
13602 (goto-char pos)
13603 (org-move-to-column col)))
13605 (defun org-move-line-up (arg)
13606 "Move the current line up. With prefix argument, move it past ARG lines."
13607 (interactive "p")
13608 (let ((col (current-column))
13609 beg end pos)
13610 (beginning-of-line 1) (setq beg (point))
13611 (beginning-of-line 2) (setq end (point))
13612 (beginning-of-line (- arg))
13613 (setq pos (move-marker (make-marker) (point)))
13614 (insert (delete-and-extract-region beg end))
13615 (goto-char pos)
13616 (org-move-to-column col)))
13618 (defun org-replace-escapes (string table)
13619 "Replace %-escapes in STRING with values in TABLE.
13620 TABLE is an association list with keys like \"%a\" and string values.
13621 The sequences in STRING may contain normal field width and padding information,
13622 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
13623 so values can contain further %-escapes if they are define later in TABLE."
13624 (let ((case-fold-search nil)
13625 e re rpl)
13626 (while (setq e (pop table))
13627 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
13628 (while (string-match re string)
13629 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
13630 (cdr e)))
13631 (setq string (replace-match rpl t t string))))
13632 string))
13635 (defun org-sublist (list start end)
13636 "Return a section of LIST, from START to END.
13637 Counting starts at 1."
13638 (let (rtn (c start))
13639 (setq list (nthcdr (1- start) list))
13640 (while (and list (<= c end))
13641 (push (pop list) rtn)
13642 (setq c (1+ c)))
13643 (nreverse rtn)))
13645 (defun org-find-base-buffer-visiting (file)
13646 "Like `find-buffer-visiting' but alway return the base buffer and
13647 not an indirect buffer."
13648 (let ((buf (find-buffer-visiting file)))
13649 (if buf
13650 (or (buffer-base-buffer buf) buf)
13651 nil)))
13653 (defun org-image-file-name-regexp ()
13654 "Return regexp matching the file names of images."
13655 (if (fboundp 'image-file-name-regexp)
13656 (image-file-name-regexp)
13657 (let ((image-file-name-extensions
13658 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
13659 "xbm" "xpm" "pbm" "pgm" "ppm")))
13660 (concat "\\."
13661 (regexp-opt (nconc (mapcar 'upcase
13662 image-file-name-extensions)
13663 image-file-name-extensions)
13665 "\\'"))))
13667 (defun org-file-image-p (file)
13668 "Return non-nil if FILE is an image."
13669 (save-match-data
13670 (string-match (org-image-file-name-regexp) file)))
13672 (defun org-get-cursor-date ()
13673 "Return the date at cursor in as a time.
13674 This works in the calendar and in the agenda, anywhere else it just
13675 returns the current time."
13676 (let (date day defd)
13677 (cond
13678 ((eq major-mode 'calendar-mode)
13679 (setq date (calendar-cursor-to-date)
13680 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13681 ((eq major-mode 'org-agenda-mode)
13682 (setq day (get-text-property (point) 'day))
13683 (if day
13684 (setq date (calendar-gregorian-from-absolute day)
13685 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
13686 (nth 2 date))))))
13687 (or defd (current-time))))
13689 (defvar org-agenda-action-marker (make-marker)
13690 "Marker pointing to the entry for the next agenda action.")
13692 (defun org-mark-entry-for-agenda-action ()
13693 "Mark the current entry as target of an agenda action.
13694 Agenda actions are actions executed from the agenda with the key `k',
13695 which make use of the date at the cursor."
13696 (interactive)
13697 (move-marker org-agenda-action-marker
13698 (save-excursion (org-back-to-heading t) (point))
13699 (current-buffer))
13700 (message
13701 "Entry marked for action; press `k' at desired date in agenda or calendar"))
13703 ;;; Paragraph filling stuff.
13704 ;; We want this to be just right, so use the full arsenal.
13706 (defun org-indent-line-function ()
13707 "Indent line like previous, but further if previous was headline or item."
13708 (interactive)
13709 (let* ((pos (point))
13710 (itemp (org-at-item-p))
13711 column bpos bcol tpos tcol bullet btype bullet-type)
13712 ;; Find the previous relevant line
13713 (beginning-of-line 1)
13714 (cond
13715 ((looking-at "#") (setq column 0))
13716 ((looking-at "\\*+ ") (setq column 0))
13718 (beginning-of-line 0)
13719 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
13720 (beginning-of-line 0))
13721 (cond
13722 ((looking-at "\\*+[ \t]+")
13723 (if (not org-adapt-indentation)
13724 (setq column 0)
13725 (goto-char (match-end 0))
13726 (setq column (current-column))))
13727 ((org-in-item-p)
13728 (org-beginning-of-item)
13729 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
13730 (setq bpos (match-beginning 1) tpos (match-end 0)
13731 bcol (progn (goto-char bpos) (current-column))
13732 tcol (progn (goto-char tpos) (current-column))
13733 bullet (match-string 1)
13734 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
13735 (if (> tcol (+ bcol org-description-max-indent))
13736 (setq tcol (+ bcol 5)))
13737 (if (not itemp)
13738 (setq column tcol)
13739 (goto-char pos)
13740 (beginning-of-line 1)
13741 (if (looking-at "\\S-")
13742 (progn
13743 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
13744 (setq bullet (match-string 1)
13745 btype (if (string-match "[0-9]" bullet) "n" bullet))
13746 (setq column (if (equal btype bullet-type) bcol tcol)))
13747 (setq column (org-get-indentation)))))
13748 (t (setq column (org-get-indentation))))))
13749 (goto-char pos)
13750 (if (<= (current-column) (current-indentation))
13751 (org-indent-line-to column)
13752 (save-excursion (org-indent-line-to column)))
13753 (setq column (current-column))
13754 (beginning-of-line 1)
13755 (if (looking-at
13756 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
13757 (replace-match (concat "\\1" (format org-property-format
13758 (match-string 2) (match-string 3)))
13759 t nil))
13760 (org-move-to-column column)))
13762 (defun org-set-autofill-regexps ()
13763 (interactive)
13764 ;; In the paragraph separator we include headlines, because filling
13765 ;; text in a line directly attached to a headline would otherwise
13766 ;; fill the headline as well.
13767 (org-set-local 'comment-start-skip "^#+[ \t]*")
13768 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
13769 ;; The paragraph starter includes hand-formatted lists.
13770 (org-set-local 'paragraph-start
13771 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
13772 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
13773 ;; But only if the user has not turned off tables or fixed-width regions
13774 (org-set-local
13775 'auto-fill-inhibit-regexp
13776 (concat "\\*+ \\|#\\+"
13777 "\\|[ \t]*" org-keyword-time-regexp
13778 (if (or org-enable-table-editor org-enable-fixed-width-editor)
13779 (concat
13780 "\\|[ \t]*["
13781 (if org-enable-table-editor "|" "")
13782 (if org-enable-fixed-width-editor ":" "")
13783 "]"))))
13784 ;; We use our own fill-paragraph function, to make sure that tables
13785 ;; and fixed-width regions are not wrapped. That function will pass
13786 ;; through to `fill-paragraph' when appropriate.
13787 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
13788 ; Adaptive filling: To get full control, first make sure that
13789 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
13790 (org-set-local 'adaptive-fill-regexp "\000")
13791 (org-set-local 'adaptive-fill-function
13792 'org-adaptive-fill-function)
13793 (org-set-local
13794 'align-mode-rules-list
13795 '((org-in-buffer-settings
13796 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
13797 (modes . '(org-mode))))))
13799 (defun org-fill-paragraph (&optional justify)
13800 "Re-align a table, pass through to fill-paragraph if no table."
13801 (let ((table-p (org-at-table-p))
13802 (table.el-p (org-at-table.el-p)))
13803 (cond ((and (equal (char-after (point-at-bol)) ?*)
13804 (save-excursion (goto-char (point-at-bol))
13805 (looking-at outline-regexp)))
13806 t) ; skip headlines
13807 (table.el-p t) ; skip table.el tables
13808 (table-p (org-table-align) t) ; align org-mode tables
13809 (t nil)))) ; call paragraph-fill
13811 ;; For reference, this is the default value of adaptive-fill-regexp
13812 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
13814 (defun org-adaptive-fill-function ()
13815 "Return a fill prefix for org-mode files.
13816 In particular, this makes sure hanging paragraphs for hand-formatted lists
13817 work correctly."
13818 (cond ((looking-at "#[ \t]+")
13819 (match-string 0))
13820 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
13821 (save-excursion
13822 (if (> (match-end 1) (+ (match-beginning 1)
13823 org-description-max-indent))
13824 (goto-char (+ (match-beginning 1) 5))
13825 (goto-char (match-end 0)))
13826 (make-string (current-column) ?\ )))
13827 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
13828 (save-excursion
13829 (goto-char (match-end 0))
13830 (make-string (current-column) ?\ )))
13831 (t nil)))
13833 ;;; Other stuff.
13835 (defun org-toggle-fixed-width-section (arg)
13836 "Toggle the fixed-width export.
13837 If there is no active region, the QUOTE keyword at the current headline is
13838 inserted or removed. When present, it causes the text between this headline
13839 and the next to be exported as fixed-width text, and unmodified.
13840 If there is an active region, this command adds or removes a colon as the
13841 first character of this line. If the first character of a line is a colon,
13842 this line is also exported in fixed-width font."
13843 (interactive "P")
13844 (let* ((cc 0)
13845 (regionp (org-region-active-p))
13846 (beg (if regionp (region-beginning) (point)))
13847 (end (if regionp (region-end)))
13848 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
13849 (case-fold-search nil)
13850 (re "[ \t]*\\(:\\)")
13851 off)
13852 (if regionp
13853 (save-excursion
13854 (goto-char beg)
13855 (setq cc (current-column))
13856 (beginning-of-line 1)
13857 (setq off (looking-at re))
13858 (while (> nlines 0)
13859 (setq nlines (1- nlines))
13860 (beginning-of-line 1)
13861 (cond
13862 (arg
13863 (org-move-to-column cc t)
13864 (insert ":\n")
13865 (forward-line -1))
13866 ((and off (looking-at re))
13867 (replace-match "" t t nil 1))
13868 ((not off) (org-move-to-column cc t) (insert ":")))
13869 (forward-line 1)))
13870 (save-excursion
13871 (org-back-to-heading)
13872 (if (looking-at (concat outline-regexp
13873 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
13874 (replace-match "" t t nil 1)
13875 (if (looking-at outline-regexp)
13876 (progn
13877 (goto-char (match-end 0))
13878 (insert org-quote-string " "))))))))
13880 ;;;; Functions extending outline functionality
13882 (defun org-beginning-of-line (&optional arg)
13883 "Go to the beginning of the current line. If that is invisible, continue
13884 to a visible line beginning. This makes the function of C-a more intuitive.
13885 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
13886 first attempt, and only move to after the tags when the cursor is already
13887 beyond the end of the headline."
13888 (interactive "P")
13889 (let ((pos (point)) refpos)
13890 (beginning-of-line 1)
13891 (if (bobp)
13893 (backward-char 1)
13894 (if (org-invisible-p)
13895 (while (and (not (bobp)) (org-invisible-p))
13896 (backward-char 1)
13897 (beginning-of-line 1))
13898 (forward-char 1)))
13899 (when org-special-ctrl-a/e
13900 (cond
13901 ((and (looking-at org-complex-heading-regexp)
13902 (= (char-after (match-end 1)) ?\ ))
13903 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
13904 (point-at-eol)))
13905 (goto-char
13906 (if (eq org-special-ctrl-a/e t)
13907 (cond ((> pos refpos) refpos)
13908 ((= pos (point)) refpos)
13909 (t (point)))
13910 (cond ((> pos (point)) (point))
13911 ((not (eq last-command this-command)) (point))
13912 (t refpos)))))
13913 ((org-at-item-p)
13914 (goto-char
13915 (if (eq org-special-ctrl-a/e t)
13916 (cond ((> pos (match-end 4)) (match-end 4))
13917 ((= pos (point)) (match-end 4))
13918 (t (point)))
13919 (cond ((> pos (point)) (point))
13920 ((not (eq last-command this-command)) (point))
13921 (t (match-end 4))))))))
13922 (org-no-warnings
13923 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
13925 (defun org-end-of-line (&optional arg)
13926 "Go to the end of the line.
13927 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
13928 first attempt, and only move to after the tags when the cursor is already
13929 beyond the end of the headline."
13930 (interactive "P")
13931 (if (or (not org-special-ctrl-a/e)
13932 (not (org-on-heading-p)))
13933 (end-of-line arg)
13934 (let ((pos (point)))
13935 (beginning-of-line 1)
13936 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
13937 (if (eq org-special-ctrl-a/e t)
13938 (if (or (< pos (match-beginning 1))
13939 (= pos (match-end 0)))
13940 (goto-char (match-beginning 1))
13941 (goto-char (match-end 0)))
13942 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
13943 (goto-char (match-end 0))
13944 (goto-char (match-beginning 1))))
13945 (end-of-line arg))))
13946 (org-no-warnings
13947 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
13950 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
13951 (define-key org-mode-map "\C-e" 'org-end-of-line)
13953 (defun org-kill-line (&optional arg)
13954 "Kill line, to tags or end of line."
13955 (interactive "P")
13956 (cond
13957 ((or (not org-special-ctrl-k)
13958 (bolp)
13959 (not (org-on-heading-p)))
13960 (call-interactively 'kill-line))
13961 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
13962 (kill-region (point) (match-beginning 1))
13963 (org-set-tags nil t))
13964 (t (kill-region (point) (point-at-eol)))))
13966 (define-key org-mode-map "\C-k" 'org-kill-line)
13968 (defun org-yank ()
13969 "Yank. If the kill is a subtree, treat it specially.
13970 This command will look at the current kill and check if is a single
13971 subtree, or a series of subtrees[1]. If it passes the test, and if the
13972 cursor is at the beginning of a line or after the stars of a currently
13973 empty headline, then the yank is handeled specially. How exactly depends
13974 on the value of the following variables, both 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.
13983 \[1] Basically, the test checks if the first non-white line is a heading
13984 and if there are no other headings with fewer stars."
13985 (interactive)
13986 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
13987 (and (org-kill-is-subtree-p)
13988 (or (bolp)
13989 (and (looking-at "[ \t]*$")
13990 (string-match
13991 "\\`\\*+\\'"
13992 (buffer-substring (point-at-bol) (point))))))))
13993 (cond
13994 ((and subtreep org-yank-folded-subtrees)
13995 (let ((beg (point))
13996 end)
13997 (if (and subtreep org-yank-adjusted-subtrees)
13998 (org-paste-subtree nil nil 'for-yank)
13999 (call-interactively 'yank))
14000 (setq end (point))
14001 (goto-char beg)
14002 (when (and (bolp) subtreep)
14003 (or (looking-at outline-regexp)
14004 (re-search-forward (concat "^" outline-regexp) end t))
14005 (while (and (< (point) end) (looking-at outline-regexp))
14006 (hide-subtree)
14007 (org-cycle-show-empty-lines 'folded)
14008 (condition-case nil
14009 (outline-forward-same-level 1)
14010 (error (goto-char end)))))
14011 (goto-char end)
14012 (skip-chars-forward " \t\n\r")))
14013 ((and subtreep org-yank-adjusted-subtrees)
14014 (org-paste-subtree nil nil 'for-yank))
14015 (t (call-interactively 'yank)))))
14017 (define-key org-mode-map "\C-y" 'org-yank)
14019 (defun org-invisible-p ()
14020 "Check if point is at a character currently not visible."
14021 ;; Early versions of noutline don't have `outline-invisible-p'.
14022 (if (fboundp 'outline-invisible-p)
14023 (outline-invisible-p)
14024 (get-char-property (point) 'invisible)))
14026 (defun org-invisible-p2 ()
14027 "Check if point is at a character currently not visible."
14028 (save-excursion
14029 (if (and (eolp) (not (bobp))) (backward-char 1))
14030 ;; Early versions of noutline don't have `outline-invisible-p'.
14031 (if (fboundp 'outline-invisible-p)
14032 (outline-invisible-p)
14033 (get-char-property (point) 'invisible))))
14035 (defalias 'org-back-to-heading 'outline-back-to-heading)
14036 (defalias 'org-on-heading-p 'outline-on-heading-p)
14037 (defalias 'org-at-heading-p 'outline-on-heading-p)
14038 (defun org-at-heading-or-item-p ()
14039 (or (org-on-heading-p) (org-at-item-p)))
14041 (defun org-on-target-p ()
14042 (or (org-in-regexp org-radio-target-regexp)
14043 (org-in-regexp org-target-regexp)))
14045 (defun org-up-heading-all (arg)
14046 "Move to the heading line of which the present line is a subheading.
14047 This function considers both visible and invisible heading lines.
14048 With argument, move up ARG levels."
14049 (if (fboundp 'outline-up-heading-all)
14050 (outline-up-heading-all arg) ; emacs 21 version of outline.el
14051 (outline-up-heading arg t))) ; emacs 22 version of outline.el
14053 (defun org-up-heading-safe ()
14054 "Move to the heading line of which the present line is a subheading.
14055 This version will not throw an error. It will return the level of the
14056 headline found, or nil if no higher level is found."
14057 (let ((pos (point)) start-level level
14058 (re (concat "^" outline-regexp)))
14059 (catch 'exit
14060 (outline-back-to-heading t)
14061 (setq start-level (funcall outline-level))
14062 (if (equal start-level 1) (throw 'exit nil))
14063 (while (re-search-backward re nil t)
14064 (setq level (funcall outline-level))
14065 (if (< level start-level) (throw 'exit level)))
14066 nil)))
14068 (defun org-first-sibling-p ()
14069 "Is this heading the first child of its parents?"
14070 (interactive)
14071 (let ((re (concat "^" outline-regexp))
14072 level l)
14073 (unless (org-at-heading-p t)
14074 (error "Not at a heading"))
14075 (setq level (funcall outline-level))
14076 (save-excursion
14077 (if (not (re-search-backward re nil t))
14079 (setq l (funcall outline-level))
14080 (< l level)))))
14082 (defun org-goto-sibling (&optional previous)
14083 "Goto the next sibling, even if it is invisible.
14084 When PREVIOUS is set, go to the previous sibling instead. Returns t
14085 when a sibling was found. When none is found, return nil and don't
14086 move point."
14087 (let ((fun (if previous 're-search-backward 're-search-forward))
14088 (pos (point))
14089 (re (concat "^" outline-regexp))
14090 level l)
14091 (when (condition-case nil (org-back-to-heading t) (error nil))
14092 (setq level (funcall outline-level))
14093 (catch 'exit
14094 (or previous (forward-char 1))
14095 (while (funcall fun re nil t)
14096 (setq l (funcall outline-level))
14097 (when (< l level) (goto-char pos) (throw 'exit nil))
14098 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
14099 (goto-char pos)
14100 nil))))
14102 (defun org-show-siblings ()
14103 "Show all siblings of the current headline."
14104 (save-excursion
14105 (while (org-goto-sibling) (org-flag-heading nil)))
14106 (save-excursion
14107 (while (org-goto-sibling 'previous)
14108 (org-flag-heading nil))))
14110 (defun org-show-hidden-entry ()
14111 "Show an entry where even the heading is hidden."
14112 (save-excursion
14113 (org-show-entry)))
14115 (defun org-flag-heading (flag &optional entry)
14116 "Flag the current heading. FLAG non-nil means make invisible.
14117 When ENTRY is non-nil, show the entire entry."
14118 (save-excursion
14119 (org-back-to-heading t)
14120 ;; Check if we should show the entire entry
14121 (if entry
14122 (progn
14123 (org-show-entry)
14124 (save-excursion
14125 (and (outline-next-heading)
14126 (org-flag-heading nil))))
14127 (outline-flag-region (max (point-min) (1- (point)))
14128 (save-excursion (outline-end-of-heading) (point))
14129 flag))))
14131 (defun org-forward-same-level (arg)
14132 "Move forward to the ARG'th subheading at same level as this one.
14133 Stop at the first and last subheadings of a superior heading.
14134 This is like outline-forward-same-level, but invisible headings are ok."
14135 (interactive "p")
14136 (outline-back-to-heading t)
14137 (while (> arg 0)
14138 (let ((point-to-move-to (save-excursion
14139 (org-get-next-sibling))))
14140 (if point-to-move-to
14141 (progn
14142 (goto-char point-to-move-to)
14143 (setq arg (1- arg)))
14144 (progn
14145 (setq arg 0)
14146 (error "No following same-level heading"))))))
14148 (defun org-get-next-sibling ()
14149 "Move to next heading of the same level, and return point.
14150 If there is no such heading, return nil.
14151 This is like outline-next-sibling, but invisible headings are ok."
14152 (let ((level (funcall outline-level)))
14153 (outline-next-heading)
14154 (while (and (not (eobp)) (> (funcall outline-level) level))
14155 (outline-next-heading))
14156 (if (or (eobp) (< (funcall outline-level) level))
14158 (point))))
14160 (defun org-end-of-subtree (&optional invisible-OK to-heading)
14161 ;; This is an exact copy of the original function, but it uses
14162 ;; `org-back-to-heading', to make it work also in invisible
14163 ;; trees. And is uses an invisible-OK argument.
14164 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
14165 (org-back-to-heading invisible-OK)
14166 (let ((first t)
14167 (level (funcall outline-level)))
14168 (while (and (not (eobp))
14169 (or first (> (funcall outline-level) level)))
14170 (setq first nil)
14171 (outline-next-heading))
14172 (unless to-heading
14173 (if (memq (preceding-char) '(?\n ?\^M))
14174 (progn
14175 ;; Go to end of line before heading
14176 (forward-char -1)
14177 (if (memq (preceding-char) '(?\n ?\^M))
14178 ;; leave blank line before heading
14179 (forward-char -1))))))
14180 (point))
14182 (defun org-show-subtree ()
14183 "Show everything after this heading at deeper levels."
14184 (outline-flag-region
14185 (point)
14186 (save-excursion
14187 (outline-end-of-subtree) (outline-next-heading) (point))
14188 nil))
14190 (defun org-show-entry ()
14191 "Show the body directly following this heading.
14192 Show the heading too, if it is currently invisible."
14193 (interactive)
14194 (save-excursion
14195 (condition-case nil
14196 (progn
14197 (org-back-to-heading t)
14198 (outline-flag-region
14199 (max (point-min) (1- (point)))
14200 (save-excursion
14201 (re-search-forward
14202 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
14203 (or (match-beginning 1) (point-max)))
14204 nil))
14205 (error nil))))
14207 (defun org-make-options-regexp (kwds)
14208 "Make a regular expression for keyword lines."
14209 (concat
14211 "#?[ \t]*\\+\\("
14212 (mapconcat 'regexp-quote kwds "\\|")
14213 "\\):[ \t]*"
14214 "\\(.+\\)"))
14216 ;; Make isearch reveal the necessary context
14217 (defun org-isearch-end ()
14218 "Reveal context after isearch exits."
14219 (when isearch-success ; only if search was successful
14220 (if (featurep 'xemacs)
14221 ;; Under XEmacs, the hook is run in the correct place,
14222 ;; we directly show the context.
14223 (org-show-context 'isearch)
14224 ;; In Emacs the hook runs *before* restoring the overlays.
14225 ;; So we have to use a one-time post-command-hook to do this.
14226 ;; (Emacs 22 has a special variable, see function `org-mode')
14227 (unless (and (boundp 'isearch-mode-end-hook-quit)
14228 isearch-mode-end-hook-quit)
14229 ;; Only when the isearch was not quitted.
14230 (org-add-hook 'post-command-hook 'org-isearch-post-command
14231 'append 'local)))))
14233 (defun org-isearch-post-command ()
14234 "Remove self from hook, and show context."
14235 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
14236 (org-show-context 'isearch))
14239 ;;;; Integration with and fixes for other packages
14241 ;;; Imenu support
14243 (defvar org-imenu-markers nil
14244 "All markers currently used by Imenu.")
14245 (make-variable-buffer-local 'org-imenu-markers)
14247 (defun org-imenu-new-marker (&optional pos)
14248 "Return a new marker for use by Imenu, and remember the marker."
14249 (let ((m (make-marker)))
14250 (move-marker m (or pos (point)))
14251 (push m org-imenu-markers)
14254 (defun org-imenu-get-tree ()
14255 "Produce the index for Imenu."
14256 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
14257 (setq org-imenu-markers nil)
14258 (let* ((n org-imenu-depth)
14259 (re (concat "^" outline-regexp))
14260 (subs (make-vector (1+ n) nil))
14261 (last-level 0)
14262 m tree level head)
14263 (save-excursion
14264 (save-restriction
14265 (widen)
14266 (goto-char (point-max))
14267 (while (re-search-backward re nil t)
14268 (setq level (org-reduced-level (funcall outline-level)))
14269 (when (<= level n)
14270 (looking-at org-complex-heading-regexp)
14271 (setq head (org-link-display-format
14272 (org-match-string-no-properties 4))
14273 m (org-imenu-new-marker))
14274 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
14275 (if (>= level last-level)
14276 (push (cons head m) (aref subs level))
14277 (push (cons head (aref subs (1+ level))) (aref subs level))
14278 (loop for i from (1+ level) to n do (aset subs i nil)))
14279 (setq last-level level)))))
14280 (aref subs 1)))
14282 (eval-after-load "imenu"
14283 '(progn
14284 (add-hook 'imenu-after-jump-hook
14285 (lambda ()
14286 (if (eq major-mode 'org-mode)
14287 (org-show-context 'org-goto))))))
14289 (defun org-link-display-format (link)
14290 "Replace a link with either the description, or the link target
14291 if no description is present"
14292 (save-match-data
14293 (if (string-match org-bracket-link-analytic-regexp link)
14294 (replace-match (or (match-string 5 link)
14295 (concat (match-string 1 link)
14296 (match-string 3 link)))
14297 nil nil link)
14298 link)))
14300 ;; Speedbar support
14302 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
14303 "Overlay marking the agenda restriction line in speedbar.")
14304 (org-overlay-put org-speedbar-restriction-lock-overlay
14305 'face 'org-agenda-restriction-lock)
14306 (org-overlay-put org-speedbar-restriction-lock-overlay
14307 'help-echo "Agendas are currently limited to this item.")
14308 (org-detach-overlay org-speedbar-restriction-lock-overlay)
14310 (defun org-speedbar-set-agenda-restriction ()
14311 "Restrict future agenda commands to the location at point in speedbar.
14312 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
14313 (interactive)
14314 (require 'org-agenda)
14315 (let (p m tp np dir txt w)
14316 (cond
14317 ((setq p (text-property-any (point-at-bol) (point-at-eol)
14318 'org-imenu t))
14319 (setq m (get-text-property p 'org-imenu-marker))
14320 (save-excursion
14321 (save-restriction
14322 (set-buffer (marker-buffer m))
14323 (goto-char m)
14324 (org-agenda-set-restriction-lock 'subtree))))
14325 ((setq p (text-property-any (point-at-bol) (point-at-eol)
14326 'speedbar-function 'speedbar-find-file))
14327 (setq tp (previous-single-property-change
14328 (1+ p) 'speedbar-function)
14329 np (next-single-property-change
14330 tp 'speedbar-function)
14331 dir (speedbar-line-directory)
14332 txt (buffer-substring-no-properties (or tp (point-min))
14333 (or np (point-max))))
14334 (save-excursion
14335 (save-restriction
14336 (set-buffer (find-file-noselect
14337 (let ((default-directory dir))
14338 (expand-file-name txt))))
14339 (unless (org-mode-p)
14340 (error "Cannot restrict to non-Org-mode file"))
14341 (org-agenda-set-restriction-lock 'file))))
14342 (t (error "Don't know how to restrict Org-mode's agenda")))
14343 (org-move-overlay org-speedbar-restriction-lock-overlay
14344 (point-at-bol) (point-at-eol))
14345 (setq current-prefix-arg nil)
14346 (org-agenda-maybe-redo)))
14348 (eval-after-load "speedbar"
14349 '(progn
14350 (speedbar-add-supported-extension ".org")
14351 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
14352 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
14353 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
14354 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
14355 (add-hook 'speedbar-visiting-tag-hook
14356 (lambda () (org-show-context 'org-goto)))))
14359 ;;; Fixes and Hacks for problems with other packages
14361 ;; Make flyspell not check words in links, to not mess up our keymap
14362 (defun org-mode-flyspell-verify ()
14363 "Don't let flyspell put overlays at active buttons."
14364 (not (get-text-property (point) 'keymap)))
14366 ;; Make `bookmark-jump' show the jump location if it was hidden.
14367 (eval-after-load "bookmark"
14368 '(if (boundp 'bookmark-after-jump-hook)
14369 ;; We can use the hook
14370 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
14371 ;; Hook not available, use advice
14372 (defadvice bookmark-jump (after org-make-visible activate)
14373 "Make the position visible."
14374 (org-bookmark-jump-unhide))))
14376 ;; Make sure saveplace show the location if it was hidden
14377 (eval-after-load "saveplace"
14378 '(defadvice save-place-find-file-hook (after org-make-visible activate)
14379 "Make the position visible."
14380 (org-bookmark-jump-unhide)))
14382 (defun org-bookmark-jump-unhide ()
14383 "Unhide the current position, to show the bookmark location."
14384 (and (org-mode-p)
14385 (or (org-invisible-p)
14386 (save-excursion (goto-char (max (point-min) (1- (point))))
14387 (org-invisible-p)))
14388 (org-show-context 'bookmark-jump)))
14390 ;; Make session.el ignore our circular variable
14391 (eval-after-load "session"
14392 '(add-to-list 'session-globals-exclude 'org-mark-ring))
14394 ;;;; Experimental code
14396 (defun org-closed-in-range ()
14397 "Sparse tree of items closed in a certain time range.
14398 Still experimental, may disappear in the future."
14399 (interactive)
14400 ;; Get the time interval from the user.
14401 (let* ((time1 (time-to-seconds
14402 (org-read-date nil 'to-time nil "Starting date: ")))
14403 (time2 (time-to-seconds
14404 (org-read-date nil 'to-time nil "End date:")))
14405 ;; callback function
14406 (callback (lambda ()
14407 (let ((time
14408 (time-to-seconds
14409 (apply 'encode-time
14410 (org-parse-time-string
14411 (match-string 1))))))
14412 ;; check if time in interval
14413 (and (>= time time1) (<= time time2))))))
14414 ;; make tree, check each match with the callback
14415 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
14418 ;;;; Finish up
14420 (provide 'org)
14422 (run-hooks 'org-load-hook)
14424 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
14426 ;;; org.el ends here