Fix issues with property time tests.
[org-mode.git] / lisp / org.el
bloba890d1fac1817eb2b63a7af249fd72fb5c711583
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.12b
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.12b"
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-modules'."
129 (when (or force (not org-modules-loaded))
130 (mapc (lambda (ext)
131 (condition-case nil (require ext)
132 (error (message "Problems while trying to load feature `%s'" ext))))
133 org-modules)
134 (setq org-modules-loaded t)))
136 (defun org-set-modules (var value)
137 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
138 (set var value)
139 (when (featurep 'org)
140 (org-load-modules-maybe 'force)))
142 (when (org-bound-and-true-p org-modules)
143 (let ((a (member 'org-infojs org-modules)))
144 (and a (setcar a 'org-jsinfo))))
146 (defcustom org-modules '(org-bbdb org-bibtex org-gnus org-info org-jsinfo org-irc org-mew org-mhe org-rmail org-vm org-wl)
147 "Modules that should always be loaded together with org.el.
148 If a description starts with <C>, the file is not part of Emacs
149 and loading it will require that you have downloaded and properly installed
150 the org-mode distribution.
152 You can also use this system to load external packages (i.e. neither Org
153 core modules, not modules from the CONTRIB directory). Just add symbols
154 to the end of the list. If the package is called org-xyz.el, then you need
155 to add the symbol `xyz', and the package must have a call to
157 (provide 'org-xyz)"
158 :group 'org
159 :set 'org-set-modules
160 :type
161 '(set :greedy t
162 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
163 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
164 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
165 (const :tag " id: Global id's for identifying entries" org-id)
166 (const :tag " info: Links to Info nodes" org-info)
167 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
168 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
169 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
170 (const :tag " mew Links to Mew folders/messages" org-mew)
171 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
172 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
173 (const :tag " vm: Links to VM folders/messages" org-vm)
174 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
175 (const :tag " mouse: Additional mouse support" org-mouse)
177 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
178 (const :tag "C annotation-helper: Call Remeber directly from Browser" org-annotation-helper)
179 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
180 (const :tag "C depend: TODO dependencies for Org-mode" org-depend)
181 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
182 (const :tag "C eval: Include command output as text" org-eval)
183 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
184 (const :tag "C id: Global id's for identifying entries" org-id)
185 (const :tag "C interactive-query: Interactive modification of tags query" org-interactive-query)
186 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
187 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
188 (const :tag "C mtags: Support for muse-like tags" org-mtags)
189 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
190 (const :tag "C registry: A registry for Org links" org-registry)
191 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
192 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
193 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
194 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
195 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
198 (defgroup org-startup nil
199 "Options concerning startup of Org-mode."
200 :tag "Org Startup"
201 :group 'org)
203 (defcustom org-startup-folded t
204 "Non-nil means, entering Org-mode will switch to OVERVIEW.
205 This can also be configured on a per-file basis by adding one of
206 the following lines anywhere in the buffer:
208 #+STARTUP: fold
209 #+STARTUP: nofold
210 #+STARTUP: content"
211 :group 'org-startup
212 :type '(choice
213 (const :tag "nofold: show all" nil)
214 (const :tag "fold: overview" t)
215 (const :tag "content: all headlines" content)))
217 (defcustom org-startup-truncated t
218 "Non-nil means, entering Org-mode will set `truncate-lines'.
219 This is useful since some lines containing links can be very long and
220 uninteresting. Also tables look terrible when wrapped."
221 :group 'org-startup
222 :type 'boolean)
224 (defcustom org-startup-align-all-tables nil
225 "Non-nil means, align all tables when visiting a file.
226 This is useful when the column width in tables is forced with <N> cookies
227 in table fields. Such tables will look correct only after the first re-align.
228 This can also be configured on a per-file basis by adding one of
229 the following lines anywhere in the buffer:
230 #+STARTUP: align
231 #+STARTUP: noalign"
232 :group 'org-startup
233 :type 'boolean)
235 (defcustom org-insert-mode-line-in-empty-file nil
236 "Non-nil means insert the first line setting Org-mode in empty files.
237 When the function `org-mode' is called interactively in an empty file, this
238 normally means that the file name does not automatically trigger Org-mode.
239 To ensure that the file will always be in Org-mode in the future, a
240 line enforcing Org-mode will be inserted into the buffer, if this option
241 has been set."
242 :group 'org-startup
243 :type 'boolean)
245 (defcustom org-replace-disputed-keys nil
246 "Non-nil means use alternative key bindings for some keys.
247 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
248 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
249 If you want to use Org-mode together with one of these other modes,
250 or more generally if you would like to move some Org-mode commands to
251 other keys, set this variable and configure the keys with the variable
252 `org-disputed-keys'.
254 This option is only relevant at load-time of Org-mode, and must be set
255 *before* org.el is loaded. Changing it requires a restart of Emacs to
256 become effective."
257 :group 'org-startup
258 :type 'boolean)
260 (defcustom org-use-extra-keys nil
261 "Non-nil means use extra key sequence definitions for certain
262 commands. This happens automatically if you run XEmacs or if
263 window-system is nil. This variable lets you do the same
264 manually. You must set it before loading org.
266 Example: on Carbon Emacs 22 running graphically, with an external
267 keyboard on a Powerbook, the default way of setting M-left might
268 not work for either Alt or ESC. Setting this variable will make
269 it work for ESC."
270 :group 'org-startup
271 :type 'boolean)
273 (if (fboundp 'defvaralias)
274 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
276 (defcustom org-disputed-keys
277 '(([(shift up)] . [(meta p)])
278 ([(shift down)] . [(meta n)])
279 ([(shift left)] . [(meta -)])
280 ([(shift right)] . [(meta +)])
281 ([(control shift right)] . [(meta shift +)])
282 ([(control shift left)] . [(meta shift -)]))
283 "Keys for which Org-mode and other modes compete.
284 This is an alist, cars are the default keys, second element specifies
285 the alternative to use when `org-replace-disputed-keys' is t.
287 Keys can be specified in any syntax supported by `define-key'.
288 The value of this option takes effect only at Org-mode's startup,
289 therefore you'll have to restart Emacs to apply it after changing."
290 :group 'org-startup
291 :type 'alist)
293 (defun org-key (key)
294 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
295 Or return the original if not disputed."
296 (if org-replace-disputed-keys
297 (let* ((nkey (key-description key))
298 (x (org-find-if (lambda (x)
299 (equal (key-description (car x)) nkey))
300 org-disputed-keys)))
301 (if x (cdr x) key))
302 key))
304 (defun org-find-if (predicate seq)
305 (catch 'exit
306 (while seq
307 (if (funcall predicate (car seq))
308 (throw 'exit (car seq))
309 (pop seq)))))
311 (defun org-defkey (keymap key def)
312 "Define a key, possibly translated, as returned by `org-key'."
313 (define-key keymap (org-key key) def))
315 (defcustom org-ellipsis nil
316 "The ellipsis to use in the Org-mode outline.
317 When nil, just use the standard three dots. When a string, use that instead,
318 When a face, use the standart 3 dots, but with the specified face.
319 The change affects only Org-mode (which will then use its own display table).
320 Changing this requires executing `M-x org-mode' in a buffer to become
321 effective."
322 :group 'org-startup
323 :type '(choice (const :tag "Default" nil)
324 (face :tag "Face" :value org-warning)
325 (string :tag "String" :value "...#")))
327 (defvar org-display-table nil
328 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
330 (defgroup org-keywords nil
331 "Keywords in Org-mode."
332 :tag "Org Keywords"
333 :group 'org)
335 (defcustom org-deadline-string "DEADLINE:"
336 "String to mark deadline entries.
337 A deadline is this string, followed by a time stamp. Should be a word,
338 terminated by a colon. You can insert a schedule keyword and
339 a timestamp with \\[org-deadline].
340 Changes become only effective after restarting Emacs."
341 :group 'org-keywords
342 :type 'string)
344 (defcustom org-scheduled-string "SCHEDULED:"
345 "String to mark scheduled TODO entries.
346 A schedule is this string, followed by a time stamp. Should be a word,
347 terminated by a colon. You can insert a schedule keyword and
348 a timestamp with \\[org-schedule].
349 Changes become only effective after restarting Emacs."
350 :group 'org-keywords
351 :type 'string)
353 (defcustom org-closed-string "CLOSED:"
354 "String used as the prefix for timestamps logging closing a TODO entry."
355 :group 'org-keywords
356 :type 'string)
358 (defcustom org-clock-string "CLOCK:"
359 "String used as prefix for timestamps clocking work hours on an item."
360 :group 'org-keywords
361 :type 'string)
363 (defcustom org-comment-string "COMMENT"
364 "Entries starting with this keyword will never be exported.
365 An entry can be toggled between COMMENT and normal with
366 \\[org-toggle-comment].
367 Changes become only effective after restarting Emacs."
368 :group 'org-keywords
369 :type 'string)
371 (defcustom org-quote-string "QUOTE"
372 "Entries starting with this keyword will be exported in fixed-width font.
373 Quoting applies only to the text in the entry following the headline, and does
374 not extend beyond the next headline, even if that is lower level.
375 An entry can be toggled between QUOTE and normal with
376 \\[org-toggle-fixed-width-section]."
377 :group 'org-keywords
378 :type 'string)
380 (defconst org-repeat-re
381 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\([.+]?\\+[0-9]+[dwmy]\\)"
382 "Regular expression for specifying repeated events.
383 After a match, group 1 contains the repeat expression.")
385 (defgroup org-structure nil
386 "Options concerning the general structure of Org-mode files."
387 :tag "Org Structure"
388 :group 'org)
390 (defgroup org-reveal-location nil
391 "Options about how to make context of a location visible."
392 :tag "Org Reveal Location"
393 :group 'org-structure)
395 (defconst org-context-choice
396 '(choice
397 (const :tag "Always" t)
398 (const :tag "Never" nil)
399 (repeat :greedy t :tag "Individual contexts"
400 (cons
401 (choice :tag "Context"
402 (const agenda)
403 (const org-goto)
404 (const occur-tree)
405 (const tags-tree)
406 (const link-search)
407 (const mark-goto)
408 (const bookmark-jump)
409 (const isearch)
410 (const default))
411 (boolean))))
412 "Contexts for the reveal options.")
414 (defcustom org-show-hierarchy-above '((default . t))
415 "Non-nil means, show full hierarchy when revealing a location.
416 Org-mode often shows locations in an org-mode file which might have
417 been invisible before. When this is set, the hierarchy of headings
418 above the exposed location is shown.
419 Turning this off for example for sparse trees makes them very compact.
420 Instead of t, this can also be an alist specifying this option for different
421 contexts. Valid contexts are
422 agenda when exposing an entry from the agenda
423 org-goto when using the command `org-goto' on key C-c C-j
424 occur-tree when using the command `org-occur' on key C-c /
425 tags-tree when constructing a sparse tree based on tags matches
426 link-search when exposing search matches associated with a link
427 mark-goto when exposing the jump goal of a mark
428 bookmark-jump when exposing a bookmark location
429 isearch when exiting from an incremental search
430 default default for all contexts not set explicitly"
431 :group 'org-reveal-location
432 :type org-context-choice)
434 (defcustom org-show-following-heading '((default . nil))
435 "Non-nil means, show following heading when revealing a location.
436 Org-mode often shows locations in an org-mode file which might have
437 been invisible before. When this is set, the heading following the
438 match is shown.
439 Turning this off for example for sparse trees makes them very compact,
440 but makes it harder to edit the location of the match. In such a case,
441 use the command \\[org-reveal] to show more context.
442 Instead of t, this can also be an alist specifying this option for different
443 contexts. See `org-show-hierarchy-above' for valid contexts."
444 :group 'org-reveal-location
445 :type org-context-choice)
447 (defcustom org-show-siblings '((default . nil) (isearch t))
448 "Non-nil means, show all sibling heading when revealing a location.
449 Org-mode often shows locations in an org-mode file which might have
450 been invisible before. When this is set, the sibling of the current entry
451 heading are all made visible. If `org-show-hierarchy-above' is t,
452 the same happens on each level of the hierarchy above the current entry.
454 By default this is on for the isearch context, off for all other contexts.
455 Turning this off for example for sparse trees makes them very compact,
456 but makes it harder to edit the location of the match. In such a case,
457 use the command \\[org-reveal] to show more context.
458 Instead of t, this can also be an alist specifying this option for different
459 contexts. See `org-show-hierarchy-above' for valid contexts."
460 :group 'org-reveal-location
461 :type org-context-choice)
463 (defcustom org-show-entry-below '((default . nil))
464 "Non-nil means, show the entry below a headline when revealing a location.
465 Org-mode often shows locations in an org-mode file which might have
466 been invisible before. When this is set, the text below the headline that is
467 exposed is also shown.
469 By default this is off for all contexts.
470 Instead of t, this can also be an alist specifying this option for different
471 contexts. See `org-show-hierarchy-above' for valid contexts."
472 :group 'org-reveal-location
473 :type org-context-choice)
475 (defcustom org-indirect-buffer-display 'other-window
476 "How should indirect tree buffers be displayed?
477 This applies to indirect buffers created with the commands
478 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
479 Valid values are:
480 current-window Display in the current window
481 other-window Just display in another window.
482 dedicated-frame Create one new frame, and re-use it each time.
483 new-frame Make a new frame each time. Note that in this case
484 previously-made indirect buffers are kept, and you need to
485 kill these buffers yourself."
486 :group 'org-structure
487 :group 'org-agenda-windows
488 :type '(choice
489 (const :tag "In current window" current-window)
490 (const :tag "In current frame, other window" other-window)
491 (const :tag "Each time a new frame" new-frame)
492 (const :tag "One dedicated frame" dedicated-frame)))
494 (defgroup org-cycle nil
495 "Options concerning visibility cycling in Org-mode."
496 :tag "Org Cycle"
497 :group 'org-structure)
499 (defcustom org-drawers '("PROPERTIES" "CLOCK")
500 "Names of drawers. Drawers are not opened by cycling on the headline above.
501 Drawers only open with a TAB on the drawer line itself. A drawer looks like
502 this:
503 :DRAWERNAME:
504 .....
505 :END:
506 The drawer \"PROPERTIES\" is special for capturing properties through
507 the property API.
509 Drawers can be defined on the per-file basis with a line like:
511 #+DRAWERS: HIDDEN STATE PROPERTIES"
512 :group 'org-structure
513 :type '(repeat (string :tag "Drawer Name")))
515 (defcustom org-cycle-global-at-bob nil
516 "Cycle globally if cursor is at beginning of buffer and not at a headline.
517 This makes it possible to do global cycling without having to use S-TAB or
518 C-u TAB. For this special case to work, the first line of the buffer
519 must not be a headline - it may be empty ot some other text. When used in
520 this way, `org-cycle-hook' is disables temporarily, to make sure the
521 cursor stays at the beginning of the buffer.
522 When this option is nil, don't do anything special at the beginning
523 of the buffer."
524 :group 'org-cycle
525 :type 'boolean)
527 (defcustom org-cycle-emulate-tab t
528 "Where should `org-cycle' emulate TAB.
529 nil Never
530 white Only in completely white lines
531 whitestart Only at the beginning of lines, before the first non-white char
532 t Everywhere except in headlines
533 exc-hl-bol Everywhere except at the start of a headline
534 If TAB is used in a place where it does not emulate TAB, the current subtree
535 visibility is cycled."
536 :group 'org-cycle
537 :type '(choice (const :tag "Never" nil)
538 (const :tag "Only in completely white lines" white)
539 (const :tag "Before first char in a line" whitestart)
540 (const :tag "Everywhere except in headlines" t)
541 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
544 (defcustom org-cycle-separator-lines 2
545 "Number of empty lines needed to keep an empty line between collapsed trees.
546 If you leave an empty line between the end of a subtree and the following
547 headline, this empty line is hidden when the subtree is folded.
548 Org-mode will leave (exactly) one empty line visible if the number of
549 empty lines is equal or larger to the number given in this variable.
550 So the default 2 means, at least 2 empty lines after the end of a subtree
551 are needed to produce free space between a collapsed subtree and the
552 following headline.
554 Special case: when 0, never leave empty lines in collapsed view."
555 :group 'org-cycle
556 :type 'integer)
557 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
559 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
560 org-cycle-hide-drawers
561 org-cycle-show-empty-lines
562 org-optimize-window-after-visibility-change)
563 "Hook that is run after `org-cycle' has changed the buffer visibility.
564 The function(s) in this hook must accept a single argument which indicates
565 the new state that was set by the most recent `org-cycle' command. The
566 argument is a symbol. After a global state change, it can have the values
567 `overview', `content', or `all'. After a local state change, it can have
568 the values `folded', `children', or `subtree'."
569 :group 'org-cycle
570 :type 'hook)
572 (defgroup org-edit-structure nil
573 "Options concerning structure editing in Org-mode."
574 :tag "Org Edit Structure"
575 :group 'org-structure)
577 (defcustom org-odd-levels-only nil
578 "Non-nil means, skip even levels and only use odd levels for the outline.
579 This has the effect that two stars are being added/taken away in
580 promotion/demotion commands. It also influences how levels are
581 handled by the exporters.
582 Changing it requires restart of `font-lock-mode' to become effective
583 for fontification also in regions already fontified.
584 You may also set this on a per-file basis by adding one of the following
585 lines to the buffer:
587 #+STARTUP: odd
588 #+STARTUP: oddeven"
589 :group 'org-edit-structure
590 :group 'org-font-lock
591 :type 'boolean)
593 (defcustom org-adapt-indentation t
594 "Non-nil means, adapt indentation when promoting and demoting.
595 When this is set and the *entire* text in an entry is indented, the
596 indentation is increased by one space in a demotion command, and
597 decreased by one in a promotion command. If any line in the entry
598 body starts at column 0, indentation is not changed at all."
599 :group 'org-edit-structure
600 :type 'boolean)
602 (defcustom org-special-ctrl-a/e nil
603 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
604 When t, `C-a' will bring back the cursor to the beginning of the
605 headline text, i.e. after the stars and after a possible TODO keyword.
606 In an item, this will be the position after the bullet.
607 When the cursor is already at that position, another `C-a' will bring
608 it to the beginning of the line.
609 `C-e' will jump to the end of the headline, ignoring the presence of tags
610 in the headline. A second `C-e' will then jump to the true end of the
611 line, after any tags.
612 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
613 and only a directly following, identical keypress will bring the cursor
614 to the special positions."
615 :group 'org-edit-structure
616 :type '(choice
617 (const :tag "off" nil)
618 (const :tag "after bullet first" t)
619 (const :tag "border first" reversed)))
621 (if (fboundp 'defvaralias)
622 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
624 (defcustom org-special-ctrl-k nil
625 "Non-nil means `C-k' will behave specially in headlines.
626 When nil, `C-k' will call the default `kill-line' command.
627 When t, the following will happen while the cursor is in the headline:
629 - When the cursor is at the beginning of a headline, kill the entire
630 line and possible the folded subtree below the line.
631 - When in the middle of the headline text, kill the headline up to the tags.
632 - When after the headline text, kill the tags."
633 :group 'org-edit-structure
634 :type 'boolean)
636 (defcustom org-yank-folded-subtrees t
637 "Non-nil means, when yanking subtrees, fold them.
638 If the kill is a single subtree, or a sequence of subtrees, i.e. if
639 it starts with a heading and all other headings in it are either children
640 or siblings, then fold all the subtrees. However, do this only if no
641 text after the yank would be swallowed into a folded tree by this action."
642 :group 'org-edit-structure
643 :type 'boolean)
645 (defcustom org-yank-adjusted-subtrees t
646 "Non-nil means, when yanking subtrees, adjust the level.
647 With this setting, `org-paste-subtree' is used to insert the subtree, see
648 this function for details."
649 :group 'org-edit-structure
650 :type 'boolean)
652 (defcustom org-M-RET-may-split-line '((default . t))
653 "Non-nil means, M-RET will split the line at the cursor position.
654 When nil, it will go to the end of the line before making a
655 new line.
656 You may also set this option in a different way for different
657 contexts. Valid contexts are:
659 headline when creating a new headline
660 item when creating a new item
661 table in a table field
662 default the value to be used for all contexts not explicitly
663 customized"
664 :group 'org-structure
665 :group 'org-table
666 :type '(choice
667 (const :tag "Always" t)
668 (const :tag "Never" nil)
669 (repeat :greedy t :tag "Individual contexts"
670 (cons
671 (choice :tag "Context"
672 (const headline)
673 (const item)
674 (const table)
675 (const default))
676 (boolean)))))
679 (defcustom org-insert-heading-respect-content nil
680 "Non-nil means, insert new headings after the current subtree.
681 When nil, the new heading is created directly after the current line.
682 The commands \\[org-insert-heading-respect-content] and
683 \\[org-insert-todo-heading-respect-content] turn this variable on
684 for the duration of the command."
685 :group 'org-structure
686 :type 'boolean)
688 (defcustom org-blank-before-new-entry '((heading . nil)
689 (plain-list-item . nil))
690 "Should `org-insert-heading' leave a blank line before new heading/item?
691 The value is an alist, with `heading' and `plain-list-item' as car,
692 and a boolean flag as cdr."
693 :group 'org-edit-structure
694 :type '(list
695 (cons (const heading) (boolean))
696 (cons (const plain-list-item) (boolean))))
698 (defcustom org-insert-heading-hook nil
699 "Hook being run after inserting a new heading."
700 :group 'org-edit-structure
701 :type 'hook)
703 (defcustom org-enable-fixed-width-editor t
704 "Non-nil means, lines starting with \":\" are treated as fixed-width.
705 This currently only means, they are never auto-wrapped.
706 When nil, such lines will be treated like ordinary lines.
707 See also the QUOTE keyword."
708 :group 'org-edit-structure
709 :type 'boolean)
711 (defcustom org-edit-src-region-extra nil
712 "Additional regexps to identify regions for editing with `org-edit-src-code'.
713 For examples see the function `org-edit-src-find-region-and-lang'.
714 The regular expression identifying the begin marker should end with a newline,
715 and the regexp marking the end line should start with a newline, to make sure
716 there are kept outside the narrowed region."
717 :group 'org-edit-structure
718 :type '(repeat
719 (list
720 (regexp :tag "begin regexp")
721 (regexp :tag "end regexp")
722 (choice :tag "language"
723 (string :tag "specify")
724 (integer :tag "from match group")
725 (const :tag "from `lang' element")
726 (const :tag "from `style' element")))))
728 (defcustom org-edit-fixed-width-region-mode 'artist-mode
729 "The mode that should be used to edit fixed-width regions.
730 These are the regions where each line starts with a colon."
731 :group 'org-edit-structure
732 :type '(choice
733 (const artist-mode)
734 (const picture-mode)
735 (const fundamental-mode)
736 (function :tag "Other (specify)")))
738 (defcustom org-goto-auto-isearch t
739 "Non-nil means, typing characters in org-goto starts incremental search."
740 :group 'org-edit-structure
741 :type 'boolean)
743 (defgroup org-sparse-trees nil
744 "Options concerning sparse trees in Org-mode."
745 :tag "Org Sparse Trees"
746 :group 'org-structure)
748 (defcustom org-highlight-sparse-tree-matches t
749 "Non-nil means, highlight all matches that define a sparse tree.
750 The highlights will automatically disappear the next time the buffer is
751 changed by an edit command."
752 :group 'org-sparse-trees
753 :type 'boolean)
755 (defcustom org-remove-highlights-with-change t
756 "Non-nil means, any change to the buffer will remove temporary highlights.
757 Such highlights are created by `org-occur' and `org-clock-display'.
758 When nil, `C-c C-c needs to be used to get rid of the highlights.
759 The highlights created by `org-preview-latex-fragment' always need
760 `C-c C-c' to be removed."
761 :group 'org-sparse-trees
762 :group 'org-time
763 :type 'boolean)
766 (defcustom org-occur-hook '(org-first-headline-recenter)
767 "Hook that is run after `org-occur' has constructed a sparse tree.
768 This can be used to recenter the window to show as much of the structure
769 as possible."
770 :group 'org-sparse-trees
771 :type 'hook)
773 (defgroup org-imenu-and-speedbar nil
774 "Options concerning imenu and speedbar in Org-mode."
775 :tag "Org Imenu and Speedbar"
776 :group 'org-structure)
778 (defcustom org-imenu-depth 2
779 "The maximum level for Imenu access to Org-mode headlines.
780 This also applied for speedbar access."
781 :group 'org-imenu-and-speedbar
782 :type 'number)
784 (defgroup org-table nil
785 "Options concerning tables in Org-mode."
786 :tag "Org Table"
787 :group 'org)
789 (defcustom org-enable-table-editor 'optimized
790 "Non-nil means, lines starting with \"|\" are handled by the table editor.
791 When nil, such lines will be treated like ordinary lines.
793 When equal to the symbol `optimized', the table editor will be optimized to
794 do the following:
795 - Automatic overwrite mode in front of whitespace in table fields.
796 This makes the structure of the table stay in tact as long as the edited
797 field does not exceed the column width.
798 - Minimize the number of realigns. Normally, the table is aligned each time
799 TAB or RET are pressed to move to another field. With optimization this
800 happens only if changes to a field might have changed the column width.
801 Optimization requires replacing the functions `self-insert-command',
802 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
803 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
804 very good at guessing when a re-align will be necessary, but you can always
805 force one with \\[org-ctrl-c-ctrl-c].
807 If you would like to use the optimized version in Org-mode, but the
808 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
810 This variable can be used to turn on and off the table editor during a session,
811 but in order to toggle optimization, a restart is required.
813 See also the variable `org-table-auto-blank-field'."
814 :group 'org-table
815 :type '(choice
816 (const :tag "off" nil)
817 (const :tag "on" t)
818 (const :tag "on, optimized" optimized)))
820 (defcustom org-table-tab-recognizes-table.el t
821 "Non-nil means, TAB will automatically notice a table.el table.
822 When it sees such a table, it moves point into it and - if necessary -
823 calls `table-recognize-table'."
824 :group 'org-table-editing
825 :type 'boolean)
827 (defgroup org-link nil
828 "Options concerning links in Org-mode."
829 :tag "Org Link"
830 :group 'org)
832 (defvar org-link-abbrev-alist-local nil
833 "Buffer-local version of `org-link-abbrev-alist', which see.
834 The value of this is taken from the #+LINK lines.")
835 (make-variable-buffer-local 'org-link-abbrev-alist-local)
837 (defcustom org-link-abbrev-alist nil
838 "Alist of link abbreviations.
839 The car of each element is a string, to be replaced at the start of a link.
840 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
841 links in Org-mode buffers can have an optional tag after a double colon, e.g.
843 [[linkkey:tag][description]]
845 If REPLACE is a string, the tag will simply be appended to create the link.
846 If the string contains \"%s\", the tag will be inserted there. Alternatively,
847 the placeholder \"%h\" will cause a url-encoded version of the tag to
848 be inserted at that point (see the function `url-hexify-string').
850 REPLACE may also be a function that will be called with the tag as the
851 only argument to create the link, which should be returned as a string.
853 See the manual for examples."
854 :group 'org-link
855 :type '(repeat
856 (cons
857 (string :tag "Protocol")
858 (choice
859 (string :tag "Format")
860 (function)))))
862 (defcustom org-descriptive-links t
863 "Non-nil means, hide link part and only show description of bracket links.
864 Bracket links are like [[link][descritpion]]. This variable sets the initial
865 state in new org-mode buffers. The setting can then be toggled on a
866 per-buffer basis from the Org->Hyperlinks menu."
867 :group 'org-link
868 :type 'boolean)
870 (defcustom org-link-file-path-type 'adaptive
871 "How the path name in file links should be stored.
872 Valid values are:
874 relative Relative to the current directory, i.e. the directory of the file
875 into which the link is being inserted.
876 absolute Absolute path, if possible with ~ for home directory.
877 noabbrev Absolute path, no abbreviation of home directory.
878 adaptive Use relative path for files in the current directory and sub-
879 directories of it. For other files, use an absolute path."
880 :group 'org-link
881 :type '(choice
882 (const relative)
883 (const absolute)
884 (const noabbrev)
885 (const adaptive)))
887 (defcustom org-activate-links '(bracket angle plain radio tag date)
888 "Types of links that should be activated in Org-mode files.
889 This is a list of symbols, each leading to the activation of a certain link
890 type. In principle, it does not hurt to turn on most link types - there may
891 be a small gain when turning off unused link types. The types are:
893 bracket The recommended [[link][description]] or [[link]] links with hiding.
894 angular Links in angular brackes that may contain whitespace like
895 <bbdb:Carsten Dominik>.
896 plain Plain links in normal text, no whitespace, like http://google.com.
897 radio Text that is matched by a radio target, see manual for details.
898 tag Tag settings in a headline (link to tag search).
899 date Time stamps (link to calendar).
901 Changing this variable requires a restart of Emacs to become effective."
902 :group 'org-link
903 :type '(set (const :tag "Double bracket links (new style)" bracket)
904 (const :tag "Angular bracket links (old style)" angular)
905 (const :tag "Plain text links" plain)
906 (const :tag "Radio target matches" radio)
907 (const :tag "Tags" tag)
908 (const :tag "Timestamps" date)))
910 (defcustom org-make-link-description-function nil
911 "Function to use to generate link descriptions from links. If
912 nil the link location will be used. This function must take two
913 parameters; the first is the link and the second the description
914 org-insert-link has generated, and should return the description
915 to use."
916 :group 'org-link
917 :type 'function)
919 (defgroup org-link-store nil
920 "Options concerning storing links in Org-mode."
921 :tag "Org Store Link"
922 :group 'org-link)
924 (defcustom org-email-link-description-format "Email %c: %.30s"
925 "Format of the description part of a link to an email or usenet message.
926 The following %-excapes will be replaced by corresponding information:
928 %F full \"From\" field
929 %f name, taken from \"From\" field, address if no name
930 %T full \"To\" field
931 %t first name in \"To\" field, address if no name
932 %c correspondent. Unually \"from NAME\", but if you sent it yourself, it
933 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
934 %s subject
935 %m message-id.
937 You may use normal field width specification between the % and the letter.
938 This is for example useful to limit the length of the subject.
940 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
941 :group 'org-link-store
942 :type 'string)
944 (defcustom org-from-is-user-regexp
945 (let (r1 r2)
946 (when (and user-mail-address (not (string= user-mail-address "")))
947 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
948 (when (and user-full-name (not (string= user-full-name "")))
949 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
950 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
951 "Regexp mached against the \"From:\" header of an email or usenet message.
952 It should match if the message is from the user him/herself."
953 :group 'org-link-store
954 :type 'regexp)
956 (defcustom org-context-in-file-links t
957 "Non-nil means, file links from `org-store-link' contain context.
958 A search string will be added to the file name with :: as separator and
959 used to find the context when the link is activated by the command
960 `org-open-at-point'.
961 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
962 negates this setting for the duration of the command."
963 :group 'org-link-store
964 :type 'boolean)
966 (defcustom org-keep-stored-link-after-insertion nil
967 "Non-nil means, keep link in list for entire session.
969 The command `org-store-link' adds a link pointing to the current
970 location to an internal list. These links accumulate during a session.
971 The command `org-insert-link' can be used to insert links into any
972 Org-mode file (offering completion for all stored links). When this
973 option is nil, every link which has been inserted once using \\[org-insert-link]
974 will be removed from the list, to make completing the unused links
975 more efficient."
976 :group 'org-link-store
977 :type 'boolean)
979 (defgroup org-link-follow nil
980 "Options concerning following links in Org-mode."
981 :tag "Org Follow Link"
982 :group 'org-link)
984 (defcustom org-link-translation-function nil
985 "Function to translate links with different syntax to Org syntax.
986 This can be used to translate links created for example by the Planner
987 or emacs-wiki packages to Org syntax.
988 The function must accept two parameters, a TYPE containing the link
989 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
990 which is everything after the link protocol. It should return a cons
991 with possibly modifed values of type and path.
992 Org contains a function for this, so if you set this variable to
993 `org-translate-link-from-planner', you should be able follow many
994 links created by planner."
995 :group 'org-link-follow
996 :type 'function)
998 (defcustom org-follow-link-hook nil
999 "Hook that is run after a link has been followed."
1000 :group 'org-link-follow
1001 :type 'hook)
1003 (defcustom org-tab-follows-link nil
1004 "Non-nil means, on links TAB will follow the link.
1005 Needs to be set before org.el is loaded."
1006 :group 'org-link-follow
1007 :type 'boolean)
1009 (defcustom org-return-follows-link nil
1010 "Non-nil means, on links RET will follow the link.
1011 Needs to be set before org.el is loaded."
1012 :group 'org-link-follow
1013 :type 'boolean)
1015 (defcustom org-mouse-1-follows-link
1016 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1017 "Non-nil means, mouse-1 on a link will follow the link.
1018 A longer mouse click will still set point. Does not work on XEmacs.
1019 Needs to be set before org.el is loaded."
1020 :group 'org-link-follow
1021 :type 'boolean)
1023 (defcustom org-mark-ring-length 4
1024 "Number of different positions to be recorded in the ring
1025 Changing this requires a restart of Emacs to work correctly."
1026 :group 'org-link-follow
1027 :type 'interger)
1029 (defcustom org-link-frame-setup
1030 '((vm . vm-visit-folder-other-frame)
1031 (gnus . gnus-other-frame)
1032 (file . find-file-other-window))
1033 "Setup the frame configuration for following links.
1034 When following a link with Emacs, it may often be useful to display
1035 this link in another window or frame. This variable can be used to
1036 set this up for the different types of links.
1037 For VM, use any of
1038 `vm-visit-folder'
1039 `vm-visit-folder-other-frame'
1040 For Gnus, use any of
1041 `gnus'
1042 `gnus-other-frame'
1043 `org-gnus-no-new-news'
1044 For FILE, use any of
1045 `find-file'
1046 `find-file-other-window'
1047 `find-file-other-frame'
1048 For the calendar, use the variable `calendar-setup'.
1049 For BBDB, it is currently only possible to display the matches in
1050 another window."
1051 :group 'org-link-follow
1052 :type '(list
1053 (cons (const vm)
1054 (choice
1055 (const vm-visit-folder)
1056 (const vm-visit-folder-other-window)
1057 (const vm-visit-folder-other-frame)))
1058 (cons (const gnus)
1059 (choice
1060 (const gnus)
1061 (const gnus-other-frame)
1062 (const org-gnus-no-new-news)))
1063 (cons (const file)
1064 (choice
1065 (const find-file)
1066 (const find-file-other-window)
1067 (const find-file-other-frame)))))
1069 (defcustom org-display-internal-link-with-indirect-buffer nil
1070 "Non-nil means, use indirect buffer to display infile links.
1071 Activating internal links (from one location in a file to another location
1072 in the same file) normally just jumps to the location. When the link is
1073 activated with a C-u prefix (or with mouse-3), the link is displayed in
1074 another window. When this option is set, the other window actually displays
1075 an indirect buffer clone of the current buffer, to avoid any visibility
1076 changes to the current buffer."
1077 :group 'org-link-follow
1078 :type 'boolean)
1080 (defcustom org-open-non-existing-files nil
1081 "Non-nil means, `org-open-file' will open non-existing files.
1082 When nil, an error will be generated."
1083 :group 'org-link-follow
1084 :type 'boolean)
1086 (defcustom org-open-directory-means-index-dot-org nil
1087 "Non-nil means, a link to a directory really means to index.org.
1088 When nil, following a directory link will run dired or open a finder/explorer
1089 window on that directory."
1090 :group 'org-link-follow
1091 :type 'boolean)
1093 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1094 "Function and arguments to call for following mailto links.
1095 This is a list with the first element being a lisp function, and the
1096 remaining elements being arguments to the function. In string arguments,
1097 %a will be replaced by the address, and %s will be replaced by the subject
1098 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1099 :group 'org-link-follow
1100 :type '(choice
1101 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1102 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1103 (const :tag "message-mail" (message-mail "%a" "%s"))
1104 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1106 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1107 "Non-nil means, ask for confirmation before executing shell links.
1108 Shell links can be dangerous: just think about a link
1110 [[shell: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 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1124 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1125 Elisp links can be dangerous: just think about a link
1127 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1129 This link would show up in your Org-mode document as \"Google Search\",
1130 but really it would remove your entire home directory.
1131 Therefore we advise against setting this variable to nil.
1132 Just change it to `y-or-n-p' of you want to confirm with a
1133 single keystroke rather than having to type \"yes\"."
1134 :group 'org-link-follow
1135 :type '(choice
1136 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1137 (const :tag "with y-or-n (faster)" y-or-n-p)
1138 (const :tag "no confirmation (dangerous)" nil)))
1140 (defconst org-file-apps-defaults-gnu
1141 '((remote . emacs)
1142 (system . mailcap)
1143 (t . mailcap))
1144 "Default file applications on a UNIX or GNU/Linux system.
1145 See `org-file-apps'.")
1147 (defconst org-file-apps-defaults-macosx
1148 '((remote . emacs)
1149 (t . "open %s")
1150 (system . "open %s")
1151 ("ps.gz" . "gv %s")
1152 ("eps.gz" . "gv %s")
1153 ("dvi" . "xdvi %s")
1154 ("fig" . "xfig %s"))
1155 "Default file applications on a MacOS X system.
1156 The system \"open\" is known as a default, but we use X11 applications
1157 for some files for which the OS does not have a good default.
1158 See `org-file-apps'.")
1160 (defconst org-file-apps-defaults-windowsnt
1161 (list
1162 '(remote . emacs)
1163 (cons t
1164 (list (if (featurep 'xemacs)
1165 'mswindows-shell-execute
1166 'w32-shell-execute)
1167 "open" 'file))
1168 (cons 'system
1169 (list (if (featurep 'xemacs)
1170 'mswindows-shell-execute
1171 'w32-shell-execute)
1172 "open" 'file)))
1173 "Default file applications on a Windows NT system.
1174 The system \"open\" is used for most files.
1175 See `org-file-apps'.")
1177 (defcustom org-file-apps
1179 (auto-mode . emacs)
1180 ("\\.x?html?\\'" . default)
1181 ("\\.pdf\\'" . default)
1183 "External applications for opening `file:path' items in a document.
1184 Org-mode uses system defaults for different file types, but
1185 you can use this variable to set the application for a given file
1186 extension. The entries in this list are cons cells where the car identifies
1187 files and the cdr the corresponding command. Possible values for the
1188 file identifier are
1189 \"regex\" Regular expression matched against the file name. For backward
1190 compatibility, this can also be a string with only alphanumeric
1191 characters, which is then interpreted as an extension.
1192 `directory' Matches a directory
1193 `remote' Matches a remote file, accessible through tramp or efs.
1194 Remote files most likely should be visited through Emacs
1195 because external applications cannot handle such paths.
1196 `auto-mode' Matches files that are mached by any entry in `auto-mode-alist',
1197 so all files Emacs knows how to handle. Using this with
1198 command `emacs' will open most files in Emacs. Beware that this
1199 will also open html files insite Emacs, unless you add
1200 (\"html\" . default) to the list as well.
1201 t Default for files not matched by any of the other options.
1202 `system' The system command to open files, like `open' on Windows
1203 and Mac OS X, and mailcap under GNU/Linux. This is the command
1204 that will be selected if you call `C-c C-o' with a double
1205 `C-u C-u' prefix.
1207 Possible values for the command are:
1208 `emacs' The file will be visited by the current Emacs process.
1209 `default' Use the default application for this file type, which is the
1210 association for t in the list, most likely in the system-specific
1211 part.
1212 This can be used to overrule an unwanted seting in the
1213 system-specific variable.
1214 `system' Use the system command for opening files, like \"open\".
1215 This command is specified by the entry whose car is `system'.
1216 Most likely, the system-specific version of this variable
1217 does define this command, but you can overrule/replace it
1218 here.
1219 string A command to be executed by a shell; %s will be replaced
1220 by the path to the file.
1221 sexp A Lisp form which will be evaluated. The file path will
1222 be available in the Lisp variable `file'.
1223 For more examples, see the system specific constants
1224 `org-file-apps-defaults-macosx'
1225 `org-file-apps-defaults-windowsnt'
1226 `org-file-apps-defaults-gnu'."
1227 :group 'org-link-follow
1228 :type '(repeat
1229 (cons (choice :value ""
1230 (string :tag "Extension")
1231 (const :tag "System command to open files" system)
1232 (const :tag "Default for unrecognized files" t)
1233 (const :tag "Remote file" remote)
1234 (const :tag "Links to a directory" directory)
1235 (const :tag "Any files that have Emacs modes"
1236 auto-mode))
1237 (choice :value ""
1238 (const :tag "Visit with Emacs" emacs)
1239 (const :tag "Use default" default)
1240 (const :tag "Use the system command" system)
1241 (string :tag "Command")
1242 (sexp :tag "Lisp form")))))
1244 (defgroup org-refile nil
1245 "Options concerning refiling entries in Org-mode."
1246 :tag "Org Remember"
1247 :group 'org)
1249 (defcustom org-directory "~/org"
1250 "Directory with org files.
1251 This directory will be used as default to prompt for org files.
1252 Used by the hooks for remember.el."
1253 :group 'org-refile
1254 :group 'org-remember
1255 :type 'directory)
1257 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1258 "Default target for storing notes.
1259 Used by the hooks for remember.el. This can be a string, or nil to mean
1260 the value of `remember-data-file'.
1261 You can set this on a per-template basis with the variable
1262 `org-remember-templates'."
1263 :group 'org-refile
1264 :group 'org-remember
1265 :type '(choice
1266 (const :tag "Default from remember-data-file" nil)
1267 file))
1269 (defcustom org-goto-interface 'outline
1270 "The default interface to be used for `org-goto'.
1271 Allowed vaues are:
1272 outline The interface shows an outline of the relevant file
1273 and the correct heading is found by moving through
1274 the outline or by searching with incremental search.
1275 outline-path-completion Headlines in the current buffer are offered via
1276 completion."
1277 :group 'org-refile
1278 :type '(choice
1279 (const :tag "Outline" outline)
1280 (const :tag "Outline-path-completion" outline-path-completion)))
1282 (defcustom org-reverse-note-order nil
1283 "Non-nil means, store new notes at the beginning of a file or entry.
1284 When nil, new notes will be filed to the end of a file or entry.
1285 This can also be a list with cons cells of regular expressions that
1286 are matched against file names, and values."
1287 :group 'org-remember
1288 :type '(choice
1289 (const :tag "Reverse always" t)
1290 (const :tag "Reverse never" nil)
1291 (repeat :tag "By file name regexp"
1292 (cons regexp boolean))))
1294 (defcustom org-refile-targets nil
1295 "Targets for refiling entries with \\[org-refile].
1296 This is list of cons cells. Each cell contains:
1297 - a specification of the files to be considered, either a list of files,
1298 or a symbol whose function or variable value will be used to retrieve
1299 a file name or a list of file names. Nil means, refile to a different
1300 heading in the current buffer.
1301 - A specification of how to find candidate refile targets. This may be
1302 any of
1303 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1304 This tag has to be present in all target headlines, inheritance will
1305 not be considered.
1306 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1307 todo keyword.
1308 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1309 headlines that are refiling targets.
1310 - a cons cell (:level . N). Any headline of level N is considered a target.
1311 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1313 When this variable is nil, all top-level headlines in the current buffer
1314 are used, equivalent to the value `((nil . (:level . 1))'."
1315 :group 'org-remember
1316 :type '(repeat
1317 (cons
1318 (choice :value org-agenda-files
1319 (const :tag "All agenda files" org-agenda-files)
1320 (const :tag "Current buffer" nil)
1321 (function) (variable) (file))
1322 (choice :tag "Identify target headline by"
1323 (cons :tag "Specific tag" (const :tag) (string))
1324 (cons :tag "TODO keyword" (const :todo) (string))
1325 (cons :tag "Regular expression" (const :regexp) (regexp))
1326 (cons :tag "Level number" (const :level) (integer))
1327 (cons :tag "Max Level number" (const :maxlevel) (integer))))))
1329 (defcustom org-refile-use-outline-path nil
1330 "Non-nil means, provide refile targets as paths.
1331 So a level 3 headline will be available as level1/level2/level3.
1332 When the value is `file', also include the file name (without directory)
1333 into the path. When `full-file-path', include the full file path."
1334 :group 'org-remember
1335 :type '(choice
1336 (const :tag "Not" nil)
1337 (const :tag "Yes" t)
1338 (const :tag "Start with file name" file)
1339 (const :tag "Start with full file path" full-file-path)))
1341 (defgroup org-todo nil
1342 "Options concerning TODO items in Org-mode."
1343 :tag "Org TODO"
1344 :group 'org)
1346 (defgroup org-progress nil
1347 "Options concerning Progress logging in Org-mode."
1348 :tag "Org Progress"
1349 :group 'org-time)
1351 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1352 "List of TODO entry keyword sequences and their interpretation.
1353 \\<org-mode-map>This is a list of sequences.
1355 Each sequence starts with a symbol, either `sequence' or `type',
1356 indicating if the keywords should be interpreted as a sequence of
1357 action steps, or as different types of TODO items. The first
1358 keywords are states requiring action - these states will select a headline
1359 for inclusion into the global TODO list Org-mode produces. If one of
1360 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1361 signify that no further action is necessary. If \"|\" is not found,
1362 the last keyword is treated as the only DONE state of the sequence.
1364 The command \\[org-todo] cycles an entry through these states, and one
1365 additional state where no keyword is present. For details about this
1366 cycling, see the manual.
1368 TODO keywords and interpretation can also be set on a per-file basis with
1369 the special #+SEQ_TODO and #+TYP_TODO lines.
1371 Each keyword can optionally specify a character for fast state selection
1372 \(in combination with the variable `org-use-fast-todo-selection')
1373 and specifiers for state change logging, using the same syntax
1374 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1375 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1376 indicates to record a time stamp each time this state is selected.
1378 Each keyword may also specify if a timestamp or a note should be
1379 recorded when entering or leaving the state, by adding additional
1380 characters in the parenthesis after the keyword. This looks like this:
1381 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1382 record only the time of the state change. With X and Y being either
1383 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1384 Y when leaving the state if and only if the *target* state does not
1385 define X. You may omit any of the fast-selection key or X or /Y,
1386 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1388 For backward compatibility, this variable may also be just a list
1389 of keywords - in this case the interptetation (sequence or type) will be
1390 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1391 :group 'org-todo
1392 :group 'org-keywords
1393 :type '(choice
1394 (repeat :tag "Old syntax, just keywords"
1395 (string :tag "Keyword"))
1396 (repeat :tag "New syntax"
1397 (cons
1398 (choice
1399 :tag "Interpretation"
1400 (const :tag "Sequence (cycling hits every state)" sequence)
1401 (const :tag "Type (cycling directly to DONE)" type))
1402 (repeat
1403 (string :tag "Keyword"))))))
1405 (defvar org-todo-keywords-1 nil
1406 "All TODO and DONE keywords active in a buffer.")
1407 (make-variable-buffer-local 'org-todo-keywords-1)
1408 (defvar org-todo-keywords-for-agenda nil)
1409 (defvar org-done-keywords-for-agenda nil)
1410 (defvar org-todo-keyword-alist-for-agenda nil)
1411 (defvar org-tag-alist-for-agenda nil)
1412 (defvar org-agenda-contributing-files nil)
1413 (defvar org-not-done-keywords nil)
1414 (make-variable-buffer-local 'org-not-done-keywords)
1415 (defvar org-done-keywords nil)
1416 (make-variable-buffer-local 'org-done-keywords)
1417 (defvar org-todo-heads nil)
1418 (make-variable-buffer-local 'org-todo-heads)
1419 (defvar org-todo-sets nil)
1420 (make-variable-buffer-local 'org-todo-sets)
1421 (defvar org-todo-log-states nil)
1422 (make-variable-buffer-local 'org-todo-log-states)
1423 (defvar org-todo-kwd-alist nil)
1424 (make-variable-buffer-local 'org-todo-kwd-alist)
1425 (defvar org-todo-key-alist nil)
1426 (make-variable-buffer-local 'org-todo-key-alist)
1427 (defvar org-todo-key-trigger nil)
1428 (make-variable-buffer-local 'org-todo-key-trigger)
1430 (defcustom org-todo-interpretation 'sequence
1431 "Controls how TODO keywords are interpreted.
1432 This variable is in principle obsolete and is only used for
1433 backward compatibility, if the interpretation of todo keywords is
1434 not given already in `org-todo-keywords'. See that variable for
1435 more information."
1436 :group 'org-todo
1437 :group 'org-keywords
1438 :type '(choice (const sequence)
1439 (const type)))
1441 (defcustom org-use-fast-todo-selection 'prefix
1442 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1443 This variable describes if and under what circumstances the cycling
1444 mechanism for TODO keywords will be replaced by a single-key, direct
1445 selection scheme.
1447 When nil, fast selection is never used.
1449 When the symbol `prefix', it will be used when `org-todo' is called with
1450 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1451 in an agenda buffer.
1453 When t, fast selection is used by default. In this case, the prefix
1454 argument forces cycling instead.
1456 In all cases, the special interface is only used if access keys have actually
1457 been assigned by the user, i.e. if keywords in the configuration are followed
1458 by a letter in parenthesis, like TODO(t)."
1459 :group 'org-todo
1460 :type '(choice
1461 (const :tag "Never" nil)
1462 (const :tag "By default" t)
1463 (const :tag "Only with C-u C-c C-t" prefix)))
1465 (defcustom org-provide-todo-statistics t
1466 "Non-nil means, update todo statistics after insert and toggle.
1467 When this is set, todo statistics is updated in the parent of the current
1468 entry each time a todo state is changed."
1469 :group 'org-todo
1470 :type 'boolean)
1472 (defcustom org-after-todo-state-change-hook nil
1473 "Hook which is run after the state of a TODO item was changed.
1474 The new state (a string with a TODO keyword, or nil) is available in the
1475 Lisp variable `state'."
1476 :group 'org-todo
1477 :type 'hook)
1479 (defcustom org-todo-state-tags-triggers nil
1480 "Tag changes that should be triggered by TODO state changes.
1481 This is a list. Each entry is
1483 (state-change (tag . flag) .......)
1485 State-change can be a string with a state, and empty string to indicate the
1486 state that has no TODO keyword, or it can be one of the symbols `todo'
1487 or `done', meaning any not-done or done state, respectively."
1488 :group 'org-todo
1489 :group 'org-tags
1490 :type '(repeat
1491 (cons (choice :tag "When changing to"
1492 (const :tag "Not-done state" todo)
1493 (const :tag "Done state" done)
1494 (string :tag "State"))
1495 (repeat
1496 (cons :tag "Tag action"
1497 (string :tag "Tag")
1498 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1500 (defcustom org-log-done nil
1501 "Non-nil means, record a CLOSED timestamp when moving an entry to DONE.
1502 When equal to the list (done), also prompt for a closing note.
1503 This can also be configured on a per-file basis by adding one of
1504 the following lines anywhere in the buffer:
1506 #+STARTUP: logdone
1507 #+STARTUP: lognotedone
1508 #+STARTUP: nologdone"
1509 :group 'org-todo
1510 :group 'org-progress
1511 :type '(choice
1512 (const :tag "No logging" nil)
1513 (const :tag "Record CLOSED timestamp" time)
1514 (const :tag "Record CLOSED timestamp with closing note." note)))
1516 ;; Normalize old uses of org-log-done.
1517 (cond
1518 ((eq org-log-done t) (setq org-log-done 'time))
1519 ((and (listp org-log-done) (memq 'done org-log-done))
1520 (setq org-log-done 'note)))
1522 (defcustom org-log-note-clock-out nil
1523 "Non-nil means, record a note when clocking out of an item.
1524 This can also be configured on a per-file basis by adding one of
1525 the following lines anywhere in the buffer:
1527 #+STARTUP: lognoteclock-out
1528 #+STARTUP: nolognoteclock-out"
1529 :group 'org-todo
1530 :group 'org-progress
1531 :type 'boolean)
1533 (defcustom org-log-done-with-time t
1534 "Non-nil means, the CLOSED time stamp will contain date and time.
1535 When nil, only the date will be recorded."
1536 :group 'org-progress
1537 :type 'boolean)
1539 (defcustom org-log-note-headings
1540 '((done . "CLOSING NOTE %t")
1541 (state . "State %-12s %t")
1542 (note . "Note taken on %t")
1543 (clock-out . ""))
1544 "Headings for notes added to entries.
1545 The value is an alist, with the car being a symbol indicating the note
1546 context, and the cdr is the heading to be used. The heading may also be the
1547 empty string.
1548 %t in the heading will be replaced by a time stamp.
1549 %s will be replaced by the new TODO state, in double quotes.
1550 %u will be replaced by the user name.
1551 %U will be replaced by the full user name."
1552 :group 'org-todo
1553 :group 'org-progress
1554 :type '(list :greedy t
1555 (cons (const :tag "Heading when closing an item" done) string)
1556 (cons (const :tag
1557 "Heading when changing todo state (todo sequence only)"
1558 state) string)
1559 (cons (const :tag "Heading when just taking a note" note) string)
1560 (cons (const :tag "Heading when clocking out" clock-out) string)))
1562 (unless (assq 'note org-log-note-headings)
1563 (push '(note . "%t") org-log-note-headings))
1565 (defcustom org-log-state-notes-insert-after-drawers nil
1566 "Non-nil means, insert state change notes after any drawers in entry.
1567 Only the drawers that *immediately* follow the headline and the
1568 deadline/scheduled line are skipped.
1569 When nil, insert notes right after the heading and perhaps the line
1570 with deadline/scheduling if present."
1571 :group 'org-todo
1572 :group 'org-progress
1573 :type 'boolean)
1575 (defcustom org-log-states-order-reversed t
1576 "Non-nil means, the latest state change note will be directly after heading.
1577 When nil, the notes will be orderer according to time."
1578 :group 'org-todo
1579 :group 'org-progress
1580 :type 'boolean)
1582 (defcustom org-log-repeat 'time
1583 "Non-nil means, record moving through the DONE state when triggering repeat.
1584 An auto-repeating tasks is immediately switched back to TODO when marked
1585 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1586 the TODO keyword definition, or recording a closing note by setting
1587 `org-log-done', there will be no record of the task moving through DONE.
1588 This variable forces taking a note anyway. Possible values are:
1590 nil Don't force a record
1591 time Record a time stamp
1592 note Record a note
1594 This option can also be set with on a per-file-basis with
1596 #+STARTUP: logrepeat
1597 #+STARTUP: lognoterepeat
1598 #+STARTUP: nologrepeat
1600 You can have local logging settings for a subtree by setting the LOGGING
1601 property to one or more of these keywords."
1602 :group 'org-todo
1603 :group 'org-progress
1604 :type '(choice
1605 (const :tag "Don't force a record" nil)
1606 (const :tag "Force recording the DONE state" time)
1607 (const :tag "Force recording a note with the DONE state" note)))
1610 (defgroup org-priorities nil
1611 "Priorities in Org-mode."
1612 :tag "Org Priorities"
1613 :group 'org-todo)
1615 (defcustom org-highest-priority ?A
1616 "The highest priority of TODO items. A character like ?A, ?B etc.
1617 Must have a smaller ASCII number than `org-lowest-priority'."
1618 :group 'org-priorities
1619 :type 'character)
1621 (defcustom org-lowest-priority ?C
1622 "The lowest priority of TODO items. A character like ?A, ?B etc.
1623 Must have a larger ASCII number than `org-highest-priority'."
1624 :group 'org-priorities
1625 :type 'character)
1627 (defcustom org-default-priority ?B
1628 "The default priority of TODO items.
1629 This is the priority an item get if no explicit priority is given."
1630 :group 'org-priorities
1631 :type 'character)
1633 (defcustom org-priority-start-cycle-with-default t
1634 "Non-nil means, start with default priority when starting to cycle.
1635 When this is nil, the first step in the cycle will be (depending on the
1636 command used) one higher or lower that the default priority."
1637 :group 'org-priorities
1638 :type 'boolean)
1640 (defgroup org-time nil
1641 "Options concerning time stamps and deadlines in Org-mode."
1642 :tag "Org Time"
1643 :group 'org)
1645 (defcustom org-insert-labeled-timestamps-at-point nil
1646 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1647 When nil, these labeled time stamps are forces into the second line of an
1648 entry, just after the headline. When scheduling from the global TODO list,
1649 the time stamp will always be forced into the second line."
1650 :group 'org-time
1651 :type 'boolean)
1653 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1654 "Formats for `format-time-string' which are used for time stamps.
1655 It is not recommended to change this constant.")
1657 (defcustom org-time-stamp-rounding-minutes '(0 5)
1658 "Number of minutes to round time stamps to.
1659 These are two values, the first applies when first creating a time stamp.
1660 The second applies when changing it with the commands `S-up' and `S-down'.
1661 When changing the time stamp, this means that it will change in steps
1662 of N minutes, as given by the second value.
1664 When a setting is 0 or 1, insert the time unmodified. Useful rounding
1665 numbers should be factors of 60, so for example 5, 10, 15.
1667 When this is larger than 1, you can still force an exact time-stamp by using
1668 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
1669 and by using a prefix arg to `S-up/down' to specify the exact number
1670 of minutes to shift."
1671 :group 'org-time
1672 :get '(lambda (var) ; Make sure all entries have 5 elements
1673 (if (integerp (default-value var))
1674 (list (default-value var) 5)
1675 (default-value var)))
1676 :type '(list
1677 (integer :tag "when inserting times")
1678 (integer :tag "when modifying times")))
1680 ;; Normalize old customizations of this variable.
1681 (when (integerp org-time-stamp-rounding-minutes)
1682 (setq org-time-stamp-rounding-minutes
1683 (list org-time-stamp-rounding-minutes
1684 org-time-stamp-rounding-minutes)))
1686 (defcustom org-display-custom-times nil
1687 "Non-nil means, overlay custom formats over all time stamps.
1688 The formats are defined through the variable `org-time-stamp-custom-formats'.
1689 To turn this on on a per-file basis, insert anywhere in the file:
1690 #+STARTUP: customtime"
1691 :group 'org-time
1692 :set 'set-default
1693 :type 'sexp)
1694 (make-variable-buffer-local 'org-display-custom-times)
1696 (defcustom org-time-stamp-custom-formats
1697 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1698 "Custom formats for time stamps. See `format-time-string' for the syntax.
1699 These are overlayed over the default ISO format if the variable
1700 `org-display-custom-times' is set. Time like %H:%M should be at the
1701 end of the second format."
1702 :group 'org-time
1703 :type 'sexp)
1705 (defun org-time-stamp-format (&optional long inactive)
1706 "Get the right format for a time string."
1707 (let ((f (if long (cdr org-time-stamp-formats)
1708 (car org-time-stamp-formats))))
1709 (if inactive
1710 (concat "[" (substring f 1 -1) "]")
1711 f)))
1713 (defcustom org-time-clocksum-format "%d:%02d"
1714 "The format string used when creating CLOCKSUM lines, or when
1715 org-mode generates a time duration."
1716 :group 'org-time
1717 :type 'string)
1719 (defcustom org-deadline-warning-days 14
1720 "No. of days before expiration during which a deadline becomes active.
1721 This variable governs the display in sparse trees and in the agenda.
1722 When 0 or negative, it means use this number (the absolute value of it)
1723 even if a deadline has a different individual lead time specified."
1724 :group 'org-time
1725 :group 'org-agenda-daily/weekly
1726 :type 'number)
1728 (defcustom org-read-date-prefer-future t
1729 "Non-nil means, assume future for incomplete date input from user.
1730 This affects the following situations:
1731 1. The user gives a day, but no month.
1732 For example, if today is the 15th, and you enter \"3\", Org-mode will
1733 read this as the third of *next* month. However, if you enter \"17\",
1734 it will be considered as *this* month.
1735 2. The user gives a month but not a year.
1736 For example, if it is april and you enter \"feb 2\", this will be read
1737 as feb 2, *next* year. \"May 5\", however, will be this year.
1739 Currently this does not work for ISO week specifications.
1741 When this option is nil, the current month and year will always be used
1742 as defaults."
1743 :group 'org-time
1744 :type 'boolean)
1746 (defcustom org-read-date-display-live t
1747 "Non-nil means, display current interpretation of date prompt live.
1748 This display will be in an overlay, in the minibuffer."
1749 :group 'org-time
1750 :type 'boolean)
1752 (defcustom org-read-date-popup-calendar t
1753 "Non-nil means, pop up a calendar when prompting for a date.
1754 In the calendar, the date can be selected with mouse-1. However, the
1755 minibuffer will also be active, and you can simply enter the date as well.
1756 When nil, only the minibuffer will be available."
1757 :group 'org-time
1758 :type 'boolean)
1759 (if (fboundp 'defvaralias)
1760 (defvaralias 'org-popup-calendar-for-date-prompt
1761 'org-read-date-popup-calendar))
1763 (defcustom org-extend-today-until 0
1764 "The hour when your day really ends. Must be an integer.
1765 This has influence for the following applications:
1766 - When switching the agenda to \"today\". It it is still earlier than
1767 the time given here, the day recognized as TODAY is actually yesterday.
1768 - When a date is read from the user and it is still before the time given
1769 here, the current date and time will be assumed to be yesterday, 23:59.
1770 Also, timestamps inserted in remember templates follow this rule.
1772 IMPORTANT: This is a feature whose implementation is and likely will
1773 remain incomplete. Really, it is only here because past midnight seems to
1774 be the favorite working time of John Wiegley :-)"
1775 :group 'org-time
1776 :type 'number)
1778 (defcustom org-edit-timestamp-down-means-later nil
1779 "Non-nil means, S-down will increase the time in a time stamp.
1780 When nil, S-up will increase."
1781 :group 'org-time
1782 :type 'boolean)
1784 (defcustom org-calendar-follow-timestamp-change t
1785 "Non-nil means, make the calendar window follow timestamp changes.
1786 When a timestamp is modified and the calendar window is visible, it will be
1787 moved to the new date."
1788 :group 'org-time
1789 :type 'boolean)
1791 (defgroup org-tags nil
1792 "Options concerning tags in Org-mode."
1793 :tag "Org Tags"
1794 :group 'org)
1796 (defcustom org-tag-alist nil
1797 "List of tags allowed in Org-mode files.
1798 When this list is nil, Org-mode will base TAG input on what is already in the
1799 buffer.
1800 The value of this variable is an alist, the car of each entry must be a
1801 keyword as a string, the cdr may be a character that is used to select
1802 that tag through the fast-tag-selection interface.
1803 See the manual for details."
1804 :group 'org-tags
1805 :type '(repeat
1806 (choice
1807 (cons (string :tag "Tag name")
1808 (character :tag "Access char"))
1809 (const :tag "Start radio group" (:startgroup))
1810 (const :tag "End radio group" (:endgroup)))))
1812 (defvar org-file-tags nil
1813 "List of tags that can be inherited by all entries in the file.
1814 The tags will be inherited if the variable `org-use-tag-inheritance'
1815 says they should be.
1816 This variable is populated from #+TAG lines.")
1818 (defcustom org-use-fast-tag-selection 'auto
1819 "Non-nil means, use fast tag selection scheme.
1820 This is a special interface to select and deselect tags with single keys.
1821 When nil, fast selection is never used.
1822 When the symbol `auto', fast selection is used if and only if selection
1823 characters for tags have been configured, either through the variable
1824 `org-tag-alist' or through a #+TAGS line in the buffer.
1825 When t, fast selection is always used and selection keys are assigned
1826 automatically if necessary."
1827 :group 'org-tags
1828 :type '(choice
1829 (const :tag "Always" t)
1830 (const :tag "Never" nil)
1831 (const :tag "When selection characters are configured" 'auto)))
1833 (defcustom org-fast-tag-selection-single-key nil
1834 "Non-nil means, fast tag selection exits after first change.
1835 When nil, you have to press RET to exit it.
1836 During fast tag selection, you can toggle this flag with `C-c'.
1837 This variable can also have the value `expert'. In this case, the window
1838 displaying the tags menu is not even shown, until you press C-c again."
1839 :group 'org-tags
1840 :type '(choice
1841 (const :tag "No" nil)
1842 (const :tag "Yes" t)
1843 (const :tag "Expert" expert)))
1845 (defvar org-fast-tag-selection-include-todo nil
1846 "Non-nil means, fast tags selection interface will also offer TODO states.
1847 This is an undocumented feature, you should not rely on it.")
1849 (defcustom org-tags-column (if (featurep 'xemacs) -79 -80)
1850 "The column to which tags should be indented in a headline.
1851 If this number is positive, it specifies the column. If it is negative,
1852 it means that the tags should be flushright to that column. For example,
1853 -80 works well for a normal 80 character screen."
1854 :group 'org-tags
1855 :type 'integer)
1857 (defcustom org-auto-align-tags t
1858 "Non-nil means, realign tags after pro/demotion of TODO state change.
1859 These operations change the length of a headline and therefore shift
1860 the tags around. With this options turned on, after each such operation
1861 the tags are again aligned to `org-tags-column'."
1862 :group 'org-tags
1863 :type 'boolean)
1865 (defcustom org-use-tag-inheritance t
1866 "Non-nil means, tags in levels apply also for sublevels.
1867 When nil, only the tags directly given in a specific line apply there.
1868 If this option is t, a match early-on in a tree can lead to a large
1869 number of matches in the subtree. If you only want to see the first
1870 match in a tree during a search, check out the variable
1871 `org-tags-match-list-sublevels'.
1873 This may also be a list of tags that should be inherited, or a regexp that
1874 matches tags that should be inherited."
1875 :group 'org-tags
1876 :type '(choice
1877 (const :tag "Not" nil)
1878 (const :tag "Always" t)
1879 (repeat :tag "Specific tags" (string :tag "Tag"))
1880 (regexp :tag "Tags matched by regexp")))
1882 (defun org-tag-inherit-p (tag)
1883 "Check if TAG is one that should be inherited."
1884 (cond
1885 ((eq org-use-tag-inheritance t) t)
1886 ((not org-use-tag-inheritance) nil)
1887 ((stringp org-use-tag-inheritance)
1888 (string-match org-use-tag-inheritance tag))
1889 ((listp org-use-tag-inheritance)
1890 (member tag org-use-tag-inheritance))
1891 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
1893 (defcustom org-tags-match-list-sublevels t
1894 "Non-nil means list also sublevels of headlines matching tag search.
1895 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1896 the sublevels of a headline matching a tag search often also match
1897 the same search. Listing all of them can create very long lists.
1898 Setting this variable to nil causes subtrees of a match to be skipped.
1899 This option is off by default, because inheritance in on. If you turn
1900 inheritance off, you very likely want to turn this option on.
1902 As a special case, if the tag search is restricted to TODO items, the
1903 value of this variable is ignored and sublevels are always checked, to
1904 make sure all corresponding TODO items find their way into the list."
1905 :group 'org-tags
1906 :type 'boolean)
1908 (defvar org-tags-history nil
1909 "History of minibuffer reads for tags.")
1910 (defvar org-last-tags-completion-table nil
1911 "The last used completion table for tags.")
1912 (defvar org-after-tags-change-hook nil
1913 "Hook that is run after the tags in a line have changed.")
1915 (defgroup org-properties nil
1916 "Options concerning properties in Org-mode."
1917 :tag "Org Properties"
1918 :group 'org)
1920 (defcustom org-property-format "%-10s %s"
1921 "How property key/value pairs should be formatted by `indent-line'.
1922 When `indent-line' hits a property definition, it will format the line
1923 according to this format, mainly to make sure that the values are
1924 lined-up with respect to each other."
1925 :group 'org-properties
1926 :type 'string)
1928 (defcustom org-use-property-inheritance nil
1929 "Non-nil means, properties apply also for sublevels.
1931 This setting is chiefly used during property searches. Turning it on can
1932 cause significant overhead when doing a search, which is why it is not
1933 on by default.
1935 When nil, only the properties directly given in the current entry count.
1936 When t, every property is inherited. The value may also be a list of
1937 properties that should have inheritance, or a regular expression matching
1938 properties that should be inherited.
1940 However, note that some special properties use inheritance under special
1941 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
1942 and the properties ending in \"_ALL\" when they are used as descriptor
1943 for valid values of a property.
1945 Note for programmers:
1946 When querying an entry with `org-entry-get', you can control if inheritance
1947 should be used. By default, `org-entry-get' looks only at the local
1948 properties. You can request inheritance by setting the inherit argument
1949 to t (to force inheritance) or to `selective' (to respect the setting
1950 in this variable)."
1951 :group 'org-properties
1952 :type '(choice
1953 (const :tag "Not" nil)
1954 (const :tag "Always" t)
1955 (repeat :tag "Specific properties" (string :tag "Property"))
1956 (regexp :tag "Properties matched by regexp")))
1958 (defun org-property-inherit-p (property)
1959 "Check if PROPERTY is one that should be inherited."
1960 (cond
1961 ((eq org-use-property-inheritance t) t)
1962 ((not org-use-property-inheritance) nil)
1963 ((stringp org-use-property-inheritance)
1964 (string-match org-use-property-inheritance property))
1965 ((listp org-use-property-inheritance)
1966 (member property org-use-property-inheritance))
1967 (t (error "Invalid setting of `org-use-property-inheritance'"))))
1969 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
1970 "The default column format, if no other format has been defined.
1971 This variable can be set on the per-file basis by inserting a line
1973 #+COLUMNS: %25ITEM ....."
1974 :group 'org-properties
1975 :type 'string)
1977 (defcustom org-columns-ellipses ".."
1978 "The ellipses to be used when a field in column view is truncated.
1979 When this is the empty string, as many characters as possible are shown,
1980 but then there will be no visual indication that the field has been truncated.
1981 When this is a string of length N, the last N characters of a truncated
1982 field are replaced by this string. If the column is narrower than the
1983 ellipses string, only part of the ellipses string will be shown."
1984 :group 'org-properties
1985 :type 'string)
1987 (defcustom org-columns-modify-value-for-display-function nil
1988 "Function that modifies values for display in column view.
1989 For example, it can be used to cut out a certain part from a time stamp.
1990 The function must take 2 arguments:
1992 column-title The tite of the column (*not* the property name)
1993 value The value that should be modified.
1995 The function should return the value that should be displayed,
1996 or nil if the normal value should be used."
1997 :group 'org-properties
1998 :type 'function)
2000 (defcustom org-effort-property "Effort"
2001 "The property that is being used to keep track of effort estimates.
2002 Effort estimates given in this property need to have the format H:MM."
2003 :group 'org-properties
2004 :group 'org-progress
2005 :type '(string :tag "Property"))
2007 (defconst org-global-properties-fixed
2008 '(("VISIBILITY_ALL" . "folded children content all"))
2009 "List of property/value pairs that can be inherited by any entry.
2010 These are fixed values, for the preset properties.")
2013 (defcustom org-global-properties nil
2014 "List of property/value pairs that can be inherited by any entry.
2015 You can set buffer-local values for this by adding lines like
2017 #+PROPERTY: NAME VALUE"
2018 :group 'org-properties
2019 :type '(repeat
2020 (cons (string :tag "Property")
2021 (string :tag "Value"))))
2023 (defvar org-file-properties nil
2024 "List of property/value pairs that can be inherited by any entry.
2025 Valid for the current buffer.
2026 This variable is populated from #+PROPERTY lines.")
2027 (make-variable-buffer-local 'org-file-properties)
2029 (defgroup org-agenda nil
2030 "Options concerning agenda views in Org-mode."
2031 :tag "Org Agenda"
2032 :group 'org)
2034 (defvar org-category nil
2035 "Variable used by org files to set a category for agenda display.
2036 Such files should use a file variable to set it, for example
2038 # -*- mode: org; org-category: \"ELisp\"
2040 or contain a special line
2042 #+CATEGORY: ELisp
2044 If the file does not specify a category, then file's base name
2045 is used instead.")
2046 (make-variable-buffer-local 'org-category)
2047 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2049 (defcustom org-agenda-files nil
2050 "The files to be used for agenda display.
2051 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2052 \\[org-remove-file]. You can also use customize to edit the list.
2054 If an entry is a directory, all files in that directory that are matched by
2055 `org-agenda-file-regexp' will be part of the file list.
2057 If the value of the variable is not a list but a single file name, then
2058 the list of agenda files is actually stored and maintained in that file, one
2059 agenda file per line."
2060 :group 'org-agenda
2061 :type '(choice
2062 (repeat :tag "List of files and directories" file)
2063 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2065 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2066 "Regular expression to match files for `org-agenda-files'.
2067 If any element in the list in that variable contains a directory instead
2068 of a normal file, all files in that directory that are matched by this
2069 regular expression will be included."
2070 :group 'org-agenda
2071 :type 'regexp)
2073 (defcustom org-agenda-text-search-extra-files nil
2074 "List of extra files to be searched by text search commands.
2075 These files will be search in addition to the agenda files by the
2076 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2077 Note that these files will only be searched for text search commands,
2078 not for the other agenda views like todo lists, tag searches or the weekly
2079 agenda. This variable is intended to list notes and possibly archive files
2080 that should also be searched by these two commands.
2081 In fact, if the first element in the list is the symbol `agenda-archives',
2082 than all archive files of all agenda files will be added to the search
2083 scope."
2084 :group 'org-agenda
2085 :type '(set :greedy t
2086 (const :tag "Agenda Archives" agenda-archives)
2087 (repeat :inline t (file))))
2089 (if (fboundp 'defvaralias)
2090 (defvaralias 'org-agenda-multi-occur-extra-files
2091 'org-agenda-text-search-extra-files))
2093 (defcustom org-agenda-skip-unavailable-files nil
2094 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2095 A nil value means to remove them, after a query, from the list."
2096 :group 'org-agenda
2097 :type 'boolean)
2099 (defcustom org-calendar-to-agenda-key [?c]
2100 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2101 The command `org-calendar-goto-agenda' will be bound to this key. The
2102 default is the character `c' because then `c' can be used to switch back and
2103 forth between agenda and calendar."
2104 :group 'org-agenda
2105 :type 'sexp)
2107 (defcustom org-calendar-agenda-action-key [?k]
2108 "The key to be installed in `calendar-mode-map' for agenda-action.
2109 The command `org-agenda-action' will be bound to this key. The
2110 default is the character `k' because we use the same key in the agenda."
2111 :group 'org-agenda
2112 :type 'sexp)
2114 (eval-after-load "calendar"
2115 '(progn
2116 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2117 'org-calendar-goto-agenda)
2118 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2119 'org-agenda-action)))
2121 (defgroup org-latex nil
2122 "Options for embedding LaTeX code into Org-mode."
2123 :tag "Org LaTeX"
2124 :group 'org)
2126 (defcustom org-format-latex-options
2127 '(:foreground default :background default :scale 1.0
2128 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2129 :matchers ("begin" "$" "$$" "\\(" "\\["))
2130 "Options for creating images from LaTeX fragments.
2131 This is a property list with the following properties:
2132 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2133 `default' means use the foreground of the default face.
2134 :background the background color, or \"Transparent\".
2135 `default' means use the background of the default face.
2136 :scale a scaling factor for the size of the images.
2137 :html-foreground, :html-background, :html-scale
2138 the same numbers for HTML export.
2139 :matchers a list indicating which matchers should be used to
2140 find LaTeX fragments. Valid members of this list are:
2141 \"begin\" find environments
2142 \"$\" find math expressions surrounded by $...$
2143 \"$$\" find math expressions surrounded by $$....$$
2144 \"\\(\" find math expressions surrounded by \\(...\\)
2145 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2146 :group 'org-latex
2147 :type 'plist)
2149 (defcustom org-format-latex-header "\\documentclass{article}
2150 \\usepackage{fullpage} % do not remove
2151 \\usepackage{amssymb}
2152 \\usepackage[usenames]{color}
2153 \\usepackage{amsmath}
2154 \\usepackage{latexsym}
2155 \\usepackage[mathscr]{eucal}
2156 \\pagestyle{empty} % do not remove"
2157 "The document header used for processing LaTeX fragments."
2158 :group 'org-latex
2159 :type 'string)
2162 (defgroup org-font-lock nil
2163 "Font-lock settings for highlighting in Org-mode."
2164 :tag "Org Font Lock"
2165 :group 'org)
2167 (defcustom org-level-color-stars-only nil
2168 "Non-nil means fontify only the stars in each headline.
2169 When nil, the entire headline is fontified.
2170 Changing it requires restart of `font-lock-mode' to become effective
2171 also in regions already fontified."
2172 :group 'org-font-lock
2173 :type 'boolean)
2175 (defcustom org-hide-leading-stars nil
2176 "Non-nil means, hide the first N-1 stars in a headline.
2177 This works by using the face `org-hide' for these stars. This
2178 face is white for a light background, and black for a dark
2179 background. You may have to customize the face `org-hide' to
2180 make this work.
2181 Changing it requires restart of `font-lock-mode' to become effective
2182 also in regions already fontified.
2183 You may also set this on a per-file basis by adding one of the following
2184 lines to the buffer:
2186 #+STARTUP: hidestars
2187 #+STARTUP: showstars"
2188 :group 'org-font-lock
2189 :type 'boolean)
2191 (defcustom org-fontify-done-headline nil
2192 "Non-nil means, change the face of a headline if it is marked DONE.
2193 Normally, only the TODO/DONE keyword indicates the state of a headline.
2194 When this is non-nil, the headline after the keyword is set to the
2195 `org-headline-done' as an additional indication."
2196 :group 'org-font-lock
2197 :type 'boolean)
2199 (defcustom org-fontify-emphasized-text t
2200 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2201 Changing this variable requires a restart of Emacs to take effect."
2202 :group 'org-font-lock
2203 :type 'boolean)
2205 (defcustom org-highlight-latex-fragments-and-specials nil
2206 "Non-nil means, fontify what is treated specially by the exporters."
2207 :group 'org-font-lock
2208 :type 'boolean)
2210 (defcustom org-hide-emphasis-markers nil
2211 "Non-nil mean font-lock should hide the emphasis marker characters."
2212 :group 'org-font-lock
2213 :type 'boolean)
2215 (defvar org-emph-re nil
2216 "Regular expression for matching emphasis.")
2217 (defvar org-verbatim-re nil
2218 "Regular expression for matching verbatim text.")
2219 (defvar org-emphasis-regexp-components) ; defined just below
2220 (defvar org-emphasis-alist) ; defined just below
2221 (defun org-set-emph-re (var val)
2222 "Set variable and compute the emphasis regular expression."
2223 (set var val)
2224 (when (and (boundp 'org-emphasis-alist)
2225 (boundp 'org-emphasis-regexp-components)
2226 org-emphasis-alist org-emphasis-regexp-components)
2227 (let* ((e org-emphasis-regexp-components)
2228 (pre (car e))
2229 (post (nth 1 e))
2230 (border (nth 2 e))
2231 (body (nth 3 e))
2232 (nl (nth 4 e))
2233 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
2234 (body1 (concat body "*?"))
2235 (markers (mapconcat 'car org-emphasis-alist ""))
2236 (vmarkers (mapconcat
2237 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2238 org-emphasis-alist "")))
2239 ;; make sure special characters appear at the right position in the class
2240 (if (string-match "\\^" markers)
2241 (setq markers (concat (replace-match "" t t markers) "^")))
2242 (if (string-match "-" markers)
2243 (setq markers (concat (replace-match "" t t markers) "-")))
2244 (if (string-match "\\^" vmarkers)
2245 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2246 (if (string-match "-" vmarkers)
2247 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2248 (if (> nl 0)
2249 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2250 (int-to-string nl) "\\}")))
2251 ;; Make the regexp
2252 (setq org-emph-re
2253 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
2254 "\\("
2255 "\\([" markers "]\\)"
2256 "\\("
2257 "[^" border "]\\|"
2258 "[^" border (if (and nil stacked) markers) "]"
2259 body1
2260 "[^" border (if (and nil stacked) markers) "]"
2261 "\\)"
2262 "\\3\\)"
2263 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
2264 (setq org-verbatim-re
2265 (concat "\\([" pre "]\\|^\\)"
2266 "\\("
2267 "\\([" vmarkers "]\\)"
2268 "\\("
2269 "[^" border "]\\|"
2270 "[^" border "]"
2271 body1
2272 "[^" border "]"
2273 "\\)"
2274 "\\3\\)"
2275 "\\([" post "]\\|$\\)")))))
2277 (defcustom org-emphasis-regexp-components
2278 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
2279 "Components used to build the regular expression for emphasis.
2280 This is a list with 6 entries. Terminology: In an emphasis string
2281 like \" *strong word* \", we call the initial space PREMATCH, the final
2282 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2283 and \"trong wor\" is the body. The different components in this variable
2284 specify what is allowed/forbidden in each part:
2286 pre Chars allowed as prematch. Beginning of line will be allowed too.
2287 post Chars allowed as postmatch. End of line will be allowed too.
2288 border The chars *forbidden* as border characters.
2289 body-regexp A regexp like \".\" to match a body character. Don't use
2290 non-shy groups here, and don't allow newline here.
2291 newline The maximum number of newlines allowed in an emphasis exp.
2293 Use customize to modify this, or restart Emacs after changing it."
2294 :group 'org-font-lock
2295 :set 'org-set-emph-re
2296 :type '(list
2297 (sexp :tag "Allowed chars in pre ")
2298 (sexp :tag "Allowed chars in post ")
2299 (sexp :tag "Forbidden chars in border ")
2300 (sexp :tag "Regexp for body ")
2301 (integer :tag "number of newlines allowed")
2302 (option (boolean :tag "Please ignore this button"))))
2304 (defcustom org-emphasis-alist
2305 `(("*" bold "<b>" "</b>")
2306 ("/" italic "<i>" "</i>")
2307 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
2308 ("=" org-code "<code>" "</code>" verbatim)
2309 ("~" org-verbatim "<code>" "</code>" verbatim)
2310 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2311 "<del>" "</del>")
2313 "Special syntax for emphasized text.
2314 Text starting and ending with a special character will be emphasized, for
2315 example *bold*, _underlined_ and /italic/. This variable sets the marker
2316 characters, the face to be used by font-lock for highlighting in Org-mode
2317 Emacs buffers, and the HTML tags to be used for this.
2318 Use customize to modify this, or restart Emacs after changing it."
2319 :group 'org-font-lock
2320 :set 'org-set-emph-re
2321 :type '(repeat
2322 (list
2323 (string :tag "Marker character")
2324 (choice
2325 (face :tag "Font-lock-face")
2326 (plist :tag "Face property list"))
2327 (string :tag "HTML start tag")
2328 (string :tag "HTML end tag")
2329 (option (const verbatim)))))
2331 ;;; Miscellaneous options
2333 (defgroup org-completion nil
2334 "Completion in Org-mode."
2335 :tag "Org Completion"
2336 :group 'org)
2338 (defcustom org-completion-fallback-command 'hippie-expand
2339 "The expansion command called by \\[org-complete] in normal context.
2340 Normal means, no org-mode-specific context."
2341 :group 'org-completion
2342 :type 'function)
2344 ;;; Functions and variables from ther packages
2345 ;; Declared here to avoid compiler warnings
2347 ;; XEmacs only
2348 (defvar outline-mode-menu-heading)
2349 (defvar outline-mode-menu-show)
2350 (defvar outline-mode-menu-hide)
2351 (defvar zmacs-regions) ; XEmacs regions
2353 ;; Emacs only
2354 (defvar mark-active)
2356 ;; Various packages
2357 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2358 (declare-function calendar-forward-day "cal-move" (arg))
2359 (declare-function calendar-goto-date "cal-move" (date))
2360 (declare-function calendar-goto-today "cal-move" ())
2361 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2362 (defvar calc-embedded-close-formula)
2363 (defvar calc-embedded-open-formula)
2364 (declare-function cdlatex-tab "ext:cdlatex" ())
2365 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2366 (defvar font-lock-unfontify-region-function)
2367 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2368 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2369 (defvar iswitchb-temp-buflist)
2370 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2371 (declare-function org-agenda-skip "org-agenda" ())
2372 (declare-function org-format-agenda-item "org-agenda"
2373 (extra txt &optional category tags dotime noprefix remove-re))
2374 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2375 (declare-function org-agenda-change-all-lines "org-agenda"
2376 (newhead hdmarker &optional fixface))
2377 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2378 (declare-function org-agenda-maybe-redo "org-agenda" ())
2379 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2380 (beg end))
2381 (declare-function parse-time-string "parse-time" (string))
2382 (declare-function remember "remember" (&optional initial))
2383 (declare-function remember-buffer-desc "remember" ())
2384 (declare-function remember-finalize "remember" ())
2385 (defvar remember-save-after-remembering)
2386 (defvar remember-data-file)
2387 (defvar remember-register)
2388 (defvar remember-buffer)
2389 (defvar remember-handler-functions)
2390 (defvar remember-annotation-functions)
2391 (defvar texmathp-why)
2392 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2393 (declare-function table--at-cell-p "table" (position &optional object at-column))
2395 (defvar w3m-current-url)
2396 (defvar w3m-current-title)
2398 (defvar org-latex-regexps)
2400 ;;; Autoload and prepare some org modules
2402 ;; Some table stuff that needs to be defined here, because it is used
2403 ;; by the functions setting up org-mode or checking for table context.
2405 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2406 "Detects an org-type or table-type table.")
2407 (defconst org-table-line-regexp "^[ \t]*|"
2408 "Detects an org-type table line.")
2409 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2410 "Detects an org-type table line.")
2411 (defconst org-table-hline-regexp "^[ \t]*|-"
2412 "Detects an org-type table hline.")
2413 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2414 "Detects a table-type table hline.")
2415 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2416 "Searching from within a table (any type) this finds the first line
2417 outside the table.")
2419 ;; Autoload the functions in org-table.el that are needed by functions here.
2421 (eval-and-compile
2422 (org-autoload "org-table"
2423 '(org-table-align org-table-begin org-table-blank-field
2424 org-table-convert org-table-convert-region org-table-copy-down
2425 org-table-copy-region org-table-create
2426 org-table-create-or-convert-from-region
2427 org-table-create-with-table.el org-table-current-dline
2428 org-table-cut-region org-table-delete-column org-table-edit-field
2429 org-table-edit-formulas org-table-end org-table-eval-formula
2430 org-table-export org-table-field-info
2431 org-table-get-stored-formulas org-table-goto-column
2432 org-table-hline-and-move org-table-import org-table-insert-column
2433 org-table-insert-hline org-table-insert-row org-table-iterate
2434 org-table-justify-field-maybe org-table-kill-row
2435 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2436 org-table-move-column org-table-move-column-left
2437 org-table-move-column-right org-table-move-row
2438 org-table-move-row-down org-table-move-row-up
2439 org-table-next-field org-table-next-row org-table-paste-rectangle
2440 org-table-previous-field org-table-recalculate
2441 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2442 org-table-toggle-coordinate-overlays
2443 org-table-toggle-formula-debugger org-table-wrap-region
2444 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
2446 (defun org-at-table-p (&optional table-type)
2447 "Return t if the cursor is inside an org-type table.
2448 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2449 (if org-enable-table-editor
2450 (save-excursion
2451 (beginning-of-line 1)
2452 (looking-at (if table-type org-table-any-line-regexp
2453 org-table-line-regexp)))
2454 nil))
2455 (defsubst org-table-p () (org-at-table-p))
2457 (defun org-at-table.el-p ()
2458 "Return t if and only if we are at a table.el table."
2459 (and (org-at-table-p 'any)
2460 (save-excursion
2461 (goto-char (org-table-begin 'any))
2462 (looking-at org-table1-hline-regexp))))
2463 (defun org-table-recognize-table.el ()
2464 "If there is a table.el table nearby, recognize it and move into it."
2465 (if org-table-tab-recognizes-table.el
2466 (if (org-at-table.el-p)
2467 (progn
2468 (beginning-of-line 1)
2469 (if (looking-at org-table-dataline-regexp)
2471 (if (looking-at org-table1-hline-regexp)
2472 (progn
2473 (beginning-of-line 2)
2474 (if (looking-at org-table-any-border-regexp)
2475 (beginning-of-line -1)))))
2476 (if (re-search-forward "|" (org-table-end t) t)
2477 (progn
2478 (require 'table)
2479 (if (table--at-cell-p (point))
2481 (message "recognizing table.el table...")
2482 (table-recognize-table)
2483 (message "recognizing table.el table...done")))
2484 (error "This should not happen..."))
2486 nil)
2487 nil))
2489 (defun org-at-table-hline-p ()
2490 "Return t if the cursor is inside a hline in a table."
2491 (if org-enable-table-editor
2492 (save-excursion
2493 (beginning-of-line 1)
2494 (looking-at org-table-hline-regexp))
2495 nil))
2497 (defvar org-table-clean-did-remove-column nil)
2499 (defun org-table-map-tables (function)
2500 "Apply FUNCTION to the start of all tables in the buffer."
2501 (save-excursion
2502 (save-restriction
2503 (widen)
2504 (goto-char (point-min))
2505 (while (re-search-forward org-table-any-line-regexp nil t)
2506 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2507 (beginning-of-line 1)
2508 (if (looking-at org-table-line-regexp)
2509 (save-excursion (funcall function)))
2510 (re-search-forward org-table-any-border-regexp nil 1))))
2511 (message "Mapping tables: done"))
2513 ;; Declare and autoload functions from org-exp.el
2515 (declare-function org-default-export-plist "org-exp")
2516 (declare-function org-infile-export-plist "org-exp")
2517 (declare-function org-get-current-options "org-exp")
2518 (eval-and-compile
2519 (org-autoload "org-exp"
2520 '(org-export org-export-as-ascii org-export-visible
2521 org-insert-export-options-template org-export-as-html-and-open
2522 org-export-as-html-batch org-export-as-html-to-buffer
2523 org-replace-region-by-html org-export-region-as-html
2524 org-export-as-html org-export-icalendar-this-file
2525 org-export-icalendar-all-agenda-files
2526 org-table-clean-before-export
2527 org-export-icalendar-combine-agenda-files org-export-as-xoxo)))
2529 ;; Declare and autoload functions from org-agenda.el
2531 (eval-and-compile
2532 (org-autoload "org-agenda"
2533 '(org-agenda org-agenda-list org-search-view
2534 org-todo-list org-tags-view org-agenda-list-stuck-projects
2535 org-diary org-agenda-to-appt)))
2537 ;; Autoload org-remember
2539 (eval-and-compile
2540 (org-autoload "org-remember"
2541 '(org-remember-insinuate org-remember-annotation
2542 org-remember-apply-template org-remember org-remember-handler)))
2544 ;; Autoload org-clock.el
2547 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
2548 (beg end))
2549 (declare-function org-update-mode-line "org-clock" ())
2550 (defvar org-clock-start-time)
2551 (defvar org-clock-marker (make-marker)
2552 "Marker recording the last clock-in.")
2554 (eval-and-compile
2555 (org-autoload
2556 "org-clock"
2557 '(org-clock-in org-clock-out org-clock-cancel
2558 org-clock-goto org-clock-sum org-clock-display
2559 org-remove-clock-overlays org-clock-report
2560 org-clocktable-shift org-dblock-write:clocktable
2561 org-get-clocktable)))
2563 (defun org-clock-update-time-maybe ()
2564 "If this is a CLOCK line, update it and return t.
2565 Otherwise, return nil."
2566 (interactive)
2567 (save-excursion
2568 (beginning-of-line 1)
2569 (skip-chars-forward " \t")
2570 (when (looking-at org-clock-string)
2571 (let ((re (concat "[ \t]*" org-clock-string
2572 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
2573 "\\([ \t]*=>.*\\)?\\)?"))
2574 ts te h m s neg)
2575 (cond
2576 ((not (looking-at re))
2577 nil)
2578 ((not (match-end 2))
2579 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2580 (> org-clock-marker (point))
2581 (<= org-clock-marker (point-at-eol)))
2582 ;; The clock is running here
2583 (setq org-clock-start-time
2584 (apply 'encode-time
2585 (org-parse-time-string (match-string 1))))
2586 (org-update-mode-line)))
2588 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
2589 (end-of-line 1)
2590 (setq ts (match-string 1)
2591 te (match-string 3))
2592 (setq s (- (time-to-seconds
2593 (apply 'encode-time (org-parse-time-string te)))
2594 (time-to-seconds
2595 (apply 'encode-time (org-parse-time-string ts))))
2596 neg (< s 0)
2597 s (abs s)
2598 h (floor (/ s 3600))
2599 s (- s (* 3600 h))
2600 m (floor (/ s 60))
2601 s (- s (* 60 s)))
2602 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
2603 t))))))
2605 (defun org-check-running-clock ()
2606 "Check if the current buffer contains the running clock.
2607 If yes, offer to stop it and to save the buffer with the changes."
2608 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2609 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
2610 (buffer-name))))
2611 (org-clock-out)
2612 (when (y-or-n-p "Save changed buffer?")
2613 (save-buffer))))
2615 (defun org-clocktable-try-shift (dir n)
2616 "Check if this line starts a clock table, if yes, shift the time block."
2617 (when (org-match-line "#\\+BEGIN: clocktable\\>")
2618 (org-clocktable-shift dir n)))
2620 ;; Autoload archiving code
2621 ;; The stuff that is needed for cycling and tags has to be defined here.
2623 (defgroup org-archive nil
2624 "Options concerning archiving in Org-mode."
2625 :tag "Org Archive"
2626 :group 'org-structure)
2628 (defcustom org-archive-location "%s_archive::"
2629 "The location where subtrees should be archived.
2631 Otherwise, the value of this variable is a string, consisting of two
2632 parts, separated by a double-colon.
2634 The first part is a file name - when omitted, archiving happens in the same
2635 file. %s will be replaced by the current file name (without directory part).
2636 Archiving to a different file is useful to keep archived entries from
2637 contributing to the Org-mode Agenda.
2639 The part after the double colon is a headline. The archived entries will be
2640 filed under that headline. When omitted, the subtrees are simply filed away
2641 at the end of the file, as top-level entries.
2643 Here are a few examples:
2644 \"%s_archive::\"
2645 If the current file is Projects.org, archive in file
2646 Projects.org_archive, as top-level trees. This is the default.
2648 \"::* Archived Tasks\"
2649 Archive in the current file, under the top-level headline
2650 \"* Archived Tasks\".
2652 \"~/org/archive.org::\"
2653 Archive in file ~/org/archive.org (absolute path), as top-level trees.
2655 \"basement::** Finished Tasks\"
2656 Archive in file ./basement (relative path), as level 3 trees
2657 below the level 2 heading \"** Finished Tasks\".
2659 You may set this option on a per-file basis by adding to the buffer a
2660 line like
2662 #+ARCHIVE: basement::** Finished Tasks
2664 You may also define it locally for a subtree by setting an ARCHIVE property
2665 in the entry. If such a property is found in an entry, or anywhere up
2666 the hierarchy, it will be used."
2667 :group 'org-archive
2668 :type 'string)
2670 (defcustom org-archive-tag "ARCHIVE"
2671 "The tag that marks a subtree as archived.
2672 An archived subtree does not open during visibility cycling, and does
2673 not contribute to the agenda listings.
2674 After changing this, font-lock must be restarted in the relevant buffers to
2675 get the proper fontification."
2676 :group 'org-archive
2677 :group 'org-keywords
2678 :type 'string)
2680 (defcustom org-agenda-skip-archived-trees t
2681 "Non-nil means, the agenda will skip any items located in archived trees.
2682 An archived tree is a tree marked with the tag ARCHIVE. The use of this
2683 variable is no longer recommended, you should leave it at the value t.
2684 Instead, use the key `v' to cycle the archives-mode in the agenda."
2685 :group 'org-archive
2686 :group 'org-agenda-skip
2687 :type 'boolean)
2689 (defcustom org-cycle-open-archived-trees nil
2690 "Non-nil means, `org-cycle' will open archived trees.
2691 An archived tree is a tree marked with the tag ARCHIVE.
2692 When nil, archived trees will stay folded. You can still open them with
2693 normal outline commands like `show-all', but not with the cycling commands."
2694 :group 'org-archive
2695 :group 'org-cycle
2696 :type 'boolean)
2698 (defcustom org-sparse-tree-open-archived-trees nil
2699 "Non-nil means sparse tree construction shows matches in archived trees.
2700 When nil, matches in these trees are highlighted, but the trees are kept in
2701 collapsed state."
2702 :group 'org-archive
2703 :group 'org-sparse-trees
2704 :type 'boolean)
2706 (defun org-cycle-hide-archived-subtrees (state)
2707 "Re-hide all archived subtrees after a visibility state change."
2708 (when (and (not org-cycle-open-archived-trees)
2709 (not (memq state '(overview folded))))
2710 (save-excursion
2711 (let* ((globalp (memq state '(contents all)))
2712 (beg (if globalp (point-min) (point)))
2713 (end (if globalp (point-max) (org-end-of-subtree t))))
2714 (org-hide-archived-subtrees beg end)
2715 (goto-char beg)
2716 (if (looking-at (concat ".*:" org-archive-tag ":"))
2717 (message "%s" (substitute-command-keys
2718 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
2720 (defun org-force-cycle-archived ()
2721 "Cycle subtree even if it is archived."
2722 (interactive)
2723 (setq this-command 'org-cycle)
2724 (let ((org-cycle-open-archived-trees t))
2725 (call-interactively 'org-cycle)))
2727 (defun org-hide-archived-subtrees (beg end)
2728 "Re-hide all archived subtrees after a visibility state change."
2729 (save-excursion
2730 (let* ((re (concat ":" org-archive-tag ":")))
2731 (goto-char beg)
2732 (while (re-search-forward re end t)
2733 (and (org-on-heading-p) (hide-subtree))
2734 (org-end-of-subtree t)))))
2736 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
2738 (eval-and-compile
2739 (org-autoload "org-archive"
2740 '(org-add-archive-files org-archive-subtree
2741 org-archive-to-archive-sibling org-toggle-archive-tag)))
2743 ;; Autoload Column View Code
2745 (declare-function org-columns-number-to-string "org-colview")
2746 (declare-function org-columns-get-format-and-top-level "org-colview")
2747 (declare-function org-columns-compute "org-colview")
2749 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
2750 '(org-columns-number-to-string org-columns-get-format-and-top-level
2751 org-columns-compute org-agenda-columns org-columns-remove-overlays
2752 org-columns org-insert-columns-dblock org-dblock-write:columnview))
2754 ;; Autoload ID code
2756 (org-autoload "org-id"
2757 '(org-id-get-create org-id-new org-id-copy org-id-get
2758 org-id-get-with-outline-path-completion
2759 org-id-get-with-outline-drilling
2760 org-id-goto org-id-find))
2762 ;;; Variables for pre-computed regular expressions, all buffer local
2764 (defvar org-drawer-regexp nil
2765 "Matches first line of a hidden block.")
2766 (make-variable-buffer-local 'org-drawer-regexp)
2767 (defvar org-todo-regexp nil
2768 "Matches any of the TODO state keywords.")
2769 (make-variable-buffer-local 'org-todo-regexp)
2770 (defvar org-not-done-regexp nil
2771 "Matches any of the TODO state keywords except the last one.")
2772 (make-variable-buffer-local 'org-not-done-regexp)
2773 (defvar org-todo-line-regexp nil
2774 "Matches a headline and puts TODO state into group 2 if present.")
2775 (make-variable-buffer-local 'org-todo-line-regexp)
2776 (defvar org-complex-heading-regexp nil
2777 "Matches a headline and puts everything into groups:
2778 group 1: the stars
2779 group 2: The todo keyword, maybe
2780 group 3: Priority cookie
2781 group 4: True headline
2782 group 5: Tags")
2783 (make-variable-buffer-local 'org-complex-heading-regexp)
2784 (defvar org-todo-line-tags-regexp nil
2785 "Matches a headline and puts TODO state into group 2 if present.
2786 Also put tags into group 4 if tags are present.")
2787 (make-variable-buffer-local 'org-todo-line-tags-regexp)
2788 (defvar org-nl-done-regexp nil
2789 "Matches newline followed by a headline with the DONE keyword.")
2790 (make-variable-buffer-local 'org-nl-done-regexp)
2791 (defvar org-looking-at-done-regexp nil
2792 "Matches the DONE keyword a point.")
2793 (make-variable-buffer-local 'org-looking-at-done-regexp)
2794 (defvar org-ds-keyword-length 12
2795 "Maximum length of the Deadline and SCHEDULED keywords.")
2796 (make-variable-buffer-local 'org-ds-keyword-length)
2797 (defvar org-deadline-regexp nil
2798 "Matches the DEADLINE keyword.")
2799 (make-variable-buffer-local 'org-deadline-regexp)
2800 (defvar org-deadline-time-regexp nil
2801 "Matches the DEADLINE keyword together with a time stamp.")
2802 (make-variable-buffer-local 'org-deadline-time-regexp)
2803 (defvar org-deadline-line-regexp nil
2804 "Matches the DEADLINE keyword and the rest of the line.")
2805 (make-variable-buffer-local 'org-deadline-line-regexp)
2806 (defvar org-scheduled-regexp nil
2807 "Matches the SCHEDULED keyword.")
2808 (make-variable-buffer-local 'org-scheduled-regexp)
2809 (defvar org-scheduled-time-regexp nil
2810 "Matches the SCHEDULED keyword together with a time stamp.")
2811 (make-variable-buffer-local 'org-scheduled-time-regexp)
2812 (defvar org-closed-time-regexp nil
2813 "Matches the CLOSED keyword together with a time stamp.")
2814 (make-variable-buffer-local 'org-closed-time-regexp)
2816 (defvar org-keyword-time-regexp nil
2817 "Matches any of the 4 keywords, together with the time stamp.")
2818 (make-variable-buffer-local 'org-keyword-time-regexp)
2819 (defvar org-keyword-time-not-clock-regexp nil
2820 "Matches any of the 3 keywords, together with the time stamp.")
2821 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
2822 (defvar org-maybe-keyword-time-regexp nil
2823 "Matches a timestamp, possibly preceeded by a keyword.")
2824 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
2825 (defvar org-planning-or-clock-line-re nil
2826 "Matches a line with planning or clock info.")
2827 (make-variable-buffer-local 'org-planning-or-clock-line-re)
2829 (defconst org-plain-time-of-day-regexp
2830 (concat
2831 "\\(\\<[012]?[0-9]"
2832 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2833 "\\(--?"
2834 "\\(\\<[012]?[0-9]"
2835 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2836 "\\)?")
2837 "Regular expression to match a plain time or time range.
2838 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2839 groups carry important information:
2840 0 the full match
2841 1 the first time, range or not
2842 8 the second time, if it is a range.")
2844 (defconst org-plain-time-extension-regexp
2845 (concat
2846 "\\(\\<[012]?[0-9]"
2847 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2848 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
2849 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
2850 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2851 groups carry important information:
2852 0 the full match
2853 7 hours of duration
2854 9 minutes of duration")
2856 (defconst org-stamp-time-of-day-regexp
2857 (concat
2858 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
2859 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
2860 "\\(--?"
2861 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
2862 "Regular expression to match a timestamp time or time range.
2863 After a match, the following groups carry important information:
2864 0 the full match
2865 1 date plus weekday, for backreferencing to make sure both times on same day
2866 2 the first time, range or not
2867 4 the second time, if it is a range.")
2869 (defconst org-startup-options
2870 '(("fold" org-startup-folded t)
2871 ("overview" org-startup-folded t)
2872 ("nofold" org-startup-folded nil)
2873 ("showall" org-startup-folded nil)
2874 ("content" org-startup-folded content)
2875 ("hidestars" org-hide-leading-stars t)
2876 ("showstars" org-hide-leading-stars nil)
2877 ("odd" org-odd-levels-only t)
2878 ("oddeven" org-odd-levels-only nil)
2879 ("align" org-startup-align-all-tables t)
2880 ("noalign" org-startup-align-all-tables nil)
2881 ("customtime" org-display-custom-times t)
2882 ("logdone" org-log-done time)
2883 ("lognotedone" org-log-done note)
2884 ("nologdone" org-log-done nil)
2885 ("lognoteclock-out" org-log-note-clock-out t)
2886 ("nolognoteclock-out" org-log-note-clock-out nil)
2887 ("logrepeat" org-log-repeat state)
2888 ("lognoterepeat" org-log-repeat note)
2889 ("nologrepeat" org-log-repeat nil)
2890 ("constcgs" constants-unit-system cgs)
2891 ("constSI" constants-unit-system SI))
2892 "Variable associated with STARTUP options for org-mode.
2893 Each element is a list of three items: The startup options as written
2894 in the #+STARTUP line, the corresponding variable, and the value to
2895 set this variable to if the option is found. An optional forth element PUSH
2896 means to push this value onto the list in the variable.")
2898 (defun org-set-regexps-and-options ()
2899 "Precompute regular expressions for current buffer."
2900 (when (org-mode-p)
2901 (org-set-local 'org-todo-kwd-alist nil)
2902 (org-set-local 'org-todo-key-alist nil)
2903 (org-set-local 'org-todo-key-trigger nil)
2904 (org-set-local 'org-todo-keywords-1 nil)
2905 (org-set-local 'org-done-keywords nil)
2906 (org-set-local 'org-todo-heads nil)
2907 (org-set-local 'org-todo-sets nil)
2908 (org-set-local 'org-todo-log-states nil)
2909 (org-set-local 'org-file-properties nil)
2910 (org-set-local 'org-file-tags nil)
2911 (let ((re (org-make-options-regexp
2912 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
2913 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
2914 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")))
2915 (splitre "[ \t]+")
2916 kwds kws0 kwsa key log value cat arch tags const links hw dws
2917 tail sep kws1 prio props ftags drawers
2918 ext-setup-or-nil setup-contents (start 0))
2919 (save-excursion
2920 (save-restriction
2921 (widen)
2922 (goto-char (point-min))
2923 (while (or (and ext-setup-or-nil
2924 (string-match re ext-setup-or-nil start)
2925 (setq start (match-end 0)))
2926 (and (setq ext-setup-or-nil nil start 0)
2927 (re-search-forward re nil t)))
2928 (setq key (upcase (match-string 1 ext-setup-or-nil))
2929 value (org-match-string-no-properties 2 ext-setup-or-nil))
2930 (cond
2931 ((equal key "CATEGORY")
2932 (if (string-match "[ \t]+$" value)
2933 (setq value (replace-match "" t t value)))
2934 (setq cat value))
2935 ((member key '("SEQ_TODO" "TODO"))
2936 (push (cons 'sequence (org-split-string value splitre)) kwds))
2937 ((equal key "TYP_TODO")
2938 (push (cons 'type (org-split-string value splitre)) kwds))
2939 ((equal key "TAGS")
2940 (setq tags (append tags (org-split-string value splitre))))
2941 ((equal key "COLUMNS")
2942 (org-set-local 'org-columns-default-format value))
2943 ((equal key "LINK")
2944 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
2945 (push (cons (match-string 1 value)
2946 (org-trim (match-string 2 value)))
2947 links)))
2948 ((equal key "PRIORITIES")
2949 (setq prio (org-split-string value " +")))
2950 ((equal key "PROPERTY")
2951 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
2952 (push (cons (match-string 1 value) (match-string 2 value))
2953 props)))
2954 ((equal key "FILETAGS")
2955 (when (string-match "\\S-" value)
2956 (setq ftags
2957 (append
2958 ftags
2959 (apply 'append
2960 (mapcar (lambda (x) (org-split-string x ":"))
2961 (org-split-string value)))))))
2962 ((equal key "DRAWERS")
2963 (setq drawers (org-split-string value splitre)))
2964 ((equal key "CONSTANTS")
2965 (setq const (append const (org-split-string value splitre))))
2966 ((equal key "STARTUP")
2967 (let ((opts (org-split-string value splitre))
2968 l var val)
2969 (while (setq l (pop opts))
2970 (when (setq l (assoc l org-startup-options))
2971 (setq var (nth 1 l) val (nth 2 l))
2972 (if (not (nth 3 l))
2973 (set (make-local-variable var) val)
2974 (if (not (listp (symbol-value var)))
2975 (set (make-local-variable var) nil))
2976 (set (make-local-variable var) (symbol-value var))
2977 (add-to-list var val))))))
2978 ((equal key "ARCHIVE")
2979 (string-match " *$" value)
2980 (setq arch (replace-match "" t t value))
2981 (remove-text-properties 0 (length arch)
2982 '(face t fontified t) arch))
2983 ((equal key "SETUPFILE")
2984 (setq setup-contents (org-file-contents
2985 (expand-file-name
2986 (org-remove-double-quotes value))
2987 'noerror))
2988 (if (not ext-setup-or-nil)
2989 (setq ext-setup-or-nil setup-contents start 0)
2990 (setq ext-setup-or-nil
2991 (concat (substring ext-setup-or-nil 0 start)
2992 "\n" setup-contents "\n"
2993 (substring ext-setup-or-nil start)))))
2994 ))))
2995 (when cat
2996 (org-set-local 'org-category (intern cat))
2997 (push (cons "CATEGORY" cat) props))
2998 (when prio
2999 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3000 (setq prio (mapcar 'string-to-char prio))
3001 (org-set-local 'org-highest-priority (nth 0 prio))
3002 (org-set-local 'org-lowest-priority (nth 1 prio))
3003 (org-set-local 'org-default-priority (nth 2 prio)))
3004 (and props (org-set-local 'org-file-properties (nreverse props)))
3005 (and ftags (org-set-local 'org-file-tags ftags))
3006 (and drawers (org-set-local 'org-drawers drawers))
3007 (and arch (org-set-local 'org-archive-location arch))
3008 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3009 ;; Process the TODO keywords
3010 (unless kwds
3011 ;; Use the global values as if they had been given locally.
3012 (setq kwds (default-value 'org-todo-keywords))
3013 (if (stringp (car kwds))
3014 (setq kwds (list (cons org-todo-interpretation
3015 (default-value 'org-todo-keywords)))))
3016 (setq kwds (reverse kwds)))
3017 (setq kwds (nreverse kwds))
3018 (let (inter kws kw)
3019 (while (setq kws (pop kwds))
3020 (setq inter (pop kws) sep (member "|" kws)
3021 kws0 (delete "|" (copy-sequence kws))
3022 kwsa nil
3023 kws1 (mapcar
3024 (lambda (x)
3025 ;; 1 2
3026 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3027 (progn
3028 (setq kw (match-string 1 x)
3029 key (and (match-end 2) (match-string 2 x))
3030 log (org-extract-log-state-settings x))
3031 (push (cons kw (and key (string-to-char key))) kwsa)
3032 (and log (push log org-todo-log-states))
3034 (error "Invalid TODO keyword %s" x)))
3035 kws0)
3036 kwsa (if kwsa (append '((:startgroup))
3037 (nreverse kwsa)
3038 '((:endgroup))))
3039 hw (car kws1)
3040 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3041 tail (list inter hw (car dws) (org-last dws)))
3042 (add-to-list 'org-todo-heads hw 'append)
3043 (push kws1 org-todo-sets)
3044 (setq org-done-keywords (append org-done-keywords dws nil))
3045 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3046 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3047 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3048 (setq org-todo-sets (nreverse org-todo-sets)
3049 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3050 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3051 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3052 ;; Process the constants
3053 (when const
3054 (let (e cst)
3055 (while (setq e (pop const))
3056 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3057 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3058 (setq org-table-formula-constants-local cst)))
3060 ;; Process the tags.
3061 (when tags
3062 (let (e tgs)
3063 (while (setq e (pop tags))
3064 (cond
3065 ((equal e "{") (push '(:startgroup) tgs))
3066 ((equal e "}") (push '(:endgroup) tgs))
3067 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3068 (push (cons (match-string 1 e)
3069 (string-to-char (match-string 2 e)))
3070 tgs))
3071 (t (push (list e) tgs))))
3072 (org-set-local 'org-tag-alist nil)
3073 (while (setq e (pop tgs))
3074 (or (and (stringp (car e))
3075 (assoc (car e) org-tag-alist))
3076 (push e org-tag-alist)))))
3078 ;; Compute the regular expressions and other local variables
3079 (if (not org-done-keywords)
3080 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
3081 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3082 (length org-scheduled-string)
3083 (length org-clock-string)
3084 (length org-closed-string)))
3085 org-drawer-regexp
3086 (concat "^[ \t]*:\\("
3087 (mapconcat 'regexp-quote org-drawers "\\|")
3088 "\\):[ \t]*$")
3089 org-not-done-keywords
3090 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3091 org-todo-regexp
3092 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3093 "\\|") "\\)\\>")
3094 org-not-done-regexp
3095 (concat "\\<\\("
3096 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3097 "\\)\\>")
3098 org-todo-line-regexp
3099 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3100 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3101 "\\)\\>\\)?[ \t]*\\(.*\\)")
3102 org-complex-heading-regexp
3103 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
3104 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3105 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3106 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3107 org-nl-done-regexp
3108 (concat "\n\\*+[ \t]+"
3109 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3110 "\\)" "\\>")
3111 org-todo-line-tags-regexp
3112 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3113 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3114 (org-re
3115 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3116 org-looking-at-done-regexp
3117 (concat "^" "\\(?:"
3118 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3119 "\\>")
3120 org-deadline-regexp (concat "\\<" org-deadline-string)
3121 org-deadline-time-regexp
3122 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3123 org-deadline-line-regexp
3124 (concat "\\<\\(" org-deadline-string "\\).*")
3125 org-scheduled-regexp
3126 (concat "\\<" org-scheduled-string)
3127 org-scheduled-time-regexp
3128 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3129 org-closed-time-regexp
3130 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3131 org-keyword-time-regexp
3132 (concat "\\<\\(" org-scheduled-string
3133 "\\|" org-deadline-string
3134 "\\|" org-closed-string
3135 "\\|" org-clock-string "\\)"
3136 " *[[<]\\([^]>]+\\)[]>]")
3137 org-keyword-time-not-clock-regexp
3138 (concat "\\<\\(" org-scheduled-string
3139 "\\|" org-deadline-string
3140 "\\|" org-closed-string
3141 "\\)"
3142 " *[[<]\\([^]>]+\\)[]>]")
3143 org-maybe-keyword-time-regexp
3144 (concat "\\(\\<\\(" org-scheduled-string
3145 "\\|" org-deadline-string
3146 "\\|" org-closed-string
3147 "\\|" org-clock-string "\\)\\)?"
3148 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3149 org-planning-or-clock-line-re
3150 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3151 "\\|" org-deadline-string
3152 "\\|" org-closed-string "\\|" org-clock-string
3153 "\\)\\>\\)")
3155 (org-compute-latex-and-specials-regexp)
3156 (org-set-font-lock-defaults))))
3158 (defun org-file-contents (file &optional noerror)
3159 "Return the contents of FILE, as a string."
3160 (if (or (not file)
3161 (not (file-readable-p file)))
3162 (if noerror
3163 (progn
3164 (message "Cannot read file %s" file)
3165 (ding) (sit-for 2)
3167 (error "Cannot read file %s" file))
3168 (with-temp-buffer
3169 (insert-file-contents file)
3170 (buffer-string))))
3172 (defun org-extract-log-state-settings (x)
3173 "Extract the log state setting from a TODO keyword string.
3174 This will extract info from a string like \"WAIT(w@/!)\"."
3175 (let (kw key log1 log2)
3176 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3177 (setq kw (match-string 1 x)
3178 key (and (match-end 2) (match-string 2 x))
3179 log1 (and (match-end 3) (match-string 3 x))
3180 log2 (and (match-end 4) (match-string 4 x)))
3181 (and (or log1 log2)
3182 (list kw
3183 (and log1 (if (equal log1 "!") 'time 'note))
3184 (and log2 (if (equal log2 "!") 'time 'note)))))))
3186 (defun org-remove-keyword-keys (list)
3187 "Remove a pair of parenthesis at the end of each string in LIST."
3188 (mapcar (lambda (x)
3189 (if (string-match "(.*)$" x)
3190 (substring x 0 (match-beginning 0))
3192 list))
3194 ;; FIXME: this could be done much better, using second characters etc.
3195 (defun org-assign-fast-keys (alist)
3196 "Assign fast keys to a keyword-key alist.
3197 Respect keys that are already there."
3198 (let (new e k c c1 c2 (char ?a))
3199 (while (setq e (pop alist))
3200 (cond
3201 ((equal e '(:startgroup)) (push e new))
3202 ((equal e '(:endgroup)) (push e new))
3204 (setq k (car e) c2 nil)
3205 (if (cdr e)
3206 (setq c (cdr e))
3207 ;; automatically assign a character.
3208 (setq c1 (string-to-char
3209 (downcase (substring
3210 k (if (= (string-to-char k) ?@) 1 0)))))
3211 (if (or (rassoc c1 new) (rassoc c1 alist))
3212 (while (or (rassoc char new) (rassoc char alist))
3213 (setq char (1+ char)))
3214 (setq c2 c1))
3215 (setq c (or c2 char)))
3216 (push (cons k c) new))))
3217 (nreverse new)))
3219 ;;; Some variables used in various places
3221 (defvar org-window-configuration nil
3222 "Used in various places to store a window configuration.")
3223 (defvar org-finish-function nil
3224 "Function to be called when `C-c C-c' is used.
3225 This is for getting out of special buffers like remember.")
3228 ;; FIXME: Occasionally check by commenting these, to make sure
3229 ;; no other functions uses these, forgetting to let-bind them.
3230 (defvar entry)
3231 (defvar state)
3232 (defvar last-state)
3233 (defvar date)
3234 (defvar description)
3236 ;; Defined somewhere in this file, but used before definition.
3237 (defvar org-html-entities)
3238 (defvar org-struct-menu)
3239 (defvar org-org-menu)
3240 (defvar org-tbl-menu)
3241 (defvar org-agenda-keymap)
3243 ;;;; Define the Org-mode
3245 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3246 (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."))
3249 ;; We use a before-change function to check if a table might need
3250 ;; an update.
3251 (defvar org-table-may-need-update t
3252 "Indicates that a table might need an update.
3253 This variable is set by `org-before-change-function'.
3254 `org-table-align' sets it back to nil.")
3255 (defun org-before-change-function (beg end)
3256 "Every change indicates that a table might need an update."
3257 (setq org-table-may-need-update t))
3258 (defvar org-mode-map)
3259 (defvar org-mode-hook nil)
3260 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3261 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3262 (defvar org-table-buffer-is-an nil)
3263 (defconst org-outline-regexp "\\*+ ")
3265 ;;;###autoload
3266 (define-derived-mode org-mode outline-mode "Org"
3267 "Outline-based notes management and organizer, alias
3268 \"Carsten's outline-mode for keeping track of everything.\"
3270 Org-mode develops organizational tasks around a NOTES file which
3271 contains information about projects as plain text. Org-mode is
3272 implemented on top of outline-mode, which is ideal to keep the content
3273 of large files well structured. It supports ToDo items, deadlines and
3274 time stamps, which magically appear in the diary listing of the Emacs
3275 calendar. Tables are easily created with a built-in table editor.
3276 Plain text URL-like links connect to websites, emails (VM), Usenet
3277 messages (Gnus), BBDB entries, and any files related to the project.
3278 For printing and sharing of notes, an Org-mode file (or a part of it)
3279 can be exported as a structured ASCII or HTML file.
3281 The following commands are available:
3283 \\{org-mode-map}"
3285 ;; Get rid of Outline menus, they are not needed
3286 ;; Need to do this here because define-derived-mode sets up
3287 ;; the keymap so late. Still, it is a waste to call this each time
3288 ;; we switch another buffer into org-mode.
3289 (if (featurep 'xemacs)
3290 (when (boundp 'outline-mode-menu-heading)
3291 ;; Assume this is Greg's port, it used easymenu
3292 (easy-menu-remove outline-mode-menu-heading)
3293 (easy-menu-remove outline-mode-menu-show)
3294 (easy-menu-remove outline-mode-menu-hide))
3295 (define-key org-mode-map [menu-bar headings] 'undefined)
3296 (define-key org-mode-map [menu-bar hide] 'undefined)
3297 (define-key org-mode-map [menu-bar show] 'undefined))
3299 (org-load-modules-maybe)
3300 (easy-menu-add org-org-menu)
3301 (easy-menu-add org-tbl-menu)
3302 (org-install-agenda-files-menu)
3303 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3304 (org-add-to-invisibility-spec '(org-cwidth))
3305 (when (featurep 'xemacs)
3306 (org-set-local 'line-move-ignore-invisible t))
3307 (org-set-local 'outline-regexp org-outline-regexp)
3308 (org-set-local 'outline-level 'org-outline-level)
3309 (when (and org-ellipsis
3310 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3311 (fboundp 'make-glyph-code))
3312 (unless org-display-table
3313 (setq org-display-table (make-display-table)))
3314 (set-display-table-slot
3315 org-display-table 4
3316 (vconcat (mapcar
3317 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3318 org-ellipsis)))
3319 (if (stringp org-ellipsis) org-ellipsis "..."))))
3320 (setq buffer-display-table org-display-table))
3321 (org-set-regexps-and-options)
3322 ;; Calc embedded
3323 (org-set-local 'calc-embedded-open-mode "# ")
3324 (modify-syntax-entry ?# "<")
3325 (modify-syntax-entry ?@ "w")
3326 (if org-startup-truncated (setq truncate-lines t))
3327 (org-set-local 'font-lock-unfontify-region-function
3328 'org-unfontify-region)
3329 ;; Activate before-change-function
3330 (org-set-local 'org-table-may-need-update t)
3331 (org-add-hook 'before-change-functions 'org-before-change-function nil
3332 'local)
3333 ;; Check for running clock before killing a buffer
3334 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3335 ;; Paragraphs and auto-filling
3336 (org-set-autofill-regexps)
3337 (setq indent-line-function 'org-indent-line-function)
3338 (org-update-radio-target-regexp)
3340 ;; Comment characters
3341 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3342 (org-set-local 'comment-padding " ")
3344 ;; Align options lines
3345 (org-set-local
3346 'align-mode-rules-list
3347 '((org-in-buffer-settings
3348 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3349 (modes . '(org-mode)))))
3351 ;; Imenu
3352 (org-set-local 'imenu-create-index-function
3353 'org-imenu-get-tree)
3355 ;; Make isearch reveal context
3356 (if (or (featurep 'xemacs)
3357 (not (boundp 'outline-isearch-open-invisible-function)))
3358 ;; Emacs 21 and XEmacs make use of the hook
3359 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3360 ;; Emacs 22 deals with this through a special variable
3361 (org-set-local 'outline-isearch-open-invisible-function
3362 (lambda (&rest ignore) (org-show-context 'isearch))))
3364 ;; If empty file that did not turn on org-mode automatically, make it to.
3365 (if (and org-insert-mode-line-in-empty-file
3366 (interactive-p)
3367 (= (point-min) (point-max)))
3368 (insert "# -*- mode: org -*-\n\n"))
3370 (unless org-inhibit-startup
3371 (when org-startup-align-all-tables
3372 (let ((bmp (buffer-modified-p)))
3373 (org-table-map-tables 'org-table-align)
3374 (set-buffer-modified-p bmp)))
3375 (org-set-startup-visibility)))
3377 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3379 (defun org-current-time ()
3380 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3381 (if (> (car org-time-stamp-rounding-minutes) 1)
3382 (let ((r (car org-time-stamp-rounding-minutes))
3383 (time (decode-time)))
3384 (apply 'encode-time
3385 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3386 (nthcdr 2 time))))
3387 (current-time)))
3389 ;;;; Font-Lock stuff, including the activators
3391 (defvar org-mouse-map (make-sparse-keymap))
3392 (org-defkey org-mouse-map
3393 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3394 (org-defkey org-mouse-map
3395 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3396 (when org-mouse-1-follows-link
3397 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3398 (when org-tab-follows-link
3399 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3400 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3401 (when org-return-follows-link
3402 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
3403 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
3405 (require 'font-lock)
3407 (defconst org-non-link-chars "]\t\n\r<>")
3408 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3409 "shell" "elisp"))
3410 (defvar org-link-types-re nil
3411 "Matches a link that has a url-like prefix like \"http:\"")
3412 (defvar org-link-re-with-space nil
3413 "Matches a link with spaces, optional angular brackets around it.")
3414 (defvar org-link-re-with-space2 nil
3415 "Matches a link with spaces, optional angular brackets around it.")
3416 (defvar org-link-re-with-space3 nil
3417 "Matches a link with spaces, only for internal part in bracket links.")
3418 (defvar org-angle-link-re nil
3419 "Matches link with angular brackets, spaces are allowed.")
3420 (defvar org-plain-link-re nil
3421 "Matches plain link, without spaces.")
3422 (defvar org-bracket-link-regexp nil
3423 "Matches a link in double brackets.")
3424 (defvar org-bracket-link-analytic-regexp nil
3425 "Regular expression used to analyze links.
3426 Here is what the match groups contain after a match:
3427 1: http:
3428 2: http
3429 3: path
3430 4: [desc]
3431 5: desc")
3432 (defvar org-any-link-re nil
3433 "Regular expression matching any link.")
3435 (defun org-make-link-regexps ()
3436 "Update the link regular expressions.
3437 This should be called after the variable `org-link-types' has changed."
3438 (setq org-link-types-re
3439 (concat
3440 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3441 org-link-re-with-space
3442 (concat
3443 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3444 "\\([^" org-non-link-chars " ]"
3445 "[^" org-non-link-chars "]*"
3446 "[^" org-non-link-chars " ]\\)>?")
3447 org-link-re-with-space2
3448 (concat
3449 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3450 "\\([^" org-non-link-chars " ]"
3451 "[^\t\n\r]*"
3452 "[^" org-non-link-chars " ]\\)>?")
3453 org-link-re-with-space3
3454 (concat
3455 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3456 "\\([^" org-non-link-chars " ]"
3457 "[^\t\n\r]*\\)")
3458 org-angle-link-re
3459 (concat
3460 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3461 "\\([^" org-non-link-chars " ]"
3462 "[^" org-non-link-chars "]*"
3463 "\\)>")
3464 org-plain-link-re
3465 (concat
3466 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3467 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3468 org-bracket-link-regexp
3469 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3470 org-bracket-link-analytic-regexp
3471 (concat
3472 "\\[\\["
3473 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3474 "\\([^]]+\\)"
3475 "\\]"
3476 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3477 "\\]")
3478 org-any-link-re
3479 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3480 org-angle-link-re "\\)\\|\\("
3481 org-plain-link-re "\\)")))
3483 (org-make-link-regexps)
3485 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
3486 "Regular expression for fast time stamp matching.")
3487 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
3488 "Regular expression for fast time stamp matching.")
3489 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3490 "Regular expression matching time strings for analysis.
3491 This one does not require the space after the date, so it can be used
3492 on a string that terminates immediately after the date.")
3493 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3494 "Regular expression matching time strings for analysis.")
3495 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
3496 "Regular expression matching time stamps, with groups.")
3497 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
3498 "Regular expression matching time stamps (also [..]), with groups.")
3499 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3500 "Regular expression matching a time stamp range.")
3501 (defconst org-tr-regexp-both
3502 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3503 "Regular expression matching a time stamp range.")
3504 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3505 org-ts-regexp "\\)?")
3506 "Regular expression matching a time stamp or time stamp range.")
3507 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3508 org-ts-regexp-both "\\)?")
3509 "Regular expression matching a time stamp or time stamp range.
3510 The time stamps may be either active or inactive.")
3512 (defvar org-emph-face nil)
3514 (defun org-do-emphasis-faces (limit)
3515 "Run through the buffer and add overlays to links."
3516 (let (rtn)
3517 (while (and (not rtn) (re-search-forward org-emph-re limit t))
3518 (if (not (= (char-after (match-beginning 3))
3519 (char-after (match-beginning 4))))
3520 (progn
3521 (setq rtn t)
3522 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3523 'face
3524 (nth 1 (assoc (match-string 3)
3525 org-emphasis-alist)))
3526 (add-text-properties (match-beginning 2) (match-end 2)
3527 '(font-lock-multiline t))
3528 (when org-hide-emphasis-markers
3529 (add-text-properties (match-end 4) (match-beginning 5)
3530 '(invisible org-link))
3531 (add-text-properties (match-beginning 3) (match-end 3)
3532 '(invisible org-link)))))
3533 (backward-char 1))
3534 rtn))
3536 (defun org-emphasize (&optional char)
3537 "Insert or change an emphasis, i.e. a font like bold or italic.
3538 If there is an active region, change that region to a new emphasis.
3539 If there is no region, just insert the marker characters and position
3540 the cursor between them.
3541 CHAR should be either the marker character, or the first character of the
3542 HTML tag associated with that emphasis. If CHAR is a space, the means
3543 to remove the emphasis of the selected region.
3544 If char is not given (for example in an interactive call) it
3545 will be prompted for."
3546 (interactive)
3547 (let ((eal org-emphasis-alist) e det
3548 (erc org-emphasis-regexp-components)
3549 (prompt "")
3550 (string "") beg end move tag c s)
3551 (if (org-region-active-p)
3552 (setq beg (region-beginning) end (region-end)
3553 string (buffer-substring beg end))
3554 (setq move t))
3556 (while (setq e (pop eal))
3557 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
3558 c (aref tag 0))
3559 (push (cons c (string-to-char (car e))) det)
3560 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
3561 (substring tag 1)))))
3562 (setq det (nreverse det))
3563 (unless char
3564 (message "%s" (concat "Emphasis marker or tag:" prompt))
3565 (setq char (read-char-exclusive)))
3566 (setq char (or (cdr (assoc char det)) char))
3567 (if (equal char ?\ )
3568 (setq s "" move nil)
3569 (unless (assoc (char-to-string char) org-emphasis-alist)
3570 (error "No such emphasis marker: \"%c\"" char))
3571 (setq s (char-to-string char)))
3572 (while (and (> (length string) 1)
3573 (equal (substring string 0 1) (substring string -1))
3574 (assoc (substring string 0 1) org-emphasis-alist))
3575 (setq string (substring string 1 -1)))
3576 (setq string (concat s string s))
3577 (if beg (delete-region beg end))
3578 (unless (or (bolp)
3579 (string-match (concat "[" (nth 0 erc) "\n]")
3580 (char-to-string (char-before (point)))))
3581 (insert " "))
3582 (unless (string-match (concat "[" (nth 1 erc) "\n]")
3583 (char-to-string (char-after (point))))
3584 (insert " ") (backward-char 1))
3585 (insert string)
3586 (and move (backward-char 1))))
3588 (defconst org-nonsticky-props
3589 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
3592 (defun org-activate-plain-links (limit)
3593 "Run through the buffer and add overlays to links."
3594 (catch 'exit
3595 (let (f)
3596 (while (re-search-forward org-plain-link-re limit t)
3597 (setq f (get-text-property (match-beginning 0) 'face))
3598 (if (or (eq f 'org-tag)
3599 (and (listp f) (memq 'org-tag f)))
3601 (add-text-properties (match-beginning 0) (match-end 0)
3602 (list 'mouse-face 'highlight
3603 'rear-nonsticky org-nonsticky-props
3604 'keymap org-mouse-map
3606 (throw 'exit t))))))
3608 (defun org-activate-code (limit)
3609 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
3610 (progn
3611 (remove-text-properties (match-beginning 0) (match-end 0)
3612 '(display t invisible t intangible t))
3613 t)))
3615 (defun org-activate-angle-links (limit)
3616 "Run through the buffer and add overlays to links."
3617 (if (re-search-forward org-angle-link-re limit t)
3618 (progn
3619 (add-text-properties (match-beginning 0) (match-end 0)
3620 (list 'mouse-face 'highlight
3621 'rear-nonsticky org-nonsticky-props
3622 'keymap org-mouse-map
3624 t)))
3626 (defun org-activate-bracket-links (limit)
3627 "Run through the buffer and add overlays to bracketed links."
3628 (if (re-search-forward org-bracket-link-regexp limit t)
3629 (let* ((help (concat "LINK: "
3630 (org-match-string-no-properties 1)))
3631 ;; FIXME: above we should remove the escapes.
3632 ;; but that requires another match, protecting match data,
3633 ;; a lot of overhead for font-lock.
3634 (ip (org-maybe-intangible
3635 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
3636 'keymap org-mouse-map 'mouse-face 'highlight
3637 'font-lock-multiline t 'help-echo help)))
3638 (vp (list 'rear-nonsticky org-nonsticky-props
3639 'keymap org-mouse-map 'mouse-face 'highlight
3640 ' font-lock-multiline t 'help-echo help)))
3641 ;; We need to remove the invisible property here. Table narrowing
3642 ;; may have made some of this invisible.
3643 (remove-text-properties (match-beginning 0) (match-end 0)
3644 '(invisible nil))
3645 (if (match-end 3)
3646 (progn
3647 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3648 (add-text-properties (match-beginning 3) (match-end 3) vp)
3649 (add-text-properties (match-end 3) (match-end 0) ip))
3650 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3651 (add-text-properties (match-beginning 1) (match-end 1) vp)
3652 (add-text-properties (match-end 1) (match-end 0) ip))
3653 t)))
3655 (defun org-activate-dates (limit)
3656 "Run through the buffer and add overlays to dates."
3657 (if (re-search-forward org-tsr-regexp-both limit t)
3658 (progn
3659 (add-text-properties (match-beginning 0) (match-end 0)
3660 (list 'mouse-face 'highlight
3661 'rear-nonsticky org-nonsticky-props
3662 'keymap org-mouse-map))
3663 (when org-display-custom-times
3664 (if (match-end 3)
3665 (org-display-custom-time (match-beginning 3) (match-end 3)))
3666 (org-display-custom-time (match-beginning 1) (match-end 1)))
3667 t)))
3669 (defvar org-target-link-regexp nil
3670 "Regular expression matching radio targets in plain text.")
3671 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3672 "Regular expression matching a link target.")
3673 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3674 "Regular expression matching a radio target.")
3675 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
3676 "Regular expression matching any target.")
3678 (defun org-activate-target-links (limit)
3679 "Run through the buffer and add overlays to target matches."
3680 (when org-target-link-regexp
3681 (let ((case-fold-search t))
3682 (if (re-search-forward org-target-link-regexp limit t)
3683 (progn
3684 (add-text-properties (match-beginning 0) (match-end 0)
3685 (list 'mouse-face 'highlight
3686 'rear-nonsticky org-nonsticky-props
3687 'keymap org-mouse-map
3688 'help-echo "Radio target link"
3689 'org-linked-text t))
3690 t)))))
3692 (defun org-update-radio-target-regexp ()
3693 "Find all radio targets in this file and update the regular expression."
3694 (interactive)
3695 (when (memq 'radio org-activate-links)
3696 (setq org-target-link-regexp
3697 (org-make-target-link-regexp (org-all-targets 'radio)))
3698 (org-restart-font-lock)))
3700 (defun org-hide-wide-columns (limit)
3701 (let (s e)
3702 (setq s (text-property-any (point) (or limit (point-max))
3703 'org-cwidth t))
3704 (when s
3705 (setq e (next-single-property-change s 'org-cwidth))
3706 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
3707 (goto-char e)
3708 t)))
3710 (defvar org-latex-and-specials-regexp nil
3711 "Regular expression for highlighting export special stuff.")
3712 (defvar org-match-substring-regexp)
3713 (defvar org-match-substring-with-braces-regexp)
3714 (defvar org-export-html-special-string-regexps)
3716 (defun org-compute-latex-and-specials-regexp ()
3717 "Compute regular expression for stuff treated specially by exporters."
3718 (if (not org-highlight-latex-fragments-and-specials)
3719 (org-set-local 'org-latex-and-specials-regexp nil)
3720 (require 'org-exp)
3721 (let*
3722 ((matchers (plist-get org-format-latex-options :matchers))
3723 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
3724 org-latex-regexps)))
3725 (options (org-combine-plists (org-default-export-plist)
3726 (org-infile-export-plist)))
3727 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
3728 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
3729 (org-export-with-TeX-macros (plist-get options :TeX-macros))
3730 (org-export-html-expand (plist-get options :expand-quoted-html))
3731 (org-export-with-special-strings (plist-get options :special-strings))
3732 (re-sub
3733 (cond
3734 ((equal org-export-with-sub-superscripts '{})
3735 (list org-match-substring-with-braces-regexp))
3736 (org-export-with-sub-superscripts
3737 (list org-match-substring-regexp))
3738 (t nil)))
3739 (re-latex
3740 (if org-export-with-LaTeX-fragments
3741 (mapcar (lambda (x) (nth 1 x)) latexs)))
3742 (re-macros
3743 (if org-export-with-TeX-macros
3744 (list (concat "\\\\"
3745 (regexp-opt
3746 (append (mapcar 'car org-html-entities)
3747 (if (boundp 'org-latex-entities)
3748 org-latex-entities nil))
3749 'words))) ; FIXME
3751 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
3752 (re-special (if org-export-with-special-strings
3753 (mapcar (lambda (x) (car x))
3754 org-export-html-special-string-regexps)))
3755 (re-rest
3756 (delq nil
3757 (list
3758 (if org-export-html-expand "@<[^>\n]+>")
3759 ))))
3760 (org-set-local
3761 'org-latex-and-specials-regexp
3762 (mapconcat 'identity (append re-latex re-sub re-macros re-special
3763 re-rest) "\\|")))))
3765 (defun org-do-latex-and-special-faces (limit)
3766 "Run through the buffer and add overlays to links."
3767 (when org-latex-and-specials-regexp
3768 (let (rtn d)
3769 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
3770 limit t))
3771 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
3772 'face))
3773 '(org-code org-verbatim underline)))
3774 (progn
3775 (setq rtn t
3776 d (cond ((member (char-after (1+ (match-beginning 0)))
3777 '(?_ ?^)) 1)
3778 (t 0)))
3779 (font-lock-prepend-text-property
3780 (+ d (match-beginning 0)) (match-end 0)
3781 'face 'org-latex-and-export-specials)
3782 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
3783 '(font-lock-multiline t)))))
3784 rtn)))
3786 (defun org-restart-font-lock ()
3787 "Restart font-lock-mode, to force refontification."
3788 (when (and (boundp 'font-lock-mode) font-lock-mode)
3789 (font-lock-mode -1)
3790 (font-lock-mode 1)))
3792 (defun org-all-targets (&optional radio)
3793 "Return a list of all targets in this file.
3794 With optional argument RADIO, only find radio targets."
3795 (let ((re (if radio org-radio-target-regexp org-target-regexp))
3796 rtn)
3797 (save-excursion
3798 (goto-char (point-min))
3799 (while (re-search-forward re nil t)
3800 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
3801 rtn)))
3803 (defun org-make-target-link-regexp (targets)
3804 "Make regular expression matching all strings in TARGETS.
3805 The regular expression finds the targets also if there is a line break
3806 between words."
3807 (and targets
3808 (concat
3809 "\\<\\("
3810 (mapconcat
3811 (lambda (x)
3812 (while (string-match " +" x)
3813 (setq x (replace-match "\\s-+" t t x)))
3815 targets
3816 "\\|")
3817 "\\)\\>")))
3819 (defun org-activate-tags (limit)
3820 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
3821 (progn
3822 (add-text-properties (match-beginning 1) (match-end 1)
3823 (list 'mouse-face 'highlight
3824 'rear-nonsticky org-nonsticky-props
3825 'keymap org-mouse-map))
3826 t)))
3828 (defun org-outline-level ()
3829 (save-excursion
3830 (looking-at outline-regexp)
3831 (if (match-beginning 1)
3832 (+ (org-get-string-indentation (match-string 1)) 1000)
3833 (1- (- (match-end 0) (match-beginning 0))))))
3835 (defvar org-font-lock-keywords nil)
3837 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
3838 "Regular expression matching a property line.")
3840 (defvar org-font-lock-hook nil
3841 "Functions to be called for special font lock stuff.")
3843 (defun org-font-lock-hook (limit)
3844 (run-hook-with-args 'org-font-lock-hook limit))
3846 (defun org-set-font-lock-defaults ()
3847 (let* ((em org-fontify-emphasized-text)
3848 (lk org-activate-links)
3849 (org-font-lock-extra-keywords
3850 (list
3851 ;; Call the hook
3852 '(org-font-lock-hook)
3853 ;; Headlines
3854 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
3855 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
3856 ;; Table lines
3857 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
3858 (1 'org-table t))
3859 ;; Table internals
3860 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
3861 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
3862 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
3863 ;; Drawers
3864 (list org-drawer-regexp '(0 'org-special-keyword t))
3865 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
3866 ;; Properties
3867 (list org-property-re
3868 '(1 'org-special-keyword t)
3869 '(3 'org-property-value t))
3870 (if org-format-transports-properties-p
3871 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
3872 ;; Links
3873 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
3874 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
3875 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
3876 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
3877 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
3878 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
3879 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
3880 '(org-hide-wide-columns (0 nil append))
3881 ;; TODO lines
3882 (list (concat "^\\*+[ \t]+" org-todo-regexp)
3883 '(1 (org-get-todo-face 1) t))
3884 ;; DONE
3885 (if org-fontify-done-headline
3886 (list (concat "^[*]+ +\\<\\("
3887 (mapconcat 'regexp-quote org-done-keywords "\\|")
3888 "\\)\\(.*\\)")
3889 '(2 'org-headline-done t))
3890 nil)
3891 ;; Priorities
3892 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
3893 ;; Special keywords
3894 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
3895 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
3896 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
3897 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
3898 ;; Emphasis
3899 (if em
3900 (if (featurep 'xemacs)
3901 '(org-do-emphasis-faces (0 nil append))
3902 '(org-do-emphasis-faces)))
3903 ;; Checkboxes
3904 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
3905 2 'bold prepend)
3906 (if org-provide-checkbox-statistics
3907 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
3908 (0 (org-get-checkbox-statistics-face) t)))
3909 ;; Description list items
3910 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
3911 2 'bold prepend)
3912 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
3913 '(1 'org-archived prepend))
3914 ;; Specials
3915 '(org-do-latex-and-special-faces)
3916 ;; Code
3917 '(org-activate-code (1 'org-code t))
3918 ;; COMMENT
3919 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
3920 "\\|" org-quote-string "\\)\\>")
3921 '(1 'org-special-keyword t))
3922 '("^#.*" (0 'font-lock-comment-face t))
3924 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
3925 ;; Now set the full font-lock-keywords
3926 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
3927 (org-set-local 'font-lock-defaults
3928 '(org-font-lock-keywords t nil nil backward-paragraph))
3929 (kill-local-variable 'font-lock-keywords) nil))
3931 (defvar org-m nil)
3932 (defvar org-l nil)
3933 (defvar org-f nil)
3934 (defun org-get-level-face (n)
3935 "Get the right face for match N in font-lock matching of healdines."
3936 (setq org-l (- (match-end 2) (match-beginning 1) 1))
3937 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
3938 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
3939 (cond
3940 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
3941 ((eq n 2) org-f)
3942 (t (if org-level-color-stars-only nil org-f))))
3944 (defun org-get-todo-face (kwd)
3945 "Get the right face for a TODO keyword KWD.
3946 If KWD is a number, get the corresponding match group."
3947 (if (numberp kwd) (setq kwd (match-string kwd)))
3948 (or (cdr (assoc kwd org-todo-keyword-faces))
3949 (and (member kwd org-done-keywords) 'org-done)
3950 'org-todo))
3952 (defun org-unfontify-region (beg end &optional maybe_loudly)
3953 "Remove fontification and activation overlays from links."
3954 (font-lock-default-unfontify-region beg end)
3955 (let* ((buffer-undo-list t)
3956 (inhibit-read-only t) (inhibit-point-motion-hooks t)
3957 (inhibit-modification-hooks t)
3958 deactivate-mark buffer-file-name buffer-file-truename)
3959 (remove-text-properties beg end
3960 '(mouse-face t keymap t org-linked-text t
3961 invisible t intangible t))))
3963 ;;;; Visibility cycling, including org-goto and indirect buffer
3965 ;;; Cycling
3967 (defvar org-cycle-global-status nil)
3968 (make-variable-buffer-local 'org-cycle-global-status)
3969 (defvar org-cycle-subtree-status nil)
3970 (make-variable-buffer-local 'org-cycle-subtree-status)
3972 ;;;###autoload
3973 (defun org-cycle (&optional arg)
3974 "Visibility cycling for Org-mode.
3976 - When this function is called with a prefix argument, rotate the entire
3977 buffer through 3 states (global cycling)
3978 1. OVERVIEW: Show only top-level headlines.
3979 2. CONTENTS: Show all headlines of all levels, but no body text.
3980 3. SHOW ALL: Show everything.
3981 When called with two C-u C-u prefixes, switch to the startup visibility,
3982 determined by the variable `org-startup-folded', and by any VISIBILITY
3983 properties in the buffer.
3984 When called with three C-u C-u C-u prefixed, show the entire buffer,
3985 including drawers.
3987 - When point is at the beginning of a headline, rotate the subtree started
3988 by this line through 3 different states (local cycling)
3989 1. FOLDED: Only the main headline is shown.
3990 2. CHILDREN: The main headline and the direct children are shown.
3991 From this state, you can move to one of the children
3992 and zoom in further.
3993 3. SUBTREE: Show the entire subtree, including body text.
3995 - When there is a numeric prefix, go up to a heading with level ARG, do
3996 a `show-subtree' and return to the previous cursor position. If ARG
3997 is negative, go up that many levels.
3999 - When point is not at the beginning of a headline, execute the global
4000 binding for TAB, which is re-indenting the line. See the option
4001 `org-cycle-emulate-tab' for details.
4003 - Special case: if point is at the beginning of the buffer and there is
4004 no headline in line 1, this function will act as if called with prefix arg.
4005 But only if also the variable `org-cycle-global-at-bob' is t."
4006 (interactive "P")
4007 (org-load-modules-maybe)
4008 (let* ((outline-regexp
4009 (if (and (org-mode-p) org-cycle-include-plain-lists)
4010 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
4011 outline-regexp))
4012 (bob-special (and org-cycle-global-at-bob (bobp)
4013 (not (looking-at outline-regexp))))
4014 (org-cycle-hook
4015 (if bob-special
4016 (delq 'org-optimize-window-after-visibility-change
4017 (copy-sequence org-cycle-hook))
4018 org-cycle-hook))
4019 (pos (point)))
4021 (if (or bob-special (equal arg '(4)))
4022 ;; special case: use global cycling
4023 (setq arg t))
4025 (cond
4027 ((equal arg '(16))
4028 (org-set-startup-visibility)
4029 (message "Startup visibility, plus VISIBILITY properties"))
4031 ((equal arg '(64))
4032 (show-all)
4033 (message "Entire buffer visible, including drawers"))
4035 ((org-at-table-p 'any)
4036 ;; Enter the table or move to the next field in the table
4037 (or (org-table-recognize-table.el)
4038 (progn
4039 (if arg (org-table-edit-field t)
4040 (org-table-justify-field-maybe)
4041 (call-interactively 'org-table-next-field)))))
4043 ((eq arg t) ;; Global cycling
4045 (cond
4046 ((and (eq last-command this-command)
4047 (eq org-cycle-global-status 'overview))
4048 ;; We just created the overview - now do table of contents
4049 ;; This can be slow in very large buffers, so indicate action
4050 (message "CONTENTS...")
4051 (org-content)
4052 (message "CONTENTS...done")
4053 (setq org-cycle-global-status 'contents)
4054 (run-hook-with-args 'org-cycle-hook 'contents))
4056 ((and (eq last-command this-command)
4057 (eq org-cycle-global-status 'contents))
4058 ;; We just showed the table of contents - now show everything
4059 (show-all)
4060 (message "SHOW ALL")
4061 (setq org-cycle-global-status 'all)
4062 (run-hook-with-args 'org-cycle-hook 'all))
4065 ;; Default action: go to overview
4066 (org-overview)
4067 (message "OVERVIEW")
4068 (setq org-cycle-global-status 'overview)
4069 (run-hook-with-args 'org-cycle-hook 'overview))))
4071 ((and org-drawers org-drawer-regexp
4072 (save-excursion
4073 (beginning-of-line 1)
4074 (looking-at org-drawer-regexp)))
4075 ;; Toggle block visibility
4076 (org-flag-drawer
4077 (not (get-char-property (match-end 0) 'invisible))))
4079 ((integerp arg)
4080 ;; Show-subtree, ARG levels up from here.
4081 (save-excursion
4082 (org-back-to-heading)
4083 (outline-up-heading (if (< arg 0) (- arg)
4084 (- (funcall outline-level) arg)))
4085 (org-show-subtree)))
4087 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4088 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4089 ;; At a heading: rotate between three different views
4090 (org-back-to-heading)
4091 (let ((goal-column 0) eoh eol eos)
4092 ;; First, some boundaries
4093 (save-excursion
4094 (org-back-to-heading)
4095 (save-excursion
4096 (beginning-of-line 2)
4097 (while (and (not (eobp)) ;; this is like `next-line'
4098 (get-char-property (1- (point)) 'invisible))
4099 (beginning-of-line 2)) (setq eol (point)))
4100 (outline-end-of-heading) (setq eoh (point))
4101 (org-end-of-subtree t)
4102 (unless (eobp)
4103 (skip-chars-forward " \t\n")
4104 (beginning-of-line 1) ; in case this is an item
4106 (setq eos (1- (point))))
4107 ;; Find out what to do next and set `this-command'
4108 (cond
4109 ((= eos eoh)
4110 ;; Nothing is hidden behind this heading
4111 (message "EMPTY ENTRY")
4112 (setq org-cycle-subtree-status nil)
4113 (save-excursion
4114 (goto-char eos)
4115 (outline-next-heading)
4116 (if (org-invisible-p) (org-flag-heading nil))))
4117 ((or (>= eol eos)
4118 (not (string-match "\\S-" (buffer-substring eol eos))))
4119 ;; Entire subtree is hidden in one line: open it
4120 (org-show-entry)
4121 (show-children)
4122 (message "CHILDREN")
4123 (save-excursion
4124 (goto-char eos)
4125 (outline-next-heading)
4126 (if (org-invisible-p) (org-flag-heading nil)))
4127 (setq org-cycle-subtree-status 'children)
4128 (run-hook-with-args 'org-cycle-hook 'children))
4129 ((and (eq last-command this-command)
4130 (eq org-cycle-subtree-status 'children))
4131 ;; We just showed the children, now show everything.
4132 (org-show-subtree)
4133 (message "SUBTREE")
4134 (setq org-cycle-subtree-status 'subtree)
4135 (run-hook-with-args 'org-cycle-hook 'subtree))
4137 ;; Default action: hide the subtree.
4138 (hide-subtree)
4139 (message "FOLDED")
4140 (setq org-cycle-subtree-status 'folded)
4141 (run-hook-with-args 'org-cycle-hook 'folded)))))
4143 ;; TAB emulation and template completion
4144 (buffer-read-only (org-back-to-heading))
4146 ((org-try-structure-completion))
4148 ((org-try-cdlatex-tab))
4150 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4151 (or (not (bolp))
4152 (not (looking-at outline-regexp))))
4153 (call-interactively (global-key-binding "\t")))
4155 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4156 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4157 (or (and (eq org-cycle-emulate-tab 'white)
4158 (= (match-end 0) (point-at-eol)))
4159 (and (eq org-cycle-emulate-tab 'whitestart)
4160 (>= (match-end 0) pos))))
4162 (eq org-cycle-emulate-tab t))
4163 (call-interactively (global-key-binding "\t")))
4165 (t (save-excursion
4166 (org-back-to-heading)
4167 (org-cycle))))))
4169 ;;;###autoload
4170 (defun org-global-cycle (&optional arg)
4171 "Cycle the global visibility. For details see `org-cycle'.
4172 With C-u prefix arg, switch to startup visibility.
4173 With a numeric prefix, show all headlines up to that level."
4174 (interactive "P")
4175 (let ((org-cycle-include-plain-lists
4176 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4177 (cond
4178 ((integerp arg)
4179 (show-all)
4180 (hide-sublevels arg)
4181 (setq org-cycle-global-status 'contents))
4182 ((equal arg '(4))
4183 (org-set-startup-visibility)
4184 (message "Startup visibility, plus VISIBILITY properties."))
4186 (org-cycle '(4))))))
4188 (defun org-set-startup-visibility ()
4189 "Set the visibility required by startup options and properties."
4190 (cond
4191 ((eq org-startup-folded t)
4192 (org-cycle '(4)))
4193 ((eq org-startup-folded 'content)
4194 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4195 (org-cycle '(4)) (org-cycle '(4)))))
4196 (org-set-visibility-according-to-property 'no-cleanup)
4197 (org-cycle-hide-archived-subtrees 'all)
4198 (org-cycle-hide-drawers 'all)
4199 (org-cycle-show-empty-lines 'all))
4201 (defun org-set-visibility-according-to-property (&optional no-cleanup)
4202 "Switch subtree visibilities according to :VISIBILITY: property."
4203 (interactive)
4204 (let (state)
4205 (save-excursion
4206 (goto-char (point-min))
4207 (while (re-search-forward
4208 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
4209 nil t)
4210 (setq state (match-string 1))
4211 (save-excursion
4212 (org-back-to-heading t)
4213 (hide-subtree)
4214 (org-reveal)
4215 (cond
4216 ((equal state '("fold" "folded"))
4217 (hide-subtree))
4218 ((equal state "children")
4219 (org-show-hidden-entry)
4220 (show-children))
4221 ((equal state "content")
4222 (save-excursion
4223 (save-restriction
4224 (org-narrow-to-subtree)
4225 (org-content))))
4226 ((member state '("all" "showall"))
4227 (show-subtree)))))
4228 (unless no-cleanup
4229 (org-cycle-hide-archived-subtrees 'all)
4230 (org-cycle-hide-drawers 'all)
4231 (org-cycle-show-empty-lines 'all)))))
4233 (defun org-overview ()
4234 "Switch to overview mode, shoing only top-level headlines.
4235 Really, this shows all headlines with level equal or greater than the level
4236 of the first headline in the buffer. This is important, because if the
4237 first headline is not level one, then (hide-sublevels 1) gives confusing
4238 results."
4239 (interactive)
4240 (let ((level (save-excursion
4241 (goto-char (point-min))
4242 (if (re-search-forward (concat "^" outline-regexp) nil t)
4243 (progn
4244 (goto-char (match-beginning 0))
4245 (funcall outline-level))))))
4246 (and level (hide-sublevels level))))
4248 (defun org-content (&optional arg)
4249 "Show all headlines in the buffer, like a table of contents.
4250 With numerical argument N, show content up to level N."
4251 (interactive "P")
4252 (save-excursion
4253 ;; Visit all headings and show their offspring
4254 (and (integerp arg) (org-overview))
4255 (goto-char (point-max))
4256 (catch 'exit
4257 (while (and (progn (condition-case nil
4258 (outline-previous-visible-heading 1)
4259 (error (goto-char (point-min))))
4261 (looking-at outline-regexp))
4262 (if (integerp arg)
4263 (show-children (1- arg))
4264 (show-branches))
4265 (if (bobp) (throw 'exit nil))))))
4268 (defun org-optimize-window-after-visibility-change (state)
4269 "Adjust the window after a change in outline visibility.
4270 This function is the default value of the hook `org-cycle-hook'."
4271 (when (get-buffer-window (current-buffer))
4272 (cond
4273 ; ((eq state 'overview) (org-first-headline-recenter 1))
4274 ; ((eq state 'overview) (org-beginning-of-line))
4275 ((eq state 'content) nil)
4276 ((eq state 'all) nil)
4277 ((eq state 'folded) nil)
4278 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4279 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4281 (defun org-compact-display-after-subtree-move ()
4282 (let (beg end)
4283 (save-excursion
4284 (if (org-up-heading-safe)
4285 (progn
4286 (hide-subtree)
4287 (show-entry)
4288 (show-children)
4289 (org-cycle-show-empty-lines 'children)
4290 (org-cycle-hide-drawers 'children))
4291 (org-overview)))))
4293 (defun org-cycle-show-empty-lines (state)
4294 "Show empty lines above all visible headlines.
4295 The region to be covered depends on STATE when called through
4296 `org-cycle-hook'. Lisp program can use t for STATE to get the
4297 entire buffer covered. Note that an empty line is only shown if there
4298 are at least `org-cycle-separator-lines' empty lines before the headeline."
4299 (when (> org-cycle-separator-lines 0)
4300 (save-excursion
4301 (let* ((n org-cycle-separator-lines)
4302 (re (cond
4303 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
4304 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
4305 (t (let ((ns (number-to-string (- n 2))))
4306 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
4307 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
4308 beg end)
4309 (cond
4310 ((memq state '(overview contents t))
4311 (setq beg (point-min) end (point-max)))
4312 ((memq state '(children folded))
4313 (setq beg (point) end (progn (org-end-of-subtree t t)
4314 (beginning-of-line 2)
4315 (point)))))
4316 (when beg
4317 (goto-char beg)
4318 (while (re-search-forward re end t)
4319 (if (not (get-char-property (match-end 1) 'invisible))
4320 (outline-flag-region
4321 (match-beginning 1) (match-end 1) nil)))))))
4322 ;; Never hide empty lines at the end of the file.
4323 (save-excursion
4324 (goto-char (point-max))
4325 (outline-previous-heading)
4326 (outline-end-of-heading)
4327 (if (and (looking-at "[ \t\n]+")
4328 (= (match-end 0) (point-max)))
4329 (outline-flag-region (point) (match-end 0) nil))))
4331 (defun org-show-empty-lines-in-parent ()
4332 "Move to the parent and re-show empty lines before visible headlines."
4333 (save-excursion
4334 (let ((context (if (org-up-heading-safe) 'children 'overview)))
4335 (org-cycle-show-empty-lines context))))
4337 (defun org-cycle-hide-drawers (state)
4338 "Re-hide all drawers after a visibility state change."
4339 (when (and (org-mode-p)
4340 (not (memq state '(overview folded))))
4341 (save-excursion
4342 (let* ((globalp (memq state '(contents all)))
4343 (beg (if globalp (point-min) (point)))
4344 (end (if globalp (point-max) (org-end-of-subtree t))))
4345 (goto-char beg)
4346 (while (re-search-forward org-drawer-regexp end t)
4347 (org-flag-drawer t))))))
4349 (defun org-flag-drawer (flag)
4350 (save-excursion
4351 (beginning-of-line 1)
4352 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
4353 (let ((b (match-end 0))
4354 (outline-regexp org-outline-regexp))
4355 (if (re-search-forward
4356 "^[ \t]*:END:"
4357 (save-excursion (outline-next-heading) (point)) t)
4358 (outline-flag-region b (point-at-eol) flag)
4359 (error ":END: line missing"))))))
4361 (defun org-subtree-end-visible-p ()
4362 "Is the end of the current subtree visible?"
4363 (pos-visible-in-window-p
4364 (save-excursion (org-end-of-subtree t) (point))))
4366 (defun org-first-headline-recenter (&optional N)
4367 "Move cursor to the first headline and recenter the headline.
4368 Optional argument N means, put the headline into the Nth line of the window."
4369 (goto-char (point-min))
4370 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4371 (beginning-of-line)
4372 (recenter (prefix-numeric-value N))))
4374 ;;; Org-goto
4376 (defvar org-goto-window-configuration nil)
4377 (defvar org-goto-marker nil)
4378 (defvar org-goto-map
4379 (let ((map (make-sparse-keymap)))
4380 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
4381 (while (setq cmd (pop cmds))
4382 (substitute-key-definition cmd cmd map global-map)))
4383 (suppress-keymap map)
4384 (org-defkey map "\C-m" 'org-goto-ret)
4385 (org-defkey map [(return)] 'org-goto-ret)
4386 (org-defkey map [(left)] 'org-goto-left)
4387 (org-defkey map [(right)] 'org-goto-right)
4388 (org-defkey map [(control ?g)] 'org-goto-quit)
4389 (org-defkey map "\C-i" 'org-cycle)
4390 (org-defkey map [(tab)] 'org-cycle)
4391 (org-defkey map [(down)] 'outline-next-visible-heading)
4392 (org-defkey map [(up)] 'outline-previous-visible-heading)
4393 (if org-goto-auto-isearch
4394 (if (fboundp 'define-key-after)
4395 (define-key-after map [t] 'org-goto-local-auto-isearch)
4396 nil)
4397 (org-defkey map "q" 'org-goto-quit)
4398 (org-defkey map "n" 'outline-next-visible-heading)
4399 (org-defkey map "p" 'outline-previous-visible-heading)
4400 (org-defkey map "f" 'outline-forward-same-level)
4401 (org-defkey map "b" 'outline-backward-same-level)
4402 (org-defkey map "u" 'outline-up-heading))
4403 (org-defkey map "/" 'org-occur)
4404 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4405 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4406 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
4407 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
4408 (org-defkey map "\C-c\C-u" 'outline-up-heading)
4409 map))
4411 (defconst org-goto-help
4412 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4413 RET=jump to location [Q]uit and return to previous location
4414 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4416 (defvar org-goto-start-pos) ; dynamically scoped parameter
4418 ;; FIXME: Docstring doe not mention both interfaces
4419 (defun org-goto (&optional alternative-interface)
4420 "Look up a different location in the current file, keeping current visibility.
4422 When you want look-up or go to a different location in a document, the
4423 fastest way is often to fold the entire buffer and then dive into the tree.
4424 This method has the disadvantage, that the previous location will be folded,
4425 which may not be what you want.
4427 This command works around this by showing a copy of the current buffer
4428 in an indirect buffer, in overview mode. You can dive into the tree in
4429 that copy, use org-occur and incremental search to find a location.
4430 When pressing RET or `Q', the command returns to the original buffer in
4431 which the visibility is still unchanged. After RET is will also jump to
4432 the location selected in the indirect buffer and expose the
4433 the headline hierarchy above."
4434 (interactive "P")
4435 (let* ((org-refile-targets '((nil . (:maxlevel . 10))))
4436 (org-refile-use-outline-path t)
4437 (interface
4438 (if (not alternative-interface)
4439 org-goto-interface
4440 (if (eq org-goto-interface 'outline)
4441 'outline-path-completion
4442 'outline)))
4443 (org-goto-start-pos (point))
4444 (selected-point
4445 (if (eq interface 'outline)
4446 (car (org-get-location (current-buffer) org-goto-help))
4447 (nth 3 (org-refile-get-location "Goto: ")))))
4448 (if selected-point
4449 (progn
4450 (org-mark-ring-push org-goto-start-pos)
4451 (goto-char selected-point)
4452 (if (or (org-invisible-p) (org-invisible-p2))
4453 (org-show-context 'org-goto)))
4454 (message "Quit"))))
4456 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
4457 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
4458 (defvar org-goto-local-auto-isearch-map) ; defined below
4460 (defun org-get-location (buf help)
4461 "Let the user select a location in the Org-mode buffer BUF.
4462 This function uses a recursive edit. It returns the selected position
4463 or nil."
4464 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
4465 (isearch-hide-immediately nil)
4466 (isearch-search-fun-function
4467 (lambda () 'org-goto-local-search-headings))
4468 (org-goto-selected-point org-goto-exit-command))
4469 (save-excursion
4470 (save-window-excursion
4471 (delete-other-windows)
4472 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
4473 (switch-to-buffer
4474 (condition-case nil
4475 (make-indirect-buffer (current-buffer) "*org-goto*")
4476 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
4477 (with-output-to-temp-buffer "*Help*"
4478 (princ help))
4479 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
4480 (setq buffer-read-only nil)
4481 (let ((org-startup-truncated t)
4482 (org-startup-folded nil)
4483 (org-startup-align-all-tables nil))
4484 (org-mode)
4485 (org-overview))
4486 (setq buffer-read-only t)
4487 (if (and (boundp 'org-goto-start-pos)
4488 (integer-or-marker-p org-goto-start-pos))
4489 (let ((org-show-hierarchy-above t)
4490 (org-show-siblings t)
4491 (org-show-following-heading t))
4492 (goto-char org-goto-start-pos)
4493 (and (org-invisible-p) (org-show-context)))
4494 (goto-char (point-min)))
4495 (org-beginning-of-line)
4496 (message "Select location and press RET")
4497 (use-local-map org-goto-map)
4498 (recursive-edit)
4500 (kill-buffer "*org-goto*")
4501 (cons org-goto-selected-point org-goto-exit-command)))
4503 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
4504 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
4505 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
4506 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
4508 (defun org-goto-local-search-headings (string bound noerror)
4509 "Search and make sure that any matches are in headlines."
4510 (catch 'return
4511 (while (if isearch-forward
4512 (search-forward string bound noerror)
4513 (search-backward string bound noerror))
4514 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
4515 (and (member :headline context)
4516 (not (member :tags context))))
4517 (throw 'return (point))))))
4519 (defun org-goto-local-auto-isearch ()
4520 "Start isearch."
4521 (interactive)
4522 (goto-char (point-min))
4523 (let ((keys (this-command-keys)))
4524 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
4525 (isearch-mode t)
4526 (isearch-process-search-char (string-to-char keys)))))
4528 (defun org-goto-ret (&optional arg)
4529 "Finish `org-goto' by going to the new location."
4530 (interactive "P")
4531 (setq org-goto-selected-point (point)
4532 org-goto-exit-command 'return)
4533 (throw 'exit nil))
4535 (defun org-goto-left ()
4536 "Finish `org-goto' by going to the new location."
4537 (interactive)
4538 (if (org-on-heading-p)
4539 (progn
4540 (beginning-of-line 1)
4541 (setq org-goto-selected-point (point)
4542 org-goto-exit-command 'left)
4543 (throw 'exit nil))
4544 (error "Not on a heading")))
4546 (defun org-goto-right ()
4547 "Finish `org-goto' by going to the new location."
4548 (interactive)
4549 (if (org-on-heading-p)
4550 (progn
4551 (setq org-goto-selected-point (point)
4552 org-goto-exit-command 'right)
4553 (throw 'exit nil))
4554 (error "Not on a heading")))
4556 (defun org-goto-quit ()
4557 "Finish `org-goto' without cursor motion."
4558 (interactive)
4559 (setq org-goto-selected-point nil)
4560 (setq org-goto-exit-command 'quit)
4561 (throw 'exit nil))
4563 ;;; Indirect buffer display of subtrees
4565 (defvar org-indirect-dedicated-frame nil
4566 "This is the frame being used for indirect tree display.")
4567 (defvar org-last-indirect-buffer nil)
4569 (defun org-tree-to-indirect-buffer (&optional arg)
4570 "Create indirect buffer and narrow it to current subtree.
4571 With numerical prefix ARG, go up to this level and then take that tree.
4572 If ARG is negative, go up that many levels.
4573 If `org-indirect-buffer-display' is not `new-frame', the command removes the
4574 indirect buffer previously made with this command, to avoid proliferation of
4575 indirect buffers. However, when you call the command with a `C-u' prefix, or
4576 when `org-indirect-buffer-display' is `new-frame', the last buffer
4577 is kept so that you can work with several indirect buffers at the same time.
4578 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
4579 requests that a new frame be made for the new buffer, so that the dedicated
4580 frame is not changed."
4581 (interactive "P")
4582 (let ((cbuf (current-buffer))
4583 (cwin (selected-window))
4584 (pos (point))
4585 beg end level heading ibuf)
4586 (save-excursion
4587 (org-back-to-heading t)
4588 (when (numberp arg)
4589 (setq level (org-outline-level))
4590 (if (< arg 0) (setq arg (+ level arg)))
4591 (while (> (setq level (org-outline-level)) arg)
4592 (outline-up-heading 1 t)))
4593 (setq beg (point)
4594 heading (org-get-heading))
4595 (org-end-of-subtree t) (setq end (point)))
4596 (if (and (buffer-live-p org-last-indirect-buffer)
4597 (not (eq org-indirect-buffer-display 'new-frame))
4598 (not arg))
4599 (kill-buffer org-last-indirect-buffer))
4600 (setq ibuf (org-get-indirect-buffer cbuf)
4601 org-last-indirect-buffer ibuf)
4602 (cond
4603 ((or (eq org-indirect-buffer-display 'new-frame)
4604 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
4605 (select-frame (make-frame))
4606 (delete-other-windows)
4607 (switch-to-buffer ibuf)
4608 (org-set-frame-title heading))
4609 ((eq org-indirect-buffer-display 'dedicated-frame)
4610 (raise-frame
4611 (select-frame (or (and org-indirect-dedicated-frame
4612 (frame-live-p org-indirect-dedicated-frame)
4613 org-indirect-dedicated-frame)
4614 (setq org-indirect-dedicated-frame (make-frame)))))
4615 (delete-other-windows)
4616 (switch-to-buffer ibuf)
4617 (org-set-frame-title (concat "Indirect: " heading)))
4618 ((eq org-indirect-buffer-display 'current-window)
4619 (switch-to-buffer ibuf))
4620 ((eq org-indirect-buffer-display 'other-window)
4621 (pop-to-buffer ibuf))
4622 (t (error "Invalid value.")))
4623 (if (featurep 'xemacs)
4624 (save-excursion (org-mode) (turn-on-font-lock)))
4625 (narrow-to-region beg end)
4626 (show-all)
4627 (goto-char pos)
4628 (and (window-live-p cwin) (select-window cwin))))
4630 (defun org-get-indirect-buffer (&optional buffer)
4631 (setq buffer (or buffer (current-buffer)))
4632 (let ((n 1) (base (buffer-name buffer)) bname)
4633 (while (buffer-live-p
4634 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
4635 (setq n (1+ n)))
4636 (condition-case nil
4637 (make-indirect-buffer buffer bname 'clone)
4638 (error (make-indirect-buffer buffer bname)))))
4640 (defun org-set-frame-title (title)
4641 "Set the title of the current frame to the string TITLE."
4642 ;; FIXME: how to name a single frame in XEmacs???
4643 (unless (featurep 'xemacs)
4644 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
4646 ;;;; Structure editing
4648 ;;; Inserting headlines
4650 (defun org-insert-heading (&optional force-heading)
4651 "Insert a new heading or item with same depth at point.
4652 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
4653 If point is at the beginning of a headline, insert a sibling before the
4654 current headline. If point is not at the beginning, do not split the line,
4655 but create the new headline after the current line."
4656 (interactive "P")
4657 (if (= (buffer-size) 0)
4658 (insert "\n* ")
4659 (when (or force-heading (not (org-insert-item)))
4660 (let* ((head (save-excursion
4661 (condition-case nil
4662 (progn
4663 (org-back-to-heading)
4664 (match-string 0))
4665 (error "*"))))
4666 (blank (cdr (assq 'heading org-blank-before-new-entry)))
4667 pos hide-previous previous-pos)
4668 (cond
4669 ((and (org-on-heading-p) (bolp)
4670 (or (bobp)
4671 (save-excursion (backward-char 1) (not (org-invisible-p)))))
4672 ;; insert before the current line
4673 (open-line (if blank 2 1)))
4674 ((and (bolp)
4675 (or (bobp)
4676 (save-excursion
4677 (backward-char 1) (not (org-invisible-p)))))
4678 ;; insert right here
4679 nil)
4681 ;; somewhere in the line
4682 (save-excursion
4683 (setq previous-pos (point-at-bol))
4684 (end-of-line)
4685 (setq hide-previous (org-invisible-p)))
4686 (and org-insert-heading-respect-content (org-show-subtree))
4687 (let ((split
4688 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
4689 (save-excursion
4690 (let ((p (point)))
4691 (goto-char (point-at-bol))
4692 (and (looking-at org-complex-heading-regexp)
4693 (> p (match-beginning 4)))))))
4694 tags pos)
4695 (cond
4696 (org-insert-heading-respect-content
4697 (org-end-of-subtree nil t)
4698 (or (bolp) (newline))
4699 (open-line 1))
4700 ((org-on-heading-p)
4701 (when hide-previous
4702 (show-children)
4703 (org-show-entry))
4704 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4705 (setq tags (and (match-end 2) (match-string 2)))
4706 (and (match-end 1)
4707 (delete-region (match-beginning 1) (match-end 1)))
4708 (setq pos (point-at-bol))
4709 (or split (end-of-line 1))
4710 (delete-horizontal-space)
4711 (newline (if blank 2 1))
4712 (when tags
4713 (save-excursion
4714 (goto-char pos)
4715 (end-of-line 1)
4716 (insert " " tags)
4717 (org-set-tags nil 'align))))
4719 (or split (end-of-line 1))
4720 (newline (if blank 2 1)))))))
4721 (insert head) (just-one-space)
4722 (setq pos (point))
4723 (end-of-line 1)
4724 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
4725 (when (and org-insert-heading-respect-content hide-previous)
4726 (save-excursion
4727 (goto-char previous-pos)
4728 (hide-subtree)))
4729 (run-hooks 'org-insert-heading-hook)))))
4731 (defun org-get-heading (&optional no-tags)
4732 "Return the heading of the current entry, without the stars."
4733 (save-excursion
4734 (org-back-to-heading t)
4735 (if (looking-at
4736 (if no-tags
4737 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
4738 "\\*+[ \t]+\\([^\r\n]*\\)"))
4739 (match-string 1) "")))
4741 (defun org-insert-heading-after-current ()
4742 "Insert a new heading with same level as current, after current subtree."
4743 (interactive)
4744 (org-back-to-heading)
4745 (org-insert-heading)
4746 (org-move-subtree-down)
4747 (end-of-line 1))
4749 (defun org-insert-heading-respect-content ()
4750 (interactive)
4751 (let ((org-insert-heading-respect-content t))
4752 (org-insert-heading t)))
4754 (defun org-insert-todo-heading-respect-content (&optional force-state)
4755 (interactive "P")
4756 (let ((org-insert-heading-respect-content t))
4757 (org-insert-todo-heading force-state t)))
4759 (defun org-insert-todo-heading (arg &optional force-heading)
4760 "Insert a new heading with the same level and TODO state as current heading.
4761 If the heading has no TODO state, or if the state is DONE, use the first
4762 state (TODO by default). Also with prefix arg, force first state."
4763 (interactive "P")
4764 (when (or force-heading (not (org-insert-item 'checkbox)))
4765 (org-insert-heading force-heading)
4766 (save-excursion
4767 (org-back-to-heading)
4768 (outline-previous-heading)
4769 (looking-at org-todo-line-regexp))
4770 (if (or arg
4771 (not (match-beginning 2))
4772 (member (match-string 2) org-done-keywords))
4773 (insert (car org-todo-keywords-1) " ")
4774 (insert (match-string 2) " "))
4775 (when org-provide-todo-statistics
4776 (org-update-parent-todo-statistics))))
4778 (defun org-insert-subheading (arg)
4779 "Insert a new subheading and demote it.
4780 Works for outline headings and for plain lists alike."
4781 (interactive "P")
4782 (org-insert-heading arg)
4783 (cond
4784 ((org-on-heading-p) (org-do-demote))
4785 ((org-at-item-p) (org-indent-item 1))))
4787 (defun org-insert-todo-subheading (arg)
4788 "Insert a new subheading with TODO keyword or checkbox and demote it.
4789 Works for outline headings and for plain lists alike."
4790 (interactive "P")
4791 (org-insert-todo-heading arg)
4792 (cond
4793 ((org-on-heading-p) (org-do-demote))
4794 ((org-at-item-p) (org-indent-item 1))))
4796 ;;; Promotion and Demotion
4798 (defun org-promote-subtree ()
4799 "Promote the entire subtree.
4800 See also `org-promote'."
4801 (interactive)
4802 (save-excursion
4803 (org-map-tree 'org-promote))
4804 (org-fix-position-after-promote))
4806 (defun org-demote-subtree ()
4807 "Demote the entire subtree. See `org-demote'.
4808 See also `org-promote'."
4809 (interactive)
4810 (save-excursion
4811 (org-map-tree 'org-demote))
4812 (org-fix-position-after-promote))
4815 (defun org-do-promote ()
4816 "Promote the current heading higher up the tree.
4817 If the region is active in `transient-mark-mode', promote all headings
4818 in the region."
4819 (interactive)
4820 (save-excursion
4821 (if (org-region-active-p)
4822 (org-map-region 'org-promote (region-beginning) (region-end))
4823 (org-promote)))
4824 (org-fix-position-after-promote))
4826 (defun org-do-demote ()
4827 "Demote the current heading lower down the tree.
4828 If the region is active in `transient-mark-mode', demote all headings
4829 in the region."
4830 (interactive)
4831 (save-excursion
4832 (if (org-region-active-p)
4833 (org-map-region 'org-demote (region-beginning) (region-end))
4834 (org-demote)))
4835 (org-fix-position-after-promote))
4837 (defun org-fix-position-after-promote ()
4838 "Make sure that after pro/demotion cursor position is right."
4839 (let ((pos (point)))
4840 (when (save-excursion
4841 (beginning-of-line 1)
4842 (looking-at org-todo-line-regexp)
4843 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
4844 (cond ((eobp) (insert " "))
4845 ((eolp) (insert " "))
4846 ((equal (char-after) ?\ ) (forward-char 1))))))
4848 (defun org-reduced-level (l)
4849 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
4851 (defun org-get-valid-level (level &optional change)
4852 "Rectify a level change under the influence of `org-odd-levels-only'
4853 LEVEL is a current level, CHANGE is by how much the level should be
4854 modified. Even if CHANGE is nil, LEVEL may be returned modified because
4855 even level numbers will become the next higher odd number."
4856 (if org-odd-levels-only
4857 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
4858 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
4859 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
4860 (max 1 (+ level change))))
4862 (if (boundp 'define-obsolete-function-alias)
4863 (if (or (featurep 'xemacs) (< emacs-major-version 23))
4864 (define-obsolete-function-alias 'org-get-legal-level
4865 'org-get-valid-level)
4866 (define-obsolete-function-alias 'org-get-legal-level
4867 'org-get-valid-level "23.1")))
4869 (defun org-promote ()
4870 "Promote the current heading higher up the tree.
4871 If the region is active in `transient-mark-mode', promote all headings
4872 in the region."
4873 (org-back-to-heading t)
4874 (let* ((level (save-match-data (funcall outline-level)))
4875 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
4876 (diff (abs (- level (length up-head) -1))))
4877 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
4878 (replace-match up-head nil t)
4879 ;; Fixup tag positioning
4880 (and org-auto-align-tags (org-set-tags nil t))
4881 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
4883 (defun org-demote ()
4884 "Demote the current heading lower down the tree.
4885 If the region is active in `transient-mark-mode', demote all headings
4886 in the region."
4887 (org-back-to-heading t)
4888 (let* ((level (save-match-data (funcall outline-level)))
4889 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
4890 (diff (abs (- level (length down-head) -1))))
4891 (replace-match down-head nil t)
4892 ;; Fixup tag positioning
4893 (and org-auto-align-tags (org-set-tags nil t))
4894 (if org-adapt-indentation (org-fixup-indentation diff))))
4896 (defun org-map-tree (fun)
4897 "Call FUN for every heading underneath the current one."
4898 (org-back-to-heading)
4899 (let ((level (funcall outline-level)))
4900 (save-excursion
4901 (funcall fun)
4902 (while (and (progn
4903 (outline-next-heading)
4904 (> (funcall outline-level) level))
4905 (not (eobp)))
4906 (funcall fun)))))
4908 (defun org-map-region (fun beg end)
4909 "Call FUN for every heading between BEG and END."
4910 (let ((org-ignore-region t))
4911 (save-excursion
4912 (setq end (copy-marker end))
4913 (goto-char beg)
4914 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
4915 (< (point) end))
4916 (funcall fun))
4917 (while (and (progn
4918 (outline-next-heading)
4919 (< (point) end))
4920 (not (eobp)))
4921 (funcall fun)))))
4923 (defun org-fixup-indentation (diff)
4924 "Change the indentation in the current entry by DIFF
4925 However, if any line in the current entry has no indentation, or if it
4926 would end up with no indentation after the change, nothing at all is done."
4927 (save-excursion
4928 (let ((end (save-excursion (outline-next-heading)
4929 (point-marker)))
4930 (prohibit (if (> diff 0)
4931 "^\\S-"
4932 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
4933 col)
4934 (unless (save-excursion (end-of-line 1)
4935 (re-search-forward prohibit end t))
4936 (while (and (< (point) end)
4937 (re-search-forward "^[ \t]+" end t))
4938 (goto-char (match-end 0))
4939 (setq col (current-column))
4940 (if (< diff 0) (replace-match ""))
4941 (indent-to (+ diff col))))
4942 (move-marker end nil))))
4944 (defun org-convert-to-odd-levels ()
4945 "Convert an org-mode file with all levels allowed to one with odd levels.
4946 This will leave level 1 alone, convert level 2 to level 3, level 3 to
4947 level 5 etc."
4948 (interactive)
4949 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
4950 (let ((org-odd-levels-only nil) n)
4951 (save-excursion
4952 (goto-char (point-min))
4953 (while (re-search-forward "^\\*\\*+ " nil t)
4954 (setq n (- (length (match-string 0)) 2))
4955 (while (>= (setq n (1- n)) 0)
4956 (org-demote))
4957 (end-of-line 1))))))
4960 (defun org-convert-to-oddeven-levels ()
4961 "Convert an org-mode file with only odd levels to one with odd and even levels.
4962 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
4963 section with an even level, conversion would destroy the structure of the file. An error
4964 is signaled in this case."
4965 (interactive)
4966 (goto-char (point-min))
4967 ;; First check if there are no even levels
4968 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
4969 (org-show-context t)
4970 (error "Not all levels are odd in this file. Conversion not possible."))
4971 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
4972 (let ((org-odd-levels-only nil) n)
4973 (save-excursion
4974 (goto-char (point-min))
4975 (while (re-search-forward "^\\*\\*+ " nil t)
4976 (setq n (/ (1- (length (match-string 0))) 2))
4977 (while (>= (setq n (1- n)) 0)
4978 (org-promote))
4979 (end-of-line 1))))))
4981 (defun org-tr-level (n)
4982 "Make N odd if required."
4983 (if org-odd-levels-only (1+ (/ n 2)) n))
4985 ;;; Vertical tree motion, cutting and pasting of subtrees
4987 (defun org-move-subtree-up (&optional arg)
4988 "Move the current subtree up past ARG headlines of the same level."
4989 (interactive "p")
4990 (org-move-subtree-down (- (prefix-numeric-value arg))))
4992 (defun org-move-subtree-down (&optional arg)
4993 "Move the current subtree down past ARG headlines of the same level."
4994 (interactive "p")
4995 (setq arg (prefix-numeric-value arg))
4996 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
4997 'outline-get-last-sibling))
4998 (ins-point (make-marker))
4999 (cnt (abs arg))
5000 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
5001 ;; Select the tree
5002 (org-back-to-heading)
5003 (setq beg0 (point))
5004 (save-excursion
5005 (setq ne-beg (org-back-over-empty-lines))
5006 (setq beg (point)))
5007 (save-match-data
5008 (save-excursion (outline-end-of-heading)
5009 (setq folded (org-invisible-p)))
5010 (outline-end-of-subtree))
5011 (outline-next-heading)
5012 (setq ne-end (org-back-over-empty-lines))
5013 (setq end (point))
5014 (goto-char beg0)
5015 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
5016 ;; include less whitespace
5017 (save-excursion
5018 (goto-char beg)
5019 (forward-line (- ne-beg ne-end))
5020 (setq beg (point))))
5021 ;; Find insertion point, with error handling
5022 (while (> cnt 0)
5023 (or (and (funcall movfunc) (looking-at outline-regexp))
5024 (progn (goto-char beg0)
5025 (error "Cannot move past superior level or buffer limit")))
5026 (setq cnt (1- cnt)))
5027 (if (> arg 0)
5028 ;; Moving forward - still need to move over subtree
5029 (progn (org-end-of-subtree t t)
5030 (save-excursion
5031 (org-back-over-empty-lines)
5032 (or (bolp) (newline)))))
5033 (setq ne-ins (org-back-over-empty-lines))
5034 (move-marker ins-point (point))
5035 (setq txt (buffer-substring beg end))
5036 (org-save-markers-in-region beg end)
5037 (delete-region beg end)
5038 (outline-flag-region (1- beg) beg nil)
5039 (outline-flag-region (1- (point)) (point) nil)
5040 (let ((bbb (point)))
5041 (insert-before-markers txt)
5042 (org-reinstall-markers-in-region bbb)
5043 (move-marker ins-point bbb))
5044 (or (bolp) (insert "\n"))
5045 (setq ins-end (point))
5046 (goto-char ins-point)
5047 (org-skip-whitespace)
5048 (when (and (< arg 0)
5049 (org-first-sibling-p)
5050 (> ne-ins ne-beg))
5051 ;; Move whitespace back to beginning
5052 (save-excursion
5053 (goto-char ins-end)
5054 (let ((kill-whole-line t))
5055 (kill-line (- ne-ins ne-beg)) (point)))
5056 (insert (make-string (- ne-ins ne-beg) ?\n)))
5057 (move-marker ins-point nil)
5058 (org-compact-display-after-subtree-move)
5059 (org-show-empty-lines-in-parent)
5060 (unless folded
5061 (org-show-entry)
5062 (show-children)
5063 (org-cycle-hide-drawers 'children))))
5065 (defvar org-subtree-clip ""
5066 "Clipboard for cut and paste of subtrees.
5067 This is actually only a copy of the kill, because we use the normal kill
5068 ring. We need it to check if the kill was created by `org-copy-subtree'.")
5070 (defvar org-subtree-clip-folded nil
5071 "Was the last copied subtree folded?
5072 This is used to fold the tree back after pasting.")
5074 (defun org-cut-subtree (&optional n)
5075 "Cut the current subtree into the clipboard.
5076 With prefix arg N, cut this many sequential subtrees.
5077 This is a short-hand for marking the subtree and then cutting it."
5078 (interactive "p")
5079 (org-copy-subtree n 'cut))
5081 (defun org-copy-subtree (&optional n cut force-store-markers)
5082 "Cut the current subtree into the clipboard.
5083 With prefix arg N, cut this many sequential subtrees.
5084 This is a short-hand for marking the subtree and then copying it.
5085 If CUT is non-nil, actually cut the subtree.
5086 If FORCE-STORE-MARKERS is non-nil, store the relative locations
5087 of some markers in the region, even if CUT is non-nil. This is
5088 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
5089 (interactive "p")
5090 (let (beg end folded (beg0 (point)))
5091 (if (interactive-p)
5092 (org-back-to-heading nil) ; take what looks like a subtree
5093 (org-back-to-heading t)) ; take what is really there
5094 (org-back-over-empty-lines)
5095 (setq beg (point))
5096 (skip-chars-forward " \t\r\n")
5097 (save-match-data
5098 (save-excursion (outline-end-of-heading)
5099 (setq folded (org-invisible-p)))
5100 (condition-case nil
5101 (outline-forward-same-level (1- n))
5102 (error nil))
5103 (org-end-of-subtree t t))
5104 (org-back-over-empty-lines)
5105 (setq end (point))
5106 (goto-char beg0)
5107 (when (> end beg)
5108 (setq org-subtree-clip-folded folded)
5109 (when (or cut force-store-markers)
5110 (org-save-markers-in-region beg end))
5111 (if cut (kill-region beg end) (copy-region-as-kill beg end))
5112 (setq org-subtree-clip (current-kill 0))
5113 (message "%s: Subtree(s) with %d characters"
5114 (if cut "Cut" "Copied")
5115 (length org-subtree-clip)))))
5117 (defun org-paste-subtree (&optional level tree for-yank)
5118 "Paste the clipboard as a subtree, with modification of headline level.
5119 The entire subtree is promoted or demoted in order to match a new headline
5120 level.
5122 If the cursor is at the beginning of a headline, the same level as
5123 that headline is used to paste the tree
5125 If not, the new level is derived from the *visible* headings
5126 before and after the insertion point, and taken to be the inferior headline
5127 level of the two. So if the previous visible heading is level 3 and the
5128 next is level 4 (or vice versa), level 4 will be used for insertion.
5129 This makes sure that the subtree remains an independent subtree and does
5130 not swallow low level entries.
5132 You can also force a different level, either by using a numeric prefix
5133 argument, or by inserting the heading marker by hand. For example, if the
5134 cursor is after \"*****\", then the tree will be shifted to level 5.
5136 If optional TREE is given, use this text instead of the kill ring.
5138 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
5139 move back over whitespace before inserting, and move point to the end of
5140 the inserted text when done."
5141 (interactive "P")
5142 (unless (org-kill-is-subtree-p tree)
5143 (error "%s"
5144 (substitute-command-keys
5145 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
5146 (let* ((visp (not (org-invisible-p)))
5147 (txt (or tree (and kill-ring (current-kill 0))))
5148 (^re (concat "^\\(" outline-regexp "\\)"))
5149 (re (concat "\\(" outline-regexp "\\)"))
5150 (^re_ (concat "\\(\\*+\\)[ \t]*"))
5152 (old-level (if (string-match ^re txt)
5153 (- (match-end 0) (match-beginning 0) 1)
5154 -1))
5155 (force-level (cond (level (prefix-numeric-value level))
5156 ((and (looking-at "[ \t]*$")
5157 (string-match
5158 ^re_ (buffer-substring
5159 (point-at-bol) (point))))
5160 (- (match-end 1) (match-beginning 1)))
5161 ((and (bolp)
5162 (looking-at org-outline-regexp))
5163 (- (match-end 0) (point) 1))
5164 (t nil)))
5165 (previous-level (save-excursion
5166 (condition-case nil
5167 (progn
5168 (outline-previous-visible-heading 1)
5169 (if (looking-at re)
5170 (- (match-end 0) (match-beginning 0) 1)
5172 (error 1))))
5173 (next-level (save-excursion
5174 (condition-case nil
5175 (progn
5176 (or (looking-at outline-regexp)
5177 (outline-next-visible-heading 1))
5178 (if (looking-at re)
5179 (- (match-end 0) (match-beginning 0) 1)
5181 (error 1))))
5182 (new-level (or force-level (max previous-level next-level)))
5183 (shift (if (or (= old-level -1)
5184 (= new-level -1)
5185 (= old-level new-level))
5187 (- new-level old-level)))
5188 (delta (if (> shift 0) -1 1))
5189 (func (if (> shift 0) 'org-demote 'org-promote))
5190 (org-odd-levels-only nil)
5191 beg end newend)
5192 ;; Remove the forced level indicator
5193 (if force-level
5194 (delete-region (point-at-bol) (point)))
5195 ;; Paste
5196 (beginning-of-line 1)
5197 (unless for-yank (org-back-over-empty-lines))
5198 (setq beg (point))
5199 (insert-before-markers txt)
5200 (unless (string-match "\n\\'" txt) (insert "\n"))
5201 (setq newend (point))
5202 (org-reinstall-markers-in-region beg)
5203 (setq end (point))
5204 (goto-char beg)
5205 (skip-chars-forward " \t\n\r")
5206 (setq beg (point))
5207 (if (and (org-invisible-p) visp)
5208 (save-excursion (outline-show-heading)))
5209 ;; Shift if necessary
5210 (unless (= shift 0)
5211 (save-restriction
5212 (narrow-to-region beg end)
5213 (while (not (= shift 0))
5214 (org-map-region func (point-min) (point-max))
5215 (setq shift (+ delta shift)))
5216 (goto-char (point-min))
5217 (setq newend (point-max))))
5218 (when (or (interactive-p) for-yank)
5219 (message "Clipboard pasted as level %d subtree" new-level))
5220 (if (and (not for-yank) ; in this case, org-yank will decide about folding
5221 kill-ring
5222 (eq org-subtree-clip (current-kill 0))
5223 org-subtree-clip-folded)
5224 ;; The tree was folded before it was killed/copied
5225 (hide-subtree))
5226 (and for-yank (goto-char newend))))
5228 (defun org-kill-is-subtree-p (&optional txt)
5229 "Check if the current kill is an outline subtree, or a set of trees.
5230 Returns nil if kill does not start with a headline, or if the first
5231 headline level is not the largest headline level in the tree.
5232 So this will actually accept several entries of equal levels as well,
5233 which is OK for `org-paste-subtree'.
5234 If optional TXT is given, check this string instead of the current kill."
5235 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
5236 (start-level (and kill
5237 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
5238 org-outline-regexp "\\)")
5239 kill)
5240 (- (match-end 2) (match-beginning 2) 1)))
5241 (re (concat "^" org-outline-regexp))
5242 (start (1+ (or (match-beginning 2) -1))))
5243 (if (not start-level)
5244 (progn
5245 nil) ;; does not even start with a heading
5246 (catch 'exit
5247 (while (setq start (string-match re kill (1+ start)))
5248 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
5249 (throw 'exit nil)))
5250 t))))
5252 (defvar org-markers-to-move nil
5253 "Markers that should be moved with a cut-and-paste operation.
5254 Those markers are stored together with their positions relative to
5255 the start of the region.")
5257 (defun org-save-markers-in-region (beg end)
5258 "Check markers in region.
5259 If these markers are between BEG and END, record their position relative
5260 to BEG, so that after moving the block of text, we can put the markers back
5261 into place.
5262 This function gets called just before an entry or tree gets cut from the
5263 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
5264 called immediately, to move the markers with the entries."
5265 (setq org-markers-to-move nil)
5266 (when (featurep 'org-clock)
5267 (org-clock-save-markers-for-cut-and-paste beg end))
5268 (when (featurep 'org-agenda)
5269 (org-agenda-save-markers-for-cut-and-paste beg end)))
5271 (defun org-check-and-save-marker (marker beg end)
5272 "Check if MARKER is between BEG and END.
5273 If yes, remember the marker and the distance to BEG."
5274 (when (and (marker-buffer marker)
5275 (equal (marker-buffer marker) (current-buffer)))
5276 (if (and (>= marker beg) (< marker end))
5277 (push (cons marker (- marker beg)) org-markers-to-move))))
5279 (defun org-reinstall-markers-in-region (beg)
5280 "Move all remembered markers to their position relative to BEG."
5281 (mapc (lambda (x)
5282 (move-marker (car x) (+ beg (cdr x))))
5283 org-markers-to-move)
5284 (setq org-markers-to-move nil))
5286 (defun org-narrow-to-subtree ()
5287 "Narrow buffer to the current subtree."
5288 (interactive)
5289 (save-excursion
5290 (save-match-data
5291 (narrow-to-region
5292 (progn (org-back-to-heading) (point))
5293 (progn (org-end-of-subtree t) (point))))))
5296 ;;; Outline Sorting
5298 (defun org-sort (with-case)
5299 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
5300 Optional argument WITH-CASE means sort case-sensitively."
5301 (interactive "P")
5302 (if (org-at-table-p)
5303 (org-call-with-arg 'org-table-sort-lines with-case)
5304 (org-call-with-arg 'org-sort-entries-or-items with-case)))
5306 (defun org-sort-remove-invisible (s)
5307 (remove-text-properties 0 (length s) org-rm-props s)
5308 (while (string-match org-bracket-link-regexp s)
5309 (setq s (replace-match (if (match-end 2)
5310 (match-string 3 s)
5311 (match-string 1 s)) t t s)))
5314 (defvar org-priority-regexp) ; defined later in the file
5316 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
5317 "Sort entries on a certain level of an outline tree.
5318 If there is an active region, the entries in the region are sorted.
5319 Else, if the cursor is before the first entry, sort the top-level items.
5320 Else, the children of the entry at point are sorted.
5322 Sorting can be alphabetically, numerically, and by date/time as given by
5323 the first time stamp in the entry. The command prompts for the sorting
5324 type unless it has been given to the function through the SORTING-TYPE
5325 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
5326 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
5327 called with point at the beginning of the record. It must return either
5328 a string or a number that should serve as the sorting key for that record.
5330 Comparing entries ignores case by default. However, with an optional argument
5331 WITH-CASE, the sorting considers case as well."
5332 (interactive "P")
5333 (let ((case-func (if with-case 'identity 'downcase))
5334 start beg end stars re re2
5335 txt what tmp plain-list-p)
5336 ;; Find beginning and end of region to sort
5337 (cond
5338 ((org-region-active-p)
5339 ;; we will sort the region
5340 (setq end (region-end)
5341 what "region")
5342 (goto-char (region-beginning))
5343 (if (not (org-on-heading-p)) (outline-next-heading))
5344 (setq start (point)))
5345 ((org-at-item-p)
5346 ;; we will sort this plain list
5347 (org-beginning-of-item-list) (setq start (point))
5348 (org-end-of-item-list) (setq end (point))
5349 (goto-char start)
5350 (setq plain-list-p t
5351 what "plain list"))
5352 ((or (org-on-heading-p)
5353 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
5354 ;; we will sort the children of the current headline
5355 (org-back-to-heading)
5356 (setq start (point)
5357 end (progn (org-end-of-subtree t t)
5358 (org-back-over-empty-lines)
5359 (point))
5360 what "children")
5361 (goto-char start)
5362 (show-subtree)
5363 (outline-next-heading))
5365 ;; we will sort the top-level entries in this file
5366 (goto-char (point-min))
5367 (or (org-on-heading-p) (outline-next-heading))
5368 (setq start (point) end (point-max) what "top-level")
5369 (goto-char start)
5370 (show-all)))
5372 (setq beg (point))
5373 (if (>= beg end) (error "Nothing to sort"))
5375 (unless plain-list-p
5376 (looking-at "\\(\\*+\\)")
5377 (setq stars (match-string 1)
5378 re (concat "^" (regexp-quote stars) " +")
5379 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
5380 txt (buffer-substring beg end))
5381 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
5382 (if (and (not (equal stars "*")) (string-match re2 txt))
5383 (error "Region to sort contains a level above the first entry")))
5385 (unless sorting-type
5386 (message
5387 (if plain-list-p
5388 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
5389 "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:")
5390 what)
5391 (setq sorting-type (read-char-exclusive))
5393 (and (= (downcase sorting-type) ?f)
5394 (setq getkey-func
5395 (completing-read "Sort using function: "
5396 obarray 'fboundp t nil nil))
5397 (setq getkey-func (intern getkey-func)))
5399 (and (= (downcase sorting-type) ?r)
5400 (setq property
5401 (completing-read "Property: "
5402 (mapcar 'list (org-buffer-property-keys t))
5403 nil t))))
5405 (message "Sorting entries...")
5407 (save-restriction
5408 (narrow-to-region start end)
5410 (let ((dcst (downcase sorting-type))
5411 (now (current-time)))
5412 (sort-subr
5413 (/= dcst sorting-type)
5414 ;; This function moves to the beginning character of the "record" to
5415 ;; be sorted.
5416 (if plain-list-p
5417 (lambda nil
5418 (if (org-at-item-p) t (goto-char (point-max))))
5419 (lambda nil
5420 (if (re-search-forward re nil t)
5421 (goto-char (match-beginning 0))
5422 (goto-char (point-max)))))
5423 ;; This function moves to the last character of the "record" being
5424 ;; sorted.
5425 (if plain-list-p
5426 'org-end-of-item
5427 (lambda nil
5428 (save-match-data
5429 (condition-case nil
5430 (outline-forward-same-level 1)
5431 (error
5432 (goto-char (point-max)))))))
5434 ;; This function returns the value that gets sorted against.
5435 (if plain-list-p
5436 (lambda nil
5437 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
5438 (cond
5439 ((= dcst ?n)
5440 (string-to-number (buffer-substring (match-end 0)
5441 (point-at-eol))))
5442 ((= dcst ?a)
5443 (buffer-substring (match-end 0) (point-at-eol)))
5444 ((= dcst ?t)
5445 (if (re-search-forward org-ts-regexp
5446 (point-at-eol) t)
5447 (org-time-string-to-time (match-string 0))
5448 now))
5449 ((= dcst ?f)
5450 (if getkey-func
5451 (progn
5452 (setq tmp (funcall getkey-func))
5453 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5454 tmp)
5455 (error "Invalid key function `%s'" getkey-func)))
5456 (t (error "Invalid sorting type `%c'" sorting-type)))))
5457 (lambda nil
5458 (cond
5459 ((= dcst ?n)
5460 (if (looking-at org-complex-heading-regexp)
5461 (string-to-number (match-string 4))
5462 nil))
5463 ((= dcst ?a)
5464 (if (looking-at org-complex-heading-regexp)
5465 (funcall case-func (match-string 4))
5466 nil))
5467 ((= dcst ?t)
5468 (if (re-search-forward org-ts-regexp
5469 (save-excursion
5470 (forward-line 2)
5471 (point)) t)
5472 (org-time-string-to-time (match-string 0))
5473 now))
5474 ((= dcst ?p)
5475 (if (re-search-forward org-priority-regexp (point-at-eol) t)
5476 (string-to-char (match-string 2))
5477 org-default-priority))
5478 ((= dcst ?r)
5479 (or (org-entry-get nil property) ""))
5480 ((= dcst ?o)
5481 (if (looking-at org-complex-heading-regexp)
5482 (- 9999 (length (member (match-string 2)
5483 org-todo-keywords-1)))))
5484 ((= dcst ?f)
5485 (if getkey-func
5486 (progn
5487 (setq tmp (funcall getkey-func))
5488 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5489 tmp)
5490 (error "Invalid key function `%s'" getkey-func)))
5491 (t (error "Invalid sorting type `%c'" sorting-type)))))
5493 (cond
5494 ((= dcst ?a) 'string<)
5495 ((= dcst ?t) 'time-less-p)
5496 (t nil)))))
5497 (message "Sorting entries...done")))
5499 (defun org-do-sort (table what &optional with-case sorting-type)
5500 "Sort TABLE of WHAT according to SORTING-TYPE.
5501 The user will be prompted for the SORTING-TYPE if the call to this
5502 function does not specify it. WHAT is only for the prompt, to indicate
5503 what is being sorted. The sorting key will be extracted from
5504 the car of the elements of the table.
5505 If WITH-CASE is non-nil, the sorting will be case-sensitive."
5506 (unless sorting-type
5507 (message
5508 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
5509 what)
5510 (setq sorting-type (read-char-exclusive)))
5511 (let ((dcst (downcase sorting-type))
5512 extractfun comparefun)
5513 ;; Define the appropriate functions
5514 (cond
5515 ((= dcst ?n)
5516 (setq extractfun 'string-to-number
5517 comparefun (if (= dcst sorting-type) '< '>)))
5518 ((= dcst ?a)
5519 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
5520 (lambda(x) (downcase (org-sort-remove-invisible x))))
5521 comparefun (if (= dcst sorting-type)
5522 'string<
5523 (lambda (a b) (and (not (string< a b))
5524 (not (string= a b)))))))
5525 ((= dcst ?t)
5526 (setq extractfun
5527 (lambda (x)
5528 (if (string-match org-ts-regexp x)
5529 (time-to-seconds
5530 (org-time-string-to-time (match-string 0 x)))
5532 comparefun (if (= dcst sorting-type) '< '>)))
5533 (t (error "Invalid sorting type `%c'" sorting-type)))
5535 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5536 table)
5537 (lambda (a b) (funcall comparefun (car a) (car b))))))
5539 ;;; Editing source examples
5541 (defvar org-exit-edit-mode-map (make-sparse-keymap))
5542 (define-key org-exit-edit-mode-map "\C-c'" 'org-edit-src-exit)
5543 (defvar org-edit-src-force-single-line nil)
5544 (defvar org-edit-src-from-org-mode nil)
5545 (defvar org-edit-src-picture nil)
5547 (define-minor-mode org-exit-edit-mode
5548 "Minor mode installing a single key binding, \"C-c '\" to exit special edit.")
5550 (defun org-edit-src-code ()
5551 "Edit the source code example at point.
5552 An indirect buffer is created, and that buffer is then narrowed to the
5553 example at point and switched to the correct language mode. When done,
5554 exit by killing the buffer with \\[org-edit-src-exit]."
5555 (interactive)
5556 (let ((line (org-current-line))
5557 (case-fold-search t)
5558 (msg (substitute-command-keys
5559 "Edit, then exit with C-c ' (C-c and single quote)"))
5560 (info (org-edit-src-find-region-and-lang))
5561 (org-mode-p (eq major-mode 'org-mode))
5562 beg end lang lang-f single)
5563 (if (not info)
5565 (setq beg (nth 0 info)
5566 end (nth 1 info)
5567 lang (nth 2 info)
5568 single (nth 3 info)
5569 lang-f (intern (concat lang "-mode")))
5570 (unless (functionp lang-f)
5571 (error "No such language mode: %s" lang-f))
5572 (goto-line line)
5573 (if (get-buffer "*Org Edit Src Example*")
5574 (kill-buffer "*Org Edit Src Example*"))
5575 (switch-to-buffer (make-indirect-buffer (current-buffer)
5576 "*Org Edit Src Example*"))
5577 (narrow-to-region beg end)
5578 (remove-text-properties beg end '(display nil invisible nil
5579 intangible nil))
5580 (let ((org-inhibit-startup t))
5581 (funcall lang-f))
5582 (set (make-local-variable 'org-edit-src-force-single-line) single)
5583 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5584 (when org-mode-p
5585 (goto-char (point-min))
5586 (while (re-search-forward "^," nil t)
5587 (replace-match "")))
5588 (goto-line line)
5589 (org-exit-edit-mode)
5590 (org-set-local 'header-line-format msg)
5591 (message "%s" msg)
5592 t)))
5594 (defun org-edit-fixed-width-region ()
5595 "Edit the fixed-width ascii drawing at point.
5596 This must be a region where each line starts with ca colon followed by
5597 a space character.
5598 An indirect buffer is created, and that buffer is then narrowed to the
5599 example at point and switched to artist-mode. When done,
5600 exit by killing the buffer with \\[org-edit-src-exit]."
5601 (interactive)
5602 (let ((line (org-current-line))
5603 (case-fold-search t)
5604 (msg (substitute-command-keys
5605 "Edit, then exit with C-c ' (C-c and single quote)"))
5606 (org-mode-p (eq major-mode 'org-mode))
5607 beg end lang lang-f)
5608 (beginning-of-line 1)
5609 (if (looking-at "[ \t]*[^:\n \t]")
5611 (if (looking-at "[ \t]*\\(\n\\|\\'\\)")
5612 (setq beg (point) end beg)
5613 (save-excursion
5614 (if (re-search-backward "^[ \t]*[^:]" nil 'move)
5615 (setq beg (point-at-bol 2))
5616 (setq beg (point))))
5617 (save-excursion
5618 (if (re-search-forward "^[ \t]*[^:]" nil 'move)
5619 (setq end (1- (match-beginning 0)))
5620 (setq end (point))))
5621 (goto-line line))
5622 (if (get-buffer "*Org Edit Picture*")
5623 (kill-buffer "*Org Edit Picture*"))
5624 (switch-to-buffer (make-indirect-buffer (current-buffer)
5625 "*Org Edit Picture*"))
5626 (narrow-to-region beg end)
5627 (remove-text-properties beg end '(display nil invisible nil
5628 intangible nil))
5629 (when (fboundp 'font-lock-unfontify-region)
5630 (font-lock-unfontify-region (point-min) (point-max)))
5631 (cond
5632 ((eq org-edit-fixed-width-region-mode 'artist-mode)
5633 (fundamental-mode)
5634 (artist-mode 1))
5635 (t (funcall org-edit-fixed-width-region-mode)))
5636 (set (make-local-variable 'org-edit-src-force-single-line) nil)
5637 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5638 (set (make-local-variable 'org-edit-src-picture) t)
5639 (goto-char (point-min))
5640 (while (re-search-forward "^[ \t]*: ?" nil t)
5641 (replace-match ""))
5642 (goto-line line)
5643 (org-exit-edit-mode)
5644 (org-set-local 'header-line-format msg)
5645 (message "%s" msg)
5646 t)))
5649 (defun org-edit-src-find-region-and-lang ()
5650 "Find the region and language for a local edit.
5651 Return a list with beginning and end of the region, a string representing
5652 the language, a switch telling of the content should be in a single line."
5653 (let ((re-list
5654 (append
5655 org-edit-src-region-extra
5657 ("<src\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</src>" lang)
5658 ("<literal\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</literal>" style)
5659 ("<example>[ \t]*\n?" "\n?[ \t]*</example>" "fundamental")
5660 ("<lisp>[ \t]*\n?" "\n?[ \t]*</lisp>" "emacs-lisp")
5661 ("<perl>[ \t]*\n?" "\n?[ \t]*</perl>" "perl")
5662 ("<python>[ \t]*\n?" "\n?[ \t]*</python>" "python")
5663 ("<ruby>[ \t]*\n?" "\n?[ \t]*</ruby>" "ruby")
5664 ("^#\\+begin_src\\( \\([^ \t\n]+\\)\\)?.*\n" "\n#\\+end_src" 2)
5665 ("^#\\+begin_example.*\n" "\n#\\+end_example" "fundamental")
5666 ("^#\\+html:" "\n" "html" single-line)
5667 ("^#\\+begin_html.*\n" "\n#\\+end_html" "html")
5668 ("^#\\+begin_latex.*\n" "\n#\\+end_latex" "latex")
5669 ("^#\\+latex:" "\n" "latex" single-line)
5670 ("^#\\+begin_ascii.*\n" "\n#\\+end_ascii" "fundamental")
5671 ("^#\\+ascii:" "\n" "ascii" single-line)
5673 (pos (point))
5674 re re1 re2 single beg end lang)
5675 (catch 'exit
5676 (while (setq entry (pop re-list))
5677 (setq re1 (car entry) re2 (nth 1 entry) lang (nth 2 entry)
5678 single (nth 3 entry))
5679 (save-excursion
5680 (if (or (looking-at re1)
5681 (re-search-backward re1 nil t))
5682 (progn
5683 (setq beg (match-end 0) lang (org-edit-src-get-lang lang))
5684 (if (and (re-search-forward re2 nil t)
5685 (>= (match-end 0) pos))
5686 (throw 'exit (list beg (match-beginning 0) lang single))))
5687 (if (or (looking-at re2)
5688 (re-search-forward re2 nil t))
5689 (progn
5690 (setq end (match-beginning 0))
5691 (if (and (re-search-backward re1 nil t)
5692 (<= (match-beginning 0) pos))
5693 (throw 'exit
5694 (list (match-end 0) end
5695 (org-edit-src-get-lang lang) single)))))))))))
5697 (defun org-edit-src-get-lang (lang)
5698 "Extract the src language."
5699 (let ((m (match-string 0)))
5700 (cond
5701 ((stringp lang) lang)
5702 ((integerp lang) (match-string lang))
5703 ((and (eq lang 'lang)
5704 (string-match "\\<lang=\"\\([^ \t\n\"]+\\)\"" m))
5705 (match-string 1 m))
5706 ((and (eq lang 'style)
5707 (string-match "\\<style=\"\\([^ \t\n\"]+\\)\"" m))
5708 (match-string 1 m))
5709 (t "fundamental"))))
5711 (defun org-edit-src-exit ()
5712 "Exit special edit and protect problematic lines."
5713 (interactive)
5714 (unless (buffer-base-buffer (current-buffer))
5715 (error "This is not an indirect buffer, something is wrong..."))
5716 (unless (> (point-min) 1)
5717 (error "This buffer is not narrowed, something is wrong..."))
5718 (goto-char (point-min))
5719 (if (looking-at "[ \t\n]*\n") (replace-match ""))
5720 (if (re-search-forward "\n[ \t\n]*\\'" nil t) (replace-match ""))
5721 (when (org-bound-and-true-p org-edit-src-force-single-line)
5722 (goto-char (point-min))
5723 (while (re-search-forward "\n" nil t)
5724 (replace-match " "))
5725 (goto-char (point-min))
5726 (if (looking-at "\\s-*") (replace-match " "))
5727 (if (re-search-forward "\\s-+\\'" nil t)
5728 (replace-match "")))
5729 (when (org-bound-and-true-p org-edit-src-from-org-mode)
5730 (goto-char (point-min))
5731 (while (re-search-forward (if (org-mode-p) "^\\(.\\)" "^\\([*#]\\)") nil t)
5732 (replace-match ",\\1"))
5733 (when font-lock-mode
5734 (font-lock-unfontify-region (point-min) (point-max)))
5735 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
5736 (when (org-bound-and-true-p org-edit-src-picture)
5737 (untabify (point-min) (point-max))
5738 (goto-char (point-min))
5739 (while (re-search-forward "^" nil t)
5740 (replace-match ": "))
5741 (when font-lock-mode
5742 (font-lock-unfontify-region (point-min) (point-max)))
5743 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
5744 (kill-buffer (current-buffer))
5745 (and (org-mode-p) (org-restart-font-lock)))
5748 ;;; The orgstruct minor mode
5750 ;; Define a minor mode which can be used in other modes in order to
5751 ;; integrate the org-mode structure editing commands.
5753 ;; This is really a hack, because the org-mode structure commands use
5754 ;; keys which normally belong to the major mode. Here is how it
5755 ;; works: The minor mode defines all the keys necessary to operate the
5756 ;; structure commands, but wraps the commands into a function which
5757 ;; tests if the cursor is currently at a headline or a plain list
5758 ;; item. If that is the case, the structure command is used,
5759 ;; temporarily setting many Org-mode variables like regular
5760 ;; expressions for filling etc. However, when any of those keys is
5761 ;; used at a different location, function uses `key-binding' to look
5762 ;; up if the key has an associated command in another currently active
5763 ;; keymap (minor modes, major mode, global), and executes that
5764 ;; command. There might be problems if any of the keys is otherwise
5765 ;; used as a prefix key.
5767 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
5768 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
5769 ;; addresses this by checking explicitly for both bindings.
5771 (defvar orgstruct-mode-map (make-sparse-keymap)
5772 "Keymap for the minor `orgstruct-mode'.")
5774 (defvar org-local-vars nil
5775 "List of local variables, for use by `orgstruct-mode'")
5777 ;;;###autoload
5778 (define-minor-mode orgstruct-mode
5779 "Toggle the minor more `orgstruct-mode'.
5780 This mode is for using Org-mode structure commands in other modes.
5781 The following key behave as if Org-mode was active, if the cursor
5782 is on a headline, or on a plain list item (both in the definition
5783 of Org-mode).
5785 M-up Move entry/item up
5786 M-down Move entry/item down
5787 M-left Promote
5788 M-right Demote
5789 M-S-up Move entry/item up
5790 M-S-down Move entry/item down
5791 M-S-left Promote subtree
5792 M-S-right Demote subtree
5793 M-q Fill paragraph and items like in Org-mode
5794 C-c ^ Sort entries
5795 C-c - Cycle list bullet
5796 TAB Cycle item visibility
5797 M-RET Insert new heading/item
5798 S-M-RET Insert new TODO heading / Chekbox item
5799 C-c C-c Set tags / toggle checkbox"
5800 nil " OrgStruct" nil
5801 (org-load-modules-maybe)
5802 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
5804 ;;;###autoload
5805 (defun turn-on-orgstruct ()
5806 "Unconditionally turn on `orgstruct-mode'."
5807 (orgstruct-mode 1))
5809 ;;;###autoload
5810 (defun turn-on-orgstruct++ ()
5811 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
5812 In addition to setting orgstruct-mode, this also exports all indentation and
5813 autofilling variables from org-mode into the buffer. Note that turning
5814 off orgstruct-mode will *not* remove these additional settings."
5815 (orgstruct-mode 1)
5816 (let (var val)
5817 (mapc
5818 (lambda (x)
5819 (when (string-match
5820 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
5821 (symbol-name (car x)))
5822 (setq var (car x) val (nth 1 x))
5823 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
5824 org-local-vars)))
5826 (defun orgstruct-error ()
5827 "Error when there is no default binding for a structure key."
5828 (interactive)
5829 (error "This key has no function outside structure elements"))
5831 (defun orgstruct-setup ()
5832 "Setup orgstruct keymaps."
5833 (let ((nfunc 0)
5834 (bindings
5835 (list
5836 '([(meta up)] org-metaup)
5837 '([(meta down)] org-metadown)
5838 '([(meta left)] org-metaleft)
5839 '([(meta right)] org-metaright)
5840 '([(meta shift up)] org-shiftmetaup)
5841 '([(meta shift down)] org-shiftmetadown)
5842 '([(meta shift left)] org-shiftmetaleft)
5843 '([(meta shift right)] org-shiftmetaright)
5844 '([(shift up)] org-shiftup)
5845 '([(shift down)] org-shiftdown)
5846 '("\C-c\C-c" org-ctrl-c-ctrl-c)
5847 '("\M-q" fill-paragraph)
5848 '("\C-c^" org-sort)
5849 '("\C-c-" org-cycle-list-bullet)))
5850 elt key fun cmd)
5851 (while (setq elt (pop bindings))
5852 (setq nfunc (1+ nfunc))
5853 (setq key (org-key (car elt))
5854 fun (nth 1 elt)
5855 cmd (orgstruct-make-binding fun nfunc key))
5856 (org-defkey orgstruct-mode-map key cmd))
5858 ;; Special treatment needed for TAB and RET
5859 (org-defkey orgstruct-mode-map [(tab)]
5860 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
5861 (org-defkey orgstruct-mode-map "\C-i"
5862 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
5864 (org-defkey orgstruct-mode-map "\M-\C-m"
5865 (orgstruct-make-binding 'org-insert-heading 105
5866 "\M-\C-m" [(meta return)]))
5867 (org-defkey orgstruct-mode-map [(meta return)]
5868 (orgstruct-make-binding 'org-insert-heading 106
5869 [(meta return)] "\M-\C-m"))
5871 (org-defkey orgstruct-mode-map [(shift meta return)]
5872 (orgstruct-make-binding 'org-insert-todo-heading 107
5873 [(meta return)] "\M-\C-m"))
5875 (unless org-local-vars
5876 (setq org-local-vars (org-get-local-variables)))
5880 (defun orgstruct-make-binding (fun n &rest keys)
5881 "Create a function for binding in the structure minor mode.
5882 FUN is the command to call inside a table. N is used to create a unique
5883 command name. KEYS are keys that should be checked in for a command
5884 to execute outside of tables."
5885 (eval
5886 (list 'defun
5887 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
5888 '(arg)
5889 (concat "In Structure, run `" (symbol-name fun) "'.\n"
5890 "Outside of structure, run the binding of `"
5891 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
5892 "'.")
5893 '(interactive "p")
5894 (list 'if
5895 '(org-context-p 'headline 'item)
5896 (list 'org-run-like-in-org-mode (list 'quote fun))
5897 (list 'let '(orgstruct-mode)
5898 (list 'call-interactively
5899 (append '(or)
5900 (mapcar (lambda (k)
5901 (list 'key-binding k))
5902 keys)
5903 '('orgstruct-error))))))))
5905 (defun org-context-p (&rest contexts)
5906 "Check if local context is any of CONTEXTS.
5907 Possible values in the list of contexts are `table', `headline', and `item'."
5908 (let ((pos (point)))
5909 (goto-char (point-at-bol))
5910 (prog1 (or (and (memq 'table contexts)
5911 (looking-at "[ \t]*|"))
5912 (and (memq 'headline contexts)
5913 ;;????????? (looking-at "\\*+"))
5914 (looking-at outline-regexp))
5915 (and (memq 'item contexts)
5916 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
5917 (goto-char pos))))
5919 (defun org-get-local-variables ()
5920 "Return a list of all local variables in an org-mode buffer."
5921 (let (varlist)
5922 (with-current-buffer (get-buffer-create "*Org tmp*")
5923 (erase-buffer)
5924 (org-mode)
5925 (setq varlist (buffer-local-variables)))
5926 (kill-buffer "*Org tmp*")
5927 (delq nil
5928 (mapcar
5929 (lambda (x)
5930 (setq x
5931 (if (symbolp x)
5932 (list x)
5933 (list (car x) (list 'quote (cdr x)))))
5934 (if (string-match
5935 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
5936 (symbol-name (car x)))
5937 x nil))
5938 varlist))))
5940 ;;;###autoload
5941 (defun org-run-like-in-org-mode (cmd)
5942 (org-load-modules-maybe)
5943 (unless org-local-vars
5944 (setq org-local-vars (org-get-local-variables)))
5945 (eval (list 'let org-local-vars
5946 (list 'call-interactively (list 'quote cmd)))))
5948 ;;;; Archiving
5950 (defun org-get-category (&optional pos)
5951 "Get the category applying to position POS."
5952 (get-text-property (or pos (point)) 'org-category))
5954 (defun org-refresh-category-properties ()
5955 "Refresh category text properties in the buffer."
5956 (let ((def-cat (cond
5957 ((null org-category)
5958 (if buffer-file-name
5959 (file-name-sans-extension
5960 (file-name-nondirectory buffer-file-name))
5961 "???"))
5962 ((symbolp org-category) (symbol-name org-category))
5963 (t org-category)))
5964 beg end cat pos optionp)
5965 (org-unmodified
5966 (save-excursion
5967 (save-restriction
5968 (widen)
5969 (goto-char (point-min))
5970 (put-text-property (point) (point-max) 'org-category def-cat)
5971 (while (re-search-forward
5972 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
5973 (setq pos (match-end 0)
5974 optionp (equal (char-after (match-beginning 0)) ?#)
5975 cat (org-trim (match-string 2)))
5976 (if optionp
5977 (setq beg (point-at-bol) end (point-max))
5978 (org-back-to-heading t)
5979 (setq beg (point) end (org-end-of-subtree t t)))
5980 (put-text-property beg end 'org-category cat)
5981 (goto-char pos)))))))
5984 ;;;; Link Stuff
5986 ;;; Link abbreviations
5988 (defun org-link-expand-abbrev (link)
5989 "Apply replacements as defined in `org-link-abbrev-alist."
5990 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
5991 (let* ((key (match-string 1 link))
5992 (as (or (assoc key org-link-abbrev-alist-local)
5993 (assoc key org-link-abbrev-alist)))
5994 (tag (and (match-end 2) (match-string 3 link)))
5995 rpl)
5996 (if (not as)
5997 link
5998 (setq rpl (cdr as))
5999 (cond
6000 ((symbolp rpl) (funcall rpl tag))
6001 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
6002 ((string-match "%h" rpl)
6003 (replace-match (url-hexify-string (or tag "")) t t rpl))
6004 (t (concat rpl tag)))))
6005 link))
6007 ;;; Storing and inserting links
6009 (defvar org-insert-link-history nil
6010 "Minibuffer history for links inserted with `org-insert-link'.")
6012 (defvar org-stored-links nil
6013 "Contains the links stored with `org-store-link'.")
6015 (defvar org-store-link-plist nil
6016 "Plist with info about the most recently link created with `org-store-link'.")
6018 (defvar org-link-protocols nil
6019 "Link protocols added to Org-mode using `org-add-link-type'.")
6021 (defvar org-store-link-functions nil
6022 "List of functions that are called to create and store a link.
6023 Each function will be called in turn until one returns a non-nil
6024 value. Each function should check if it is responsible for creating
6025 this link (for example by looking at the major mode).
6026 If not, it must exit and return nil.
6027 If yes, it should return a non-nil value after a calling
6028 `org-store-link-props' with a list of properties and values.
6029 Special properties are:
6031 :type The link prefix. like \"http\". This must be given.
6032 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6033 This is obligatory as well.
6034 :description Optional default description for the second pair
6035 of brackets in an Org-mode link. The user can still change
6036 this when inserting this link into an Org-mode buffer.
6038 In addition to these, any additional properties can be specified
6039 and then used in remember templates.")
6041 (defun org-add-link-type (type &optional follow export)
6042 "Add TYPE to the list of `org-link-types'.
6043 Re-compute all regular expressions depending on `org-link-types'
6045 FOLLOW and EXPORT are two functions.
6047 FOLLOW should take the link path as the single argument and do whatever
6048 is necessary to follow the link, for example find a file or display
6049 a mail message.
6051 EXPORT should format the link path for export to one of the export formats.
6052 It should be a function accepting three arguments:
6054 path the path of the link, the text after the prefix (like \"http:\")
6055 desc the description of the link, if any, nil if there was no descripton
6056 format the export format, a symbol like `html' or `latex'.
6058 The function may use the FORMAT information to return different values
6059 depending on the format. The return value will be put literally into
6060 the exported file.
6061 Org-mode has a built-in default for exporting links. If you are happy with
6062 this default, there is no need to define an export function for the link
6063 type. For a simple example of an export function, see `org-bbdb.el'."
6064 (add-to-list 'org-link-types type t)
6065 (org-make-link-regexps)
6066 (if (assoc type org-link-protocols)
6067 (setcdr (assoc type org-link-protocols) (list follow export))
6068 (push (list type follow export) org-link-protocols)))
6071 ;;;###autoload
6072 (defun org-store-link (arg)
6073 "\\<org-mode-map>Store an org-link to the current location.
6074 This link is added to `org-stored-links' and can later be inserted
6075 into an org-buffer with \\[org-insert-link].
6077 For some link types, a prefix arg is interpreted:
6078 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
6079 For file links, arg negates `org-context-in-file-links'."
6080 (interactive "P")
6081 (org-load-modules-maybe)
6082 (setq org-store-link-plist nil) ; reset
6083 (let (link cpltxt desc description search txt)
6084 (cond
6086 ((run-hook-with-args-until-success 'org-store-link-functions)
6087 (setq link (plist-get org-store-link-plist :link)
6088 desc (or (plist-get org-store-link-plist :description) link)))
6090 ((eq major-mode 'calendar-mode)
6091 (let ((cd (calendar-cursor-to-date)))
6092 (setq link
6093 (format-time-string
6094 (car org-time-stamp-formats)
6095 (apply 'encode-time
6096 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6097 nil nil nil))))
6098 (org-store-link-props :type "calendar" :date cd)))
6100 ((eq major-mode 'w3-mode)
6101 (setq cpltxt (url-view-url t)
6102 link (org-make-link cpltxt))
6103 (org-store-link-props :type "w3" :url (url-view-url t)))
6105 ((eq major-mode 'w3m-mode)
6106 (setq cpltxt (or w3m-current-title w3m-current-url)
6107 link (org-make-link w3m-current-url))
6108 (org-store-link-props :type "w3m" :url (url-view-url t)))
6110 ((setq search (run-hook-with-args-until-success
6111 'org-create-file-search-functions))
6112 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6113 "::" search))
6114 (setq cpltxt (or description link)))
6116 ((eq major-mode 'image-mode)
6117 (setq cpltxt (concat "file:"
6118 (abbreviate-file-name buffer-file-name))
6119 link (org-make-link cpltxt))
6120 (org-store-link-props :type "image" :file buffer-file-name))
6122 ((eq major-mode 'dired-mode)
6123 ;; link to the file in the current line
6124 (setq cpltxt (concat "file:"
6125 (abbreviate-file-name
6126 (expand-file-name
6127 (dired-get-filename nil t))))
6128 link (org-make-link cpltxt)))
6130 ((and buffer-file-name (org-mode-p))
6131 ;; Just link to current headline
6132 (setq cpltxt (concat "file:"
6133 (abbreviate-file-name buffer-file-name)))
6134 ;; Add a context search string
6135 (when (org-xor org-context-in-file-links arg)
6136 ;; Check if we are on a target
6137 (if (org-in-regexp "<<\\(.*?\\)>>")
6138 (setq cpltxt (concat cpltxt "::" (match-string 1)))
6139 (setq txt (cond
6140 ((org-on-heading-p) nil)
6141 ((org-region-active-p)
6142 (buffer-substring (region-beginning) (region-end)))
6143 (t nil)))
6144 (when (or (null txt) (string-match "\\S-" txt))
6145 (setq cpltxt
6146 (concat cpltxt "::"
6147 (condition-case nil
6148 (org-make-org-heading-search-string txt)
6149 (error "")))
6150 desc "NONE"))))
6151 (if (string-match "::\\'" cpltxt)
6152 (setq cpltxt (substring cpltxt 0 -2)))
6153 (setq link (org-make-link cpltxt)))
6155 ((buffer-file-name (buffer-base-buffer))
6156 ;; Just link to this file here.
6157 (setq cpltxt (concat "file:"
6158 (abbreviate-file-name
6159 (buffer-file-name (buffer-base-buffer)))))
6160 ;; Add a context string
6161 (when (org-xor org-context-in-file-links arg)
6162 (setq txt (if (org-region-active-p)
6163 (buffer-substring (region-beginning) (region-end))
6164 (buffer-substring (point-at-bol) (point-at-eol))))
6165 ;; Only use search option if there is some text.
6166 (when (string-match "\\S-" txt)
6167 (setq cpltxt
6168 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6169 desc "NONE")))
6170 (setq link (org-make-link cpltxt)))
6172 ((interactive-p)
6173 (error "Cannot link to a buffer which is not visiting a file"))
6175 (t (setq link nil)))
6177 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6178 (setq link (or link cpltxt)
6179 desc (or desc cpltxt))
6180 (if (equal desc "NONE") (setq desc nil))
6182 (if (and (interactive-p) link)
6183 (progn
6184 (setq org-stored-links
6185 (cons (list link desc) org-stored-links))
6186 (message "Stored: %s" (or desc link)))
6187 (and link (org-make-link-string link desc)))))
6189 (defun org-store-link-props (&rest plist)
6190 "Store link properties, extract names and addresses."
6191 (let (x adr)
6192 (when (setq x (plist-get plist :from))
6193 (setq adr (mail-extract-address-components x))
6194 (setq plist (plist-put plist :fromname (car adr)))
6195 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
6196 (when (setq x (plist-get plist :to))
6197 (setq adr (mail-extract-address-components x))
6198 (setq plist (plist-put plist :toname (car adr)))
6199 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
6200 (let ((from (plist-get plist :from))
6201 (to (plist-get plist :to)))
6202 (when (and from to org-from-is-user-regexp)
6203 (setq plist
6204 (plist-put plist :fromto
6205 (if (string-match org-from-is-user-regexp from)
6206 (concat "to %t")
6207 (concat "from %f"))))))
6208 (setq org-store-link-plist plist))
6210 (defun org-add-link-props (&rest plist)
6211 "Add these properties to the link property list."
6212 (let (key value)
6213 (while plist
6214 (setq key (pop plist) value (pop plist))
6215 (setq org-store-link-plist
6216 (plist-put org-store-link-plist key value)))))
6218 (defun org-email-link-description (&optional fmt)
6219 "Return the description part of an email link.
6220 This takes information from `org-store-link-plist' and formats it
6221 according to FMT (default from `org-email-link-description-format')."
6222 (setq fmt (or fmt org-email-link-description-format))
6223 (let* ((p org-store-link-plist)
6224 (to (plist-get p :toaddress))
6225 (from (plist-get p :fromaddress))
6226 (table
6227 (list
6228 (cons "%c" (plist-get p :fromto))
6229 (cons "%F" (plist-get p :from))
6230 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
6231 (cons "%T" (plist-get p :to))
6232 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
6233 (cons "%s" (plist-get p :subject))
6234 (cons "%m" (plist-get p :message-id)))))
6235 (when (string-match "%c" fmt)
6236 ;; Check if the user wrote this message
6237 (if (and org-from-is-user-regexp from to
6238 (save-match-data (string-match org-from-is-user-regexp from)))
6239 (setq fmt (replace-match "to %t" t t fmt))
6240 (setq fmt (replace-match "from %f" t t fmt))))
6241 (org-replace-escapes fmt table)))
6243 (defun org-make-org-heading-search-string (&optional string heading)
6244 "Make search string for STRING or current headline."
6245 (interactive)
6246 (let ((s (or string (org-get-heading))))
6247 (unless (and string (not heading))
6248 ;; We are using a headline, clean up garbage in there.
6249 (if (string-match org-todo-regexp s)
6250 (setq s (replace-match "" t t s)))
6251 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
6252 (setq s (replace-match "" t t s)))
6253 (setq s (org-trim s))
6254 (if (string-match (concat "^\\(" org-quote-string "\\|"
6255 org-comment-string "\\)") s)
6256 (setq s (replace-match "" t t s)))
6257 (while (string-match org-ts-regexp s)
6258 (setq s (replace-match "" t t s))))
6259 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
6260 (setq s (replace-match " " t t s)))
6261 (or string (setq s (concat "*" s))) ; Add * for headlines
6262 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
6264 (defun org-make-link (&rest strings)
6265 "Concatenate STRINGS."
6266 (apply 'concat strings))
6268 (defun org-make-link-string (link &optional description)
6269 "Make a link with brackets, consisting of LINK and DESCRIPTION."
6270 (unless (string-match "\\S-" link)
6271 (error "Empty link"))
6272 (when (stringp description)
6273 ;; Remove brackets from the description, they are fatal.
6274 (while (string-match "\\[" description)
6275 (setq description (replace-match "{" t t description)))
6276 (while (string-match "\\]" description)
6277 (setq description (replace-match "}" t t description))))
6278 (when (equal (org-link-escape link) description)
6279 ;; No description needed, it is identical
6280 (setq description nil))
6281 (when (and (not description)
6282 (not (equal link (org-link-escape link))))
6283 (setq description (org-extract-attributes link)))
6284 (concat "[[" (org-link-escape link) "]"
6285 (if description (concat "[" description "]") "")
6286 "]"))
6288 (defconst org-link-escape-chars
6289 '((?\ . "%20")
6290 (?\[ . "%5B")
6291 (?\] . "%5D")
6292 (?\340 . "%E0") ; `a
6293 (?\342 . "%E2") ; ^a
6294 (?\347 . "%E7") ; ,c
6295 (?\350 . "%E8") ; `e
6296 (?\351 . "%E9") ; 'e
6297 (?\352 . "%EA") ; ^e
6298 (?\356 . "%EE") ; ^i
6299 (?\364 . "%F4") ; ^o
6300 (?\371 . "%F9") ; `u
6301 (?\373 . "%FB") ; ^u
6302 (?\; . "%3B")
6303 (?? . "%3F")
6304 (?= . "%3D")
6305 (?+ . "%2B")
6307 "Association list of escapes for some characters problematic in links.
6308 This is the list that is used for internal purposes.")
6310 (defconst org-link-escape-chars-browser
6311 '((?\ . "%20")) ; 32 for the SPC char
6312 "Association list of escapes for some characters problematic in links.
6313 This is the list that is used before handing over to the browser.")
6315 (defun org-link-escape (text &optional table)
6316 "Escape charaters in TEXT that are problematic for links."
6317 (setq table (or table org-link-escape-chars))
6318 (when text
6319 (let ((re (mapconcat (lambda (x) (regexp-quote
6320 (char-to-string (car x))))
6321 table "\\|")))
6322 (while (string-match re text)
6323 (setq text
6324 (replace-match
6325 (cdr (assoc (string-to-char (match-string 0 text))
6326 table))
6327 t t text)))
6328 text)))
6330 (defun org-link-unescape (text &optional table)
6331 "Reverse the action of `org-link-escape'."
6332 (setq table (or table org-link-escape-chars))
6333 (when text
6334 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
6335 table "\\|")))
6336 (while (string-match re text)
6337 (setq text
6338 (replace-match
6339 (char-to-string (car (rassoc (match-string 0 text) table)))
6340 t t text)))
6341 text)))
6343 (defun org-xor (a b)
6344 "Exclusive or."
6345 (if a (not b) b))
6347 (defun org-get-header (header)
6348 "Find a header field in the current buffer."
6349 (save-excursion
6350 (goto-char (point-min))
6351 (let ((case-fold-search t) s)
6352 (cond
6353 ((eq header 'from)
6354 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
6355 (setq s (match-string 1)))
6356 (while (string-match "\"" s)
6357 (setq s (replace-match "" t t s)))
6358 (if (string-match "[<(].*" s)
6359 (setq s (replace-match "" t t s))))
6360 ((eq header 'message-id)
6361 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
6362 (setq s (match-string 1))))
6363 ((eq header 'subject)
6364 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
6365 (setq s (match-string 1)))))
6366 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
6367 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
6368 s)))
6371 (defun org-fixup-message-id-for-http (s)
6372 "Replace special characters in a message id, so it can be used in an http query."
6373 (while (string-match "<" s)
6374 (setq s (replace-match "%3C" t t s)))
6375 (while (string-match ">" s)
6376 (setq s (replace-match "%3E" t t s)))
6377 (while (string-match "@" s)
6378 (setq s (replace-match "%40" t t s)))
6381 ;;;###autoload
6382 (defun org-insert-link-global ()
6383 "Insert a link like Org-mode does.
6384 This command can be called in any mode to insert a link in Org-mode syntax."
6385 (interactive)
6386 (org-load-modules-maybe)
6387 (org-run-like-in-org-mode 'org-insert-link))
6389 (defun org-insert-link (&optional complete-file link-location)
6390 "Insert a link. At the prompt, enter the link.
6392 Completion can be used to insert any of the link protocol prefixes like
6393 http or ftp in use.
6395 The history can be used to select a link previously stored with
6396 `org-store-link'. When the empty string is entered (i.e. if you just
6397 press RET at the prompt), the link defaults to the most recently
6398 stored link. As SPC triggers completion in the minibuffer, you need to
6399 use M-SPC or C-q SPC to force the insertion of a space character.
6401 You will also be prompted for a description, and if one is given, it will
6402 be displayed in the buffer instead of the link.
6404 If there is already a link at point, this command will allow you to edit link
6405 and description parts.
6407 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
6408 be selected using completion. The path to the file will be relative to the
6409 current directory if the file is in the current directory or a subdirectory.
6410 Otherwise, the link will be the absolute path as completed in the minibuffer
6411 \(i.e. normally ~/path/to/file). You can configure this behavior using the
6412 option `org-link-file-path-type'.
6414 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
6415 the current directory or below.
6417 With three \\[universal-argument] prefixes, negate the meaning of
6418 `org-keep-stored-link-after-insertion'.
6420 If `org-make-link-description-function' is non-nil, this function will be
6421 called with the link target, and the result will be the default
6422 link description.
6424 If the LINK-LOCATION parameter is non-nil, this value will be
6425 used as the link location instead of reading one interactively."
6426 (interactive "P")
6427 (let* ((wcf (current-window-configuration))
6428 (region (if (org-region-active-p)
6429 (buffer-substring (region-beginning) (region-end))))
6430 (remove (and region (list (region-beginning) (region-end))))
6431 (desc region)
6432 tmphist ; byte-compile incorrectly complains about this
6433 (link link-location)
6434 entry file)
6435 (cond
6436 (link-location) ; specified by arg, just use it.
6437 ((org-in-regexp org-bracket-link-regexp 1)
6438 ;; We do have a link at point, and we are going to edit it.
6439 (setq remove (list (match-beginning 0) (match-end 0)))
6440 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
6441 (setq link (read-string "Link: "
6442 (org-link-unescape
6443 (org-match-string-no-properties 1)))))
6444 ((or (org-in-regexp org-angle-link-re)
6445 (org-in-regexp org-plain-link-re))
6446 ;; Convert to bracket link
6447 (setq remove (list (match-beginning 0) (match-end 0))
6448 link (read-string "Link: "
6449 (org-remove-angle-brackets (match-string 0)))))
6450 ((member complete-file '((4) (16)))
6451 ;; Completing read for file names.
6452 (setq file (read-file-name "File: "))
6453 (let ((pwd (file-name-as-directory (expand-file-name ".")))
6454 (pwd1 (file-name-as-directory (abbreviate-file-name
6455 (expand-file-name ".")))))
6456 (cond
6457 ((equal complete-file '(16))
6458 (setq link (org-make-link
6459 "file:"
6460 (abbreviate-file-name (expand-file-name file)))))
6461 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
6462 (setq link (org-make-link "file:" (match-string 1 file))))
6463 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
6464 (expand-file-name file))
6465 (setq link (org-make-link
6466 "file:" (match-string 1 (expand-file-name file)))))
6467 (t (setq link (org-make-link "file:" file))))))
6469 ;; Read link, with completion for stored links.
6470 (with-output-to-temp-buffer "*Org Links*"
6471 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
6472 (when org-stored-links
6473 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
6474 (princ (mapconcat
6475 (lambda (x)
6476 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
6477 (reverse org-stored-links) "\n"))))
6478 (let ((cw (selected-window)))
6479 (select-window (get-buffer-window "*Org Links*"))
6480 (org-fit-window-to-buffer)
6481 (setq truncate-lines t)
6482 (select-window cw))
6483 ;; Fake a link history, containing the stored links.
6484 (setq tmphist (append (mapcar 'car org-stored-links)
6485 org-insert-link-history))
6486 (unwind-protect
6487 (setq link (org-completing-read
6488 "Link: "
6489 (append
6490 (mapcar (lambda (x) (list (concat (car x) ":")))
6491 (append org-link-abbrev-alist-local org-link-abbrev-alist))
6492 (mapcar (lambda (x) (list (concat x ":")))
6493 org-link-types))
6494 nil nil nil
6495 'tmphist
6496 (or (car (car org-stored-links)))))
6497 (set-window-configuration wcf)
6498 (kill-buffer "*Org Links*"))
6499 (setq entry (assoc link org-stored-links))
6500 (or entry (push link org-insert-link-history))
6501 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
6502 (not org-keep-stored-link-after-insertion))
6503 (setq org-stored-links (delq (assoc link org-stored-links)
6504 org-stored-links)))
6505 (setq desc (or desc (nth 1 entry)))))
6507 (if (string-match org-plain-link-re link)
6508 ;; URL-like link, normalize the use of angular brackets.
6509 (setq link (org-make-link (org-remove-angle-brackets link))))
6511 ;; Check if we are linking to the current file with a search option
6512 ;; If yes, simplify the link by using only the search option.
6513 (when (and buffer-file-name
6514 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
6515 (let* ((path (match-string 1 link))
6516 (case-fold-search nil)
6517 (search (match-string 2 link)))
6518 (save-match-data
6519 (if (equal (file-truename buffer-file-name) (file-truename path))
6520 ;; We are linking to this same file, with a search option
6521 (setq link search)))))
6523 ;; Check if we can/should use a relative path. If yes, simplify the link
6524 (when (string-match "\\<file:\\(.*\\)" link)
6525 (let* ((path (match-string 1 link))
6526 (origpath path)
6527 (case-fold-search nil))
6528 (cond
6529 ((or (eq org-link-file-path-type 'absolute)
6530 (equal complete-file '(16)))
6531 (setq path (abbreviate-file-name (expand-file-name path))))
6532 ((eq org-link-file-path-type 'noabbrev)
6533 (setq path (expand-file-name path)))
6534 ((eq org-link-file-path-type 'relative)
6535 (setq path (file-relative-name path)))
6537 (save-match-data
6538 (if (string-match (concat "^" (regexp-quote
6539 (file-name-as-directory
6540 (expand-file-name "."))))
6541 (expand-file-name path))
6542 ;; We are linking a file with relative path name.
6543 (setq path (substring (expand-file-name path)
6544 (match-end 0)))
6545 (setq path (abbreviate-file-name (expand-file-name path)))))))
6546 (setq link (concat "file:" path))
6547 (if (equal desc origpath)
6548 (setq desc path))))
6550 (if org-make-link-description-function
6551 (setq desc (funcall org-make-link-description-function link desc)))
6553 (setq desc (read-string "Description: " desc))
6554 (unless (string-match "\\S-" desc) (setq desc nil))
6555 (if remove (apply 'delete-region remove))
6556 (insert (org-make-link-string link desc))))
6558 (defun org-completing-read (&rest args)
6559 "Completing-read with SPACE being a normal character."
6560 (let ((minibuffer-local-completion-map
6561 (copy-keymap minibuffer-local-completion-map)))
6562 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
6563 (apply 'completing-read args)))
6565 (defun org-extract-attributes (s)
6566 "Extract the attributes cookie from a string and set as text property."
6567 (let (a attr (start 0) key value)
6568 (save-match-data
6569 (when (string-match "{{\\([^}]+\\)}}$" s)
6570 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
6571 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
6572 (setq key (match-string 1 a) value (match-string 2 a)
6573 start (match-end 0)
6574 attr (plist-put attr (intern key) value))))
6575 (org-add-props s nil 'org-attributes attr))
6578 (defun org-attributes-to-string (plist)
6579 "Format a property list into an HTML attribute list."
6580 (let ((s "") key value)
6581 (while plist
6582 (setq key (pop plist) value (pop plist))
6583 (setq s (concat s " "(symbol-name key) "=\"" value "\"")))
6586 ;;; Opening/following a link
6588 (defvar org-link-search-failed nil)
6590 (defun org-next-link ()
6591 "Move forward to the next link.
6592 If the link is in hidden text, expose it."
6593 (interactive)
6594 (when (and org-link-search-failed (eq this-command last-command))
6595 (goto-char (point-min))
6596 (message "Link search wrapped back to beginning of buffer"))
6597 (setq org-link-search-failed nil)
6598 (let* ((pos (point))
6599 (ct (org-context))
6600 (a (assoc :link ct)))
6601 (if a (goto-char (nth 2 a)))
6602 (if (re-search-forward org-any-link-re nil t)
6603 (progn
6604 (goto-char (match-beginning 0))
6605 (if (org-invisible-p) (org-show-context)))
6606 (goto-char pos)
6607 (setq org-link-search-failed t)
6608 (error "No further link found"))))
6610 (defun org-previous-link ()
6611 "Move backward to the previous link.
6612 If the link is in hidden text, expose it."
6613 (interactive)
6614 (when (and org-link-search-failed (eq this-command last-command))
6615 (goto-char (point-max))
6616 (message "Link search wrapped back to end of buffer"))
6617 (setq org-link-search-failed nil)
6618 (let* ((pos (point))
6619 (ct (org-context))
6620 (a (assoc :link ct)))
6621 (if a (goto-char (nth 1 a)))
6622 (if (re-search-backward org-any-link-re nil t)
6623 (progn
6624 (goto-char (match-beginning 0))
6625 (if (org-invisible-p) (org-show-context)))
6626 (goto-char pos)
6627 (setq org-link-search-failed t)
6628 (error "No further link found"))))
6630 (defun org-translate-link (s)
6631 "Translate a link string if a translation function has been defined."
6632 (if (and org-link-translation-function
6633 (fboundp org-link-translation-function)
6634 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
6635 (progn
6636 (setq s (funcall org-link-translation-function
6637 (match-string 1) (match-string 2)))
6638 (concat (car s) ":" (cdr s)))
6641 (defun org-translate-link-from-planner (type path)
6642 "Translate a link from Emacs Planner syntax so that Org can follow it.
6643 This is still an experimental function, your mileage may vary."
6644 (cond
6645 ((member type '("http" "https" "news" "ftp"))
6646 ;; standard Internet links are the same.
6647 nil)
6648 ((and (equal type "irc") (string-match "^//" path))
6649 ;; Planner has two / at the beginning of an irc link, we have 1.
6650 ;; We should have zero, actually....
6651 (setq path (substring path 1)))
6652 ((and (equal type "lisp") (string-match "^/" path))
6653 ;; Planner has a slash, we do not.
6654 (setq type "elisp" path (substring path 1)))
6655 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
6656 ;; A typical message link. Planner has the id after the fina slash,
6657 ;; we separate it with a hash mark
6658 (setq path (concat (match-string 1 path) "#"
6659 (org-remove-angle-brackets (match-string 2 path)))))
6661 (cons type path))
6663 (defun org-find-file-at-mouse (ev)
6664 "Open file link or URL at mouse."
6665 (interactive "e")
6666 (mouse-set-point ev)
6667 (org-open-at-point 'in-emacs))
6669 (defun org-open-at-mouse (ev)
6670 "Open file link or URL at mouse."
6671 (interactive "e")
6672 (mouse-set-point ev)
6673 (if (eq major-mode 'org-agenda-mode)
6674 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
6675 (org-open-at-point))
6677 (defvar org-window-config-before-follow-link nil
6678 "The window configuration before following a link.
6679 This is saved in case the need arises to restore it.")
6681 (defvar org-open-link-marker (make-marker)
6682 "Marker pointing to the location where `org-open-at-point; was called.")
6684 ;;;###autoload
6685 (defun org-open-at-point-global ()
6686 "Follow a link like Org-mode does.
6687 This command can be called in any mode to follow a link that has
6688 Org-mode syntax."
6689 (interactive)
6690 (org-run-like-in-org-mode 'org-open-at-point))
6692 ;;;###autoload
6693 (defun org-open-link-from-string (s &optional arg)
6694 "Open a link in the string S, as if it was in Org-mode."
6695 (interactive "sLink: \nP")
6696 (with-temp-buffer
6697 (let ((org-inhibit-startup t))
6698 (org-mode)
6699 (insert s)
6700 (goto-char (point-min))
6701 (org-open-at-point arg))))
6703 (defun org-open-at-point (&optional in-emacs)
6704 "Open link at or after point.
6705 If there is no link at point, this function will search forward up to
6706 the end of the current subtree.
6707 Normally, files will be opened by an appropriate application. If the
6708 optional argument IN-EMACS is non-nil, Emacs will visit the file.
6709 With a double prefix argument, try to open outside of Emacs, in the
6710 application the system uses for this file type."
6711 (interactive "P")
6712 (org-load-modules-maybe)
6713 (move-marker org-open-link-marker (point))
6714 (setq org-window-config-before-follow-link (current-window-configuration))
6715 (org-remove-occur-highlights nil nil t)
6716 (if (org-at-timestamp-p t)
6717 (org-follow-timestamp-link)
6718 (let (type path link line search (pos (point)))
6719 (catch 'match
6720 (save-excursion
6721 (skip-chars-forward "^]\n\r")
6722 (when (org-in-regexp org-bracket-link-regexp)
6723 (setq link (org-extract-attributes
6724 (org-link-unescape (org-match-string-no-properties 1))))
6725 (while (string-match " *\n *" link)
6726 (setq link (replace-match " " t t link)))
6727 (setq link (org-link-expand-abbrev link))
6728 (cond
6729 ((or (file-name-absolute-p link)
6730 (string-match "^\\.\\.?/" link))
6731 (setq type "file" path link))
6732 ((string-match org-link-re-with-space3 link)
6733 (setq type (match-string 1 link) path (match-string 2 link)))
6734 (t (setq type "thisfile" path link)))
6735 (throw 'match t)))
6737 (when (get-text-property (point) 'org-linked-text)
6738 (setq type "thisfile"
6739 pos (if (get-text-property (1+ (point)) 'org-linked-text)
6740 (1+ (point)) (point))
6741 path (buffer-substring
6742 (previous-single-property-change pos 'org-linked-text)
6743 (next-single-property-change pos 'org-linked-text)))
6744 (throw 'match t))
6746 (save-excursion
6747 (when (or (org-in-regexp org-angle-link-re)
6748 (org-in-regexp org-plain-link-re))
6749 (setq type (match-string 1) path (match-string 2))
6750 (throw 'match t)))
6751 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
6752 (setq type "tree-match"
6753 path (match-string 1))
6754 (throw 'match t))
6755 (save-excursion
6756 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
6757 (setq type "tags"
6758 path (match-string 1))
6759 (while (string-match ":" path)
6760 (setq path (replace-match "+" t t path)))
6761 (throw 'match t))))
6762 (unless path
6763 (error "No link found"))
6764 ;; Remove any trailing spaces in path
6765 (if (string-match " +\\'" path)
6766 (setq path (replace-match "" t t path)))
6767 (if (and org-link-translation-function
6768 (fboundp org-link-translation-function))
6769 ;; Check if we need to translate the link
6770 (let ((tmp (funcall org-link-translation-function type path)))
6771 (setq type (car tmp) path (cdr tmp))))
6773 (cond
6775 ((assoc type org-link-protocols)
6776 (funcall (nth 1 (assoc type org-link-protocols)) path))
6778 ((equal type "mailto")
6779 (let ((cmd (car org-link-mailto-program))
6780 (args (cdr org-link-mailto-program)) args1
6781 (address path) (subject "") a)
6782 (if (string-match "\\(.*\\)::\\(.*\\)" path)
6783 (setq address (match-string 1 path)
6784 subject (org-link-escape (match-string 2 path))))
6785 (while args
6786 (cond
6787 ((not (stringp (car args))) (push (pop args) args1))
6788 (t (setq a (pop args))
6789 (if (string-match "%a" a)
6790 (setq a (replace-match address t t a)))
6791 (if (string-match "%s" a)
6792 (setq a (replace-match subject t t a)))
6793 (push a args1))))
6794 (apply cmd (nreverse args1))))
6796 ((member type '("http" "https" "ftp" "news"))
6797 (browse-url (concat type ":" (org-link-escape
6798 path org-link-escape-chars-browser))))
6800 ((member type '("message"))
6801 (browse-url (concat type ":" path)))
6803 ((string= type "tags")
6804 (org-tags-view in-emacs path))
6805 ((string= type "thisfile")
6806 (if in-emacs
6807 (switch-to-buffer-other-window
6808 (org-get-buffer-for-internal-link (current-buffer)))
6809 (org-mark-ring-push))
6810 (let ((cmd `(org-link-search
6811 ,path
6812 ,(cond ((equal in-emacs '(4)) 'occur)
6813 ((equal in-emacs '(16)) 'org-occur)
6814 (t nil))
6815 ,pos)))
6816 (condition-case nil (eval cmd)
6817 (error (progn (widen) (eval cmd))))))
6819 ((string= type "tree-match")
6820 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
6822 ((string= type "file")
6823 (if (string-match "::\\([0-9]+\\)\\'" path)
6824 (setq line (string-to-number (match-string 1 path))
6825 path (substring path 0 (match-beginning 0)))
6826 (if (string-match "::\\(.+\\)\\'" path)
6827 (setq search (match-string 1 path)
6828 path (substring path 0 (match-beginning 0)))))
6829 (if (string-match "[*?{]" (file-name-nondirectory path))
6830 (dired path)
6831 (org-open-file path in-emacs line search)))
6833 ((string= type "news")
6834 (require 'org-gnus)
6835 (org-gnus-follow-link path))
6837 ((string= type "shell")
6838 (let ((cmd path))
6839 (if (or (not org-confirm-shell-link-function)
6840 (funcall org-confirm-shell-link-function
6841 (format "Execute \"%s\" in shell? "
6842 (org-add-props cmd nil
6843 'face 'org-warning))))
6844 (progn
6845 (message "Executing %s" cmd)
6846 (shell-command cmd))
6847 (error "Abort"))))
6849 ((string= type "elisp")
6850 (let ((cmd path))
6851 (if (or (not org-confirm-elisp-link-function)
6852 (funcall org-confirm-elisp-link-function
6853 (format "Execute \"%s\" as elisp? "
6854 (org-add-props cmd nil
6855 'face 'org-warning))))
6856 (message "%s => %s" cmd
6857 (if (equal (string-to-char cmd) ?\()
6858 (call-interactively (read cmd))
6859 (eval (read cmd))))
6860 (error "Abort"))))
6863 (browse-url-at-point)))))
6864 (move-marker org-open-link-marker nil)
6865 (run-hook-with-args 'org-follow-link-hook))
6867 ;;;; Time estimates
6869 (defun org-get-effort (&optional pom)
6870 "Get the effort estimate for the current entry."
6871 (org-entry-get pom org-effort-property))
6873 ;;; File search
6875 (defvar org-create-file-search-functions nil
6876 "List of functions to construct the right search string for a file link.
6877 These functions are called in turn with point at the location to
6878 which the link should point.
6880 A function in the hook should first test if it would like to
6881 handle this file type, for example by checking the major-mode or
6882 the file extension. If it decides not to handle this file, it
6883 should just return nil to give other functions a chance. If it
6884 does handle the file, it must return the search string to be used
6885 when following the link. The search string will be part of the
6886 file link, given after a double colon, and `org-open-at-point'
6887 will automatically search for it. If special measures must be
6888 taken to make the search successful, another function should be
6889 added to the companion hook `org-execute-file-search-functions',
6890 which see.
6892 A function in this hook may also use `setq' to set the variable
6893 `description' to provide a suggestion for the descriptive text to
6894 be used for this link when it gets inserted into an Org-mode
6895 buffer with \\[org-insert-link].")
6897 (defvar org-execute-file-search-functions nil
6898 "List of functions to execute a file search triggered by a link.
6900 Functions added to this hook must accept a single argument, the
6901 search string that was part of the file link, the part after the
6902 double colon. The function must first check if it would like to
6903 handle this search, for example by checking the major-mode or the
6904 file extension. If it decides not to handle this search, it
6905 should just return nil to give other functions a chance. If it
6906 does handle the search, it must return a non-nil value to keep
6907 other functions from trying.
6909 Each function can access the current prefix argument through the
6910 variable `current-prefix-argument'. Note that a single prefix is
6911 used to force opening a link in Emacs, so it may be good to only
6912 use a numeric or double prefix to guide the search function.
6914 In case this is needed, a function in this hook can also restore
6915 the window configuration before `org-open-at-point' was called using:
6917 (set-window-configuration org-window-config-before-follow-link)")
6919 (defun org-link-search (s &optional type avoid-pos)
6920 "Search for a link search option.
6921 If S is surrounded by forward slashes, it is interpreted as a
6922 regular expression. In org-mode files, this will create an `org-occur'
6923 sparse tree. In ordinary files, `occur' will be used to list matches.
6924 If the current buffer is in `dired-mode', grep will be used to search
6925 in all files. If AVOID-POS is given, ignore matches near that position."
6926 (let ((case-fold-search t)
6927 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
6928 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
6929 (append '(("") (" ") ("\t") ("\n"))
6930 org-emphasis-alist)
6931 "\\|") "\\)"))
6932 (pos (point))
6933 (pre nil) (post nil)
6934 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
6935 (cond
6936 ;; First check if there are any special
6937 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
6938 ;; Now try the builtin stuff
6939 ((save-excursion
6940 (goto-char (point-min))
6941 (and
6942 (re-search-forward
6943 (concat "<<" (regexp-quote s0) ">>") nil t)
6944 (setq type 'dedicated
6945 pos (match-beginning 0))))
6946 ;; There is an exact target for this
6947 (goto-char pos))
6948 ((string-match "^/\\(.*\\)/$" s)
6949 ;; A regular expression
6950 (cond
6951 ((org-mode-p)
6952 (org-occur (match-string 1 s)))
6953 ;;((eq major-mode 'dired-mode)
6954 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
6955 (t (org-do-occur (match-string 1 s)))))
6957 ;; A normal search strings
6958 (when (equal (string-to-char s) ?*)
6959 ;; Anchor on headlines, post may include tags.
6960 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
6961 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
6962 s (substring s 1)))
6963 (remove-text-properties
6964 0 (length s)
6965 '(face nil mouse-face nil keymap nil fontified nil) s)
6966 ;; Make a series of regular expressions to find a match
6967 (setq words (org-split-string s "[ \n\r\t]+")
6969 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
6970 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
6971 "\\)" markers)
6972 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
6973 re2a (concat "[ \t\r\n]" re2a_)
6974 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
6975 re4 (concat "[^a-zA-Z_]" re4_)
6977 re1 (concat pre re2 post)
6978 re3 (concat pre (if pre re4_ re4) post)
6979 re5 (concat pre ".*" re4)
6980 re2 (concat pre re2)
6981 re2a (concat pre (if pre re2a_ re2a))
6982 re4 (concat pre (if pre re4_ re4))
6983 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
6984 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
6985 re5 "\\)"
6987 (cond
6988 ((eq type 'org-occur) (org-occur reall))
6989 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
6990 (t (goto-char (point-min))
6991 (setq type 'fuzzy)
6992 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
6993 (org-search-not-self 1 re1 nil t)
6994 (org-search-not-self 1 re2 nil t)
6995 (org-search-not-self 1 re2a nil t)
6996 (org-search-not-self 1 re3 nil t)
6997 (org-search-not-self 1 re4 nil t)
6998 (org-search-not-self 1 re5 nil t)
7000 (goto-char (match-beginning 1))
7001 (goto-char pos)
7002 (error "No match")))))
7004 ;; Normal string-search
7005 (goto-char (point-min))
7006 (if (search-forward s nil t)
7007 (goto-char (match-beginning 0))
7008 (error "No match"))))
7009 (and (org-mode-p) (org-show-context 'link-search))
7010 type))
7012 (defun org-search-not-self (group &rest args)
7013 "Execute `re-search-forward', but only accept matches that do not
7014 enclose the position of `org-open-link-marker'."
7015 (let ((m org-open-link-marker))
7016 (catch 'exit
7017 (while (apply 're-search-forward args)
7018 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
7019 (goto-char (match-end group))
7020 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
7021 (> (match-beginning 0) (marker-position m))
7022 (< (match-end 0) (marker-position m)))
7023 (save-match-data
7024 (or (not (org-in-regexp
7025 org-bracket-link-analytic-regexp 1))
7026 (not (match-end 4)) ; no description
7027 (and (<= (match-beginning 4) (point))
7028 (>= (match-end 4) (point))))))
7029 (throw 'exit (point))))))))
7031 (defun org-get-buffer-for-internal-link (buffer)
7032 "Return a buffer to be used for displaying the link target of internal links."
7033 (cond
7034 ((not org-display-internal-link-with-indirect-buffer)
7035 buffer)
7036 ((string-match "(Clone)$" (buffer-name buffer))
7037 (message "Buffer is already a clone, not making another one")
7038 ;; we also do not modify visibility in this case
7039 buffer)
7040 (t ; make a new indirect buffer for displaying the link
7041 (let* ((bn (buffer-name buffer))
7042 (ibn (concat bn "(Clone)"))
7043 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
7044 (with-current-buffer ib (org-overview))
7045 ib))))
7047 (defun org-do-occur (regexp &optional cleanup)
7048 "Call the Emacs command `occur'.
7049 If CLEANUP is non-nil, remove the printout of the regular expression
7050 in the *Occur* buffer. This is useful if the regex is long and not useful
7051 to read."
7052 (occur regexp)
7053 (when cleanup
7054 (let ((cwin (selected-window)) win beg end)
7055 (when (setq win (get-buffer-window "*Occur*"))
7056 (select-window win))
7057 (goto-char (point-min))
7058 (when (re-search-forward "match[a-z]+" nil t)
7059 (setq beg (match-end 0))
7060 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7061 (setq end (1- (match-beginning 0)))))
7062 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
7063 (goto-char (point-min))
7064 (select-window cwin))))
7066 ;;; The mark ring for links jumps
7068 (defvar org-mark-ring nil
7069 "Mark ring for positions before jumps in Org-mode.")
7070 (defvar org-mark-ring-last-goto nil
7071 "Last position in the mark ring used to go back.")
7072 ;; Fill and close the ring
7073 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7074 (loop for i from 1 to org-mark-ring-length do
7075 (push (make-marker) org-mark-ring))
7076 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7077 org-mark-ring)
7079 (defun org-mark-ring-push (&optional pos buffer)
7080 "Put the current position or POS into the mark ring and rotate it."
7081 (interactive)
7082 (setq pos (or pos (point)))
7083 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7084 (move-marker (car org-mark-ring)
7085 (or pos (point))
7086 (or buffer (current-buffer)))
7087 (message "%s"
7088 (substitute-command-keys
7089 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7091 (defun org-mark-ring-goto (&optional n)
7092 "Jump to the previous position in the mark ring.
7093 With prefix arg N, jump back that many stored positions. When
7094 called several times in succession, walk through the entire ring.
7095 Org-mode commands jumping to a different position in the current file,
7096 or to another Org-mode file, automatically push the old position
7097 onto the ring."
7098 (interactive "p")
7099 (let (p m)
7100 (if (eq last-command this-command)
7101 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7102 (setq p org-mark-ring))
7103 (setq org-mark-ring-last-goto p)
7104 (setq m (car p))
7105 (switch-to-buffer (marker-buffer m))
7106 (goto-char m)
7107 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
7109 (defun org-remove-angle-brackets (s)
7110 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7111 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7113 (defun org-add-angle-brackets (s)
7114 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7115 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7117 (defun org-remove-double-quotes (s)
7118 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
7119 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
7122 ;;; Following specific links
7124 (defun org-follow-timestamp-link ()
7125 (cond
7126 ((org-at-date-range-p t)
7127 (let ((org-agenda-start-on-weekday)
7128 (t1 (match-string 1))
7129 (t2 (match-string 2)))
7130 (setq t1 (time-to-days (org-time-string-to-time t1))
7131 t2 (time-to-days (org-time-string-to-time t2)))
7132 (org-agenda-list nil t1 (1+ (- t2 t1)))))
7133 ((org-at-timestamp-p t)
7134 (org-agenda-list nil (time-to-days (org-time-string-to-time
7135 (substring (match-string 1) 0 10)))
7137 (t (error "This should not happen"))))
7140 ;;; Following file links
7141 (defvar org-wait nil)
7142 (defun org-open-file (path &optional in-emacs line search)
7143 "Open the file at PATH.
7144 First, this expands any special file name abbreviations. Then the
7145 configuration variable `org-file-apps' is checked if it contains an
7146 entry for this file type, and if yes, the corresponding command is launched.
7148 If no application is found, Emacs simply visits the file.
7150 With optional prefix argument IN-EMACS, Emacs will visit the file.
7151 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
7152 and o use an external application to visit the file.
7154 Optional LINE specifies a line to go to, optional SEARCH a string to
7155 search for. If LINE or SEARCH is given, the file will always be
7156 opened in Emacs.
7157 If the file does not exist, an error is thrown."
7158 (setq in-emacs (or in-emacs line search))
7159 (let* ((file (if (equal path "")
7160 buffer-file-name
7161 (substitute-in-file-name (expand-file-name path))))
7162 (apps (append org-file-apps (org-default-apps)))
7163 (remp (and (assq 'remote apps) (org-file-remote-p file)))
7164 (dirp (if remp nil (file-directory-p file)))
7165 (file (if (and dirp org-open-directory-means-index-dot-org)
7166 (concat (file-name-as-directory file) "index.org")
7167 file))
7168 (a-m-a-p (assq 'auto-mode apps))
7169 (dfile (downcase file))
7170 (old-buffer (current-buffer))
7171 (old-pos (point))
7172 (old-mode major-mode)
7173 ext cmd)
7174 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7175 (setq ext (match-string 1 dfile))
7176 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7177 (setq ext (match-string 1 dfile))))
7178 (cond
7179 ((equal in-emacs '(16))
7180 (setq cmd (cdr (assoc 'system apps))))
7181 (in-emacs (setq cmd 'emacs))
7183 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
7184 (and dirp (cdr (assoc 'directory apps)))
7185 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
7186 'string-match)
7187 (cdr (assoc ext apps))
7188 (cdr (assoc t apps))))))
7189 (when (eq cmd 'system)
7190 (setq cmd (cdr (assoc 'system apps))))
7191 (when (eq cmd 'default)
7192 (setq cmd (cdr (assoc t apps))))
7193 (when (eq cmd 'mailcap)
7194 (require 'mailcap)
7195 (mailcap-parse-mailcaps)
7196 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7197 (command (mailcap-mime-info mime-type)))
7198 (if (stringp command)
7199 (setq cmd command)
7200 (setq cmd 'emacs))))
7201 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
7202 (not (file-exists-p file))
7203 (not org-open-non-existing-files))
7204 (error "No such file: %s" file))
7205 (cond
7206 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7207 ;; Remove quotes around the file name - we'll use shell-quote-argument.
7208 (while (string-match "['\"]%s['\"]" cmd)
7209 (setq cmd (replace-match "%s" t t cmd)))
7210 (while (string-match "%s" cmd)
7211 (setq cmd (replace-match
7212 (save-match-data
7213 (shell-quote-argument
7214 (convert-standard-filename file)))
7215 t t cmd)))
7216 (save-window-excursion
7217 (start-process-shell-command cmd nil cmd)
7218 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
7220 ((or (stringp cmd)
7221 (eq cmd 'emacs))
7222 (funcall (cdr (assq 'file org-link-frame-setup)) file)
7223 (widen)
7224 (if line (goto-line line)
7225 (if search (org-link-search search))))
7226 ((consp cmd)
7227 (let ((file (convert-standard-filename file)))
7228 (eval cmd)))
7229 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7230 (and (org-mode-p) (eq old-mode 'org-mode)
7231 (or (not (equal old-buffer (current-buffer)))
7232 (not (equal old-pos (point))))
7233 (org-mark-ring-push old-pos old-buffer))))
7235 (defun org-default-apps ()
7236 "Return the default applications for this operating system."
7237 (cond
7238 ((eq system-type 'darwin)
7239 org-file-apps-defaults-macosx)
7240 ((eq system-type 'windows-nt)
7241 org-file-apps-defaults-windowsnt)
7242 (t org-file-apps-defaults-gnu)))
7244 (defun org-apps-regexp-alist (list &optional add-auto-mode)
7245 "Convert extensions to regular expressions in the cars of LIST.
7246 Also, weed out any non-string entries, because the return value is used
7247 only for regexp matching.
7248 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
7249 point to the symbol `emacs', indicating that the file should
7250 be opened in Emacs."
7251 (append
7252 (delq nil
7253 (mapcar (lambda (x)
7254 (if (not (stringp (car x)))
7256 (if (string-match "\\W" (car x))
7258 (cons (concat "\\." (car x) "\\'") (cdr x)))))
7259 list))
7260 (if add-auto-mode
7261 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
7263 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
7264 (defun org-file-remote-p (file)
7265 "Test whether FILE specifies a location on a remote system.
7266 Return non-nil if the location is indeed remote.
7268 For example, the filename \"/user@host:/foo\" specifies a location
7269 on the system \"/user@host:\"."
7270 (cond ((fboundp 'file-remote-p)
7271 (file-remote-p file))
7272 ((fboundp 'tramp-handle-file-remote-p)
7273 (tramp-handle-file-remote-p file))
7274 ((and (boundp 'ange-ftp-name-format)
7275 (string-match (car ange-ftp-name-format) file))
7277 (t nil)))
7280 ;;;; Refiling
7282 (defun org-get-org-file ()
7283 "Read a filename, with default directory `org-directory'."
7284 (let ((default (or org-default-notes-file remember-data-file)))
7285 (read-file-name (format "File name [%s]: " default)
7286 (file-name-as-directory org-directory)
7287 default)))
7289 (defun org-notes-order-reversed-p ()
7290 "Check if the current file should receive notes in reversed order."
7291 (cond
7292 ((not org-reverse-note-order) nil)
7293 ((eq t org-reverse-note-order) t)
7294 ((not (listp org-reverse-note-order)) nil)
7295 (t (catch 'exit
7296 (let ((all org-reverse-note-order)
7297 entry)
7298 (while (setq entry (pop all))
7299 (if (string-match (car entry) buffer-file-name)
7300 (throw 'exit (cdr entry))))
7301 nil)))))
7303 (defvar org-refile-target-table nil
7304 "The list of refile targets, created by `org-refile'.")
7306 (defvar org-agenda-new-buffers nil
7307 "Buffers created to visit agenda files.")
7309 (defun org-get-refile-targets (&optional default-buffer)
7310 "Produce a table with refile targets."
7311 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
7312 targets txt re files f desc descre)
7313 (with-current-buffer (or default-buffer (current-buffer))
7314 (while (setq entry (pop entries))
7315 (setq files (car entry) desc (cdr entry))
7316 (cond
7317 ((null files) (setq files (list (current-buffer))))
7318 ((eq files 'org-agenda-files)
7319 (setq files (org-agenda-files 'unrestricted)))
7320 ((and (symbolp files) (fboundp files))
7321 (setq files (funcall files)))
7322 ((and (symbolp files) (boundp files))
7323 (setq files (symbol-value files))))
7324 (if (stringp files) (setq files (list files)))
7325 (cond
7326 ((eq (car desc) :tag)
7327 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
7328 ((eq (car desc) :todo)
7329 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
7330 ((eq (car desc) :regexp)
7331 (setq descre (cdr desc)))
7332 ((eq (car desc) :level)
7333 (setq descre (concat "^\\*\\{" (number-to-string
7334 (if org-odd-levels-only
7335 (1- (* 2 (cdr desc)))
7336 (cdr desc)))
7337 "\\}[ \t]")))
7338 ((eq (car desc) :maxlevel)
7339 (setq descre (concat "^\\*\\{1," (number-to-string
7340 (if org-odd-levels-only
7341 (1- (* 2 (cdr desc)))
7342 (cdr desc)))
7343 "\\}[ \t]")))
7344 (t (error "Bad refiling target description %s" desc)))
7345 (while (setq f (pop files))
7346 (save-excursion
7347 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
7348 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
7349 (save-excursion
7350 (save-restriction
7351 (widen)
7352 (goto-char (point-min))
7353 (while (re-search-forward descre nil t)
7354 (goto-char (point-at-bol))
7355 (when (looking-at org-complex-heading-regexp)
7356 (setq txt (org-link-display-format (match-string 4))
7357 re (concat "^" (regexp-quote
7358 (buffer-substring (match-beginning 1)
7359 (match-end 4)))))
7360 (if (match-end 5) (setq re (concat re "[ \t]+"
7361 (regexp-quote
7362 (match-string 5)))))
7363 (setq re (concat re "[ \t]*$"))
7364 (when org-refile-use-outline-path
7365 (setq txt (mapconcat 'org-protect-slash
7366 (append
7367 (if (eq org-refile-use-outline-path 'file)
7368 (list (file-name-nondirectory
7369 (buffer-file-name (buffer-base-buffer))))
7370 (if (eq org-refile-use-outline-path 'full-file-path)
7371 (list (buffer-file-name (buffer-base-buffer)))))
7372 (org-get-outline-path)
7373 (list txt))
7374 "/")))
7375 (push (list txt f re (point)) targets))
7376 (goto-char (point-at-eol))))))))
7377 (nreverse targets))))
7379 (defun org-protect-slash (s)
7380 (while (string-match "/" s)
7381 (setq s (replace-match "\\" t t s)))
7384 (defun org-get-outline-path ()
7385 "Return the outline path to the current entry, as a list."
7386 (let (rtn)
7387 (save-excursion
7388 (while (org-up-heading-safe)
7389 (when (looking-at org-complex-heading-regexp)
7390 (push (org-match-string-no-properties 4) rtn)))
7391 rtn)))
7393 (defvar org-refile-history nil
7394 "History for refiling operations.")
7396 (defun org-refile (&optional goto default-buffer)
7397 "Move the entry at point to another heading.
7398 The list of target headings is compiled using the information in
7399 `org-refile-targets', which see. This list is created before each use
7400 and will therefore always be up-to-date.
7402 At the target location, the entry is filed as a subitem of the target heading.
7403 Depending on `org-reverse-note-order', the new subitem will either be the
7404 first or the last subitem.
7406 If there is an active region, all entries in that region will be moved.
7407 However, the region must fulfil the requirement that the first heading
7408 is the first one sets the top-level of the moved text - at most siblings
7409 below it are allowed.
7411 With prefix arg GOTO, the command will only visit the target location,
7412 not actually move anything.
7413 With a double prefix `C-u C-u', go to the location where the last refiling
7414 operation has put the subtree."
7415 (interactive "P")
7416 (let* ((cbuf (current-buffer))
7417 (regionp (org-region-active-p))
7418 (region-start (and regionp (region-beginning)))
7419 (region-end (and regionp (region-end)))
7420 (region-length (and regionp (- region-end region-start)))
7421 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7422 pos it nbuf file re level reversed)
7423 (when regionp (goto-char region-start)
7424 (unless (org-kill-is-subtree-p
7425 (buffer-substring region-start region-end))
7426 (error "The region is not a (sequence of) subtree(s)")))
7427 (if (equal goto '(16))
7428 (org-refile-goto-last-stored)
7429 (when (setq it (org-refile-get-location
7430 (if goto "Goto: " "Refile to: ") default-buffer))
7431 (setq file (nth 1 it)
7432 re (nth 2 it)
7433 pos (nth 3 it))
7434 (setq nbuf (or (find-buffer-visiting file)
7435 (find-file-noselect file)))
7436 (if goto
7437 (progn
7438 (switch-to-buffer nbuf)
7439 (goto-char pos)
7440 (org-show-context 'org-goto))
7441 (if regionp
7442 (progn
7443 (kill-new (buffer-substring region-start region-end))
7444 (org-save-markers-in-region region-start region-end))
7445 (org-copy-subtree 1 nil t))
7446 (save-excursion
7447 (set-buffer (setq nbuf (or (find-buffer-visiting file)
7448 (find-file-noselect file))))
7449 (setq reversed (org-notes-order-reversed-p))
7450 (save-excursion
7451 (save-restriction
7452 (widen)
7453 (goto-char pos)
7454 (looking-at outline-regexp)
7455 (setq level (org-get-valid-level (funcall outline-level) 1))
7456 (goto-char
7457 (if reversed
7458 (or (outline-next-heading) (point-max))
7459 (or (save-excursion (outline-get-next-sibling))
7460 (org-end-of-subtree t t)
7461 (point-max))))
7462 (if (not (bolp)) (newline))
7463 (bookmark-set "org-refile-last-stored")
7464 (org-paste-subtree level))))
7465 (if regionp
7466 (delete-region (point) (+ (point) region-length))
7467 (org-cut-subtree))
7468 (setq org-markers-to-move nil)
7469 (message "Refiled to \"%s\"" (car it)))))))
7471 (defun org-refile-goto-last-stored ()
7472 "Go to the location where the last refile was stored."
7473 (interactive)
7474 (bookmark-jump "org-refile-last-stored")
7475 (message "This is the location of the last refile"))
7477 (defun org-refile-get-location (&optional prompt default-buffer)
7478 "Prompt the user for a refile location, using PROMPT."
7479 (let ((org-refile-targets org-refile-targets)
7480 (org-refile-use-outline-path org-refile-use-outline-path))
7481 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
7482 (unless org-refile-target-table
7483 (error "No refile targets"))
7484 (let* ((cbuf (current-buffer))
7485 (cfunc (if org-refile-use-outline-path
7486 'org-olpath-completing-read
7487 'completing-read))
7488 (extra (if org-refile-use-outline-path "/" ""))
7489 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7490 (fname (and filename (file-truename filename)))
7491 (tbl (mapcar
7492 (lambda (x)
7493 (if (not (equal fname (file-truename (nth 1 x))))
7494 (cons (concat (car x) extra " ("
7495 (file-name-nondirectory (nth 1 x)) ")")
7496 (cdr x))
7497 (cons (concat (car x) extra) (cdr x))))
7498 org-refile-target-table))
7499 (completion-ignore-case t))
7500 (assoc (funcall cfunc prompt tbl nil t nil 'org-refile-history)
7501 tbl)))
7503 (defun org-olpath-completing-read (prompt collection &rest args)
7504 "Read an outline path like a file name."
7505 (let ((thetable collection))
7506 (apply
7507 'completing-read prompt
7508 (lambda (string predicate &optional flag)
7509 (let (rtn r s f (l (length string)))
7510 (cond
7511 ((eq flag nil)
7512 ;; try completion
7513 (try-completion string thetable))
7514 ((eq flag t)
7515 ;; all-completions
7516 (setq rtn (all-completions string thetable predicate))
7517 (mapcar
7518 (lambda (x)
7519 (setq r (substring x l))
7520 (if (string-match " ([^)]*)$" x)
7521 (setq f (match-string 0 x))
7522 (setq f ""))
7523 (if (string-match "/" r)
7524 (concat string (substring r 0 (match-end 0)) f)
7526 rtn))
7527 ((eq flag 'lambda)
7528 ;; exact match?
7529 (assoc string thetable)))
7531 args)))
7533 ;;;; Dynamic blocks
7535 (defun org-find-dblock (name)
7536 "Find the first dynamic block with name NAME in the buffer.
7537 If not found, stay at current position and return nil."
7538 (let (pos)
7539 (save-excursion
7540 (goto-char (point-min))
7541 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
7542 nil t)
7543 (match-beginning 0))))
7544 (if pos (goto-char pos))
7545 pos))
7547 (defconst org-dblock-start-re
7548 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
7549 "Matches the startline of a dynamic block, with parameters.")
7551 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
7552 "Matches the end of a dyhamic block.")
7554 (defun org-create-dblock (plist)
7555 "Create a dynamic block section, with parameters taken from PLIST.
7556 PLIST must containe a :name entry which is used as name of the block."
7557 (unless (bolp) (newline))
7558 (let ((name (plist-get plist :name)))
7559 (insert "#+BEGIN: " name)
7560 (while plist
7561 (if (eq (car plist) :name)
7562 (setq plist (cddr plist))
7563 (insert " " (prin1-to-string (pop plist)))))
7564 (insert "\n\n#+END:\n")
7565 (beginning-of-line -2)))
7567 (defun org-prepare-dblock ()
7568 "Prepare dynamic block for refresh.
7569 This empties the block, puts the cursor at the insert position and returns
7570 the property list including an extra property :name with the block name."
7571 (unless (looking-at org-dblock-start-re)
7572 (error "Not at a dynamic block"))
7573 (let* ((begdel (1+ (match-end 0)))
7574 (name (org-no-properties (match-string 1)))
7575 (params (append (list :name name)
7576 (read (concat "(" (match-string 3) ")")))))
7577 (unless (re-search-forward org-dblock-end-re nil t)
7578 (error "Dynamic block not terminated"))
7579 (setq params
7580 (append params
7581 (list :content (buffer-substring
7582 begdel (match-beginning 0)))))
7583 (delete-region begdel (match-beginning 0))
7584 (goto-char begdel)
7585 (open-line 1)
7586 params))
7588 (defun org-map-dblocks (&optional command)
7589 "Apply COMMAND to all dynamic blocks in the current buffer.
7590 If COMMAND is not given, use `org-update-dblock'."
7591 (let ((cmd (or command 'org-update-dblock))
7592 pos)
7593 (save-excursion
7594 (goto-char (point-min))
7595 (while (re-search-forward org-dblock-start-re nil t)
7596 (goto-char (setq pos (match-beginning 0)))
7597 (condition-case nil
7598 (funcall cmd)
7599 (error (message "Error during update of dynamic block")))
7600 (goto-char pos)
7601 (unless (re-search-forward org-dblock-end-re nil t)
7602 (error "Dynamic block not terminated"))))))
7604 (defun org-dblock-update (&optional arg)
7605 "User command for updating dynamic blocks.
7606 Update the dynamic block at point. With prefix ARG, update all dynamic
7607 blocks in the buffer."
7608 (interactive "P")
7609 (if arg
7610 (org-update-all-dblocks)
7611 (or (looking-at org-dblock-start-re)
7612 (org-beginning-of-dblock))
7613 (org-update-dblock)))
7615 (defun org-update-dblock ()
7616 "Update the dynamic block at point
7617 This means to empty the block, parse for parameters and then call
7618 the correct writing function."
7619 (save-window-excursion
7620 (let* ((pos (point))
7621 (line (org-current-line))
7622 (params (org-prepare-dblock))
7623 (name (plist-get params :name))
7624 (cmd (intern (concat "org-dblock-write:" name))))
7625 (message "Updating dynamic block `%s' at line %d..." name line)
7626 (funcall cmd params)
7627 (message "Updating dynamic block `%s' at line %d...done" name line)
7628 (goto-char pos))))
7630 (defun org-beginning-of-dblock ()
7631 "Find the beginning of the dynamic block at point.
7632 Error if there is no scuh block at point."
7633 (let ((pos (point))
7634 beg)
7635 (end-of-line 1)
7636 (if (and (re-search-backward org-dblock-start-re nil t)
7637 (setq beg (match-beginning 0))
7638 (re-search-forward org-dblock-end-re nil t)
7639 (> (match-end 0) pos))
7640 (goto-char beg)
7641 (goto-char pos)
7642 (error "Not in a dynamic block"))))
7644 (defun org-update-all-dblocks ()
7645 "Update all dynamic blocks in the buffer.
7646 This function can be used in a hook."
7647 (when (org-mode-p)
7648 (org-map-dblocks 'org-update-dblock)))
7651 ;;;; Completion
7653 (defconst org-additional-option-like-keywords
7654 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
7655 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
7656 "BEGIN_EXAMPLE" "END_EXAMPLE"
7657 "BEGIN_QUOTE" "END_QUOTE"
7658 "BEGIN_VERSE" "END_VERSE"
7659 "BEGIN_SRC" "END_SRC"))
7661 (defcustom org-structure-template-alist
7663 ("s" "#+begin_src ?\n\n#+end_src"
7664 "<src lang=\"?\">\n\n</src>")
7665 ("e" "#+begin_example\n?\n#+end_example"
7666 "<example>\n?\n</example>")
7667 ("q" "#+begin_quote\n?\n#+end_quote"
7668 "<quote>\n?\n</quote>")
7669 ("v" "#+begin_verse\n?\n#+end_verse"
7670 "<verse>\n?\n/verse>")
7671 ("l" "#+begin_latex\n?\n#+end_latex"
7672 "<literal style=\"latex\">\n?\n</literal>")
7673 ("L" "#+latex: "
7674 "<literal style=\"latex\">?</literal>")
7675 ("h" "#+begin_html\n?\n#+end_html"
7676 "<literal style=\"html\">\n?\n</literal>")
7677 ("H" "#+html: "
7678 "<literal style=\"html\">?</literal>")
7679 ("a" "#+begin_ascii\n?\n#+end_ascii")
7680 ("A" "#+ascii: ")
7681 ("i" "#+include %file ?"
7682 "<include file=%file markup=\"?\">")
7684 "Structure completion elements.
7685 This is a list of abbreviation keys and values. The value gets inserted
7686 it you type @samp{.} followed by the key and then the completion key,
7687 usually `M-TAB'. %file will be replaced by a file name after prompting
7688 for the file uning completion.
7689 There are two templates for each key, the first uses the original Org syntax,
7690 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
7691 the default when the /org-mtags.el/ module has been loaded. See also the
7692 variable `org-mtags-prefere-muse-templates'.
7693 This is an experimental feature, it is undecided if it is going to stay in."
7694 :group 'org-completion
7695 :type '(repeat
7696 (string :tag "Key")
7697 (string :tag "Template")
7698 (string :tag "Muse Template")))
7700 (defun org-try-structure-completion ()
7701 "Try to complete a structure template before point.
7702 This looks for strings like \"<e\" on an otherwise empty line and
7703 expands them."
7704 (let ((l (buffer-substring (point-at-bol) (point)))
7706 (when (and (looking-at "[ \t]*$")
7707 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
7708 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
7709 (org-complete-expand-structure-template (+ -1 (point-at-bol)
7710 (match-beginning 1)) a)
7711 t)))
7713 (defun org-complete-expand-structure-template (start cell)
7714 "Expand a structure template."
7715 (let* ((musep (org-bound-and-true-p org-mtags-prefere-muse-templates))
7716 (rpl (nth (if musep 2 1) cell)))
7717 (delete-region start (point))
7718 (when (string-match "\\`#\\+" rpl)
7719 (cond
7720 ((bolp))
7721 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
7722 (delete-region (point-at-bol) (point)))
7723 (t (newline))))
7724 (setq start (point))
7725 (if (string-match "%file" rpl)
7726 (setq rpl (replace-match
7727 (concat
7728 "\""
7729 (save-match-data
7730 (abbreviate-file-name (read-file-name "Include file: ")))
7731 "\"")
7732 t t rpl)))
7733 (insert rpl)
7734 (if (re-search-backward "\\?" start t) (delete-char 1))))
7737 (defun org-complete (&optional arg)
7738 "Perform completion on word at point.
7739 At the beginning of a headline, this completes TODO keywords as given in
7740 `org-todo-keywords'.
7741 If the current word is preceded by a backslash, completes the TeX symbols
7742 that are supported for HTML support.
7743 If the current word is preceded by \"#+\", completes special words for
7744 setting file options.
7745 In the line after \"#+STARTUP:, complete valid keywords.\"
7746 At all other locations, this simply calls the value of
7747 `org-completion-fallback-command'."
7748 (interactive "P")
7749 (org-without-partial-completion
7750 (catch 'exit
7751 (let* ((a nil)
7752 (end (point))
7753 (beg1 (save-excursion
7754 (skip-chars-backward (org-re "[:alnum:]_@"))
7755 (point)))
7756 (beg (save-excursion
7757 (skip-chars-backward "a-zA-Z0-9_:$")
7758 (point)))
7759 (confirm (lambda (x) (stringp (car x))))
7760 (searchhead (equal (char-before beg) ?*))
7761 (struct
7762 (when (and (member (char-before beg1) '(?. ?<))
7763 (setq a (assoc (buffer-substring beg1 (point))
7764 org-structure-template-alist)))
7765 (org-complete-expand-structure-template (1- beg1) a)
7766 (throw 'exit t)))
7767 (tag (and (equal (char-before beg1) ?:)
7768 (equal (char-after (point-at-bol)) ?*)))
7769 (prop (and (equal (char-before beg1) ?:)
7770 (not (equal (char-after (point-at-bol)) ?*))))
7771 (texp (equal (char-before beg) ?\\))
7772 (link (equal (char-before beg) ?\[))
7773 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
7774 beg)
7775 "#+"))
7776 (startup (string-match "^#\\+STARTUP:.*"
7777 (buffer-substring (point-at-bol) (point))))
7778 (completion-ignore-case opt)
7779 (type nil)
7780 (tbl nil)
7781 (table (cond
7782 (opt
7783 (setq type :opt)
7784 (require 'org-exp)
7785 (append
7786 (mapcar
7787 (lambda (x)
7788 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
7789 (cons (match-string 2 x) (match-string 1 x)))
7790 (org-split-string (org-get-current-options) "\n"))
7791 (mapcar 'list org-additional-option-like-keywords)))
7792 (startup
7793 (setq type :startup)
7794 org-startup-options)
7795 (link (append org-link-abbrev-alist-local
7796 org-link-abbrev-alist))
7797 (texp
7798 (setq type :tex)
7799 org-html-entities)
7800 ((string-match "\\`\\*+[ \t]+\\'"
7801 (buffer-substring (point-at-bol) beg))
7802 (setq type :todo)
7803 (mapcar 'list org-todo-keywords-1))
7804 (searchhead
7805 (setq type :searchhead)
7806 (save-excursion
7807 (goto-char (point-min))
7808 (while (re-search-forward org-todo-line-regexp nil t)
7809 (push (list
7810 (org-make-org-heading-search-string
7811 (match-string 3) t))
7812 tbl)))
7813 tbl)
7814 (tag (setq type :tag beg beg1)
7815 (or org-tag-alist (org-get-buffer-tags)))
7816 (prop (setq type :prop beg beg1)
7817 (mapcar 'list (org-buffer-property-keys nil t t)))
7818 (t (progn
7819 (call-interactively org-completion-fallback-command)
7820 (throw 'exit nil)))))
7821 (pattern (buffer-substring-no-properties beg end))
7822 (completion (try-completion pattern table confirm)))
7823 (cond ((eq completion t)
7824 (if (not (assoc (upcase pattern) table))
7825 (message "Already complete")
7826 (if (and (equal type :opt)
7827 (not (member (car (assoc (upcase pattern) table))
7828 org-additional-option-like-keywords)))
7829 (insert (substring (cdr (assoc (upcase pattern) table))
7830 (length pattern)))
7831 (if (memq type '(:tag :prop)) (insert ":")))))
7832 ((null completion)
7833 (message "Can't find completion for \"%s\"" pattern)
7834 (ding))
7835 ((not (string= pattern completion))
7836 (delete-region beg end)
7837 (if (string-match " +$" completion)
7838 (setq completion (replace-match "" t t completion)))
7839 (insert completion)
7840 (if (get-buffer-window "*Completions*")
7841 (delete-window (get-buffer-window "*Completions*")))
7842 (if (assoc completion table)
7843 (if (eq type :todo) (insert " ")
7844 (if (memq type '(:tag :prop)) (insert ":"))))
7845 (if (and (equal type :opt) (assoc completion table))
7846 (message "%s" (substitute-command-keys
7847 "Press \\[org-complete] again to insert example settings"))))
7849 (message "Making completion list...")
7850 (let ((list (sort (all-completions pattern table confirm)
7851 'string<)))
7852 (with-output-to-temp-buffer "*Completions*"
7853 (condition-case nil
7854 ;; Protection needed for XEmacs and emacs 21
7855 (display-completion-list list pattern)
7856 (error (display-completion-list list)))))
7857 (message "Making completion list...%s" "done")))))))
7859 ;;;; TODO, DEADLINE, Comments
7861 (defun org-toggle-comment ()
7862 "Change the COMMENT state of an entry."
7863 (interactive)
7864 (save-excursion
7865 (org-back-to-heading)
7866 (let (case-fold-search)
7867 (if (looking-at (concat outline-regexp
7868 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
7869 (replace-match "" t t nil 1)
7870 (if (looking-at outline-regexp)
7871 (progn
7872 (goto-char (match-end 0))
7873 (insert org-comment-string " ")))))))
7875 (defvar org-last-todo-state-is-todo nil
7876 "This is non-nil when the last TODO state change led to a TODO state.
7877 If the last change removed the TODO tag or switched to DONE, then
7878 this is nil.")
7880 (defvar org-setting-tags nil) ; dynamically skiped
7882 (defun org-parse-local-options (string var)
7883 "Parse STRING for startup setting relevant for variable VAR."
7884 (let ((rtn (symbol-value var))
7885 e opts)
7886 (save-match-data
7887 (if (or (not string) (not (string-match "\\S-" string)))
7889 (setq opts (delq nil (mapcar (lambda (x)
7890 (setq e (assoc x org-startup-options))
7891 (if (eq (nth 1 e) var) e nil))
7892 (org-split-string string "[ \t]+"))))
7893 (if (not opts)
7895 (setq rtn nil)
7896 (while (setq e (pop opts))
7897 (if (not (nth 3 e))
7898 (setq rtn (nth 2 e))
7899 (if (not (listp rtn)) (setq rtn nil))
7900 (push (nth 2 e) rtn)))
7901 rtn)))))
7903 (defvar org-blocker-hook nil
7904 "Hook for functions that are allowed to block a state change.
7906 Each function gets as its single argument a property list, see
7907 `org-trigger-hook' for more information about this list.
7909 If any of the functions in this hook returns nil, the state change
7910 is blocked.")
7912 (defvar org-trigger-hook nil
7913 "Hook for functions that are triggered by a state change.
7915 Each function gets as its single argument a property list with at least
7916 the following elements:
7918 (:type type-of-change :position pos-at-entry-start
7919 :from old-state :to new-state)
7921 Depending on the type, more properties may be present.
7923 This mechanism is currently implemented for:
7925 TODO state changes
7926 ------------------
7927 :type todo-state-change
7928 :from previous state (keyword as a string), or nil
7929 :to new state (keyword as a string), or nil")
7931 (defvar org-agenda-headline-snapshot-before-repeat)
7932 (defun org-todo (&optional arg)
7933 "Change the TODO state of an item.
7934 The state of an item is given by a keyword at the start of the heading,
7935 like
7936 *** TODO Write paper
7937 *** DONE Call mom
7939 The different keywords are specified in the variable `org-todo-keywords'.
7940 By default the available states are \"TODO\" and \"DONE\".
7941 So for this example: when the item starts with TODO, it is changed to DONE.
7942 When it starts with DONE, the DONE is removed. And when neither TODO nor
7943 DONE are present, add TODO at the beginning of the heading.
7945 With C-u prefix arg, use completion to determine the new state.
7946 With numeric prefix arg, switch to that state.
7948 For calling through lisp, arg is also interpreted in the following way:
7949 'none -> empty state
7950 \"\"(empty string) -> switch to empty state
7951 'done -> switch to DONE
7952 'nextset -> switch to the next set of keywords
7953 'previousset -> switch to the previous set of keywords
7954 \"WAITING\" -> switch to the specified keyword, but only if it
7955 really is a member of `org-todo-keywords'."
7956 (interactive "P")
7957 (save-excursion
7958 (catch 'exit
7959 (org-back-to-heading)
7960 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
7961 (or (looking-at (concat " +" org-todo-regexp " *"))
7962 (looking-at " *"))
7963 (let* ((match-data (match-data))
7964 (startpos (point-at-bol))
7965 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
7966 (org-log-done org-log-done)
7967 (org-log-repeat org-log-repeat)
7968 (org-todo-log-states org-todo-log-states)
7969 (this (match-string 1))
7970 (hl-pos (match-beginning 0))
7971 (head (org-get-todo-sequence-head this))
7972 (ass (assoc head org-todo-kwd-alist))
7973 (interpret (nth 1 ass))
7974 (done-word (nth 3 ass))
7975 (final-done-word (nth 4 ass))
7976 (last-state (or this ""))
7977 (completion-ignore-case t)
7978 (member (member this org-todo-keywords-1))
7979 (tail (cdr member))
7980 (state (cond
7981 ((and org-todo-key-trigger
7982 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
7983 (and (not arg) org-use-fast-todo-selection
7984 (not (eq org-use-fast-todo-selection 'prefix)))))
7985 ;; Use fast selection
7986 (org-fast-todo-selection))
7987 ((and (equal arg '(4))
7988 (or (not org-use-fast-todo-selection)
7989 (not org-todo-key-trigger)))
7990 ;; Read a state with completion
7991 (completing-read "State: " (mapcar (lambda(x) (list x))
7992 org-todo-keywords-1)
7993 nil t))
7994 ((eq arg 'right)
7995 (if this
7996 (if tail (car tail) nil)
7997 (car org-todo-keywords-1)))
7998 ((eq arg 'left)
7999 (if (equal member org-todo-keywords-1)
8001 (if this
8002 (nth (- (length org-todo-keywords-1) (length tail) 2)
8003 org-todo-keywords-1)
8004 (org-last org-todo-keywords-1))))
8005 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
8006 (setq arg nil))) ; hack to fall back to cycling
8007 (arg
8008 ;; user or caller requests a specific state
8009 (cond
8010 ((equal arg "") nil)
8011 ((eq arg 'none) nil)
8012 ((eq arg 'done) (or done-word (car org-done-keywords)))
8013 ((eq arg 'nextset)
8014 (or (car (cdr (member head org-todo-heads)))
8015 (car org-todo-heads)))
8016 ((eq arg 'previousset)
8017 (let ((org-todo-heads (reverse org-todo-heads)))
8018 (or (car (cdr (member head org-todo-heads)))
8019 (car org-todo-heads))))
8020 ((car (member arg org-todo-keywords-1)))
8021 ((nth (1- (prefix-numeric-value arg))
8022 org-todo-keywords-1))))
8023 ((null member) (or head (car org-todo-keywords-1)))
8024 ((equal this final-done-word) nil) ;; -> make empty
8025 ((null tail) nil) ;; -> first entry
8026 ((eq interpret 'sequence)
8027 (car tail))
8028 ((memq interpret '(type priority))
8029 (if (eq this-command last-command)
8030 (car tail)
8031 (if (> (length tail) 0)
8032 (or done-word (car org-done-keywords))
8033 nil)))
8034 (t nil)))
8035 (next (if state (concat " " state " ") " "))
8036 (change-plist (list :type 'todo-state-change :from this :to state
8037 :position startpos))
8038 dolog now-done-p)
8039 (when org-blocker-hook
8040 (unless (save-excursion
8041 (save-match-data
8042 (run-hook-with-args-until-failure
8043 'org-blocker-hook change-plist)))
8044 (if (interactive-p)
8045 (error "TODO state change from %s to %s blocked" this state)
8046 ;; fail silently
8047 (message "TODO state change from %s to %s blocked" this state)
8048 (throw 'exit nil))))
8049 (store-match-data match-data)
8050 (replace-match next t t)
8051 (unless (pos-visible-in-window-p hl-pos)
8052 (message "TODO state changed to %s" (org-trim next)))
8053 (unless head
8054 (setq head (org-get-todo-sequence-head state)
8055 ass (assoc head org-todo-kwd-alist)
8056 interpret (nth 1 ass)
8057 done-word (nth 3 ass)
8058 final-done-word (nth 4 ass)))
8059 (when (memq arg '(nextset previousset))
8060 (message "Keyword-Set %d/%d: %s"
8061 (- (length org-todo-sets) -1
8062 (length (memq (assoc state org-todo-sets) org-todo-sets)))
8063 (length org-todo-sets)
8064 (mapconcat 'identity (assoc state org-todo-sets) " ")))
8065 (setq org-last-todo-state-is-todo
8066 (not (member state org-done-keywords)))
8067 (setq now-done-p (and (member state org-done-keywords)
8068 (not (member this org-done-keywords))))
8069 (and logging (org-local-logging logging))
8070 (when (and (or org-todo-log-states org-log-done)
8071 (not (memq arg '(nextset previousset))))
8072 ;; we need to look at recording a time and note
8073 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
8074 (nth 2 (assoc this org-todo-log-states))))
8075 (when (and state
8076 (member state org-not-done-keywords)
8077 (not (member this org-not-done-keywords)))
8078 ;; This is now a todo state and was not one before
8079 ;; If there was a CLOSED time stamp, get rid of it.
8080 (org-add-planning-info nil nil 'closed))
8081 (when (and now-done-p org-log-done)
8082 ;; It is now done, and it was not done before
8083 (org-add-planning-info 'closed (org-current-time))
8084 (if (and (not dolog) (eq 'note org-log-done))
8085 (org-add-log-setup 'done state 'findpos 'note)))
8086 (when (and state dolog)
8087 ;; This is a non-nil state, and we need to log it
8088 (org-add-log-setup 'state state 'findpos dolog)))
8089 ;; Fixup tag positioning
8090 (org-todo-trigger-tag-changes state)
8091 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
8092 (when org-provide-todo-statistics
8093 (org-update-parent-todo-statistics))
8094 (run-hooks 'org-after-todo-state-change-hook)
8095 (if (and arg (not (member state org-done-keywords)))
8096 (setq head (org-get-todo-sequence-head state)))
8097 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
8098 ;; Do we need to trigger a repeat?
8099 (when now-done-p
8100 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
8101 ;; This is for the agenda, take a snapshot of the headline.
8102 (save-match-data
8103 (setq org-agenda-headline-snapshot-before-repeat
8104 (org-get-heading))))
8105 (org-auto-repeat-maybe state))
8106 ;; Fixup cursor location if close to the keyword
8107 (if (and (outline-on-heading-p)
8108 (not (bolp))
8109 (save-excursion (beginning-of-line 1)
8110 (looking-at org-todo-line-regexp))
8111 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
8112 (progn
8113 (goto-char (or (match-end 2) (match-end 1)))
8114 (just-one-space)))
8115 (when org-trigger-hook
8116 (save-excursion
8117 (run-hook-with-args 'org-trigger-hook change-plist)))))))
8119 (defun org-update-parent-todo-statistics ()
8120 "Update any statistics cookie in the parent of the current headline."
8121 (interactive)
8122 (let ((box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
8123 level (cnt-all 0) (cnt-done 0) is-percent kwd)
8124 (catch 'exit
8125 (save-excursion
8126 (setq level (org-up-heading-safe))
8127 (unless (and level
8128 (re-search-forward box-re (point-at-eol) t))
8129 (throw 'exit nil))
8130 (setq is-percent (match-end 2))
8131 (save-match-data
8132 (unless (outline-next-heading) (throw 'exit nil))
8133 (while (looking-at org-todo-line-regexp)
8134 (setq kwd (match-string 2))
8135 (and kwd (setq cnt-all (1+ cnt-all)))
8136 (and (member kwd org-done-keywords)
8137 (setq cnt-done (1+ cnt-done)))
8138 (condition-case nil
8139 (org-forward-same-level 1)
8140 (error (end-of-line 1)))))
8141 (replace-match
8142 (if is-percent
8143 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
8144 (format "[%d/%d]" cnt-done cnt-all)))
8145 (run-hook-with-args 'org-after-todo-statistics-hook
8146 cnt-done (- cnt-all cnt-done))))))
8148 (defvar org-after-todo-statistics-hook nil
8149 "Hook that is called after a TODO statistics cookie has been updated.
8150 Each function is called with two arguments: the number of not-done entries
8151 and the number of done entries.
8153 For example, the following function, when added to this hook, will switch
8154 an entry to DONE when all children are done, and back to TODO when new
8155 entries are set to a TODO status. Note that this hook is only called
8156 when there is a statistics cookie in the headline!
8158 (defun org-summary-todo (n-done n-not-done)
8159 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
8160 (let (org-log-done org-log-states) ; turn off logging
8161 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
8164 (defun org-todo-trigger-tag-changes (state)
8165 "Apply the changes defined in `org-todo-state-tags-triggers'."
8166 (let ((l org-todo-state-tags-triggers)
8167 changes)
8168 (when (or (not state) (equal state ""))
8169 (setq changes (append changes (cdr (assoc "" l)))))
8170 (when (and (stringp state) (> (length state) 0))
8171 (setq changes (append changes (cdr (assoc state l)))))
8172 (when (member state org-not-done-keywords)
8173 (setq changes (append changes (cdr (assoc 'todo l)))))
8174 (when (member state org-done-keywords)
8175 (setq changes (append changes (cdr (assoc 'done l)))))
8176 (dolist (c changes)
8177 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
8179 (defun org-local-logging (value)
8180 "Get logging settings from a property VALUE."
8181 (let* (words w a)
8182 ;; directly set the variables, they are already local.
8183 (setq org-log-done nil
8184 org-log-repeat nil
8185 org-todo-log-states nil)
8186 (setq words (org-split-string value))
8187 (while (setq w (pop words))
8188 (cond
8189 ((setq a (assoc w org-startup-options))
8190 (and (member (nth 1 a) '(org-log-done org-log-repeat))
8191 (set (nth 1 a) (nth 2 a))))
8192 ((setq a (org-extract-log-state-settings w))
8193 (and (member (car a) org-todo-keywords-1)
8194 (push a org-todo-log-states)))))))
8196 (defun org-get-todo-sequence-head (kwd)
8197 "Return the head of the TODO sequence to which KWD belongs.
8198 If KWD is not set, check if there is a text property remembering the
8199 right sequence."
8200 (let (p)
8201 (cond
8202 ((not kwd)
8203 (or (get-text-property (point-at-bol) 'org-todo-head)
8204 (progn
8205 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
8206 nil (point-at-eol)))
8207 (get-text-property p 'org-todo-head))))
8208 ((not (member kwd org-todo-keywords-1))
8209 (car org-todo-keywords-1))
8210 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
8212 (defun org-fast-todo-selection ()
8213 "Fast TODO keyword selection with single keys.
8214 Returns the new TODO keyword, or nil if no state change should occur."
8215 (let* ((fulltable org-todo-key-alist)
8216 (done-keywords org-done-keywords) ;; needed for the faces.
8217 (maxlen (apply 'max (mapcar
8218 (lambda (x)
8219 (if (stringp (car x)) (string-width (car x)) 0))
8220 fulltable)))
8221 (expert nil)
8222 (fwidth (+ maxlen 3 1 3))
8223 (ncol (/ (- (window-width) 4) fwidth))
8224 tg cnt e c tbl
8225 groups ingroup)
8226 (save-window-excursion
8227 (if expert
8228 (set-buffer (get-buffer-create " *Org todo*"))
8229 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
8230 (erase-buffer)
8231 (org-set-local 'org-done-keywords done-keywords)
8232 (setq tbl fulltable cnt 0)
8233 (while (setq e (pop tbl))
8234 (cond
8235 ((equal e '(:startgroup))
8236 (push '() groups) (setq ingroup t)
8237 (when (not (= cnt 0))
8238 (setq cnt 0)
8239 (insert "\n"))
8240 (insert "{ "))
8241 ((equal e '(:endgroup))
8242 (setq ingroup nil cnt 0)
8243 (insert "}\n"))
8245 (setq tg (car e) c (cdr e))
8246 (if ingroup (push tg (car groups)))
8247 (setq tg (org-add-props tg nil 'face
8248 (org-get-todo-face tg)))
8249 (if (and (= cnt 0) (not ingroup)) (insert " "))
8250 (insert "[" c "] " tg (make-string
8251 (- fwidth 4 (length tg)) ?\ ))
8252 (when (= (setq cnt (1+ cnt)) ncol)
8253 (insert "\n")
8254 (if ingroup (insert " "))
8255 (setq cnt 0)))))
8256 (insert "\n")
8257 (goto-char (point-min))
8258 (if (not expert) (org-fit-window-to-buffer))
8259 (message "[a-z..]:Set [SPC]:clear")
8260 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
8261 (cond
8262 ((or (= c ?\C-g)
8263 (and (= c ?q) (not (rassoc c fulltable))))
8264 (setq quit-flag t))
8265 ((= c ?\ ) nil)
8266 ((setq e (rassoc c fulltable) tg (car e))
8268 (t (setq quit-flag t))))))
8270 (defun org-entry-is-todo-p ()
8271 (member (org-get-todo-state) org-not-done-keywords))
8273 (defun org-entry-is-done-p ()
8274 (member (org-get-todo-state) org-done-keywords))
8276 (defun org-get-todo-state ()
8277 (save-excursion
8278 (org-back-to-heading t)
8279 (and (looking-at org-todo-line-regexp)
8280 (match-end 2)
8281 (match-string 2))))
8283 (defun org-at-date-range-p (&optional inactive-ok)
8284 "Is the cursor inside a date range?"
8285 (interactive)
8286 (save-excursion
8287 (catch 'exit
8288 (let ((pos (point)))
8289 (skip-chars-backward "^[<\r\n")
8290 (skip-chars-backward "<[")
8291 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8292 (>= (match-end 0) pos)
8293 (throw 'exit t))
8294 (skip-chars-backward "^<[\r\n")
8295 (skip-chars-backward "<[")
8296 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8297 (>= (match-end 0) pos)
8298 (throw 'exit t)))
8299 nil)))
8301 (defun org-get-repeat ()
8302 "Check if there is a deadline/schedule with repeater in this entry."
8303 (save-match-data
8304 (save-excursion
8305 (org-back-to-heading t)
8306 (if (re-search-forward
8307 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
8308 (match-string 1)))))
8310 (defvar org-last-changed-timestamp)
8311 (defvar org-last-inserted-timestamp)
8312 (defvar org-log-post-message)
8313 (defvar org-log-note-purpose)
8314 (defvar org-log-note-how)
8315 (defvar org-log-note-extra)
8316 (defun org-auto-repeat-maybe (done-word)
8317 "Check if the current headline contains a repeated deadline/schedule.
8318 If yes, set TODO state back to what it was and change the base date
8319 of repeating deadline/scheduled time stamps to new date.
8320 This function is run automatically after each state change to a DONE state."
8321 ;; last-state is dynamically scoped into this function
8322 (let* ((repeat (org-get-repeat))
8323 (aa (assoc last-state org-todo-kwd-alist))
8324 (interpret (nth 1 aa))
8325 (head (nth 2 aa))
8326 (whata '(("d" . day) ("m" . month) ("y" . year)))
8327 (msg "Entry repeats: ")
8328 (org-log-done nil)
8329 (org-todo-log-states nil)
8330 (nshiftmax 10) (nshift 0)
8331 re type n what ts mb0 time)
8332 (when repeat
8333 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
8334 (org-todo (if (eq interpret 'type) last-state head))
8335 (when org-log-repeat
8336 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
8337 (memq 'org-add-log-note post-command-hook))
8338 ;; OK, we are already setup for some record
8339 (if (eq org-log-repeat 'note)
8340 ;; make sure we take a note, not only a time stamp
8341 (setq org-log-note-how 'note))
8342 ;; Set up for taking a record
8343 (org-add-log-setup 'state (or done-word (car org-done-keywords))
8344 'findpos org-log-repeat)))
8345 (org-back-to-heading t)
8346 (org-add-planning-info nil nil 'closed)
8347 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
8348 org-deadline-time-regexp "\\)\\|\\("
8349 org-ts-regexp "\\)"))
8350 (while (re-search-forward
8351 re (save-excursion (outline-next-heading) (point)) t)
8352 (setq type (if (match-end 1) org-scheduled-string
8353 (if (match-end 3) org-deadline-string "Plain:"))
8354 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0)))
8355 mb0 (match-beginning 0))
8356 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
8357 (setq n (string-to-number (match-string 2 ts))
8358 what (match-string 3 ts))
8359 (if (equal what "w") (setq n (* n 7) what "d"))
8360 ;; Preparation, see if we need to modify the start date for the change
8361 (when (match-end 1)
8362 (setq time (save-match-data (org-time-string-to-time ts)))
8363 (cond
8364 ((equal (match-string 1 ts) ".")
8365 ;; Shift starting date to today
8366 (org-timestamp-change
8367 (- (time-to-days (current-time)) (time-to-days time))
8368 'day))
8369 ((equal (match-string 1 ts) "+")
8370 (while (or (= nshift 0)
8371 (<= (time-to-days time) (time-to-days (current-time))))
8372 (when (= (incf nshift) nshiftmax)
8373 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
8374 (error "Abort")))
8375 (org-timestamp-change n (cdr (assoc what whata)))
8376 (org-at-timestamp-p t)
8377 (setq ts (match-string 1))
8378 (setq time (save-match-data (org-time-string-to-time ts))))
8379 (org-timestamp-change (- n) (cdr (assoc what whata)))
8380 ;; rematch, so that we have everything in place for the real shift
8381 (org-at-timestamp-p t)
8382 (setq ts (match-string 1))
8383 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
8384 (org-timestamp-change n (cdr (assoc what whata)))
8385 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
8386 (setq org-log-post-message msg)
8387 (message "%s" msg))))
8389 (defun org-show-todo-tree (arg)
8390 "Make a compact tree which shows all headlines marked with TODO.
8391 The tree will show the lines where the regexp matches, and all higher
8392 headlines above the match.
8393 With a \\[universal-argument] prefix, also show the DONE entries.
8394 With a numeric prefix N, construct a sparse tree for the Nth element
8395 of `org-todo-keywords-1'."
8396 (interactive "P")
8397 (let ((case-fold-search nil)
8398 (kwd-re
8399 (cond ((null arg) org-not-done-regexp)
8400 ((equal arg '(4))
8401 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
8402 (mapcar 'list org-todo-keywords-1))))
8403 (concat "\\("
8404 (mapconcat 'identity (org-split-string kwd "|") "\\|")
8405 "\\)\\>")))
8406 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
8407 (regexp-quote (nth (1- (prefix-numeric-value arg))
8408 org-todo-keywords-1)))
8409 (t (error "Invalid prefix argument: %s" arg)))))
8410 (message "%d TODO entries found"
8411 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
8413 (defun org-deadline (&optional remove time)
8414 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
8415 With argument REMOVE, remove any deadline from the item.
8416 When TIME is set, it should be an internal time specification, and the
8417 scheduling will use the corresponding date."
8418 (interactive "P")
8419 (if remove
8420 (progn
8421 (org-remove-timestamp-with-keyword org-deadline-string)
8422 (message "Item no longer has a deadline."))
8423 (if (org-get-repeat)
8424 (error "Cannot change deadline on task with repeater, please do that by hand")
8425 (org-add-planning-info 'deadline time 'closed)
8426 (message "Deadline on %s" org-last-inserted-timestamp))))
8428 (defun org-schedule (&optional remove time)
8429 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
8430 With argument REMOVE, remove any scheduling date from the item.
8431 When TIME is set, it should be an internal time specification, and the
8432 scheduling will use the corresponding date."
8433 (interactive "P")
8434 (if remove
8435 (progn
8436 (org-remove-timestamp-with-keyword org-scheduled-string)
8437 (message "Item is no longer scheduled."))
8438 (if (org-get-repeat)
8439 (error "Cannot reschedule task with repeater, please do that by hand")
8440 (org-add-planning-info 'scheduled time 'closed)
8441 (message "Scheduled to %s" org-last-inserted-timestamp))))
8443 (defun org-remove-timestamp-with-keyword (keyword)
8444 "Remove all time stamps with KEYWORD in the current entry."
8445 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
8446 beg)
8447 (save-excursion
8448 (org-back-to-heading t)
8449 (setq beg (point))
8450 (org-end-of-subtree t t)
8451 (while (re-search-backward re beg t)
8452 (replace-match "")
8453 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
8454 (equal (char-before) ?\ ))
8455 (backward-delete-char 1)
8456 (if (string-match "^[ \t]*$" (buffer-substring
8457 (point-at-bol) (point-at-eol)))
8458 (delete-region (point-at-bol)
8459 (min (point-max) (1+ (point-at-eol))))))))))
8461 (defun org-add-planning-info (what &optional time &rest remove)
8462 "Insert new timestamp with keyword in the line directly after the headline.
8463 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
8464 If non is given, the user is prompted for a date.
8465 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
8466 be removed."
8467 (interactive)
8468 (let (org-time-was-given org-end-time-was-given ts
8469 end default-time default-input)
8471 (when (and (not time) (memq what '(scheduled deadline)))
8472 ;; Try to get a default date/time from existing timestamp
8473 (save-excursion
8474 (org-back-to-heading t)
8475 (setq end (save-excursion (outline-next-heading) (point)))
8476 (when (re-search-forward (if (eq what 'scheduled)
8477 org-scheduled-time-regexp
8478 org-deadline-time-regexp)
8479 end t)
8480 (setq ts (match-string 1)
8481 default-time
8482 (apply 'encode-time (org-parse-time-string ts))
8483 default-input (and ts (org-get-compact-tod ts))))))
8484 (when what
8485 ;; If necessary, get the time from the user
8486 (setq time (or time (org-read-date nil 'to-time nil nil
8487 default-time default-input))))
8489 (when (and org-insert-labeled-timestamps-at-point
8490 (member what '(scheduled deadline)))
8491 (insert
8492 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
8493 (org-insert-time-stamp time org-time-was-given
8494 nil nil nil (list org-end-time-was-given))
8495 (setq what nil))
8496 (save-excursion
8497 (save-restriction
8498 (let (col list elt ts buffer-invisibility-spec)
8499 (org-back-to-heading t)
8500 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
8501 (goto-char (match-end 1))
8502 (setq col (current-column))
8503 (goto-char (match-end 0))
8504 (if (eobp) (insert "\n") (forward-char 1))
8505 (if (and (not (looking-at outline-regexp))
8506 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
8507 "[^\r\n]*"))
8508 (not (equal (match-string 1) org-clock-string)))
8509 (narrow-to-region (match-beginning 0) (match-end 0))
8510 (insert-before-markers "\n")
8511 (backward-char 1)
8512 (narrow-to-region (point) (point))
8513 (and org-adapt-indentation (org-indent-to-column col)))
8514 ;; Check if we have to remove something.
8515 (setq list (cons what remove))
8516 (while list
8517 (setq elt (pop list))
8518 (goto-char (point-min))
8519 (when (or (and (eq elt 'scheduled)
8520 (re-search-forward org-scheduled-time-regexp nil t))
8521 (and (eq elt 'deadline)
8522 (re-search-forward org-deadline-time-regexp nil t))
8523 (and (eq elt 'closed)
8524 (re-search-forward org-closed-time-regexp nil t)))
8525 (replace-match "")
8526 (if (looking-at "--+<[^>]+>") (replace-match ""))
8527 (if (looking-at " +") (replace-match ""))))
8528 (goto-char (point-max))
8529 (when what
8530 (insert
8531 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
8532 (cond ((eq what 'scheduled) org-scheduled-string)
8533 ((eq what 'deadline) org-deadline-string)
8534 ((eq what 'closed) org-closed-string))
8535 " ")
8536 (setq ts (org-insert-time-stamp
8537 time
8538 (or org-time-was-given
8539 (and (eq what 'closed) org-log-done-with-time))
8540 (eq what 'closed)
8541 nil nil (list org-end-time-was-given)))
8542 (end-of-line 1))
8543 (goto-char (point-min))
8544 (widen)
8545 (if (and (looking-at "[ \t]+\n")
8546 (equal (char-before) ?\n))
8547 (delete-region (1- (point)) (point-at-eol)))
8548 ts)))))
8550 (defvar org-log-note-marker (make-marker))
8551 (defvar org-log-note-purpose nil)
8552 (defvar org-log-note-state nil)
8553 (defvar org-log-note-how nil)
8554 (defvar org-log-note-extra nil)
8555 (defvar org-log-note-window-configuration nil)
8556 (defvar org-log-note-return-to (make-marker))
8557 (defvar org-log-post-message nil
8558 "Message to be displayed after a log note has been stored.
8559 The auto-repeater uses this.")
8561 (defun org-add-note ()
8562 "Add a note to the current entry.
8563 This is done in the same way as adding a state change note."
8564 (interactive)
8565 (org-add-log-setup 'note nil 'findpos nil))
8567 (defvar org-property-end-re)
8568 (defun org-add-log-setup (&optional purpose state findpos how &optional extra)
8569 "Set up the post command hook to take a note.
8570 If this is about to TODO state change, the new state is expected in STATE.
8571 When FINDPOS is non-nil, find the correct position for the note in
8572 the current entry. If not, assume that it can be inserted at point.
8573 HOW is an indicator what kind of note should be created.
8574 EXTRA is additional text that will be inserted into the notes buffer."
8575 (save-restriction
8576 (save-excursion
8577 (when findpos
8578 (org-back-to-heading t)
8579 (narrow-to-region (point) (save-excursion
8580 (outline-next-heading) (point)))
8581 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
8582 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
8583 "[^\r\n]*\\)?"))
8584 (goto-char (match-end 0))
8585 (when (and org-log-state-notes-insert-after-drawers
8586 (save-excursion
8587 (forward-line) (looking-at org-drawer-regexp)))
8588 (progn (forward-line)
8589 (while (looking-at org-drawer-regexp)
8590 (goto-char (match-end 0))
8591 (re-search-forward org-property-end-re (point-max) t)
8592 (forward-line))
8593 (forward-line -1)))
8594 (unless org-log-states-order-reversed
8595 (and (= (char-after) ?\n) (forward-char 1))
8596 (org-skip-over-state-notes)
8597 (skip-chars-backward " \t\n\r")))
8598 (move-marker org-log-note-marker (point))
8599 (setq org-log-note-purpose purpose
8600 org-log-note-state state
8601 org-log-note-how how
8602 org-log-note-extra extra)
8603 (add-hook 'post-command-hook 'org-add-log-note 'append))))
8605 (defun org-skip-over-state-notes ()
8606 "Skip past the list of State notes in an entry."
8607 (if (looking-at "\n[ \t]*- State") (forward-char 1))
8608 (while (looking-at "[ \t]*- State")
8609 (condition-case nil
8610 (org-next-item)
8611 (error (org-end-of-item)))))
8613 (defun org-add-log-note (&optional purpose)
8614 "Pop up a window for taking a note, and add this note later at point."
8615 (remove-hook 'post-command-hook 'org-add-log-note)
8616 (setq org-log-note-window-configuration (current-window-configuration))
8617 (delete-other-windows)
8618 (move-marker org-log-note-return-to (point))
8619 (switch-to-buffer (marker-buffer org-log-note-marker))
8620 (goto-char org-log-note-marker)
8621 (org-switch-to-buffer-other-window "*Org Note*")
8622 (erase-buffer)
8623 (if (memq org-log-note-how '(time state))
8624 (let (current-prefix-arg) (org-store-log-note))
8625 (let ((org-inhibit-startup t)) (org-mode))
8626 (insert (format "# Insert note for %s.
8627 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
8628 (cond
8629 ((eq org-log-note-purpose 'clock-out) "stopped clock")
8630 ((eq org-log-note-purpose 'done) "closed todo item")
8631 ((eq org-log-note-purpose 'state)
8632 (format "state change to \"%s\"" org-log-note-state))
8633 ((eq org-log-note-purpose 'note)
8634 "this entry")
8635 (t (error "This should not happen")))))
8636 (if org-log-note-extra (insert org-log-note-extra))
8637 (org-set-local 'org-finish-function 'org-store-log-note)))
8639 (defvar org-note-abort nil) ; dynamically scoped
8640 (defun org-store-log-note ()
8641 "Finish taking a log note, and insert it to where it belongs."
8642 (let ((txt (buffer-string))
8643 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
8644 lines ind)
8645 (kill-buffer (current-buffer))
8646 (while (string-match "\\`#.*\n[ \t\n]*" txt)
8647 (setq txt (replace-match "" t t txt)))
8648 (if (string-match "\\s-+\\'" txt)
8649 (setq txt (replace-match "" t t txt)))
8650 (setq lines (org-split-string txt "\n"))
8651 (when (and note (string-match "\\S-" note))
8652 (setq note
8653 (org-replace-escapes
8654 note
8655 (list (cons "%u" (user-login-name))
8656 (cons "%U" user-full-name)
8657 (cons "%t" (format-time-string
8658 (org-time-stamp-format 'long 'inactive)
8659 (current-time)))
8660 (cons "%s" (if org-log-note-state
8661 (concat "\"" org-log-note-state "\"")
8662 "")))))
8663 (if lines (setq note (concat note " \\\\")))
8664 (push note lines))
8665 (when (or current-prefix-arg org-note-abort) (setq lines nil))
8666 (when lines
8667 (save-excursion
8668 (set-buffer (marker-buffer org-log-note-marker))
8669 (save-excursion
8670 (goto-char org-log-note-marker)
8671 (move-marker org-log-note-marker nil)
8672 (end-of-line 1)
8673 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
8674 (indent-relative nil)
8675 (insert "- " (pop lines))
8676 (org-indent-line-function)
8677 (beginning-of-line 1)
8678 (looking-at "[ \t]*")
8679 (setq ind (concat (match-string 0) " "))
8680 (end-of-line 1)
8681 (while lines (insert "\n" ind (pop lines)))))))
8682 (set-window-configuration org-log-note-window-configuration)
8683 (with-current-buffer (marker-buffer org-log-note-return-to)
8684 (goto-char org-log-note-return-to))
8685 (move-marker org-log-note-return-to nil)
8686 (and org-log-post-message (message "%s" org-log-post-message)))
8688 (defun org-sparse-tree (&optional arg)
8689 "Create a sparse tree, prompt for the details.
8690 This command can create sparse trees. You first need to select the type
8691 of match used to create the tree:
8693 t Show entries with a specific TODO keyword.
8694 T Show entries selected by a tags match.
8695 p Enter a property name and its value (both with completion on existing
8696 names/values) and show entries with that property.
8697 r Show entries matching a regular expression
8698 d Show deadlines due within `org-deadline-warning-days'."
8699 (interactive "P")
8700 (let (ans kwd value)
8701 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
8702 (setq ans (read-char-exclusive))
8703 (cond
8704 ((equal ans ?d)
8705 (call-interactively 'org-check-deadlines))
8706 ((equal ans ?b)
8707 (call-interactively 'org-check-before-date))
8708 ((equal ans ?t)
8709 (org-show-todo-tree '(4)))
8710 ((equal ans ?T)
8711 (call-interactively 'org-tags-sparse-tree))
8712 ((member ans '(?p ?P))
8713 (setq kwd (completing-read "Property: "
8714 (mapcar 'list (org-buffer-property-keys))))
8715 (setq value (completing-read "Value: "
8716 (mapcar 'list (org-property-values kwd))))
8717 (unless (string-match "\\`{.*}\\'" value)
8718 (setq value (concat "\"" value "\"")))
8719 (org-tags-sparse-tree arg (concat kwd "=" value)))
8720 ((member ans '(?r ?R ?/))
8721 (call-interactively 'org-occur))
8722 (t (error "No such sparse tree command \"%c\"" ans)))))
8724 (defvar org-occur-highlights nil
8725 "List of overlays used for occur matches.")
8726 (make-variable-buffer-local 'org-occur-highlights)
8727 (defvar org-occur-parameters nil
8728 "Parameters of the active org-occur calls.
8729 This is a list, each call to org-occur pushes as cons cell,
8730 containing the regular expression and the callback, onto the list.
8731 The list can contain several entries if `org-occur' has been called
8732 several time with the KEEP-PREVIOUS argument. Otherwise, this list
8733 will only contain one set of parameters. When the highlights are
8734 removed (for example with `C-c C-c', or with the next edit (depending
8735 on `org-remove-highlights-with-change'), this variable is emptied
8736 as well.")
8737 (make-variable-buffer-local 'org-occur-parameters)
8739 (defun org-occur (regexp &optional keep-previous callback)
8740 "Make a compact tree which shows all matches of REGEXP.
8741 The tree will show the lines where the regexp matches, and all higher
8742 headlines above the match. It will also show the heading after the match,
8743 to make sure editing the matching entry is easy.
8744 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
8745 call to `org-occur' will be kept, to allow stacking of calls to this
8746 command.
8747 If CALLBACK is non-nil, it is a function which is called to confirm
8748 that the match should indeed be shown."
8749 (interactive "sRegexp: \nP")
8750 (unless keep-previous
8751 (org-remove-occur-highlights nil nil t))
8752 (push (cons regexp callback) org-occur-parameters)
8753 (let ((cnt 0))
8754 (save-excursion
8755 (goto-char (point-min))
8756 (if (or (not keep-previous) ; do not want to keep
8757 (not org-occur-highlights)) ; no previous matches
8758 ;; hide everything
8759 (org-overview))
8760 (while (re-search-forward regexp nil t)
8761 (when (or (not callback)
8762 (save-match-data (funcall callback)))
8763 (setq cnt (1+ cnt))
8764 (when org-highlight-sparse-tree-matches
8765 (org-highlight-new-match (match-beginning 0) (match-end 0)))
8766 (org-show-context 'occur-tree))))
8767 (when org-remove-highlights-with-change
8768 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
8769 nil 'local))
8770 (unless org-sparse-tree-open-archived-trees
8771 (org-hide-archived-subtrees (point-min) (point-max)))
8772 (run-hooks 'org-occur-hook)
8773 (if (interactive-p)
8774 (message "%d match(es) for regexp %s" cnt regexp))
8775 cnt))
8777 (defun org-show-context (&optional key)
8778 "Make sure point and context and visible.
8779 How much context is shown depends upon the variables
8780 `org-show-hierarchy-above', `org-show-following-heading'. and
8781 `org-show-siblings'."
8782 (let ((heading-p (org-on-heading-p t))
8783 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
8784 (following-p (org-get-alist-option org-show-following-heading key))
8785 (entry-p (org-get-alist-option org-show-entry-below key))
8786 (siblings-p (org-get-alist-option org-show-siblings key)))
8787 (catch 'exit
8788 ;; Show heading or entry text
8789 (if (and heading-p (not entry-p))
8790 (org-flag-heading nil) ; only show the heading
8791 (and (or entry-p (org-invisible-p) (org-invisible-p2))
8792 (org-show-hidden-entry))) ; show entire entry
8793 (when following-p
8794 ;; Show next sibling, or heading below text
8795 (save-excursion
8796 (and (if heading-p (org-goto-sibling) (outline-next-heading))
8797 (org-flag-heading nil))))
8798 (when siblings-p (org-show-siblings))
8799 (when hierarchy-p
8800 ;; show all higher headings, possibly with siblings
8801 (save-excursion
8802 (while (and (condition-case nil
8803 (progn (org-up-heading-all 1) t)
8804 (error nil))
8805 (not (bobp)))
8806 (org-flag-heading nil)
8807 (when siblings-p (org-show-siblings))))))))
8809 (defun org-reveal (&optional siblings)
8810 "Show current entry, hierarchy above it, and the following headline.
8811 This can be used to show a consistent set of context around locations
8812 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
8813 not t for the search context.
8815 With optional argument SIBLINGS, on each level of the hierarchy all
8816 siblings are shown. This repairs the tree structure to what it would
8817 look like when opened with hierarchical calls to `org-cycle'."
8818 (interactive "P")
8819 (let ((org-show-hierarchy-above t)
8820 (org-show-following-heading t)
8821 (org-show-siblings (if siblings t org-show-siblings)))
8822 (org-show-context nil)))
8824 (defun org-highlight-new-match (beg end)
8825 "Highlight from BEG to END and mark the highlight is an occur headline."
8826 (let ((ov (org-make-overlay beg end)))
8827 (org-overlay-put ov 'face 'secondary-selection)
8828 (push ov org-occur-highlights)))
8830 (defun org-remove-occur-highlights (&optional beg end noremove)
8831 "Remove the occur highlights from the buffer.
8832 BEG and END are ignored. If NOREMOVE is nil, remove this function
8833 from the `before-change-functions' in the current buffer."
8834 (interactive)
8835 (unless org-inhibit-highlight-removal
8836 (mapc 'org-delete-overlay org-occur-highlights)
8837 (setq org-occur-highlights nil)
8838 (setq org-occur-parameters nil)
8839 (unless noremove
8840 (remove-hook 'before-change-functions
8841 'org-remove-occur-highlights 'local))))
8843 ;;;; Priorities
8845 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
8846 "Regular expression matching the priority indicator.")
8848 (defvar org-remove-priority-next-time nil)
8850 (defun org-priority-up ()
8851 "Increase the priority of the current item."
8852 (interactive)
8853 (org-priority 'up))
8855 (defun org-priority-down ()
8856 "Decrease the priority of the current item."
8857 (interactive)
8858 (org-priority 'down))
8860 (defun org-priority (&optional action)
8861 "Change the priority of an item by ARG.
8862 ACTION can be `set', `up', `down', or a character."
8863 (interactive)
8864 (setq action (or action 'set))
8865 (let (current new news have remove)
8866 (save-excursion
8867 (org-back-to-heading)
8868 (if (looking-at org-priority-regexp)
8869 (setq current (string-to-char (match-string 2))
8870 have t)
8871 (setq current org-default-priority))
8872 (cond
8873 ((or (eq action 'set)
8874 (if (featurep 'xemacs) (characterp action) (integerp action)))
8875 (if (not (eq action 'set))
8876 (setq new action)
8877 (message "Priority %c-%c, SPC to remove: "
8878 org-highest-priority org-lowest-priority)
8879 (setq new (read-char-exclusive)))
8880 (if (and (= (upcase org-highest-priority) org-highest-priority)
8881 (= (upcase org-lowest-priority) org-lowest-priority))
8882 (setq new (upcase new)))
8883 (cond ((equal new ?\ ) (setq remove t))
8884 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
8885 (error "Priority must be between `%c' and `%c'"
8886 org-highest-priority org-lowest-priority))))
8887 ((eq action 'up)
8888 (if (and (not have) (eq last-command this-command))
8889 (setq new org-lowest-priority)
8890 (setq new (if (and org-priority-start-cycle-with-default (not have))
8891 org-default-priority (1- current)))))
8892 ((eq action 'down)
8893 (if (and (not have) (eq last-command this-command))
8894 (setq new org-highest-priority)
8895 (setq new (if (and org-priority-start-cycle-with-default (not have))
8896 org-default-priority (1+ current)))))
8897 (t (error "Invalid action")))
8898 (if (or (< (upcase new) org-highest-priority)
8899 (> (upcase new) org-lowest-priority))
8900 (setq remove t))
8901 (setq news (format "%c" new))
8902 (if have
8903 (if remove
8904 (replace-match "" t t nil 1)
8905 (replace-match news t t nil 2))
8906 (if remove
8907 (error "No priority cookie found in line")
8908 (looking-at org-todo-line-regexp)
8909 (if (match-end 2)
8910 (progn
8911 (goto-char (match-end 2))
8912 (insert " [#" news "]"))
8913 (goto-char (match-beginning 3))
8914 (insert "[#" news "] ")))))
8915 (org-preserve-lc (org-set-tags nil 'align))
8916 (if remove
8917 (message "Priority removed")
8918 (message "Priority of current item set to %s" news))))
8921 (defun org-get-priority (s)
8922 "Find priority cookie and return priority."
8923 (save-match-data
8924 (if (not (string-match org-priority-regexp s))
8925 (* 1000 (- org-lowest-priority org-default-priority))
8926 (* 1000 (- org-lowest-priority
8927 (string-to-char (match-string 2 s)))))))
8929 ;;;; Tags
8931 (defvar org-agenda-archives-mode)
8932 (defun org-scan-tags (action matcher &optional todo-only)
8933 "Scan headline tags with inheritance and produce output ACTION.
8935 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
8936 or `agenda' to produce an entry list for an agenda view. It can also be
8937 a Lisp form or a function that should be called at each matched headline, in
8938 this case the return value is a list of all return values from these calls.
8940 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
8941 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
8942 only lines with a TODO keyword are included in the output."
8943 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
8944 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
8945 (org-re
8946 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
8947 (props (list 'face 'default
8948 'done-face 'org-done
8949 'undone-face 'default
8950 'mouse-face 'highlight
8951 'org-not-done-regexp org-not-done-regexp
8952 'org-todo-regexp org-todo-regexp
8953 'keymap org-agenda-keymap
8954 'help-echo
8955 (format "mouse-2 or RET jump to org file %s"
8956 (abbreviate-file-name
8957 (or (buffer-file-name (buffer-base-buffer))
8958 (buffer-name (buffer-base-buffer)))))))
8959 (case-fold-search nil)
8960 lspos tags tags-list
8961 (tags-alist (list (cons 0 (mapcar 'downcase org-file-tags))))
8962 (llast 0) rtn rtn1 level category i txt
8963 todo marker entry priority)
8964 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
8965 (setq action (list 'lambda nil action)))
8966 (save-excursion
8967 (goto-char (point-min))
8968 (when (eq action 'sparse-tree)
8969 (org-overview)
8970 (org-remove-occur-highlights))
8971 (while (re-search-forward re nil t)
8972 (catch :skip
8973 (setq todo (if (match-end 1) (match-string 2))
8974 tags (if (match-end 4) (match-string 4)))
8975 (goto-char (setq lspos (1+ (match-beginning 0))))
8976 (setq level (org-reduced-level (funcall outline-level))
8977 category (org-get-category))
8978 (setq i llast llast level)
8979 ;; remove tag lists from same and sublevels
8980 (while (>= i level)
8981 (when (setq entry (assoc i tags-alist))
8982 (setq tags-alist (delete entry tags-alist)))
8983 (setq i (1- i)))
8984 ;; add the next tags
8985 (when tags
8986 (setq tags (mapcar 'downcase (org-split-string tags ":"))
8987 tags-alist
8988 (cons (cons level tags) tags-alist)))
8989 ;; compile tags for current headline
8990 (setq tags-list
8991 (if org-use-tag-inheritance
8992 (apply 'append (mapcar 'cdr tags-alist))
8993 tags))
8994 (when (and tags org-use-tag-inheritance
8995 (not (eq t org-use-tag-inheritance)))
8996 ;; selective inheritance, remove uninherited ones
8997 (setcdr (car tags-alist)
8998 (org-remove-uniherited-tags (cdar tags-alist))))
8999 (when (and (or (not todo-only) (member todo org-not-done-keywords))
9000 (let ((case-fold-search t)) (eval matcher))
9002 (not (member org-archive-tag tags-list))
9003 ;; we have an archive tag, should we use this anyway?
9004 (or (not org-agenda-skip-archived-trees)
9005 (and (eq action 'agenda) org-agenda-archives-mode))))
9006 (unless (eq action 'sparse-tree) (org-agenda-skip))
9008 ;; select this headline
9010 (cond
9011 ((eq action 'sparse-tree)
9012 (and org-highlight-sparse-tree-matches
9013 (org-get-heading) (match-end 0)
9014 (org-highlight-new-match
9015 (match-beginning 0) (match-beginning 1)))
9016 (org-show-context 'tags-tree))
9017 ((eq action 'agenda)
9018 (setq txt (org-format-agenda-item
9020 (concat
9021 (if org-tags-match-list-sublevels
9022 (make-string (1- level) ?.) "")
9023 (org-get-heading))
9024 category tags-list)
9025 priority (org-get-priority txt))
9026 (goto-char lspos)
9027 (setq marker (org-agenda-new-marker))
9028 (org-add-props txt props
9029 'org-marker marker 'org-hd-marker marker 'org-category category
9030 'priority priority 'type "tagsmatch")
9031 (push txt rtn))
9032 ((functionp action)
9033 (save-excursion
9034 (setq rtn1 (funcall action))
9035 (push rtn1 rtn))
9036 (goto-char (point-at-eol)))
9037 (t (error "Invalid action")))
9039 ;; if we are to skip sublevels, jump to end of subtree
9040 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
9041 (when (and (eq action 'sparse-tree)
9042 (not org-sparse-tree-open-archived-trees))
9043 (org-hide-archived-subtrees (point-min) (point-max)))
9044 (nreverse rtn)))
9046 (defun org-remove-uniherited-tags (tags)
9047 "Remove all tags that are not inherited from the list TAGS."
9048 (cond
9049 ((eq org-use-tag-inheritance t) tags)
9050 ((not org-use-tag-inheritance) nil)
9051 ((stringp org-use-tag-inheritance)
9052 (delq nil (mapcar
9053 (lambda (x) (if (string-match org-use-tag-inheritance x) x nil))
9054 tags)))
9055 ((listp org-use-tag-inheritance)
9056 (delq nil (mapcar
9057 (lambda (x) (if (member x org-use-tag-inheritance) x nil))
9058 tags)))))
9060 (defvar todo-only) ;; dynamically scoped
9062 (defun org-tags-sparse-tree (&optional todo-only match)
9063 "Create a sparse tree according to tags string MATCH.
9064 MATCH can contain positive and negative selection of tags, like
9065 \"+WORK+URGENT-WITHBOSS\".
9066 If optional argument TODO_ONLY is non-nil, only select lines that are
9067 also TODO lines."
9068 (interactive "P")
9069 (org-prepare-agenda-buffers (list (current-buffer)))
9070 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
9072 (defvar org-cached-props nil)
9073 (defun org-cached-entry-get (pom property)
9074 (if (or (eq t org-use-property-inheritance)
9075 (and (stringp org-use-property-inheritance)
9076 (string-match org-use-property-inheritance property))
9077 (and (listp org-use-property-inheritance)
9078 (member property org-use-property-inheritance)))
9079 ;; Caching is not possible, check it directly
9080 (org-entry-get pom property 'inherit)
9081 ;; Get all properties, so that we can do complicated checks easily
9082 (cdr (assoc property (or org-cached-props
9083 (setq org-cached-props
9084 (org-entry-properties pom)))))))
9086 (defun org-global-tags-completion-table (&optional files)
9087 "Return the list of all tags in all agenda buffer/files."
9088 (save-excursion
9089 (org-uniquify
9090 (delq nil
9091 (apply 'append
9092 (mapcar
9093 (lambda (file)
9094 (set-buffer (find-file-noselect file))
9095 (append (org-get-buffer-tags)
9096 (mapcar (lambda (x) (if (stringp (car-safe x))
9097 (list (car-safe x)) nil))
9098 org-tag-alist)))
9099 (if (and files (car files))
9100 files
9101 (org-agenda-files))))))))
9103 (defun org-make-tags-matcher (match)
9104 "Create the TAGS//TODO matcher form for the selection string MATCH."
9105 ;; todo-only is scoped dynamically into this function, and the function
9106 ;; may change it it the matcher asksk for it.
9107 (unless match
9108 ;; Get a new match request, with completion
9109 (let ((org-last-tags-completion-table
9110 (org-global-tags-completion-table)))
9111 (setq match (completing-read
9112 "Match: " 'org-tags-completion-function nil nil nil
9113 'org-tags-history))))
9115 ;; Parse the string and create a lisp form
9116 (let ((match0 match)
9117 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
9118 minus tag mm
9119 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
9120 orterms term orlist re-p str-p level-p level-op time-p
9121 prop-p pn pv po cat-p gv rest)
9122 (if (string-match "/+" match)
9123 ;; match contains also a todo-matching request
9124 (progn
9125 (setq tagsmatch (substring match 0 (match-beginning 0))
9126 todomatch (substring match (match-end 0)))
9127 (if (string-match "^!" todomatch)
9128 (setq todo-only t todomatch (substring todomatch 1)))
9129 (if (string-match "^\\s-*$" todomatch)
9130 (setq todomatch nil)))
9131 ;; only matching tags
9132 (setq tagsmatch match todomatch nil))
9134 ;; Make the tags matcher
9135 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
9136 (setq tagsmatcher t)
9137 (setq orterms (org-split-string tagsmatch "|") orlist nil)
9138 (while (setq term (pop orterms))
9139 (while (and (equal (substring term -1) "\\") orterms)
9140 (setq term (concat term "|" (pop orterms)))) ; repair bad split
9141 (while (string-match re term)
9142 (setq rest (substring term (match-end 0))
9143 minus (and (match-end 1)
9144 (equal (match-string 1 term) "-"))
9145 tag (match-string 2 term)
9146 re-p (equal (string-to-char tag) ?{)
9147 level-p (match-end 4)
9148 prop-p (match-end 5)
9149 mm (cond
9150 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
9151 (level-p
9152 (setq level-op (org-op-to-function (match-string 3 term)))
9153 `(,level-op level ,(string-to-number
9154 (match-string 4 term))))
9155 (prop-p
9156 (setq pn (match-string 5 term)
9157 po (match-string 6 term)
9158 pv (match-string 7 term)
9159 cat-p (equal pn "CATEGORY")
9160 re-p (equal (string-to-char pv) ?{)
9161 str-p (equal (string-to-char pv) ?\")
9162 time-p (save-match-data
9163 (string-match "^\"[[<].*[]>]\"$" pv))
9164 pv (if (or re-p str-p) (substring pv 1 -1) pv))
9165 (if time-p (setq pv (org-matcher-time pv)))
9166 (setq po (org-op-to-function po (if time-p 'time str-p)))
9167 (cond
9168 ((equal pn "CATEGORY")
9169 (setq gv '(get-text-property (point) 'org-category)))
9170 ((equal pn "TODO")
9171 (setq gv 'todo))
9173 (setq gv `(org-cached-entry-get nil ,pn))))
9174 (if re-p
9175 (if (eq po 'org<>)
9176 `(not (string-match ,pv (or ,gv "")))
9177 `(string-match ,pv (or ,gv "")))
9178 (if str-p
9179 `(,po (or ,gv "") ,pv)
9180 `(,po (string-to-number (or ,gv ""))
9181 ,(string-to-number pv) ))))
9182 (t `(member ,(downcase tag) tags-list)))
9183 mm (if minus (list 'not mm) mm)
9184 term rest)
9185 (push mm tagsmatcher))
9186 (push (if (> (length tagsmatcher) 1)
9187 (cons 'and tagsmatcher)
9188 (car tagsmatcher))
9189 orlist)
9190 (setq tagsmatcher nil))
9191 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
9192 (setq tagsmatcher
9193 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
9194 ;; Make the todo matcher
9195 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
9196 (setq todomatcher t)
9197 (setq orterms (org-split-string todomatch "|") orlist nil)
9198 (while (setq term (pop orterms))
9199 (while (string-match re term)
9200 (setq minus (and (match-end 1)
9201 (equal (match-string 1 term) "-"))
9202 kwd (match-string 2 term)
9203 re-p (equal (string-to-char kwd) ?{)
9204 term (substring term (match-end 0))
9205 mm (if re-p
9206 `(string-match ,(substring kwd 1 -1) todo)
9207 (list 'equal 'todo kwd))
9208 mm (if minus (list 'not mm) mm))
9209 (push mm todomatcher))
9210 (push (if (> (length todomatcher) 1)
9211 (cons 'and todomatcher)
9212 (car todomatcher))
9213 orlist)
9214 (setq todomatcher nil))
9215 (setq todomatcher (if (> (length orlist) 1)
9216 (cons 'or orlist) (car orlist))))
9218 ;; Return the string and lisp forms of the matcher
9219 (setq matcher (if todomatcher
9220 (list 'and tagsmatcher todomatcher)
9221 tagsmatcher))
9222 (cons match0 matcher)))
9224 (defun org-op-to-function (op &optional stringp)
9225 "Turn an operator into the appropriate function."
9226 (setq op
9227 (cond
9228 ((equal op "<" ) '(< string< org-time<))
9229 ((equal op ">" ) '(> org-string> org-time>))
9230 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
9231 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
9232 ((member op '("=" "==")) '(= string= org-time=))
9233 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
9234 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
9236 (defun org<> (a b) (not (= a b)))
9237 (defun org-string<= (a b) (or (string= a b) (string< a b)))
9238 (defun org-string>= (a b) (not (string< a b)))
9239 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
9240 (defun org-string<> (a b) (not (string= a b)))
9241 (defun org-time= (a b) (= (org-2ft a) (org-2ft b)))
9242 (defun org-time< (a b) (< (org-2ft a) (org-2ft b)))
9243 (defun org-time<= (a b) (<= (org-2ft a) (org-2ft b)))
9244 (defun org-time> (a b) (> (org-2ft a) (org-2ft b)))
9245 (defun org-time>= (a b) (>= (org-2ft a) (org-2ft b)))
9246 (defun org-time<> (a b) (org<> (org-2ft a) (org-2ft b)))
9247 (defun org-2ft (s)
9248 "Convert S to a floating point time.
9249 If S is already a number, just return it. If it is a string, parse
9250 it as a time string and apply `float-time' to it. f S is nil, just return 0."
9251 (cond
9252 ((numberp s) s)
9253 ((stringp s)
9254 (condition-case nil
9255 (float-time (apply 'encode-time (org-parse-time-string s)))
9256 (error 0.)))
9257 (t 0.)))
9259 (defun org-time-today ()
9260 "Time in seconds today at 0:00.
9261 Returns the float number of seconds since the beginning of the
9262 epoch to the beginning of today (00:00)."
9263 (float-time (apply 'encode-time
9264 (append '(0 0 0) (nthcdr 3 (decode-time))))))
9266 (defun org-matcher-time (s)
9267 (cond
9268 ((string= s "<now>") (float-time))
9269 ((string= s "<today>") (org-time-today))
9270 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
9271 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
9272 (t (org-2ft s))))
9274 (defun org-match-any-p (re list)
9275 "Does re match any element of list?"
9276 (setq list (mapcar (lambda (x) (string-match re x)) list))
9277 (delq nil list))
9279 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
9280 (defvar org-tags-overlay (org-make-overlay 1 1))
9281 (org-detach-overlay org-tags-overlay)
9283 (defun org-get-local-tags-at (&optional pos)
9284 "Get a list of tags defined in the current headline."
9285 (org-get-tags-at pos 'local))
9287 (defun org-get-local-tags ()
9288 "Get a list of tags defined in the current headline."
9289 (org-get-tags-at nil 'local))
9291 (defun org-get-tags-at (&optional pos local)
9292 "Get a list of all headline tags applicable at POS.
9293 POS defaults to point. If tags are inherited, the list contains
9294 the targets in the same sequence as the headlines appear, i.e.
9295 the tags of the current headline come last.
9296 When LOCAL is non-nil, only return tags from the current headline,
9297 ignore inherited ones."
9298 (interactive)
9299 (let (tags ltags lastpos parent)
9300 (save-excursion
9301 (save-restriction
9302 (widen)
9303 (goto-char (or pos (point)))
9304 (save-match-data
9305 (catch 'done
9306 (condition-case nil
9307 (progn
9308 (org-back-to-heading t)
9309 (while (not (equal lastpos (point)))
9310 (setq lastpos (point))
9311 (when (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
9312 (setq ltags (org-split-string
9313 (org-match-string-no-properties 1) ":"))
9314 (setq tags (append
9315 (if parent
9316 (org-remove-uniherited-tags ltags)
9317 ltags)
9318 tags)))
9319 (or org-use-tag-inheritance (throw 'done t))
9320 (if local (throw 'done t))
9321 (org-up-heading-all 1)
9322 (setq parent t)))
9323 (error nil)))))
9324 (append (org-remove-uniherited-tags org-file-tags) tags))))
9326 (defun org-toggle-tag (tag &optional onoff)
9327 "Toggle the tag TAG for the current line.
9328 If ONOFF is `on' or `off', don't toggle but set to this state."
9329 (unless (org-on-heading-p t) (error "Not on headling"))
9330 (let (res current)
9331 (save-excursion
9332 (beginning-of-line)
9333 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
9334 (point-at-eol) t)
9335 (progn
9336 (setq current (match-string 1))
9337 (replace-match ""))
9338 (setq current ""))
9339 (setq current (nreverse (org-split-string current ":")))
9340 (cond
9341 ((eq onoff 'on)
9342 (setq res t)
9343 (or (member tag current) (push tag current)))
9344 ((eq onoff 'off)
9345 (or (not (member tag current)) (setq current (delete tag current))))
9346 (t (if (member tag current)
9347 (setq current (delete tag current))
9348 (setq res t)
9349 (push tag current))))
9350 (end-of-line 1)
9351 (if current
9352 (progn
9353 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
9354 (org-set-tags nil t))
9355 (delete-horizontal-space))
9356 (run-hooks 'org-after-tags-change-hook))
9357 res))
9359 (defun org-align-tags-here (to-col)
9360 ;; Assumes that this is a headline
9361 (let ((pos (point)) (col (current-column)) ncol tags-l p)
9362 (beginning-of-line 1)
9363 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9364 (< pos (match-beginning 2)))
9365 (progn
9366 (setq tags-l (- (match-end 2) (match-beginning 2)))
9367 (goto-char (match-beginning 1))
9368 (insert " ")
9369 (delete-region (point) (1+ (match-beginning 2)))
9370 (setq ncol (max (1+ (current-column))
9371 (1+ col)
9372 (if (> to-col 0)
9373 to-col
9374 (- (abs to-col) tags-l))))
9375 (setq p (point))
9376 (insert (make-string (- ncol (current-column)) ?\ ))
9377 (setq ncol (current-column))
9378 (when indent-tabs-mode (tabify p (point-at-eol)))
9379 (org-move-to-column (min ncol col) t))
9380 (goto-char pos))))
9382 (defun org-set-tags-command (&optional arg just-align)
9383 "Call the set-tags command for the current entry."
9384 (interactive "P")
9385 (if (org-on-heading-p)
9386 (org-set-tags arg just-align)
9387 (save-excursion
9388 (org-back-to-heading t)
9389 (org-set-tags arg just-align))))
9391 (defun org-set-tags (&optional arg just-align)
9392 "Set the tags for the current headline.
9393 With prefix ARG, realign all tags in headings in the current buffer."
9394 (interactive "P")
9395 (let* ((re (concat "^" outline-regexp))
9396 (current (org-get-tags-string))
9397 (col (current-column))
9398 (org-setting-tags t)
9399 table current-tags inherited-tags ; computed below when needed
9400 tags p0 c0 c1 rpl)
9401 (if arg
9402 (save-excursion
9403 (goto-char (point-min))
9404 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
9405 (while (re-search-forward re nil t)
9406 (org-set-tags nil t)
9407 (end-of-line 1)))
9408 (message "All tags realigned to column %d" org-tags-column))
9409 (if just-align
9410 (setq tags current)
9411 ;; Get a new set of tags from the user
9412 (save-excursion
9413 (setq table (or org-tag-alist (org-get-buffer-tags))
9414 org-last-tags-completion-table table
9415 current-tags (org-split-string current ":")
9416 inherited-tags (nreverse
9417 (nthcdr (length current-tags)
9418 (nreverse (org-get-tags-at))))
9419 tags
9420 (if (or (eq t org-use-fast-tag-selection)
9421 (and org-use-fast-tag-selection
9422 (delq nil (mapcar 'cdr table))))
9423 (org-fast-tag-selection
9424 current-tags inherited-tags table
9425 (if org-fast-tag-selection-include-todo org-todo-key-alist))
9426 (let ((org-add-colon-after-tag-completion t))
9427 (org-trim
9428 (org-without-partial-completion
9429 (completing-read "Tags: " 'org-tags-completion-function
9430 nil nil current 'org-tags-history)))))))
9431 (while (string-match "[-+&]+" tags)
9432 ;; No boolean logic, just a list
9433 (setq tags (replace-match ":" t t tags))))
9435 (if (string-match "\\`[\t ]*\\'" tags)
9436 (setq tags "")
9437 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
9438 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
9440 ;; Insert new tags at the correct column
9441 (beginning-of-line 1)
9442 (cond
9443 ((and (equal current "") (equal tags "")))
9444 ((re-search-forward
9445 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
9446 (point-at-eol) t)
9447 (if (equal tags "")
9448 (setq rpl "")
9449 (goto-char (match-beginning 0))
9450 (setq c0 (current-column) p0 (point)
9451 c1 (max (1+ c0) (if (> org-tags-column 0)
9452 org-tags-column
9453 (- (- org-tags-column) (length tags))))
9454 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
9455 (replace-match rpl t t)
9456 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
9457 tags)
9458 (t (error "Tags alignment failed")))
9459 (org-move-to-column col)
9460 (unless just-align
9461 (run-hooks 'org-after-tags-change-hook)))))
9463 (defun org-change-tag-in-region (beg end tag off)
9464 "Add or remove TAG for each entry in the region.
9465 This works in the agenda, and also in an org-mode buffer."
9466 (interactive
9467 (list (region-beginning) (region-end)
9468 (let ((org-last-tags-completion-table
9469 (if (org-mode-p)
9470 (org-get-buffer-tags)
9471 (org-global-tags-completion-table))))
9472 (completing-read
9473 "Tag: " 'org-tags-completion-function nil nil nil
9474 'org-tags-history))
9475 (progn
9476 (message "[s]et or [r]emove? ")
9477 (equal (read-char-exclusive) ?r))))
9478 (if (fboundp 'deactivate-mark) (deactivate-mark))
9479 (let ((agendap (equal major-mode 'org-agenda-mode))
9480 l1 l2 m buf pos newhead (cnt 0))
9481 (goto-char end)
9482 (setq l2 (1- (org-current-line)))
9483 (goto-char beg)
9484 (setq l1 (org-current-line))
9485 (loop for l from l1 to l2 do
9486 (goto-line l)
9487 (setq m (get-text-property (point) 'org-hd-marker))
9488 (when (or (and (org-mode-p) (org-on-heading-p))
9489 (and agendap m))
9490 (setq buf (if agendap (marker-buffer m) (current-buffer))
9491 pos (if agendap m (point)))
9492 (with-current-buffer buf
9493 (save-excursion
9494 (save-restriction
9495 (goto-char pos)
9496 (setq cnt (1+ cnt))
9497 (org-toggle-tag tag (if off 'off 'on))
9498 (setq newhead (org-get-heading)))))
9499 (and agendap (org-agenda-change-all-lines newhead m))))
9500 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
9502 (defun org-tags-completion-function (string predicate &optional flag)
9503 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
9504 (confirm (lambda (x) (stringp (car x)))))
9505 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
9506 (setq s1 (match-string 1 string)
9507 s2 (match-string 2 string))
9508 (setq s1 "" s2 string))
9509 (cond
9510 ((eq flag nil)
9511 ;; try completion
9512 (setq rtn (try-completion s2 ctable confirm))
9513 (if (stringp rtn)
9514 (setq rtn
9515 (concat s1 s2 (substring rtn (length s2))
9516 (if (and org-add-colon-after-tag-completion
9517 (assoc rtn ctable))
9518 ":" ""))))
9519 rtn)
9520 ((eq flag t)
9521 ;; all-completions
9522 (all-completions s2 ctable confirm)
9524 ((eq flag 'lambda)
9525 ;; exact match?
9526 (assoc s2 ctable)))
9529 (defun org-fast-tag-insert (kwd tags face &optional end)
9530 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
9531 (insert (format "%-12s" (concat kwd ":"))
9532 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
9533 (or end "")))
9535 (defun org-fast-tag-show-exit (flag)
9536 (save-excursion
9537 (goto-line 3)
9538 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
9539 (replace-match ""))
9540 (when flag
9541 (end-of-line 1)
9542 (org-move-to-column (- (window-width) 19) t)
9543 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
9545 (defun org-set-current-tags-overlay (current prefix)
9546 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
9547 (if (featurep 'xemacs)
9548 (org-overlay-display org-tags-overlay (concat prefix s)
9549 'secondary-selection)
9550 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
9551 (org-overlay-display org-tags-overlay (concat prefix s)))))
9553 (defun org-fast-tag-selection (current inherited table &optional todo-table)
9554 "Fast tag selection with single keys.
9555 CURRENT is the current list of tags in the headline, INHERITED is the
9556 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
9557 possibly with grouping information. TODO-TABLE is a similar table with
9558 TODO keywords, should these have keys assigned to them.
9559 If the keys are nil, a-z are automatically assigned.
9560 Returns the new tags string, or nil to not change the current settings."
9561 (let* ((fulltable (append table todo-table))
9562 (maxlen (apply 'max (mapcar
9563 (lambda (x)
9564 (if (stringp (car x)) (string-width (car x)) 0))
9565 fulltable)))
9566 (buf (current-buffer))
9567 (expert (eq org-fast-tag-selection-single-key 'expert))
9568 (buffer-tags nil)
9569 (fwidth (+ maxlen 3 1 3))
9570 (ncol (/ (- (window-width) 4) fwidth))
9571 (i-face 'org-done)
9572 (c-face 'org-todo)
9573 tg cnt e c char c1 c2 ntable tbl rtn
9574 ov-start ov-end ov-prefix
9575 (exit-after-next org-fast-tag-selection-single-key)
9576 (done-keywords org-done-keywords)
9577 groups ingroup)
9578 (save-excursion
9579 (beginning-of-line 1)
9580 (if (looking-at
9581 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9582 (setq ov-start (match-beginning 1)
9583 ov-end (match-end 1)
9584 ov-prefix "")
9585 (setq ov-start (1- (point-at-eol))
9586 ov-end (1+ ov-start))
9587 (skip-chars-forward "^\n\r")
9588 (setq ov-prefix
9589 (concat
9590 (buffer-substring (1- (point)) (point))
9591 (if (> (current-column) org-tags-column)
9593 (make-string (- org-tags-column (current-column)) ?\ ))))))
9594 (org-move-overlay org-tags-overlay ov-start ov-end)
9595 (save-window-excursion
9596 (if expert
9597 (set-buffer (get-buffer-create " *Org tags*"))
9598 (delete-other-windows)
9599 (split-window-vertically)
9600 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
9601 (erase-buffer)
9602 (org-set-local 'org-done-keywords done-keywords)
9603 (org-fast-tag-insert "Inherited" inherited i-face "\n")
9604 (org-fast-tag-insert "Current" current c-face "\n\n")
9605 (org-fast-tag-show-exit exit-after-next)
9606 (org-set-current-tags-overlay current ov-prefix)
9607 (setq tbl fulltable char ?a cnt 0)
9608 (while (setq e (pop tbl))
9609 (cond
9610 ((equal e '(:startgroup))
9611 (push '() groups) (setq ingroup t)
9612 (when (not (= cnt 0))
9613 (setq cnt 0)
9614 (insert "\n"))
9615 (insert "{ "))
9616 ((equal e '(:endgroup))
9617 (setq ingroup nil cnt 0)
9618 (insert "}\n"))
9620 (setq tg (car e) c2 nil)
9621 (if (cdr e)
9622 (setq c (cdr e))
9623 ;; automatically assign a character.
9624 (setq c1 (string-to-char
9625 (downcase (substring
9626 tg (if (= (string-to-char tg) ?@) 1 0)))))
9627 (if (or (rassoc c1 ntable) (rassoc c1 table))
9628 (while (or (rassoc char ntable) (rassoc char table))
9629 (setq char (1+ char)))
9630 (setq c2 c1))
9631 (setq c (or c2 char)))
9632 (if ingroup (push tg (car groups)))
9633 (setq tg (org-add-props tg nil 'face
9634 (cond
9635 ((not (assoc tg table))
9636 (org-get-todo-face tg))
9637 ((member tg current) c-face)
9638 ((member tg inherited) i-face)
9639 (t nil))))
9640 (if (and (= cnt 0) (not ingroup)) (insert " "))
9641 (insert "[" c "] " tg (make-string
9642 (- fwidth 4 (length tg)) ?\ ))
9643 (push (cons tg c) ntable)
9644 (when (= (setq cnt (1+ cnt)) ncol)
9645 (insert "\n")
9646 (if ingroup (insert " "))
9647 (setq cnt 0)))))
9648 (setq ntable (nreverse ntable))
9649 (insert "\n")
9650 (goto-char (point-min))
9651 (if (not expert) (org-fit-window-to-buffer))
9652 (setq rtn
9653 (catch 'exit
9654 (while t
9655 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
9656 (if groups " [!] no groups" " [!]groups")
9657 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
9658 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9659 (cond
9660 ((= c ?\r) (throw 'exit t))
9661 ((= c ?!)
9662 (setq groups (not groups))
9663 (goto-char (point-min))
9664 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
9665 ((= c ?\C-c)
9666 (if (not expert)
9667 (org-fast-tag-show-exit
9668 (setq exit-after-next (not exit-after-next)))
9669 (setq expert nil)
9670 (delete-other-windows)
9671 (split-window-vertically)
9672 (org-switch-to-buffer-other-window " *Org tags*")
9673 (org-fit-window-to-buffer)))
9674 ((or (= c ?\C-g)
9675 (and (= c ?q) (not (rassoc c ntable))))
9676 (org-detach-overlay org-tags-overlay)
9677 (setq quit-flag t))
9678 ((= c ?\ )
9679 (setq current nil)
9680 (if exit-after-next (setq exit-after-next 'now)))
9681 ((= c ?\t)
9682 (condition-case nil
9683 (setq tg (completing-read
9684 "Tag: "
9685 (or buffer-tags
9686 (with-current-buffer buf
9687 (org-get-buffer-tags)))))
9688 (quit (setq tg "")))
9689 (when (string-match "\\S-" tg)
9690 (add-to-list 'buffer-tags (list tg))
9691 (if (member tg current)
9692 (setq current (delete tg current))
9693 (push tg current)))
9694 (if exit-after-next (setq exit-after-next 'now)))
9695 ((setq e (rassoc c todo-table) tg (car e))
9696 (with-current-buffer buf
9697 (save-excursion (org-todo tg)))
9698 (if exit-after-next (setq exit-after-next 'now)))
9699 ((setq e (rassoc c ntable) tg (car e))
9700 (if (member tg current)
9701 (setq current (delete tg current))
9702 (loop for g in groups do
9703 (if (member tg g)
9704 (mapc (lambda (x)
9705 (setq current (delete x current)))
9706 g)))
9707 (push tg current))
9708 (if exit-after-next (setq exit-after-next 'now))))
9710 ;; Create a sorted list
9711 (setq current
9712 (sort current
9713 (lambda (a b)
9714 (assoc b (cdr (memq (assoc a ntable) ntable))))))
9715 (if (eq exit-after-next 'now) (throw 'exit t))
9716 (goto-char (point-min))
9717 (beginning-of-line 2)
9718 (delete-region (point) (point-at-eol))
9719 (org-fast-tag-insert "Current" current c-face)
9720 (org-set-current-tags-overlay current ov-prefix)
9721 (while (re-search-forward
9722 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
9723 (setq tg (match-string 1))
9724 (add-text-properties
9725 (match-beginning 1) (match-end 1)
9726 (list 'face
9727 (cond
9728 ((member tg current) c-face)
9729 ((member tg inherited) i-face)
9730 (t (get-text-property (match-beginning 1) 'face))))))
9731 (goto-char (point-min)))))
9732 (org-detach-overlay org-tags-overlay)
9733 (if rtn
9734 (mapconcat 'identity current ":")
9735 nil))))
9737 (defun org-get-tags-string ()
9738 "Get the TAGS string in the current headline."
9739 (unless (org-on-heading-p t)
9740 (error "Not on a heading"))
9741 (save-excursion
9742 (beginning-of-line 1)
9743 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9744 (org-match-string-no-properties 1)
9745 "")))
9747 (defun org-get-tags ()
9748 "Get the list of tags specified in the current headline."
9749 (org-split-string (org-get-tags-string) ":"))
9751 (defun org-get-buffer-tags ()
9752 "Get a table of all tags used in the buffer, for completion."
9753 (let (tags)
9754 (save-excursion
9755 (goto-char (point-min))
9756 (while (re-search-forward
9757 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
9758 (when (equal (char-after (point-at-bol 0)) ?*)
9759 (mapc (lambda (x) (add-to-list 'tags x))
9760 (org-split-string (org-match-string-no-properties 1) ":")))))
9761 (mapcar 'list tags)))
9763 ;;;; The mapping API
9765 ;;;###autoload
9766 (defun org-map-entries (func &optional match scope &rest skip)
9767 "Call FUNC at each headline selected by MATCH in SCOPE.
9769 FUNC is a function or a lisp form. The function will be called without
9770 arguments, with the cursor positioned at the beginning of the headline.
9771 The return values of all calls to the function will be collected and
9772 returned as a list.
9774 MATCH is a tags/property/todo match as it is used in the agenda tags view.
9775 Only headlines that are matched by this query will be considered during
9776 the iteration. When MATCH is nil or t, all headlines will be
9777 visited by the iteration.
9779 SCOPE determines the scope of this command. It can be any of:
9781 nil The current buffer, respecting the restriction if any
9782 tree The subtree started with the entry at point
9783 file The current buffer, without restriction
9784 file-with-archives
9785 The current buffer, and any archives associated with it
9786 agenda All agenda files
9787 agenda-with-archives
9788 All agenda files with any archive files associated with them
9789 \(file1 file2 ...)
9790 If this is a list, all files in the list will be scanned
9792 The remaining args are treated as settings for the skipping facilities of
9793 the scanner. The following items can be given here:
9795 archive skip trees with the archive tag.
9796 comment skip trees with the COMMENT keyword
9797 function or Emacs Lisp form:
9798 will be used as value for `org-agenda-skip-function', so whenever
9799 the the function returns t, FUNC will not be called for that
9800 entry and search will continue from the point where the
9801 function leaves it."
9802 (let* ((org-agenda-archives-mode nil) ; just to make sure
9803 (org-agenda-skip-archived-trees (memq 'archive skip))
9804 (org-agenda-skip-comment-trees (memq 'comment skip))
9805 (org-agenda-skip-function
9806 (car (org-delete-all '(comment archive) skip)))
9807 (org-tags-match-list-sublevels t)
9808 matcher pos file
9809 org-todo-keywords-for-agenda
9810 org-done-keywords-for-agenda
9811 org-todo-keyword-alist-for-agenda
9812 org-tag-alist-for-agenda)
9814 (cond
9815 ((eq match t) (setq matcher t))
9816 ((eq match nil) (setq matcher t))
9817 (t (setq matcher (if match (org-make-tags-matcher match) t))))
9819 (when (eq scope 'tree)
9820 (org-back-to-heading t)
9821 (org-narrow-to-subtree)
9822 (setq scope nil))
9824 (if (not scope)
9825 (progn
9826 (org-prepare-agenda-buffers
9827 (list (buffer-file-name (current-buffer))))
9828 (org-scan-tags func matcher))
9829 ;; Get the right scope
9830 (setq pos (point))
9831 (cond
9832 ((and scope (listp scope) (symbolp (car scope)))
9833 (setq scope (eval scope)))
9834 ((eq scope 'agenda)
9835 (setq scope (org-agenda-files t)))
9836 ((eq scope 'agenda-with-archives)
9837 (setq scope (org-agenda-files t))
9838 (setq scope (org-add-archive-files scope)))
9839 ((eq scope 'file)
9840 (setq scope (list (buffer-file-name))))
9841 ((eq scope 'file-with-archives)
9842 (setq scope (org-add-archive-files (list (buffer-file-name))))))
9843 (org-prepare-agenda-buffers scope)
9844 (while (setq file (pop scope))
9845 (with-current-buffer (org-find-base-buffer-visiting file)
9846 (save-excursion
9847 (save-restriction
9848 (widen)
9849 (goto-char (point-min))
9850 (org-scan-tags func matcher))))))))
9852 ;;;; Properties
9854 ;;; Setting and retrieving properties
9856 (defconst org-special-properties
9857 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
9858 "TIMESTAMP" "TIMESTAMP_IA")
9859 "The special properties valid in Org-mode.
9861 These are properties that are not defined in the property drawer,
9862 but in some other way.")
9864 (defconst org-default-properties
9865 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
9866 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
9867 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
9868 "EXPORT_FILE_NAME" "EXPORT_TITLE")
9869 "Some properties that are used by Org-mode for various purposes.
9870 Being in this list makes sure that they are offered for completion.")
9872 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
9873 "Regular expression matching the first line of a property drawer.")
9875 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
9876 "Regular expression matching the first line of a property drawer.")
9878 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
9879 "Regular expression matching the first line of a property drawer.")
9881 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
9882 "Regular expression matching the first line of a property drawer.")
9884 (defconst org-property-drawer-re
9885 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
9886 org-property-end-re "\\)\n?")
9887 "Matches an entire property drawer.")
9889 (defconst org-clock-drawer-re
9890 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
9891 org-property-end-re "\\)\n?")
9892 "Matches an entire clock drawer.")
9894 (defun org-property-action ()
9895 "Do an action on properties."
9896 (interactive)
9897 (let (c)
9898 (org-at-property-p)
9899 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
9900 (setq c (read-char-exclusive))
9901 (cond
9902 ((equal c ?s)
9903 (call-interactively 'org-set-property))
9904 ((equal c ?d)
9905 (call-interactively 'org-delete-property))
9906 ((equal c ?D)
9907 (call-interactively 'org-delete-property-globally))
9908 ((equal c ?c)
9909 (call-interactively 'org-compute-property-at-point))
9910 (t (error "No such property action %c" c)))))
9912 (defun org-at-property-p ()
9913 "Is the cursor in a property line?"
9914 ;; FIXME: Does not check if we are actually in the drawer.
9915 ;; FIXME: also returns true on any drawers.....
9916 ;; This is used by C-c C-c for property action.
9917 (save-excursion
9918 (beginning-of-line 1)
9919 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
9921 (defun org-get-property-block (&optional beg end force)
9922 "Return the (beg . end) range of the body of the property drawer.
9923 BEG and END can be beginning and end of subtree, if not given
9924 they will be found.
9925 If the drawer does not exist and FORCE is non-nil, create the drawer."
9926 (catch 'exit
9927 (save-excursion
9928 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
9929 (end (or end (progn (outline-next-heading) (point)))))
9930 (goto-char beg)
9931 (if (re-search-forward org-property-start-re end t)
9932 (setq beg (1+ (match-end 0)))
9933 (if force
9934 (save-excursion
9935 (org-insert-property-drawer)
9936 (setq end (progn (outline-next-heading) (point))))
9937 (throw 'exit nil))
9938 (goto-char beg)
9939 (if (re-search-forward org-property-start-re end t)
9940 (setq beg (1+ (match-end 0)))))
9941 (if (re-search-forward org-property-end-re end t)
9942 (setq end (match-beginning 0))
9943 (or force (throw 'exit nil))
9944 (goto-char beg)
9945 (setq end beg)
9946 (org-indent-line-function)
9947 (insert ":END:\n"))
9948 (cons beg end)))))
9950 (defun org-entry-properties (&optional pom which)
9951 "Get all properties of the entry at point-or-marker POM.
9952 This includes the TODO keyword, the tags, time strings for deadline,
9953 scheduled, and clocking, and any additional properties defined in the
9954 entry. The return value is an alist, keys may occur multiple times
9955 if the property key was used several times.
9956 POM may also be nil, in which case the current entry is used.
9957 If WHICH is nil or `all', get all properties. If WHICH is
9958 `special' or `standard', only get that subclass."
9959 (setq which (or which 'all))
9960 (org-with-point-at pom
9961 (let ((clockstr (substring org-clock-string 0 -1))
9962 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
9963 beg end range props sum-props key value string clocksum)
9964 (save-excursion
9965 (when (condition-case nil (org-back-to-heading t) (error nil))
9966 (setq beg (point))
9967 (setq sum-props (get-text-property (point) 'org-summaries))
9968 (setq clocksum (get-text-property (point) :org-clock-minutes))
9969 (outline-next-heading)
9970 (setq end (point))
9971 (when (memq which '(all special))
9972 ;; Get the special properties, like TODO and tags
9973 (goto-char beg)
9974 (when (and (looking-at org-todo-line-regexp) (match-end 2))
9975 (push (cons "TODO" (org-match-string-no-properties 2)) props))
9976 (when (looking-at org-priority-regexp)
9977 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
9978 (when (and (setq value (org-get-tags-string))
9979 (string-match "\\S-" value))
9980 (push (cons "TAGS" value) props))
9981 (when (setq value (org-get-tags-at))
9982 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
9983 props))
9984 (while (re-search-forward org-maybe-keyword-time-regexp end t)
9985 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
9986 string (if (equal key clockstr)
9987 (org-no-properties
9988 (org-trim
9989 (buffer-substring
9990 (match-beginning 3) (goto-char (point-at-eol)))))
9991 (substring (org-match-string-no-properties 3) 1 -1)))
9992 (unless key
9993 (if (= (char-after (match-beginning 3)) ?\[)
9994 (setq key "TIMESTAMP_IA")
9995 (setq key "TIMESTAMP")))
9996 (when (or (equal key clockstr) (not (assoc key props)))
9997 (push (cons key string) props)))
10001 (when (memq which '(all standard))
10002 ;; Get the standard properties, like :PORP: ...
10003 (setq range (org-get-property-block beg end))
10004 (when range
10005 (goto-char (car range))
10006 (while (re-search-forward
10007 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
10008 (cdr range) t)
10009 (setq key (org-match-string-no-properties 1)
10010 value (org-trim (or (org-match-string-no-properties 2) "")))
10011 (unless (member key excluded)
10012 (push (cons key (or value "")) props)))))
10013 (if clocksum
10014 (push (cons "CLOCKSUM"
10015 (org-columns-number-to-string (/ (float clocksum) 60.)
10016 'add_times))
10017 props))
10018 (unless (assoc "CATEGORY" props)
10019 (setq value (or (org-get-category)
10020 (progn (org-refresh-category-properties)
10021 (org-get-category))))
10022 (push (cons "CATEGORY" value) props))
10023 (append sum-props (nreverse props)))))))
10025 (defun org-entry-get (pom property &optional inherit)
10026 "Get value of PROPERTY for entry at point-or-marker POM.
10027 If INHERIT is non-nil and the entry does not have the property,
10028 then also check higher levels of the hierarchy.
10029 If INHERIT is the symbol `selective', use inheritance only if the setting
10030 in `org-use-property-inheritance' selects PROPERTY for inheritance.
10031 If the property is present but empty, the return value is the empty string.
10032 If the property is not present at all, nil is returned."
10033 (org-with-point-at pom
10034 (if (and inherit (if (eq inherit 'selective)
10035 (org-property-inherit-p property)
10037 (org-entry-get-with-inheritance property)
10038 (if (member property org-special-properties)
10039 ;; We need a special property. Use brute force, get all properties.
10040 (cdr (assoc property (org-entry-properties nil 'special)))
10041 (let ((range (org-get-property-block)))
10042 (if (and range
10043 (goto-char (car range))
10044 (re-search-forward
10045 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
10046 (cdr range) t))
10047 ;; Found the property, return it.
10048 (if (match-end 1)
10049 (org-match-string-no-properties 1)
10050 "")))))))
10052 (defun org-property-or-variable-value (var &optional inherit)
10053 "Check if there is a property fixing the value of VAR.
10054 If yes, return this value. If not, return the current value of the variable."
10055 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
10056 (if (and prop (stringp prop) (string-match "\\S-" prop))
10057 (read prop)
10058 (symbol-value var))))
10060 (defun org-entry-delete (pom property)
10061 "Delete the property PROPERTY from entry at point-or-marker POM."
10062 (org-with-point-at pom
10063 (if (member property org-special-properties)
10064 nil ; cannot delete these properties.
10065 (let ((range (org-get-property-block)))
10066 (if (and range
10067 (goto-char (car range))
10068 (re-search-forward
10069 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
10070 (cdr range) t))
10071 (progn
10072 (delete-region (match-beginning 0) (1+ (point-at-eol)))
10074 nil)))))
10076 ;; Multi-values properties are properties that contain multiple values
10077 ;; These values are assumed to be single words, separated by whitespace.
10078 (defun org-entry-add-to-multivalued-property (pom property value)
10079 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
10080 (let* ((old (org-entry-get pom property))
10081 (values (and old (org-split-string old "[ \t]"))))
10082 (setq value (org-entry-protect-space value))
10083 (unless (member value values)
10084 (setq values (cons value values))
10085 (org-entry-put pom property
10086 (mapconcat 'identity values " ")))))
10088 (defun org-entry-remove-from-multivalued-property (pom property value)
10089 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
10090 (let* ((old (org-entry-get pom property))
10091 (values (and old (org-split-string old "[ \t]"))))
10092 (setq value (org-entry-protect-space value))
10093 (when (member value values)
10094 (setq values (delete value values))
10095 (org-entry-put pom property
10096 (mapconcat 'identity values " ")))))
10098 (defun org-entry-member-in-multivalued-property (pom property value)
10099 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
10100 (let* ((old (org-entry-get pom property))
10101 (values (and old (org-split-string old "[ \t]"))))
10102 (setq value (org-entry-protect-space value))
10103 (member value values)))
10105 (defun org-entry-get-multivalued-property (pom property)
10106 "Return a list of values in a multivalued property."
10107 (let* ((value (org-entry-get pom property))
10108 (values (and value (org-split-string value "[ \t]"))))
10109 (mapcar 'org-entry-restore-space values)))
10111 (defun org-entry-put-multivalued-property (pom property &rest values)
10112 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
10113 VALUES should be a list of strings. Spaces will be protected."
10114 (org-entry-put pom property
10115 (mapconcat 'org-entry-protect-space values " "))
10116 (let* ((value (org-entry-get pom property))
10117 (values (and value (org-split-string value "[ \t]"))))
10118 (mapcar 'org-entry-restore-space values)))
10120 (defun org-entry-protect-space (s)
10121 "Protect spaces and newline in string S."
10122 (while (string-match " " s)
10123 (setq s (replace-match "%20" t t s)))
10124 (while (string-match "\n" s)
10125 (setq s (replace-match "%0A" t t s)))
10128 (defun org-entry-restore-space (s)
10129 "Restore spaces and newline in string S."
10130 (while (string-match "%20" s)
10131 (setq s (replace-match " " t t s)))
10132 (while (string-match "%0A" s)
10133 (setq s (replace-match "\n" t t s)))
10136 (defvar org-entry-property-inherited-from (make-marker)
10137 "Marker pointing to the entry from where a proerty was inherited.
10138 Each call to `org-entry-get-with-inheritance' will set this marker to the
10139 location of the entry where the inheriance search matched. If there was
10140 no match, the marker will point nowhere.
10141 Note that also `org-entry-get' calls this function, if the INHERIT flag
10142 is set.")
10144 (defun org-entry-get-with-inheritance (property)
10145 "Get entry property, and search higher levels if not present."
10146 (move-marker org-entry-property-inherited-from nil)
10147 (let (tmp)
10148 (save-excursion
10149 (save-restriction
10150 (widen)
10151 (catch 'ex
10152 (while t
10153 (when (setq tmp (org-entry-get nil property))
10154 (org-back-to-heading t)
10155 (move-marker org-entry-property-inherited-from (point))
10156 (throw 'ex tmp))
10157 (or (org-up-heading-safe) (throw 'ex nil)))))
10158 (or tmp
10159 (cdr (assoc property org-file-properties))
10160 (cdr (assoc property org-global-properties))
10161 (cdr (assoc property org-global-properties-fixed))))))
10163 (defun org-entry-put (pom property value)
10164 "Set PROPERTY to VALUE for entry at point-or-marker POM."
10165 (org-with-point-at pom
10166 (org-back-to-heading t)
10167 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
10168 range)
10169 (cond
10170 ((equal property "TODO")
10171 (when (and (stringp value) (string-match "\\S-" value)
10172 (not (member value org-todo-keywords-1)))
10173 (error "\"%s\" is not a valid TODO state" value))
10174 (if (or (not value)
10175 (not (string-match "\\S-" value)))
10176 (setq value 'none))
10177 (org-todo value)
10178 (org-set-tags nil 'align))
10179 ((equal property "PRIORITY")
10180 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
10181 (string-to-char value) ?\ ))
10182 (org-set-tags nil 'align))
10183 ((equal property "SCHEDULED")
10184 (if (re-search-forward org-scheduled-time-regexp end t)
10185 (cond
10186 ((eq value 'earlier) (org-timestamp-change -1 'day))
10187 ((eq value 'later) (org-timestamp-change 1 'day))
10188 (t (call-interactively 'org-schedule)))
10189 (call-interactively 'org-schedule)))
10190 ((equal property "DEADLINE")
10191 (if (re-search-forward org-deadline-time-regexp end t)
10192 (cond
10193 ((eq value 'earlier) (org-timestamp-change -1 'day))
10194 ((eq value 'later) (org-timestamp-change 1 'day))
10195 (t (call-interactively 'org-deadline)))
10196 (call-interactively 'org-deadline)))
10197 ((member property org-special-properties)
10198 (error "The %s property can not yet be set with `org-entry-put'"
10199 property))
10200 (t ; a non-special property
10201 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
10202 (setq range (org-get-property-block beg end 'force))
10203 (goto-char (car range))
10204 (if (re-search-forward
10205 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
10206 (progn
10207 (delete-region (match-beginning 1) (match-end 1))
10208 (goto-char (match-beginning 1)))
10209 (goto-char (cdr range))
10210 (insert "\n")
10211 (backward-char 1)
10212 (org-indent-line-function)
10213 (insert ":" property ":"))
10214 (and value (insert " " value))
10215 (org-indent-line-function)))))))
10217 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
10218 "Get all property keys in the current buffer.
10219 With INCLUDE-SPECIALS, also list the special properties that relect things
10220 like tags and TODO state.
10221 With INCLUDE-DEFAULTS, also include properties that has special meaning
10222 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
10223 With INCLUDE-COLUMNS, also include property names given in COLUMN
10224 formats in the current buffer."
10225 (let (rtn range cfmt cols s p)
10226 (save-excursion
10227 (save-restriction
10228 (widen)
10229 (goto-char (point-min))
10230 (while (re-search-forward org-property-start-re nil t)
10231 (setq range (org-get-property-block))
10232 (goto-char (car range))
10233 (while (re-search-forward
10234 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
10235 (cdr range) t)
10236 (add-to-list 'rtn (org-match-string-no-properties 1)))
10237 (outline-next-heading))))
10239 (when include-specials
10240 (setq rtn (append org-special-properties rtn)))
10242 (when include-defaults
10243 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
10245 (when include-columns
10246 (save-excursion
10247 (save-restriction
10248 (widen)
10249 (goto-char (point-min))
10250 (while (re-search-forward
10251 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
10252 nil t)
10253 (setq cfmt (match-string 2) s 0)
10254 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
10255 cfmt s)
10256 (setq s (match-end 0)
10257 p (match-string 1 cfmt))
10258 (unless (or (equal p "ITEM")
10259 (member p org-special-properties))
10260 (add-to-list 'rtn (match-string 1 cfmt))))))))
10262 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
10264 (defun org-property-values (key)
10265 "Return a list of all values of property KEY."
10266 (save-excursion
10267 (save-restriction
10268 (widen)
10269 (goto-char (point-min))
10270 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
10271 values)
10272 (while (re-search-forward re nil t)
10273 (add-to-list 'values (org-trim (match-string 1))))
10274 (delete "" values)))))
10276 (defun org-insert-property-drawer ()
10277 "Insert a property drawer into the current entry."
10278 (interactive)
10279 (org-back-to-heading t)
10280 (looking-at outline-regexp)
10281 (let ((indent (- (match-end 0)(match-beginning 0)))
10282 (beg (point))
10283 (re (concat "^[ \t]*" org-keyword-time-regexp))
10284 end hiddenp)
10285 (outline-next-heading)
10286 (setq end (point))
10287 (goto-char beg)
10288 (while (re-search-forward re end t))
10289 (setq hiddenp (org-invisible-p))
10290 (end-of-line 1)
10291 (and (equal (char-after) ?\n) (forward-char 1))
10292 (while (looking-at "^[ \t]*\\(:CLOCK:\\|CLOCK\\|:END:\\)")
10293 (beginning-of-line 2))
10294 (org-skip-over-state-notes)
10295 (skip-chars-backward " \t\n\r")
10296 (if (eq (char-before) ?*) (forward-char 1))
10297 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
10298 (beginning-of-line 0)
10299 (org-indent-to-column indent)
10300 (beginning-of-line 2)
10301 (org-indent-to-column indent)
10302 (beginning-of-line 0)
10303 (if hiddenp
10304 (save-excursion
10305 (org-back-to-heading t)
10306 (hide-entry))
10307 (org-flag-drawer t))))
10309 (defun org-set-property (property value)
10310 "In the current entry, set PROPERTY to VALUE.
10311 When called interactively, this will prompt for a property name, offering
10312 completion on existing and default properties. And then it will prompt
10313 for a value, offering competion either on allowed values (via an inherited
10314 xxx_ALL property) or on existing values in other instances of this property
10315 in the current file."
10316 (interactive
10317 (let* ((completion-ignore-case t)
10318 (keys (org-buffer-property-keys nil t t))
10319 (prop0 (completing-read "Property: " (mapcar 'list keys)))
10320 (prop (if (member prop0 keys)
10321 prop0
10322 (or (cdr (assoc (downcase prop0)
10323 (mapcar (lambda (x) (cons (downcase x) x))
10324 keys)))
10325 prop0)))
10326 (cur (org-entry-get nil prop))
10327 (allowed (org-property-get-allowed-values nil prop 'table))
10328 (existing (mapcar 'list (org-property-values prop)))
10329 (val (if allowed
10330 (org-completing-read "Value: " allowed nil 'req-match)
10331 (org-completing-read
10332 (concat "Value" (if (and cur (string-match "\\S-" cur))
10333 (concat "[" cur "]") "")
10334 ": ")
10335 existing nil nil "" nil cur))))
10336 (list prop (if (equal val "") cur val))))
10337 (unless (equal (org-entry-get nil property) value)
10338 (org-entry-put nil property value)))
10340 (defun org-delete-property (property)
10341 "In the current entry, delete PROPERTY."
10342 (interactive
10343 (let* ((completion-ignore-case t)
10344 (prop (completing-read
10345 "Property: " (org-entry-properties nil 'standard))))
10346 (list prop)))
10347 (message "Property %s %s" property
10348 (if (org-entry-delete nil property)
10349 "deleted"
10350 "was not present in the entry")))
10352 (defun org-delete-property-globally (property)
10353 "Remove PROPERTY globally, from all entries."
10354 (interactive
10355 (let* ((completion-ignore-case t)
10356 (prop (completing-read
10357 "Globally remove property: "
10358 (mapcar 'list (org-buffer-property-keys)))))
10359 (list prop)))
10360 (save-excursion
10361 (save-restriction
10362 (widen)
10363 (goto-char (point-min))
10364 (let ((cnt 0))
10365 (while (re-search-forward
10366 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
10367 nil t)
10368 (setq cnt (1+ cnt))
10369 (replace-match ""))
10370 (message "Property \"%s\" removed from %d entries" property cnt)))))
10372 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
10374 (defun org-compute-property-at-point ()
10375 "Compute the property at point.
10376 This looks for an enclosing column format, extracts the operator and
10377 then applies it to the proerty in the column format's scope."
10378 (interactive)
10379 (unless (org-at-property-p)
10380 (error "Not at a property"))
10381 (let ((prop (org-match-string-no-properties 2)))
10382 (org-columns-get-format-and-top-level)
10383 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
10384 (error "No operator defined for property %s" prop))
10385 (org-columns-compute prop)))
10387 (defun org-property-get-allowed-values (pom property &optional table)
10388 "Get allowed values for the property PROPERTY.
10389 When TABLE is non-nil, return an alist that can directly be used for
10390 completion."
10391 (let (vals)
10392 (cond
10393 ((equal property "TODO")
10394 (setq vals (org-with-point-at pom
10395 (append org-todo-keywords-1 '("")))))
10396 ((equal property "PRIORITY")
10397 (let ((n org-lowest-priority))
10398 (while (>= n org-highest-priority)
10399 (push (char-to-string n) vals)
10400 (setq n (1- n)))))
10401 ((member property org-special-properties))
10403 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
10405 (when (and vals (string-match "\\S-" vals))
10406 (setq vals (car (read-from-string (concat "(" vals ")"))))
10407 (setq vals (mapcar (lambda (x)
10408 (cond ((stringp x) x)
10409 ((numberp x) (number-to-string x))
10410 ((symbolp x) (symbol-name x))
10411 (t "???")))
10412 vals)))))
10413 (if table (mapcar 'list vals) vals)))
10415 (defun org-property-previous-allowed-value (&optional previous)
10416 "Switch to the next allowed value for this property."
10417 (interactive)
10418 (org-property-next-allowed-value t))
10420 (defun org-property-next-allowed-value (&optional previous)
10421 "Switch to the next allowed value for this property."
10422 (interactive)
10423 (unless (org-at-property-p)
10424 (error "Not at a property"))
10425 (let* ((key (match-string 2))
10426 (value (match-string 3))
10427 (allowed (or (org-property-get-allowed-values (point) key)
10428 (and (member value '("[ ]" "[-]" "[X]"))
10429 '("[ ]" "[X]"))))
10430 nval)
10431 (unless allowed
10432 (error "Allowed values for this property have not been defined"))
10433 (if previous (setq allowed (reverse allowed)))
10434 (if (member value allowed)
10435 (setq nval (car (cdr (member value allowed)))))
10436 (setq nval (or nval (car allowed)))
10437 (if (equal nval value)
10438 (error "Only one allowed value for this property"))
10439 (org-at-property-p)
10440 (replace-match (concat " :" key ": " nval) t t)
10441 (org-indent-line-function)
10442 (beginning-of-line 1)
10443 (skip-chars-forward " \t")))
10445 (defun org-find-entry-with-id (ident)
10446 "Locate the entry that contains the ID property with exact value IDENT.
10447 IDENT can be a string, a symbol or a number, this function will search for
10448 the string representation of it.
10449 Return the position where this entry starts, or nil if there is no such entry."
10450 (let ((id (cond
10451 ((stringp ident) ident)
10452 ((symbol-name ident) (symbol-name ident))
10453 ((numberp ident) (number-to-string ident))
10454 (t (error "IDENT %s must be a string, symbol or number" ident))))
10455 (case-fold-search nil))
10456 (save-excursion
10457 (save-restriction
10458 (widen)
10459 (goto-char (point-min))
10460 (when (re-search-forward
10461 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
10462 nil t)
10463 (org-back-to-heading)
10464 (point))))))
10466 ;;;; Timestamps
10468 (defvar org-last-changed-timestamp nil)
10469 (defvar org-last-inserted-timestamp nil
10470 "The last time stamp inserted with `org-insert-time-stamp'.")
10471 (defvar org-time-was-given) ; dynamically scoped parameter
10472 (defvar org-end-time-was-given) ; dynamically scoped parameter
10473 (defvar org-ts-what) ; dynamically scoped parameter
10475 (defun org-time-stamp (arg &optional inactive)
10476 "Prompt for a date/time and insert a time stamp.
10477 If the user specifies a time like HH:MM, or if this command is called
10478 with a prefix argument, the time stamp will contain date and time.
10479 Otherwise, only the date will be included. All parts of a date not
10480 specified by the user will be filled in from the current date/time.
10481 So if you press just return without typing anything, the time stamp
10482 will represent the current date/time. If there is already a timestamp
10483 at the cursor, it will be modified."
10484 (interactive "P")
10485 (let* ((ts nil)
10486 (default-time
10487 ;; Default time is either today, or, when entering a range,
10488 ;; the range start.
10489 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
10490 (save-excursion
10491 (re-search-backward
10492 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
10493 (- (point) 20) t)))
10494 (apply 'encode-time (org-parse-time-string (match-string 1)))
10495 (current-time)))
10496 (default-input (and ts (org-get-compact-tod ts)))
10497 org-time-was-given org-end-time-was-given time)
10498 (cond
10499 ((and (org-at-timestamp-p t)
10500 (memq last-command '(org-time-stamp org-time-stamp-inactive))
10501 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
10502 (insert "--")
10503 (setq time (let ((this-command this-command))
10504 (org-read-date arg 'totime nil nil
10505 default-time default-input)))
10506 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
10507 ((org-at-timestamp-p t)
10508 (setq time (let ((this-command this-command))
10509 (org-read-date arg 'totime nil nil default-time default-input)))
10510 (when (org-at-timestamp-p t) ; just to get the match data
10511 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
10512 (replace-match "")
10513 (setq org-last-changed-timestamp
10514 (org-insert-time-stamp
10515 time (or org-time-was-given arg)
10516 inactive nil nil (list org-end-time-was-given))))
10517 (message "Timestamp updated"))
10519 (setq time (let ((this-command this-command))
10520 (org-read-date arg 'totime nil nil default-time default-input)))
10521 (org-insert-time-stamp time (or org-time-was-given arg) inactive
10522 nil nil (list org-end-time-was-given))))))
10524 ;; FIXME: can we use this for something else, like computing time differences?
10525 (defun org-get-compact-tod (s)
10526 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
10527 (let* ((t1 (match-string 1 s))
10528 (h1 (string-to-number (match-string 2 s)))
10529 (m1 (string-to-number (match-string 3 s)))
10530 (t2 (and (match-end 4) (match-string 5 s)))
10531 (h2 (and t2 (string-to-number (match-string 6 s))))
10532 (m2 (and t2 (string-to-number (match-string 7 s))))
10533 dh dm)
10534 (if (not t2)
10536 (setq dh (- h2 h1) dm (- m2 m1))
10537 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
10538 (concat t1 "+" (number-to-string dh)
10539 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
10541 (defun org-time-stamp-inactive (&optional arg)
10542 "Insert an inactive time stamp.
10543 An inactive time stamp is enclosed in square brackets instead of angle
10544 brackets. It is inactive in the sense that it does not trigger agenda entries,
10545 does not link to the calendar and cannot be changed with the S-cursor keys.
10546 So these are more for recording a certain time/date."
10547 (interactive "P")
10548 (org-time-stamp arg 'inactive))
10550 (defvar org-date-ovl (org-make-overlay 1 1))
10551 (org-overlay-put org-date-ovl 'face 'org-warning)
10552 (org-detach-overlay org-date-ovl)
10554 (defvar org-ans1) ; dynamically scoped parameter
10555 (defvar org-ans2) ; dynamically scoped parameter
10557 (defvar org-plain-time-of-day-regexp) ; defined below
10559 (defvar org-overriding-default-time nil) ; dynamically scoped
10560 (defvar org-read-date-overlay nil)
10561 (defvar org-dcst nil) ; dynamically scoped
10563 (defun org-read-date (&optional with-time to-time from-string prompt
10564 default-time default-input)
10565 "Read a date, possibly a time, and make things smooth for the user.
10566 The prompt will suggest to enter an ISO date, but you can also enter anything
10567 which will at least partially be understood by `parse-time-string'.
10568 Unrecognized parts of the date will default to the current day, month, year,
10569 hour and minute. If this command is called to replace a timestamp at point,
10570 of to enter the second timestamp of a range, the default time is taken from the
10571 existing stamp. For example,
10572 3-2-5 --> 2003-02-05
10573 feb 15 --> currentyear-02-15
10574 sep 12 9 --> 2009-09-12
10575 12:45 --> today 12:45
10576 22 sept 0:34 --> currentyear-09-22 0:34
10577 12 --> currentyear-currentmonth-12
10578 Fri --> nearest Friday (today or later)
10579 etc.
10581 Furthermore you can specify a relative date by giving, as the *first* thing
10582 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
10583 change in days weeks, months, years.
10584 With a single plus or minus, the date is relative to today. With a double
10585 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
10586 +4d --> four days from today
10587 +4 --> same as above
10588 +2w --> two weeks from today
10589 ++5 --> five days from default date
10591 The function understands only English month and weekday abbreviations,
10592 but this can be configured with the variables `parse-time-months' and
10593 `parse-time-weekdays'.
10595 While prompting, a calendar is popped up - you can also select the
10596 date with the mouse (button 1). The calendar shows a period of three
10597 months. To scroll it to other months, use the keys `>' and `<'.
10598 If you don't like the calendar, turn it off with
10599 \(setq org-read-date-popup-calendar nil)
10601 With optional argument TO-TIME, the date will immediately be converted
10602 to an internal time.
10603 With an optional argument WITH-TIME, the prompt will suggest to also
10604 insert a time. Note that when WITH-TIME is not set, you can still
10605 enter a time, and this function will inform the calling routine about
10606 this change. The calling routine may then choose to change the format
10607 used to insert the time stamp into the buffer to include the time.
10608 With optional argument FROM-STRING, read from this string instead from
10609 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
10610 the time/date that is used for everything that is not specified by the
10611 user."
10612 (require 'parse-time)
10613 (let* ((org-time-stamp-rounding-minutes
10614 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
10615 (org-dcst org-display-custom-times)
10616 (ct (org-current-time))
10617 (def (or org-overriding-default-time default-time ct))
10618 (defdecode (decode-time def))
10619 (dummy (progn
10620 (when (< (nth 2 defdecode) org-extend-today-until)
10621 (setcar (nthcdr 2 defdecode) -1)
10622 (setcar (nthcdr 1 defdecode) 59)
10623 (setq def (apply 'encode-time defdecode)
10624 defdecode (decode-time def)))))
10625 (calendar-move-hook nil)
10626 (calendar-view-diary-initially-flag nil)
10627 (view-diary-entries-initially nil)
10628 (calendar-view-holidays-initially-flag nil)
10629 (view-calendar-holidays-initially nil)
10630 (timestr (format-time-string
10631 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
10632 (prompt (concat (if prompt (concat prompt " ") "")
10633 (format "Date+time [%s]: " timestr)))
10634 ans (org-ans0 "") org-ans1 org-ans2 final)
10636 (cond
10637 (from-string (setq ans from-string))
10638 (org-read-date-popup-calendar
10639 (save-excursion
10640 (save-window-excursion
10641 (calendar)
10642 (calendar-forward-day (- (time-to-days def)
10643 (calendar-absolute-from-gregorian
10644 (calendar-current-date))))
10645 (org-eval-in-calendar nil t)
10646 (let* ((old-map (current-local-map))
10647 (map (copy-keymap calendar-mode-map))
10648 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
10649 (org-defkey map (kbd "RET") 'org-calendar-select)
10650 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
10651 'org-calendar-select-mouse)
10652 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
10653 'org-calendar-select-mouse)
10654 (org-defkey minibuffer-local-map [(meta shift left)]
10655 (lambda () (interactive)
10656 (org-eval-in-calendar '(calendar-backward-month 1))))
10657 (org-defkey minibuffer-local-map [(meta shift right)]
10658 (lambda () (interactive)
10659 (org-eval-in-calendar '(calendar-forward-month 1))))
10660 (org-defkey minibuffer-local-map [(meta shift up)]
10661 (lambda () (interactive)
10662 (org-eval-in-calendar '(calendar-backward-year 1))))
10663 (org-defkey minibuffer-local-map [(meta shift down)]
10664 (lambda () (interactive)
10665 (org-eval-in-calendar '(calendar-forward-year 1))))
10666 (org-defkey minibuffer-local-map [(shift up)]
10667 (lambda () (interactive)
10668 (org-eval-in-calendar '(calendar-backward-week 1))))
10669 (org-defkey minibuffer-local-map [(shift down)]
10670 (lambda () (interactive)
10671 (org-eval-in-calendar '(calendar-forward-week 1))))
10672 (org-defkey minibuffer-local-map [(shift left)]
10673 (lambda () (interactive)
10674 (org-eval-in-calendar '(calendar-backward-day 1))))
10675 (org-defkey minibuffer-local-map [(shift right)]
10676 (lambda () (interactive)
10677 (org-eval-in-calendar '(calendar-forward-day 1))))
10678 (org-defkey minibuffer-local-map ">"
10679 (lambda () (interactive)
10680 (org-eval-in-calendar '(scroll-calendar-left 1))))
10681 (org-defkey minibuffer-local-map "<"
10682 (lambda () (interactive)
10683 (org-eval-in-calendar '(scroll-calendar-right 1))))
10684 (unwind-protect
10685 (progn
10686 (use-local-map map)
10687 (add-hook 'post-command-hook 'org-read-date-display)
10688 (setq org-ans0 (read-string prompt default-input nil nil))
10689 ;; org-ans0: from prompt
10690 ;; org-ans1: from mouse click
10691 ;; org-ans2: from calendar motion
10692 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
10693 (remove-hook 'post-command-hook 'org-read-date-display)
10694 (use-local-map old-map)
10695 (when org-read-date-overlay
10696 (org-delete-overlay org-read-date-overlay)
10697 (setq org-read-date-overlay nil)))))))
10699 (t ; Naked prompt only
10700 (unwind-protect
10701 (setq ans (read-string prompt default-input nil timestr))
10702 (when org-read-date-overlay
10703 (org-delete-overlay org-read-date-overlay)
10704 (setq org-read-date-overlay nil)))))
10706 (setq final (org-read-date-analyze ans def defdecode))
10708 (if to-time
10709 (apply 'encode-time final)
10710 (if (and (boundp 'org-time-was-given) org-time-was-given)
10711 (format "%04d-%02d-%02d %02d:%02d"
10712 (nth 5 final) (nth 4 final) (nth 3 final)
10713 (nth 2 final) (nth 1 final))
10714 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
10715 (defvar def)
10716 (defvar defdecode)
10717 (defvar with-time)
10718 (defun org-read-date-display ()
10719 "Display the currrent date prompt interpretation in the minibuffer."
10720 (when org-read-date-display-live
10721 (when org-read-date-overlay
10722 (org-delete-overlay org-read-date-overlay))
10723 (let ((p (point)))
10724 (end-of-line 1)
10725 (while (not (equal (buffer-substring
10726 (max (point-min) (- (point) 4)) (point))
10727 " "))
10728 (insert " "))
10729 (goto-char p))
10730 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
10731 " " (or org-ans1 org-ans2)))
10732 (org-end-time-was-given nil)
10733 (f (org-read-date-analyze ans def defdecode))
10734 (fmts (if org-dcst
10735 org-time-stamp-custom-formats
10736 org-time-stamp-formats))
10737 (fmt (if (or with-time
10738 (and (boundp 'org-time-was-given) org-time-was-given))
10739 (cdr fmts)
10740 (car fmts)))
10741 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
10742 (when (and org-end-time-was-given
10743 (string-match org-plain-time-of-day-regexp txt))
10744 (setq txt (concat (substring txt 0 (match-end 0)) "-"
10745 org-end-time-was-given
10746 (substring txt (match-end 0)))))
10747 (setq org-read-date-overlay
10748 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
10749 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
10751 (defun org-read-date-analyze (ans def defdecode)
10752 "Analyze the combined answer of the date prompt."
10753 ;; FIXME: cleanup and comment
10754 (let (delta deltan deltaw deltadef year month day
10755 hour minute second wday pm h2 m2 tl wday1
10756 iso-year iso-weekday iso-week iso-year iso-date)
10758 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
10759 (setq ans "+0"))
10761 (when (setq delta (org-read-date-get-relative ans (current-time) def))
10762 (setq ans (replace-match "" t t ans)
10763 deltan (car delta)
10764 deltaw (nth 1 delta)
10765 deltadef (nth 2 delta)))
10767 ;; Check if there is an iso week date in there
10768 ;; If yes, sore the info and ostpone interpreting it until the rest
10769 ;; of the parsing is done
10770 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
10771 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
10772 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
10773 iso-week (string-to-number (match-string 2 ans)))
10774 (setq ans (replace-match "" t t ans)))
10776 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
10777 (when (string-match
10778 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
10779 (setq year (if (match-end 2)
10780 (string-to-number (match-string 2 ans))
10781 (string-to-number (format-time-string "%Y")))
10782 month (string-to-number (match-string 3 ans))
10783 day (string-to-number (match-string 4 ans)))
10784 (if (< year 100) (setq year (+ 2000 year)))
10785 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
10786 t nil ans)))
10787 ;; Help matching am/pm times, because `parse-time-string' does not do that.
10788 ;; If there is a time with am/pm, and *no* time without it, we convert
10789 ;; so that matching will be successful.
10790 (loop for i from 1 to 2 do ; twice, for end time as well
10791 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
10792 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
10793 (setq hour (string-to-number (match-string 1 ans))
10794 minute (if (match-end 3)
10795 (string-to-number (match-string 3 ans))
10797 pm (equal ?p
10798 (string-to-char (downcase (match-string 4 ans)))))
10799 (if (and (= hour 12) (not pm))
10800 (setq hour 0)
10801 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
10802 (setq ans (replace-match (format "%02d:%02d" hour minute)
10803 t t ans))))
10805 ;; Check if a time range is given as a duration
10806 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
10807 (setq hour (string-to-number (match-string 1 ans))
10808 h2 (+ hour (string-to-number (match-string 3 ans)))
10809 minute (string-to-number (match-string 2 ans))
10810 m2 (+ minute (if (match-end 5) (string-to-number
10811 (match-string 5 ans))0)))
10812 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
10813 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
10814 t t ans)))
10816 ;; Check if there is a time range
10817 (when (boundp 'org-end-time-was-given)
10818 (setq org-time-was-given nil)
10819 (when (and (string-match org-plain-time-of-day-regexp ans)
10820 (match-end 8))
10821 (setq org-end-time-was-given (match-string 8 ans))
10822 (setq ans (concat (substring ans 0 (match-beginning 7))
10823 (substring ans (match-end 7))))))
10825 (setq tl (parse-time-string ans)
10826 day (or (nth 3 tl) (nth 3 defdecode))
10827 month (or (nth 4 tl)
10828 (if (and org-read-date-prefer-future
10829 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
10830 (1+ (nth 4 defdecode))
10831 (nth 4 defdecode)))
10832 year (or (nth 5 tl)
10833 (if (and org-read-date-prefer-future
10834 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
10835 (1+ (nth 5 defdecode))
10836 (nth 5 defdecode)))
10837 hour (or (nth 2 tl) (nth 2 defdecode))
10838 minute (or (nth 1 tl) (nth 1 defdecode))
10839 second (or (nth 0 tl) 0)
10840 wday (nth 6 tl))
10842 ;; Special date definitions below
10843 (cond
10844 (iso-week
10845 ;; There was an iso week
10846 (setq year (or iso-year year)
10847 day (or iso-weekday wday 1)
10848 wday nil ; to make sure that the trigger below does not match
10849 iso-date (calendar-gregorian-from-absolute
10850 (calendar-absolute-from-iso
10851 (list iso-week day year))))
10852 ; FIXME: Should we also push ISO weeks into the future?
10853 ; (when (and org-read-date-prefer-future
10854 ; (not iso-year)
10855 ; (< (calendar-absolute-from-gregorian iso-date)
10856 ; (time-to-days (current-time))))
10857 ; (setq year (1+ year)
10858 ; iso-date (calendar-gregorian-from-absolute
10859 ; (calendar-absolute-from-iso
10860 ; (list iso-week day year)))))
10861 (setq month (car iso-date)
10862 year (nth 2 iso-date)
10863 day (nth 1 iso-date)))
10864 (deltan
10865 (unless deltadef
10866 (let ((now (decode-time (current-time))))
10867 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
10868 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
10869 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
10870 ((equal deltaw "m") (setq month (+ month deltan)))
10871 ((equal deltaw "y") (setq year (+ year deltan)))))
10872 ((and wday (not (nth 3 tl)))
10873 ;; Weekday was given, but no day, so pick that day in the week
10874 ;; on or after the derived date.
10875 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
10876 (unless (equal wday wday1)
10877 (setq day (+ day (% (- wday wday1 -7) 7))))))
10878 (if (and (boundp 'org-time-was-given)
10879 (nth 2 tl))
10880 (setq org-time-was-given t))
10881 (if (< year 100) (setq year (+ 2000 year)))
10882 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
10883 (list second minute hour day month year)))
10885 (defvar parse-time-weekdays)
10887 (defun org-read-date-get-relative (s today default)
10888 "Check string S for special relative date string.
10889 TODAY and DEFAULT are internal times, for today and for a default.
10890 Return shift list (N what def-flag)
10891 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
10892 N is the number of WHATs to shift.
10893 DEF-FLAG is t when a double ++ or -- indicates shift relative to
10894 the DEFAULT date rather than TODAY."
10895 (when (and
10896 (string-match
10897 (concat
10898 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
10899 "\\([0-9]+\\)?"
10900 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
10901 "\\([ \t]\\|$\\)") s)
10902 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
10903 (let* ((dir (if (> (match-end 1) (match-beginning 1))
10904 (string-to-char (substring (match-string 1 s) -1))
10905 ?+))
10906 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
10907 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
10908 (what (if (match-end 3) (match-string 3 s) "d"))
10909 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
10910 (date (if rel default today))
10911 (wday (nth 6 (decode-time date)))
10912 delta)
10913 (if wday1
10914 (progn
10915 (setq delta (mod (+ 7 (- wday1 wday)) 7))
10916 (if (= dir ?-) (setq delta (- delta 7)))
10917 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
10918 (list delta "d" rel))
10919 (list (* n (if (= dir ?-) -1 1)) what rel)))))
10921 (defun org-eval-in-calendar (form &optional keepdate)
10922 "Eval FORM in the calendar window and return to current window.
10923 Also, store the cursor date in variable org-ans2."
10924 (let ((sw (selected-window)))
10925 (select-window (get-buffer-window "*Calendar*"))
10926 (eval form)
10927 (when (and (not keepdate) (calendar-cursor-to-date))
10928 (let* ((date (calendar-cursor-to-date))
10929 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10930 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
10931 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
10932 (select-window sw)))
10934 (defun org-calendar-select ()
10935 "Return to `org-read-date' with the date currently selected.
10936 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
10937 (interactive)
10938 (when (calendar-cursor-to-date)
10939 (let* ((date (calendar-cursor-to-date))
10940 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10941 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
10942 (if (active-minibuffer-window) (exit-minibuffer))))
10944 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
10945 "Insert a date stamp for the date given by the internal TIME.
10946 WITH-HM means, use the stamp format that includes the time of the day.
10947 INACTIVE means use square brackets instead of angular ones, so that the
10948 stamp will not contribute to the agenda.
10949 PRE and POST are optional strings to be inserted before and after the
10950 stamp.
10951 The command returns the inserted time stamp."
10952 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
10953 stamp)
10954 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
10955 (insert-before-markers (or pre ""))
10956 (insert-before-markers (setq stamp (format-time-string fmt time)))
10957 (when (listp extra)
10958 (setq extra (car extra))
10959 (if (and (stringp extra)
10960 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
10961 (setq extra (format "-%02d:%02d"
10962 (string-to-number (match-string 1 extra))
10963 (string-to-number (match-string 2 extra))))
10964 (setq extra nil)))
10965 (when extra
10966 (backward-char 1)
10967 (insert-before-markers extra)
10968 (forward-char 1))
10969 (insert-before-markers (or post ""))
10970 (setq org-last-inserted-timestamp stamp)))
10972 (defun org-toggle-time-stamp-overlays ()
10973 "Toggle the use of custom time stamp formats."
10974 (interactive)
10975 (setq org-display-custom-times (not org-display-custom-times))
10976 (unless org-display-custom-times
10977 (let ((p (point-min)) (bmp (buffer-modified-p)))
10978 (while (setq p (next-single-property-change p 'display))
10979 (if (and (get-text-property p 'display)
10980 (eq (get-text-property p 'face) 'org-date))
10981 (remove-text-properties
10982 p (setq p (next-single-property-change p 'display))
10983 '(display t))))
10984 (set-buffer-modified-p bmp)))
10985 (if (featurep 'xemacs)
10986 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
10987 (org-restart-font-lock)
10988 (setq org-table-may-need-update t)
10989 (if org-display-custom-times
10990 (message "Time stamps are overlayed with custom format")
10991 (message "Time stamp overlays removed")))
10993 (defun org-display-custom-time (beg end)
10994 "Overlay modified time stamp format over timestamp between BEG and END."
10995 (let* ((ts (buffer-substring beg end))
10996 t1 w1 with-hm tf time str w2 (off 0))
10997 (save-match-data
10998 (setq t1 (org-parse-time-string ts t))
10999 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
11000 (setq off (- (match-end 0) (match-beginning 0)))))
11001 (setq end (- end off))
11002 (setq w1 (- end beg)
11003 with-hm (and (nth 1 t1) (nth 2 t1))
11004 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
11005 time (org-fix-decoded-time t1)
11006 str (org-add-props
11007 (format-time-string
11008 (substring tf 1 -1) (apply 'encode-time time))
11009 nil 'mouse-face 'highlight)
11010 w2 (length str))
11011 (if (not (= w2 w1))
11012 (add-text-properties (1+ beg) (+ 2 beg)
11013 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
11014 (if (featurep 'xemacs)
11015 (progn
11016 (put-text-property beg end 'invisible t)
11017 (put-text-property beg end 'end-glyph (make-glyph str)))
11018 (put-text-property beg end 'display str))))
11020 (defun org-translate-time (string)
11021 "Translate all timestamps in STRING to custom format.
11022 But do this only if the variable `org-display-custom-times' is set."
11023 (when org-display-custom-times
11024 (save-match-data
11025 (let* ((start 0)
11026 (re org-ts-regexp-both)
11027 t1 with-hm inactive tf time str beg end)
11028 (while (setq start (string-match re string start))
11029 (setq beg (match-beginning 0)
11030 end (match-end 0)
11031 t1 (save-match-data
11032 (org-parse-time-string (substring string beg end) t))
11033 with-hm (and (nth 1 t1) (nth 2 t1))
11034 inactive (equal (substring string beg (1+ beg)) "[")
11035 tf (funcall (if with-hm 'cdr 'car)
11036 org-time-stamp-custom-formats)
11037 time (org-fix-decoded-time t1)
11038 str (format-time-string
11039 (concat
11040 (if inactive "[" "<") (substring tf 1 -1)
11041 (if inactive "]" ">"))
11042 (apply 'encode-time time))
11043 string (replace-match str t t string)
11044 start (+ start (length str)))))))
11045 string)
11047 (defun org-fix-decoded-time (time)
11048 "Set 0 instead of nil for the first 6 elements of time.
11049 Don't touch the rest."
11050 (let ((n 0))
11051 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
11053 (defun org-days-to-time (timestamp-string)
11054 "Difference between TIMESTAMP-STRING and now in days."
11055 (- (time-to-days (org-time-string-to-time timestamp-string))
11056 (time-to-days (current-time))))
11058 (defun org-deadline-close (timestamp-string &optional ndays)
11059 "Is the time in TIMESTAMP-STRING close to the current date?"
11060 (setq ndays (or ndays (org-get-wdays timestamp-string)))
11061 (and (< (org-days-to-time timestamp-string) ndays)
11062 (not (org-entry-is-done-p))))
11064 (defun org-get-wdays (ts)
11065 "Get the deadline lead time appropriate for timestring TS."
11066 (cond
11067 ((<= org-deadline-warning-days 0)
11068 ;; 0 or negative, enforce this value no matter what
11069 (- org-deadline-warning-days))
11070 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
11071 ;; lead time is specified.
11072 (floor (* (string-to-number (match-string 1 ts))
11073 (cdr (assoc (match-string 2 ts)
11074 '(("d" . 1) ("w" . 7)
11075 ("m" . 30.4) ("y" . 365.25)))))))
11076 ;; go for the default.
11077 (t org-deadline-warning-days)))
11079 (defun org-calendar-select-mouse (ev)
11080 "Return to `org-read-date' with the date currently selected.
11081 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11082 (interactive "e")
11083 (mouse-set-point ev)
11084 (when (calendar-cursor-to-date)
11085 (let* ((date (calendar-cursor-to-date))
11086 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11087 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11088 (if (active-minibuffer-window) (exit-minibuffer))))
11090 (defun org-check-deadlines (ndays)
11091 "Check if there are any deadlines due or past due.
11092 A deadline is considered due if it happens within `org-deadline-warning-days'
11093 days from today's date. If the deadline appears in an entry marked DONE,
11094 it is not shown. The prefix arg NDAYS can be used to test that many
11095 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
11096 (interactive "P")
11097 (let* ((org-warn-days
11098 (cond
11099 ((equal ndays '(4)) 100000)
11100 (ndays (prefix-numeric-value ndays))
11101 (t (abs org-deadline-warning-days))))
11102 (case-fold-search nil)
11103 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
11104 (callback
11105 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
11107 (message "%d deadlines past-due or due within %d days"
11108 (org-occur regexp nil callback)
11109 org-warn-days)))
11111 (defun org-check-before-date (date)
11112 "Check if there are deadlines or scheduled entries before DATE."
11113 (interactive (list (org-read-date)))
11114 (let ((case-fold-search nil)
11115 (regexp (concat "\\<\\(" org-deadline-string
11116 "\\|" org-scheduled-string
11117 "\\) *<\\([^>]+\\)>"))
11118 (callback
11119 (lambda () (time-less-p
11120 (org-time-string-to-time (match-string 2))
11121 (org-time-string-to-time date)))))
11122 (message "%d entries before %s"
11123 (org-occur regexp nil callback) date)))
11125 (defun org-evaluate-time-range (&optional to-buffer)
11126 "Evaluate a time range by computing the difference between start and end.
11127 Normally the result is just printed in the echo area, but with prefix arg
11128 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
11129 If the time range is actually in a table, the result is inserted into the
11130 next column.
11131 For time difference computation, a year is assumed to be exactly 365
11132 days in order to avoid rounding problems."
11133 (interactive "P")
11135 (org-clock-update-time-maybe)
11136 (save-excursion
11137 (unless (org-at-date-range-p t)
11138 (goto-char (point-at-bol))
11139 (re-search-forward org-tr-regexp-both (point-at-eol) t))
11140 (if (not (org-at-date-range-p t))
11141 (error "Not at a time-stamp range, and none found in current line")))
11142 (let* ((ts1 (match-string 1))
11143 (ts2 (match-string 2))
11144 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
11145 (match-end (match-end 0))
11146 (time1 (org-time-string-to-time ts1))
11147 (time2 (org-time-string-to-time ts2))
11148 (t1 (time-to-seconds time1))
11149 (t2 (time-to-seconds time2))
11150 (diff (abs (- t2 t1)))
11151 (negative (< (- t2 t1) 0))
11152 ;; (ys (floor (* 365 24 60 60)))
11153 (ds (* 24 60 60))
11154 (hs (* 60 60))
11155 (fy "%dy %dd %02d:%02d")
11156 (fy1 "%dy %dd")
11157 (fd "%dd %02d:%02d")
11158 (fd1 "%dd")
11159 (fh "%02d:%02d")
11160 y d h m align)
11161 (if havetime
11162 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11164 d (floor (/ diff ds)) diff (mod diff ds)
11165 h (floor (/ diff hs)) diff (mod diff hs)
11166 m (floor (/ diff 60)))
11167 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11169 d (floor (+ (/ diff ds) 0.5))
11170 h 0 m 0))
11171 (if (not to-buffer)
11172 (message "%s" (org-make-tdiff-string y d h m))
11173 (if (org-at-table-p)
11174 (progn
11175 (goto-char match-end)
11176 (setq align t)
11177 (and (looking-at " *|") (goto-char (match-end 0))))
11178 (goto-char match-end))
11179 (if (looking-at
11180 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
11181 (replace-match ""))
11182 (if negative (insert " -"))
11183 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
11184 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
11185 (insert " " (format fh h m))))
11186 (if align (org-table-align))
11187 (message "Time difference inserted")))))
11189 (defun org-make-tdiff-string (y d h m)
11190 (let ((fmt "")
11191 (l nil))
11192 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
11193 l (push y l)))
11194 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
11195 l (push d l)))
11196 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
11197 l (push h l)))
11198 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
11199 l (push m l)))
11200 (apply 'format fmt (nreverse l))))
11202 (defun org-time-string-to-time (s)
11203 (apply 'encode-time (org-parse-time-string s)))
11205 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
11206 "Convert a time stamp to an absolute day number.
11207 If there is a specifyer for a cyclic time stamp, get the closest date to
11208 DAYNR.
11209 PREFER and SHOW_ALL are passed through to `org-closest-date'."
11210 (cond
11211 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
11212 (if (org-diary-sexp-entry (match-string 1 s) "" date)
11213 daynr
11214 (+ daynr 1000)))
11215 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
11216 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
11217 (time-to-days (current-time))) (match-string 0 s)
11218 prefer show-all))
11219 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
11221 (defun org-days-to-iso-week (days)
11222 "Return the iso week number."
11223 (require 'cal-iso)
11224 (car (calendar-iso-from-absolute days)))
11226 (defun org-small-year-to-year (year)
11227 "Convert 2-digit years into 4-digit years.
11228 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
11229 The year 2000 cannot be abbreviated. Any year lager than 99
11230 is retrned unchanged."
11231 (if (< year 38)
11232 (setq year (+ 2000 year))
11233 (if (< year 100)
11234 (setq year (+ 1900 year))))
11235 year)
11237 (defun org-time-from-absolute (d)
11238 "Return the time corresponding to date D.
11239 D may be an absolute day number, or a calendar-type list (month day year)."
11240 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
11241 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
11243 (defun org-calendar-holiday ()
11244 "List of holidays, for Diary display in Org-mode."
11245 (require 'holidays)
11246 (let ((hl (funcall
11247 (if (fboundp 'calendar-check-holidays)
11248 'calendar-check-holidays 'check-calendar-holidays) date)))
11249 (if hl (mapconcat 'identity hl "; "))))
11251 (defun org-diary-sexp-entry (sexp entry date)
11252 "Process a SEXP diary ENTRY for DATE."
11253 (require 'diary-lib)
11254 (let ((result (if calendar-debug-sexp
11255 (let ((stack-trace-on-error t))
11256 (eval (car (read-from-string sexp))))
11257 (condition-case nil
11258 (eval (car (read-from-string sexp)))
11259 (error
11260 (beep)
11261 (message "Bad sexp at line %d in %s: %s"
11262 (org-current-line)
11263 (buffer-file-name) sexp)
11264 (sleep-for 2))))))
11265 (cond ((stringp result) result)
11266 ((and (consp result)
11267 (stringp (cdr result))) (cdr result))
11268 (result entry)
11269 (t nil))))
11271 (defun org-diary-to-ical-string (frombuf)
11272 "Get iCalendar entries from diary entries in buffer FROMBUF.
11273 This uses the icalendar.el library."
11274 (let* ((tmpdir (if (featurep 'xemacs)
11275 (temp-directory)
11276 temporary-file-directory))
11277 (tmpfile (make-temp-name
11278 (expand-file-name "orgics" tmpdir)))
11279 buf rtn b e)
11280 (save-excursion
11281 (set-buffer frombuf)
11282 (icalendar-export-region (point-min) (point-max) tmpfile)
11283 (setq buf (find-buffer-visiting tmpfile))
11284 (set-buffer buf)
11285 (goto-char (point-min))
11286 (if (re-search-forward "^BEGIN:VEVENT" nil t)
11287 (setq b (match-beginning 0)))
11288 (goto-char (point-max))
11289 (if (re-search-backward "^END:VEVENT" nil t)
11290 (setq e (match-end 0)))
11291 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
11292 (kill-buffer buf)
11293 (delete-file tmpfile)
11294 rtn))
11296 (defun org-closest-date (start current change prefer show-all)
11297 "Find the date closest to CURRENT that is consistent with START and CHANGE.
11298 When PREFER is `past' return a date that is either CURRENT or past.
11299 When PREFER is `future', return a date that is either CURRENT or future.
11300 When SHOW-ALL is nil, only return the current occurence of a time stamp."
11301 ;; Make the proper lists from the dates
11302 (catch 'exit
11303 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
11304 dn dw sday cday n1 n2
11305 d m y y1 y2 date1 date2 nmonths nm ny m2)
11307 (setq start (org-date-to-gregorian start)
11308 current (org-date-to-gregorian
11309 (if show-all
11310 current
11311 (time-to-days (current-time))))
11312 sday (calendar-absolute-from-gregorian start)
11313 cday (calendar-absolute-from-gregorian current))
11315 (if (<= cday sday) (throw 'exit sday))
11317 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
11318 (setq dn (string-to-number (match-string 1 change))
11319 dw (cdr (assoc (match-string 2 change) a1)))
11320 (error "Invalid change specifyer: %s" change))
11321 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
11322 (cond
11323 ((eq dw 'day)
11324 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
11325 n2 (+ n1 dn)))
11326 ((eq dw 'year)
11327 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
11328 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
11329 (setq date1 (list m d y1)
11330 n1 (calendar-absolute-from-gregorian date1)
11331 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
11332 n2 (calendar-absolute-from-gregorian date2)))
11333 ((eq dw 'month)
11334 ;; approx number of month between the two dates
11335 (setq nmonths (floor (/ (- cday sday) 30.436875)))
11336 ;; How often does dn fit in there?
11337 (setq d (nth 1 start) m (car start) y (nth 2 start)
11338 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
11339 m (+ m nm)
11340 ny (floor (/ m 12))
11341 y (+ y ny)
11342 m (- m (* ny 12)))
11343 (while (> m 12) (setq m (- m 12) y (1+ y)))
11344 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
11345 (setq m2 (+ m dn) y2 y)
11346 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11347 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
11348 (while (<= n2 cday)
11349 (setq n1 n2 m m2 y y2)
11350 (setq m2 (+ m dn) y2 y)
11351 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11352 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
11353 (if show-all
11354 (cond
11355 ((eq prefer 'past) n1)
11356 ((eq prefer 'future) (if (= cday n1) n1 n2))
11357 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
11358 (cond
11359 ((eq prefer 'past) n1)
11360 ((eq prefer 'future) (if (= cday n1) n1 n2))
11361 (t (if (= cday n1) n1 n2)))))))
11363 (defun org-date-to-gregorian (date)
11364 "Turn any specification of DATE into a gregorian date for the calendar."
11365 (cond ((integerp date) (calendar-gregorian-from-absolute date))
11366 ((and (listp date) (= (length date) 3)) date)
11367 ((stringp date)
11368 (setq date (org-parse-time-string date))
11369 (list (nth 4 date) (nth 3 date) (nth 5 date)))
11370 ((listp date)
11371 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
11373 (defun org-parse-time-string (s &optional nodefault)
11374 "Parse the standard Org-mode time string.
11375 This should be a lot faster than the normal `parse-time-string'.
11376 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
11377 hour and minute fields will be nil if not given."
11378 (if (string-match org-ts-regexp0 s)
11379 (list 0
11380 (if (or (match-beginning 8) (not nodefault))
11381 (string-to-number (or (match-string 8 s) "0")))
11382 (if (or (match-beginning 7) (not nodefault))
11383 (string-to-number (or (match-string 7 s) "0")))
11384 (string-to-number (match-string 4 s))
11385 (string-to-number (match-string 3 s))
11386 (string-to-number (match-string 2 s))
11387 nil nil nil)
11388 (make-list 9 0)))
11390 (defun org-timestamp-up (&optional arg)
11391 "Increase the date item at the cursor by one.
11392 If the cursor is on the year, change the year. If it is on the month or
11393 the day, change that.
11394 With prefix ARG, change by that many units."
11395 (interactive "p")
11396 (org-timestamp-change (prefix-numeric-value arg)))
11398 (defun org-timestamp-down (&optional arg)
11399 "Decrease the date item at the cursor by one.
11400 If the cursor is on the year, change the year. If it is on the month or
11401 the day, change that.
11402 With prefix ARG, change by that many units."
11403 (interactive "p")
11404 (org-timestamp-change (- (prefix-numeric-value arg))))
11406 (defun org-timestamp-up-day (&optional arg)
11407 "Increase the date in the time stamp by one day.
11408 With prefix ARG, change that many days."
11409 (interactive "p")
11410 (if (and (not (org-at-timestamp-p t))
11411 (org-on-heading-p))
11412 (org-todo 'up)
11413 (org-timestamp-change (prefix-numeric-value arg) 'day)))
11415 (defun org-timestamp-down-day (&optional arg)
11416 "Decrease the date in the time stamp by one day.
11417 With prefix ARG, change that many days."
11418 (interactive "p")
11419 (if (and (not (org-at-timestamp-p t))
11420 (org-on-heading-p))
11421 (org-todo 'down)
11422 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
11424 (defun org-at-timestamp-p (&optional inactive-ok)
11425 "Determine if the cursor is in or at a timestamp."
11426 (interactive)
11427 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
11428 (pos (point))
11429 (ans (or (looking-at tsr)
11430 (save-excursion
11431 (skip-chars-backward "^[<\n\r\t")
11432 (if (> (point) (point-min)) (backward-char 1))
11433 (and (looking-at tsr)
11434 (> (- (match-end 0) pos) -1))))))
11435 (and ans
11436 (boundp 'org-ts-what)
11437 (setq org-ts-what
11438 (cond
11439 ((= pos (match-beginning 0)) 'bracket)
11440 ((= pos (1- (match-end 0))) 'bracket)
11441 ((org-pos-in-match-range pos 2) 'year)
11442 ((org-pos-in-match-range pos 3) 'month)
11443 ((org-pos-in-match-range pos 7) 'hour)
11444 ((org-pos-in-match-range pos 8) 'minute)
11445 ((or (org-pos-in-match-range pos 4)
11446 (org-pos-in-match-range pos 5)) 'day)
11447 ((and (> pos (or (match-end 8) (match-end 5)))
11448 (< pos (match-end 0)))
11449 (- pos (or (match-end 8) (match-end 5))))
11450 (t 'day))))
11451 ans))
11453 (defun org-toggle-timestamp-type ()
11454 "Toggle the type (<active> or [inactive]) of a time stamp."
11455 (interactive)
11456 (when (org-at-timestamp-p t)
11457 (let ((beg (match-beginning 0)) (end (match-end 0))
11458 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
11459 (save-excursion
11460 (goto-char beg)
11461 (while (re-search-forward "[][<>]" end t)
11462 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
11463 t t)))
11464 (message "Timestamp is now %sactive"
11465 (if (equal (char-after beg) ?<) "" "in")))))
11467 (defun org-timestamp-change (n &optional what)
11468 "Change the date in the time stamp at point.
11469 The date will be changed by N times WHAT. WHAT can be `day', `month',
11470 `year', `minute', `second'. If WHAT is not given, the cursor position
11471 in the timestamp determines what will be changed."
11472 (let ((pos (point))
11473 with-hm inactive
11474 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
11475 org-ts-what
11476 extra rem
11477 ts time time0)
11478 (if (not (org-at-timestamp-p t))
11479 (error "Not at a timestamp"))
11480 (if (and (not what) (eq org-ts-what 'bracket))
11481 (org-toggle-timestamp-type)
11482 (if (and (not what) (not (eq org-ts-what 'day))
11483 org-display-custom-times
11484 (get-text-property (point) 'display)
11485 (not (get-text-property (1- (point)) 'display)))
11486 (setq org-ts-what 'day))
11487 (setq org-ts-what (or what org-ts-what)
11488 inactive (= (char-after (match-beginning 0)) ?\[)
11489 ts (match-string 0))
11490 (replace-match "")
11491 (if (string-match
11492 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
11494 (setq extra (match-string 1 ts)))
11495 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
11496 (setq with-hm t))
11497 (setq time0 (org-parse-time-string ts))
11498 (when (and (eq org-ts-what 'minute)
11499 (eq current-prefix-arg nil))
11500 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
11501 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
11502 (setcar (cdr time0) (+ (nth 1 time0)
11503 (if (> n 0) (- rem) (- dm rem))))))
11504 (setq time
11505 (encode-time (or (car time0) 0)
11506 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
11507 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
11508 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
11509 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
11510 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
11511 (nthcdr 6 time0)))
11512 (when (integerp org-ts-what)
11513 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
11514 (if (eq what 'calendar)
11515 (let ((cal-date (org-get-date-from-calendar)))
11516 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
11517 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
11518 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
11519 (setcar time0 (or (car time0) 0))
11520 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
11521 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
11522 (setq time (apply 'encode-time time0))))
11523 (setq org-last-changed-timestamp
11524 (org-insert-time-stamp time with-hm inactive nil nil extra))
11525 (org-clock-update-time-maybe)
11526 (goto-char pos)
11527 ;; Try to recenter the calendar window, if any
11528 (if (and org-calendar-follow-timestamp-change
11529 (get-buffer-window "*Calendar*" t)
11530 (memq org-ts-what '(day month year)))
11531 (org-recenter-calendar (time-to-days time))))))
11533 (defun org-modify-ts-extra (s pos n dm)
11534 "Change the different parts of the lead-time and repeat fields in timestamp."
11535 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
11536 ng h m new rem)
11537 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
11538 (cond
11539 ((or (org-pos-in-match-range pos 2)
11540 (org-pos-in-match-range pos 3))
11541 (setq m (string-to-number (match-string 3 s))
11542 h (string-to-number (match-string 2 s)))
11543 (if (org-pos-in-match-range pos 2)
11544 (setq h (+ h n))
11545 (setq n (* dm (org-no-warnings (signum n))))
11546 (when (not (= 0 (setq rem (% m dm))))
11547 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
11548 (setq m (+ m n)))
11549 (if (< m 0) (setq m (+ m 60) h (1- h)))
11550 (if (> m 59) (setq m (- m 60) h (1+ h)))
11551 (setq h (min 24 (max 0 h)))
11552 (setq ng 1 new (format "-%02d:%02d" h m)))
11553 ((org-pos-in-match-range pos 6)
11554 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
11555 ((org-pos-in-match-range pos 5)
11556 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
11558 ((org-pos-in-match-range pos 9)
11559 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
11560 ((org-pos-in-match-range pos 8)
11561 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
11563 (when ng
11564 (setq s (concat
11565 (substring s 0 (match-beginning ng))
11567 (substring s (match-end ng))))))
11570 (defun org-recenter-calendar (date)
11571 "If the calendar is visible, recenter it to DATE."
11572 (let* ((win (selected-window))
11573 (cwin (get-buffer-window "*Calendar*" t))
11574 (calendar-move-hook nil))
11575 (when cwin
11576 (select-window cwin)
11577 (calendar-goto-date (if (listp date) date
11578 (calendar-gregorian-from-absolute date)))
11579 (select-window win))))
11581 (defun org-goto-calendar (&optional arg)
11582 "Go to the Emacs calendar at the current date.
11583 If there is a time stamp in the current line, go to that date.
11584 A prefix ARG can be used to force the current date."
11585 (interactive "P")
11586 (let ((tsr org-ts-regexp) diff
11587 (calendar-move-hook nil)
11588 (calendar-view-holidays-initially-flag nil)
11589 (view-calendar-holidays-initially nil)
11590 (calendar-view-diary-initially-flag nil)
11591 (view-diary-entries-initially nil))
11592 (if (or (org-at-timestamp-p)
11593 (save-excursion
11594 (beginning-of-line 1)
11595 (looking-at (concat ".*" tsr))))
11596 (let ((d1 (time-to-days (current-time)))
11597 (d2 (time-to-days
11598 (org-time-string-to-time (match-string 1)))))
11599 (setq diff (- d2 d1))))
11600 (calendar)
11601 (calendar-goto-today)
11602 (if (and diff (not arg)) (calendar-forward-day diff))))
11604 (defun org-get-date-from-calendar ()
11605 "Return a list (month day year) of date at point in calendar."
11606 (with-current-buffer "*Calendar*"
11607 (save-match-data
11608 (calendar-cursor-to-date))))
11610 (defun org-date-from-calendar ()
11611 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
11612 If there is already a time stamp at the cursor position, update it."
11613 (interactive)
11614 (if (org-at-timestamp-p t)
11615 (org-timestamp-change 0 'calendar)
11616 (let ((cal-date (org-get-date-from-calendar)))
11617 (org-insert-time-stamp
11618 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
11620 (defun org-minutes-to-hh:mm-string (m)
11621 "Compute H:MM from a number of minutes."
11622 (let ((h (/ m 60)))
11623 (setq m (- m (* 60 h)))
11624 (format org-time-clocksum-format h m)))
11626 (defun org-hh:mm-string-to-minutes (s)
11627 "Convert a string H:MM to a number of minutes."
11628 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
11629 (+ (* (string-to-number (match-string 1 s)) 60)
11630 (string-to-number (match-string 2 s)))
11633 ;;;; Agenda files
11635 ;;;###autoload
11636 (defun org-iswitchb (&optional arg)
11637 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
11638 With a prefix argument, restrict available to files.
11639 With two prefix arguments, restrict available buffers to agenda files.
11641 Due to some yet unresolved reason, the global function
11642 `iswitchb-mode' needs to be active for this function to work."
11643 (interactive "P")
11644 (require 'iswitchb)
11645 (let ((enabled iswitchb-mode) blist)
11646 (or enabled (iswitchb-mode 1))
11647 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
11648 ((equal arg '(16)) (org-buffer-list 'agenda))
11649 (t (org-buffer-list))))
11650 (unwind-protect
11651 (let ((iswitchb-make-buflist-hook
11652 (lambda ()
11653 (setq iswitchb-temp-buflist
11654 (mapcar 'buffer-name blist)))))
11655 (switch-to-buffer
11656 (iswitchb-read-buffer
11657 "Switch-to: " nil t))
11658 (or enabled (iswitchb-mode -1))))))
11660 (defun org-buffer-list (&optional predicate exclude-tmp)
11661 "Return a list of Org buffers.
11662 PREDICATE can be `export', `files' or `agenda'.
11664 export restrict the list to Export buffers.
11665 files restrict the list to buffers visiting Org files.
11666 agenda restrict the list to buffers visiting agenda files.
11668 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
11669 (let* ((bfn nil)
11670 (agenda-files (and (eq predicate 'agenda)
11671 (mapcar 'file-truename (org-agenda-files t))))
11672 (filter
11673 (cond
11674 ((eq predicate 'files)
11675 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
11676 ((eq predicate 'export)
11677 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
11678 ((eq predicate 'agenda)
11679 (lambda (b)
11680 (with-current-buffer b
11681 (and (eq major-mode 'org-mode)
11682 (setq bfn (buffer-file-name b))
11683 (member (file-truename bfn) agenda-files)))))
11684 (t (lambda (b) (with-current-buffer b
11685 (or (eq major-mode 'org-mode)
11686 (string-match "\*Org .*Export"
11687 (buffer-name b)))))))))
11688 (delq nil
11689 (mapcar
11690 (lambda(b)
11691 (if (and (funcall filter b)
11692 (or (not exclude-tmp)
11693 (not (string-match "tmp" (buffer-name b)))))
11695 nil))
11696 (buffer-list)))))
11698 (defun org-agenda-files (&optional unrestricted archives)
11699 "Get the list of agenda files.
11700 Optional UNRESTRICTED means return the full list even if a restriction
11701 is currently in place.
11702 When ARCHIVES is t, include all archive files hat are really being
11703 used by the agenda files. If ARCHIVE is `ifmode', do this only if
11704 `org-agenda-archives-mode' is t."
11705 (let ((files
11706 (cond
11707 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
11708 ((stringp org-agenda-files) (org-read-agenda-file-list))
11709 ((listp org-agenda-files) org-agenda-files)
11710 (t (error "Invalid value of `org-agenda-files'")))))
11711 (setq files (apply 'append
11712 (mapcar (lambda (f)
11713 (if (file-directory-p f)
11714 (directory-files
11715 f t org-agenda-file-regexp)
11716 (list f)))
11717 files)))
11718 (when org-agenda-skip-unavailable-files
11719 (setq files (delq nil
11720 (mapcar (function
11721 (lambda (file)
11722 (and (file-readable-p file) file)))
11723 files))))
11724 (when (or (eq archives t)
11725 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
11726 (setq files (org-add-archive-files files)))
11727 files))
11729 (defun org-edit-agenda-file-list ()
11730 "Edit the list of agenda files.
11731 Depending on setup, this either uses customize to edit the variable
11732 `org-agenda-files', or it visits the file that is holding the list. In the
11733 latter case, the buffer is set up in a way that saving it automatically kills
11734 the buffer and restores the previous window configuration."
11735 (interactive)
11736 (if (stringp org-agenda-files)
11737 (let ((cw (current-window-configuration)))
11738 (find-file org-agenda-files)
11739 (org-set-local 'org-window-configuration cw)
11740 (org-add-hook 'after-save-hook
11741 (lambda ()
11742 (set-window-configuration
11743 (prog1 org-window-configuration
11744 (kill-buffer (current-buffer))))
11745 (org-install-agenda-files-menu)
11746 (message "New agenda file list installed"))
11747 nil 'local)
11748 (message "%s" (substitute-command-keys
11749 "Edit list and finish with \\[save-buffer]")))
11750 (customize-variable 'org-agenda-files)))
11752 (defun org-store-new-agenda-file-list (list)
11753 "Set new value for the agenda file list and save it correcly."
11754 (if (stringp org-agenda-files)
11755 (let ((f org-agenda-files) b)
11756 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
11757 (with-temp-file f
11758 (insert (mapconcat 'identity list "\n") "\n")))
11759 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
11760 (setq org-agenda-files list)
11761 (customize-save-variable 'org-agenda-files org-agenda-files))))
11763 (defun org-read-agenda-file-list ()
11764 "Read the list of agenda files from a file."
11765 (when (file-directory-p org-agenda-files)
11766 (error "`org-agenda-files' cannot be a single directory"))
11767 (when (stringp org-agenda-files)
11768 (with-temp-buffer
11769 (insert-file-contents org-agenda-files)
11770 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
11773 ;;;###autoload
11774 (defun org-cycle-agenda-files ()
11775 "Cycle through the files in `org-agenda-files'.
11776 If the current buffer visits an agenda file, find the next one in the list.
11777 If the current buffer does not, find the first agenda file."
11778 (interactive)
11779 (let* ((fs (org-agenda-files t))
11780 (files (append fs (list (car fs))))
11781 (tcf (if buffer-file-name (file-truename buffer-file-name)))
11782 file)
11783 (unless files (error "No agenda files"))
11784 (catch 'exit
11785 (while (setq file (pop files))
11786 (if (equal (file-truename file) tcf)
11787 (when (car files)
11788 (find-file (car files))
11789 (throw 'exit t))))
11790 (find-file (car fs)))
11791 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
11793 (defun org-agenda-file-to-front (&optional to-end)
11794 "Move/add the current file to the top of the agenda file list.
11795 If the file is not present in the list, it is added to the front. If it is
11796 present, it is moved there. With optional argument TO-END, add/move to the
11797 end of the list."
11798 (interactive "P")
11799 (let ((org-agenda-skip-unavailable-files nil)
11800 (file-alist (mapcar (lambda (x)
11801 (cons (file-truename x) x))
11802 (org-agenda-files t)))
11803 (ctf (file-truename buffer-file-name))
11804 x had)
11805 (setq x (assoc ctf file-alist) had x)
11807 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
11808 (if to-end
11809 (setq file-alist (append (delq x file-alist) (list x)))
11810 (setq file-alist (cons x (delq x file-alist))))
11811 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
11812 (org-install-agenda-files-menu)
11813 (message "File %s to %s of agenda file list"
11814 (if had "moved" "added") (if to-end "end" "front"))))
11816 (defun org-remove-file (&optional file)
11817 "Remove current file from the list of files in variable `org-agenda-files'.
11818 These are the files which are being checked for agenda entries.
11819 Optional argument FILE means, use this file instead of the current."
11820 (interactive)
11821 (let* ((org-agenda-skip-unavailable-files nil)
11822 (file (or file buffer-file-name))
11823 (true-file (file-truename file))
11824 (afile (abbreviate-file-name file))
11825 (files (delq nil (mapcar
11826 (lambda (x)
11827 (if (equal true-file
11828 (file-truename x))
11829 nil x))
11830 (org-agenda-files t)))))
11831 (if (not (= (length files) (length (org-agenda-files t))))
11832 (progn
11833 (org-store-new-agenda-file-list files)
11834 (org-install-agenda-files-menu)
11835 (message "Removed file: %s" afile))
11836 (message "File was not in list: %s (not removed)" afile))))
11838 (defun org-file-menu-entry (file)
11839 (vector file (list 'find-file file) t))
11841 (defun org-check-agenda-file (file)
11842 "Make sure FILE exists. If not, ask user what to do."
11843 (when (not (file-exists-p file))
11844 (message "non-existent file %s. [R]emove from list or [A]bort?"
11845 (abbreviate-file-name file))
11846 (let ((r (downcase (read-char-exclusive))))
11847 (cond
11848 ((equal r ?r)
11849 (org-remove-file file)
11850 (throw 'nextfile t))
11851 (t (error "Abort"))))))
11853 (defun org-get-agenda-file-buffer (file)
11854 "Get a buffer visiting FILE. If the buffer needs to be created, add
11855 it to the list of buffers which might be released later."
11856 (let ((buf (org-find-base-buffer-visiting file)))
11857 (if buf
11858 buf ; just return it
11859 ;; Make a new buffer and remember it
11860 (setq buf (find-file-noselect file))
11861 (if buf (push buf org-agenda-new-buffers))
11862 buf)))
11864 (defun org-release-buffers (blist)
11865 "Release all buffers in list, asking the user for confirmation when needed.
11866 When a buffer is unmodified, it is just killed. When modified, it is saved
11867 \(if the user agrees) and then killed."
11868 (let (buf file)
11869 (while (setq buf (pop blist))
11870 (setq file (buffer-file-name buf))
11871 (when (and (buffer-modified-p buf)
11872 file
11873 (y-or-n-p (format "Save file %s? " file)))
11874 (with-current-buffer buf (save-buffer)))
11875 (kill-buffer buf))))
11877 (defun org-prepare-agenda-buffers (files)
11878 "Create buffers for all agenda files, protect archived trees and comments."
11879 (interactive)
11880 (let ((pa '(:org-archived t))
11881 (pc '(:org-comment t))
11882 (pall '(:org-archived t :org-comment t))
11883 (inhibit-read-only t)
11884 (rea (concat ":" org-archive-tag ":"))
11885 bmp file re)
11886 (save-excursion
11887 (save-restriction
11888 (while (setq file (pop files))
11889 (if (bufferp file)
11890 (set-buffer file)
11891 (org-check-agenda-file file)
11892 (set-buffer (org-get-agenda-file-buffer file)))
11893 (widen)
11894 (setq bmp (buffer-modified-p))
11895 (org-refresh-category-properties)
11896 (setq org-todo-keywords-for-agenda
11897 (append org-todo-keywords-for-agenda org-todo-keywords-1))
11898 (setq org-done-keywords-for-agenda
11899 (append org-done-keywords-for-agenda org-done-keywords))
11900 (setq org-todo-keyword-alist-for-agenda
11901 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
11902 (setq org-tag-alist-for-agenda
11903 (append org-tag-alist-for-agenda org-tag-alist))
11905 (save-excursion
11906 (remove-text-properties (point-min) (point-max) pall)
11907 (when org-agenda-skip-archived-trees
11908 (goto-char (point-min))
11909 (while (re-search-forward rea nil t)
11910 (if (org-on-heading-p t)
11911 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
11912 (goto-char (point-min))
11913 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
11914 (while (re-search-forward re nil t)
11915 (add-text-properties
11916 (match-beginning 0) (org-end-of-subtree t) pc)))
11917 (set-buffer-modified-p bmp))))
11918 (setq org-todo-keyword-alist-for-agenda
11919 (org-uniquify org-todo-keyword-alist-for-agenda)
11920 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
11922 ;;;; Embedded LaTeX
11924 (defvar org-cdlatex-mode-map (make-sparse-keymap)
11925 "Keymap for the minor `org-cdlatex-mode'.")
11927 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
11928 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
11929 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
11930 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
11931 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
11933 (defvar org-cdlatex-texmathp-advice-is-done nil
11934 "Flag remembering if we have applied the advice to texmathp already.")
11936 (define-minor-mode org-cdlatex-mode
11937 "Toggle the minor `org-cdlatex-mode'.
11938 This mode supports entering LaTeX environment and math in LaTeX fragments
11939 in Org-mode.
11940 \\{org-cdlatex-mode-map}"
11941 nil " OCDL" nil
11942 (when org-cdlatex-mode (require 'cdlatex))
11943 (unless org-cdlatex-texmathp-advice-is-done
11944 (setq org-cdlatex-texmathp-advice-is-done t)
11945 (defadvice texmathp (around org-math-always-on activate)
11946 "Always return t in org-mode buffers.
11947 This is because we want to insert math symbols without dollars even outside
11948 the LaTeX math segments. If Orgmode thinks that point is actually inside
11949 en embedded LaTeX fragement, let texmathp do its job.
11950 \\[org-cdlatex-mode-map]"
11951 (interactive)
11952 (let (p)
11953 (cond
11954 ((not (org-mode-p)) ad-do-it)
11955 ((eq this-command 'cdlatex-math-symbol)
11956 (setq ad-return-value t
11957 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
11959 (let ((p (org-inside-LaTeX-fragment-p)))
11960 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
11961 (setq ad-return-value t
11962 texmathp-why '("Org-mode embedded math" . 0))
11963 (if p ad-do-it)))))))))
11965 (defun turn-on-org-cdlatex ()
11966 "Unconditionally turn on `org-cdlatex-mode'."
11967 (org-cdlatex-mode 1))
11969 (defun org-inside-LaTeX-fragment-p ()
11970 "Test if point is inside a LaTeX fragment.
11971 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
11972 sequence appearing also before point.
11973 Even though the matchers for math are configurable, this function assumes
11974 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
11975 delimiters are skipped when they have been removed by customization.
11976 The return value is nil, or a cons cell with the delimiter and
11977 and the position of this delimiter.
11979 This function does a reasonably good job, but can locally be fooled by
11980 for example currency specifications. For example it will assume being in
11981 inline math after \"$22.34\". The LaTeX fragment formatter will only format
11982 fragments that are properly closed, but during editing, we have to live
11983 with the uncertainty caused by missing closing delimiters. This function
11984 looks only before point, not after."
11985 (catch 'exit
11986 (let ((pos (point))
11987 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
11988 (lim (progn
11989 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
11990 (point)))
11991 dd-on str (start 0) m re)
11992 (goto-char pos)
11993 (when dodollar
11994 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
11995 re (nth 1 (assoc "$" org-latex-regexps)))
11996 (while (string-match re str start)
11997 (cond
11998 ((= (match-end 0) (length str))
11999 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
12000 ((= (match-end 0) (- (length str) 5))
12001 (throw 'exit nil))
12002 (t (setq start (match-end 0))))))
12003 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
12004 (goto-char pos)
12005 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
12006 (and (match-beginning 2) (throw 'exit nil))
12007 ;; count $$
12008 (while (re-search-backward "\\$\\$" lim t)
12009 (setq dd-on (not dd-on)))
12010 (goto-char pos)
12011 (if dd-on (cons "$$" m))))))
12014 (defun org-try-cdlatex-tab ()
12015 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
12016 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
12017 - inside a LaTeX fragment, or
12018 - after the first word in a line, where an abbreviation expansion could
12019 insert a LaTeX environment."
12020 (when org-cdlatex-mode
12021 (cond
12022 ((save-excursion
12023 (skip-chars-backward "a-zA-Z0-9*")
12024 (skip-chars-backward " \t")
12025 (bolp))
12026 (cdlatex-tab) t)
12027 ((org-inside-LaTeX-fragment-p)
12028 (cdlatex-tab) t)
12029 (t nil))))
12031 (defun org-cdlatex-underscore-caret (&optional arg)
12032 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
12033 Revert to the normal definition outside of these fragments."
12034 (interactive "P")
12035 (if (org-inside-LaTeX-fragment-p)
12036 (call-interactively 'cdlatex-sub-superscript)
12037 (let (org-cdlatex-mode)
12038 (call-interactively (key-binding (vector last-input-event))))))
12040 (defun org-cdlatex-math-modify (&optional arg)
12041 "Execute `cdlatex-math-modify' in LaTeX fragments.
12042 Revert to the normal definition outside of these fragments."
12043 (interactive "P")
12044 (if (org-inside-LaTeX-fragment-p)
12045 (call-interactively 'cdlatex-math-modify)
12046 (let (org-cdlatex-mode)
12047 (call-interactively (key-binding (vector last-input-event))))))
12049 (defvar org-latex-fragment-image-overlays nil
12050 "List of overlays carrying the images of latex fragments.")
12051 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
12053 (defun org-remove-latex-fragment-image-overlays ()
12054 "Remove all overlays with LaTeX fragment images in current buffer."
12055 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
12056 (setq org-latex-fragment-image-overlays nil))
12058 (defun org-preview-latex-fragment (&optional subtree)
12059 "Preview the LaTeX fragment at point, or all locally or globally.
12060 If the cursor is in a LaTeX fragment, create the image and overlay
12061 it over the source code. If there is no fragment at point, display
12062 all fragments in the current text, from one headline to the next. With
12063 prefix SUBTREE, display all fragments in the current subtree. With a
12064 double prefix `C-u C-u', or when the cursor is before the first headline,
12065 display all fragments in the buffer.
12066 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
12067 (interactive "P")
12068 (org-remove-latex-fragment-image-overlays)
12069 (save-excursion
12070 (save-restriction
12071 (let (beg end at msg)
12072 (cond
12073 ((or (equal subtree '(16))
12074 (not (save-excursion
12075 (re-search-backward (concat "^" outline-regexp) nil t))))
12076 (setq beg (point-min) end (point-max)
12077 msg "Creating images for buffer...%s"))
12078 ((equal subtree '(4))
12079 (org-back-to-heading)
12080 (setq beg (point) end (org-end-of-subtree t)
12081 msg "Creating images for subtree...%s"))
12083 (if (setq at (org-inside-LaTeX-fragment-p))
12084 (goto-char (max (point-min) (- (cdr at) 2)))
12085 (org-back-to-heading))
12086 (setq beg (point) end (progn (outline-next-heading) (point))
12087 msg (if at "Creating image...%s"
12088 "Creating images for entry...%s"))))
12089 (message msg "")
12090 (narrow-to-region beg end)
12091 (goto-char beg)
12092 (org-format-latex
12093 (concat "ltxpng/" (file-name-sans-extension
12094 (file-name-nondirectory
12095 buffer-file-name)))
12096 default-directory 'overlays msg at 'forbuffer)
12097 (message msg "done. Use `C-c C-c' to remove images.")))))
12099 (defvar org-latex-regexps
12100 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
12101 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
12102 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
12103 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
12104 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
12105 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
12106 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
12107 "Regular expressions for matching embedded LaTeX.")
12109 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
12110 "Replace LaTeX fragments with links to an image, and produce images."
12111 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
12112 (let* ((prefixnodir (file-name-nondirectory prefix))
12113 (absprefix (expand-file-name prefix dir))
12114 (todir (file-name-directory absprefix))
12115 (opt org-format-latex-options)
12116 (matchers (plist-get opt :matchers))
12117 (re-list org-latex-regexps)
12118 (cnt 0) txt link beg end re e checkdir
12119 m n block linkfile movefile ov)
12120 ;; Check if there are old images files with this prefix, and remove them
12121 (when (file-directory-p todir)
12122 (mapc 'delete-file
12123 (directory-files
12124 todir 'full
12125 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
12126 ;; Check the different regular expressions
12127 (while (setq e (pop re-list))
12128 (setq m (car e) re (nth 1 e) n (nth 2 e)
12129 block (if (nth 3 e) "\n\n" ""))
12130 (when (member m matchers)
12131 (goto-char (point-min))
12132 (while (re-search-forward re nil t)
12133 (when (or (not at) (equal (cdr at) (match-beginning n)))
12134 (setq txt (match-string n)
12135 beg (match-beginning n) end (match-end n)
12136 cnt (1+ cnt)
12137 linkfile (format "%s_%04d.png" prefix cnt)
12138 movefile (format "%s_%04d.png" absprefix cnt)
12139 link (concat block "[[file:" linkfile "]]" block))
12140 (if msg (message msg cnt))
12141 (goto-char beg)
12142 (unless checkdir ; make sure the directory exists
12143 (setq checkdir t)
12144 (or (file-directory-p todir) (make-directory todir)))
12145 (org-create-formula-image
12146 txt movefile opt forbuffer)
12147 (if overlays
12148 (progn
12149 (setq ov (org-make-overlay beg end))
12150 (if (featurep 'xemacs)
12151 (progn
12152 (org-overlay-put ov 'invisible t)
12153 (org-overlay-put
12154 ov 'end-glyph
12155 (make-glyph (vector 'png :file movefile))))
12156 (org-overlay-put
12157 ov 'display
12158 (list 'image :type 'png :file movefile :ascent 'center)))
12159 (push ov org-latex-fragment-image-overlays)
12160 (goto-char end))
12161 (delete-region beg end)
12162 (insert link))))))))
12164 ;; This function borrows from Ganesh Swami's latex2png.el
12165 (defun org-create-formula-image (string tofile options buffer)
12166 (let* ((tmpdir (if (featurep 'xemacs)
12167 (temp-directory)
12168 temporary-file-directory))
12169 (texfilebase (make-temp-name
12170 (expand-file-name "orgtex" tmpdir)))
12171 (texfile (concat texfilebase ".tex"))
12172 (dvifile (concat texfilebase ".dvi"))
12173 (pngfile (concat texfilebase ".png"))
12174 (fnh (if (featurep 'xemacs)
12175 (font-height (get-face-font 'default))
12176 (face-attribute 'default :height nil)))
12177 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
12178 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
12179 (fg (or (plist-get options (if buffer :foreground :html-foreground))
12180 "Black"))
12181 (bg (or (plist-get options (if buffer :background :html-background))
12182 "Transparent")))
12183 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
12184 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
12185 (with-temp-file texfile
12186 (insert org-format-latex-header
12187 "\n\\begin{document}\n" string "\n\\end{document}\n"))
12188 (let ((dir default-directory))
12189 (condition-case nil
12190 (progn
12191 (cd tmpdir)
12192 (call-process "latex" nil nil nil texfile))
12193 (error nil))
12194 (cd dir))
12195 (if (not (file-exists-p dvifile))
12196 (progn (message "Failed to create dvi file from %s" texfile) nil)
12197 (condition-case nil
12198 (call-process "dvipng" nil nil nil
12199 "-E" "-fg" fg "-bg" bg
12200 "-D" dpi
12201 ;;"-x" scale "-y" scale
12202 "-T" "tight"
12203 "-o" pngfile
12204 dvifile)
12205 (error nil))
12206 (if (not (file-exists-p pngfile))
12207 (progn (message "Failed to create png file from %s" texfile) nil)
12208 ;; Use the requested file name and clean up
12209 (copy-file pngfile tofile 'replace)
12210 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
12211 (delete-file (concat texfilebase e)))
12212 pngfile))))
12214 (defun org-dvipng-color (attr)
12215 "Return an rgb color specification for dvipng."
12216 (apply 'format "rgb %s %s %s"
12217 (mapcar 'org-normalize-color
12218 (color-values (face-attribute 'default attr nil)))))
12220 (defun org-normalize-color (value)
12221 "Return string to be used as color value for an RGB component."
12222 (format "%g" (/ value 65535.0)))
12225 ;;;; Key bindings
12227 ;; Make `C-c C-x' a prefix key
12228 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
12230 ;; TAB key with modifiers
12231 (org-defkey org-mode-map "\C-i" 'org-cycle)
12232 (org-defkey org-mode-map [(tab)] 'org-cycle)
12233 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
12234 (org-defkey org-mode-map [(meta tab)] 'org-complete)
12235 (org-defkey org-mode-map "\M-\t" 'org-complete)
12236 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
12237 ;; The following line is necessary under Suse GNU/Linux
12238 (unless (featurep 'xemacs)
12239 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
12240 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
12241 (define-key org-mode-map [backtab] 'org-shifttab)
12243 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
12244 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
12245 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
12247 ;; Cursor keys with modifiers
12248 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
12249 (org-defkey org-mode-map [(meta right)] 'org-metaright)
12250 (org-defkey org-mode-map [(meta up)] 'org-metaup)
12251 (org-defkey org-mode-map [(meta down)] 'org-metadown)
12253 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
12254 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
12255 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
12256 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
12258 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
12259 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
12260 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
12261 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
12263 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
12264 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
12266 ;;; Extra keys for tty access.
12267 ;; We only set them when really needed because otherwise the
12268 ;; menus don't show the simple keys
12270 (when (or org-use-extra-keys
12271 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
12272 (not window-system))
12273 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
12274 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
12275 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
12276 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
12277 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
12278 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
12279 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
12280 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
12281 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
12282 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
12283 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
12284 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
12285 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
12286 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
12287 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
12288 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
12289 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
12290 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
12291 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
12292 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
12293 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
12294 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
12296 ;; All the other keys
12298 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
12299 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
12300 (if (boundp 'narrow-map)
12301 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
12302 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
12303 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
12304 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
12305 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
12306 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
12307 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
12308 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
12309 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
12310 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
12311 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
12312 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
12313 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
12314 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
12315 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
12316 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
12317 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
12318 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
12319 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
12320 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
12321 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
12322 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
12323 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
12324 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
12325 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
12326 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
12327 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
12328 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
12329 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
12330 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
12331 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
12332 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
12333 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
12334 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
12335 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
12336 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
12337 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
12338 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
12339 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
12340 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
12341 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
12342 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
12343 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
12344 (org-defkey org-mode-map "\C-c^" 'org-sort)
12345 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
12346 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
12347 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
12348 (org-defkey org-mode-map "\C-m" 'org-return)
12349 (org-defkey org-mode-map "\C-j" 'org-return-indent)
12350 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
12351 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
12352 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
12353 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
12354 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
12355 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
12356 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
12357 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
12358 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
12359 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
12360 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
12361 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
12362 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
12363 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
12364 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
12366 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
12367 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
12368 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
12369 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
12371 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
12372 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
12373 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
12374 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
12375 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
12376 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
12377 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
12378 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
12379 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
12380 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
12381 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
12382 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
12384 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
12386 (when (featurep 'xemacs)
12387 (org-defkey org-mode-map 'button3 'popup-mode-menu))
12389 (defvar org-table-auto-blank-field) ; defined in org-table.el
12390 (defun org-self-insert-command (N)
12391 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
12392 If the cursor is in a table looking at whitespace, the whitespace is
12393 overwritten, and the table is not marked as requiring realignment."
12394 (interactive "p")
12395 (if (and (org-table-p)
12396 (progn
12397 ;; check if we blank the field, and if that triggers align
12398 (and (featurep 'org-table) org-table-auto-blank-field
12399 (member last-command
12400 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
12401 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
12402 ;; got extra space, this field does not determine column width
12403 (let (org-table-may-need-update) (org-table-blank-field))
12404 ;; no extra space, this field may determine column width
12405 (org-table-blank-field)))
12407 (eq N 1)
12408 (looking-at "[^|\n]* |"))
12409 (let (org-table-may-need-update)
12410 (goto-char (1- (match-end 0)))
12411 (delete-backward-char 1)
12412 (goto-char (match-beginning 0))
12413 (self-insert-command N))
12414 (setq org-table-may-need-update t)
12415 (self-insert-command N)
12416 (org-fix-tags-on-the-fly)))
12418 (defun org-fix-tags-on-the-fly ()
12419 (when (and (equal (char-after (point-at-bol)) ?*)
12420 (org-on-heading-p))
12421 (org-align-tags-here org-tags-column)))
12423 (defun org-delete-backward-char (N)
12424 "Like `delete-backward-char', insert whitespace at field end in tables.
12425 When deleting backwards, in tables this function will insert whitespace in
12426 front of the next \"|\" separator, to keep the table aligned. The table will
12427 still be marked for re-alignment if the field did fill the entire column,
12428 because, in this case the deletion might narrow the column."
12429 (interactive "p")
12430 (if (and (org-table-p)
12431 (eq N 1)
12432 (string-match "|" (buffer-substring (point-at-bol) (point)))
12433 (looking-at ".*?|"))
12434 (let ((pos (point))
12435 (noalign (looking-at "[^|\n\r]* |"))
12436 (c org-table-may-need-update))
12437 (backward-delete-char N)
12438 (skip-chars-forward "^|")
12439 (insert " ")
12440 (goto-char (1- pos))
12441 ;; noalign: if there were two spaces at the end, this field
12442 ;; does not determine the width of the column.
12443 (if noalign (setq org-table-may-need-update c)))
12444 (backward-delete-char N)
12445 (org-fix-tags-on-the-fly)))
12447 (defun org-delete-char (N)
12448 "Like `delete-char', but insert whitespace at field end in tables.
12449 When deleting characters, in tables this function will insert whitespace in
12450 front of the next \"|\" separator, to keep the table aligned. The table will
12451 still be marked for re-alignment if the field did fill the entire column,
12452 because, in this case the deletion might narrow the column."
12453 (interactive "p")
12454 (if (and (org-table-p)
12455 (not (bolp))
12456 (not (= (char-after) ?|))
12457 (eq N 1))
12458 (if (looking-at ".*?|")
12459 (let ((pos (point))
12460 (noalign (looking-at "[^|\n\r]* |"))
12461 (c org-table-may-need-update))
12462 (replace-match (concat
12463 (substring (match-string 0) 1 -1)
12464 " |"))
12465 (goto-char pos)
12466 ;; noalign: if there were two spaces at the end, this field
12467 ;; does not determine the width of the column.
12468 (if noalign (setq org-table-may-need-update c)))
12469 (delete-char N))
12470 (delete-char N)
12471 (org-fix-tags-on-the-fly)))
12473 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
12474 (put 'org-self-insert-command 'delete-selection t)
12475 (put 'orgtbl-self-insert-command 'delete-selection t)
12476 (put 'org-delete-char 'delete-selection 'supersede)
12477 (put 'org-delete-backward-char 'delete-selection 'supersede)
12479 ;; Make `flyspell-mode' delay after some commands
12480 (put 'org-self-insert-command 'flyspell-delayed t)
12481 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
12482 (put 'org-delete-char 'flyspell-delayed t)
12483 (put 'org-delete-backward-char 'flyspell-delayed t)
12485 ;; Make pabbrev-mode expand after org-mode commands
12486 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
12487 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
12489 ;; How to do this: Measure non-white length of current string
12490 ;; If equal to column width, we should realign.
12492 (defun org-remap (map &rest commands)
12493 "In MAP, remap the functions given in COMMANDS.
12494 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
12495 (let (new old)
12496 (while commands
12497 (setq old (pop commands) new (pop commands))
12498 (if (fboundp 'command-remapping)
12499 (org-defkey map (vector 'remap old) new)
12500 (substitute-key-definition old new map global-map)))))
12502 (when (eq org-enable-table-editor 'optimized)
12503 ;; If the user wants maximum table support, we need to hijack
12504 ;; some standard editing functions
12505 (org-remap org-mode-map
12506 'self-insert-command 'org-self-insert-command
12507 'delete-char 'org-delete-char
12508 'delete-backward-char 'org-delete-backward-char)
12509 (org-defkey org-mode-map "|" 'org-force-self-insert))
12511 (defun org-shiftcursor-error ()
12512 "Throw an error because Shift-Cursor command was applied in wrong context."
12513 (error "This command is active in special context like tables, headlines or timestamps"))
12515 (defun org-shifttab (&optional arg)
12516 "Global visibility cycling or move to previous table field.
12517 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
12518 on context.
12519 See the individual commands for more information."
12520 (interactive "P")
12521 (cond
12522 ((org-at-table-p) (call-interactively 'org-table-previous-field))
12523 ((integerp arg)
12524 (message "Content view to level: %d" arg)
12525 (org-content (prefix-numeric-value arg))
12526 (setq org-cycle-global-status 'overview))
12527 (t (call-interactively 'org-global-cycle))))
12529 (defun org-shiftmetaleft ()
12530 "Promote subtree or delete table column.
12531 Calls `org-promote-subtree', `org-outdent-item',
12532 or `org-table-delete-column', depending on context.
12533 See the individual commands for more information."
12534 (interactive)
12535 (cond
12536 ((org-at-table-p) (call-interactively 'org-table-delete-column))
12537 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
12538 ((org-at-item-p) (call-interactively 'org-outdent-item))
12539 (t (org-shiftcursor-error))))
12541 (defun org-shiftmetaright ()
12542 "Demote subtree or insert table column.
12543 Calls `org-demote-subtree', `org-indent-item',
12544 or `org-table-insert-column', depending on context.
12545 See the individual commands for more information."
12546 (interactive)
12547 (cond
12548 ((org-at-table-p) (call-interactively 'org-table-insert-column))
12549 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
12550 ((org-at-item-p) (call-interactively 'org-indent-item))
12551 (t (org-shiftcursor-error))))
12553 (defun org-shiftmetaup (&optional arg)
12554 "Move subtree up or kill table row.
12555 Calls `org-move-subtree-up' or `org-table-kill-row' or
12556 `org-move-item-up' depending on context. See the individual commands
12557 for more information."
12558 (interactive "P")
12559 (cond
12560 ((org-at-table-p) (call-interactively 'org-table-kill-row))
12561 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12562 ((org-at-item-p) (call-interactively 'org-move-item-up))
12563 (t (org-shiftcursor-error))))
12564 (defun org-shiftmetadown (&optional arg)
12565 "Move subtree down or insert table row.
12566 Calls `org-move-subtree-down' or `org-table-insert-row' or
12567 `org-move-item-down', depending on context. See the individual
12568 commands for more information."
12569 (interactive "P")
12570 (cond
12571 ((org-at-table-p) (call-interactively 'org-table-insert-row))
12572 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12573 ((org-at-item-p) (call-interactively 'org-move-item-down))
12574 (t (org-shiftcursor-error))))
12576 (defun org-metaleft (&optional arg)
12577 "Promote heading or move table column to left.
12578 Calls `org-do-promote' or `org-table-move-column', depending on context.
12579 With no specific context, calls the Emacs default `backward-word'.
12580 See the individual commands for more information."
12581 (interactive "P")
12582 (cond
12583 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
12584 ((or (org-on-heading-p) (org-region-active-p))
12585 (call-interactively 'org-do-promote))
12586 ((org-at-item-p) (call-interactively 'org-outdent-item))
12587 (t (call-interactively 'backward-word))))
12589 (defun org-metaright (&optional arg)
12590 "Demote subtree or move table column to right.
12591 Calls `org-do-demote' or `org-table-move-column', depending on context.
12592 With no specific context, calls the Emacs default `forward-word'.
12593 See the individual commands for more information."
12594 (interactive "P")
12595 (cond
12596 ((org-at-table-p) (call-interactively 'org-table-move-column))
12597 ((or (org-on-heading-p) (org-region-active-p))
12598 (call-interactively 'org-do-demote))
12599 ((org-at-item-p) (call-interactively 'org-indent-item))
12600 (t (call-interactively 'forward-word))))
12602 (defun org-metaup (&optional arg)
12603 "Move subtree up or move table row up.
12604 Calls `org-move-subtree-up' or `org-table-move-row' or
12605 `org-move-item-up', depending on context. See the individual commands
12606 for more information."
12607 (interactive "P")
12608 (cond
12609 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
12610 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12611 ((org-at-item-p) (call-interactively 'org-move-item-up))
12612 (t (transpose-lines 1) (beginning-of-line -1))))
12614 (defun org-metadown (&optional arg)
12615 "Move subtree down or move table row down.
12616 Calls `org-move-subtree-down' or `org-table-move-row' or
12617 `org-move-item-down', depending on context. See the individual
12618 commands for more information."
12619 (interactive "P")
12620 (cond
12621 ((org-at-table-p) (call-interactively 'org-table-move-row))
12622 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12623 ((org-at-item-p) (call-interactively 'org-move-item-down))
12624 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
12626 (defun org-shiftup (&optional arg)
12627 "Increase item in timestamp or increase priority of current headline.
12628 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
12629 depending on context. See the individual commands for more information."
12630 (interactive "P")
12631 (cond
12632 ((org-at-timestamp-p t)
12633 (call-interactively (if org-edit-timestamp-down-means-later
12634 'org-timestamp-down 'org-timestamp-up)))
12635 ((org-on-heading-p) (call-interactively 'org-priority-up))
12636 ((org-at-item-p) (call-interactively 'org-previous-item))
12637 ((org-clocktable-try-shift 'up arg))
12638 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
12640 (defun org-shiftdown (&optional arg)
12641 "Decrease item in timestamp or decrease priority of current headline.
12642 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
12643 depending on context. See the individual commands for more information."
12644 (interactive "P")
12645 (cond
12646 ((org-at-timestamp-p t)
12647 (call-interactively (if org-edit-timestamp-down-means-later
12648 'org-timestamp-up 'org-timestamp-down)))
12649 ((org-on-heading-p) (call-interactively 'org-priority-down))
12650 ((org-clocktable-try-shift 'down arg))
12651 (t (call-interactively 'org-next-item))))
12653 (defun org-shiftright (&optional arg)
12654 "Next TODO keyword or timestamp one day later, depending on context."
12655 (interactive "P")
12656 (cond
12657 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
12658 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
12659 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
12660 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
12661 ((org-clocktable-try-shift 'right arg))
12662 (t (org-shiftcursor-error))))
12664 (defun org-shiftleft (&optional arg)
12665 "Previous TODO keyword or timestamp one day earlier, depending on context."
12666 (interactive "P")
12667 (cond
12668 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
12669 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
12670 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
12671 ((org-at-property-p)
12672 (call-interactively 'org-property-previous-allowed-value))
12673 ((org-clocktable-try-shift 'left arg))
12674 (t (org-shiftcursor-error))))
12676 (defun org-shiftcontrolright ()
12677 "Switch to next TODO set."
12678 (interactive)
12679 (cond
12680 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
12681 (t (org-shiftcursor-error))))
12683 (defun org-shiftcontrolleft ()
12684 "Switch to previous TODO set."
12685 (interactive)
12686 (cond
12687 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
12688 (t (org-shiftcursor-error))))
12690 (defun org-ctrl-c-ret ()
12691 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
12692 (interactive)
12693 (cond
12694 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
12695 (t (call-interactively 'org-insert-heading))))
12697 (defun org-copy-special ()
12698 "Copy region in table or copy current subtree.
12699 Calls `org-table-copy' or `org-copy-subtree', depending on context.
12700 See the individual commands for more information."
12701 (interactive)
12702 (call-interactively
12703 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
12705 (defun org-cut-special ()
12706 "Cut region in table or cut current subtree.
12707 Calls `org-table-copy' or `org-cut-subtree', depending on context.
12708 See the individual commands for more information."
12709 (interactive)
12710 (call-interactively
12711 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
12713 (defun org-paste-special (arg)
12714 "Paste rectangular region into table, or past subtree relative to level.
12715 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
12716 See the individual commands for more information."
12717 (interactive "P")
12718 (if (org-at-table-p)
12719 (org-table-paste-rectangle)
12720 (org-paste-subtree arg)))
12722 (defun org-edit-special ()
12723 "Call a special editor for the stuff at point.
12724 When at a table, call the formula editor with `org-table-edit-formulas'.
12725 When at the first line of an src example, call `org-edit-src-code'.
12726 When in an #+include line, visit the include file. Otherwise call
12727 `ffap' to visit the file at point."
12728 (interactive)
12729 (cond
12730 ((org-at-table-p)
12731 (call-interactively 'org-table-edit-formulas))
12732 ((save-excursion
12733 (beginning-of-line 1)
12734 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
12735 (find-file (org-trim (match-string 1))))
12736 ((org-edit-src-code))
12737 ((org-edit-fixed-width-region))
12738 (t (call-interactively 'ffap))))
12740 (defun org-ctrl-c-ctrl-c (&optional arg)
12741 "Set tags in headline, or update according to changed information at point.
12743 This command does many different things, depending on context:
12745 - If the cursor is in a headline, prompt for tags and insert them
12746 into the current line, aligned to `org-tags-column'. When called
12747 with prefix arg, realign all tags in the current buffer.
12749 - If the cursor is in one of the special #+KEYWORD lines, this
12750 triggers scanning the buffer for these lines and updating the
12751 information.
12753 - If the cursor is inside a table, realign the table. This command
12754 works even if the automatic table editor has been turned off.
12756 - If the cursor is on a #+TBLFM line, re-apply the formulas to
12757 the entire table.
12759 - If the cursor is a the beginning of a dynamic block, update it.
12761 - If the cursor is inside a table created by the table.el package,
12762 activate that table.
12764 - If the current buffer is a remember buffer, close note and file
12765 it. A prefix argument of 1 files to the default location
12766 without further interaction. A prefix argument of 2 files to
12767 the currently clocking task.
12769 - If the cursor is on a <<<target>>>, update radio targets and corresponding
12770 links in this buffer.
12772 - If the cursor is on a numbered item in a plain list, renumber the
12773 ordered list.
12775 - If the cursor is on a checkbox, toggle it."
12776 (interactive "P")
12777 (let ((org-enable-table-editor t))
12778 (cond
12779 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
12780 org-occur-highlights
12781 org-latex-fragment-image-overlays)
12782 (and (boundp 'org-clock-overlays) (org-remove-clock-overlays))
12783 (org-remove-occur-highlights)
12784 (org-remove-latex-fragment-image-overlays)
12785 (message "Temporary highlights/overlays removed from current buffer"))
12786 ((and (local-variable-p 'org-finish-function (current-buffer))
12787 (fboundp org-finish-function))
12788 (funcall org-finish-function))
12789 ((org-at-property-p)
12790 (call-interactively 'org-property-action))
12791 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
12792 ((org-on-heading-p) (call-interactively 'org-set-tags))
12793 ((org-at-table.el-p)
12794 (require 'table)
12795 (beginning-of-line 1)
12796 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
12797 (call-interactively 'table-recognize-table))
12798 ((org-at-table-p)
12799 (org-table-maybe-eval-formula)
12800 (if arg
12801 (call-interactively 'org-table-recalculate)
12802 (org-table-maybe-recalculate-line))
12803 (call-interactively 'org-table-align))
12804 ((org-at-item-checkbox-p)
12805 (call-interactively 'org-toggle-checkbox))
12806 ((org-at-item-p)
12807 (call-interactively 'org-maybe-renumber-ordered-list))
12808 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
12809 ;; Dynamic block
12810 (beginning-of-line 1)
12811 (save-excursion (org-update-dblock)))
12812 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
12813 (cond
12814 ((equal (match-string 1) "TBLFM")
12815 ;; Recalculate the table before this line
12816 (save-excursion
12817 (beginning-of-line 1)
12818 (skip-chars-backward " \r\n\t")
12819 (if (org-at-table-p)
12820 (org-call-with-arg 'org-table-recalculate t))))
12822 ; (org-set-regexps-and-options)
12823 ; (org-restart-font-lock)
12824 (let ((org-inhibit-startup t)) (org-mode-restart))
12825 (message "Local setup has been refreshed"))))
12826 (t (error "C-c C-c can do nothing useful at this location.")))))
12828 (defun org-mode-restart ()
12829 "Restart Org-mode, to scan again for special lines.
12830 Also updates the keyword regular expressions."
12831 (interactive)
12832 (org-mode)
12833 (message "Org-mode restarted"))
12835 (defun org-kill-note-or-show-branches ()
12836 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
12837 (interactive)
12838 (if (not org-finish-function)
12839 (call-interactively 'show-branches)
12840 (let ((org-note-abort t))
12841 (funcall org-finish-function))))
12843 (defun org-return (&optional indent)
12844 "Goto next table row or insert a newline.
12845 Calls `org-table-next-row' or `newline', depending on context.
12846 See the individual commands for more information."
12847 (interactive)
12848 (cond
12849 ((bobp) (if indent (newline-and-indent) (newline)))
12850 ((and (org-at-heading-p)
12851 (looking-at
12852 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
12853 (org-show-entry)
12854 (end-of-line 1)
12855 (newline))
12856 ((org-at-table-p)
12857 (org-table-justify-field-maybe)
12858 (call-interactively 'org-table-next-row))
12859 (t (if indent (newline-and-indent) (newline)))))
12861 (defun org-return-indent ()
12862 "Goto next table row or insert a newline and indent.
12863 Calls `org-table-next-row' or `newline-and-indent', depending on
12864 context. See the individual commands for more information."
12865 (interactive)
12866 (org-return t))
12868 (defun org-ctrl-c-star ()
12869 "Compute table, or change heading status of lines.
12870 Calls `org-table-recalculate' or `org-toggle-region-headings',
12871 depending on context. This will also turn a plain list item or a normal
12872 line into a subheading."
12873 (interactive)
12874 (cond
12875 ((org-at-table-p)
12876 (call-interactively 'org-table-recalculate))
12877 ((org-region-active-p)
12878 ;; Convert all lines in region to list items
12879 (call-interactively 'org-toggle-region-headings))
12880 ((org-on-heading-p)
12881 (org-toggle-region-headings (point-at-bol)
12882 (min (1+ (point-at-eol)) (point-max))))
12883 ((org-at-item-p)
12884 ;; Convert to heading
12885 (let ((level (save-match-data
12886 (save-excursion
12887 (condition-case nil
12888 (progn
12889 (org-back-to-heading t)
12890 (funcall outline-level))
12891 (error 0))))))
12892 (replace-match
12893 (concat (make-string (org-get-valid-level level 1) ?*) " ") t t)))
12894 (t (org-toggle-region-headings (point-at-bol)
12895 (min (1+ (point-at-eol)) (point-max))))))
12897 (defun org-ctrl-c-minus ()
12898 "Insert separator line in table or modify bullet status of line.
12899 Also turns a plain line or a region of lines into list items.
12900 Calls `org-table-insert-hline', `org-toggle-region-items', or
12901 `org-cycle-list-bullet', depending on context."
12902 (interactive)
12903 (cond
12904 ((org-at-table-p)
12905 (call-interactively 'org-table-insert-hline))
12906 ((org-on-heading-p)
12907 ;; Convert to item
12908 (save-excursion
12909 (beginning-of-line 1)
12910 (if (looking-at "\\*+ ")
12911 (replace-match (concat (make-string (- (match-end 0) (point) 1) ?\ ) "- ")))))
12912 ((org-region-active-p)
12913 ;; Convert all lines in region to list items
12914 (call-interactively 'org-toggle-region-items))
12915 ((org-in-item-p)
12916 (call-interactively 'org-cycle-list-bullet))
12917 (t (org-toggle-region-items (point-at-bol)
12918 (min (1+ (point-at-eol)) (point-max))))))
12920 (defun org-toggle-region-items (beg end)
12921 "Convert all lines in region to list items.
12922 If the first line is already an item, convert all list items in the region
12923 to normal lines."
12924 (interactive "r")
12925 (let (l2 l)
12926 (save-excursion
12927 (goto-char end)
12928 (setq l2 (org-current-line))
12929 (goto-char beg)
12930 (beginning-of-line 1)
12931 (setq l (1- (org-current-line)))
12932 (if (org-at-item-p)
12933 ;; We already have items, de-itemize
12934 (while (< (setq l (1+ l)) l2)
12935 (when (org-at-item-p)
12936 (goto-char (match-beginning 2))
12937 (delete-region (match-beginning 2) (match-end 2))
12938 (and (looking-at "[ \t]+") (replace-match "")))
12939 (beginning-of-line 2))
12940 (while (< (setq l (1+ l)) l2)
12941 (unless (org-at-item-p)
12942 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
12943 (replace-match "\\1- \\2")))
12944 (beginning-of-line 2))))))
12946 (defun org-toggle-region-headings (beg end)
12947 "Convert all lines in region to list items.
12948 If the first line is already an item, convert all list items in the region
12949 to normal lines."
12950 (interactive "r")
12951 (let (l2 l)
12952 (save-excursion
12953 (goto-char end)
12954 (setq l2 (org-current-line))
12955 (goto-char beg)
12956 (beginning-of-line 1)
12957 (setq l (1- (org-current-line)))
12958 (if (org-on-heading-p)
12959 ;; We already have headlines, de-star them
12960 (while (< (setq l (1+ l)) l2)
12961 (when (org-on-heading-p t)
12962 (and (looking-at outline-regexp) (replace-match "")))
12963 (beginning-of-line 2))
12964 (let* ((stars (save-excursion
12965 (re-search-backward org-complex-heading-regexp nil t)
12966 (or (match-string 1) "*")))
12967 (add-stars (if org-odd-levels-only "**" "*"))
12968 (rpl (concat stars add-stars " \\2")))
12969 (while (< (setq l (1+ l)) l2)
12970 (unless (org-on-heading-p)
12971 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
12972 (replace-match rpl)))
12973 (beginning-of-line 2)))))))
12975 (defun org-meta-return (&optional arg)
12976 "Insert a new heading or wrap a region in a table.
12977 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
12978 See the individual commands for more information."
12979 (interactive "P")
12980 (cond
12981 ((org-at-table-p)
12982 (call-interactively 'org-table-wrap-region))
12983 (t (call-interactively 'org-insert-heading))))
12985 ;;; Menu entries
12987 ;; Define the Org-mode menus
12988 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
12989 '("Tbl"
12990 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
12991 ["Next Field" org-cycle (org-at-table-p)]
12992 ["Previous Field" org-shifttab (org-at-table-p)]
12993 ["Next Row" org-return (org-at-table-p)]
12994 "--"
12995 ["Blank Field" org-table-blank-field (org-at-table-p)]
12996 ["Edit Field" org-table-edit-field (org-at-table-p)]
12997 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
12998 "--"
12999 ("Column"
13000 ["Move Column Left" org-metaleft (org-at-table-p)]
13001 ["Move Column Right" org-metaright (org-at-table-p)]
13002 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
13003 ["Insert Column" org-shiftmetaright (org-at-table-p)])
13004 ("Row"
13005 ["Move Row Up" org-metaup (org-at-table-p)]
13006 ["Move Row Down" org-metadown (org-at-table-p)]
13007 ["Delete Row" org-shiftmetaup (org-at-table-p)]
13008 ["Insert Row" org-shiftmetadown (org-at-table-p)]
13009 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
13010 "--"
13011 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
13012 ("Rectangle"
13013 ["Copy Rectangle" org-copy-special (org-at-table-p)]
13014 ["Cut Rectangle" org-cut-special (org-at-table-p)]
13015 ["Paste Rectangle" org-paste-special (org-at-table-p)]
13016 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
13017 "--"
13018 ("Calculate"
13019 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
13020 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
13021 ["Edit Formulas" org-edit-special (org-at-table-p)]
13022 "--"
13023 ["Recalculate line" org-table-recalculate (org-at-table-p)]
13024 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
13025 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
13026 "--"
13027 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
13028 "--"
13029 ["Sum Column/Rectangle" org-table-sum
13030 (or (org-at-table-p) (org-region-active-p))]
13031 ["Which Column?" org-table-current-column (org-at-table-p)])
13032 ["Debug Formulas"
13033 org-table-toggle-formula-debugger
13034 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
13035 ["Show Col/Row Numbers"
13036 org-table-toggle-coordinate-overlays
13037 :style toggle
13038 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
13039 "--"
13040 ["Create" org-table-create (and (not (org-at-table-p))
13041 org-enable-table-editor)]
13042 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
13043 ["Import from File" org-table-import (not (org-at-table-p))]
13044 ["Export to File" org-table-export (org-at-table-p)]
13045 "--"
13046 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
13048 (easy-menu-define org-org-menu org-mode-map "Org menu"
13049 '("Org"
13050 ("Show/Hide"
13051 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
13052 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
13053 ["Sparse Tree..." org-sparse-tree t]
13054 ["Reveal Context" org-reveal t]
13055 ["Show All" show-all t]
13056 "--"
13057 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
13058 "--"
13059 ["New Heading" org-insert-heading t]
13060 ("Navigate Headings"
13061 ["Up" outline-up-heading t]
13062 ["Next" outline-next-visible-heading t]
13063 ["Previous" outline-previous-visible-heading t]
13064 ["Next Same Level" outline-forward-same-level t]
13065 ["Previous Same Level" outline-backward-same-level t]
13066 "--"
13067 ["Jump" org-goto t])
13068 ("Edit Structure"
13069 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
13070 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
13071 "--"
13072 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
13073 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
13074 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
13075 "--"
13076 ["Promote Heading" org-metaleft (not (org-at-table-p))]
13077 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
13078 ["Demote Heading" org-metaright (not (org-at-table-p))]
13079 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
13080 "--"
13081 ["Sort Region/Children" org-sort (not (org-at-table-p))]
13082 "--"
13083 ["Convert to odd levels" org-convert-to-odd-levels t]
13084 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
13085 ("Editing"
13086 ["Emphasis..." org-emphasize t]
13087 ["Edit Source Example" org-edit-special t])
13088 ("Archive"
13089 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
13090 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
13091 ; :active t :keys "C-u C-c C-x C-a"]
13092 ["Sparse trees open ARCHIVE trees"
13093 (setq org-sparse-tree-open-archived-trees
13094 (not org-sparse-tree-open-archived-trees))
13095 :style toggle :selected org-sparse-tree-open-archived-trees]
13096 ["Cycling opens ARCHIVE trees"
13097 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
13098 :style toggle :selected org-cycle-open-archived-trees]
13099 "--"
13100 ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
13101 ["Move Subtree to Archive" org-advertized-archive-subtree t]
13102 ; ["Check and Move Children" (org-archive-subtree '(4))
13103 ; :active t :keys "C-u C-c C-x C-s"]
13105 "--"
13106 ("TODO Lists"
13107 ["TODO/DONE/-" org-todo t]
13108 ("Select keyword"
13109 ["Next keyword" org-shiftright (org-on-heading-p)]
13110 ["Previous keyword" org-shiftleft (org-on-heading-p)]
13111 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
13112 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
13113 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
13114 ["Show TODO Tree" org-show-todo-tree t]
13115 ["Global TODO list" org-todo-list t]
13116 "--"
13117 ["Set Priority" org-priority t]
13118 ["Priority Up" org-shiftup t]
13119 ["Priority Down" org-shiftdown t])
13120 ("TAGS and Properties"
13121 ["Set Tags" 'org-set-tags-command t]
13122 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
13123 "--"
13124 ["Set property" 'org-set-property t]
13125 ["Column view of properties" org-columns t]
13126 ["Insert Column View DBlock" org-insert-columns-dblock t])
13127 ("Dates and Scheduling"
13128 ["Timestamp" org-time-stamp t]
13129 ["Timestamp (inactive)" org-time-stamp-inactive t]
13130 ("Change Date"
13131 ["1 Day Later" org-shiftright t]
13132 ["1 Day Earlier" org-shiftleft t]
13133 ["1 ... Later" org-shiftup t]
13134 ["1 ... Earlier" org-shiftdown t])
13135 ["Compute Time Range" org-evaluate-time-range t]
13136 ["Schedule Item" org-schedule t]
13137 ["Deadline" org-deadline t]
13138 "--"
13139 ["Custom time format" org-toggle-time-stamp-overlays
13140 :style radio :selected org-display-custom-times]
13141 "--"
13142 ["Goto Calendar" org-goto-calendar t]
13143 ["Date from Calendar" org-date-from-calendar t])
13144 ("Logging work"
13145 ["Clock in" org-clock-in t]
13146 ["Clock out" org-clock-out t]
13147 ["Clock cancel" org-clock-cancel t]
13148 ["Goto running clock" org-clock-goto t]
13149 ["Display times" org-clock-display t]
13150 ["Create clock table" org-clock-report t]
13151 "--"
13152 ["Record DONE time"
13153 (progn (setq org-log-done (not org-log-done))
13154 (message "Switching to %s will %s record a timestamp"
13155 (car org-done-keywords)
13156 (if org-log-done "automatically" "not")))
13157 :style toggle :selected org-log-done])
13158 "--"
13159 ["Agenda Command..." org-agenda t]
13160 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
13161 ("File List for Agenda")
13162 ("Special views current file"
13163 ["TODO Tree" org-show-todo-tree t]
13164 ["Check Deadlines" org-check-deadlines t]
13165 ["Timeline" org-timeline t]
13166 ["Tags Tree" org-tags-sparse-tree t])
13167 "--"
13168 ("Hyperlinks"
13169 ["Store Link (Global)" org-store-link t]
13170 ["Insert Link" org-insert-link t]
13171 ["Follow Link" org-open-at-point t]
13172 "--"
13173 ["Next link" org-next-link t]
13174 ["Previous link" org-previous-link t]
13175 "--"
13176 ["Descriptive Links"
13177 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
13178 :style radio
13179 :selected (member '(org-link) buffer-invisibility-spec)]
13180 ["Literal Links"
13181 (progn
13182 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
13183 :style radio
13184 :selected (not (member '(org-link) buffer-invisibility-spec))])
13185 "--"
13186 ["Export/Publish..." org-export t]
13187 ("LaTeX"
13188 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
13189 :selected org-cdlatex-mode]
13190 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
13191 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
13192 ["Modify math symbol" org-cdlatex-math-modify
13193 (org-inside-LaTeX-fragment-p)]
13194 ["Export LaTeX fragments as images"
13195 (if (featurep 'org-exp)
13196 (setq org-export-with-LaTeX-fragments
13197 (not org-export-with-LaTeX-fragments))
13198 (require 'org-exp))
13199 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
13200 org-export-with-LaTeX-fragments)])
13201 "--"
13202 ("Documentation"
13203 ["Show Version" org-version t]
13204 ["Info Documentation" org-info t])
13205 ("Customize"
13206 ["Browse Org Group" org-customize t]
13207 "--"
13208 ["Expand This Menu" org-create-customize-menu
13209 (fboundp 'customize-menu-create)])
13210 "--"
13211 ["Refresh setup" org-mode-restart t]
13214 (defun org-info (&optional node)
13215 "Read documentation for Org-mode in the info system.
13216 With optional NODE, go directly to that node."
13217 (interactive)
13218 (info (format "(org)%s" (or node ""))))
13220 (defun org-install-agenda-files-menu ()
13221 (let ((bl (buffer-list)))
13222 (save-excursion
13223 (while bl
13224 (set-buffer (pop bl))
13225 (if (org-mode-p) (setq bl nil)))
13226 (when (org-mode-p)
13227 (easy-menu-change
13228 '("Org") "File List for Agenda"
13229 (append
13230 (list
13231 ["Edit File List" (org-edit-agenda-file-list) t]
13232 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
13233 ["Remove Current File from List" org-remove-file t]
13234 ["Cycle through agenda files" org-cycle-agenda-files t]
13235 ["Occur in all agenda files" org-occur-in-agenda-files t]
13236 "--")
13237 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
13239 ;;;; Documentation
13241 ;;;###autoload
13242 (defun org-require-autoloaded-modules ()
13243 (interactive)
13244 (mapc 'require
13245 '(org-agenda org-archive org-clock org-colview
13246 org-exp org-id org-export-latex org-publish
13247 org-remember org-table)))
13249 ;;;###autoload
13250 (defun org-customize ()
13251 "Call the customize function with org as argument."
13252 (interactive)
13253 (org-load-modules-maybe)
13254 (org-require-autoloaded-modules)
13255 (customize-browse 'org))
13257 (defun org-create-customize-menu ()
13258 "Create a full customization menu for Org-mode, insert it into the menu."
13259 (interactive)
13260 (org-load-modules-maybe)
13261 (org-require-autoloaded-modules)
13262 (if (fboundp 'customize-menu-create)
13263 (progn
13264 (easy-menu-change
13265 '("Org") "Customize"
13266 `(["Browse Org group" org-customize t]
13267 "--"
13268 ,(customize-menu-create 'org)
13269 ["Set" Custom-set t]
13270 ["Save" Custom-save t]
13271 ["Reset to Current" Custom-reset-current t]
13272 ["Reset to Saved" Custom-reset-saved t]
13273 ["Reset to Standard Settings" Custom-reset-standard t]))
13274 (message "\"Org\"-menu now contains full customization menu"))
13275 (error "Cannot expand menu (outdated version of cus-edit.el)")))
13277 ;;;; Miscellaneous stuff
13279 ;;; Generally useful functions
13281 (defun org-display-warning (message) ;; Copied from Emacs-Muse
13282 "Display the given MESSAGE as a warning."
13283 (if (fboundp 'display-warning)
13284 (display-warning 'org message
13285 (if (featurep 'xemacs)
13286 'warning
13287 :warning))
13288 (let ((buf (get-buffer-create "*Org warnings*")))
13289 (with-current-buffer buf
13290 (goto-char (point-max))
13291 (insert "Warning (Org): " message)
13292 (unless (bolp)
13293 (newline)))
13294 (display-buffer buf)
13295 (sit-for 0))))
13297 (defun org-goto-marker-or-bmk (marker &optional bookmark)
13298 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
13299 (if (and marker (marker-buffer marker)
13300 (buffer-live-p (marker-buffer marker)))
13301 (progn
13302 (switch-to-buffer (marker-buffer marker))
13303 (if (or (> marker (point-max)) (< marker (point-min)))
13304 (widen))
13305 (goto-char marker))
13306 (if bookmark
13307 (bookmark-jump bookmark)
13308 (error "Cannot find location"))))
13310 (defun org-quote-csv-field (s)
13311 "Quote field for inclusion in CSV material."
13312 (if (string-match "[\",]" s)
13313 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
13316 (defun org-plist-delete (plist property)
13317 "Delete PROPERTY from PLIST.
13318 This is in contrast to merely setting it to 0."
13319 (let (p)
13320 (while plist
13321 (if (not (eq property (car plist)))
13322 (setq p (plist-put p (car plist) (nth 1 plist))))
13323 (setq plist (cddr plist)))
13326 (defun org-force-self-insert (N)
13327 "Needed to enforce self-insert under remapping."
13328 (interactive "p")
13329 (self-insert-command N))
13331 (defun org-string-width (s)
13332 "Compute width of string, ignoring invisible characters.
13333 This ignores character with invisibility property `org-link', and also
13334 characters with property `org-cwidth', because these will become invisible
13335 upon the next fontification round."
13336 (let (b l)
13337 (when (or (eq t buffer-invisibility-spec)
13338 (assq 'org-link buffer-invisibility-spec))
13339 (while (setq b (text-property-any 0 (length s)
13340 'invisible 'org-link s))
13341 (setq s (concat (substring s 0 b)
13342 (substring s (or (next-single-property-change
13343 b 'invisible s) (length s)))))))
13344 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
13345 (setq s (concat (substring s 0 b)
13346 (substring s (or (next-single-property-change
13347 b 'org-cwidth s) (length s))))))
13348 (setq l (string-width s) b -1)
13349 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
13350 (setq l (- l (get-text-property b 'org-dwidth-n s))))
13353 (defun org-get-indentation (&optional line)
13354 "Get the indentation of the current line, interpreting tabs.
13355 When LINE is given, assume it represents a line and compute its indentation."
13356 (if line
13357 (if (string-match "^ *" (org-remove-tabs line))
13358 (match-end 0))
13359 (save-excursion
13360 (beginning-of-line 1)
13361 (skip-chars-forward " \t")
13362 (current-column))))
13364 (defun org-remove-tabs (s &optional width)
13365 "Replace tabulators in S with spaces.
13366 Assumes that s is a single line, starting in column 0."
13367 (setq width (or width tab-width))
13368 (while (string-match "\t" s)
13369 (setq s (replace-match
13370 (make-string
13371 (- (* width (/ (+ (match-beginning 0) width) width))
13372 (match-beginning 0)) ?\ )
13373 t t s)))
13376 (defun org-fix-indentation (line ind)
13377 "Fix indentation in LINE.
13378 IND is a cons cell with target and minimum indentation.
13379 If the current indenation in LINE is smaller than the minimum,
13380 leave it alone. If it is larger than ind, set it to the target."
13381 (let* ((l (org-remove-tabs line))
13382 (i (org-get-indentation l))
13383 (i1 (car ind)) (i2 (cdr ind)))
13384 (if (>= i i2) (setq l (substring line i2)))
13385 (if (> i1 0)
13386 (concat (make-string i1 ?\ ) l)
13387 l)))
13389 (defun org-base-buffer (buffer)
13390 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
13391 (if (not buffer)
13392 buffer
13393 (or (buffer-base-buffer buffer)
13394 buffer)))
13396 (defun org-trim (s)
13397 "Remove whitespace at beginning and end of string."
13398 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
13399 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
13402 (defun org-wrap (string &optional width lines)
13403 "Wrap string to either a number of lines, or a width in characters.
13404 If WIDTH is non-nil, the string is wrapped to that width, however many lines
13405 that costs. If there is a word longer than WIDTH, the text is actually
13406 wrapped to the length of that word.
13407 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
13408 many lines, whatever width that takes.
13409 The return value is a list of lines, without newlines at the end."
13410 (let* ((words (org-split-string string "[ \t\n]+"))
13411 (maxword (apply 'max (mapcar 'org-string-width words)))
13412 w ll)
13413 (cond (width
13414 (org-do-wrap words (max maxword width)))
13415 (lines
13416 (setq w maxword)
13417 (setq ll (org-do-wrap words maxword))
13418 (if (<= (length ll) lines)
13420 (setq ll words)
13421 (while (> (length ll) lines)
13422 (setq w (1+ w))
13423 (setq ll (org-do-wrap words w)))
13424 ll))
13425 (t (error "Cannot wrap this")))))
13427 (defun org-do-wrap (words width)
13428 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
13429 (let (lines line)
13430 (while words
13431 (setq line (pop words))
13432 (while (and words (< (+ (length line) (length (car words))) width))
13433 (setq line (concat line " " (pop words))))
13434 (setq lines (push line lines)))
13435 (nreverse lines)))
13437 (defun org-split-string (string &optional separators)
13438 "Splits STRING into substrings at SEPARATORS.
13439 No empty strings are returned if there are matches at the beginning
13440 and end of string."
13441 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
13442 (start 0)
13443 notfirst
13444 (list nil))
13445 (while (and (string-match rexp string
13446 (if (and notfirst
13447 (= start (match-beginning 0))
13448 (< start (length string)))
13449 (1+ start) start))
13450 (< (match-beginning 0) (length string)))
13451 (setq notfirst t)
13452 (or (eq (match-beginning 0) 0)
13453 (and (eq (match-beginning 0) (match-end 0))
13454 (eq (match-beginning 0) start))
13455 (setq list
13456 (cons (substring string start (match-beginning 0))
13457 list)))
13458 (setq start (match-end 0)))
13459 (or (eq start (length string))
13460 (setq list
13461 (cons (substring string start)
13462 list)))
13463 (nreverse list)))
13465 (defun org-context ()
13466 "Return a list of contexts of the current cursor position.
13467 If several contexts apply, all are returned.
13468 Each context entry is a list with a symbol naming the context, and
13469 two positions indicating start and end of the context. Possible
13470 contexts are:
13472 :headline anywhere in a headline
13473 :headline-stars on the leading stars in a headline
13474 :todo-keyword on a TODO keyword (including DONE) in a headline
13475 :tags on the TAGS in a headline
13476 :priority on the priority cookie in a headline
13477 :item on the first line of a plain list item
13478 :item-bullet on the bullet/number of a plain list item
13479 :checkbox on the checkbox in a plain list item
13480 :table in an org-mode table
13481 :table-special on a special filed in a table
13482 :table-table in a table.el table
13483 :link on a hyperlink
13484 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
13485 :target on a <<target>>
13486 :radio-target on a <<<radio-target>>>
13487 :latex-fragment on a LaTeX fragment
13488 :latex-preview on a LaTeX fragment with overlayed preview image
13490 This function expects the position to be visible because it uses font-lock
13491 faces as a help to recognize the following contexts: :table-special, :link,
13492 and :keyword."
13493 (let* ((f (get-text-property (point) 'face))
13494 (faces (if (listp f) f (list f)))
13495 (p (point)) clist o)
13496 ;; First the large context
13497 (cond
13498 ((org-on-heading-p t)
13499 (push (list :headline (point-at-bol) (point-at-eol)) clist)
13500 (when (progn
13501 (beginning-of-line 1)
13502 (looking-at org-todo-line-tags-regexp))
13503 (push (org-point-in-group p 1 :headline-stars) clist)
13504 (push (org-point-in-group p 2 :todo-keyword) clist)
13505 (push (org-point-in-group p 4 :tags) clist))
13506 (goto-char p)
13507 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
13508 (if (looking-at "\\[#[A-Z0-9]\\]")
13509 (push (org-point-in-group p 0 :priority) clist)))
13511 ((org-at-item-p)
13512 (push (org-point-in-group p 2 :item-bullet) clist)
13513 (push (list :item (point-at-bol)
13514 (save-excursion (org-end-of-item) (point)))
13515 clist)
13516 (and (org-at-item-checkbox-p)
13517 (push (org-point-in-group p 0 :checkbox) clist)))
13519 ((org-at-table-p)
13520 (push (list :table (org-table-begin) (org-table-end)) clist)
13521 (if (memq 'org-formula faces)
13522 (push (list :table-special
13523 (previous-single-property-change p 'face)
13524 (next-single-property-change p 'face)) clist)))
13525 ((org-at-table-p 'any)
13526 (push (list :table-table) clist)))
13527 (goto-char p)
13529 ;; Now the small context
13530 (cond
13531 ((org-at-timestamp-p)
13532 (push (org-point-in-group p 0 :timestamp) clist))
13533 ((memq 'org-link faces)
13534 (push (list :link
13535 (previous-single-property-change p 'face)
13536 (next-single-property-change p 'face)) clist))
13537 ((memq 'org-special-keyword faces)
13538 (push (list :keyword
13539 (previous-single-property-change p 'face)
13540 (next-single-property-change p 'face)) clist))
13541 ((org-on-target-p)
13542 (push (org-point-in-group p 0 :target) clist)
13543 (goto-char (1- (match-beginning 0)))
13544 (if (looking-at org-radio-target-regexp)
13545 (push (org-point-in-group p 0 :radio-target) clist))
13546 (goto-char p))
13547 ((setq o (car (delq nil
13548 (mapcar
13549 (lambda (x)
13550 (if (memq x org-latex-fragment-image-overlays) x))
13551 (org-overlays-at (point))))))
13552 (push (list :latex-fragment
13553 (org-overlay-start o) (org-overlay-end o)) clist)
13554 (push (list :latex-preview
13555 (org-overlay-start o) (org-overlay-end o)) clist))
13556 ((org-inside-LaTeX-fragment-p)
13557 ;; FIXME: positions wrong.
13558 (push (list :latex-fragment (point) (point)) clist)))
13560 (setq clist (nreverse (delq nil clist)))
13561 clist))
13563 ;; FIXME: Compare with at-regexp-p Do we need both?
13564 (defun org-in-regexp (re &optional nlines visually)
13565 "Check if point is inside a match of regexp.
13566 Normally only the current line is checked, but you can include NLINES extra
13567 lines both before and after point into the search.
13568 If VISUALLY is set, require that the cursor is not after the match but
13569 really on, so that the block visually is on the match."
13570 (catch 'exit
13571 (let ((pos (point))
13572 (eol (point-at-eol (+ 1 (or nlines 0))))
13573 (inc (if visually 1 0)))
13574 (save-excursion
13575 (beginning-of-line (- 1 (or nlines 0)))
13576 (while (re-search-forward re eol t)
13577 (if (and (<= (match-beginning 0) pos)
13578 (>= (+ inc (match-end 0)) pos))
13579 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
13581 (defun org-at-regexp-p (regexp)
13582 "Is point inside a match of REGEXP in the current line?"
13583 (catch 'exit
13584 (save-excursion
13585 (let ((pos (point)) (end (point-at-eol)))
13586 (beginning-of-line 1)
13587 (while (re-search-forward regexp end t)
13588 (if (and (<= (match-beginning 0) pos)
13589 (>= (match-end 0) pos))
13590 (throw 'exit t)))
13591 nil))))
13593 (defun org-occur-in-agenda-files (regexp &optional nlines)
13594 "Call `multi-occur' with buffers for all agenda files."
13595 (interactive "sOrg-files matching: \np")
13596 (let* ((files (org-agenda-files))
13597 (tnames (mapcar 'file-truename files))
13598 (extra org-agenda-text-search-extra-files)
13600 (when (eq (car extra) 'agenda-archives)
13601 (setq extra (cdr extra))
13602 (setq files (org-add-archive-files files)))
13603 (while (setq f (pop extra))
13604 (unless (member (file-truename f) tnames)
13605 (add-to-list 'files f 'append)
13606 (add-to-list 'tnames (file-truename f) 'append)))
13607 (multi-occur
13608 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
13609 regexp)))
13611 (if (boundp 'occur-mode-find-occurrence-hook)
13612 ;; Emacs 23
13613 (add-hook 'occur-mode-find-occurrence-hook
13614 (lambda ()
13615 (when (org-mode-p)
13616 (org-reveal))))
13617 ;; Emacs 22
13618 (defadvice occur-mode-goto-occurrence
13619 (after org-occur-reveal activate)
13620 (and (org-mode-p) (org-reveal)))
13621 (defadvice occur-mode-goto-occurrence-other-window
13622 (after org-occur-reveal activate)
13623 (and (org-mode-p) (org-reveal)))
13624 (defadvice occur-mode-display-occurrence
13625 (after org-occur-reveal activate)
13626 (when (org-mode-p)
13627 (let ((pos (occur-mode-find-occurrence)))
13628 (with-current-buffer (marker-buffer pos)
13629 (save-excursion
13630 (goto-char pos)
13631 (org-reveal)))))))
13633 (defun org-uniquify (list)
13634 "Remove duplicate elements from LIST."
13635 (let (res)
13636 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
13637 res))
13639 (defun org-delete-all (elts list)
13640 "Remove all elements in ELTS from LIST."
13641 (while elts
13642 (setq list (delete (pop elts) list)))
13643 list)
13645 (defun org-back-over-empty-lines ()
13646 "Move backwards over witespace, to the beginning of the first empty line.
13647 Returns the number of empty lines passed."
13648 (let ((pos (point)))
13649 (skip-chars-backward " \t\n\r")
13650 (beginning-of-line 2)
13651 (goto-char (min (point) pos))
13652 (count-lines (point) pos)))
13654 (defun org-skip-whitespace ()
13655 (skip-chars-forward " \t\n\r"))
13657 (defun org-point-in-group (point group &optional context)
13658 "Check if POINT is in match-group GROUP.
13659 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
13660 match. If the match group does ot exist or point is not inside it,
13661 return nil."
13662 (and (match-beginning group)
13663 (>= point (match-beginning group))
13664 (<= point (match-end group))
13665 (if context
13666 (list context (match-beginning group) (match-end group))
13667 t)))
13669 (defun org-switch-to-buffer-other-window (&rest args)
13670 "Switch to buffer in a second window on the current frame.
13671 In particular, do not allow pop-up frames."
13672 (let (pop-up-frames special-display-buffer-names special-display-regexps
13673 special-display-function)
13674 (apply 'switch-to-buffer-other-window args)))
13676 (defun org-combine-plists (&rest plists)
13677 "Create a single property list from all plists in PLISTS.
13678 The process starts by copying the first list, and then setting properties
13679 from the other lists. Settings in the last list are the most significant
13680 ones and overrule settings in the other lists."
13681 (let ((rtn (copy-sequence (pop plists)))
13682 p v ls)
13683 (while plists
13684 (setq ls (pop plists))
13685 (while ls
13686 (setq p (pop ls) v (pop ls))
13687 (setq rtn (plist-put rtn p v))))
13688 rtn))
13690 (defun org-move-line-down (arg)
13691 "Move the current line down. With prefix argument, move it past ARG lines."
13692 (interactive "p")
13693 (let ((col (current-column))
13694 beg end pos)
13695 (beginning-of-line 1) (setq beg (point))
13696 (beginning-of-line 2) (setq end (point))
13697 (beginning-of-line (+ 1 arg))
13698 (setq pos (move-marker (make-marker) (point)))
13699 (insert (delete-and-extract-region beg end))
13700 (goto-char pos)
13701 (org-move-to-column col)))
13703 (defun org-move-line-up (arg)
13704 "Move the current line up. With prefix argument, move it past ARG lines."
13705 (interactive "p")
13706 (let ((col (current-column))
13707 beg end pos)
13708 (beginning-of-line 1) (setq beg (point))
13709 (beginning-of-line 2) (setq end (point))
13710 (beginning-of-line (- arg))
13711 (setq pos (move-marker (make-marker) (point)))
13712 (insert (delete-and-extract-region beg end))
13713 (goto-char pos)
13714 (org-move-to-column col)))
13716 (defun org-replace-escapes (string table)
13717 "Replace %-escapes in STRING with values in TABLE.
13718 TABLE is an association list with keys like \"%a\" and string values.
13719 The sequences in STRING may contain normal field width and padding information,
13720 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
13721 so values can contain further %-escapes if they are define later in TABLE."
13722 (let ((case-fold-search nil)
13723 e re rpl)
13724 (while (setq e (pop table))
13725 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
13726 (while (string-match re string)
13727 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
13728 (cdr e)))
13729 (setq string (replace-match rpl t t string))))
13730 string))
13733 (defun org-sublist (list start end)
13734 "Return a section of LIST, from START to END.
13735 Counting starts at 1."
13736 (let (rtn (c start))
13737 (setq list (nthcdr (1- start) list))
13738 (while (and list (<= c end))
13739 (push (pop list) rtn)
13740 (setq c (1+ c)))
13741 (nreverse rtn)))
13743 (defun org-find-base-buffer-visiting (file)
13744 "Like `find-buffer-visiting' but alway return the base buffer and
13745 not an indirect buffer."
13746 (let ((buf (find-buffer-visiting file)))
13747 (if buf
13748 (or (buffer-base-buffer buf) buf)
13749 nil)))
13751 (defun org-image-file-name-regexp ()
13752 "Return regexp matching the file names of images."
13753 (if (fboundp 'image-file-name-regexp)
13754 (image-file-name-regexp)
13755 (let ((image-file-name-extensions
13756 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
13757 "xbm" "xpm" "pbm" "pgm" "ppm")))
13758 (concat "\\."
13759 (regexp-opt (nconc (mapcar 'upcase
13760 image-file-name-extensions)
13761 image-file-name-extensions)
13763 "\\'"))))
13765 (defun org-file-image-p (file)
13766 "Return non-nil if FILE is an image."
13767 (save-match-data
13768 (string-match (org-image-file-name-regexp) file)))
13770 (defun org-get-cursor-date ()
13771 "Return the date at cursor in as a time.
13772 This works in the calendar and in the agenda, anywhere else it just
13773 returns the current time."
13774 (let (date day defd)
13775 (cond
13776 ((eq major-mode 'calendar-mode)
13777 (setq date (calendar-cursor-to-date)
13778 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13779 ((eq major-mode 'org-agenda-mode)
13780 (setq day (get-text-property (point) 'day))
13781 (if day
13782 (setq date (calendar-gregorian-from-absolute day)
13783 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
13784 (nth 2 date))))))
13785 (or defd (current-time))))
13787 (defvar org-agenda-action-marker (make-marker)
13788 "Marker pointing to the entry for the next agenda action.")
13790 (defun org-mark-entry-for-agenda-action ()
13791 "Mark the current entry as target of an agenda action.
13792 Agenda actions are actions executed from the agenda with the key `k',
13793 which make use of the date at the cursor."
13794 (interactive)
13795 (move-marker org-agenda-action-marker
13796 (save-excursion (org-back-to-heading t) (point))
13797 (current-buffer))
13798 (message
13799 "Entry marked for action; press `k' at desired date in agenda or calendar"))
13801 ;;; Paragraph filling stuff.
13802 ;; We want this to be just right, so use the full arsenal.
13804 (defun org-indent-line-function ()
13805 "Indent line like previous, but further if previous was headline or item."
13806 (interactive)
13807 (let* ((pos (point))
13808 (itemp (org-at-item-p))
13809 column bpos bcol tpos tcol bullet btype bullet-type)
13810 ;; Find the previous relevant line
13811 (beginning-of-line 1)
13812 (cond
13813 ((looking-at "#") (setq column 0))
13814 ((looking-at "\\*+ ") (setq column 0))
13816 (beginning-of-line 0)
13817 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
13818 (beginning-of-line 0))
13819 (cond
13820 ((looking-at "\\*+[ \t]+")
13821 (if (not org-adapt-indentation)
13822 (setq column 0)
13823 (goto-char (match-end 0))
13824 (setq column (current-column))))
13825 ((org-in-item-p)
13826 (org-beginning-of-item)
13827 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
13828 (setq bpos (match-beginning 1) tpos (match-end 0)
13829 bcol (progn (goto-char bpos) (current-column))
13830 tcol (progn (goto-char tpos) (current-column))
13831 bullet (match-string 1)
13832 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
13833 (if (> tcol (+ bcol org-description-max-indent))
13834 (setq tcol (+ bcol 5)))
13835 (if (not itemp)
13836 (setq column tcol)
13837 (goto-char pos)
13838 (beginning-of-line 1)
13839 (if (looking-at "\\S-")
13840 (progn
13841 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
13842 (setq bullet (match-string 1)
13843 btype (if (string-match "[0-9]" bullet) "n" bullet))
13844 (setq column (if (equal btype bullet-type) bcol tcol)))
13845 (setq column (org-get-indentation)))))
13846 (t (setq column (org-get-indentation))))))
13847 (goto-char pos)
13848 (if (<= (current-column) (current-indentation))
13849 (org-indent-line-to column)
13850 (save-excursion (org-indent-line-to column)))
13851 (setq column (current-column))
13852 (beginning-of-line 1)
13853 (if (looking-at
13854 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
13855 (replace-match (concat "\\1" (format org-property-format
13856 (match-string 2) (match-string 3)))
13857 t nil))
13858 (org-move-to-column column)))
13860 (defun org-set-autofill-regexps ()
13861 (interactive)
13862 ;; In the paragraph separator we include headlines, because filling
13863 ;; text in a line directly attached to a headline would otherwise
13864 ;; fill the headline as well.
13865 (org-set-local 'comment-start-skip "^#+[ \t]*")
13866 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
13867 ;; The paragraph starter includes hand-formatted lists.
13868 (org-set-local 'paragraph-start
13869 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
13870 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
13871 ;; But only if the user has not turned off tables or fixed-width regions
13872 (org-set-local
13873 'auto-fill-inhibit-regexp
13874 (concat "\\*+ \\|#\\+"
13875 "\\|[ \t]*" org-keyword-time-regexp
13876 (if (or org-enable-table-editor org-enable-fixed-width-editor)
13877 (concat
13878 "\\|[ \t]*["
13879 (if org-enable-table-editor "|" "")
13880 (if org-enable-fixed-width-editor ":" "")
13881 "]"))))
13882 ;; We use our own fill-paragraph function, to make sure that tables
13883 ;; and fixed-width regions are not wrapped. That function will pass
13884 ;; through to `fill-paragraph' when appropriate.
13885 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
13886 ; Adaptive filling: To get full control, first make sure that
13887 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
13888 (org-set-local 'adaptive-fill-regexp "\000")
13889 (org-set-local 'adaptive-fill-function
13890 'org-adaptive-fill-function)
13891 (org-set-local
13892 'align-mode-rules-list
13893 '((org-in-buffer-settings
13894 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
13895 (modes . '(org-mode))))))
13897 (defun org-fill-paragraph (&optional justify)
13898 "Re-align a table, pass through to fill-paragraph if no table."
13899 (let ((table-p (org-at-table-p))
13900 (table.el-p (org-at-table.el-p)))
13901 (cond ((and (equal (char-after (point-at-bol)) ?*)
13902 (save-excursion (goto-char (point-at-bol))
13903 (looking-at outline-regexp)))
13904 t) ; skip headlines
13905 (table.el-p t) ; skip table.el tables
13906 (table-p (org-table-align) t) ; align org-mode tables
13907 (t nil)))) ; call paragraph-fill
13909 ;; For reference, this is the default value of adaptive-fill-regexp
13910 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
13912 (defun org-adaptive-fill-function ()
13913 "Return a fill prefix for org-mode files.
13914 In particular, this makes sure hanging paragraphs for hand-formatted lists
13915 work correctly."
13916 (cond ((looking-at "#[ \t]+")
13917 (match-string 0))
13918 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
13919 (save-excursion
13920 (if (> (match-end 1) (+ (match-beginning 1)
13921 org-description-max-indent))
13922 (goto-char (+ (match-beginning 1) 5))
13923 (goto-char (match-end 0)))
13924 (make-string (current-column) ?\ )))
13925 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
13926 (save-excursion
13927 (goto-char (match-end 0))
13928 (make-string (current-column) ?\ )))
13929 (t nil)))
13931 ;;; Other stuff.
13933 (defun org-toggle-fixed-width-section (arg)
13934 "Toggle the fixed-width export.
13935 If there is no active region, the QUOTE keyword at the current headline is
13936 inserted or removed. When present, it causes the text between this headline
13937 and the next to be exported as fixed-width text, and unmodified.
13938 If there is an active region, this command adds or removes a colon as the
13939 first character of this line. If the first character of a line is a colon,
13940 this line is also exported in fixed-width font."
13941 (interactive "P")
13942 (let* ((cc 0)
13943 (regionp (org-region-active-p))
13944 (beg (if regionp (region-beginning) (point)))
13945 (end (if regionp (region-end)))
13946 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
13947 (case-fold-search nil)
13948 (re "[ \t]*\\(:\\)")
13949 off)
13950 (if regionp
13951 (save-excursion
13952 (goto-char beg)
13953 (setq cc (current-column))
13954 (beginning-of-line 1)
13955 (setq off (looking-at re))
13956 (while (> nlines 0)
13957 (setq nlines (1- nlines))
13958 (beginning-of-line 1)
13959 (cond
13960 (arg
13961 (org-move-to-column cc t)
13962 (insert ":\n")
13963 (forward-line -1))
13964 ((and off (looking-at re))
13965 (replace-match "" t t nil 1))
13966 ((not off) (org-move-to-column cc t) (insert ":")))
13967 (forward-line 1)))
13968 (save-excursion
13969 (org-back-to-heading)
13970 (if (looking-at (concat outline-regexp
13971 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
13972 (replace-match "" t t nil 1)
13973 (if (looking-at outline-regexp)
13974 (progn
13975 (goto-char (match-end 0))
13976 (insert org-quote-string " "))))))))
13978 ;;;; Functions extending outline functionality
13980 (defun org-beginning-of-line (&optional arg)
13981 "Go to the beginning of the current line. If that is invisible, continue
13982 to a visible line beginning. This makes the function of C-a more intuitive.
13983 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
13984 first attempt, and only move to after the tags when the cursor is already
13985 beyond the end of the headline."
13986 (interactive "P")
13987 (let ((pos (point)) refpos)
13988 (beginning-of-line 1)
13989 (if (bobp)
13991 (backward-char 1)
13992 (if (org-invisible-p)
13993 (while (and (not (bobp)) (org-invisible-p))
13994 (backward-char 1)
13995 (beginning-of-line 1))
13996 (forward-char 1)))
13997 (when org-special-ctrl-a/e
13998 (cond
13999 ((and (looking-at org-complex-heading-regexp)
14000 (= (char-after (match-end 1)) ?\ ))
14001 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
14002 (point-at-eol)))
14003 (goto-char
14004 (if (eq org-special-ctrl-a/e t)
14005 (cond ((> pos refpos) refpos)
14006 ((= pos (point)) refpos)
14007 (t (point)))
14008 (cond ((> pos (point)) (point))
14009 ((not (eq last-command this-command)) (point))
14010 (t refpos)))))
14011 ((org-at-item-p)
14012 (goto-char
14013 (if (eq org-special-ctrl-a/e t)
14014 (cond ((> pos (match-end 4)) (match-end 4))
14015 ((= pos (point)) (match-end 4))
14016 (t (point)))
14017 (cond ((> pos (point)) (point))
14018 ((not (eq last-command this-command)) (point))
14019 (t (match-end 4))))))))
14020 (org-no-warnings
14021 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
14023 (defun org-end-of-line (&optional arg)
14024 "Go to the end of the line.
14025 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
14026 first attempt, and only move to after the tags when the cursor is already
14027 beyond the end of the headline."
14028 (interactive "P")
14029 (if (or (not org-special-ctrl-a/e)
14030 (not (org-on-heading-p)))
14031 (end-of-line arg)
14032 (let ((pos (point)))
14033 (beginning-of-line 1)
14034 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
14035 (if (eq org-special-ctrl-a/e t)
14036 (if (or (< pos (match-beginning 1))
14037 (= pos (match-end 0)))
14038 (goto-char (match-beginning 1))
14039 (goto-char (match-end 0)))
14040 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
14041 (goto-char (match-end 0))
14042 (goto-char (match-beginning 1))))
14043 (end-of-line arg))))
14044 (org-no-warnings
14045 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
14048 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
14049 (define-key org-mode-map "\C-e" 'org-end-of-line)
14051 (defun org-kill-line (&optional arg)
14052 "Kill line, to tags or end of line."
14053 (interactive "P")
14054 (cond
14055 ((or (not org-special-ctrl-k)
14056 (bolp)
14057 (not (org-on-heading-p)))
14058 (call-interactively 'kill-line))
14059 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
14060 (kill-region (point) (match-beginning 1))
14061 (org-set-tags nil t))
14062 (t (kill-region (point) (point-at-eol)))))
14064 (define-key org-mode-map "\C-k" 'org-kill-line)
14066 (defun org-yank (&optional arg)
14067 "Yank. If the kill is a subtree, treat it specially.
14068 This command will look at the current kill and check if is a single
14069 subtree, or a series of subtrees[1]. If it passes the test, and if the
14070 cursor is at the beginning of a line or after the stars of a currently
14071 empty headline, then the yank is handeled specially. How exactly depends
14072 on the value of the following variables, both set by default.
14074 org-yank-folded-subtrees
14075 When set, the subree(s) will be folded after insertion, but only
14076 if doing so would now swallow text after the yanked text.
14078 org-yank-adjusted-subtrees
14079 When set, the subtree will be promoted or demoted in order to
14080 fit into the local outline tree structure, which means that the level
14081 will be adjusted so that it becomes the smaller one of the two
14082 *visible* surrounding headings.
14084 Any prefix to this command will cause `yank' to be called directly with
14085 no special treatment. In particular, a simple `C-u' prefix will just
14086 plainly yank the text as it is.
14088 \[1] Basically, the test checks if the first non-white line is a heading
14089 and if there are no other headings with fewer stars."
14090 (interactive "P")
14091 (setq this-command 'yank)
14092 (if arg
14093 (call-interactively 'yank)
14094 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
14095 (and (org-kill-is-subtree-p)
14096 (or (bolp)
14097 (and (looking-at "[ \t]*$")
14098 (string-match
14099 "\\`\\*+\\'"
14100 (buffer-substring (point-at-bol) (point)))))))
14101 swallowp)
14102 (cond
14103 ((and subtreep org-yank-folded-subtrees)
14104 (let ((beg (point))
14105 end)
14106 (if (and subtreep org-yank-adjusted-subtrees)
14107 (org-paste-subtree nil nil 'for-yank)
14108 (call-interactively 'yank))
14109 (setq end (point))
14110 (goto-char beg)
14111 (when (and (bolp) subtreep
14112 (not (setq swallowp
14113 (org-yank-folding-would-swallow-text beg end))))
14114 (or (looking-at outline-regexp)
14115 (re-search-forward (concat "^" outline-regexp) end t))
14116 (while (and (< (point) end) (looking-at outline-regexp))
14117 (hide-subtree)
14118 (org-cycle-show-empty-lines 'folded)
14119 (condition-case nil
14120 (outline-forward-same-level 1)
14121 (error (goto-char end)))))
14122 (when swallowp
14123 (message
14124 "Yanked text not folded because that would swallow text"))
14125 (goto-char end)
14126 (skip-chars-forward " \t\n\r")
14127 (beginning-of-line 1)
14128 (push-mark beg 'nomsg)))
14129 ((and subtreep org-yank-adjusted-subtrees)
14130 (let ((beg (point-at-bol)))
14131 (org-paste-subtree nil nil 'for-yank)
14132 (push-mark beg 'nomsg)))
14134 (call-interactively 'yank))))))
14136 (defun org-yank-folding-would-swallow-text (beg end)
14137 "Would hide-subtree at BEG swallow any text after END?"
14138 (let (level)
14139 (save-excursion
14140 (goto-char beg)
14141 (when (or (looking-at outline-regexp)
14142 (re-search-forward (concat "^" outline-regexp) end t))
14143 (setq level (org-outline-level)))
14144 (goto-char end)
14145 (skip-chars-forward " \t\r\n\v\f")
14146 (if (or (eobp)
14147 (and (bolp) (looking-at org-outline-regexp)
14148 (<= (org-outline-level) level)))
14149 nil ; Nothing would be swallowed
14150 t)))) ; something would swallow
14152 (define-key org-mode-map "\C-y" 'org-yank)
14154 (defun org-invisible-p ()
14155 "Check if point is at a character currently not visible."
14156 ;; Early versions of noutline don't have `outline-invisible-p'.
14157 (if (fboundp 'outline-invisible-p)
14158 (outline-invisible-p)
14159 (get-char-property (point) 'invisible)))
14161 (defun org-invisible-p2 ()
14162 "Check if point is at a character currently not visible."
14163 (save-excursion
14164 (if (and (eolp) (not (bobp))) (backward-char 1))
14165 ;; Early versions of noutline don't have `outline-invisible-p'.
14166 (if (fboundp 'outline-invisible-p)
14167 (outline-invisible-p)
14168 (get-char-property (point) 'invisible))))
14170 (defun org-back-to-heading (&optional invisible-ok)
14171 "Call `outline-back-to-heading', but provide a better error message."
14172 (condition-case nil
14173 (outline-back-to-heading invisible-ok)
14174 (error (error "Before first headline at position %d in buffer %s"
14175 (point) (current-buffer)))))
14177 (defalias 'org-on-heading-p 'outline-on-heading-p)
14178 (defalias 'org-at-heading-p 'outline-on-heading-p)
14179 (defun org-at-heading-or-item-p ()
14180 (or (org-on-heading-p) (org-at-item-p)))
14182 (defun org-on-target-p ()
14183 (or (org-in-regexp org-radio-target-regexp)
14184 (org-in-regexp org-target-regexp)))
14186 (defun org-up-heading-all (arg)
14187 "Move to the heading line of which the present line is a subheading.
14188 This function considers both visible and invisible heading lines.
14189 With argument, move up ARG levels."
14190 (if (fboundp 'outline-up-heading-all)
14191 (outline-up-heading-all arg) ; emacs 21 version of outline.el
14192 (outline-up-heading arg t))) ; emacs 22 version of outline.el
14194 (defun org-up-heading-safe ()
14195 "Move to the heading line of which the present line is a subheading.
14196 This version will not throw an error. It will return the level of the
14197 headline found, or nil if no higher level is found."
14198 (let ((pos (point)) start-level level
14199 (re (concat "^" outline-regexp)))
14200 (catch 'exit
14201 (org-back-to-heading t)
14202 (setq start-level (funcall outline-level))
14203 (if (equal start-level 1) (throw 'exit nil))
14204 (while (re-search-backward re nil t)
14205 (setq level (funcall outline-level))
14206 (if (< level start-level) (throw 'exit level)))
14207 nil)))
14209 (defun org-first-sibling-p ()
14210 "Is this heading the first child of its parents?"
14211 (interactive)
14212 (let ((re (concat "^" outline-regexp))
14213 level l)
14214 (unless (org-at-heading-p t)
14215 (error "Not at a heading"))
14216 (setq level (funcall outline-level))
14217 (save-excursion
14218 (if (not (re-search-backward re nil t))
14220 (setq l (funcall outline-level))
14221 (< l level)))))
14223 (defun org-goto-sibling (&optional previous)
14224 "Goto the next sibling, even if it is invisible.
14225 When PREVIOUS is set, go to the previous sibling instead. Returns t
14226 when a sibling was found. When none is found, return nil and don't
14227 move point."
14228 (let ((fun (if previous 're-search-backward 're-search-forward))
14229 (pos (point))
14230 (re (concat "^" outline-regexp))
14231 level l)
14232 (when (condition-case nil (org-back-to-heading t) (error nil))
14233 (setq level (funcall outline-level))
14234 (catch 'exit
14235 (or previous (forward-char 1))
14236 (while (funcall fun re nil t)
14237 (setq l (funcall outline-level))
14238 (when (< l level) (goto-char pos) (throw 'exit nil))
14239 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
14240 (goto-char pos)
14241 nil))))
14243 (defun org-show-siblings ()
14244 "Show all siblings of the current headline."
14245 (save-excursion
14246 (while (org-goto-sibling) (org-flag-heading nil)))
14247 (save-excursion
14248 (while (org-goto-sibling 'previous)
14249 (org-flag-heading nil))))
14251 (defun org-show-hidden-entry ()
14252 "Show an entry where even the heading is hidden."
14253 (save-excursion
14254 (org-show-entry)))
14256 (defun org-flag-heading (flag &optional entry)
14257 "Flag the current heading. FLAG non-nil means make invisible.
14258 When ENTRY is non-nil, show the entire entry."
14259 (save-excursion
14260 (org-back-to-heading t)
14261 ;; Check if we should show the entire entry
14262 (if entry
14263 (progn
14264 (org-show-entry)
14265 (save-excursion
14266 (and (outline-next-heading)
14267 (org-flag-heading nil))))
14268 (outline-flag-region (max (point-min) (1- (point)))
14269 (save-excursion (outline-end-of-heading) (point))
14270 flag))))
14272 (defun org-forward-same-level (arg)
14273 "Move forward to the ARG'th subheading at same level as this one.
14274 Stop at the first and last subheadings of a superior heading.
14275 This is like outline-forward-same-level, but invisible headings are ok."
14276 (interactive "p")
14277 (org-back-to-heading t)
14278 (while (> arg 0)
14279 (let ((point-to-move-to (save-excursion
14280 (org-get-next-sibling))))
14281 (if point-to-move-to
14282 (progn
14283 (goto-char point-to-move-to)
14284 (setq arg (1- arg)))
14285 (progn
14286 (setq arg 0)
14287 (error "No following same-level heading"))))))
14289 (defun org-get-next-sibling ()
14290 "Move to next heading of the same level, and return point.
14291 If there is no such heading, return nil.
14292 This is like outline-next-sibling, but invisible headings are ok."
14293 (let ((level (funcall outline-level)))
14294 (outline-next-heading)
14295 (while (and (not (eobp)) (> (funcall outline-level) level))
14296 (outline-next-heading))
14297 (if (or (eobp) (< (funcall outline-level) level))
14299 (point))))
14301 (defun org-end-of-subtree (&optional invisible-OK to-heading)
14302 ;; This is an exact copy of the original function, but it uses
14303 ;; `org-back-to-heading', to make it work also in invisible
14304 ;; trees. And is uses an invisible-OK argument.
14305 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
14306 (org-back-to-heading invisible-OK)
14307 (let ((first t)
14308 (level (funcall outline-level)))
14309 (while (and (not (eobp))
14310 (or first (> (funcall outline-level) level)))
14311 (setq first nil)
14312 (outline-next-heading))
14313 (unless to-heading
14314 (if (memq (preceding-char) '(?\n ?\^M))
14315 (progn
14316 ;; Go to end of line before heading
14317 (forward-char -1)
14318 (if (memq (preceding-char) '(?\n ?\^M))
14319 ;; leave blank line before heading
14320 (forward-char -1))))))
14321 (point))
14323 (defun org-show-subtree ()
14324 "Show everything after this heading at deeper levels."
14325 (outline-flag-region
14326 (point)
14327 (save-excursion
14328 (outline-end-of-subtree) (outline-next-heading) (point))
14329 nil))
14331 (defun org-show-entry ()
14332 "Show the body directly following this heading.
14333 Show the heading too, if it is currently invisible."
14334 (interactive)
14335 (save-excursion
14336 (condition-case nil
14337 (progn
14338 (org-back-to-heading t)
14339 (outline-flag-region
14340 (max (point-min) (1- (point)))
14341 (save-excursion
14342 (re-search-forward
14343 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
14344 (or (match-beginning 1) (point-max)))
14345 nil))
14346 (error nil))))
14348 (defun org-make-options-regexp (kwds)
14349 "Make a regular expression for keyword lines."
14350 (concat
14352 "#?[ \t]*\\+\\("
14353 (mapconcat 'regexp-quote kwds "\\|")
14354 "\\):[ \t]*"
14355 "\\(.+\\)"))
14357 ;; Make isearch reveal the necessary context
14358 (defun org-isearch-end ()
14359 "Reveal context after isearch exits."
14360 (when isearch-success ; only if search was successful
14361 (if (featurep 'xemacs)
14362 ;; Under XEmacs, the hook is run in the correct place,
14363 ;; we directly show the context.
14364 (org-show-context 'isearch)
14365 ;; In Emacs the hook runs *before* restoring the overlays.
14366 ;; So we have to use a one-time post-command-hook to do this.
14367 ;; (Emacs 22 has a special variable, see function `org-mode')
14368 (unless (and (boundp 'isearch-mode-end-hook-quit)
14369 isearch-mode-end-hook-quit)
14370 ;; Only when the isearch was not quitted.
14371 (org-add-hook 'post-command-hook 'org-isearch-post-command
14372 'append 'local)))))
14374 (defun org-isearch-post-command ()
14375 "Remove self from hook, and show context."
14376 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
14377 (org-show-context 'isearch))
14380 ;;;; Integration with and fixes for other packages
14382 ;;; Imenu support
14384 (defvar org-imenu-markers nil
14385 "All markers currently used by Imenu.")
14386 (make-variable-buffer-local 'org-imenu-markers)
14388 (defun org-imenu-new-marker (&optional pos)
14389 "Return a new marker for use by Imenu, and remember the marker."
14390 (let ((m (make-marker)))
14391 (move-marker m (or pos (point)))
14392 (push m org-imenu-markers)
14395 (defun org-imenu-get-tree ()
14396 "Produce the index for Imenu."
14397 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
14398 (setq org-imenu-markers nil)
14399 (let* ((n org-imenu-depth)
14400 (re (concat "^" outline-regexp))
14401 (subs (make-vector (1+ n) nil))
14402 (last-level 0)
14403 m tree level head)
14404 (save-excursion
14405 (save-restriction
14406 (widen)
14407 (goto-char (point-max))
14408 (while (re-search-backward re nil t)
14409 (setq level (org-reduced-level (funcall outline-level)))
14410 (when (<= level n)
14411 (looking-at org-complex-heading-regexp)
14412 (setq head (org-link-display-format
14413 (org-match-string-no-properties 4))
14414 m (org-imenu-new-marker))
14415 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
14416 (if (>= level last-level)
14417 (push (cons head m) (aref subs level))
14418 (push (cons head (aref subs (1+ level))) (aref subs level))
14419 (loop for i from (1+ level) to n do (aset subs i nil)))
14420 (setq last-level level)))))
14421 (aref subs 1)))
14423 (eval-after-load "imenu"
14424 '(progn
14425 (add-hook 'imenu-after-jump-hook
14426 (lambda ()
14427 (if (eq major-mode 'org-mode)
14428 (org-show-context 'org-goto))))))
14430 (defun org-link-display-format (link)
14431 "Replace a link with either the description, or the link target
14432 if no description is present"
14433 (save-match-data
14434 (if (string-match org-bracket-link-analytic-regexp link)
14435 (replace-match (or (match-string 5 link)
14436 (concat (match-string 1 link)
14437 (match-string 3 link)))
14438 nil nil link)
14439 link)))
14441 ;; Speedbar support
14443 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
14444 "Overlay marking the agenda restriction line in speedbar.")
14445 (org-overlay-put org-speedbar-restriction-lock-overlay
14446 'face 'org-agenda-restriction-lock)
14447 (org-overlay-put org-speedbar-restriction-lock-overlay
14448 'help-echo "Agendas are currently limited to this item.")
14449 (org-detach-overlay org-speedbar-restriction-lock-overlay)
14451 (defun org-speedbar-set-agenda-restriction ()
14452 "Restrict future agenda commands to the location at point in speedbar.
14453 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
14454 (interactive)
14455 (require 'org-agenda)
14456 (let (p m tp np dir txt w)
14457 (cond
14458 ((setq p (text-property-any (point-at-bol) (point-at-eol)
14459 'org-imenu t))
14460 (setq m (get-text-property p 'org-imenu-marker))
14461 (save-excursion
14462 (save-restriction
14463 (set-buffer (marker-buffer m))
14464 (goto-char m)
14465 (org-agenda-set-restriction-lock 'subtree))))
14466 ((setq p (text-property-any (point-at-bol) (point-at-eol)
14467 'speedbar-function 'speedbar-find-file))
14468 (setq tp (previous-single-property-change
14469 (1+ p) 'speedbar-function)
14470 np (next-single-property-change
14471 tp 'speedbar-function)
14472 dir (speedbar-line-directory)
14473 txt (buffer-substring-no-properties (or tp (point-min))
14474 (or np (point-max))))
14475 (save-excursion
14476 (save-restriction
14477 (set-buffer (find-file-noselect
14478 (let ((default-directory dir))
14479 (expand-file-name txt))))
14480 (unless (org-mode-p)
14481 (error "Cannot restrict to non-Org-mode file"))
14482 (org-agenda-set-restriction-lock 'file))))
14483 (t (error "Don't know how to restrict Org-mode's agenda")))
14484 (org-move-overlay org-speedbar-restriction-lock-overlay
14485 (point-at-bol) (point-at-eol))
14486 (setq current-prefix-arg nil)
14487 (org-agenda-maybe-redo)))
14489 (eval-after-load "speedbar"
14490 '(progn
14491 (speedbar-add-supported-extension ".org")
14492 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
14493 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
14494 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
14495 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
14496 (add-hook 'speedbar-visiting-tag-hook
14497 (lambda () (org-show-context 'org-goto)))))
14500 ;;; Fixes and Hacks for problems with other packages
14502 ;; Make flyspell not check words in links, to not mess up our keymap
14503 (defun org-mode-flyspell-verify ()
14504 "Don't let flyspell put overlays at active buttons."
14505 (not (get-text-property (point) 'keymap)))
14507 ;; Make `bookmark-jump' show the jump location if it was hidden.
14508 (eval-after-load "bookmark"
14509 '(if (boundp 'bookmark-after-jump-hook)
14510 ;; We can use the hook
14511 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
14512 ;; Hook not available, use advice
14513 (defadvice bookmark-jump (after org-make-visible activate)
14514 "Make the position visible."
14515 (org-bookmark-jump-unhide))))
14517 ;; Make sure saveplace show the location if it was hidden
14518 (eval-after-load "saveplace"
14519 '(defadvice save-place-find-file-hook (after org-make-visible activate)
14520 "Make the position visible."
14521 (org-bookmark-jump-unhide)))
14523 (defun org-bookmark-jump-unhide ()
14524 "Unhide the current position, to show the bookmark location."
14525 (and (org-mode-p)
14526 (or (org-invisible-p)
14527 (save-excursion (goto-char (max (point-min) (1- (point))))
14528 (org-invisible-p)))
14529 (org-show-context 'bookmark-jump)))
14531 ;; Make session.el ignore our circular variable
14532 (eval-after-load "session"
14533 '(add-to-list 'session-globals-exclude 'org-mark-ring))
14535 ;;;; Experimental code
14537 (defun org-closed-in-range ()
14538 "Sparse tree of items closed in a certain time range.
14539 Still experimental, may disappear in the future."
14540 (interactive)
14541 ;; Get the time interval from the user.
14542 (let* ((time1 (time-to-seconds
14543 (org-read-date nil 'to-time nil "Starting date: ")))
14544 (time2 (time-to-seconds
14545 (org-read-date nil 'to-time nil "End date:")))
14546 ;; callback function
14547 (callback (lambda ()
14548 (let ((time
14549 (time-to-seconds
14550 (apply 'encode-time
14551 (org-parse-time-string
14552 (match-string 1))))))
14553 ;; check if time in interval
14554 (and (>= time time1) (<= time time2))))))
14555 ;; make tree, check each match with the callback
14556 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
14559 ;;;; Finish up
14561 (provide 'org)
14563 (run-hooks 'org-load-hook)
14565 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
14567 ;;; org.el ends here