Fix quoting bug TODO state change code.
[org-mode.git] / lisp / org.el
blob6a6f9f402acc242ed25acbe21a375e1cc2691da1
1 ;;; org.el --- Outline-based notes management and organizer
2 ;; Carstens outline-mode for keeping track of everything.
3 ;; Copyright (C) 2004, 2005, 2006, 2007, 2008 Free Software Foundation, Inc.
4 ;;
5 ;; Author: Carsten Dominik <carsten at orgmode dot org>
6 ;; Keywords: outlines, hypermedia, calendar, wp
7 ;; Homepage: http://orgmode.org
8 ;; Version: 6.10c
9 ;;
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
24 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
26 ;;; Commentary:
28 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
29 ;; project planning with a fast and effective plain-text system.
31 ;; Org-mode develops organizational tasks around NOTES files that contain
32 ;; information about projects as plain text. Org-mode is implemented on
33 ;; top of outline-mode, which makes it possible to keep the content of
34 ;; large files well structured. Visibility cycling and structure editing
35 ;; help to work with the tree. Tables are easily created with a built-in
36 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
37 ;; and scheduling. It dynamically compiles entries into an agenda that
38 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
39 ;; Plain text URL-like links connect to websites, emails, Usenet
40 ;; messages, BBDB entries, and any files related to the projects. For
41 ;; printing and sharing of notes, an Org-mode file can be exported as a
42 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
43 ;; iCalendar file. It can also serve as a publishing tool for a set of
44 ;; linked webpages.
46 ;; Installation and Activation
47 ;; ---------------------------
48 ;; See the corresponding sections in the manual at
50 ;; http://orgmode.org/org.html#Installation
52 ;; Documentation
53 ;; -------------
54 ;; The documentation of Org-mode can be found in the TeXInfo file. The
55 ;; distribution also contains a PDF version of it. At the homepage of
56 ;; Org-mode, you can read the same text online as HTML. There is also an
57 ;; excellent reference card made by Philip Rooke. This card can be found
58 ;; in the etc/ directory of Emacs 22.
60 ;; A list of recent changes can be found at
61 ;; http://orgmode.org/Changes.html
63 ;;; Code:
65 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
66 (defvar org-table-formula-constants-local nil
67 "Local version of `org-table-formula-constants'.")
68 (make-variable-buffer-local 'org-table-formula-constants-local)
70 ;;;; Require other packages
72 (eval-when-compile
73 (require 'cl)
74 (require 'gnus-sum)
75 (require 'calendar))
76 ;; For XEmacs, noutline is not yet provided by outline.el, so arrange for
77 ;; the file noutline.el being loaded.
78 (if (featurep 'xemacs) (condition-case nil (require 'noutline)))
79 ;; We require noutline, which might be provided in outline.el
80 (require 'outline) (require 'noutline)
81 ;; Other stuff we need.
82 (require 'time-date)
83 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
84 (require 'easymenu)
86 (require 'org-macs)
87 (require 'org-compat)
88 (require 'org-faces)
89 (require 'org-list)
91 ;;;; Customization variables
93 ;;; Version
95 (defconst org-version "6.10c"
96 "The version number of the file org.el.")
98 (defun org-version (&optional here)
99 "Show the org-mode version in the echo area.
100 With prefix arg HERE, insert it at point."
101 (interactive "P")
102 (let ((version (format "Org-mode version %s" org-version)))
103 (message version)
104 (if here
105 (insert version))))
107 ;;; Compatibility constants
109 ;;; The custom variables
111 (defgroup org nil
112 "Outline-based notes management and organizer."
113 :tag "Org"
114 :group 'outlines
115 :group 'hypermedia
116 :group 'calendar)
118 (defcustom org-load-hook nil
119 "Hook that is run after org.el has been loaded."
120 :group 'org
121 :type 'hook)
123 (defvar org-modules) ; defined below
124 (defvar org-modules-loaded nil
125 "Have the modules been loaded already?")
127 (defun org-load-modules-maybe (&optional force)
128 "Load all extensions listed in `org-default-extensions'."
129 (when (or force (not org-modules-loaded))
130 (mapc (lambda (ext)
131 (condition-case nil (require ext)
132 (error (message "Problems while trying to load feature `%s'" ext))))
133 org-modules)
134 (setq org-modules-loaded t)))
136 (defun org-set-modules (var value)
137 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
138 (set var value)
139 (when (featurep 'org)
140 (org-load-modules-maybe 'force)))
142 (when (org-bound-and-true-p org-modules)
143 (let ((a (member 'org-infojs org-modules)))
144 (and a (setcar a 'org-jsinfo))))
146 (defcustom org-modules '(org-bbdb org-bibtex org-gnus org-info org-jsinfo org-irc org-mew org-mhe org-rmail org-vm org-wl)
147 "Modules that should always be loaded together with org.el.
148 If a description starts with <C>, the file is not part of Emacs
149 and loading it will require that you have downloaded and properly installed
150 the org-mode distribution.
152 You can also use this system to load external packages (i.e. neither Org
153 core modules, not modules from the CONTRIB directory). Just add symbols
154 to the end of the list. If the package is called org-xyz.el, then you need
155 to add the symbol `xyz', and the package must have a call to
157 (provide 'org-xyz)"
158 :group 'org
159 :set 'org-set-modules
160 :type
161 '(set :greedy t
162 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
163 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
164 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
165 (const :tag " id: Global id's for identifying entries" org-id)
166 (const :tag " info: Links to Info nodes" org-info)
167 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
168 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
169 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
170 (const :tag " mew Links to Mew folders/messages" org-mew)
171 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
172 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
173 (const :tag " vm: Links to VM folders/messages" org-vm)
174 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
175 (const :tag " mouse: Additional mouse support" org-mouse)
177 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
178 (const :tag "C annotation-helper: Call Remeber directly from Browser" org-annotation-helper)
179 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
180 (const :tag "C depend: TODO dependencies for Org-mode" org-depend)
181 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
182 (const :tag "C eval: Include command output as text" org-eval)
183 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
184 (const :tag "C id: Global id's for identifying entries" org-id)
185 (const :tag "C interactive-query: Interactive modification of tags query" org-interactive-query)
186 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
187 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
188 (const :tag "C mtags: Support for muse-like tags" org-mtags)
189 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
190 (const :tag "C registry: A registry for Org links" org-registry)
191 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
192 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
193 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
194 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
195 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
198 (defgroup org-startup nil
199 "Options concerning startup of Org-mode."
200 :tag "Org Startup"
201 :group 'org)
203 (defcustom org-startup-folded t
204 "Non-nil means, entering Org-mode will switch to OVERVIEW.
205 This can also be configured on a per-file basis by adding one of
206 the following lines anywhere in the buffer:
208 #+STARTUP: fold
209 #+STARTUP: nofold
210 #+STARTUP: content"
211 :group 'org-startup
212 :type '(choice
213 (const :tag "nofold: show all" nil)
214 (const :tag "fold: overview" t)
215 (const :tag "content: all headlines" content)))
217 (defcustom org-startup-truncated t
218 "Non-nil means, entering Org-mode will set `truncate-lines'.
219 This is useful since some lines containing links can be very long and
220 uninteresting. Also tables look terrible when wrapped."
221 :group 'org-startup
222 :type 'boolean)
224 (defcustom org-startup-align-all-tables nil
225 "Non-nil means, align all tables when visiting a file.
226 This is useful when the column width in tables is forced with <N> cookies
227 in table fields. Such tables will look correct only after the first re-align.
228 This can also be configured on a per-file basis by adding one of
229 the following lines anywhere in the buffer:
230 #+STARTUP: align
231 #+STARTUP: noalign"
232 :group 'org-startup
233 :type 'boolean)
235 (defcustom org-insert-mode-line-in-empty-file nil
236 "Non-nil means insert the first line setting Org-mode in empty files.
237 When the function `org-mode' is called interactively in an empty file, this
238 normally means that the file name does not automatically trigger Org-mode.
239 To ensure that the file will always be in Org-mode in the future, a
240 line enforcing Org-mode will be inserted into the buffer, if this option
241 has been set."
242 :group 'org-startup
243 :type 'boolean)
245 (defcustom org-replace-disputed-keys nil
246 "Non-nil means use alternative key bindings for some keys.
247 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
248 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
249 If you want to use Org-mode together with one of these other modes,
250 or more generally if you would like to move some Org-mode commands to
251 other keys, set this variable and configure the keys with the variable
252 `org-disputed-keys'.
254 This option is only relevant at load-time of Org-mode, and must be set
255 *before* org.el is loaded. Changing it requires a restart of Emacs to
256 become effective."
257 :group 'org-startup
258 :type 'boolean)
260 (defcustom org-use-extra-keys nil
261 "Non-nil means use extra key sequence definitions for certain
262 commands. This happens automatically if you run XEmacs or if
263 window-system is nil. This variable lets you do the same
264 manually. You must set it before loading org.
266 Example: on Carbon Emacs 22 running graphically, with an external
267 keyboard on a Powerbook, the default way of setting M-left might
268 not work for either Alt or ESC. Setting this variable will make
269 it work for ESC."
270 :group 'org-startup
271 :type 'boolean)
273 (if (fboundp 'defvaralias)
274 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
276 (defcustom org-disputed-keys
277 '(([(shift up)] . [(meta p)])
278 ([(shift down)] . [(meta n)])
279 ([(shift left)] . [(meta -)])
280 ([(shift right)] . [(meta +)])
281 ([(control shift right)] . [(meta shift +)])
282 ([(control shift left)] . [(meta shift -)]))
283 "Keys for which Org-mode and other modes compete.
284 This is an alist, cars are the default keys, second element specifies
285 the alternative to use when `org-replace-disputed-keys' is t.
287 Keys can be specified in any syntax supported by `define-key'.
288 The value of this option takes effect only at Org-mode's startup,
289 therefore you'll have to restart Emacs to apply it after changing."
290 :group 'org-startup
291 :type 'alist)
293 (defun org-key (key)
294 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
295 Or return the original if not disputed."
296 (if org-replace-disputed-keys
297 (let* ((nkey (key-description key))
298 (x (org-find-if (lambda (x)
299 (equal (key-description (car x)) nkey))
300 org-disputed-keys)))
301 (if x (cdr x) key))
302 key))
304 (defun org-find-if (predicate seq)
305 (catch 'exit
306 (while seq
307 (if (funcall predicate (car seq))
308 (throw 'exit (car seq))
309 (pop seq)))))
311 (defun org-defkey (keymap key def)
312 "Define a key, possibly translated, as returned by `org-key'."
313 (define-key keymap (org-key key) def))
315 (defcustom org-ellipsis nil
316 "The ellipsis to use in the Org-mode outline.
317 When nil, just use the standard three dots. When a string, use that instead,
318 When a face, use the standart 3 dots, but with the specified face.
319 The change affects only Org-mode (which will then use its own display table).
320 Changing this requires executing `M-x org-mode' in a buffer to become
321 effective."
322 :group 'org-startup
323 :type '(choice (const :tag "Default" nil)
324 (face :tag "Face" :value org-warning)
325 (string :tag "String" :value "...#")))
327 (defvar org-display-table nil
328 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
330 (defgroup org-keywords nil
331 "Keywords in Org-mode."
332 :tag "Org Keywords"
333 :group 'org)
335 (defcustom org-deadline-string "DEADLINE:"
336 "String to mark deadline entries.
337 A deadline is this string, followed by a time stamp. Should be a word,
338 terminated by a colon. You can insert a schedule keyword and
339 a timestamp with \\[org-deadline].
340 Changes become only effective after restarting Emacs."
341 :group 'org-keywords
342 :type 'string)
344 (defcustom org-scheduled-string "SCHEDULED:"
345 "String to mark scheduled TODO entries.
346 A schedule is this string, followed by a time stamp. Should be a word,
347 terminated by a colon. You can insert a schedule keyword and
348 a timestamp with \\[org-schedule].
349 Changes become only effective after restarting Emacs."
350 :group 'org-keywords
351 :type 'string)
353 (defcustom org-closed-string "CLOSED:"
354 "String used as the prefix for timestamps logging closing a TODO entry."
355 :group 'org-keywords
356 :type 'string)
358 (defcustom org-clock-string "CLOCK:"
359 "String used as prefix for timestamps clocking work hours on an item."
360 :group 'org-keywords
361 :type 'string)
363 (defcustom org-comment-string "COMMENT"
364 "Entries starting with this keyword will never be exported.
365 An entry can be toggled between COMMENT and normal with
366 \\[org-toggle-comment].
367 Changes become only effective after restarting Emacs."
368 :group 'org-keywords
369 :type 'string)
371 (defcustom org-quote-string "QUOTE"
372 "Entries starting with this keyword will be exported in fixed-width font.
373 Quoting applies only to the text in the entry following the headline, and does
374 not extend beyond the next headline, even if that is lower level.
375 An entry can be toggled between QUOTE and normal with
376 \\[org-toggle-fixed-width-section]."
377 :group 'org-keywords
378 :type 'string)
380 (defconst org-repeat-re
381 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\([.+]?\\+[0-9]+[dwmy]\\)"
382 "Regular expression for specifying repeated events.
383 After a match, group 1 contains the repeat expression.")
385 (defgroup org-structure nil
386 "Options concerning the general structure of Org-mode files."
387 :tag "Org Structure"
388 :group 'org)
390 (defgroup org-reveal-location nil
391 "Options about how to make context of a location visible."
392 :tag "Org Reveal Location"
393 :group 'org-structure)
395 (defconst org-context-choice
396 '(choice
397 (const :tag "Always" t)
398 (const :tag "Never" nil)
399 (repeat :greedy t :tag "Individual contexts"
400 (cons
401 (choice :tag "Context"
402 (const agenda)
403 (const org-goto)
404 (const occur-tree)
405 (const tags-tree)
406 (const link-search)
407 (const mark-goto)
408 (const bookmark-jump)
409 (const isearch)
410 (const default))
411 (boolean))))
412 "Contexts for the reveal options.")
414 (defcustom org-show-hierarchy-above '((default . t))
415 "Non-nil means, show full hierarchy when revealing a location.
416 Org-mode often shows locations in an org-mode file which might have
417 been invisible before. When this is set, the hierarchy of headings
418 above the exposed location is shown.
419 Turning this off for example for sparse trees makes them very compact.
420 Instead of t, this can also be an alist specifying this option for different
421 contexts. Valid contexts are
422 agenda when exposing an entry from the agenda
423 org-goto when using the command `org-goto' on key C-c C-j
424 occur-tree when using the command `org-occur' on key C-c /
425 tags-tree when constructing a sparse tree based on tags matches
426 link-search when exposing search matches associated with a link
427 mark-goto when exposing the jump goal of a mark
428 bookmark-jump when exposing a bookmark location
429 isearch when exiting from an incremental search
430 default default for all contexts not set explicitly"
431 :group 'org-reveal-location
432 :type org-context-choice)
434 (defcustom org-show-following-heading '((default . nil))
435 "Non-nil means, show following heading when revealing a location.
436 Org-mode often shows locations in an org-mode file which might have
437 been invisible before. When this is set, the heading following the
438 match is shown.
439 Turning this off for example for sparse trees makes them very compact,
440 but makes it harder to edit the location of the match. In such a case,
441 use the command \\[org-reveal] to show more context.
442 Instead of t, this can also be an alist specifying this option for different
443 contexts. See `org-show-hierarchy-above' for valid contexts."
444 :group 'org-reveal-location
445 :type org-context-choice)
447 (defcustom org-show-siblings '((default . nil) (isearch t))
448 "Non-nil means, show all sibling heading when revealing a location.
449 Org-mode often shows locations in an org-mode file which might have
450 been invisible before. When this is set, the sibling of the current entry
451 heading are all made visible. If `org-show-hierarchy-above' is t,
452 the same happens on each level of the hierarchy above the current entry.
454 By default this is on for the isearch context, off for all other contexts.
455 Turning this off for example for sparse trees makes them very compact,
456 but makes it harder to edit the location of the match. In such a case,
457 use the command \\[org-reveal] to show more context.
458 Instead of t, this can also be an alist specifying this option for different
459 contexts. See `org-show-hierarchy-above' for valid contexts."
460 :group 'org-reveal-location
461 :type org-context-choice)
463 (defcustom org-show-entry-below '((default . nil))
464 "Non-nil means, show the entry below a headline when revealing a location.
465 Org-mode often shows locations in an org-mode file which might have
466 been invisible before. When this is set, the text below the headline that is
467 exposed is also shown.
469 By default this is off for all contexts.
470 Instead of t, this can also be an alist specifying this option for different
471 contexts. See `org-show-hierarchy-above' for valid contexts."
472 :group 'org-reveal-location
473 :type org-context-choice)
475 (defcustom org-indirect-buffer-display 'other-window
476 "How should indirect tree buffers be displayed?
477 This applies to indirect buffers created with the commands
478 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
479 Valid values are:
480 current-window Display in the current window
481 other-window Just display in another window.
482 dedicated-frame Create one new frame, and re-use it each time.
483 new-frame Make a new frame each time. Note that in this case
484 previously-made indirect buffers are kept, and you need to
485 kill these buffers yourself."
486 :group 'org-structure
487 :group 'org-agenda-windows
488 :type '(choice
489 (const :tag "In current window" current-window)
490 (const :tag "In current frame, other window" other-window)
491 (const :tag "Each time a new frame" new-frame)
492 (const :tag "One dedicated frame" dedicated-frame)))
494 (defgroup org-cycle nil
495 "Options concerning visibility cycling in Org-mode."
496 :tag "Org Cycle"
497 :group 'org-structure)
499 (defcustom org-drawers '("PROPERTIES" "CLOCK")
500 "Names of drawers. Drawers are not opened by cycling on the headline above.
501 Drawers only open with a TAB on the drawer line itself. A drawer looks like
502 this:
503 :DRAWERNAME:
504 .....
505 :END:
506 The drawer \"PROPERTIES\" is special for capturing properties through
507 the property API.
509 Drawers can be defined on the per-file basis with a line like:
511 #+DRAWERS: HIDDEN STATE PROPERTIES"
512 :group 'org-structure
513 :type '(repeat (string :tag "Drawer Name")))
515 (defcustom org-cycle-global-at-bob nil
516 "Cycle globally if cursor is at beginning of buffer and not at a headline.
517 This makes it possible to do global cycling without having to use S-TAB or
518 C-u TAB. For this special case to work, the first line of the buffer
519 must not be a headline - it may be empty ot some other text. When used in
520 this way, `org-cycle-hook' is disables temporarily, to make sure the
521 cursor stays at the beginning of the buffer.
522 When this option is nil, don't do anything special at the beginning
523 of the buffer."
524 :group 'org-cycle
525 :type 'boolean)
527 (defcustom org-cycle-emulate-tab t
528 "Where should `org-cycle' emulate TAB.
529 nil Never
530 white Only in completely white lines
531 whitestart Only at the beginning of lines, before the first non-white char
532 t Everywhere except in headlines
533 exc-hl-bol Everywhere except at the start of a headline
534 If TAB is used in a place where it does not emulate TAB, the current subtree
535 visibility is cycled."
536 :group 'org-cycle
537 :type '(choice (const :tag "Never" nil)
538 (const :tag "Only in completely white lines" white)
539 (const :tag "Before first char in a line" whitestart)
540 (const :tag "Everywhere except in headlines" t)
541 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
544 (defcustom org-cycle-separator-lines 2
545 "Number of empty lines needed to keep an empty line between collapsed trees.
546 If you leave an empty line between the end of a subtree and the following
547 headline, this empty line is hidden when the subtree is folded.
548 Org-mode will leave (exactly) one empty line visible if the number of
549 empty lines is equal or larger to the number given in this variable.
550 So the default 2 means, at least 2 empty lines after the end of a subtree
551 are needed to produce free space between a collapsed subtree and the
552 following headline.
554 Special case: when 0, never leave empty lines in collapsed view."
555 :group 'org-cycle
556 :type 'integer)
557 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
559 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
560 org-cycle-hide-drawers
561 org-cycle-show-empty-lines
562 org-optimize-window-after-visibility-change)
563 "Hook that is run after `org-cycle' has changed the buffer visibility.
564 The function(s) in this hook must accept a single argument which indicates
565 the new state that was set by the most recent `org-cycle' command. The
566 argument is a symbol. After a global state change, it can have the values
567 `overview', `content', or `all'. After a local state change, it can have
568 the values `folded', `children', or `subtree'."
569 :group 'org-cycle
570 :type 'hook)
572 (defgroup org-edit-structure nil
573 "Options concerning structure editing in Org-mode."
574 :tag "Org Edit Structure"
575 :group 'org-structure)
577 (defcustom org-odd-levels-only nil
578 "Non-nil means, skip even levels and only use odd levels for the outline.
579 This has the effect that two stars are being added/taken away in
580 promotion/demotion commands. It also influences how levels are
581 handled by the exporters.
582 Changing it requires restart of `font-lock-mode' to become effective
583 for fontification also in regions already fontified.
584 You may also set this on a per-file basis by adding one of the following
585 lines to the buffer:
587 #+STARTUP: odd
588 #+STARTUP: oddeven"
589 :group 'org-edit-structure
590 :group 'org-font-lock
591 :type 'boolean)
593 (defcustom org-adapt-indentation t
594 "Non-nil means, adapt indentation when promoting and demoting.
595 When this is set and the *entire* text in an entry is indented, the
596 indentation is increased by one space in a demotion command, and
597 decreased by one in a promotion command. If any line in the entry
598 body starts at column 0, indentation is not changed at all."
599 :group 'org-edit-structure
600 :type 'boolean)
602 (defcustom org-special-ctrl-a/e nil
603 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
604 When t, `C-a' will bring back the cursor to the beginning of the
605 headline text, i.e. after the stars and after a possible TODO keyword.
606 In an item, this will be the position after the bullet.
607 When the cursor is already at that position, another `C-a' will bring
608 it to the beginning of the line.
609 `C-e' will jump to the end of the headline, ignoring the presence of tags
610 in the headline. A second `C-e' will then jump to the true end of the
611 line, after any tags.
612 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
613 and only a directly following, identical keypress will bring the cursor
614 to the special positions."
615 :group 'org-edit-structure
616 :type '(choice
617 (const :tag "off" nil)
618 (const :tag "after bullet first" t)
619 (const :tag "border first" reversed)))
621 (if (fboundp 'defvaralias)
622 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
624 (defcustom org-special-ctrl-k nil
625 "Non-nil means `C-k' will behave specially in headlines.
626 When nil, `C-k' will call the default `kill-line' command.
627 When t, the following will happen while the cursor is in the headline:
629 - When the cursor is at the beginning of a headline, kill the entire
630 line and possible the folded subtree below the line.
631 - When in the middle of the headline text, kill the headline up to the tags.
632 - When after the headline text, kill the tags."
633 :group 'org-edit-structure
634 :type 'boolean)
636 (defcustom org-yank-folded-subtrees t
637 "Non-nil means, when yanking subtrees, fold them.
638 If the kill is a single subtree, or a sequence of subtrees, i.e. if
639 it starts with a heading and all other headings in it are either children
640 or siblings, then fold all the subtrees."
641 :group 'org-edit-structure
642 :type 'boolean)
644 (defcustom org-yank-adjusted-subtrees t
645 "Non-nil means, when yanking subtrees, adjust the level.
646 With this setting, `org-paste-subtree' is used to insert the subtree, see
647 this function for details."
648 :group 'org-edit-structure
649 :type 'boolean)
651 (defcustom org-M-RET-may-split-line '((default . t))
652 "Non-nil means, M-RET will split the line at the cursor position.
653 When nil, it will go to the end of the line before making a
654 new line.
655 You may also set this option in a different way for different
656 contexts. Valid contexts are:
658 headline when creating a new headline
659 item when creating a new item
660 table in a table field
661 default the value to be used for all contexts not explicitly
662 customized"
663 :group 'org-structure
664 :group 'org-table
665 :type '(choice
666 (const :tag "Always" t)
667 (const :tag "Never" nil)
668 (repeat :greedy t :tag "Individual contexts"
669 (cons
670 (choice :tag "Context"
671 (const headline)
672 (const item)
673 (const table)
674 (const default))
675 (boolean)))))
678 (defcustom org-insert-heading-respect-content nil
679 "Non-nil means, insert new headings after the current subtree.
680 When nil, the new heading is created directly after the current line.
681 The commands \\[org-insert-heading-respect-content] and
682 \\[org-insert-todo-heading-respect-content] turn this variable on
683 for the duration of the command."
684 :group 'org-structure
685 :type 'boolean)
687 (defcustom org-blank-before-new-entry '((heading . nil)
688 (plain-list-item . nil))
689 "Should `org-insert-heading' leave a blank line before new heading/item?
690 The value is an alist, with `heading' and `plain-list-item' as car,
691 and a boolean flag as cdr."
692 :group 'org-edit-structure
693 :type '(list
694 (cons (const heading) (boolean))
695 (cons (const plain-list-item) (boolean))))
697 (defcustom org-insert-heading-hook nil
698 "Hook being run after inserting a new heading."
699 :group 'org-edit-structure
700 :type 'hook)
702 (defcustom org-enable-fixed-width-editor t
703 "Non-nil means, lines starting with \":\" are treated as fixed-width.
704 This currently only means, they are never auto-wrapped.
705 When nil, such lines will be treated like ordinary lines.
706 See also the QUOTE keyword."
707 :group 'org-edit-structure
708 :type 'boolean)
710 (defcustom org-edit-src-region-extra nil
711 "Additional regexps to identify regions for editing with `org-edit-src-code'.
712 For examples see the function `org-edit-src-find-region-and-lang'.
713 The regular expression identifying the begin marker should end with a newline,
714 and the regexp marking the end line should start with a newline, to make sure
715 there are kept outside the narrowed region."
716 :group 'org-edit-structure
717 :type '(repeat
718 (list
719 (regexp :tag "begin regexp")
720 (regexp :tag "end regexp")
721 (choice :tag "language"
722 (string :tag "specify")
723 (integer :tag "from match group")
724 (const :tag "from `lang' element")
725 (const :tag "from `style' element")))))
727 (defcustom org-edit-fixed-width-region-mode 'artist-mode
728 "The mode that should be used to edit fixed-width regions.
729 These are the regions where each line starts with a colon."
730 :group 'org-edit-structure
731 :type '(choice
732 (const artist-mode)
733 (const picture-mode)
734 (const fundamental-mode)
735 (function :tag "Other (specify)")))
737 (defcustom org-goto-auto-isearch t
738 "Non-nil means, typing characters in org-goto starts incremental search."
739 :group 'org-edit-structure
740 :type 'boolean)
742 (defgroup org-sparse-trees nil
743 "Options concerning sparse trees in Org-mode."
744 :tag "Org Sparse Trees"
745 :group 'org-structure)
747 (defcustom org-highlight-sparse-tree-matches t
748 "Non-nil means, highlight all matches that define a sparse tree.
749 The highlights will automatically disappear the next time the buffer is
750 changed by an edit command."
751 :group 'org-sparse-trees
752 :type 'boolean)
754 (defcustom org-remove-highlights-with-change t
755 "Non-nil means, any change to the buffer will remove temporary highlights.
756 Such highlights are created by `org-occur' and `org-clock-display'.
757 When nil, `C-c C-c needs to be used to get rid of the highlights.
758 The highlights created by `org-preview-latex-fragment' always need
759 `C-c C-c' to be removed."
760 :group 'org-sparse-trees
761 :group 'org-time
762 :type 'boolean)
765 (defcustom org-occur-hook '(org-first-headline-recenter)
766 "Hook that is run after `org-occur' has constructed a sparse tree.
767 This can be used to recenter the window to show as much of the structure
768 as possible."
769 :group 'org-sparse-trees
770 :type 'hook)
772 (defgroup org-imenu-and-speedbar nil
773 "Options concerning imenu and speedbar in Org-mode."
774 :tag "Org Imenu and Speedbar"
775 :group 'org-structure)
777 (defcustom org-imenu-depth 2
778 "The maximum level for Imenu access to Org-mode headlines.
779 This also applied for speedbar access."
780 :group 'org-imenu-and-speedbar
781 :type 'number)
783 (defgroup org-table nil
784 "Options concerning tables in Org-mode."
785 :tag "Org Table"
786 :group 'org)
788 (defcustom org-enable-table-editor 'optimized
789 "Non-nil means, lines starting with \"|\" are handled by the table editor.
790 When nil, such lines will be treated like ordinary lines.
792 When equal to the symbol `optimized', the table editor will be optimized to
793 do the following:
794 - Automatic overwrite mode in front of whitespace in table fields.
795 This makes the structure of the table stay in tact as long as the edited
796 field does not exceed the column width.
797 - Minimize the number of realigns. Normally, the table is aligned each time
798 TAB or RET are pressed to move to another field. With optimization this
799 happens only if changes to a field might have changed the column width.
800 Optimization requires replacing the functions `self-insert-command',
801 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
802 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
803 very good at guessing when a re-align will be necessary, but you can always
804 force one with \\[org-ctrl-c-ctrl-c].
806 If you would like to use the optimized version in Org-mode, but the
807 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
809 This variable can be used to turn on and off the table editor during a session,
810 but in order to toggle optimization, a restart is required.
812 See also the variable `org-table-auto-blank-field'."
813 :group 'org-table
814 :type '(choice
815 (const :tag "off" nil)
816 (const :tag "on" t)
817 (const :tag "on, optimized" optimized)))
819 (defcustom org-table-tab-recognizes-table.el t
820 "Non-nil means, TAB will automatically notice a table.el table.
821 When it sees such a table, it moves point into it and - if necessary -
822 calls `table-recognize-table'."
823 :group 'org-table-editing
824 :type 'boolean)
826 (defgroup org-link nil
827 "Options concerning links in Org-mode."
828 :tag "Org Link"
829 :group 'org)
831 (defvar org-link-abbrev-alist-local nil
832 "Buffer-local version of `org-link-abbrev-alist', which see.
833 The value of this is taken from the #+LINK lines.")
834 (make-variable-buffer-local 'org-link-abbrev-alist-local)
836 (defcustom org-link-abbrev-alist nil
837 "Alist of link abbreviations.
838 The car of each element is a string, to be replaced at the start of a link.
839 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
840 links in Org-mode buffers can have an optional tag after a double colon, e.g.
842 [[linkkey:tag][description]]
844 If REPLACE is a string, the tag will simply be appended to create the link.
845 If the string contains \"%s\", the tag will be inserted there.
847 REPLACE may also be a function that will be called with the tag as the
848 only argument to create the link, which should be returned as a string.
850 See the manual for examples."
851 :group 'org-link
852 :type 'alist)
854 (defcustom org-descriptive-links t
855 "Non-nil means, hide link part and only show description of bracket links.
856 Bracket links are like [[link][descritpion]]. This variable sets the initial
857 state in new org-mode buffers. The setting can then be toggled on a
858 per-buffer basis from the Org->Hyperlinks menu."
859 :group 'org-link
860 :type 'boolean)
862 (defcustom org-link-file-path-type 'adaptive
863 "How the path name in file links should be stored.
864 Valid values are:
866 relative Relative to the current directory, i.e. the directory of the file
867 into which the link is being inserted.
868 absolute Absolute path, if possible with ~ for home directory.
869 noabbrev Absolute path, no abbreviation of home directory.
870 adaptive Use relative path for files in the current directory and sub-
871 directories of it. For other files, use an absolute path."
872 :group 'org-link
873 :type '(choice
874 (const relative)
875 (const absolute)
876 (const noabbrev)
877 (const adaptive)))
879 (defcustom org-activate-links '(bracket angle plain radio tag date)
880 "Types of links that should be activated in Org-mode files.
881 This is a list of symbols, each leading to the activation of a certain link
882 type. In principle, it does not hurt to turn on most link types - there may
883 be a small gain when turning off unused link types. The types are:
885 bracket The recommended [[link][description]] or [[link]] links with hiding.
886 angular Links in angular brackes that may contain whitespace like
887 <bbdb:Carsten Dominik>.
888 plain Plain links in normal text, no whitespace, like http://google.com.
889 radio Text that is matched by a radio target, see manual for details.
890 tag Tag settings in a headline (link to tag search).
891 date Time stamps (link to calendar).
893 Changing this variable requires a restart of Emacs to become effective."
894 :group 'org-link
895 :type '(set (const :tag "Double bracket links (new style)" bracket)
896 (const :tag "Angular bracket links (old style)" angular)
897 (const :tag "Plain text links" plain)
898 (const :tag "Radio target matches" radio)
899 (const :tag "Tags" tag)
900 (const :tag "Timestamps" date)))
902 (defcustom org-make-link-description-function nil
903 "Function to use to generate link descriptions from links. If
904 nil the link location will be used. This function must take two
905 parameters; the first is the link and the second the description
906 org-insert-link has generated, and should return the description
907 to use."
908 :group 'org-link
909 :type 'function)
911 (defgroup org-link-store nil
912 "Options concerning storing links in Org-mode."
913 :tag "Org Store Link"
914 :group 'org-link)
916 (defcustom org-email-link-description-format "Email %c: %.30s"
917 "Format of the description part of a link to an email or usenet message.
918 The following %-excapes will be replaced by corresponding information:
920 %F full \"From\" field
921 %f name, taken from \"From\" field, address if no name
922 %T full \"To\" field
923 %t first name in \"To\" field, address if no name
924 %c correspondent. Unually \"from NAME\", but if you sent it yourself, it
925 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
926 %s subject
927 %m message-id.
929 You may use normal field width specification between the % and the letter.
930 This is for example useful to limit the length of the subject.
932 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
933 :group 'org-link-store
934 :type 'string)
936 (defcustom org-from-is-user-regexp
937 (let (r1 r2)
938 (when (and user-mail-address (not (string= user-mail-address "")))
939 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
940 (when (and user-full-name (not (string= user-full-name "")))
941 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
942 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
943 "Regexp mached against the \"From:\" header of an email or usenet message.
944 It should match if the message is from the user him/herself."
945 :group 'org-link-store
946 :type 'regexp)
948 (defcustom org-context-in-file-links t
949 "Non-nil means, file links from `org-store-link' contain context.
950 A search string will be added to the file name with :: as separator and
951 used to find the context when the link is activated by the command
952 `org-open-at-point'.
953 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
954 negates this setting for the duration of the command."
955 :group 'org-link-store
956 :type 'boolean)
958 (defcustom org-keep-stored-link-after-insertion nil
959 "Non-nil means, keep link in list for entire session.
961 The command `org-store-link' adds a link pointing to the current
962 location to an internal list. These links accumulate during a session.
963 The command `org-insert-link' can be used to insert links into any
964 Org-mode file (offering completion for all stored links). When this
965 option is nil, every link which has been inserted once using \\[org-insert-link]
966 will be removed from the list, to make completing the unused links
967 more efficient."
968 :group 'org-link-store
969 :type 'boolean)
971 (defgroup org-link-follow nil
972 "Options concerning following links in Org-mode."
973 :tag "Org Follow Link"
974 :group 'org-link)
976 (defcustom org-follow-link-hook nil
977 "Hook that is run after a link has been followed."
978 :group 'org-link-follow
979 :type 'hook)
981 (defcustom org-tab-follows-link nil
982 "Non-nil means, on links TAB will follow the link.
983 Needs to be set before org.el is loaded."
984 :group 'org-link-follow
985 :type 'boolean)
987 (defcustom org-return-follows-link nil
988 "Non-nil means, on links RET will follow the link.
989 Needs to be set before org.el is loaded."
990 :group 'org-link-follow
991 :type 'boolean)
993 (defcustom org-mouse-1-follows-link
994 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
995 "Non-nil means, mouse-1 on a link will follow the link.
996 A longer mouse click will still set point. Does not work on XEmacs.
997 Needs to be set before org.el is loaded."
998 :group 'org-link-follow
999 :type 'boolean)
1001 (defcustom org-mark-ring-length 4
1002 "Number of different positions to be recorded in the ring
1003 Changing this requires a restart of Emacs to work correctly."
1004 :group 'org-link-follow
1005 :type 'interger)
1007 (defcustom org-link-frame-setup
1008 '((vm . vm-visit-folder-other-frame)
1009 (gnus . gnus-other-frame)
1010 (file . find-file-other-window))
1011 "Setup the frame configuration for following links.
1012 When following a link with Emacs, it may often be useful to display
1013 this link in another window or frame. This variable can be used to
1014 set this up for the different types of links.
1015 For VM, use any of
1016 `vm-visit-folder'
1017 `vm-visit-folder-other-frame'
1018 For Gnus, use any of
1019 `gnus'
1020 `gnus-other-frame'
1021 `org-gnus-no-new-news'
1022 For FILE, use any of
1023 `find-file'
1024 `find-file-other-window'
1025 `find-file-other-frame'
1026 For the calendar, use the variable `calendar-setup'.
1027 For BBDB, it is currently only possible to display the matches in
1028 another window."
1029 :group 'org-link-follow
1030 :type '(list
1031 (cons (const vm)
1032 (choice
1033 (const vm-visit-folder)
1034 (const vm-visit-folder-other-window)
1035 (const vm-visit-folder-other-frame)))
1036 (cons (const gnus)
1037 (choice
1038 (const gnus)
1039 (const gnus-other-frame)
1040 (const org-gnus-no-new-news)))
1041 (cons (const file)
1042 (choice
1043 (const find-file)
1044 (const find-file-other-window)
1045 (const find-file-other-frame)))))
1047 (defcustom org-display-internal-link-with-indirect-buffer nil
1048 "Non-nil means, use indirect buffer to display infile links.
1049 Activating internal links (from one location in a file to another location
1050 in the same file) normally just jumps to the location. When the link is
1051 activated with a C-u prefix (or with mouse-3), the link is displayed in
1052 another window. When this option is set, the other window actually displays
1053 an indirect buffer clone of the current buffer, to avoid any visibility
1054 changes to the current buffer."
1055 :group 'org-link-follow
1056 :type 'boolean)
1058 (defcustom org-open-non-existing-files nil
1059 "Non-nil means, `org-open-file' will open non-existing files.
1060 When nil, an error will be generated."
1061 :group 'org-link-follow
1062 :type 'boolean)
1064 (defcustom org-open-directory-means-index-dot-org nil
1065 "Non-nil means, a link to a directory really means to index.org.
1066 When nil, following a directory link will run dired or open a finder/explorer
1067 window on that directory."
1068 :group 'org-link-follow
1069 :type 'boolean)
1071 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1072 "Function and arguments to call for following mailto links.
1073 This is a list with the first element being a lisp function, and the
1074 remaining elements being arguments to the function. In string arguments,
1075 %a will be replaced by the address, and %s will be replaced by the subject
1076 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1077 :group 'org-link-follow
1078 :type '(choice
1079 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1080 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1081 (const :tag "message-mail" (message-mail "%a" "%s"))
1082 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1084 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1085 "Non-nil means, ask for confirmation before executing shell links.
1086 Shell links can be dangerous: just think about a link
1088 [[shell:rm -rf ~/*][Google Search]]
1090 This link would show up in your Org-mode document as \"Google Search\",
1091 but really it would remove your entire home directory.
1092 Therefore we advise against setting this variable to nil.
1093 Just change it to `y-or-n-p' of you want to confirm with a
1094 single keystroke rather than having to type \"yes\"."
1095 :group 'org-link-follow
1096 :type '(choice
1097 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1098 (const :tag "with y-or-n (faster)" y-or-n-p)
1099 (const :tag "no confirmation (dangerous)" nil)))
1101 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1102 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1103 Elisp links can be dangerous: just think about a link
1105 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1107 This link would show up in your Org-mode document as \"Google Search\",
1108 but really it would remove your entire home directory.
1109 Therefore we advise against setting this variable to nil.
1110 Just change it to `y-or-n-p' of you want to confirm with a
1111 single keystroke rather than having to type \"yes\"."
1112 :group 'org-link-follow
1113 :type '(choice
1114 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1115 (const :tag "with y-or-n (faster)" y-or-n-p)
1116 (const :tag "no confirmation (dangerous)" nil)))
1118 (defconst org-file-apps-defaults-gnu
1119 '((remote . emacs)
1120 (t . mailcap))
1121 "Default file applications on a UNIX or GNU/Linux system.
1122 See `org-file-apps'.")
1124 (defconst org-file-apps-defaults-macosx
1125 '((remote . emacs)
1126 (t . "open %s")
1127 ("ps.gz" . "gv %s")
1128 ("eps.gz" . "gv %s")
1129 ("dvi" . "xdvi %s")
1130 ("fig" . "xfig %s"))
1131 "Default file applications on a MacOS X system.
1132 The system \"open\" is known as a default, but we use X11 applications
1133 for some files for which the OS does not have a good default.
1134 See `org-file-apps'.")
1136 (defconst org-file-apps-defaults-windowsnt
1137 (list
1138 '(remote . emacs)
1139 (cons t
1140 (list (if (featurep 'xemacs)
1141 'mswindows-shell-execute
1142 'w32-shell-execute)
1143 "open" 'file)))
1144 "Default file applications on a Windows NT system.
1145 The system \"open\" is used for most files.
1146 See `org-file-apps'.")
1148 (defcustom org-file-apps
1150 (auto-mode . emacs)
1151 ("\\.x?html?\\'" . default)
1152 ("\\.pdf\\'" . default)
1154 "External applications for opening `file:path' items in a document.
1155 Org-mode uses system defaults for different file types, but
1156 you can use this variable to set the application for a given file
1157 extension. The entries in this list are cons cells where the car identifies
1158 files and the cdr the corresponding command. Possible values for the
1159 file identifier are
1160 \"regex\" Regular expression matched against the file name. For backward
1161 compatibility, this can also be a string with only alphanumeric
1162 characters, which is then interpreted as an extension.
1163 `directory' Matches a directory
1164 `remote' Matches a remote file, accessible through tramp or efs.
1165 Remote files most likely should be visited through Emacs
1166 because external applications cannot handle such paths.
1167 `auto-mode' Matches files that are mached by any entry in `auto-mode-alist',
1168 so all files Emacs knows how to handle. Useing this with
1169 command `emacs' will open most files in Emacs. Beware that this
1170 will also open html files insite Emacs, unless you add
1171 (\"html\" . default) to the list as well.
1172 t Default for files not matched by any of the other options.
1174 Possible values for the command are:
1175 `emacs' The file will be visited by the current Emacs process.
1176 `default' Use the default application for this file type, which is the
1177 association for t in the list, most likely in the system-specific
1178 part.
1179 This can be used to overrule an unwanted seting in the
1180 system-specific variable.
1181 string A command to be executed by a shell; %s will be replaced
1182 by the path to the file.
1183 sexp A Lisp form which will be evaluated. The file path will
1184 be available in the Lisp variable `file'.
1185 For more examples, see the system specific constants
1186 `org-file-apps-defaults-macosx'
1187 `org-file-apps-defaults-windowsnt'
1188 `org-file-apps-defaults-gnu'."
1189 :group 'org-link-follow
1190 :type '(repeat
1191 (cons (choice :value ""
1192 (string :tag "Extension")
1193 (const :tag "Default for unrecognized files" t)
1194 (const :tag "Remote file" remote)
1195 (const :tag "Links to a directory" directory)
1196 (const :tag "Any files that have Emacs modes"
1197 auto-mode))
1198 (choice :value ""
1199 (const :tag "Visit with Emacs" emacs)
1200 (const :tag "Use system default" default)
1201 (string :tag "Command")
1202 (sexp :tag "Lisp form")))))
1204 (defgroup org-refile nil
1205 "Options concerning refiling entries in Org-mode."
1206 :tag "Org Remember"
1207 :group 'org)
1209 (defcustom org-directory "~/org"
1210 "Directory with org files.
1211 This directory will be used as default to prompt for org files.
1212 Used by the hooks for remember.el."
1213 :group 'org-refile
1214 :group 'org-remember
1215 :type 'directory)
1217 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1218 "Default target for storing notes.
1219 Used by the hooks for remember.el. This can be a string, or nil to mean
1220 the value of `remember-data-file'.
1221 You can set this on a per-template basis with the variable
1222 `org-remember-templates'."
1223 :group 'org-refile
1224 :group 'org-remember
1225 :type '(choice
1226 (const :tag "Default from remember-data-file" nil)
1227 file))
1229 (defcustom org-goto-interface 'outline
1230 "The default interface to be used for `org-goto'.
1231 Allowed vaues are:
1232 outline The interface shows an outline of the relevant file
1233 and the correct heading is found by moving through
1234 the outline or by searching with incremental search.
1235 outline-path-completion Headlines in the current buffer are offered via
1236 completion."
1237 :group 'org-refile
1238 :type '(choice
1239 (const :tag "Outline" outline)
1240 (const :tag "Outline-path-completion" outline-path-completion)))
1242 (defcustom org-reverse-note-order nil
1243 "Non-nil means, store new notes at the beginning of a file or entry.
1244 When nil, new notes will be filed to the end of a file or entry.
1245 This can also be a list with cons cells of regular expressions that
1246 are matched against file names, and values."
1247 :group 'org-remember
1248 :type '(choice
1249 (const :tag "Reverse always" t)
1250 (const :tag "Reverse never" nil)
1251 (repeat :tag "By file name regexp"
1252 (cons regexp boolean))))
1254 (defcustom org-refile-targets nil
1255 "Targets for refiling entries with \\[org-refile].
1256 This is list of cons cells. Each cell contains:
1257 - a specification of the files to be considered, either a list of files,
1258 or a symbol whose function or variable value will be used to retrieve
1259 a file name or a list of file names. Nil means, refile to a different
1260 heading in the current buffer.
1261 - A specification of how to find candidate refile targets. This may be
1262 any of
1263 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1264 This tag has to be present in all target headlines, inheritance will
1265 not be considered.
1266 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1267 todo keyword.
1268 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1269 headlines that are refiling targets.
1270 - a cons cell (:level . N). Any headline of level N is considered a target.
1271 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1273 When this variable is nil, all top-level headlines in the current buffer
1274 are used, equivalent to the vlaue `((nil . (:level . 1))'."
1275 :group 'org-remember
1276 :type '(repeat
1277 (cons
1278 (choice :value org-agenda-files
1279 (const :tag "All agenda files" org-agenda-files)
1280 (const :tag "Current buffer" nil)
1281 (function) (variable) (file))
1282 (choice :tag "Identify target headline by"
1283 (cons :tag "Specific tag" (const :tag) (string))
1284 (cons :tag "TODO keyword" (const :todo) (string))
1285 (cons :tag "Regular expression" (const :regexp) (regexp))
1286 (cons :tag "Level number" (const :level) (integer))
1287 (cons :tag "Max Level number" (const :maxlevel) (integer))))))
1289 (defcustom org-refile-use-outline-path nil
1290 "Non-nil means, provide refile targets as paths.
1291 So a level 3 headline will be available as level1/level2/level3.
1292 When the value is `file', also include the file name (without directory)
1293 into the path. When `full-file-path', include the full file path."
1294 :group 'org-remember
1295 :type '(choice
1296 (const :tag "Not" nil)
1297 (const :tag "Yes" t)
1298 (const :tag "Start with file name" file)
1299 (const :tag "Start with full file path" full-file-path)))
1301 (defgroup org-todo nil
1302 "Options concerning TODO items in Org-mode."
1303 :tag "Org TODO"
1304 :group 'org)
1306 (defgroup org-progress nil
1307 "Options concerning Progress logging in Org-mode."
1308 :tag "Org Progress"
1309 :group 'org-time)
1311 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1312 "List of TODO entry keyword sequences and their interpretation.
1313 \\<org-mode-map>This is a list of sequences.
1315 Each sequence starts with a symbol, either `sequence' or `type',
1316 indicating if the keywords should be interpreted as a sequence of
1317 action steps, or as different types of TODO items. The first
1318 keywords are states requiring action - these states will select a headline
1319 for inclusion into the global TODO list Org-mode produces. If one of
1320 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1321 signify that no further action is necessary. If \"|\" is not found,
1322 the last keyword is treated as the only DONE state of the sequence.
1324 The command \\[org-todo] cycles an entry through these states, and one
1325 additional state where no keyword is present. For details about this
1326 cycling, see the manual.
1328 TODO keywords and interpretation can also be set on a per-file basis with
1329 the special #+SEQ_TODO and #+TYP_TODO lines.
1331 Each keyword can optionally specify a character for fast state selection
1332 \(in combination with the variable `org-use-fast-todo-selection')
1333 and specifiers for state change logging, using the same syntax
1334 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1335 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1336 indicates to record a time stamp each time this state is selected.
1338 Each keyword may also specify if a timestamp or a note should be
1339 recorded when entering or leaving the state, by adding additional
1340 characters in the parenthesis after the keyword. This looks like this:
1341 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1342 record only the time of the state change. With X and Y being either
1343 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1344 Y when leaving the state if and only if the *target* state does not
1345 define X. You may omit any of the fast-selection key or X or /Y,
1346 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1348 For backward compatibility, this variable may also be just a list
1349 of keywords - in this case the interptetation (sequence or type) will be
1350 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1351 :group 'org-todo
1352 :group 'org-keywords
1353 :type '(choice
1354 (repeat :tag "Old syntax, just keywords"
1355 (string :tag "Keyword"))
1356 (repeat :tag "New syntax"
1357 (cons
1358 (choice
1359 :tag "Interpretation"
1360 (const :tag "Sequence (cycling hits every state)" sequence)
1361 (const :tag "Type (cycling directly to DONE)" type))
1362 (repeat
1363 (string :tag "Keyword"))))))
1365 (defvar org-todo-keywords-1 nil
1366 "All TODO and DONE keywords active in a buffer.")
1367 (make-variable-buffer-local 'org-todo-keywords-1)
1368 (defvar org-todo-keywords-for-agenda nil)
1369 (defvar org-done-keywords-for-agenda nil)
1370 (defvar org-todo-keyword-alist-for-agenda nil)
1371 (defvar org-tag-alist-for-agenda nil)
1372 (defvar org-agenda-contributing-files nil)
1373 (defvar org-not-done-keywords nil)
1374 (make-variable-buffer-local 'org-not-done-keywords)
1375 (defvar org-done-keywords nil)
1376 (make-variable-buffer-local 'org-done-keywords)
1377 (defvar org-todo-heads nil)
1378 (make-variable-buffer-local 'org-todo-heads)
1379 (defvar org-todo-sets nil)
1380 (make-variable-buffer-local 'org-todo-sets)
1381 (defvar org-todo-log-states nil)
1382 (make-variable-buffer-local 'org-todo-log-states)
1383 (defvar org-todo-kwd-alist nil)
1384 (make-variable-buffer-local 'org-todo-kwd-alist)
1385 (defvar org-todo-key-alist nil)
1386 (make-variable-buffer-local 'org-todo-key-alist)
1387 (defvar org-todo-key-trigger nil)
1388 (make-variable-buffer-local 'org-todo-key-trigger)
1390 (defcustom org-todo-interpretation 'sequence
1391 "Controls how TODO keywords are interpreted.
1392 This variable is in principle obsolete and is only used for
1393 backward compatibility, if the interpretation of todo keywords is
1394 not given already in `org-todo-keywords'. See that variable for
1395 more information."
1396 :group 'org-todo
1397 :group 'org-keywords
1398 :type '(choice (const sequence)
1399 (const type)))
1401 (defcustom org-use-fast-todo-selection 'prefix
1402 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1403 This variable describes if and under what circumstances the cycling
1404 mechanism for TODO keywords will be replaced by a single-key, direct
1405 selection scheme.
1407 When nil, fast selection is never used.
1409 When the symbol `prefix', it will be used when `org-todo' is called with
1410 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1411 in an agenda buffer.
1413 When t, fast selection is used by default. In this case, the prefix
1414 argument forces cycling instead.
1416 In all cases, the special interface is only used if access keys have actually
1417 been assigned by the user, i.e. if keywords in the configuration are followed
1418 by a letter in parenthesis, like TODO(t)."
1419 :group 'org-todo
1420 :type '(choice
1421 (const :tag "Never" nil)
1422 (const :tag "By default" t)
1423 (const :tag "Only with C-u C-c C-t" prefix)))
1425 (defcustom org-provide-todo-statistics t
1426 "Non-nil means, update todo statistics after insert and toggle.
1427 When this is set, todo statistics is updated in the parent of the current
1428 entry each time a todo state is changed."
1429 :group 'org-todo
1430 :type 'boolean)
1432 (defcustom org-after-todo-state-change-hook nil
1433 "Hook which is run after the state of a TODO item was changed.
1434 The new state (a string with a TODO keyword, or nil) is available in the
1435 Lisp variable `state'."
1436 :group 'org-todo
1437 :type 'hook)
1439 (defcustom org-todo-state-tags-triggers nil
1440 "Tag changes that should be triggered by TODO state changes.
1441 This is a list. Each entry is
1443 (state-change (tag . flag) .......)
1445 State-change can be a string with a state, and empty string to indicate the
1446 state that has no TODO keyword, or it can be one of the symbols `todo'
1447 or `done', meaning any not-done or done state, respectively."
1448 :group 'org-todo
1449 :group 'org-tags
1450 :type '(repeat
1451 (cons (choice :tag "When changing to"
1452 (const :tag "Not-done state" todo)
1453 (const :tag "Done state" done)
1454 (string :tag "State"))
1455 (repeat
1456 (cons :tag "Tag action"
1457 (string :tag "Tag")
1458 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1460 (defcustom org-log-done nil
1461 "Non-nil means, record a CLOSED timestamp when moving an entry to DONE.
1462 When equal to the list (done), also prompt for a closing note.
1463 This can also be configured on a per-file basis by adding one of
1464 the following lines anywhere in the buffer:
1466 #+STARTUP: logdone
1467 #+STARTUP: lognotedone
1468 #+STARTUP: nologdone"
1469 :group 'org-todo
1470 :group 'org-progress
1471 :type '(choice
1472 (const :tag "No logging" nil)
1473 (const :tag "Record CLOSED timestamp" time)
1474 (const :tag "Record CLOSED timestamp with closing note." note)))
1476 ;; Normalize old uses of org-log-done.
1477 (cond
1478 ((eq org-log-done t) (setq org-log-done 'time))
1479 ((and (listp org-log-done) (memq 'done org-log-done))
1480 (setq org-log-done 'note)))
1482 (defcustom org-log-note-clock-out nil
1483 "Non-nil means, record a note when clocking out of an item.
1484 This can also be configured on a per-file basis by adding one of
1485 the following lines anywhere in the buffer:
1487 #+STARTUP: lognoteclock-out
1488 #+STARTUP: nolognoteclock-out"
1489 :group 'org-todo
1490 :group 'org-progress
1491 :type 'boolean)
1493 (defcustom org-log-done-with-time t
1494 "Non-nil means, the CLOSED time stamp will contain date and time.
1495 When nil, only the date will be recorded."
1496 :group 'org-progress
1497 :type 'boolean)
1499 (defcustom org-log-note-headings
1500 '((done . "CLOSING NOTE %t")
1501 (state . "State %-12s %t")
1502 (note . "Note taken on %t")
1503 (clock-out . ""))
1504 "Headings for notes added to entries.
1505 The value is an alist, with the car being a symbol indicating the note
1506 context, and the cdr is the heading to be used. The heading may also be the
1507 empty string.
1508 %t in the heading will be replaced by a time stamp.
1509 %s will be replaced by the new TODO state, in double quotes.
1510 %u will be replaced by the user name.
1511 %U will be replaced by the full user name."
1512 :group 'org-todo
1513 :group 'org-progress
1514 :type '(list :greedy t
1515 (cons (const :tag "Heading when closing an item" done) string)
1516 (cons (const :tag
1517 "Heading when changing todo state (todo sequence only)"
1518 state) string)
1519 (cons (const :tag "Heading when just taking a note" note) string)
1520 (cons (const :tag "Heading when clocking out" clock-out) string)))
1522 (unless (assq 'note org-log-note-headings)
1523 (push '(note . "%t") org-log-note-headings))
1525 (defcustom org-log-state-notes-insert-after-drawers nil
1526 "Non-nil means, insert state change notes after any drawers in entry.
1527 Only the drawers that *immediately* follow the headline and the
1528 deadline/scheduled line are skipped.
1529 When nil, insert notes right after the heading and perhaps the line
1530 with deadline/scheduling if present."
1531 :group 'org-todo
1532 :group 'org-progress
1533 :type 'boolean)
1535 (defcustom org-log-states-order-reversed t
1536 "Non-nil means, the latest state change note will be directly after heading.
1537 When nil, the notes will be orderer according to time."
1538 :group 'org-todo
1539 :group 'org-progress
1540 :type 'boolean)
1542 (defcustom org-log-repeat 'time
1543 "Non-nil means, record moving through the DONE state when triggering repeat.
1544 An auto-repeating tasks is immediately switched back to TODO when marked
1545 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1546 the TODO keyword definition, or recording a closing note by setting
1547 `org-log-done', there will be no record of the task moving through DONE.
1548 This variable forces taking a note anyway. Possible values are:
1550 nil Don't force a record
1551 time Record a time stamp
1552 note Record a note
1554 This option can also be set with on a per-file-basis with
1556 #+STARTUP: logrepeat
1557 #+STARTUP: lognoterepeat
1558 #+STARTUP: nologrepeat
1560 You can have local logging settings for a subtree by setting the LOGGING
1561 property to one or more of these keywords."
1562 :group 'org-todo
1563 :group 'org-progress
1564 :type '(choice
1565 (const :tag "Don't force a record" nil)
1566 (const :tag "Force recording the DONE state" time)
1567 (const :tag "Force recording a note with the DONE state" note)))
1570 (defgroup org-priorities nil
1571 "Priorities in Org-mode."
1572 :tag "Org Priorities"
1573 :group 'org-todo)
1575 (defcustom org-highest-priority ?A
1576 "The highest priority of TODO items. A character like ?A, ?B etc.
1577 Must have a smaller ASCII number than `org-lowest-priority'."
1578 :group 'org-priorities
1579 :type 'character)
1581 (defcustom org-lowest-priority ?C
1582 "The lowest priority of TODO items. A character like ?A, ?B etc.
1583 Must have a larger ASCII number than `org-highest-priority'."
1584 :group 'org-priorities
1585 :type 'character)
1587 (defcustom org-default-priority ?B
1588 "The default priority of TODO items.
1589 This is the priority an item get if no explicit priority is given."
1590 :group 'org-priorities
1591 :type 'character)
1593 (defcustom org-priority-start-cycle-with-default t
1594 "Non-nil means, start with default priority when starting to cycle.
1595 When this is nil, the first step in the cycle will be (depending on the
1596 command used) one higher or lower that the default priority."
1597 :group 'org-priorities
1598 :type 'boolean)
1600 (defgroup org-time nil
1601 "Options concerning time stamps and deadlines in Org-mode."
1602 :tag "Org Time"
1603 :group 'org)
1605 (defcustom org-insert-labeled-timestamps-at-point nil
1606 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1607 When nil, these labeled time stamps are forces into the second line of an
1608 entry, just after the headline. When scheduling from the global TODO list,
1609 the time stamp will always be forced into the second line."
1610 :group 'org-time
1611 :type 'boolean)
1613 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1614 "Formats for `format-time-string' which are used for time stamps.
1615 It is not recommended to change this constant.")
1617 (defcustom org-time-stamp-rounding-minutes '(0 5)
1618 "Number of minutes to round time stamps to.
1619 These are two values, the first applies when first creating a time stamp.
1620 The second applies when changing it with the commands `S-up' and `S-down'.
1621 When changing the time stamp, this means that it will change in steps
1622 of N minutes, as given by the second value.
1624 When a setting is 0 or 1, insert the time unmodified. Useful rounding
1625 numbers should be factors of 60, so for example 5, 10, 15.
1627 When this is larger than 1, you can still force an exact time-stamp by using
1628 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
1629 and by using a prefix arg to `S-up/down' to specify the exact number
1630 of minutes to shift."
1631 :group 'org-time
1632 :get '(lambda (var) ; Make sure all entries have 5 elements
1633 (if (integerp (default-value var))
1634 (list (default-value var) 5)
1635 (default-value var)))
1636 :type '(list
1637 (integer :tag "when inserting times")
1638 (integer :tag "when modifying times")))
1640 ;; Normalize old customizations of this variable.
1641 (when (integerp org-time-stamp-rounding-minutes)
1642 (setq org-time-stamp-rounding-minutes
1643 (list org-time-stamp-rounding-minutes
1644 org-time-stamp-rounding-minutes)))
1646 (defcustom org-display-custom-times nil
1647 "Non-nil means, overlay custom formats over all time stamps.
1648 The formats are defined through the variable `org-time-stamp-custom-formats'.
1649 To turn this on on a per-file basis, insert anywhere in the file:
1650 #+STARTUP: customtime"
1651 :group 'org-time
1652 :set 'set-default
1653 :type 'sexp)
1654 (make-variable-buffer-local 'org-display-custom-times)
1656 (defcustom org-time-stamp-custom-formats
1657 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1658 "Custom formats for time stamps. See `format-time-string' for the syntax.
1659 These are overlayed over the default ISO format if the variable
1660 `org-display-custom-times' is set. Time like %H:%M should be at the
1661 end of the second format."
1662 :group 'org-time
1663 :type 'sexp)
1665 (defun org-time-stamp-format (&optional long inactive)
1666 "Get the right format for a time string."
1667 (let ((f (if long (cdr org-time-stamp-formats)
1668 (car org-time-stamp-formats))))
1669 (if inactive
1670 (concat "[" (substring f 1 -1) "]")
1671 f)))
1673 (defcustom org-time-clocksum-format "%d:%02d"
1674 "The format string used when creating CLOCKSUM lines, or when
1675 org-mode generates a time duration."
1676 :group 'org-time
1677 :type 'string)
1679 (defcustom org-deadline-warning-days 14
1680 "No. of days before expiration during which a deadline becomes active.
1681 This variable governs the display in sparse trees and in the agenda.
1682 When 0 or negative, it means use this number (the absolute value of it)
1683 even if a deadline has a different individual lead time specified."
1684 :group 'org-time
1685 :group 'org-agenda-daily/weekly
1686 :type 'number)
1688 (defcustom org-read-date-prefer-future t
1689 "Non-nil means, assume future for incomplete date input from user.
1690 This affects the following situations:
1691 1. The user gives a day, but no month.
1692 For example, if today is the 15th, and you enter \"3\", Org-mode will
1693 read this as the third of *next* month. However, if you enter \"17\",
1694 it will be considered as *this* month.
1695 2. The user gives a month but not a year.
1696 For example, if it is april and you enter \"feb 2\", this will be read
1697 as feb 2, *next* year. \"May 5\", however, will be this year.
1699 Currently this does not work for ISO week specifications.
1701 When this option is nil, the current month and year will always be used
1702 as defaults."
1703 :group 'org-time
1704 :type 'boolean)
1706 (defcustom org-read-date-display-live t
1707 "Non-nil means, display current interpretation of date prompt live.
1708 This display will be in an overlay, in the minibuffer."
1709 :group 'org-time
1710 :type 'boolean)
1712 (defcustom org-read-date-popup-calendar t
1713 "Non-nil means, pop up a calendar when prompting for a date.
1714 In the calendar, the date can be selected with mouse-1. However, the
1715 minibuffer will also be active, and you can simply enter the date as well.
1716 When nil, only the minibuffer will be available."
1717 :group 'org-time
1718 :type 'boolean)
1719 (if (fboundp 'defvaralias)
1720 (defvaralias 'org-popup-calendar-for-date-prompt
1721 'org-read-date-popup-calendar))
1723 (defcustom org-extend-today-until 0
1724 "The hour when your day really ends. Must be an integer.
1725 This has influence for the following applications:
1726 - When switching the agenda to \"today\". It it is still earlier than
1727 the time given here, the day recognized as TODAY is actually yesterday.
1728 - When a date is read from the user and it is still before the time given
1729 here, the current date and time will be assumed to be yesterday, 23:59.
1730 Also, timestamps inserted in remember templates follow this rule.
1732 IMPORTANT: This is a feature whose implementation is and likely will
1733 remain incomplete. Really, it is only here because past midnight seems to
1734 be the favorite working time of John Wiegley :-)"
1735 :group 'org-time
1736 :type 'number)
1738 (defcustom org-edit-timestamp-down-means-later nil
1739 "Non-nil means, S-down will increase the time in a time stamp.
1740 When nil, S-up will increase."
1741 :group 'org-time
1742 :type 'boolean)
1744 (defcustom org-calendar-follow-timestamp-change t
1745 "Non-nil means, make the calendar window follow timestamp changes.
1746 When a timestamp is modified and the calendar window is visible, it will be
1747 moved to the new date."
1748 :group 'org-time
1749 :type 'boolean)
1751 (defgroup org-tags nil
1752 "Options concerning tags in Org-mode."
1753 :tag "Org Tags"
1754 :group 'org)
1756 (defcustom org-tag-alist nil
1757 "List of tags allowed in Org-mode files.
1758 When this list is nil, Org-mode will base TAG input on what is already in the
1759 buffer.
1760 The value of this variable is an alist, the car of each entry must be a
1761 keyword as a string, the cdr may be a character that is used to select
1762 that tag through the fast-tag-selection interface.
1763 See the manual for details."
1764 :group 'org-tags
1765 :type '(repeat
1766 (choice
1767 (cons (string :tag "Tag name")
1768 (character :tag "Access char"))
1769 (const :tag "Start radio group" (:startgroup))
1770 (const :tag "End radio group" (:endgroup)))))
1772 (defvar org-file-tags nil
1773 "List of tags that can be inherited by all entries in the file.
1774 The tags will be inherited if the variable `org-use-tag-inheritance'
1775 says they should be.
1776 This variable is populated from #+TAG lines.")
1778 (defcustom org-use-fast-tag-selection 'auto
1779 "Non-nil means, use fast tag selection scheme.
1780 This is a special interface to select and deselect tags with single keys.
1781 When nil, fast selection is never used.
1782 When the symbol `auto', fast selection is used if and only if selection
1783 characters for tags have been configured, either through the variable
1784 `org-tag-alist' or through a #+TAGS line in the buffer.
1785 When t, fast selection is always used and selection keys are assigned
1786 automatically if necessary."
1787 :group 'org-tags
1788 :type '(choice
1789 (const :tag "Always" t)
1790 (const :tag "Never" nil)
1791 (const :tag "When selection characters are configured" 'auto)))
1793 (defcustom org-fast-tag-selection-single-key nil
1794 "Non-nil means, fast tag selection exits after first change.
1795 When nil, you have to press RET to exit it.
1796 During fast tag selection, you can toggle this flag with `C-c'.
1797 This variable can also have the value `expert'. In this case, the window
1798 displaying the tags menu is not even shown, until you press C-c again."
1799 :group 'org-tags
1800 :type '(choice
1801 (const :tag "No" nil)
1802 (const :tag "Yes" t)
1803 (const :tag "Expert" expert)))
1805 (defvar org-fast-tag-selection-include-todo nil
1806 "Non-nil means, fast tags selection interface will also offer TODO states.
1807 This is an undocumented feature, you should not rely on it.")
1809 (defcustom org-tags-column (if (featurep 'xemacs) -79 -80)
1810 "The column to which tags should be indented in a headline.
1811 If this number is positive, it specifies the column. If it is negative,
1812 it means that the tags should be flushright to that column. For example,
1813 -80 works well for a normal 80 character screen."
1814 :group 'org-tags
1815 :type 'integer)
1817 (defcustom org-auto-align-tags t
1818 "Non-nil means, realign tags after pro/demotion of TODO state change.
1819 These operations change the length of a headline and therefore shift
1820 the tags around. With this options turned on, after each such operation
1821 the tags are again aligned to `org-tags-column'."
1822 :group 'org-tags
1823 :type 'boolean)
1825 (defcustom org-use-tag-inheritance t
1826 "Non-nil means, tags in levels apply also for sublevels.
1827 When nil, only the tags directly given in a specific line apply there.
1828 If this option is t, a match early-on in a tree can lead to a large
1829 number of matches in the subtree. If you only want to see the first
1830 match in a tree during a search, check out the variable
1831 `org-tags-match-list-sublevels'.
1833 This may also be a list of tags that should be inherited, or a regexp that
1834 matches tags that should be inherited."
1835 :group 'org-tags
1836 :type '(choice
1837 (const :tag "Not" nil)
1838 (const :tag "Always" t)
1839 (repeat :tag "Specific tags" (string :tag "Tag"))
1840 (regexp :tag "Tags matched by regexp")))
1842 (defun org-tag-inherit-p (tag)
1843 "Check if TAG is one that should be inherited."
1844 (cond
1845 ((eq org-use-tag-inheritance t) t)
1846 ((not org-use-tag-inheritance) nil)
1847 ((stringp org-use-tag-inheritance)
1848 (string-match org-use-tag-inheritance tag))
1849 ((listp org-use-tag-inheritance)
1850 (member tag org-use-tag-inheritance))
1851 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
1853 (defcustom org-tags-match-list-sublevels t
1854 "Non-nil means list also sublevels of headlines matching tag search.
1855 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1856 the sublevels of a headline matching a tag search often also match
1857 the same search. Listing all of them can create very long lists.
1858 Setting this variable to nil causes subtrees of a match to be skipped.
1859 This option is off by default, because inheritance in on. If you turn
1860 inheritance off, you very likely want to turn this option on.
1862 As a special case, if the tag search is restricted to TODO items, the
1863 value of this variable is ignored and sublevels are always checked, to
1864 make sure all corresponding TODO items find their way into the list."
1865 :group 'org-tags
1866 :type 'boolean)
1868 (defvar org-tags-history nil
1869 "History of minibuffer reads for tags.")
1870 (defvar org-last-tags-completion-table nil
1871 "The last used completion table for tags.")
1872 (defvar org-after-tags-change-hook nil
1873 "Hook that is run after the tags in a line have changed.")
1875 (defgroup org-properties nil
1876 "Options concerning properties in Org-mode."
1877 :tag "Org Properties"
1878 :group 'org)
1880 (defcustom org-property-format "%-10s %s"
1881 "How property key/value pairs should be formatted by `indent-line'.
1882 When `indent-line' hits a property definition, it will format the line
1883 according to this format, mainly to make sure that the values are
1884 lined-up with respect to each other."
1885 :group 'org-properties
1886 :type 'string)
1888 (defcustom org-use-property-inheritance nil
1889 "Non-nil means, properties apply also for sublevels.
1891 This setting is chiefly used during property searches. Turning it on can
1892 cause significant overhead when doing a search, which is why it is not
1893 on by default.
1895 When nil, only the properties directly given in the current entry count.
1896 When t, every property is inherited. The value may also be a list of
1897 properties that should have inheritance, or a regular expression matching
1898 properties that should be inherited.
1900 However, note that some special properties use inheritance under special
1901 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
1902 and the properties ending in \"_ALL\" when they are used as descriptor
1903 for valid values of a property.
1905 Note for programmers:
1906 When querying an entry with `org-entry-get', you can control if inheritance
1907 should be used. By default, `org-entry-get' looks only at the local
1908 properties. You can request inheritance by setting the inherit argument
1909 to t (to force inheritance) or to `selective' (to respect the setting
1910 in this variable)."
1911 :group 'org-properties
1912 :type '(choice
1913 (const :tag "Not" nil)
1914 (const :tag "Always" t)
1915 (repeat :tag "Specific properties" (string :tag "Property"))
1916 (regexp :tag "Properties matched by regexp")))
1918 (defun org-property-inherit-p (property)
1919 "Check if PROPERTY is one that should be inherited."
1920 (cond
1921 ((eq org-use-property-inheritance t) t)
1922 ((not org-use-property-inheritance) nil)
1923 ((stringp org-use-property-inheritance)
1924 (string-match org-use-property-inheritance property))
1925 ((listp org-use-property-inheritance)
1926 (member property org-use-property-inheritance))
1927 (t (error "Invalid setting of `org-use-property-inheritance'"))))
1929 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
1930 "The default column format, if no other format has been defined.
1931 This variable can be set on the per-file basis by inserting a line
1933 #+COLUMNS: %25ITEM ....."
1934 :group 'org-properties
1935 :type 'string)
1937 (defcustom org-columns-ellipses ".."
1938 "The ellipses to be used when a field in column view is truncated.
1939 When this is the empty string, as many characters as possible are shown,
1940 but then there will be no visual indication that the field has been truncated.
1941 When this is a string of length N, the last N characters of a truncated
1942 field are replaced by this string. If the column is narrower than the
1943 ellipses string, only part of the ellipses string will be shown."
1944 :group 'org-properties
1945 :type 'string)
1947 (defcustom org-columns-modify-value-for-display-function nil
1948 "Function that modifies values for display in column view.
1949 For example, it can be used to cut out a certain part from a time stamp.
1950 The function must take 2 argments:
1952 column-title The tite of the column (*not* the property name)
1953 value The value that should be modified.
1955 The function should return the value that should be displayed,
1956 or nil if the normal value should be used."
1957 :group 'org-properties
1958 :type 'function)
1960 (defcustom org-effort-property "Effort"
1961 "The property that is being used to keep track of effort estimates.
1962 Effort estimates given in this property need to have the format H:MM."
1963 :group 'org-properties
1964 :group 'org-progress
1965 :type '(string :tag "Property"))
1967 (defconst org-global-properties-fixed
1968 '(("VISIBILITY_ALL" . "folded children content all"))
1969 "List of property/value pairs that can be inherited by any entry.
1970 These are fixed values, for the preset properties.")
1973 (defcustom org-global-properties nil
1974 "List of property/value pairs that can be inherited by any entry.
1975 You can set buffer-local values for this by adding lines like
1977 #+PROPERTY: NAME VALUE"
1978 :group 'org-properties
1979 :type '(repeat
1980 (cons (string :tag "Property")
1981 (string :tag "Value"))))
1983 (defvar org-file-properties nil
1984 "List of property/value pairs that can be inherited by any entry.
1985 Valid for the current buffer.
1986 This variable is populated from #+PROPERTY lines.")
1987 (make-variable-buffer-local 'org-file-properties)
1989 (defgroup org-agenda nil
1990 "Options concerning agenda views in Org-mode."
1991 :tag "Org Agenda"
1992 :group 'org)
1994 (defvar org-category nil
1995 "Variable used by org files to set a category for agenda display.
1996 Such files should use a file variable to set it, for example
1998 # -*- mode: org; org-category: \"ELisp\"
2000 or contain a special line
2002 #+CATEGORY: ELisp
2004 If the file does not specify a category, then file's base name
2005 is used instead.")
2006 (make-variable-buffer-local 'org-category)
2007 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2009 (defcustom org-agenda-files nil
2010 "The files to be used for agenda display.
2011 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2012 \\[org-remove-file]. You can also use customize to edit the list.
2014 If an entry is a directory, all files in that directory that are matched by
2015 `org-agenda-file-regexp' will be part of the file list.
2017 If the value of the variable is not a list but a single file name, then
2018 the list of agenda files is actually stored and maintained in that file, one
2019 agenda file per line."
2020 :group 'org-agenda
2021 :type '(choice
2022 (repeat :tag "List of files and directories" file)
2023 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2025 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2026 "Regular expression to match files for `org-agenda-files'.
2027 If any element in the list in that variable contains a directory instead
2028 of a normal file, all files in that directory that are matched by this
2029 regular expression will be included."
2030 :group 'org-agenda
2031 :type 'regexp)
2033 (defcustom org-agenda-text-search-extra-files nil
2034 "List of extra files to be searched by text search commands.
2035 These files will be search in addition to the agenda files by the
2036 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2037 Note that these files will only be searched for text search commands,
2038 not for the other agenda views like todo lists, tag searches or the weekly
2039 agenda. This variable is intended to list notes and possibly archive files
2040 that should also be searched by these two commands.
2041 In fact, if the first element in the list is the symbol `agenda-archives',
2042 than all archive files of all agenda files will be added to the search
2043 scope."
2044 :group 'org-agenda
2045 :type '(set :greedy t
2046 (const :tag "Agenda Archives" agenda-archives)
2047 (repeat :inline t (file))))
2049 (if (fboundp 'defvaralias)
2050 (defvaralias 'org-agenda-multi-occur-extra-files
2051 'org-agenda-text-search-extra-files))
2053 (defcustom org-agenda-skip-unavailable-files nil
2054 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2055 A nil value means to remove them, after a query, from the list."
2056 :group 'org-agenda
2057 :type 'boolean)
2059 (defcustom org-calendar-to-agenda-key [?c]
2060 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2061 The command `org-calendar-goto-agenda' will be bound to this key. The
2062 default is the character `c' because then `c' can be used to switch back and
2063 forth between agenda and calendar."
2064 :group 'org-agenda
2065 :type 'sexp)
2067 (defcustom org-calendar-agenda-action-key [?k]
2068 "The key to be installed in `calendar-mode-map' for agenda-action.
2069 The command `org-agenda-action' will be bound to this key. The
2070 default is the character `k' because we use the same key in the agenda."
2071 :group 'org-agenda
2072 :type 'sexp)
2074 (eval-after-load "calendar"
2075 '(progn
2076 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2077 'org-calendar-goto-agenda)
2078 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2079 'org-agenda-action)))
2081 (defgroup org-latex nil
2082 "Options for embedding LaTeX code into Org-mode."
2083 :tag "Org LaTeX"
2084 :group 'org)
2086 (defcustom org-format-latex-options
2087 '(:foreground default :background default :scale 1.0
2088 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2089 :matchers ("begin" "$" "$$" "\\(" "\\["))
2090 "Options for creating images from LaTeX fragments.
2091 This is a property list with the following properties:
2092 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2093 `default' means use the foreground of the default face.
2094 :background the background color, or \"Transparent\".
2095 `default' means use the background of the default face.
2096 :scale a scaling factor for the size of the images.
2097 :html-foreground, :html-background, :html-scale
2098 the same numbers for HTML export.
2099 :matchers a list indicating which matchers should be used to
2100 find LaTeX fragments. Valid members of this list are:
2101 \"begin\" find environments
2102 \"$\" find math expressions surrounded by $...$
2103 \"$$\" find math expressions surrounded by $$....$$
2104 \"\\(\" find math expressions surrounded by \\(...\\)
2105 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2106 :group 'org-latex
2107 :type 'plist)
2109 (defcustom org-format-latex-header "\\documentclass{article}
2110 \\usepackage{fullpage} % do not remove
2111 \\usepackage{amssymb}
2112 \\usepackage[usenames]{color}
2113 \\usepackage{amsmath}
2114 \\usepackage{latexsym}
2115 \\usepackage[mathscr]{eucal}
2116 \\pagestyle{empty} % do not remove"
2117 "The document header used for processing LaTeX fragments."
2118 :group 'org-latex
2119 :type 'string)
2122 (defgroup org-font-lock nil
2123 "Font-lock settings for highlighting in Org-mode."
2124 :tag "Org Font Lock"
2125 :group 'org)
2127 (defcustom org-level-color-stars-only nil
2128 "Non-nil means fontify only the stars in each headline.
2129 When nil, the entire headline is fontified.
2130 Changing it requires restart of `font-lock-mode' to become effective
2131 also in regions already fontified."
2132 :group 'org-font-lock
2133 :type 'boolean)
2135 (defcustom org-hide-leading-stars nil
2136 "Non-nil means, hide the first N-1 stars in a headline.
2137 This works by using the face `org-hide' for these stars. This
2138 face is white for a light background, and black for a dark
2139 background. You may have to customize the face `org-hide' to
2140 make this work.
2141 Changing it requires restart of `font-lock-mode' to become effective
2142 also in regions already fontified.
2143 You may also set this on a per-file basis by adding one of the following
2144 lines to the buffer:
2146 #+STARTUP: hidestars
2147 #+STARTUP: showstars"
2148 :group 'org-font-lock
2149 :type 'boolean)
2151 (defcustom org-fontify-done-headline nil
2152 "Non-nil means, change the face of a headline if it is marked DONE.
2153 Normally, only the TODO/DONE keyword indicates the state of a headline.
2154 When this is non-nil, the headline after the keyword is set to the
2155 `org-headline-done' as an additional indication."
2156 :group 'org-font-lock
2157 :type 'boolean)
2159 (defcustom org-fontify-emphasized-text t
2160 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2161 Changing this variable requires a restart of Emacs to take effect."
2162 :group 'org-font-lock
2163 :type 'boolean)
2165 (defcustom org-highlight-latex-fragments-and-specials nil
2166 "Non-nil means, fontify what is treated specially by the exporters."
2167 :group 'org-font-lock
2168 :type 'boolean)
2170 (defcustom org-hide-emphasis-markers nil
2171 "Non-nil mean font-lock should hide the emphasis marker characters."
2172 :group 'org-font-lock
2173 :type 'boolean)
2175 (defvar org-emph-re nil
2176 "Regular expression for matching emphasis.")
2177 (defvar org-verbatim-re nil
2178 "Regular expression for matching verbatim text.")
2179 (defvar org-emphasis-regexp-components) ; defined just below
2180 (defvar org-emphasis-alist) ; defined just below
2181 (defun org-set-emph-re (var val)
2182 "Set variable and compute the emphasis regular expression."
2183 (set var val)
2184 (when (and (boundp 'org-emphasis-alist)
2185 (boundp 'org-emphasis-regexp-components)
2186 org-emphasis-alist org-emphasis-regexp-components)
2187 (let* ((e org-emphasis-regexp-components)
2188 (pre (car e))
2189 (post (nth 1 e))
2190 (border (nth 2 e))
2191 (body (nth 3 e))
2192 (nl (nth 4 e))
2193 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
2194 (body1 (concat body "*?"))
2195 (markers (mapconcat 'car org-emphasis-alist ""))
2196 (vmarkers (mapconcat
2197 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2198 org-emphasis-alist "")))
2199 ;; make sure special characters appear at the right position in the class
2200 (if (string-match "\\^" markers)
2201 (setq markers (concat (replace-match "" t t markers) "^")))
2202 (if (string-match "-" markers)
2203 (setq markers (concat (replace-match "" t t markers) "-")))
2204 (if (string-match "\\^" vmarkers)
2205 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2206 (if (string-match "-" vmarkers)
2207 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2208 (if (> nl 0)
2209 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2210 (int-to-string nl) "\\}")))
2211 ;; Make the regexp
2212 (setq org-emph-re
2213 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
2214 "\\("
2215 "\\([" markers "]\\)"
2216 "\\("
2217 "[^" border "]\\|"
2218 "[^" border (if (and nil stacked) markers) "]"
2219 body1
2220 "[^" border (if (and nil stacked) markers) "]"
2221 "\\)"
2222 "\\3\\)"
2223 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
2224 (setq org-verbatim-re
2225 (concat "\\([" pre "]\\|^\\)"
2226 "\\("
2227 "\\([" vmarkers "]\\)"
2228 "\\("
2229 "[^" border "]\\|"
2230 "[^" border "]"
2231 body1
2232 "[^" border "]"
2233 "\\)"
2234 "\\3\\)"
2235 "\\([" post "]\\|$\\)")))))
2237 (defcustom org-emphasis-regexp-components
2238 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
2239 "Components used to build the regular expression for emphasis.
2240 This is a list with 6 entries. Terminology: In an emphasis string
2241 like \" *strong word* \", we call the initial space PREMATCH, the final
2242 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2243 and \"trong wor\" is the body. The different components in this variable
2244 specify what is allowed/forbidden in each part:
2246 pre Chars allowed as prematch. Beginning of line will be allowed too.
2247 post Chars allowed as postmatch. End of line will be allowed too.
2248 border The chars *forbidden* as border characters.
2249 body-regexp A regexp like \".\" to match a body character. Don't use
2250 non-shy groups here, and don't allow newline here.
2251 newline The maximum number of newlines allowed in an emphasis exp.
2253 Use customize to modify this, or restart Emacs after changing it."
2254 :group 'org-font-lock
2255 :set 'org-set-emph-re
2256 :type '(list
2257 (sexp :tag "Allowed chars in pre ")
2258 (sexp :tag "Allowed chars in post ")
2259 (sexp :tag "Forbidden chars in border ")
2260 (sexp :tag "Regexp for body ")
2261 (integer :tag "number of newlines allowed")
2262 (option (boolean :tag "Please ignore this button"))))
2264 (defcustom org-emphasis-alist
2265 `(("*" bold "<b>" "</b>")
2266 ("/" italic "<i>" "</i>")
2267 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
2268 ("=" org-code "<code>" "</code>" verbatim)
2269 ("~" org-verbatim "<code>" "</code>" verbatim)
2270 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2271 "<del>" "</del>")
2273 "Special syntax for emphasized text.
2274 Text starting and ending with a special character will be emphasized, for
2275 example *bold*, _underlined_ and /italic/. This variable sets the marker
2276 characters, the face to be used by font-lock for highlighting in Org-mode
2277 Emacs buffers, and the HTML tags to be used for this.
2278 Use customize to modify this, or restart Emacs after changing it."
2279 :group 'org-font-lock
2280 :set 'org-set-emph-re
2281 :type '(repeat
2282 (list
2283 (string :tag "Marker character")
2284 (choice
2285 (face :tag "Font-lock-face")
2286 (plist :tag "Face property list"))
2287 (string :tag "HTML start tag")
2288 (string :tag "HTML end tag")
2289 (option (const verbatim)))))
2291 ;;; Miscellaneous options
2293 (defgroup org-completion nil
2294 "Completion in Org-mode."
2295 :tag "Org Completion"
2296 :group 'org)
2298 (defcustom org-completion-fallback-command 'hippie-expand
2299 "The expansion command called by \\[org-complete] in normal context.
2300 Normal means, no org-mode-specific context."
2301 :group 'org-completion
2302 :type 'function)
2304 ;;; Functions and variables from ther packages
2305 ;; Declared here to avoid compiler warnings
2307 ;; XEmacs only
2308 (defvar outline-mode-menu-heading)
2309 (defvar outline-mode-menu-show)
2310 (defvar outline-mode-menu-hide)
2311 (defvar zmacs-regions) ; XEmacs regions
2313 ;; Emacs only
2314 (defvar mark-active)
2316 ;; Various packages
2317 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2318 (declare-function calendar-forward-day "cal-move" (arg))
2319 (declare-function calendar-goto-date "cal-move" (date))
2320 (declare-function calendar-goto-today "cal-move" ())
2321 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2322 (defvar calc-embedded-close-formula)
2323 (defvar calc-embedded-open-formula)
2324 (declare-function cdlatex-tab "ext:cdlatex" ())
2325 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2326 (defvar font-lock-unfontify-region-function)
2327 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2328 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2329 (defvar iswitchb-temp-buflist)
2330 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2331 (declare-function org-agenda-skip "org-agenda" ())
2332 (declare-function org-format-agenda-item "org-agenda"
2333 (extra txt &optional category tags dotime noprefix remove-re))
2334 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2335 (declare-function org-agenda-change-all-lines "org-agenda"
2336 (newhead hdmarker &optional fixface))
2337 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2338 (declare-function org-agenda-maybe-redo "org-agenda" ())
2339 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2340 (beg end))
2341 (declare-function parse-time-string "parse-time" (string))
2342 (declare-function remember "remember" (&optional initial))
2343 (declare-function remember-buffer-desc "remember" ())
2344 (declare-function remember-finalize "remember" ())
2345 (defvar remember-save-after-remembering)
2346 (defvar remember-data-file)
2347 (defvar remember-register)
2348 (defvar remember-buffer)
2349 (defvar remember-handler-functions)
2350 (defvar remember-annotation-functions)
2351 (defvar texmathp-why)
2352 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2353 (declare-function table--at-cell-p "table" (position &optional object at-column))
2355 (defvar w3m-current-url)
2356 (defvar w3m-current-title)
2358 (defvar org-latex-regexps)
2360 ;;; Autoload and prepare some org modules
2362 ;; Some table stuff that needs to be defined here, because it is used
2363 ;; by the functions setting up org-mode or checking for table context.
2365 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2366 "Detects an org-type or table-type table.")
2367 (defconst org-table-line-regexp "^[ \t]*|"
2368 "Detects an org-type table line.")
2369 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2370 "Detects an org-type table line.")
2371 (defconst org-table-hline-regexp "^[ \t]*|-"
2372 "Detects an org-type table hline.")
2373 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2374 "Detects a table-type table hline.")
2375 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2376 "Searching from within a table (any type) this finds the first line
2377 outside the table.")
2379 ;; Autoload the functions in org-table.el that are needed by functions here.
2381 (eval-and-compile
2382 (org-autoload "org-table"
2383 '(org-table-align org-table-begin org-table-blank-field
2384 org-table-convert org-table-convert-region org-table-copy-down
2385 org-table-copy-region org-table-create
2386 org-table-create-or-convert-from-region
2387 org-table-create-with-table.el org-table-current-dline
2388 org-table-cut-region org-table-delete-column org-table-edit-field
2389 org-table-edit-formulas org-table-end org-table-eval-formula
2390 org-table-export org-table-field-info
2391 org-table-get-stored-formulas org-table-goto-column
2392 org-table-hline-and-move org-table-import org-table-insert-column
2393 org-table-insert-hline org-table-insert-row org-table-iterate
2394 org-table-justify-field-maybe org-table-kill-row
2395 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2396 org-table-move-column org-table-move-column-left
2397 org-table-move-column-right org-table-move-row
2398 org-table-move-row-down org-table-move-row-up
2399 org-table-next-field org-table-next-row org-table-paste-rectangle
2400 org-table-previous-field org-table-recalculate
2401 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2402 org-table-toggle-coordinate-overlays
2403 org-table-toggle-formula-debugger org-table-wrap-region
2404 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
2406 (defun org-at-table-p (&optional table-type)
2407 "Return t if the cursor is inside an org-type table.
2408 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2409 (if org-enable-table-editor
2410 (save-excursion
2411 (beginning-of-line 1)
2412 (looking-at (if table-type org-table-any-line-regexp
2413 org-table-line-regexp)))
2414 nil))
2415 (defsubst org-table-p () (org-at-table-p))
2417 (defun org-at-table.el-p ()
2418 "Return t if and only if we are at a table.el table."
2419 (and (org-at-table-p 'any)
2420 (save-excursion
2421 (goto-char (org-table-begin 'any))
2422 (looking-at org-table1-hline-regexp))))
2423 (defun org-table-recognize-table.el ()
2424 "If there is a table.el table nearby, recognize it and move into it."
2425 (if org-table-tab-recognizes-table.el
2426 (if (org-at-table.el-p)
2427 (progn
2428 (beginning-of-line 1)
2429 (if (looking-at org-table-dataline-regexp)
2431 (if (looking-at org-table1-hline-regexp)
2432 (progn
2433 (beginning-of-line 2)
2434 (if (looking-at org-table-any-border-regexp)
2435 (beginning-of-line -1)))))
2436 (if (re-search-forward "|" (org-table-end t) t)
2437 (progn
2438 (require 'table)
2439 (if (table--at-cell-p (point))
2441 (message "recognizing table.el table...")
2442 (table-recognize-table)
2443 (message "recognizing table.el table...done")))
2444 (error "This should not happen..."))
2446 nil)
2447 nil))
2449 (defun org-at-table-hline-p ()
2450 "Return t if the cursor is inside a hline in a table."
2451 (if org-enable-table-editor
2452 (save-excursion
2453 (beginning-of-line 1)
2454 (looking-at org-table-hline-regexp))
2455 nil))
2457 (defvar org-table-clean-did-remove-column nil)
2459 (defun org-table-map-tables (function)
2460 "Apply FUNCTION to the start of all tables in the buffer."
2461 (save-excursion
2462 (save-restriction
2463 (widen)
2464 (goto-char (point-min))
2465 (while (re-search-forward org-table-any-line-regexp nil t)
2466 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2467 (beginning-of-line 1)
2468 (if (looking-at org-table-line-regexp)
2469 (save-excursion (funcall function)))
2470 (re-search-forward org-table-any-border-regexp nil 1))))
2471 (message "Mapping tables: done"))
2473 ;; Declare and autoload functions from org-exp.el
2475 (declare-function org-default-export-plist "org-exp")
2476 (declare-function org-infile-export-plist "org-exp")
2477 (declare-function org-get-current-options "org-exp")
2478 (eval-and-compile
2479 (org-autoload "org-exp"
2480 '(org-export org-export-as-ascii org-export-visible
2481 org-insert-export-options-template org-export-as-html-and-open
2482 org-export-as-html-batch org-export-as-html-to-buffer
2483 org-replace-region-by-html org-export-region-as-html
2484 org-export-as-html org-export-icalendar-this-file
2485 org-export-icalendar-all-agenda-files
2486 org-table-clean-before-export
2487 org-export-icalendar-combine-agenda-files org-export-as-xoxo)))
2489 ;; Declare and autoload functions from org-agenda.el
2491 (eval-and-compile
2492 (org-autoload "org-agenda"
2493 '(org-agenda org-agenda-list org-search-view
2494 org-todo-list org-tags-view org-agenda-list-stuck-projects
2495 org-diary org-agenda-to-appt)))
2497 ;; Autoload org-remember
2499 (eval-and-compile
2500 (org-autoload "org-remember"
2501 '(org-remember-insinuate org-remember-annotation
2502 org-remember-apply-template org-remember org-remember-handler)))
2504 ;; Autoload org-clock.el
2507 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
2508 (beg end))
2509 (declare-function org-update-mode-line "org-clock" ())
2510 (defvar org-clock-start-time)
2511 (defvar org-clock-marker (make-marker)
2512 "Marker recording the last clock-in.")
2514 (eval-and-compile
2515 (org-autoload
2516 "org-clock"
2517 '(org-clock-in org-clock-out org-clock-cancel
2518 org-clock-goto org-clock-sum org-clock-display
2519 org-remove-clock-overlays org-clock-report
2520 org-clocktable-shift org-dblock-write:clocktable
2521 org-get-clocktable)))
2523 (defun org-clock-update-time-maybe ()
2524 "If this is a CLOCK line, update it and return t.
2525 Otherwise, return nil."
2526 (interactive)
2527 (save-excursion
2528 (beginning-of-line 1)
2529 (skip-chars-forward " \t")
2530 (when (looking-at org-clock-string)
2531 (let ((re (concat "[ \t]*" org-clock-string
2532 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
2533 "\\([ \t]*=>.*\\)?\\)?"))
2534 ts te h m s neg)
2535 (cond
2536 ((not (looking-at re))
2537 nil)
2538 ((not (match-end 2))
2539 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2540 (> org-clock-marker (point))
2541 (<= org-clock-marker (point-at-eol)))
2542 ;; The clock is running here
2543 (setq org-clock-start-time
2544 (apply 'encode-time
2545 (org-parse-time-string (match-string 1))))
2546 (org-update-mode-line)))
2548 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
2549 (end-of-line 1)
2550 (setq ts (match-string 1)
2551 te (match-string 3))
2552 (setq s (- (time-to-seconds
2553 (apply 'encode-time (org-parse-time-string te)))
2554 (time-to-seconds
2555 (apply 'encode-time (org-parse-time-string ts))))
2556 neg (< s 0)
2557 s (abs s)
2558 h (floor (/ s 3600))
2559 s (- s (* 3600 h))
2560 m (floor (/ s 60))
2561 s (- s (* 60 s)))
2562 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
2563 t))))))
2565 (defun org-check-running-clock ()
2566 "Check if the current buffer contains the running clock.
2567 If yes, offer to stop it and to save the buffer with the changes."
2568 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2569 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
2570 (buffer-name))))
2571 (org-clock-out)
2572 (when (y-or-n-p "Save changed buffer?")
2573 (save-buffer))))
2575 (defun org-clocktable-try-shift (dir n)
2576 "Check if this line starts a clock table, if yes, shift the time block."
2577 (when (org-match-line "#\\+BEGIN: clocktable\\>")
2578 (org-clocktable-shift dir n)))
2580 ;; Autoload archiving code
2581 ;; The stuff that is needed for cycling and tags has to be defined here.
2583 (defgroup org-archive nil
2584 "Options concerning archiving in Org-mode."
2585 :tag "Org Archive"
2586 :group 'org-structure)
2588 (defcustom org-archive-location "%s_archive::"
2589 "The location where subtrees should be archived.
2591 Otherwise, the value of this variable is a string, consisting of two
2592 parts, separated by a double-colon.
2594 The first part is a file name - when omitted, archiving happens in the same
2595 file. %s will be replaced by the current file name (without directory part).
2596 Archiving to a different file is useful to keep archived entries from
2597 contributing to the Org-mode Agenda.
2599 The part after the double colon is a headline. The archived entries will be
2600 filed under that headline. When omitted, the subtrees are simply filed away
2601 at the end of the file, as top-level entries.
2603 Here are a few examples:
2604 \"%s_archive::\"
2605 If the current file is Projects.org, archive in file
2606 Projects.org_archive, as top-level trees. This is the default.
2608 \"::* Archived Tasks\"
2609 Archive in the current file, under the top-level headline
2610 \"* Archived Tasks\".
2612 \"~/org/archive.org::\"
2613 Archive in file ~/org/archive.org (absolute path), as top-level trees.
2615 \"basement::** Finished Tasks\"
2616 Archive in file ./basement (relative path), as level 3 trees
2617 below the level 2 heading \"** Finished Tasks\".
2619 You may set this option on a per-file basis by adding to the buffer a
2620 line like
2622 #+ARCHIVE: basement::** Finished Tasks
2624 You may also define it locally for a subtree by setting an ARCHIVE property
2625 in the entry. If such a property is found in an entry, or anywhere up
2626 the hierarchy, it will be used."
2627 :group 'org-archive
2628 :type 'string)
2630 (defcustom org-archive-tag "ARCHIVE"
2631 "The tag that marks a subtree as archived.
2632 An archived subtree does not open during visibility cycling, and does
2633 not contribute to the agenda listings.
2634 After changing this, font-lock must be restarted in the relevant buffers to
2635 get the proper fontification."
2636 :group 'org-archive
2637 :group 'org-keywords
2638 :type 'string)
2640 (defcustom org-agenda-skip-archived-trees t
2641 "Non-nil means, the agenda will skip any items located in archived trees.
2642 An archived tree is a tree marked with the tag ARCHIVE. The use of this
2643 variable is no longer recommended, you should leave it at the value t.
2644 Instead, use the key `v' to cycle the archives-mode in the agenda."
2645 :group 'org-archive
2646 :group 'org-agenda-skip
2647 :type 'boolean)
2649 (defcustom org-cycle-open-archived-trees nil
2650 "Non-nil means, `org-cycle' will open archived trees.
2651 An archived tree is a tree marked with the tag ARCHIVE.
2652 When nil, archived trees will stay folded. You can still open them with
2653 normal outline commands like `show-all', but not with the cycling commands."
2654 :group 'org-archive
2655 :group 'org-cycle
2656 :type 'boolean)
2658 (defcustom org-sparse-tree-open-archived-trees nil
2659 "Non-nil means sparse tree construction shows matches in archived trees.
2660 When nil, matches in these trees are highlighted, but the trees are kept in
2661 collapsed state."
2662 :group 'org-archive
2663 :group 'org-sparse-trees
2664 :type 'boolean)
2666 (defun org-cycle-hide-archived-subtrees (state)
2667 "Re-hide all archived subtrees after a visibility state change."
2668 (when (and (not org-cycle-open-archived-trees)
2669 (not (memq state '(overview folded))))
2670 (save-excursion
2671 (let* ((globalp (memq state '(contents all)))
2672 (beg (if globalp (point-min) (point)))
2673 (end (if globalp (point-max) (org-end-of-subtree t))))
2674 (org-hide-archived-subtrees beg end)
2675 (goto-char beg)
2676 (if (looking-at (concat ".*:" org-archive-tag ":"))
2677 (message "%s" (substitute-command-keys
2678 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
2680 (defun org-force-cycle-archived ()
2681 "Cycle subtree even if it is archived."
2682 (interactive)
2683 (setq this-command 'org-cycle)
2684 (let ((org-cycle-open-archived-trees t))
2685 (call-interactively 'org-cycle)))
2687 (defun org-hide-archived-subtrees (beg end)
2688 "Re-hide all archived subtrees after a visibility state change."
2689 (save-excursion
2690 (let* ((re (concat ":" org-archive-tag ":")))
2691 (goto-char beg)
2692 (while (re-search-forward re end t)
2693 (and (org-on-heading-p) (hide-subtree))
2694 (org-end-of-subtree t)))))
2696 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
2698 (eval-and-compile
2699 (org-autoload "org-archive"
2700 '(org-add-archive-files org-archive-subtree
2701 org-archive-to-archive-sibling org-toggle-archive-tag)))
2703 ;; Autoload Column View Code
2705 (declare-function org-columns-number-to-string "org-colview")
2706 (declare-function org-columns-get-format-and-top-level "org-colview")
2707 (declare-function org-columns-compute "org-colview")
2709 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
2710 '(org-columns-number-to-string org-columns-get-format-and-top-level
2711 org-columns-compute org-agenda-columns org-columns-remove-overlays
2712 org-columns org-insert-columns-dblock org-dblock-write:columnview))
2714 ;; Autoload ID code
2716 (org-autoload "org-id"
2717 '(org-id-get-create org-id-new org-id-copy org-id-get
2718 org-id-get-with-outline-path-completion
2719 org-id-get-with-outline-drilling
2720 org-id-goto org-id-find))
2722 ;;; Variables for pre-computed regular expressions, all buffer local
2724 (defvar org-drawer-regexp nil
2725 "Matches first line of a hidden block.")
2726 (make-variable-buffer-local 'org-drawer-regexp)
2727 (defvar org-todo-regexp nil
2728 "Matches any of the TODO state keywords.")
2729 (make-variable-buffer-local 'org-todo-regexp)
2730 (defvar org-not-done-regexp nil
2731 "Matches any of the TODO state keywords except the last one.")
2732 (make-variable-buffer-local 'org-not-done-regexp)
2733 (defvar org-todo-line-regexp nil
2734 "Matches a headline and puts TODO state into group 2 if present.")
2735 (make-variable-buffer-local 'org-todo-line-regexp)
2736 (defvar org-complex-heading-regexp nil
2737 "Matches a headline and puts everything into groups:
2738 group 1: the stars
2739 group 2: The todo keyword, maybe
2740 group 3: Priority cookie
2741 group 4: True headline
2742 group 5: Tags")
2743 (make-variable-buffer-local 'org-complex-heading-regexp)
2744 (defvar org-todo-line-tags-regexp nil
2745 "Matches a headline and puts TODO state into group 2 if present.
2746 Also put tags into group 4 if tags are present.")
2747 (make-variable-buffer-local 'org-todo-line-tags-regexp)
2748 (defvar org-nl-done-regexp nil
2749 "Matches newline followed by a headline with the DONE keyword.")
2750 (make-variable-buffer-local 'org-nl-done-regexp)
2751 (defvar org-looking-at-done-regexp nil
2752 "Matches the DONE keyword a point.")
2753 (make-variable-buffer-local 'org-looking-at-done-regexp)
2754 (defvar org-ds-keyword-length 12
2755 "Maximum length of the Deadline and SCHEDULED keywords.")
2756 (make-variable-buffer-local 'org-ds-keyword-length)
2757 (defvar org-deadline-regexp nil
2758 "Matches the DEADLINE keyword.")
2759 (make-variable-buffer-local 'org-deadline-regexp)
2760 (defvar org-deadline-time-regexp nil
2761 "Matches the DEADLINE keyword together with a time stamp.")
2762 (make-variable-buffer-local 'org-deadline-time-regexp)
2763 (defvar org-deadline-line-regexp nil
2764 "Matches the DEADLINE keyword and the rest of the line.")
2765 (make-variable-buffer-local 'org-deadline-line-regexp)
2766 (defvar org-scheduled-regexp nil
2767 "Matches the SCHEDULED keyword.")
2768 (make-variable-buffer-local 'org-scheduled-regexp)
2769 (defvar org-scheduled-time-regexp nil
2770 "Matches the SCHEDULED keyword together with a time stamp.")
2771 (make-variable-buffer-local 'org-scheduled-time-regexp)
2772 (defvar org-closed-time-regexp nil
2773 "Matches the CLOSED keyword together with a time stamp.")
2774 (make-variable-buffer-local 'org-closed-time-regexp)
2776 (defvar org-keyword-time-regexp nil
2777 "Matches any of the 4 keywords, together with the time stamp.")
2778 (make-variable-buffer-local 'org-keyword-time-regexp)
2779 (defvar org-keyword-time-not-clock-regexp nil
2780 "Matches any of the 3 keywords, together with the time stamp.")
2781 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
2782 (defvar org-maybe-keyword-time-regexp nil
2783 "Matches a timestamp, possibly preceeded by a keyword.")
2784 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
2785 (defvar org-planning-or-clock-line-re nil
2786 "Matches a line with planning or clock info.")
2787 (make-variable-buffer-local 'org-planning-or-clock-line-re)
2789 (defconst org-plain-time-of-day-regexp
2790 (concat
2791 "\\(\\<[012]?[0-9]"
2792 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2793 "\\(--?"
2794 "\\(\\<[012]?[0-9]"
2795 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2796 "\\)?")
2797 "Regular expression to match a plain time or time range.
2798 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2799 groups carry important information:
2800 0 the full match
2801 1 the first time, range or not
2802 8 the second time, if it is a range.")
2804 (defconst org-plain-time-extension-regexp
2805 (concat
2806 "\\(\\<[012]?[0-9]"
2807 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2808 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
2809 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
2810 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2811 groups carry important information:
2812 0 the full match
2813 7 hours of duration
2814 9 minutes of duration")
2816 (defconst org-stamp-time-of-day-regexp
2817 (concat
2818 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
2819 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
2820 "\\(--?"
2821 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
2822 "Regular expression to match a timestamp time or time range.
2823 After a match, the following groups carry important information:
2824 0 the full match
2825 1 date plus weekday, for backreferencing to make sure both times on same day
2826 2 the first time, range or not
2827 4 the second time, if it is a range.")
2829 (defconst org-startup-options
2830 '(("fold" org-startup-folded t)
2831 ("overview" org-startup-folded t)
2832 ("nofold" org-startup-folded nil)
2833 ("showall" org-startup-folded nil)
2834 ("content" org-startup-folded content)
2835 ("hidestars" org-hide-leading-stars t)
2836 ("showstars" org-hide-leading-stars nil)
2837 ("odd" org-odd-levels-only t)
2838 ("oddeven" org-odd-levels-only nil)
2839 ("align" org-startup-align-all-tables t)
2840 ("noalign" org-startup-align-all-tables nil)
2841 ("customtime" org-display-custom-times t)
2842 ("logdone" org-log-done time)
2843 ("lognotedone" org-log-done note)
2844 ("nologdone" org-log-done nil)
2845 ("lognoteclock-out" org-log-note-clock-out t)
2846 ("nolognoteclock-out" org-log-note-clock-out nil)
2847 ("logrepeat" org-log-repeat state)
2848 ("lognoterepeat" org-log-repeat note)
2849 ("nologrepeat" org-log-repeat nil)
2850 ("constcgs" constants-unit-system cgs)
2851 ("constSI" constants-unit-system SI))
2852 "Variable associated with STARTUP options for org-mode.
2853 Each element is a list of three items: The startup options as written
2854 in the #+STARTUP line, the corresponding variable, and the value to
2855 set this variable to if the option is found. An optional forth element PUSH
2856 means to push this value onto the list in the variable.")
2858 (defun org-set-regexps-and-options ()
2859 "Precompute regular expressions for current buffer."
2860 (when (org-mode-p)
2861 (org-set-local 'org-todo-kwd-alist nil)
2862 (org-set-local 'org-todo-key-alist nil)
2863 (org-set-local 'org-todo-key-trigger nil)
2864 (org-set-local 'org-todo-keywords-1 nil)
2865 (org-set-local 'org-done-keywords nil)
2866 (org-set-local 'org-todo-heads nil)
2867 (org-set-local 'org-todo-sets nil)
2868 (org-set-local 'org-todo-log-states nil)
2869 (org-set-local 'org-file-properties nil)
2870 (org-set-local 'org-file-tags nil)
2871 (let ((re (org-make-options-regexp
2872 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
2873 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
2874 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")))
2875 (splitre "[ \t]+")
2876 kwds kws0 kwsa key log value cat arch tags const links hw dws
2877 tail sep kws1 prio props ftags drawers
2878 ext-setup-or-nil setup-contents (start 0))
2879 (save-excursion
2880 (save-restriction
2881 (widen)
2882 (goto-char (point-min))
2883 (while (or (and ext-setup-or-nil
2884 (string-match re ext-setup-or-nil start)
2885 (setq start (match-end 0)))
2886 (and (setq ext-setup-or-nil nil start 0)
2887 (re-search-forward re nil t)))
2888 (setq key (upcase (match-string 1 ext-setup-or-nil))
2889 value (org-match-string-no-properties 2 ext-setup-or-nil))
2890 (cond
2891 ((equal key "CATEGORY")
2892 (if (string-match "[ \t]+$" value)
2893 (setq value (replace-match "" t t value)))
2894 (setq cat value))
2895 ((member key '("SEQ_TODO" "TODO"))
2896 (push (cons 'sequence (org-split-string value splitre)) kwds))
2897 ((equal key "TYP_TODO")
2898 (push (cons 'type (org-split-string value splitre)) kwds))
2899 ((equal key "TAGS")
2900 (setq tags (append tags (org-split-string value splitre))))
2901 ((equal key "COLUMNS")
2902 (org-set-local 'org-columns-default-format value))
2903 ((equal key "LINK")
2904 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
2905 (push (cons (match-string 1 value)
2906 (org-trim (match-string 2 value)))
2907 links)))
2908 ((equal key "PRIORITIES")
2909 (setq prio (org-split-string value " +")))
2910 ((equal key "PROPERTY")
2911 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
2912 (push (cons (match-string 1 value) (match-string 2 value))
2913 props)))
2914 ((equal key "FILETAGS")
2915 (when (string-match "\\S-" value)
2916 (setq ftags
2917 (append
2918 ftags
2919 (apply 'append
2920 (mapcar (lambda (x) (org-split-string x ":"))
2921 (org-split-string value)))))))
2922 ((equal key "DRAWERS")
2923 (setq drawers (org-split-string value splitre)))
2924 ((equal key "CONSTANTS")
2925 (setq const (append const (org-split-string value splitre))))
2926 ((equal key "STARTUP")
2927 (let ((opts (org-split-string value splitre))
2928 l var val)
2929 (while (setq l (pop opts))
2930 (when (setq l (assoc l org-startup-options))
2931 (setq var (nth 1 l) val (nth 2 l))
2932 (if (not (nth 3 l))
2933 (set (make-local-variable var) val)
2934 (if (not (listp (symbol-value var)))
2935 (set (make-local-variable var) nil))
2936 (set (make-local-variable var) (symbol-value var))
2937 (add-to-list var val))))))
2938 ((equal key "ARCHIVE")
2939 (string-match " *$" value)
2940 (setq arch (replace-match "" t t value))
2941 (remove-text-properties 0 (length arch)
2942 '(face t fontified t) arch))
2943 ((equal key "SETUPFILE")
2944 (setq setup-contents (org-file-contents
2945 (expand-file-name
2946 (org-remove-double-quotes value))
2947 'noerror))
2948 (if (not ext-setup-or-nil)
2949 (setq ext-setup-or-nil setup-contents start 0)
2950 (setq ext-setup-or-nil
2951 (concat (substring ext-setup-or-nil 0 start)
2952 "\n" setup-contents "\n"
2953 (substring ext-setup-or-nil start)))))
2954 ))))
2955 (when cat
2956 (org-set-local 'org-category (intern cat))
2957 (push (cons "CATEGORY" cat) props))
2958 (when prio
2959 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
2960 (setq prio (mapcar 'string-to-char prio))
2961 (org-set-local 'org-highest-priority (nth 0 prio))
2962 (org-set-local 'org-lowest-priority (nth 1 prio))
2963 (org-set-local 'org-default-priority (nth 2 prio)))
2964 (and props (org-set-local 'org-file-properties (nreverse props)))
2965 (and ftags (org-set-local 'org-file-tags ftags))
2966 (and drawers (org-set-local 'org-drawers drawers))
2967 (and arch (org-set-local 'org-archive-location arch))
2968 (and links (setq org-link-abbrev-alist-local (nreverse links)))
2969 ;; Process the TODO keywords
2970 (unless kwds
2971 ;; Use the global values as if they had been given locally.
2972 (setq kwds (default-value 'org-todo-keywords))
2973 (if (stringp (car kwds))
2974 (setq kwds (list (cons org-todo-interpretation
2975 (default-value 'org-todo-keywords)))))
2976 (setq kwds (reverse kwds)))
2977 (setq kwds (nreverse kwds))
2978 (let (inter kws kw)
2979 (while (setq kws (pop kwds))
2980 (setq inter (pop kws) sep (member "|" kws)
2981 kws0 (delete "|" (copy-sequence kws))
2982 kwsa nil
2983 kws1 (mapcar
2984 (lambda (x)
2985 ;; 1 2
2986 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
2987 (progn
2988 (setq kw (match-string 1 x)
2989 key (and (match-end 2) (match-string 2 x))
2990 log (org-extract-log-state-settings x))
2991 (push (cons kw (and key (string-to-char key))) kwsa)
2992 (and log (push log org-todo-log-states))
2994 (error "Invalid TODO keyword %s" x)))
2995 kws0)
2996 kwsa (if kwsa (append '((:startgroup))
2997 (nreverse kwsa)
2998 '((:endgroup))))
2999 hw (car kws1)
3000 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3001 tail (list inter hw (car dws) (org-last dws)))
3002 (add-to-list 'org-todo-heads hw 'append)
3003 (push kws1 org-todo-sets)
3004 (setq org-done-keywords (append org-done-keywords dws nil))
3005 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3006 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3007 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3008 (setq org-todo-sets (nreverse org-todo-sets)
3009 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3010 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3011 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3012 ;; Process the constants
3013 (when const
3014 (let (e cst)
3015 (while (setq e (pop const))
3016 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3017 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3018 (setq org-table-formula-constants-local cst)))
3020 ;; Process the tags.
3021 (when tags
3022 (let (e tgs)
3023 (while (setq e (pop tags))
3024 (cond
3025 ((equal e "{") (push '(:startgroup) tgs))
3026 ((equal e "}") (push '(:endgroup) tgs))
3027 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3028 (push (cons (match-string 1 e)
3029 (string-to-char (match-string 2 e)))
3030 tgs))
3031 (t (push (list e) tgs))))
3032 (org-set-local 'org-tag-alist nil)
3033 (while (setq e (pop tgs))
3034 (or (and (stringp (car e))
3035 (assoc (car e) org-tag-alist))
3036 (push e org-tag-alist)))))
3038 ;; Compute the regular expressions and other local variables
3039 (if (not org-done-keywords)
3040 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
3041 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3042 (length org-scheduled-string)
3043 (length org-clock-string)
3044 (length org-closed-string)))
3045 org-drawer-regexp
3046 (concat "^[ \t]*:\\("
3047 (mapconcat 'regexp-quote org-drawers "\\|")
3048 "\\):[ \t]*$")
3049 org-not-done-keywords
3050 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3051 org-todo-regexp
3052 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3053 "\\|") "\\)\\>")
3054 org-not-done-regexp
3055 (concat "\\<\\("
3056 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3057 "\\)\\>")
3058 org-todo-line-regexp
3059 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3060 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3061 "\\)\\>\\)?[ \t]*\\(.*\\)")
3062 org-complex-heading-regexp
3063 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
3064 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3065 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3066 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3067 org-nl-done-regexp
3068 (concat "\n\\*+[ \t]+"
3069 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3070 "\\)" "\\>")
3071 org-todo-line-tags-regexp
3072 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3073 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3074 (org-re
3075 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3076 org-looking-at-done-regexp
3077 (concat "^" "\\(?:"
3078 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3079 "\\>")
3080 org-deadline-regexp (concat "\\<" org-deadline-string)
3081 org-deadline-time-regexp
3082 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3083 org-deadline-line-regexp
3084 (concat "\\<\\(" org-deadline-string "\\).*")
3085 org-scheduled-regexp
3086 (concat "\\<" org-scheduled-string)
3087 org-scheduled-time-regexp
3088 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3089 org-closed-time-regexp
3090 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3091 org-keyword-time-regexp
3092 (concat "\\<\\(" org-scheduled-string
3093 "\\|" org-deadline-string
3094 "\\|" org-closed-string
3095 "\\|" org-clock-string "\\)"
3096 " *[[<]\\([^]>]+\\)[]>]")
3097 org-keyword-time-not-clock-regexp
3098 (concat "\\<\\(" org-scheduled-string
3099 "\\|" org-deadline-string
3100 "\\|" org-closed-string
3101 "\\)"
3102 " *[[<]\\([^]>]+\\)[]>]")
3103 org-maybe-keyword-time-regexp
3104 (concat "\\(\\<\\(" org-scheduled-string
3105 "\\|" org-deadline-string
3106 "\\|" org-closed-string
3107 "\\|" org-clock-string "\\)\\)?"
3108 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3109 org-planning-or-clock-line-re
3110 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3111 "\\|" org-deadline-string
3112 "\\|" org-closed-string "\\|" org-clock-string
3113 "\\)\\>\\)")
3115 (org-compute-latex-and-specials-regexp)
3116 (org-set-font-lock-defaults))))
3118 (defun org-file-contents (file &optional noerror)
3119 "Return the contents of FILE, as a string."
3120 (if (or (not file)
3121 (not (file-readable-p file)))
3122 (if noerror
3123 (progn
3124 (message "Cannot read file %s" file)
3125 (ding) (sit-for 2)
3127 (error "Cannot read file %s" file))
3128 (with-temp-buffer
3129 (insert-file-contents file)
3130 (buffer-string))))
3132 (defun org-extract-log-state-settings (x)
3133 "Extract the log state setting from a TODO keyword string.
3134 This will extract info from a string like \"WAIT(w@/!)\"."
3135 (let (kw key log1 log2)
3136 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3137 (setq kw (match-string 1 x)
3138 key (and (match-end 2) (match-string 2 x))
3139 log1 (and (match-end 3) (match-string 3 x))
3140 log2 (and (match-end 4) (match-string 4 x)))
3141 (and (or log1 log2)
3142 (list kw
3143 (and log1 (if (equal log1 "!") 'time 'note))
3144 (and log2 (if (equal log2 "!") 'time 'note)))))))
3146 (defun org-remove-keyword-keys (list)
3147 "Remove a pair of parenthesis at the end of each string in LIST."
3148 (mapcar (lambda (x)
3149 (if (string-match "(.*)$" x)
3150 (substring x 0 (match-beginning 0))
3152 list))
3154 ;; FIXME: this could be done much better, using second characters etc.
3155 (defun org-assign-fast-keys (alist)
3156 "Assign fast keys to a keyword-key alist.
3157 Respect keys that are already there."
3158 (let (new e k c c1 c2 (char ?a))
3159 (while (setq e (pop alist))
3160 (cond
3161 ((equal e '(:startgroup)) (push e new))
3162 ((equal e '(:endgroup)) (push e new))
3164 (setq k (car e) c2 nil)
3165 (if (cdr e)
3166 (setq c (cdr e))
3167 ;; automatically assign a character.
3168 (setq c1 (string-to-char
3169 (downcase (substring
3170 k (if (= (string-to-char k) ?@) 1 0)))))
3171 (if (or (rassoc c1 new) (rassoc c1 alist))
3172 (while (or (rassoc char new) (rassoc char alist))
3173 (setq char (1+ char)))
3174 (setq c2 c1))
3175 (setq c (or c2 char)))
3176 (push (cons k c) new))))
3177 (nreverse new)))
3179 ;;; Some variables used in various places
3181 (defvar org-window-configuration nil
3182 "Used in various places to store a window configuration.")
3183 (defvar org-finish-function nil
3184 "Function to be called when `C-c C-c' is used.
3185 This is for getting out of special buffers like remember.")
3188 ;; FIXME: Occasionally check by commenting these, to make sure
3189 ;; no other functions uses these, forgetting to let-bind them.
3190 (defvar entry)
3191 (defvar state)
3192 (defvar last-state)
3193 (defvar date)
3194 (defvar description)
3196 ;; Defined somewhere in this file, but used before definition.
3197 (defvar org-html-entities)
3198 (defvar org-struct-menu)
3199 (defvar org-org-menu)
3200 (defvar org-tbl-menu)
3201 (defvar org-agenda-keymap)
3203 ;;;; Define the Org-mode
3205 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3206 (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."))
3209 ;; We use a before-change function to check if a table might need
3210 ;; an update.
3211 (defvar org-table-may-need-update t
3212 "Indicates that a table might need an update.
3213 This variable is set by `org-before-change-function'.
3214 `org-table-align' sets it back to nil.")
3215 (defun org-before-change-function (beg end)
3216 "Every change indicates that a table might need an update."
3217 (setq org-table-may-need-update t))
3218 (defvar org-mode-map)
3219 (defvar org-mode-hook nil)
3220 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3221 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3222 (defvar org-table-buffer-is-an nil)
3223 (defconst org-outline-regexp "\\*+ ")
3225 ;;;###autoload
3226 (define-derived-mode org-mode outline-mode "Org"
3227 "Outline-based notes management and organizer, alias
3228 \"Carsten's outline-mode for keeping track of everything.\"
3230 Org-mode develops organizational tasks around a NOTES file which
3231 contains information about projects as plain text. Org-mode is
3232 implemented on top of outline-mode, which is ideal to keep the content
3233 of large files well structured. It supports ToDo items, deadlines and
3234 time stamps, which magically appear in the diary listing of the Emacs
3235 calendar. Tables are easily created with a built-in table editor.
3236 Plain text URL-like links connect to websites, emails (VM), Usenet
3237 messages (Gnus), BBDB entries, and any files related to the project.
3238 For printing and sharing of notes, an Org-mode file (or a part of it)
3239 can be exported as a structured ASCII or HTML file.
3241 The following commands are available:
3243 \\{org-mode-map}"
3245 ;; Get rid of Outline menus, they are not needed
3246 ;; Need to do this here because define-derived-mode sets up
3247 ;; the keymap so late. Still, it is a waste to call this each time
3248 ;; we switch another buffer into org-mode.
3249 (if (featurep 'xemacs)
3250 (when (boundp 'outline-mode-menu-heading)
3251 ;; Assume this is Greg's port, it used easymenu
3252 (easy-menu-remove outline-mode-menu-heading)
3253 (easy-menu-remove outline-mode-menu-show)
3254 (easy-menu-remove outline-mode-menu-hide))
3255 (define-key org-mode-map [menu-bar headings] 'undefined)
3256 (define-key org-mode-map [menu-bar hide] 'undefined)
3257 (define-key org-mode-map [menu-bar show] 'undefined))
3259 (org-load-modules-maybe)
3260 (easy-menu-add org-org-menu)
3261 (easy-menu-add org-tbl-menu)
3262 (org-install-agenda-files-menu)
3263 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3264 (org-add-to-invisibility-spec '(org-cwidth))
3265 (when (featurep 'xemacs)
3266 (org-set-local 'line-move-ignore-invisible t))
3267 (org-set-local 'outline-regexp org-outline-regexp)
3268 (org-set-local 'outline-level 'org-outline-level)
3269 (when (and org-ellipsis
3270 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3271 (fboundp 'make-glyph-code))
3272 (unless org-display-table
3273 (setq org-display-table (make-display-table)))
3274 (set-display-table-slot
3275 org-display-table 4
3276 (vconcat (mapcar
3277 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3278 org-ellipsis)))
3279 (if (stringp org-ellipsis) org-ellipsis "..."))))
3280 (setq buffer-display-table org-display-table))
3281 (org-set-regexps-and-options)
3282 ;; Calc embedded
3283 (org-set-local 'calc-embedded-open-mode "# ")
3284 (modify-syntax-entry ?# "<")
3285 (modify-syntax-entry ?@ "w")
3286 (if org-startup-truncated (setq truncate-lines t))
3287 (org-set-local 'font-lock-unfontify-region-function
3288 'org-unfontify-region)
3289 ;; Activate before-change-function
3290 (org-set-local 'org-table-may-need-update t)
3291 (org-add-hook 'before-change-functions 'org-before-change-function nil
3292 'local)
3293 ;; Check for running clock before killing a buffer
3294 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3295 ;; Paragraphs and auto-filling
3296 (org-set-autofill-regexps)
3297 (setq indent-line-function 'org-indent-line-function)
3298 (org-update-radio-target-regexp)
3300 ;; Comment characters
3301 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3302 (org-set-local 'comment-padding " ")
3304 ;; Align options lines
3305 (org-set-local
3306 'align-mode-rules-list
3307 '((org-in-buffer-settings
3308 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3309 (modes . '(org-mode)))))
3311 ;; Imenu
3312 (org-set-local 'imenu-create-index-function
3313 'org-imenu-get-tree)
3315 ;; Make isearch reveal context
3316 (if (or (featurep 'xemacs)
3317 (not (boundp 'outline-isearch-open-invisible-function)))
3318 ;; Emacs 21 and XEmacs make use of the hook
3319 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3320 ;; Emacs 22 deals with this through a special variable
3321 (org-set-local 'outline-isearch-open-invisible-function
3322 (lambda (&rest ignore) (org-show-context 'isearch))))
3324 ;; If empty file that did not turn on org-mode automatically, make it to.
3325 (if (and org-insert-mode-line-in-empty-file
3326 (interactive-p)
3327 (= (point-min) (point-max)))
3328 (insert "# -*- mode: org -*-\n\n"))
3330 (unless org-inhibit-startup
3331 (when org-startup-align-all-tables
3332 (let ((bmp (buffer-modified-p)))
3333 (org-table-map-tables 'org-table-align)
3334 (set-buffer-modified-p bmp)))
3335 (org-set-startup-visibility)))
3337 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3339 (defun org-current-time ()
3340 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3341 (if (> (car org-time-stamp-rounding-minutes) 1)
3342 (let ((r (car org-time-stamp-rounding-minutes))
3343 (time (decode-time)))
3344 (apply 'encode-time
3345 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3346 (nthcdr 2 time))))
3347 (current-time)))
3349 ;;;; Font-Lock stuff, including the activators
3351 (defvar org-mouse-map (make-sparse-keymap))
3352 (org-defkey org-mouse-map
3353 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3354 (org-defkey org-mouse-map
3355 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3356 (when org-mouse-1-follows-link
3357 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3358 (when org-tab-follows-link
3359 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3360 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3361 (when org-return-follows-link
3362 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
3363 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
3365 (require 'font-lock)
3367 (defconst org-non-link-chars "]\t\n\r<>")
3368 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3369 "shell" "elisp"))
3370 (defvar org-link-types-re nil
3371 "Matches a link that has a url-like prefix like \"http:\"")
3372 (defvar org-link-re-with-space nil
3373 "Matches a link with spaces, optional angular brackets around it.")
3374 (defvar org-link-re-with-space2 nil
3375 "Matches a link with spaces, optional angular brackets around it.")
3376 (defvar org-angle-link-re nil
3377 "Matches link with angular brackets, spaces are allowed.")
3378 (defvar org-plain-link-re nil
3379 "Matches plain link, without spaces.")
3380 (defvar org-bracket-link-regexp nil
3381 "Matches a link in double brackets.")
3382 (defvar org-bracket-link-analytic-regexp nil
3383 "Regular expression used to analyze links.
3384 Here is what the match groups contain after a match:
3385 1: http:
3386 2: http
3387 3: path
3388 4: [desc]
3389 5: desc")
3390 (defvar org-any-link-re nil
3391 "Regular expression matching any link.")
3393 (defun org-make-link-regexps ()
3394 "Update the link regular expressions.
3395 This should be called after the variable `org-link-types' has changed."
3396 (setq org-link-types-re
3397 (concat
3398 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3399 org-link-re-with-space
3400 (concat
3401 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3402 "\\([^" org-non-link-chars " ]"
3403 "[^" org-non-link-chars "]*"
3404 "[^" org-non-link-chars " ]\\)>?")
3405 org-link-re-with-space2
3406 (concat
3407 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3408 "\\([^" org-non-link-chars " ]"
3409 "[^]\t\n\r]*"
3410 "[^" org-non-link-chars " ]\\)>?")
3411 org-angle-link-re
3412 (concat
3413 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3414 "\\([^" org-non-link-chars " ]"
3415 "[^" org-non-link-chars "]*"
3416 "\\)>")
3417 org-plain-link-re
3418 (concat
3419 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3420 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3421 org-bracket-link-regexp
3422 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3423 org-bracket-link-analytic-regexp
3424 (concat
3425 "\\[\\["
3426 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3427 "\\([^]]+\\)"
3428 "\\]"
3429 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3430 "\\]")
3431 org-any-link-re
3432 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3433 org-angle-link-re "\\)\\|\\("
3434 org-plain-link-re "\\)")))
3436 (org-make-link-regexps)
3438 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
3439 "Regular expression for fast time stamp matching.")
3440 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
3441 "Regular expression for fast time stamp matching.")
3442 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3443 "Regular expression matching time strings for analysis.
3444 This one does not require the space after the date, so it can be used
3445 on a string that terminates immediately after the date.")
3446 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3447 "Regular expression matching time strings for analysis.")
3448 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
3449 "Regular expression matching time stamps, with groups.")
3450 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
3451 "Regular expression matching time stamps (also [..]), with groups.")
3452 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3453 "Regular expression matching a time stamp range.")
3454 (defconst org-tr-regexp-both
3455 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3456 "Regular expression matching a time stamp range.")
3457 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3458 org-ts-regexp "\\)?")
3459 "Regular expression matching a time stamp or time stamp range.")
3460 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3461 org-ts-regexp-both "\\)?")
3462 "Regular expression matching a time stamp or time stamp range.
3463 The time stamps may be either active or inactive.")
3465 (defvar org-emph-face nil)
3467 (defun org-do-emphasis-faces (limit)
3468 "Run through the buffer and add overlays to links."
3469 (let (rtn)
3470 (while (and (not rtn) (re-search-forward org-emph-re limit t))
3471 (if (not (= (char-after (match-beginning 3))
3472 (char-after (match-beginning 4))))
3473 (progn
3474 (setq rtn t)
3475 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3476 'face
3477 (nth 1 (assoc (match-string 3)
3478 org-emphasis-alist)))
3479 (add-text-properties (match-beginning 2) (match-end 2)
3480 '(font-lock-multiline t))
3481 (when org-hide-emphasis-markers
3482 (add-text-properties (match-end 4) (match-beginning 5)
3483 '(invisible org-link))
3484 (add-text-properties (match-beginning 3) (match-end 3)
3485 '(invisible org-link)))))
3486 (backward-char 1))
3487 rtn))
3489 (defun org-emphasize (&optional char)
3490 "Insert or change an emphasis, i.e. a font like bold or italic.
3491 If there is an active region, change that region to a new emphasis.
3492 If there is no region, just insert the marker characters and position
3493 the cursor between them.
3494 CHAR should be either the marker character, or the first character of the
3495 HTML tag associated with that emphasis. If CHAR is a space, the means
3496 to remove the emphasis of the selected region.
3497 If char is not given (for example in an interactive call) it
3498 will be prompted for."
3499 (interactive)
3500 (let ((eal org-emphasis-alist) e det
3501 (erc org-emphasis-regexp-components)
3502 (prompt "")
3503 (string "") beg end move tag c s)
3504 (if (org-region-active-p)
3505 (setq beg (region-beginning) end (region-end)
3506 string (buffer-substring beg end))
3507 (setq move t))
3509 (while (setq e (pop eal))
3510 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
3511 c (aref tag 0))
3512 (push (cons c (string-to-char (car e))) det)
3513 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
3514 (substring tag 1)))))
3515 (setq det (nreverse det))
3516 (unless char
3517 (message "%s" (concat "Emphasis marker or tag:" prompt))
3518 (setq char (read-char-exclusive)))
3519 (setq char (or (cdr (assoc char det)) char))
3520 (if (equal char ?\ )
3521 (setq s "" move nil)
3522 (unless (assoc (char-to-string char) org-emphasis-alist)
3523 (error "No such emphasis marker: \"%c\"" char))
3524 (setq s (char-to-string char)))
3525 (while (and (> (length string) 1)
3526 (equal (substring string 0 1) (substring string -1))
3527 (assoc (substring string 0 1) org-emphasis-alist))
3528 (setq string (substring string 1 -1)))
3529 (setq string (concat s string s))
3530 (if beg (delete-region beg end))
3531 (unless (or (bolp)
3532 (string-match (concat "[" (nth 0 erc) "\n]")
3533 (char-to-string (char-before (point)))))
3534 (insert " "))
3535 (unless (string-match (concat "[" (nth 1 erc) "\n]")
3536 (char-to-string (char-after (point))))
3537 (insert " ") (backward-char 1))
3538 (insert string)
3539 (and move (backward-char 1))))
3541 (defconst org-nonsticky-props
3542 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
3545 (defun org-activate-plain-links (limit)
3546 "Run through the buffer and add overlays to links."
3547 (catch 'exit
3548 (let (f)
3549 (while (re-search-forward org-plain-link-re limit t)
3550 (setq f (get-text-property (match-beginning 0) 'face))
3551 (if (or (eq f 'org-tag)
3552 (and (listp f) (memq 'org-tag f)))
3554 (add-text-properties (match-beginning 0) (match-end 0)
3555 (list 'mouse-face 'highlight
3556 'rear-nonsticky org-nonsticky-props
3557 'keymap org-mouse-map
3559 (throw 'exit t))))))
3561 (defun org-activate-code (limit)
3562 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
3563 (progn
3564 (remove-text-properties (match-beginning 0) (match-end 0)
3565 '(display t invisible t intangible t))
3566 t)))
3568 (defun org-activate-angle-links (limit)
3569 "Run through the buffer and add overlays to links."
3570 (if (re-search-forward org-angle-link-re limit t)
3571 (progn
3572 (add-text-properties (match-beginning 0) (match-end 0)
3573 (list 'mouse-face 'highlight
3574 'rear-nonsticky org-nonsticky-props
3575 'keymap org-mouse-map
3577 t)))
3579 (defun org-activate-bracket-links (limit)
3580 "Run through the buffer and add overlays to bracketed links."
3581 (if (re-search-forward org-bracket-link-regexp limit t)
3582 (let* ((help (concat "LINK: "
3583 (org-match-string-no-properties 1)))
3584 ;; FIXME: above we should remove the escapes.
3585 ;; but that requires another match, protecting match data,
3586 ;; a lot of overhead for font-lock.
3587 (ip (org-maybe-intangible
3588 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
3589 'keymap org-mouse-map 'mouse-face 'highlight
3590 'font-lock-multiline t 'help-echo help)))
3591 (vp (list 'rear-nonsticky org-nonsticky-props
3592 'keymap org-mouse-map 'mouse-face 'highlight
3593 ' font-lock-multiline t 'help-echo help)))
3594 ;; We need to remove the invisible property here. Table narrowing
3595 ;; may have made some of this invisible.
3596 (remove-text-properties (match-beginning 0) (match-end 0)
3597 '(invisible nil))
3598 (if (match-end 3)
3599 (progn
3600 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3601 (add-text-properties (match-beginning 3) (match-end 3) vp)
3602 (add-text-properties (match-end 3) (match-end 0) ip))
3603 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3604 (add-text-properties (match-beginning 1) (match-end 1) vp)
3605 (add-text-properties (match-end 1) (match-end 0) ip))
3606 t)))
3608 (defun org-activate-dates (limit)
3609 "Run through the buffer and add overlays to dates."
3610 (if (re-search-forward org-tsr-regexp-both limit t)
3611 (progn
3612 (add-text-properties (match-beginning 0) (match-end 0)
3613 (list 'mouse-face 'highlight
3614 'rear-nonsticky org-nonsticky-props
3615 'keymap org-mouse-map))
3616 (when org-display-custom-times
3617 (if (match-end 3)
3618 (org-display-custom-time (match-beginning 3) (match-end 3)))
3619 (org-display-custom-time (match-beginning 1) (match-end 1)))
3620 t)))
3622 (defvar org-target-link-regexp nil
3623 "Regular expression matching radio targets in plain text.")
3624 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3625 "Regular expression matching a link target.")
3626 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3627 "Regular expression matching a radio target.")
3628 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
3629 "Regular expression matching any target.")
3631 (defun org-activate-target-links (limit)
3632 "Run through the buffer and add overlays to target matches."
3633 (when org-target-link-regexp
3634 (let ((case-fold-search t))
3635 (if (re-search-forward org-target-link-regexp limit t)
3636 (progn
3637 (add-text-properties (match-beginning 0) (match-end 0)
3638 (list 'mouse-face 'highlight
3639 'rear-nonsticky org-nonsticky-props
3640 'keymap org-mouse-map
3641 'help-echo "Radio target link"
3642 'org-linked-text t))
3643 t)))))
3645 (defun org-update-radio-target-regexp ()
3646 "Find all radio targets in this file and update the regular expression."
3647 (interactive)
3648 (when (memq 'radio org-activate-links)
3649 (setq org-target-link-regexp
3650 (org-make-target-link-regexp (org-all-targets 'radio)))
3651 (org-restart-font-lock)))
3653 (defun org-hide-wide-columns (limit)
3654 (let (s e)
3655 (setq s (text-property-any (point) (or limit (point-max))
3656 'org-cwidth t))
3657 (when s
3658 (setq e (next-single-property-change s 'org-cwidth))
3659 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
3660 (goto-char e)
3661 t)))
3663 (defvar org-latex-and-specials-regexp nil
3664 "Regular expression for highlighting export special stuff.")
3665 (defvar org-match-substring-regexp)
3666 (defvar org-match-substring-with-braces-regexp)
3667 (defvar org-export-html-special-string-regexps)
3669 (defun org-compute-latex-and-specials-regexp ()
3670 "Compute regular expression for stuff treated specially by exporters."
3671 (if (not org-highlight-latex-fragments-and-specials)
3672 (org-set-local 'org-latex-and-specials-regexp nil)
3673 (require 'org-exp)
3674 (let*
3675 ((matchers (plist-get org-format-latex-options :matchers))
3676 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
3677 org-latex-regexps)))
3678 (options (org-combine-plists (org-default-export-plist)
3679 (org-infile-export-plist)))
3680 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
3681 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
3682 (org-export-with-TeX-macros (plist-get options :TeX-macros))
3683 (org-export-html-expand (plist-get options :expand-quoted-html))
3684 (org-export-with-special-strings (plist-get options :special-strings))
3685 (re-sub
3686 (cond
3687 ((equal org-export-with-sub-superscripts '{})
3688 (list org-match-substring-with-braces-regexp))
3689 (org-export-with-sub-superscripts
3690 (list org-match-substring-regexp))
3691 (t nil)))
3692 (re-latex
3693 (if org-export-with-LaTeX-fragments
3694 (mapcar (lambda (x) (nth 1 x)) latexs)))
3695 (re-macros
3696 (if org-export-with-TeX-macros
3697 (list (concat "\\\\"
3698 (regexp-opt
3699 (append (mapcar 'car org-html-entities)
3700 (if (boundp 'org-latex-entities)
3701 org-latex-entities nil))
3702 'words))) ; FIXME
3704 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
3705 (re-special (if org-export-with-special-strings
3706 (mapcar (lambda (x) (car x))
3707 org-export-html-special-string-regexps)))
3708 (re-rest
3709 (delq nil
3710 (list
3711 (if org-export-html-expand "@<[^>\n]+>")
3712 ))))
3713 (org-set-local
3714 'org-latex-and-specials-regexp
3715 (mapconcat 'identity (append re-latex re-sub re-macros re-special
3716 re-rest) "\\|")))))
3718 (defun org-do-latex-and-special-faces (limit)
3719 "Run through the buffer and add overlays to links."
3720 (when org-latex-and-specials-regexp
3721 (let (rtn d)
3722 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
3723 limit t))
3724 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
3725 'face))
3726 '(org-code org-verbatim underline)))
3727 (progn
3728 (setq rtn t
3729 d (cond ((member (char-after (1+ (match-beginning 0)))
3730 '(?_ ?^)) 1)
3731 (t 0)))
3732 (font-lock-prepend-text-property
3733 (+ d (match-beginning 0)) (match-end 0)
3734 'face 'org-latex-and-export-specials)
3735 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
3736 '(font-lock-multiline t)))))
3737 rtn)))
3739 (defun org-restart-font-lock ()
3740 "Restart font-lock-mode, to force refontification."
3741 (when (and (boundp 'font-lock-mode) font-lock-mode)
3742 (font-lock-mode -1)
3743 (font-lock-mode 1)))
3745 (defun org-all-targets (&optional radio)
3746 "Return a list of all targets in this file.
3747 With optional argument RADIO, only find radio targets."
3748 (let ((re (if radio org-radio-target-regexp org-target-regexp))
3749 rtn)
3750 (save-excursion
3751 (goto-char (point-min))
3752 (while (re-search-forward re nil t)
3753 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
3754 rtn)))
3756 (defun org-make-target-link-regexp (targets)
3757 "Make regular expression matching all strings in TARGETS.
3758 The regular expression finds the targets also if there is a line break
3759 between words."
3760 (and targets
3761 (concat
3762 "\\<\\("
3763 (mapconcat
3764 (lambda (x)
3765 (while (string-match " +" x)
3766 (setq x (replace-match "\\s-+" t t x)))
3768 targets
3769 "\\|")
3770 "\\)\\>")))
3772 (defun org-activate-tags (limit)
3773 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
3774 (progn
3775 (add-text-properties (match-beginning 1) (match-end 1)
3776 (list 'mouse-face 'highlight
3777 'rear-nonsticky org-nonsticky-props
3778 'keymap org-mouse-map))
3779 t)))
3781 (defun org-outline-level ()
3782 (save-excursion
3783 (looking-at outline-regexp)
3784 (if (match-beginning 1)
3785 (+ (org-get-string-indentation (match-string 1)) 1000)
3786 (1- (- (match-end 0) (match-beginning 0))))))
3788 (defvar org-font-lock-keywords nil)
3790 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
3791 "Regular expression matching a property line.")
3793 (defvar org-font-lock-hook nil
3794 "Functions to be called for special font lock stuff.")
3796 (defun org-font-lock-hook (limit)
3797 (run-hook-with-args 'org-font-lock-hook limit))
3799 (defun org-set-font-lock-defaults ()
3800 (let* ((em org-fontify-emphasized-text)
3801 (lk org-activate-links)
3802 (org-font-lock-extra-keywords
3803 (list
3804 ;; Call the hook
3805 '(org-font-lock-hook)
3806 ;; Headlines
3807 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
3808 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
3809 ;; Table lines
3810 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
3811 (1 'org-table t))
3812 ;; Table internals
3813 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
3814 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
3815 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
3816 ;; Drawers
3817 (list org-drawer-regexp '(0 'org-special-keyword t))
3818 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
3819 ;; Properties
3820 (list org-property-re
3821 '(1 'org-special-keyword t)
3822 '(3 'org-property-value t))
3823 (if org-format-transports-properties-p
3824 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
3825 ;; Links
3826 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
3827 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
3828 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
3829 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
3830 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
3831 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
3832 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
3833 '(org-hide-wide-columns (0 nil append))
3834 ;; TODO lines
3835 (list (concat "^\\*+[ \t]+" org-todo-regexp)
3836 '(1 (org-get-todo-face 1) t))
3837 ;; DONE
3838 (if org-fontify-done-headline
3839 (list (concat "^[*]+ +\\<\\("
3840 (mapconcat 'regexp-quote org-done-keywords "\\|")
3841 "\\)\\(.*\\)")
3842 '(2 'org-headline-done t))
3843 nil)
3844 ;; Priorities
3845 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
3846 ;; Special keywords
3847 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
3848 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
3849 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
3850 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
3851 ;; Emphasis
3852 (if em
3853 (if (featurep 'xemacs)
3854 '(org-do-emphasis-faces (0 nil append))
3855 '(org-do-emphasis-faces)))
3856 ;; Checkboxes
3857 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
3858 2 'bold prepend)
3859 (if org-provide-checkbox-statistics
3860 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
3861 (0 (org-get-checkbox-statistics-face) t)))
3862 ;; Description list items
3863 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
3864 2 'bold prepend)
3865 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
3866 '(1 'org-archived prepend))
3867 ;; Specials
3868 '(org-do-latex-and-special-faces)
3869 ;; Code
3870 '(org-activate-code (1 'org-code t))
3871 ;; COMMENT
3872 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
3873 "\\|" org-quote-string "\\)\\>")
3874 '(1 'org-special-keyword t))
3875 '("^#.*" (0 'font-lock-comment-face t))
3877 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
3878 ;; Now set the full font-lock-keywords
3879 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
3880 (org-set-local 'font-lock-defaults
3881 '(org-font-lock-keywords t nil nil backward-paragraph))
3882 (kill-local-variable 'font-lock-keywords) nil))
3884 (defvar org-m nil)
3885 (defvar org-l nil)
3886 (defvar org-f nil)
3887 (defun org-get-level-face (n)
3888 "Get the right face for match N in font-lock matching of healdines."
3889 (setq org-l (- (match-end 2) (match-beginning 1) 1))
3890 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
3891 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
3892 (cond
3893 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
3894 ((eq n 2) org-f)
3895 (t (if org-level-color-stars-only nil org-f))))
3897 (defun org-get-todo-face (kwd)
3898 "Get the right face for a TODO keyword KWD.
3899 If KWD is a number, get the corresponding match group."
3900 (if (numberp kwd) (setq kwd (match-string kwd)))
3901 (or (cdr (assoc kwd org-todo-keyword-faces))
3902 (and (member kwd org-done-keywords) 'org-done)
3903 'org-todo))
3905 (defun org-unfontify-region (beg end &optional maybe_loudly)
3906 "Remove fontification and activation overlays from links."
3907 (font-lock-default-unfontify-region beg end)
3908 (let* ((buffer-undo-list t)
3909 (inhibit-read-only t) (inhibit-point-motion-hooks t)
3910 (inhibit-modification-hooks t)
3911 deactivate-mark buffer-file-name buffer-file-truename)
3912 (remove-text-properties beg end
3913 '(mouse-face t keymap t org-linked-text t
3914 invisible t intangible t))))
3916 ;;;; Visibility cycling, including org-goto and indirect buffer
3918 ;;; Cycling
3920 (defvar org-cycle-global-status nil)
3921 (make-variable-buffer-local 'org-cycle-global-status)
3922 (defvar org-cycle-subtree-status nil)
3923 (make-variable-buffer-local 'org-cycle-subtree-status)
3925 ;;;###autoload
3926 (defun org-cycle (&optional arg)
3927 "Visibility cycling for Org-mode.
3929 - When this function is called with a prefix argument, rotate the entire
3930 buffer through 3 states (global cycling)
3931 1. OVERVIEW: Show only top-level headlines.
3932 2. CONTENTS: Show all headlines of all levels, but no body text.
3933 3. SHOW ALL: Show everything.
3934 When called with two C-u C-u prefixes, switch to the startup visibility,
3935 determined by the variable `org-startup-folded', and by any VISIBILITY
3936 properties in the buffer.
3937 When called with three C-u C-u C-u prefixed, show the entire buffer,
3938 including drawers.
3940 - When point is at the beginning of a headline, rotate the subtree started
3941 by this line through 3 different states (local cycling)
3942 1. FOLDED: Only the main headline is shown.
3943 2. CHILDREN: The main headline and the direct children are shown.
3944 From this state, you can move to one of the children
3945 and zoom in further.
3946 3. SUBTREE: Show the entire subtree, including body text.
3948 - When there is a numeric prefix, go up to a heading with level ARG, do
3949 a `show-subtree' and return to the previous cursor position. If ARG
3950 is negative, go up that many levels.
3952 - When point is not at the beginning of a headline, execute the global
3953 binding for TAB, which is re-indenting the line. See the option
3954 `org-cycle-emulate-tab' for details.
3956 - Special case: if point is at the beginning of the buffer and there is
3957 no headline in line 1, this function will act as if called with prefix arg.
3958 But only if also the variable `org-cycle-global-at-bob' is t."
3959 (interactive "P")
3960 (org-load-modules-maybe)
3961 (let* ((outline-regexp
3962 (if (and (org-mode-p) org-cycle-include-plain-lists)
3963 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
3964 outline-regexp))
3965 (bob-special (and org-cycle-global-at-bob (bobp)
3966 (not (looking-at outline-regexp))))
3967 (org-cycle-hook
3968 (if bob-special
3969 (delq 'org-optimize-window-after-visibility-change
3970 (copy-sequence org-cycle-hook))
3971 org-cycle-hook))
3972 (pos (point)))
3974 (if (or bob-special (equal arg '(4)))
3975 ;; special case: use global cycling
3976 (setq arg t))
3978 (cond
3980 ((equal arg '(16))
3981 (org-set-startup-visibility)
3982 (message "Startup visibility, plus VISIBILITY properties"))
3984 ((equal arg '(64))
3985 (show-all)
3986 (message "Entire buffer visible, including drawers"))
3988 ((org-at-table-p 'any)
3989 ;; Enter the table or move to the next field in the table
3990 (or (org-table-recognize-table.el)
3991 (progn
3992 (if arg (org-table-edit-field t)
3993 (org-table-justify-field-maybe)
3994 (call-interactively 'org-table-next-field)))))
3996 ((eq arg t) ;; Global cycling
3998 (cond
3999 ((and (eq last-command this-command)
4000 (eq org-cycle-global-status 'overview))
4001 ;; We just created the overview - now do table of contents
4002 ;; This can be slow in very large buffers, so indicate action
4003 (message "CONTENTS...")
4004 (org-content)
4005 (message "CONTENTS...done")
4006 (setq org-cycle-global-status 'contents)
4007 (run-hook-with-args 'org-cycle-hook 'contents))
4009 ((and (eq last-command this-command)
4010 (eq org-cycle-global-status 'contents))
4011 ;; We just showed the table of contents - now show everything
4012 (show-all)
4013 (message "SHOW ALL")
4014 (setq org-cycle-global-status 'all)
4015 (run-hook-with-args 'org-cycle-hook 'all))
4018 ;; Default action: go to overview
4019 (org-overview)
4020 (message "OVERVIEW")
4021 (setq org-cycle-global-status 'overview)
4022 (run-hook-with-args 'org-cycle-hook 'overview))))
4024 ((and org-drawers org-drawer-regexp
4025 (save-excursion
4026 (beginning-of-line 1)
4027 (looking-at org-drawer-regexp)))
4028 ;; Toggle block visibility
4029 (org-flag-drawer
4030 (not (get-char-property (match-end 0) 'invisible))))
4032 ((integerp arg)
4033 ;; Show-subtree, ARG levels up from here.
4034 (save-excursion
4035 (org-back-to-heading)
4036 (outline-up-heading (if (< arg 0) (- arg)
4037 (- (funcall outline-level) arg)))
4038 (org-show-subtree)))
4040 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4041 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4042 ;; At a heading: rotate between three different views
4043 (org-back-to-heading)
4044 (let ((goal-column 0) eoh eol eos)
4045 ;; First, some boundaries
4046 (save-excursion
4047 (org-back-to-heading)
4048 (save-excursion
4049 (beginning-of-line 2)
4050 (while (and (not (eobp)) ;; this is like `next-line'
4051 (get-char-property (1- (point)) 'invisible))
4052 (beginning-of-line 2)) (setq eol (point)))
4053 (outline-end-of-heading) (setq eoh (point))
4054 (org-end-of-subtree t)
4055 (unless (eobp)
4056 (skip-chars-forward " \t\n")
4057 (beginning-of-line 1) ; in case this is an item
4059 (setq eos (1- (point))))
4060 ;; Find out what to do next and set `this-command'
4061 (cond
4062 ((= eos eoh)
4063 ;; Nothing is hidden behind this heading
4064 (message "EMPTY ENTRY")
4065 (setq org-cycle-subtree-status nil)
4066 (save-excursion
4067 (goto-char eos)
4068 (outline-next-heading)
4069 (if (org-invisible-p) (org-flag-heading nil))))
4070 ((or (>= eol eos)
4071 (not (string-match "\\S-" (buffer-substring eol eos))))
4072 ;; Entire subtree is hidden in one line: open it
4073 (org-show-entry)
4074 (show-children)
4075 (message "CHILDREN")
4076 (save-excursion
4077 (goto-char eos)
4078 (outline-next-heading)
4079 (if (org-invisible-p) (org-flag-heading nil)))
4080 (setq org-cycle-subtree-status 'children)
4081 (run-hook-with-args 'org-cycle-hook 'children))
4082 ((and (eq last-command this-command)
4083 (eq org-cycle-subtree-status 'children))
4084 ;; We just showed the children, now show everything.
4085 (org-show-subtree)
4086 (message "SUBTREE")
4087 (setq org-cycle-subtree-status 'subtree)
4088 (run-hook-with-args 'org-cycle-hook 'subtree))
4090 ;; Default action: hide the subtree.
4091 (hide-subtree)
4092 (message "FOLDED")
4093 (setq org-cycle-subtree-status 'folded)
4094 (run-hook-with-args 'org-cycle-hook 'folded)))))
4096 ;; TAB emulation and template completion
4097 (buffer-read-only (org-back-to-heading))
4099 ((org-try-structure-completion))
4101 ((org-try-cdlatex-tab))
4103 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4104 (or (not (bolp))
4105 (not (looking-at outline-regexp))))
4106 (call-interactively (global-key-binding "\t")))
4108 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4109 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4110 (or (and (eq org-cycle-emulate-tab 'white)
4111 (= (match-end 0) (point-at-eol)))
4112 (and (eq org-cycle-emulate-tab 'whitestart)
4113 (>= (match-end 0) pos))))
4115 (eq org-cycle-emulate-tab t))
4116 (call-interactively (global-key-binding "\t")))
4118 (t (save-excursion
4119 (org-back-to-heading)
4120 (org-cycle))))))
4122 ;;;###autoload
4123 (defun org-global-cycle (&optional arg)
4124 "Cycle the global visibility. For details see `org-cycle'.
4125 With C-u prefix arg, switch to startup visibility.
4126 With a numeric prefix, show all headlines up to that level."
4127 (interactive "P")
4128 (let ((org-cycle-include-plain-lists
4129 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4130 (cond
4131 ((integerp arg)
4132 (show-all)
4133 (hide-sublevels arg)
4134 (setq org-cycle-global-status 'contents))
4135 ((equal arg '(4))
4136 (org-set-startup-visibility)
4137 (message "Startup visibility, plus VISIBILITY properties."))
4139 (org-cycle '(4))))))
4141 (defun org-set-startup-visibility ()
4142 "Set the visibility required by startup options and properties."
4143 (cond
4144 ((eq org-startup-folded t)
4145 (org-cycle '(4)))
4146 ((eq org-startup-folded 'content)
4147 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4148 (org-cycle '(4)) (org-cycle '(4)))))
4149 (org-set-visibility-according-to-property 'no-cleanup)
4150 (org-cycle-hide-archived-subtrees 'all)
4151 (org-cycle-hide-drawers 'all)
4152 (org-cycle-show-empty-lines 'all))
4154 (defun org-set-visibility-according-to-property (&optional no-cleanup)
4155 "Switch subtree visibilities according to :VISIBILITY: property."
4156 (interactive)
4157 (let (state)
4158 (save-excursion
4159 (goto-char (point-min))
4160 (while (re-search-forward
4161 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
4162 nil t)
4163 (setq state (match-string 1))
4164 (save-excursion
4165 (org-back-to-heading t)
4166 (hide-subtree)
4167 (org-reveal)
4168 (cond
4169 ((equal state '("fold" "folded"))
4170 (hide-subtree))
4171 ((equal state "children")
4172 (org-show-hidden-entry)
4173 (show-children))
4174 ((equal state "content")
4175 (save-excursion
4176 (save-restriction
4177 (org-narrow-to-subtree)
4178 (org-content))))
4179 ((member state '("all" "showall"))
4180 (show-subtree)))))
4181 (unless no-cleanup
4182 (org-cycle-hide-archived-subtrees 'all)
4183 (org-cycle-hide-drawers 'all)
4184 (org-cycle-show-empty-lines 'all)))))
4186 (defun org-overview ()
4187 "Switch to overview mode, shoing only top-level headlines.
4188 Really, this shows all headlines with level equal or greater than the level
4189 of the first headline in the buffer. This is important, because if the
4190 first headline is not level one, then (hide-sublevels 1) gives confusing
4191 results."
4192 (interactive)
4193 (let ((level (save-excursion
4194 (goto-char (point-min))
4195 (if (re-search-forward (concat "^" outline-regexp) nil t)
4196 (progn
4197 (goto-char (match-beginning 0))
4198 (funcall outline-level))))))
4199 (and level (hide-sublevels level))))
4201 (defun org-content (&optional arg)
4202 "Show all headlines in the buffer, like a table of contents.
4203 With numerical argument N, show content up to level N."
4204 (interactive "P")
4205 (save-excursion
4206 ;; Visit all headings and show their offspring
4207 (and (integerp arg) (org-overview))
4208 (goto-char (point-max))
4209 (catch 'exit
4210 (while (and (progn (condition-case nil
4211 (outline-previous-visible-heading 1)
4212 (error (goto-char (point-min))))
4214 (looking-at outline-regexp))
4215 (if (integerp arg)
4216 (show-children (1- arg))
4217 (show-branches))
4218 (if (bobp) (throw 'exit nil))))))
4221 (defun org-optimize-window-after-visibility-change (state)
4222 "Adjust the window after a change in outline visibility.
4223 This function is the default value of the hook `org-cycle-hook'."
4224 (when (get-buffer-window (current-buffer))
4225 (cond
4226 ; ((eq state 'overview) (org-first-headline-recenter 1))
4227 ; ((eq state 'overview) (org-beginning-of-line))
4228 ((eq state 'content) nil)
4229 ((eq state 'all) nil)
4230 ((eq state 'folded) nil)
4231 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4232 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4234 (defun org-compact-display-after-subtree-move ()
4235 (let (beg end)
4236 (save-excursion
4237 (if (org-up-heading-safe)
4238 (progn
4239 (hide-subtree)
4240 (show-entry)
4241 (show-children)
4242 (org-cycle-show-empty-lines 'children)
4243 (org-cycle-hide-drawers 'children))
4244 (org-overview)))))
4246 (defun org-cycle-show-empty-lines (state)
4247 "Show empty lines above all visible headlines.
4248 The region to be covered depends on STATE when called through
4249 `org-cycle-hook'. Lisp program can use t for STATE to get the
4250 entire buffer covered. Note that an empty line is only shown if there
4251 are at least `org-cycle-separator-lines' empty lines before the headeline."
4252 (when (> org-cycle-separator-lines 0)
4253 (save-excursion
4254 (let* ((n org-cycle-separator-lines)
4255 (re (cond
4256 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
4257 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
4258 (t (let ((ns (number-to-string (- n 2))))
4259 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
4260 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
4261 beg end)
4262 (cond
4263 ((memq state '(overview contents t))
4264 (setq beg (point-min) end (point-max)))
4265 ((memq state '(children folded))
4266 (setq beg (point) end (progn (org-end-of-subtree t t)
4267 (beginning-of-line 2)
4268 (point)))))
4269 (when beg
4270 (goto-char beg)
4271 (while (re-search-forward re end t)
4272 (if (not (get-char-property (match-end 1) 'invisible))
4273 (outline-flag-region
4274 (match-beginning 1) (match-end 1) nil)))))))
4275 ;; Never hide empty lines at the end of the file.
4276 (save-excursion
4277 (goto-char (point-max))
4278 (outline-previous-heading)
4279 (outline-end-of-heading)
4280 (if (and (looking-at "[ \t\n]+")
4281 (= (match-end 0) (point-max)))
4282 (outline-flag-region (point) (match-end 0) nil))))
4284 (defun org-show-empty-lines-in-parent ()
4285 "Move to the parent and re-show empty lines before visible headlines."
4286 (save-excursion
4287 (let ((context (if (org-up-heading-safe) 'children 'overview)))
4288 (org-cycle-show-empty-lines context))))
4290 (defun org-cycle-hide-drawers (state)
4291 "Re-hide all drawers after a visibility state change."
4292 (when (and (org-mode-p)
4293 (not (memq state '(overview folded))))
4294 (save-excursion
4295 (let* ((globalp (memq state '(contents all)))
4296 (beg (if globalp (point-min) (point)))
4297 (end (if globalp (point-max) (org-end-of-subtree t))))
4298 (goto-char beg)
4299 (while (re-search-forward org-drawer-regexp end t)
4300 (org-flag-drawer t))))))
4302 (defun org-flag-drawer (flag)
4303 (save-excursion
4304 (beginning-of-line 1)
4305 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
4306 (let ((b (match-end 0))
4307 (outline-regexp org-outline-regexp))
4308 (if (re-search-forward
4309 "^[ \t]*:END:"
4310 (save-excursion (outline-next-heading) (point)) t)
4311 (outline-flag-region b (point-at-eol) flag)
4312 (error ":END: line missing"))))))
4314 (defun org-subtree-end-visible-p ()
4315 "Is the end of the current subtree visible?"
4316 (pos-visible-in-window-p
4317 (save-excursion (org-end-of-subtree t) (point))))
4319 (defun org-first-headline-recenter (&optional N)
4320 "Move cursor to the first headline and recenter the headline.
4321 Optional argument N means, put the headline into the Nth line of the window."
4322 (goto-char (point-min))
4323 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4324 (beginning-of-line)
4325 (recenter (prefix-numeric-value N))))
4327 ;;; Org-goto
4329 (defvar org-goto-window-configuration nil)
4330 (defvar org-goto-marker nil)
4331 (defvar org-goto-map
4332 (let ((map (make-sparse-keymap)))
4333 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
4334 (while (setq cmd (pop cmds))
4335 (substitute-key-definition cmd cmd map global-map)))
4336 (suppress-keymap map)
4337 (org-defkey map "\C-m" 'org-goto-ret)
4338 (org-defkey map [(return)] 'org-goto-ret)
4339 (org-defkey map [(left)] 'org-goto-left)
4340 (org-defkey map [(right)] 'org-goto-right)
4341 (org-defkey map [(control ?g)] 'org-goto-quit)
4342 (org-defkey map "\C-i" 'org-cycle)
4343 (org-defkey map [(tab)] 'org-cycle)
4344 (org-defkey map [(down)] 'outline-next-visible-heading)
4345 (org-defkey map [(up)] 'outline-previous-visible-heading)
4346 (if org-goto-auto-isearch
4347 (if (fboundp 'define-key-after)
4348 (define-key-after map [t] 'org-goto-local-auto-isearch)
4349 nil)
4350 (org-defkey map "q" 'org-goto-quit)
4351 (org-defkey map "n" 'outline-next-visible-heading)
4352 (org-defkey map "p" 'outline-previous-visible-heading)
4353 (org-defkey map "f" 'outline-forward-same-level)
4354 (org-defkey map "b" 'outline-backward-same-level)
4355 (org-defkey map "u" 'outline-up-heading))
4356 (org-defkey map "/" 'org-occur)
4357 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4358 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4359 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
4360 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
4361 (org-defkey map "\C-c\C-u" 'outline-up-heading)
4362 map))
4364 (defconst org-goto-help
4365 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4366 RET=jump to location [Q]uit and return to previous location
4367 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4369 (defvar org-goto-start-pos) ; dynamically scoped parameter
4371 ;; FIXME: Docstring doe not mention both interfaces
4372 (defun org-goto (&optional alternative-interface)
4373 "Look up a different location in the current file, keeping current visibility.
4375 When you want look-up or go to a different location in a document, the
4376 fastest way is often to fold the entire buffer and then dive into the tree.
4377 This method has the disadvantage, that the previous location will be folded,
4378 which may not be what you want.
4380 This command works around this by showing a copy of the current buffer
4381 in an indirect buffer, in overview mode. You can dive into the tree in
4382 that copy, use org-occur and incremental search to find a location.
4383 When pressing RET or `Q', the command returns to the original buffer in
4384 which the visibility is still unchanged. After RET is will also jump to
4385 the location selected in the indirect buffer and expose the
4386 the headline hierarchy above."
4387 (interactive "P")
4388 (let* ((org-refile-targets '((nil . (:maxlevel . 10))))
4389 (org-refile-use-outline-path t)
4390 (interface
4391 (if (not alternative-interface)
4392 org-goto-interface
4393 (if (eq org-goto-interface 'outline)
4394 'outline-path-completion
4395 'outline)))
4396 (org-goto-start-pos (point))
4397 (selected-point
4398 (if (eq interface 'outline)
4399 (car (org-get-location (current-buffer) org-goto-help))
4400 (nth 3 (org-refile-get-location "Goto: ")))))
4401 (if selected-point
4402 (progn
4403 (org-mark-ring-push org-goto-start-pos)
4404 (goto-char selected-point)
4405 (if (or (org-invisible-p) (org-invisible-p2))
4406 (org-show-context 'org-goto)))
4407 (message "Quit"))))
4409 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
4410 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
4411 (defvar org-goto-local-auto-isearch-map) ; defined below
4413 (defun org-get-location (buf help)
4414 "Let the user select a location in the Org-mode buffer BUF.
4415 This function uses a recursive edit. It returns the selected position
4416 or nil."
4417 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
4418 (isearch-hide-immediately nil)
4419 (isearch-search-fun-function
4420 (lambda () 'org-goto-local-search-headings))
4421 (org-goto-selected-point org-goto-exit-command))
4422 (save-excursion
4423 (save-window-excursion
4424 (delete-other-windows)
4425 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
4426 (switch-to-buffer
4427 (condition-case nil
4428 (make-indirect-buffer (current-buffer) "*org-goto*")
4429 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
4430 (with-output-to-temp-buffer "*Help*"
4431 (princ help))
4432 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
4433 (setq buffer-read-only nil)
4434 (let ((org-startup-truncated t)
4435 (org-startup-folded nil)
4436 (org-startup-align-all-tables nil))
4437 (org-mode)
4438 (org-overview))
4439 (setq buffer-read-only t)
4440 (if (and (boundp 'org-goto-start-pos)
4441 (integer-or-marker-p org-goto-start-pos))
4442 (let ((org-show-hierarchy-above t)
4443 (org-show-siblings t)
4444 (org-show-following-heading t))
4445 (goto-char org-goto-start-pos)
4446 (and (org-invisible-p) (org-show-context)))
4447 (goto-char (point-min)))
4448 (org-beginning-of-line)
4449 (message "Select location and press RET")
4450 (use-local-map org-goto-map)
4451 (recursive-edit)
4453 (kill-buffer "*org-goto*")
4454 (cons org-goto-selected-point org-goto-exit-command)))
4456 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
4457 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
4458 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
4459 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
4461 (defun org-goto-local-search-headings (string bound noerror)
4462 "Search and make sure that any matches are in headlines."
4463 (catch 'return
4464 (while (if isearch-forward
4465 (search-forward string bound noerror)
4466 (search-backward string bound noerror))
4467 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
4468 (and (member :headline context)
4469 (not (member :tags context))))
4470 (throw 'return (point))))))
4472 (defun org-goto-local-auto-isearch ()
4473 "Start isearch."
4474 (interactive)
4475 (goto-char (point-min))
4476 (let ((keys (this-command-keys)))
4477 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
4478 (isearch-mode t)
4479 (isearch-process-search-char (string-to-char keys)))))
4481 (defun org-goto-ret (&optional arg)
4482 "Finish `org-goto' by going to the new location."
4483 (interactive "P")
4484 (setq org-goto-selected-point (point)
4485 org-goto-exit-command 'return)
4486 (throw 'exit nil))
4488 (defun org-goto-left ()
4489 "Finish `org-goto' by going to the new location."
4490 (interactive)
4491 (if (org-on-heading-p)
4492 (progn
4493 (beginning-of-line 1)
4494 (setq org-goto-selected-point (point)
4495 org-goto-exit-command 'left)
4496 (throw 'exit nil))
4497 (error "Not on a heading")))
4499 (defun org-goto-right ()
4500 "Finish `org-goto' by going to the new location."
4501 (interactive)
4502 (if (org-on-heading-p)
4503 (progn
4504 (setq org-goto-selected-point (point)
4505 org-goto-exit-command 'right)
4506 (throw 'exit nil))
4507 (error "Not on a heading")))
4509 (defun org-goto-quit ()
4510 "Finish `org-goto' without cursor motion."
4511 (interactive)
4512 (setq org-goto-selected-point nil)
4513 (setq org-goto-exit-command 'quit)
4514 (throw 'exit nil))
4516 ;;; Indirect buffer display of subtrees
4518 (defvar org-indirect-dedicated-frame nil
4519 "This is the frame being used for indirect tree display.")
4520 (defvar org-last-indirect-buffer nil)
4522 (defun org-tree-to-indirect-buffer (&optional arg)
4523 "Create indirect buffer and narrow it to current subtree.
4524 With numerical prefix ARG, go up to this level and then take that tree.
4525 If ARG is negative, go up that many levels.
4526 If `org-indirect-buffer-display' is not `new-frame', the command removes the
4527 indirect buffer previously made with this command, to avoid proliferation of
4528 indirect buffers. However, when you call the command with a `C-u' prefix, or
4529 when `org-indirect-buffer-display' is `new-frame', the last buffer
4530 is kept so that you can work with several indirect buffers at the same time.
4531 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
4532 requests that a new frame be made for the new buffer, so that the dedicated
4533 frame is not changed."
4534 (interactive "P")
4535 (let ((cbuf (current-buffer))
4536 (cwin (selected-window))
4537 (pos (point))
4538 beg end level heading ibuf)
4539 (save-excursion
4540 (org-back-to-heading t)
4541 (when (numberp arg)
4542 (setq level (org-outline-level))
4543 (if (< arg 0) (setq arg (+ level arg)))
4544 (while (> (setq level (org-outline-level)) arg)
4545 (outline-up-heading 1 t)))
4546 (setq beg (point)
4547 heading (org-get-heading))
4548 (org-end-of-subtree t) (setq end (point)))
4549 (if (and (buffer-live-p org-last-indirect-buffer)
4550 (not (eq org-indirect-buffer-display 'new-frame))
4551 (not arg))
4552 (kill-buffer org-last-indirect-buffer))
4553 (setq ibuf (org-get-indirect-buffer cbuf)
4554 org-last-indirect-buffer ibuf)
4555 (cond
4556 ((or (eq org-indirect-buffer-display 'new-frame)
4557 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
4558 (select-frame (make-frame))
4559 (delete-other-windows)
4560 (switch-to-buffer ibuf)
4561 (org-set-frame-title heading))
4562 ((eq org-indirect-buffer-display 'dedicated-frame)
4563 (raise-frame
4564 (select-frame (or (and org-indirect-dedicated-frame
4565 (frame-live-p org-indirect-dedicated-frame)
4566 org-indirect-dedicated-frame)
4567 (setq org-indirect-dedicated-frame (make-frame)))))
4568 (delete-other-windows)
4569 (switch-to-buffer ibuf)
4570 (org-set-frame-title (concat "Indirect: " heading)))
4571 ((eq org-indirect-buffer-display 'current-window)
4572 (switch-to-buffer ibuf))
4573 ((eq org-indirect-buffer-display 'other-window)
4574 (pop-to-buffer ibuf))
4575 (t (error "Invalid value.")))
4576 (if (featurep 'xemacs)
4577 (save-excursion (org-mode) (turn-on-font-lock)))
4578 (narrow-to-region beg end)
4579 (show-all)
4580 (goto-char pos)
4581 (and (window-live-p cwin) (select-window cwin))))
4583 (defun org-get-indirect-buffer (&optional buffer)
4584 (setq buffer (or buffer (current-buffer)))
4585 (let ((n 1) (base (buffer-name buffer)) bname)
4586 (while (buffer-live-p
4587 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
4588 (setq n (1+ n)))
4589 (condition-case nil
4590 (make-indirect-buffer buffer bname 'clone)
4591 (error (make-indirect-buffer buffer bname)))))
4593 (defun org-set-frame-title (title)
4594 "Set the title of the current frame to the string TITLE."
4595 ;; FIXME: how to name a single frame in XEmacs???
4596 (unless (featurep 'xemacs)
4597 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
4599 ;;;; Structure editing
4601 ;;; Inserting headlines
4603 (defun org-insert-heading (&optional force-heading)
4604 "Insert a new heading or item with same depth at point.
4605 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
4606 If point is at the beginning of a headline, insert a sibling before the
4607 current headline. If point is not at the beginning, do not split the line,
4608 but create the new headline after the current line."
4609 (interactive "P")
4610 (if (= (buffer-size) 0)
4611 (insert "\n* ")
4612 (when (or force-heading (not (org-insert-item)))
4613 (let* ((head (save-excursion
4614 (condition-case nil
4615 (progn
4616 (org-back-to-heading)
4617 (match-string 0))
4618 (error "*"))))
4619 (blank (cdr (assq 'heading org-blank-before-new-entry)))
4620 pos hide-previous previous-pos)
4621 (cond
4622 ((and (org-on-heading-p) (bolp)
4623 (or (bobp)
4624 (save-excursion (backward-char 1) (not (org-invisible-p)))))
4625 ;; insert before the current line
4626 (open-line (if blank 2 1)))
4627 ((and (bolp)
4628 (or (bobp)
4629 (save-excursion
4630 (backward-char 1) (not (org-invisible-p)))))
4631 ;; insert right here
4632 nil)
4634 ;; somewhere in the line
4635 (save-excursion
4636 (setq previous-pos (point-at-bol))
4637 (end-of-line)
4638 (setq hide-previous (org-invisible-p)))
4639 (and org-insert-heading-respect-content (org-show-subtree))
4640 (let ((split
4641 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
4642 (save-excursion
4643 (let ((p (point)))
4644 (goto-char (point-at-bol))
4645 (and (looking-at org-complex-heading-regexp)
4646 (> p (match-beginning 4)))))))
4647 tags pos)
4648 (cond
4649 (org-insert-heading-respect-content
4650 (org-end-of-subtree nil t)
4651 (open-line 1))
4652 ((org-on-heading-p)
4653 (when hide-previous
4654 (show-children)
4655 (org-show-entry))
4656 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4657 (setq tags (and (match-end 2) (match-string 2)))
4658 (and (match-end 1)
4659 (delete-region (match-beginning 1) (match-end 1)))
4660 (setq pos (point-at-bol))
4661 (or split (end-of-line 1))
4662 (delete-horizontal-space)
4663 (newline (if blank 2 1))
4664 (when tags
4665 (save-excursion
4666 (goto-char pos)
4667 (end-of-line 1)
4668 (insert " " tags)
4669 (org-set-tags nil 'align))))
4671 (or split (end-of-line 1))
4672 (newline (if blank 2 1)))))))
4673 (insert head) (just-one-space)
4674 (setq pos (point))
4675 (end-of-line 1)
4676 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
4677 (when (and org-insert-heading-respect-content hide-previous)
4678 (save-excursion
4679 (goto-char previous-pos)
4680 (hide-subtree)))
4681 (run-hooks 'org-insert-heading-hook)))))
4683 (defun org-get-heading (&optional no-tags)
4684 "Return the heading of the current entry, without the stars."
4685 (save-excursion
4686 (org-back-to-heading t)
4687 (if (looking-at
4688 (if no-tags
4689 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
4690 "\\*+[ \t]+\\([^\r\n]*\\)"))
4691 (match-string 1) "")))
4693 (defun org-insert-heading-after-current ()
4694 "Insert a new heading with same level as current, after current subtree."
4695 (interactive)
4696 (org-back-to-heading)
4697 (org-insert-heading)
4698 (org-move-subtree-down)
4699 (end-of-line 1))
4701 (defun org-insert-heading-respect-content ()
4702 (interactive)
4703 (let ((org-insert-heading-respect-content t))
4704 (org-insert-heading t)))
4706 (defun org-insert-todo-heading-respect-content (&optional force-state)
4707 (interactive "P")
4708 (let ((org-insert-heading-respect-content t))
4709 (org-insert-todo-heading force-state t)))
4711 (defun org-insert-todo-heading (arg &optional force-heading)
4712 "Insert a new heading with the same level and TODO state as current heading.
4713 If the heading has no TODO state, or if the state is DONE, use the first
4714 state (TODO by default). Also with prefix arg, force first state."
4715 (interactive "P")
4716 (when (or force-heading (not (org-insert-item 'checkbox)))
4717 (org-insert-heading force-heading)
4718 (save-excursion
4719 (org-back-to-heading)
4720 (outline-previous-heading)
4721 (looking-at org-todo-line-regexp))
4722 (if (or arg
4723 (not (match-beginning 2))
4724 (member (match-string 2) org-done-keywords))
4725 (insert (car org-todo-keywords-1) " ")
4726 (insert (match-string 2) " "))
4727 (when org-provide-todo-statistics
4728 (org-update-parent-todo-statistics))))
4730 (defun org-insert-subheading (arg)
4731 "Insert a new subheading and demote it.
4732 Works for outline headings and for plain lists alike."
4733 (interactive "P")
4734 (org-insert-heading arg)
4735 (cond
4736 ((org-on-heading-p) (org-do-demote))
4737 ((org-at-item-p) (org-indent-item 1))))
4739 (defun org-insert-todo-subheading (arg)
4740 "Insert a new subheading with TODO keyword or checkbox and demote it.
4741 Works for outline headings and for plain lists alike."
4742 (interactive "P")
4743 (org-insert-todo-heading arg)
4744 (cond
4745 ((org-on-heading-p) (org-do-demote))
4746 ((org-at-item-p) (org-indent-item 1))))
4748 ;;; Promotion and Demotion
4750 (defun org-promote-subtree ()
4751 "Promote the entire subtree.
4752 See also `org-promote'."
4753 (interactive)
4754 (save-excursion
4755 (org-map-tree 'org-promote))
4756 (org-fix-position-after-promote))
4758 (defun org-demote-subtree ()
4759 "Demote the entire subtree. See `org-demote'.
4760 See also `org-promote'."
4761 (interactive)
4762 (save-excursion
4763 (org-map-tree 'org-demote))
4764 (org-fix-position-after-promote))
4767 (defun org-do-promote ()
4768 "Promote the current heading higher up the tree.
4769 If the region is active in `transient-mark-mode', promote all headings
4770 in the region."
4771 (interactive)
4772 (save-excursion
4773 (if (org-region-active-p)
4774 (org-map-region 'org-promote (region-beginning) (region-end))
4775 (org-promote)))
4776 (org-fix-position-after-promote))
4778 (defun org-do-demote ()
4779 "Demote the current heading lower down the tree.
4780 If the region is active in `transient-mark-mode', demote all headings
4781 in the region."
4782 (interactive)
4783 (save-excursion
4784 (if (org-region-active-p)
4785 (org-map-region 'org-demote (region-beginning) (region-end))
4786 (org-demote)))
4787 (org-fix-position-after-promote))
4789 (defun org-fix-position-after-promote ()
4790 "Make sure that after pro/demotion cursor position is right."
4791 (let ((pos (point)))
4792 (when (save-excursion
4793 (beginning-of-line 1)
4794 (looking-at org-todo-line-regexp)
4795 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
4796 (cond ((eobp) (insert " "))
4797 ((eolp) (insert " "))
4798 ((equal (char-after) ?\ ) (forward-char 1))))))
4800 (defun org-reduced-level (l)
4801 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
4803 (defun org-get-valid-level (level &optional change)
4804 "Rectify a level change under the influence of `org-odd-levels-only'
4805 LEVEL is a current level, CHANGE is by how much the level should be
4806 modified. Even if CHANGE is nil, LEVEL may be returned modified because
4807 even level numbers will become the next higher odd number."
4808 (if org-odd-levels-only
4809 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
4810 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
4811 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
4812 (max 1 (+ level change))))
4814 (if (boundp 'define-obsolete-function-alias)
4815 (if (or (featurep 'xemacs) (< emacs-major-version 23))
4816 (define-obsolete-function-alias 'org-get-legal-level
4817 'org-get-valid-level)
4818 (define-obsolete-function-alias 'org-get-legal-level
4819 'org-get-valid-level "23.1")))
4821 (defun org-promote ()
4822 "Promote the current heading higher up the tree.
4823 If the region is active in `transient-mark-mode', promote all headings
4824 in the region."
4825 (org-back-to-heading t)
4826 (let* ((level (save-match-data (funcall outline-level)))
4827 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
4828 (diff (abs (- level (length up-head) -1))))
4829 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
4830 (replace-match up-head nil t)
4831 ;; Fixup tag positioning
4832 (and org-auto-align-tags (org-set-tags nil t))
4833 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
4835 (defun org-demote ()
4836 "Demote the current heading lower down the tree.
4837 If the region is active in `transient-mark-mode', demote all headings
4838 in the region."
4839 (org-back-to-heading t)
4840 (let* ((level (save-match-data (funcall outline-level)))
4841 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
4842 (diff (abs (- level (length down-head) -1))))
4843 (replace-match down-head nil t)
4844 ;; Fixup tag positioning
4845 (and org-auto-align-tags (org-set-tags nil t))
4846 (if org-adapt-indentation (org-fixup-indentation diff))))
4848 (defun org-map-tree (fun)
4849 "Call FUN for every heading underneath the current one."
4850 (org-back-to-heading)
4851 (let ((level (funcall outline-level)))
4852 (save-excursion
4853 (funcall fun)
4854 (while (and (progn
4855 (outline-next-heading)
4856 (> (funcall outline-level) level))
4857 (not (eobp)))
4858 (funcall fun)))))
4860 (defun org-map-region (fun beg end)
4861 "Call FUN for every heading between BEG and END."
4862 (let ((org-ignore-region t))
4863 (save-excursion
4864 (setq end (copy-marker end))
4865 (goto-char beg)
4866 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
4867 (< (point) end))
4868 (funcall fun))
4869 (while (and (progn
4870 (outline-next-heading)
4871 (< (point) end))
4872 (not (eobp)))
4873 (funcall fun)))))
4875 (defun org-fixup-indentation (diff)
4876 "Change the indentation in the current entry by DIFF
4877 However, if any line in the current entry has no indentation, or if it
4878 would end up with no indentation after the change, nothing at all is done."
4879 (save-excursion
4880 (let ((end (save-excursion (outline-next-heading)
4881 (point-marker)))
4882 (prohibit (if (> diff 0)
4883 "^\\S-"
4884 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
4885 col)
4886 (unless (save-excursion (end-of-line 1)
4887 (re-search-forward prohibit end t))
4888 (while (and (< (point) end)
4889 (re-search-forward "^[ \t]+" end t))
4890 (goto-char (match-end 0))
4891 (setq col (current-column))
4892 (if (< diff 0) (replace-match ""))
4893 (indent-to (+ diff col))))
4894 (move-marker end nil))))
4896 (defun org-convert-to-odd-levels ()
4897 "Convert an org-mode file with all levels allowed to one with odd levels.
4898 This will leave level 1 alone, convert level 2 to level 3, level 3 to
4899 level 5 etc."
4900 (interactive)
4901 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
4902 (let ((org-odd-levels-only nil) n)
4903 (save-excursion
4904 (goto-char (point-min))
4905 (while (re-search-forward "^\\*\\*+ " nil t)
4906 (setq n (- (length (match-string 0)) 2))
4907 (while (>= (setq n (1- n)) 0)
4908 (org-demote))
4909 (end-of-line 1))))))
4912 (defun org-convert-to-oddeven-levels ()
4913 "Convert an org-mode file with only odd levels to one with odd and even levels.
4914 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
4915 section with an even level, conversion would destroy the structure of the file. An error
4916 is signaled in this case."
4917 (interactive)
4918 (goto-char (point-min))
4919 ;; First check if there are no even levels
4920 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
4921 (org-show-context t)
4922 (error "Not all levels are odd in this file. Conversion not possible."))
4923 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
4924 (let ((org-odd-levels-only nil) n)
4925 (save-excursion
4926 (goto-char (point-min))
4927 (while (re-search-forward "^\\*\\*+ " nil t)
4928 (setq n (/ (1- (length (match-string 0))) 2))
4929 (while (>= (setq n (1- n)) 0)
4930 (org-promote))
4931 (end-of-line 1))))))
4933 (defun org-tr-level (n)
4934 "Make N odd if required."
4935 (if org-odd-levels-only (1+ (/ n 2)) n))
4937 ;;; Vertical tree motion, cutting and pasting of subtrees
4939 (defun org-move-subtree-up (&optional arg)
4940 "Move the current subtree up past ARG headlines of the same level."
4941 (interactive "p")
4942 (org-move-subtree-down (- (prefix-numeric-value arg))))
4944 (defun org-move-subtree-down (&optional arg)
4945 "Move the current subtree down past ARG headlines of the same level."
4946 (interactive "p")
4947 (setq arg (prefix-numeric-value arg))
4948 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
4949 'outline-get-last-sibling))
4950 (ins-point (make-marker))
4951 (cnt (abs arg))
4952 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
4953 ;; Select the tree
4954 (org-back-to-heading)
4955 (setq beg0 (point))
4956 (save-excursion
4957 (setq ne-beg (org-back-over-empty-lines))
4958 (setq beg (point)))
4959 (save-match-data
4960 (save-excursion (outline-end-of-heading)
4961 (setq folded (org-invisible-p)))
4962 (outline-end-of-subtree))
4963 (outline-next-heading)
4964 (setq ne-end (org-back-over-empty-lines))
4965 (setq end (point))
4966 (goto-char beg0)
4967 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
4968 ;; include less whitespace
4969 (save-excursion
4970 (goto-char beg)
4971 (forward-line (- ne-beg ne-end))
4972 (setq beg (point))))
4973 ;; Find insertion point, with error handling
4974 (while (> cnt 0)
4975 (or (and (funcall movfunc) (looking-at outline-regexp))
4976 (progn (goto-char beg0)
4977 (error "Cannot move past superior level or buffer limit")))
4978 (setq cnt (1- cnt)))
4979 (if (> arg 0)
4980 ;; Moving forward - still need to move over subtree
4981 (progn (org-end-of-subtree t t)
4982 (save-excursion
4983 (org-back-over-empty-lines)
4984 (or (bolp) (newline)))))
4985 (setq ne-ins (org-back-over-empty-lines))
4986 (move-marker ins-point (point))
4987 (setq txt (buffer-substring beg end))
4988 (org-save-markers-in-region beg end)
4989 (delete-region beg end)
4990 (outline-flag-region (1- beg) beg nil)
4991 (outline-flag-region (1- (point)) (point) nil)
4992 (let ((bbb (point)))
4993 (insert-before-markers txt)
4994 (org-reinstall-markers-in-region bbb)
4995 (move-marker ins-point bbb))
4996 (or (bolp) (insert "\n"))
4997 (setq ins-end (point))
4998 (goto-char ins-point)
4999 (org-skip-whitespace)
5000 (when (and (< arg 0)
5001 (org-first-sibling-p)
5002 (> ne-ins ne-beg))
5003 ;; Move whitespace back to beginning
5004 (save-excursion
5005 (goto-char ins-end)
5006 (let ((kill-whole-line t))
5007 (kill-line (- ne-ins ne-beg)) (point)))
5008 (insert (make-string (- ne-ins ne-beg) ?\n)))
5009 (move-marker ins-point nil)
5010 (org-compact-display-after-subtree-move)
5011 (org-show-empty-lines-in-parent)
5012 (unless folded
5013 (org-show-entry)
5014 (show-children)
5015 (org-cycle-hide-drawers 'children))))
5017 (defvar org-subtree-clip ""
5018 "Clipboard for cut and paste of subtrees.
5019 This is actually only a copy of the kill, because we use the normal kill
5020 ring. We need it to check if the kill was created by `org-copy-subtree'.")
5022 (defvar org-subtree-clip-folded nil
5023 "Was the last copied subtree folded?
5024 This is used to fold the tree back after pasting.")
5026 (defun org-cut-subtree (&optional n)
5027 "Cut the current subtree into the clipboard.
5028 With prefix arg N, cut this many sequential subtrees.
5029 This is a short-hand for marking the subtree and then cutting it."
5030 (interactive "p")
5031 (org-copy-subtree n 'cut))
5033 (defun org-copy-subtree (&optional n cut force-store-markers)
5034 "Cut the current subtree into the clipboard.
5035 With prefix arg N, cut this many sequential subtrees.
5036 This is a short-hand for marking the subtree and then copying it.
5037 If CUT is non-nil, actually cut the subtree.
5038 If FORCE-STORE-MARKERS is non-nil, store the relative locations
5039 of some markers in the region, even if CUT is non-nil. This is
5040 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
5041 (interactive "p")
5042 (let (beg end folded (beg0 (point)))
5043 (if (interactive-p)
5044 (org-back-to-heading nil) ; take what looks like a subtree
5045 (org-back-to-heading t)) ; take what is really there
5046 (org-back-over-empty-lines)
5047 (setq beg (point))
5048 (skip-chars-forward " \t\r\n")
5049 (save-match-data
5050 (save-excursion (outline-end-of-heading)
5051 (setq folded (org-invisible-p)))
5052 (condition-case nil
5053 (outline-forward-same-level (1- n))
5054 (error nil))
5055 (org-end-of-subtree t t))
5056 (org-back-over-empty-lines)
5057 (setq end (point))
5058 (goto-char beg0)
5059 (when (> end beg)
5060 (setq org-subtree-clip-folded folded)
5061 (when (or cut force-store-markers)
5062 (org-save-markers-in-region beg end))
5063 (if cut (kill-region beg end) (copy-region-as-kill beg end))
5064 (setq org-subtree-clip (current-kill 0))
5065 (message "%s: Subtree(s) with %d characters"
5066 (if cut "Cut" "Copied")
5067 (length org-subtree-clip)))))
5069 (defun org-paste-subtree (&optional level tree for-yank)
5070 "Paste the clipboard as a subtree, with modification of headline level.
5071 The entire subtree is promoted or demoted in order to match a new headline
5072 level.
5074 If the cursor is at the beginning of a headline, the same level as
5075 that headline is used to paste the tree
5077 If not, the new level is derived from the *visible* headings
5078 before and after the insertion point, and taken to be the inferior headline
5079 level of the two. So if the previous visible heading is level 3 and the
5080 next is level 4 (or vice versa), level 4 will be used for insertion.
5081 This makes sure that the subtree remains an independent subtree and does
5082 not swallow low level entries.
5084 You can also force a different level, either by using a numeric prefix
5085 argument, or by inserting the heading marker by hand. For example, if the
5086 cursor is after \"*****\", then the tree will be shifted to level 5.
5088 If optional TREE is given, use this text instead of the kill ring.
5090 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
5091 move back over whitespace before inserting, and move point to the end of
5092 the inserted text when done."
5093 (interactive "P")
5094 (unless (org-kill-is-subtree-p tree)
5095 (error "%s"
5096 (substitute-command-keys
5097 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
5098 (let* ((visp (not (org-invisible-p)))
5099 (txt (or tree (and kill-ring (current-kill 0))))
5100 (^re (concat "^\\(" outline-regexp "\\)"))
5101 (re (concat "\\(" outline-regexp "\\)"))
5102 (^re_ (concat "\\(\\*+\\)[ \t]*"))
5104 (old-level (if (string-match ^re txt)
5105 (- (match-end 0) (match-beginning 0) 1)
5106 -1))
5107 (force-level (cond (level (prefix-numeric-value level))
5108 ((and (looking-at "[ \t]*$")
5109 (string-match
5110 ^re_ (buffer-substring
5111 (point-at-bol) (point))))
5112 (- (match-end 1) (match-beginning 1)))
5113 ((and (bolp)
5114 (looking-at org-outline-regexp))
5115 (- (match-end 0) (point) 1))
5116 (t nil)))
5117 (previous-level (save-excursion
5118 (condition-case nil
5119 (progn
5120 (outline-previous-visible-heading 1)
5121 (if (looking-at re)
5122 (- (match-end 0) (match-beginning 0) 1)
5124 (error 1))))
5125 (next-level (save-excursion
5126 (condition-case nil
5127 (progn
5128 (or (looking-at outline-regexp)
5129 (outline-next-visible-heading 1))
5130 (if (looking-at re)
5131 (- (match-end 0) (match-beginning 0) 1)
5133 (error 1))))
5134 (new-level (or force-level (max previous-level next-level)))
5135 (shift (if (or (= old-level -1)
5136 (= new-level -1)
5137 (= old-level new-level))
5139 (- new-level old-level)))
5140 (delta (if (> shift 0) -1 1))
5141 (func (if (> shift 0) 'org-demote 'org-promote))
5142 (org-odd-levels-only nil)
5143 beg end newend)
5144 ;; Remove the forced level indicator
5145 (if force-level
5146 (delete-region (point-at-bol) (point)))
5147 ;; Paste
5148 (beginning-of-line 1)
5149 (unless for-yank (org-back-over-empty-lines))
5150 (setq beg (point))
5151 (insert-before-markers txt)
5152 (unless (string-match "\n\\'" txt) (insert "\n"))
5153 (setq newend (point))
5154 (org-reinstall-markers-in-region beg)
5155 (setq end (point))
5156 (goto-char beg)
5157 (skip-chars-forward " \t\n\r")
5158 (setq beg (point))
5159 (if (and (org-invisible-p) visp)
5160 (save-excursion (outline-show-heading)))
5161 ;; Shift if necessary
5162 (unless (= shift 0)
5163 (save-restriction
5164 (narrow-to-region beg end)
5165 (while (not (= shift 0))
5166 (org-map-region func (point-min) (point-max))
5167 (setq shift (+ delta shift)))
5168 (goto-char (point-min))
5169 (setq newend (point-max))))
5170 (when (or (interactive-p) for-yank)
5171 (message "Clipboard pasted as level %d subtree" new-level))
5172 (if (and (not for-yank) ; in this case, org-yank will decide about folding
5173 kill-ring
5174 (eq org-subtree-clip (current-kill 0))
5175 org-subtree-clip-folded)
5176 ;; The tree was folded before it was killed/copied
5177 (hide-subtree))
5178 (and for-yank (goto-char newend))))
5180 (defun org-kill-is-subtree-p (&optional txt)
5181 "Check if the current kill is an outline subtree, or a set of trees.
5182 Returns nil if kill does not start with a headline, or if the first
5183 headline level is not the largest headline level in the tree.
5184 So this will actually accept several entries of equal levels as well,
5185 which is OK for `org-paste-subtree'.
5186 If optional TXT is given, check this string instead of the current kill."
5187 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
5188 (start-level (and kill
5189 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
5190 org-outline-regexp "\\)")
5191 kill)
5192 (- (match-end 2) (match-beginning 2) 1)))
5193 (re (concat "^" org-outline-regexp))
5194 (start (1+ (or (match-beginning 2) -1))))
5195 (if (not start-level)
5196 (progn
5197 nil) ;; does not even start with a heading
5198 (catch 'exit
5199 (while (setq start (string-match re kill (1+ start)))
5200 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
5201 (throw 'exit nil)))
5202 t))))
5204 (defvar org-markers-to-move nil
5205 "Markers that should be moved with a cut-and-paste operation.
5206 Those markers are stored together with their positions relative to
5207 the start of the region.")
5209 (defun org-save-markers-in-region (beg end)
5210 "Check markers in region.
5211 If these markers are between BEG and END, record their position relative
5212 to BEG, so that after moving the block of text, we can put the markers back
5213 into place.
5214 This function gets called just before an entry or tree gets cut from the
5215 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
5216 called immediately, to move the markers with the entries."
5217 (setq org-markers-to-move nil)
5218 (when (featurep 'org-clock)
5219 (org-clock-save-markers-for-cut-and-paste beg end))
5220 (when (featurep 'org-agenda)
5221 (org-agenda-save-markers-for-cut-and-paste beg end)))
5223 (defun org-check-and-save-marker (marker beg end)
5224 "Check if MARKER is between BEG and END.
5225 If yes, remember the marker and the distance to BEG."
5226 (when (and (marker-buffer marker)
5227 (equal (marker-buffer marker) (current-buffer)))
5228 (if (and (>= marker beg) (< marker end))
5229 (push (cons marker (- marker beg)) org-markers-to-move))))
5231 (defun org-reinstall-markers-in-region (beg)
5232 "Move all remembered markers to their position relative to BEG."
5233 (mapc (lambda (x)
5234 (move-marker (car x) (+ beg (cdr x))))
5235 org-markers-to-move)
5236 (setq org-markers-to-move nil))
5238 (defun org-narrow-to-subtree ()
5239 "Narrow buffer to the current subtree."
5240 (interactive)
5241 (save-excursion
5242 (save-match-data
5243 (narrow-to-region
5244 (progn (org-back-to-heading) (point))
5245 (progn (org-end-of-subtree t) (point))))))
5248 ;;; Outline Sorting
5250 (defun org-sort (with-case)
5251 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
5252 Optional argument WITH-CASE means sort case-sensitively."
5253 (interactive "P")
5254 (if (org-at-table-p)
5255 (org-call-with-arg 'org-table-sort-lines with-case)
5256 (org-call-with-arg 'org-sort-entries-or-items with-case)))
5258 (defun org-sort-remove-invisible (s)
5259 (remove-text-properties 0 (length s) org-rm-props s)
5260 (while (string-match org-bracket-link-regexp s)
5261 (setq s (replace-match (if (match-end 2)
5262 (match-string 3 s)
5263 (match-string 1 s)) t t s)))
5266 (defvar org-priority-regexp) ; defined later in the file
5268 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
5269 "Sort entries on a certain level of an outline tree.
5270 If there is an active region, the entries in the region are sorted.
5271 Else, if the cursor is before the first entry, sort the top-level items.
5272 Else, the children of the entry at point are sorted.
5274 Sorting can be alphabetically, numerically, and by date/time as given by
5275 the first time stamp in the entry. The command prompts for the sorting
5276 type unless it has been given to the function through the SORTING-TYPE
5277 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
5278 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
5279 called with point at the beginning of the record. It must return either
5280 a string or a number that should serve as the sorting key for that record.
5282 Comparing entries ignores case by default. However, with an optional argument
5283 WITH-CASE, the sorting considers case as well."
5284 (interactive "P")
5285 (let ((case-func (if with-case 'identity 'downcase))
5286 start beg end stars re re2
5287 txt what tmp plain-list-p)
5288 ;; Find beginning and end of region to sort
5289 (cond
5290 ((org-region-active-p)
5291 ;; we will sort the region
5292 (setq end (region-end)
5293 what "region")
5294 (goto-char (region-beginning))
5295 (if (not (org-on-heading-p)) (outline-next-heading))
5296 (setq start (point)))
5297 ((org-at-item-p)
5298 ;; we will sort this plain list
5299 (org-beginning-of-item-list) (setq start (point))
5300 (org-end-of-item-list) (setq end (point))
5301 (goto-char start)
5302 (setq plain-list-p t
5303 what "plain list"))
5304 ((or (org-on-heading-p)
5305 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
5306 ;; we will sort the children of the current headline
5307 (org-back-to-heading)
5308 (setq start (point)
5309 end (progn (org-end-of-subtree t t)
5310 (org-back-over-empty-lines)
5311 (point))
5312 what "children")
5313 (goto-char start)
5314 (show-subtree)
5315 (outline-next-heading))
5317 ;; we will sort the top-level entries in this file
5318 (goto-char (point-min))
5319 (or (org-on-heading-p) (outline-next-heading))
5320 (setq start (point) end (point-max) what "top-level")
5321 (goto-char start)
5322 (show-all)))
5324 (setq beg (point))
5325 (if (>= beg end) (error "Nothing to sort"))
5327 (unless plain-list-p
5328 (looking-at "\\(\\*+\\)")
5329 (setq stars (match-string 1)
5330 re (concat "^" (regexp-quote stars) " +")
5331 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
5332 txt (buffer-substring beg end))
5333 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
5334 (if (and (not (equal stars "*")) (string-match re2 txt))
5335 (error "Region to sort contains a level above the first entry")))
5337 (unless sorting-type
5338 (message
5339 (if plain-list-p
5340 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
5341 "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:")
5342 what)
5343 (setq sorting-type (read-char-exclusive))
5345 (and (= (downcase sorting-type) ?f)
5346 (setq getkey-func
5347 (completing-read "Sort using function: "
5348 obarray 'fboundp t nil nil))
5349 (setq getkey-func (intern getkey-func)))
5351 (and (= (downcase sorting-type) ?r)
5352 (setq property
5353 (completing-read "Property: "
5354 (mapcar 'list (org-buffer-property-keys t))
5355 nil t))))
5357 (message "Sorting entries...")
5359 (save-restriction
5360 (narrow-to-region start end)
5362 (let ((dcst (downcase sorting-type))
5363 (now (current-time)))
5364 (sort-subr
5365 (/= dcst sorting-type)
5366 ;; This function moves to the beginning character of the "record" to
5367 ;; be sorted.
5368 (if plain-list-p
5369 (lambda nil
5370 (if (org-at-item-p) t (goto-char (point-max))))
5371 (lambda nil
5372 (if (re-search-forward re nil t)
5373 (goto-char (match-beginning 0))
5374 (goto-char (point-max)))))
5375 ;; This function moves to the last character of the "record" being
5376 ;; sorted.
5377 (if plain-list-p
5378 'org-end-of-item
5379 (lambda nil
5380 (save-match-data
5381 (condition-case nil
5382 (outline-forward-same-level 1)
5383 (error
5384 (goto-char (point-max)))))))
5386 ;; This function returns the value that gets sorted against.
5387 (if plain-list-p
5388 (lambda nil
5389 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
5390 (cond
5391 ((= dcst ?n)
5392 (string-to-number (buffer-substring (match-end 0)
5393 (point-at-eol))))
5394 ((= dcst ?a)
5395 (buffer-substring (match-end 0) (point-at-eol)))
5396 ((= dcst ?t)
5397 (if (re-search-forward org-ts-regexp
5398 (point-at-eol) t)
5399 (org-time-string-to-time (match-string 0))
5400 now))
5401 ((= dcst ?f)
5402 (if getkey-func
5403 (progn
5404 (setq tmp (funcall getkey-func))
5405 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5406 tmp)
5407 (error "Invalid key function `%s'" getkey-func)))
5408 (t (error "Invalid sorting type `%c'" sorting-type)))))
5409 (lambda nil
5410 (cond
5411 ((= dcst ?n)
5412 (if (looking-at org-complex-heading-regexp)
5413 (string-to-number (match-string 4))
5414 nil))
5415 ((= dcst ?a)
5416 (if (looking-at org-complex-heading-regexp)
5417 (funcall case-func (match-string 4))
5418 nil))
5419 ((= dcst ?t)
5420 (if (re-search-forward org-ts-regexp
5421 (save-excursion
5422 (forward-line 2)
5423 (point)) t)
5424 (org-time-string-to-time (match-string 0))
5425 now))
5426 ((= dcst ?p)
5427 (if (re-search-forward org-priority-regexp (point-at-eol) t)
5428 (string-to-char (match-string 2))
5429 org-default-priority))
5430 ((= dcst ?r)
5431 (or (org-entry-get nil property) ""))
5432 ((= dcst ?o)
5433 (if (looking-at org-complex-heading-regexp)
5434 (- 9999 (length (member (match-string 2)
5435 org-todo-keywords-1)))))
5436 ((= dcst ?f)
5437 (if getkey-func
5438 (progn
5439 (setq tmp (funcall getkey-func))
5440 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5441 tmp)
5442 (error "Invalid key function `%s'" getkey-func)))
5443 (t (error "Invalid sorting type `%c'" sorting-type)))))
5445 (cond
5446 ((= dcst ?a) 'string<)
5447 ((= dcst ?t) 'time-less-p)
5448 (t nil)))))
5449 (message "Sorting entries...done")))
5451 (defun org-do-sort (table what &optional with-case sorting-type)
5452 "Sort TABLE of WHAT according to SORTING-TYPE.
5453 The user will be prompted for the SORTING-TYPE if the call to this
5454 function does not specify it. WHAT is only for the prompt, to indicate
5455 what is being sorted. The sorting key will be extracted from
5456 the car of the elements of the table.
5457 If WITH-CASE is non-nil, the sorting will be case-sensitive."
5458 (unless sorting-type
5459 (message
5460 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
5461 what)
5462 (setq sorting-type (read-char-exclusive)))
5463 (let ((dcst (downcase sorting-type))
5464 extractfun comparefun)
5465 ;; Define the appropriate functions
5466 (cond
5467 ((= dcst ?n)
5468 (setq extractfun 'string-to-number
5469 comparefun (if (= dcst sorting-type) '< '>)))
5470 ((= dcst ?a)
5471 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
5472 (lambda(x) (downcase (org-sort-remove-invisible x))))
5473 comparefun (if (= dcst sorting-type)
5474 'string<
5475 (lambda (a b) (and (not (string< a b))
5476 (not (string= a b)))))))
5477 ((= dcst ?t)
5478 (setq extractfun
5479 (lambda (x)
5480 (if (string-match org-ts-regexp x)
5481 (time-to-seconds
5482 (org-time-string-to-time (match-string 0 x)))
5484 comparefun (if (= dcst sorting-type) '< '>)))
5485 (t (error "Invalid sorting type `%c'" sorting-type)))
5487 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5488 table)
5489 (lambda (a b) (funcall comparefun (car a) (car b))))))
5491 ;;; Editing source examples
5493 (defvar org-exit-edit-mode-map (make-sparse-keymap))
5494 (define-key org-exit-edit-mode-map "\C-c'" 'org-edit-src-exit)
5495 (defvar org-edit-src-force-single-line nil)
5496 (defvar org-edit-src-from-org-mode nil)
5497 (defvar org-edit-src-picture nil)
5499 (define-minor-mode org-exit-edit-mode
5500 "Minor mode installing a single key binding, \"C-c '\" to exit special edit.")
5502 (defun org-edit-src-code ()
5503 "Edit the source code example at point.
5504 An indirect buffer is created, and that buffer is then narrowed to the
5505 example at point and switched to the correct language mode. When done,
5506 exit by killing the buffer with \\[org-edit-src-exit]."
5507 (interactive)
5508 (let ((line (org-current-line))
5509 (case-fold-search t)
5510 (msg (substitute-command-keys
5511 "Edit, then exit with C-c ' (C-c and single quote)"))
5512 (info (org-edit-src-find-region-and-lang))
5513 (org-mode-p (eq major-mode 'org-mode))
5514 beg end lang lang-f single)
5515 (if (not info)
5517 (setq beg (nth 0 info)
5518 end (nth 1 info)
5519 lang (nth 2 info)
5520 single (nth 3 info)
5521 lang-f (intern (concat lang "-mode")))
5522 (unless (functionp lang-f)
5523 (error "No such language mode: %s" lang-f))
5524 (goto-line line)
5525 (if (get-buffer "*Org Edit Src Example*")
5526 (kill-buffer "*Org Edit Src Example*"))
5527 (switch-to-buffer (make-indirect-buffer (current-buffer)
5528 "*Org Edit Src Example*"))
5529 (narrow-to-region beg end)
5530 (remove-text-properties beg end '(display nil invisible nil
5531 intangible nil))
5532 (let ((org-inhibit-startup t))
5533 (funcall lang-f))
5534 (set (make-local-variable 'org-edit-src-force-single-line) single)
5535 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5536 (when org-mode-p
5537 (goto-char (point-min))
5538 (while (re-search-forward "^," nil t)
5539 (replace-match "")))
5540 (goto-line line)
5541 (org-exit-edit-mode)
5542 (org-set-local 'header-line-format msg)
5543 (message "%s" msg)
5544 t)))
5546 (defun org-edit-fixed-width-region ()
5547 "Edit the fixed-width ascii drawing at point.
5548 This must be a region where each line starts with ca colon followed by
5549 a space character.
5550 An indirect buffer is created, and that buffer is then narrowed to the
5551 example at point and switched to artist-mode. When done,
5552 exit by killing the buffer with \\[org-edit-src-exit]."
5553 (interactive)
5554 (let ((line (org-current-line))
5555 (case-fold-search t)
5556 (msg (substitute-command-keys
5557 "Edit, then exit with C-c ' (C-c and single quote)"))
5558 (org-mode-p (eq major-mode 'org-mode))
5559 beg end lang lang-f)
5560 (beginning-of-line 1)
5561 (if (looking-at "[ \t]*[^:\n \t]")
5563 (if (looking-at "[ \t]*\\(\n\\|\\'\\)]")
5564 (setq beg (point) end (match-end 0))
5565 (save-excursion
5566 (if (re-search-backward "^[ \t]*[^:]" nil 'move)
5567 (setq beg (point-at-bol 2))
5568 (setq beg (point))))
5569 (save-excursion
5570 (if (re-search-forward "^[ \t]*[^:]" nil 'move)
5571 (setq end (1- (match-beginning 0)))
5572 (setq end (point))))
5573 (goto-line line)
5574 (if (get-buffer "*Org Edit Picture*")
5575 (kill-buffer "*Org Edit Picture*"))
5576 (switch-to-buffer (make-indirect-buffer (current-buffer)
5577 "*Org Edit Picture*"))
5578 (narrow-to-region beg end)
5579 (remove-text-properties beg end '(display nil invisible nil
5580 intangible nil))
5581 (when (fboundp 'font-lock-unfontify-region)
5582 (font-lock-unfontify-region (point-min) (point-max)))
5583 (cond
5584 ((eq org-edit-fixed-width-region-mode 'artist-mode)
5585 (fundamental-mode)
5586 (artist-mode 1))
5587 (t (funcall org-edit-fixed-width-region-mode)))
5588 (set (make-local-variable 'org-edit-src-force-single-line) nil)
5589 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5590 (set (make-local-variable 'org-edit-src-picture) t)
5591 (goto-char (point-min))
5592 (while (re-search-forward "^[ \t]*: " nil t)
5593 (replace-match ""))
5594 (goto-line line)
5595 (org-exit-edit-mode)
5596 (org-set-local 'header-line-format msg)
5597 (message "%s" msg)
5598 t))))
5601 (defun org-edit-src-find-region-and-lang ()
5602 "Find the region and language for a local edit.
5603 Return a list with beginning and end of the region, a string representing
5604 the language, a switch telling of the content should be in a single line."
5605 (let ((re-list
5606 (append
5607 org-edit-src-region-extra
5609 ("<src\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</src>" lang)
5610 ("<literal\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</literal>" style)
5611 ("<example>[ \t]*\n?" "\n?[ \t]*</example>" "fundamental")
5612 ("<lisp>[ \t]*\n?" "\n?[ \t]*</lisp>" "emacs-lisp")
5613 ("<perl>[ \t]*\n?" "\n?[ \t]*</perl>" "perl")
5614 ("<python>[ \t]*\n?" "\n?[ \t]*</python>" "python")
5615 ("<ruby>[ \t]*\n?" "\n?[ \t]*</ruby>" "ruby")
5616 ("^#\\+begin_src\\( \\([^ \t\n]+\\)\\)?.*\n" "\n#\\+end_src" 2)
5617 ("^#\\+begin_example.*\n" "\n#\\+end_example" "fundamental")
5618 ("^#\\+html:" "\n" "html" single-line)
5619 ("^#\\+begin_html.*\n" "\n#\\+end_html" "html")
5620 ("^#\\+begin_latex.*\n" "\n#\\+end_latex" "latex")
5621 ("^#\\+latex:" "\n" "latex" single-line)
5622 ("^#\\+begin_ascii.*\n" "\n#\\+end_ascii" "fundamental")
5623 ("^#\\+ascii:" "\n" "ascii" single-line)
5625 (pos (point))
5626 re re1 re2 single beg end lang)
5627 (catch 'exit
5628 (while (setq entry (pop re-list))
5629 (setq re1 (car entry) re2 (nth 1 entry) lang (nth 2 entry)
5630 single (nth 3 entry))
5631 (save-excursion
5632 (if (or (looking-at re1)
5633 (re-search-backward re1 nil t))
5634 (progn
5635 (setq beg (match-end 0) lang (org-edit-src-get-lang lang))
5636 (if (and (re-search-forward re2 nil t)
5637 (>= (match-end 0) pos))
5638 (throw 'exit (list beg (match-beginning 0) lang single))))
5639 (if (or (looking-at re2)
5640 (re-search-forward re2 nil t))
5641 (progn
5642 (setq end (match-beginning 0))
5643 (if (and (re-search-backward re1 nil t)
5644 (<= (match-beginning 0) pos))
5645 (throw 'exit
5646 (list (match-end 0) end
5647 (org-edit-src-get-lang lang) single)))))))))))
5649 (defun org-edit-src-get-lang (lang)
5650 "Extract the src language."
5651 (let ((m (match-string 0)))
5652 (cond
5653 ((stringp lang) lang)
5654 ((integerp lang) (match-string lang))
5655 ((and (eq lang 'lang)
5656 (string-match "\\<lang=\"\\([^ \t\n\"]+\\)\"" m))
5657 (match-string 1 m))
5658 ((and (eq lang 'style)
5659 (string-match "\\<style=\"\\([^ \t\n\"]+\\)\"" m))
5660 (match-string 1 m))
5661 (t "fundamental"))))
5663 (defun org-edit-src-exit ()
5664 "Exit special edit and protect problematic lines."
5665 (interactive)
5666 (unless (buffer-base-buffer (current-buffer))
5667 (error "This is not an indirect buffer, something is wrong..."))
5668 (unless (> (point-min) 1)
5669 (error "This buffer is not narrowed, something is wrong..."))
5670 (goto-char (point-min))
5671 (if (looking-at "[ \t\n]*\n") (replace-match ""))
5672 (if (re-search-forward "\n[ \t\n]*\\'" nil t) (replace-match ""))
5673 (when (org-bound-and-true-p org-edit-src-force-single-line)
5674 (goto-char (point-min))
5675 (while (re-search-forward "\n" nil t)
5676 (replace-match " "))
5677 (goto-char (point-min))
5678 (if (looking-at "\\s-*") (replace-match " "))
5679 (if (re-search-forward "\\s-+\\'" nil t)
5680 (replace-match "")))
5681 (when (org-bound-and-true-p org-edit-src-from-org-mode)
5682 (goto-char (point-min))
5683 (while (re-search-forward (if (org-mode-p) "^\\(.\\)" "^\\([*#]\\)") nil t)
5684 (replace-match ",\\1"))
5685 (when font-lock-mode
5686 (font-lock-unfontify-region (point-min) (point-max)))
5687 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
5688 (when (org-bound-and-true-p org-edit-src-picture)
5689 (goto-char (point-min))
5690 (while (re-search-forward "^" nil t)
5691 (replace-match ": "))
5692 (when font-lock-mode
5693 (font-lock-unfontify-region (point-min) (point-max)))
5694 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
5695 (kill-buffer (current-buffer))
5696 (and (org-mode-p) (org-restart-font-lock)))
5699 ;;; The orgstruct minor mode
5701 ;; Define a minor mode which can be used in other modes in order to
5702 ;; integrate the org-mode structure editing commands.
5704 ;; This is really a hack, because the org-mode structure commands use
5705 ;; keys which normally belong to the major mode. Here is how it
5706 ;; works: The minor mode defines all the keys necessary to operate the
5707 ;; structure commands, but wraps the commands into a function which
5708 ;; tests if the cursor is currently at a headline or a plain list
5709 ;; item. If that is the case, the structure command is used,
5710 ;; temporarily setting many Org-mode variables like regular
5711 ;; expressions for filling etc. However, when any of those keys is
5712 ;; used at a different location, function uses `key-binding' to look
5713 ;; up if the key has an associated command in another currently active
5714 ;; keymap (minor modes, major mode, global), and executes that
5715 ;; command. There might be problems if any of the keys is otherwise
5716 ;; used as a prefix key.
5718 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
5719 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
5720 ;; addresses this by checking explicitly for both bindings.
5722 (defvar orgstruct-mode-map (make-sparse-keymap)
5723 "Keymap for the minor `orgstruct-mode'.")
5725 (defvar org-local-vars nil
5726 "List of local variables, for use by `orgstruct-mode'")
5728 ;;;###autoload
5729 (define-minor-mode orgstruct-mode
5730 "Toggle the minor more `orgstruct-mode'.
5731 This mode is for using Org-mode structure commands in other modes.
5732 The following key behave as if Org-mode was active, if the cursor
5733 is on a headline, or on a plain list item (both in the definition
5734 of Org-mode).
5736 M-up Move entry/item up
5737 M-down Move entry/item down
5738 M-left Promote
5739 M-right Demote
5740 M-S-up Move entry/item up
5741 M-S-down Move entry/item down
5742 M-S-left Promote subtree
5743 M-S-right Demote subtree
5744 M-q Fill paragraph and items like in Org-mode
5745 C-c ^ Sort entries
5746 C-c - Cycle list bullet
5747 TAB Cycle item visibility
5748 M-RET Insert new heading/item
5749 S-M-RET Insert new TODO heading / Chekbox item
5750 C-c C-c Set tags / toggle checkbox"
5751 nil " OrgStruct" nil
5752 (org-load-modules-maybe)
5753 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
5755 ;;;###autoload
5756 (defun turn-on-orgstruct ()
5757 "Unconditionally turn on `orgstruct-mode'."
5758 (orgstruct-mode 1))
5760 ;;;###autoload
5761 (defun turn-on-orgstruct++ ()
5762 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
5763 In addition to setting orgstruct-mode, this also exports all indentation and
5764 autofilling variables from org-mode into the buffer. Note that turning
5765 off orgstruct-mode will *not* remove these additional settings."
5766 (orgstruct-mode 1)
5767 (let (var val)
5768 (mapc
5769 (lambda (x)
5770 (when (string-match
5771 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
5772 (symbol-name (car x)))
5773 (setq var (car x) val (nth 1 x))
5774 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
5775 org-local-vars)))
5777 (defun orgstruct-error ()
5778 "Error when there is no default binding for a structure key."
5779 (interactive)
5780 (error "This key has no function outside structure elements"))
5782 (defun orgstruct-setup ()
5783 "Setup orgstruct keymaps."
5784 (let ((nfunc 0)
5785 (bindings
5786 (list
5787 '([(meta up)] org-metaup)
5788 '([(meta down)] org-metadown)
5789 '([(meta left)] org-metaleft)
5790 '([(meta right)] org-metaright)
5791 '([(meta shift up)] org-shiftmetaup)
5792 '([(meta shift down)] org-shiftmetadown)
5793 '([(meta shift left)] org-shiftmetaleft)
5794 '([(meta shift right)] org-shiftmetaright)
5795 '([(shift up)] org-shiftup)
5796 '([(shift down)] org-shiftdown)
5797 '("\C-c\C-c" org-ctrl-c-ctrl-c)
5798 '("\M-q" fill-paragraph)
5799 '("\C-c^" org-sort)
5800 '("\C-c-" org-cycle-list-bullet)))
5801 elt key fun cmd)
5802 (while (setq elt (pop bindings))
5803 (setq nfunc (1+ nfunc))
5804 (setq key (org-key (car elt))
5805 fun (nth 1 elt)
5806 cmd (orgstruct-make-binding fun nfunc key))
5807 (org-defkey orgstruct-mode-map key cmd))
5809 ;; Special treatment needed for TAB and RET
5810 (org-defkey orgstruct-mode-map [(tab)]
5811 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
5812 (org-defkey orgstruct-mode-map "\C-i"
5813 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
5815 (org-defkey orgstruct-mode-map "\M-\C-m"
5816 (orgstruct-make-binding 'org-insert-heading 105
5817 "\M-\C-m" [(meta return)]))
5818 (org-defkey orgstruct-mode-map [(meta return)]
5819 (orgstruct-make-binding 'org-insert-heading 106
5820 [(meta return)] "\M-\C-m"))
5822 (org-defkey orgstruct-mode-map [(shift meta return)]
5823 (orgstruct-make-binding 'org-insert-todo-heading 107
5824 [(meta return)] "\M-\C-m"))
5826 (unless org-local-vars
5827 (setq org-local-vars (org-get-local-variables)))
5831 (defun orgstruct-make-binding (fun n &rest keys)
5832 "Create a function for binding in the structure minor mode.
5833 FUN is the command to call inside a table. N is used to create a unique
5834 command name. KEYS are keys that should be checked in for a command
5835 to execute outside of tables."
5836 (eval
5837 (list 'defun
5838 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
5839 '(arg)
5840 (concat "In Structure, run `" (symbol-name fun) "'.\n"
5841 "Outside of structure, run the binding of `"
5842 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
5843 "'.")
5844 '(interactive "p")
5845 (list 'if
5846 '(org-context-p 'headline 'item)
5847 (list 'org-run-like-in-org-mode (list 'quote fun))
5848 (list 'let '(orgstruct-mode)
5849 (list 'call-interactively
5850 (append '(or)
5851 (mapcar (lambda (k)
5852 (list 'key-binding k))
5853 keys)
5854 '('orgstruct-error))))))))
5856 (defun org-context-p (&rest contexts)
5857 "Check if local context is any of CONTEXTS.
5858 Possible values in the list of contexts are `table', `headline', and `item'."
5859 (let ((pos (point)))
5860 (goto-char (point-at-bol))
5861 (prog1 (or (and (memq 'table contexts)
5862 (looking-at "[ \t]*|"))
5863 (and (memq 'headline contexts)
5864 ;;????????? (looking-at "\\*+"))
5865 (looking-at outline-regexp))
5866 (and (memq 'item contexts)
5867 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
5868 (goto-char pos))))
5870 (defun org-get-local-variables ()
5871 "Return a list of all local variables in an org-mode buffer."
5872 (let (varlist)
5873 (with-current-buffer (get-buffer-create "*Org tmp*")
5874 (erase-buffer)
5875 (org-mode)
5876 (setq varlist (buffer-local-variables)))
5877 (kill-buffer "*Org tmp*")
5878 (delq nil
5879 (mapcar
5880 (lambda (x)
5881 (setq x
5882 (if (symbolp x)
5883 (list x)
5884 (list (car x) (list 'quote (cdr x)))))
5885 (if (string-match
5886 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
5887 (symbol-name (car x)))
5888 x nil))
5889 varlist))))
5891 ;;;###autoload
5892 (defun org-run-like-in-org-mode (cmd)
5893 (org-load-modules-maybe)
5894 (unless org-local-vars
5895 (setq org-local-vars (org-get-local-variables)))
5896 (eval (list 'let org-local-vars
5897 (list 'call-interactively (list 'quote cmd)))))
5899 ;;;; Archiving
5901 (defun org-get-category (&optional pos)
5902 "Get the category applying to position POS."
5903 (get-text-property (or pos (point)) 'org-category))
5905 (defun org-refresh-category-properties ()
5906 "Refresh category text properties in the buffer."
5907 (let ((def-cat (cond
5908 ((null org-category)
5909 (if buffer-file-name
5910 (file-name-sans-extension
5911 (file-name-nondirectory buffer-file-name))
5912 "???"))
5913 ((symbolp org-category) (symbol-name org-category))
5914 (t org-category)))
5915 beg end cat pos optionp)
5916 (org-unmodified
5917 (save-excursion
5918 (save-restriction
5919 (widen)
5920 (goto-char (point-min))
5921 (put-text-property (point) (point-max) 'org-category def-cat)
5922 (while (re-search-forward
5923 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
5924 (setq pos (match-end 0)
5925 optionp (equal (char-after (match-beginning 0)) ?#)
5926 cat (org-trim (match-string 2)))
5927 (if optionp
5928 (setq beg (point-at-bol) end (point-max))
5929 (org-back-to-heading t)
5930 (setq beg (point) end (org-end-of-subtree t t)))
5931 (put-text-property beg end 'org-category cat)
5932 (goto-char pos)))))))
5935 ;;;; Link Stuff
5937 ;;; Link abbreviations
5939 (defun org-link-expand-abbrev (link)
5940 "Apply replacements as defined in `org-link-abbrev-alist."
5941 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
5942 (let* ((key (match-string 1 link))
5943 (as (or (assoc key org-link-abbrev-alist-local)
5944 (assoc key org-link-abbrev-alist)))
5945 (tag (and (match-end 2) (match-string 3 link)))
5946 rpl)
5947 (if (not as)
5948 link
5949 (setq rpl (cdr as))
5950 (cond
5951 ((symbolp rpl) (funcall rpl tag))
5952 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
5953 (t (concat rpl tag)))))
5954 link))
5956 ;;; Storing and inserting links
5958 (defvar org-insert-link-history nil
5959 "Minibuffer history for links inserted with `org-insert-link'.")
5961 (defvar org-stored-links nil
5962 "Contains the links stored with `org-store-link'.")
5964 (defvar org-store-link-plist nil
5965 "Plist with info about the most recently link created with `org-store-link'.")
5967 (defvar org-link-protocols nil
5968 "Link protocols added to Org-mode using `org-add-link-type'.")
5970 (defvar org-store-link-functions nil
5971 "List of functions that are called to create and store a link.
5972 Each function will be called in turn until one returns a non-nil
5973 value. Each function should check if it is responsible for creating
5974 this link (for example by looking at the major mode).
5975 If not, it must exit and return nil.
5976 If yes, it should return a non-nil value after a calling
5977 `org-store-link-props' with a list of properties and values.
5978 Special properties are:
5980 :type The link prefix. like \"http\". This must be given.
5981 :link The link, like \"http://www.astro.uva.nl/~dominik\".
5982 This is obligatory as well.
5983 :description Optional default description for the second pair
5984 of brackets in an Org-mode link. The user can still change
5985 this when inserting this link into an Org-mode buffer.
5987 In addition to these, any additional properties can be specified
5988 and then used in remember templates.")
5990 (defun org-add-link-type (type &optional follow export)
5991 "Add TYPE to the list of `org-link-types'.
5992 Re-compute all regular expressions depending on `org-link-types'
5994 FOLLOW and EXPORT are two functions.
5996 FOLLOW should take the link path as the single argument and do whatever
5997 is necessary to follow the link, for example find a file or display
5998 a mail message.
6000 EXPORT should format the link path for export to one of the export formats.
6001 It should be a function accepting three arguments:
6003 path the path of the link, the text after the prefix (like \"http:\")
6004 desc the description of the link, if any, nil if there was no descripton
6005 format the export format, a symbol like `html' or `latex'.
6007 The function may use the FORMAT information to return different values
6008 depending on the format. The return value will be put literally into
6009 the exported file.
6010 Org-mode has a built-in default for exporting links. If you are happy with
6011 this default, there is no need to define an export function for the link
6012 type. For a simple example of an export function, see `org-bbdb.el'."
6013 (add-to-list 'org-link-types type t)
6014 (org-make-link-regexps)
6015 (if (assoc type org-link-protocols)
6016 (setcdr (assoc type org-link-protocols) (list follow export))
6017 (push (list type follow export) org-link-protocols)))
6020 ;;;###autoload
6021 (defun org-store-link (arg)
6022 "\\<org-mode-map>Store an org-link to the current location.
6023 This link is added to `org-stored-links' and can later be inserted
6024 into an org-buffer with \\[org-insert-link].
6026 For some link types, a prefix arg is interpreted:
6027 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
6028 For file links, arg negates `org-context-in-file-links'."
6029 (interactive "P")
6030 (org-load-modules-maybe)
6031 (setq org-store-link-plist nil) ; reset
6032 (let (link cpltxt desc description search txt)
6033 (cond
6035 ((run-hook-with-args-until-success 'org-store-link-functions)
6036 (setq link (plist-get org-store-link-plist :link)
6037 desc (or (plist-get org-store-link-plist :description) link)))
6039 ((eq major-mode 'calendar-mode)
6040 (let ((cd (calendar-cursor-to-date)))
6041 (setq link
6042 (format-time-string
6043 (car org-time-stamp-formats)
6044 (apply 'encode-time
6045 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6046 nil nil nil))))
6047 (org-store-link-props :type "calendar" :date cd)))
6049 ((eq major-mode 'w3-mode)
6050 (setq cpltxt (url-view-url t)
6051 link (org-make-link cpltxt))
6052 (org-store-link-props :type "w3" :url (url-view-url t)))
6054 ((eq major-mode 'w3m-mode)
6055 (setq cpltxt (or w3m-current-title w3m-current-url)
6056 link (org-make-link w3m-current-url))
6057 (org-store-link-props :type "w3m" :url (url-view-url t)))
6059 ((setq search (run-hook-with-args-until-success
6060 'org-create-file-search-functions))
6061 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6062 "::" search))
6063 (setq cpltxt (or description link)))
6065 ((eq major-mode 'image-mode)
6066 (setq cpltxt (concat "file:"
6067 (abbreviate-file-name buffer-file-name))
6068 link (org-make-link cpltxt))
6069 (org-store-link-props :type "image" :file buffer-file-name))
6071 ((eq major-mode 'dired-mode)
6072 ;; link to the file in the current line
6073 (setq cpltxt (concat "file:"
6074 (abbreviate-file-name
6075 (expand-file-name
6076 (dired-get-filename nil t))))
6077 link (org-make-link cpltxt)))
6079 ((and buffer-file-name (org-mode-p))
6080 ;; Just link to current headline
6081 (setq cpltxt (concat "file:"
6082 (abbreviate-file-name buffer-file-name)))
6083 ;; Add a context search string
6084 (when (org-xor org-context-in-file-links arg)
6085 ;; Check if we are on a target
6086 (if (org-in-regexp "<<\\(.*?\\)>>")
6087 (setq cpltxt (concat cpltxt "::" (match-string 1)))
6088 (setq txt (cond
6089 ((org-on-heading-p) nil)
6090 ((org-region-active-p)
6091 (buffer-substring (region-beginning) (region-end)))
6092 (t nil)))
6093 (when (or (null txt) (string-match "\\S-" txt))
6094 (setq cpltxt
6095 (concat cpltxt "::"
6096 (condition-case nil
6097 (org-make-org-heading-search-string txt)
6098 (error "")))
6099 desc "NONE"))))
6100 (if (string-match "::\\'" cpltxt)
6101 (setq cpltxt (substring cpltxt 0 -2)))
6102 (setq link (org-make-link cpltxt)))
6104 ((buffer-file-name (buffer-base-buffer))
6105 ;; Just link to this file here.
6106 (setq cpltxt (concat "file:"
6107 (abbreviate-file-name
6108 (buffer-file-name (buffer-base-buffer)))))
6109 ;; Add a context string
6110 (when (org-xor org-context-in-file-links arg)
6111 (setq txt (if (org-region-active-p)
6112 (buffer-substring (region-beginning) (region-end))
6113 (buffer-substring (point-at-bol) (point-at-eol))))
6114 ;; Only use search option if there is some text.
6115 (when (string-match "\\S-" txt)
6116 (setq cpltxt
6117 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6118 desc "NONE")))
6119 (setq link (org-make-link cpltxt)))
6121 ((interactive-p)
6122 (error "Cannot link to a buffer which is not visiting a file"))
6124 (t (setq link nil)))
6126 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6127 (setq link (or link cpltxt)
6128 desc (or desc cpltxt))
6129 (if (equal desc "NONE") (setq desc nil))
6131 (if (and (interactive-p) link)
6132 (progn
6133 (setq org-stored-links
6134 (cons (list link desc) org-stored-links))
6135 (message "Stored: %s" (or desc link)))
6136 (and link (org-make-link-string link desc)))))
6138 (defun org-store-link-props (&rest plist)
6139 "Store link properties, extract names and addresses."
6140 (let (x adr)
6141 (when (setq x (plist-get plist :from))
6142 (setq adr (mail-extract-address-components x))
6143 (setq plist (plist-put plist :fromname (car adr)))
6144 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
6145 (when (setq x (plist-get plist :to))
6146 (setq adr (mail-extract-address-components x))
6147 (setq plist (plist-put plist :toname (car adr)))
6148 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
6149 (let ((from (plist-get plist :from))
6150 (to (plist-get plist :to)))
6151 (when (and from to org-from-is-user-regexp)
6152 (setq plist
6153 (plist-put plist :fromto
6154 (if (string-match org-from-is-user-regexp from)
6155 (concat "to %t")
6156 (concat "from %f"))))))
6157 (setq org-store-link-plist plist))
6159 (defun org-add-link-props (&rest plist)
6160 "Add these properties to the link property list."
6161 (let (key value)
6162 (while plist
6163 (setq key (pop plist) value (pop plist))
6164 (setq org-store-link-plist
6165 (plist-put org-store-link-plist key value)))))
6167 (defun org-email-link-description (&optional fmt)
6168 "Return the description part of an email link.
6169 This takes information from `org-store-link-plist' and formats it
6170 according to FMT (default from `org-email-link-description-format')."
6171 (setq fmt (or fmt org-email-link-description-format))
6172 (let* ((p org-store-link-plist)
6173 (to (plist-get p :toaddress))
6174 (from (plist-get p :fromaddress))
6175 (table
6176 (list
6177 (cons "%c" (plist-get p :fromto))
6178 (cons "%F" (plist-get p :from))
6179 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
6180 (cons "%T" (plist-get p :to))
6181 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
6182 (cons "%s" (plist-get p :subject))
6183 (cons "%m" (plist-get p :message-id)))))
6184 (when (string-match "%c" fmt)
6185 ;; Check if the user wrote this message
6186 (if (and org-from-is-user-regexp from to
6187 (save-match-data (string-match org-from-is-user-regexp from)))
6188 (setq fmt (replace-match "to %t" t t fmt))
6189 (setq fmt (replace-match "from %f" t t fmt))))
6190 (org-replace-escapes fmt table)))
6192 (defun org-make-org-heading-search-string (&optional string heading)
6193 "Make search string for STRING or current headline."
6194 (interactive)
6195 (let ((s (or string (org-get-heading))))
6196 (unless (and string (not heading))
6197 ;; We are using a headline, clean up garbage in there.
6198 (if (string-match org-todo-regexp s)
6199 (setq s (replace-match "" t t s)))
6200 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
6201 (setq s (replace-match "" t t s)))
6202 (setq s (org-trim s))
6203 (if (string-match (concat "^\\(" org-quote-string "\\|"
6204 org-comment-string "\\)") s)
6205 (setq s (replace-match "" t t s)))
6206 (while (string-match org-ts-regexp s)
6207 (setq s (replace-match "" t t s))))
6208 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
6209 (setq s (replace-match " " t t s)))
6210 (or string (setq s (concat "*" s))) ; Add * for headlines
6211 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
6213 (defun org-make-link (&rest strings)
6214 "Concatenate STRINGS."
6215 (apply 'concat strings))
6217 (defun org-make-link-string (link &optional description)
6218 "Make a link with brackets, consisting of LINK and DESCRIPTION."
6219 (unless (string-match "\\S-" link)
6220 (error "Empty link"))
6221 (when (stringp description)
6222 ;; Remove brackets from the description, they are fatal.
6223 (while (string-match "\\[" description)
6224 (setq description (replace-match "{" t t description)))
6225 (while (string-match "\\]" description)
6226 (setq description (replace-match "}" t t description))))
6227 (when (equal (org-link-escape link) description)
6228 ;; No description needed, it is identical
6229 (setq description nil))
6230 (when (and (not description)
6231 (not (equal link (org-link-escape link))))
6232 (setq description (org-extract-attributes link)))
6233 (concat "[[" (org-link-escape link) "]"
6234 (if description (concat "[" description "]") "")
6235 "]"))
6237 (defconst org-link-escape-chars
6238 '((?\ . "%20")
6239 (?\[ . "%5B")
6240 (?\] . "%5D")
6241 (?\340 . "%E0") ; `a
6242 (?\342 . "%E2") ; ^a
6243 (?\347 . "%E7") ; ,c
6244 (?\350 . "%E8") ; `e
6245 (?\351 . "%E9") ; 'e
6246 (?\352 . "%EA") ; ^e
6247 (?\356 . "%EE") ; ^i
6248 (?\364 . "%F4") ; ^o
6249 (?\371 . "%F9") ; `u
6250 (?\373 . "%FB") ; ^u
6251 (?\; . "%3B")
6252 (?? . "%3F")
6253 (?= . "%3D")
6254 (?+ . "%2B")
6256 "Association list of escapes for some characters problematic in links.
6257 This is the list that is used for internal purposes.")
6259 (defconst org-link-escape-chars-browser
6260 '((?\ . "%20")) ; 32 for the SPC char
6261 "Association list of escapes for some characters problematic in links.
6262 This is the list that is used before handing over to the browser.")
6264 (defun org-link-escape (text &optional table)
6265 "Escape charaters in TEXT that are problematic for links."
6266 (setq table (or table org-link-escape-chars))
6267 (when text
6268 (let ((re (mapconcat (lambda (x) (regexp-quote
6269 (char-to-string (car x))))
6270 table "\\|")))
6271 (while (string-match re text)
6272 (setq text
6273 (replace-match
6274 (cdr (assoc (string-to-char (match-string 0 text))
6275 table))
6276 t t text)))
6277 text)))
6279 (defun org-link-unescape (text &optional table)
6280 "Reverse the action of `org-link-escape'."
6281 (setq table (or table org-link-escape-chars))
6282 (when text
6283 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
6284 table "\\|")))
6285 (while (string-match re text)
6286 (setq text
6287 (replace-match
6288 (char-to-string (car (rassoc (match-string 0 text) table)))
6289 t t text)))
6290 text)))
6292 (defun org-xor (a b)
6293 "Exclusive or."
6294 (if a (not b) b))
6296 (defun org-get-header (header)
6297 "Find a header field in the current buffer."
6298 (save-excursion
6299 (goto-char (point-min))
6300 (let ((case-fold-search t) s)
6301 (cond
6302 ((eq header 'from)
6303 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
6304 (setq s (match-string 1)))
6305 (while (string-match "\"" s)
6306 (setq s (replace-match "" t t s)))
6307 (if (string-match "[<(].*" s)
6308 (setq s (replace-match "" t t s))))
6309 ((eq header 'message-id)
6310 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
6311 (setq s (match-string 1))))
6312 ((eq header 'subject)
6313 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
6314 (setq s (match-string 1)))))
6315 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
6316 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
6317 s)))
6320 (defun org-fixup-message-id-for-http (s)
6321 "Replace special characters in a message id, so it can be used in an http query."
6322 (while (string-match "<" s)
6323 (setq s (replace-match "%3C" t t s)))
6324 (while (string-match ">" s)
6325 (setq s (replace-match "%3E" t t s)))
6326 (while (string-match "@" s)
6327 (setq s (replace-match "%40" t t s)))
6330 ;;;###autoload
6331 (defun org-insert-link-global ()
6332 "Insert a link like Org-mode does.
6333 This command can be called in any mode to insert a link in Org-mode syntax."
6334 (interactive)
6335 (org-load-modules-maybe)
6336 (org-run-like-in-org-mode 'org-insert-link))
6338 (defun org-insert-link (&optional complete-file link-location)
6339 "Insert a link. At the prompt, enter the link.
6341 Completion can be used to select a link previously stored with
6342 `org-store-link'. When the empty string is entered (i.e. if you just
6343 press RET at the prompt), the link defaults to the most recently
6344 stored link. As SPC triggers completion in the minibuffer, you need to
6345 use M-SPC or C-q SPC to force the insertion of a space character.
6347 You will also be prompted for a description, and if one is given, it will
6348 be displayed in the buffer instead of the link.
6350 If there is already a link at point, this command will allow you to edit link
6351 and description parts.
6353 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
6354 be selected using completion. The path to the file will be relative to the
6355 current directory if the file is in the current directory or a subdirectory.
6356 Otherwise, the link will be the absolute path as completed in the minibuffer
6357 \(i.e. normally ~/path/to/file).
6359 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
6360 the current directory or below. With three \\[universal-argument] prefixes, negate the meaning
6361 of `org-keep-stored-link-after-insertion'.
6363 If `org-make-link-description-function' is non-nil, this function will be
6364 called with the link target, and the result will be the default
6365 link description.
6367 If the LINK-LOCATION parameter is non-nil, this value will be
6368 used as the link location instead of reading one interactively."
6369 (interactive "P")
6370 (let* ((wcf (current-window-configuration))
6371 (region (if (org-region-active-p)
6372 (buffer-substring (region-beginning) (region-end))))
6373 (remove (and region (list (region-beginning) (region-end))))
6374 (desc region)
6375 tmphist ; byte-compile incorrectly complains about this
6376 (link link-location)
6377 entry file)
6378 (cond
6379 (link-location) ; specified by arg, just use it.
6380 ((org-in-regexp org-bracket-link-regexp 1)
6381 ;; We do have a link at point, and we are going to edit it.
6382 (setq remove (list (match-beginning 0) (match-end 0)))
6383 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
6384 (setq link (read-string "Link: "
6385 (org-link-unescape
6386 (org-match-string-no-properties 1)))))
6387 ((or (org-in-regexp org-angle-link-re)
6388 (org-in-regexp org-plain-link-re))
6389 ;; Convert to bracket link
6390 (setq remove (list (match-beginning 0) (match-end 0))
6391 link (read-string "Link: "
6392 (org-remove-angle-brackets (match-string 0)))))
6393 ((equal complete-file '(4))
6394 ;; Completing read for file names.
6395 (setq file (read-file-name "File: "))
6396 (let ((pwd (file-name-as-directory (expand-file-name ".")))
6397 (pwd1 (file-name-as-directory (abbreviate-file-name
6398 (expand-file-name ".")))))
6399 (cond
6400 ((equal complete-file '(16))
6401 (setq link (org-make-link
6402 "file:"
6403 (abbreviate-file-name (expand-file-name file)))))
6404 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
6405 (setq link (org-make-link "file:" (match-string 1 file))))
6406 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
6407 (expand-file-name file))
6408 (setq link (org-make-link
6409 "file:" (match-string 1 (expand-file-name file)))))
6410 (t (setq link (org-make-link "file:" file))))))
6412 ;; Read link, with completion for stored links.
6413 (with-output-to-temp-buffer "*Org Links*"
6414 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
6415 (when org-stored-links
6416 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
6417 (princ (mapconcat
6418 (lambda (x)
6419 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
6420 (reverse org-stored-links) "\n"))))
6421 (let ((cw (selected-window)))
6422 (select-window (get-buffer-window "*Org Links*"))
6423 (org-fit-window-to-buffer)
6424 (setq truncate-lines t)
6425 (select-window cw))
6426 ;; Fake a link history, containing the stored links.
6427 (setq tmphist (append (mapcar 'car org-stored-links)
6428 org-insert-link-history))
6429 (unwind-protect
6430 (setq link (org-completing-read
6431 "Link: "
6432 (append
6433 (mapcar (lambda (x) (list (concat (car x) ":")))
6434 (append org-link-abbrev-alist-local org-link-abbrev-alist))
6435 (mapcar (lambda (x) (list (concat x ":")))
6436 org-link-types))
6437 nil nil nil
6438 'tmphist
6439 (or (car (car org-stored-links)))))
6440 (set-window-configuration wcf)
6441 (kill-buffer "*Org Links*"))
6442 (setq entry (assoc link org-stored-links))
6443 (or entry (push link org-insert-link-history))
6444 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
6445 (not org-keep-stored-link-after-insertion))
6446 (setq org-stored-links (delq (assoc link org-stored-links)
6447 org-stored-links)))
6448 (setq desc (or desc (nth 1 entry)))))
6450 (if (string-match org-plain-link-re link)
6451 ;; URL-like link, normalize the use of angular brackets.
6452 (setq link (org-make-link (org-remove-angle-brackets link))))
6454 ;; Check if we are linking to the current file with a search option
6455 ;; If yes, simplify the link by using only the search option.
6456 (when (and buffer-file-name
6457 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
6458 (let* ((path (match-string 1 link))
6459 (case-fold-search nil)
6460 (search (match-string 2 link)))
6461 (save-match-data
6462 (if (equal (file-truename buffer-file-name) (file-truename path))
6463 ;; We are linking to this same file, with a search option
6464 (setq link search)))))
6466 ;; Check if we can/should use a relative path. If yes, simplify the link
6467 (when (string-match "\\<file:\\(.*\\)" link)
6468 (let* ((path (match-string 1 link))
6469 (origpath path)
6470 (case-fold-search nil))
6471 (cond
6472 ((eq org-link-file-path-type 'absolute)
6473 (setq path (abbreviate-file-name (expand-file-name path))))
6474 ((eq org-link-file-path-type 'noabbrev)
6475 (setq path (expand-file-name path)))
6476 ((eq org-link-file-path-type 'relative)
6477 (setq path (file-relative-name path)))
6479 (save-match-data
6480 (if (string-match (concat "^" (regexp-quote
6481 (file-name-as-directory
6482 (expand-file-name "."))))
6483 (expand-file-name path))
6484 ;; We are linking a file with relative path name.
6485 (setq path (substring (expand-file-name path)
6486 (match-end 0)))))))
6487 (setq link (concat "file:" path))
6488 (if (equal desc origpath)
6489 (setq desc path))))
6491 (if org-make-link-description-function
6492 (setq desc (funcall org-make-link-description-function link desc)))
6494 (setq desc (read-string "Description: " desc))
6495 (unless (string-match "\\S-" desc) (setq desc nil))
6496 (if remove (apply 'delete-region remove))
6497 (insert (org-make-link-string link desc))))
6499 (defun org-completing-read (&rest args)
6500 (let ((minibuffer-local-completion-map
6501 (copy-keymap minibuffer-local-completion-map)))
6502 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
6503 (apply 'completing-read args)))
6505 (defun org-extract-attributes (s)
6506 "Extract the attributes cookie from a string and set as text property."
6507 (let (a attr (start 0) key value)
6508 (save-match-data
6509 (when (string-match "{{\\([^}]+\\)}}$" s)
6510 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
6511 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
6512 (setq key (match-string 1 a) value (match-string 2 a)
6513 start (match-end 0)
6514 attr (plist-put attr (intern key) value))))
6515 (org-add-props s nil 'org-attributes attr))
6518 (defun org-attributes-to-string (plist)
6519 "Format a property list into an HTML attribute list."
6520 (let ((s "") key value)
6521 (while plist
6522 (setq key (pop plist) value (pop plist))
6523 (setq s (concat s " "(symbol-name key) "=\"" value "\"")))
6526 ;;; Opening/following a link
6528 (defvar org-link-search-failed nil)
6530 (defun org-next-link ()
6531 "Move forward to the next link.
6532 If the link is in hidden text, expose it."
6533 (interactive)
6534 (when (and org-link-search-failed (eq this-command last-command))
6535 (goto-char (point-min))
6536 (message "Link search wrapped back to beginning of buffer"))
6537 (setq org-link-search-failed nil)
6538 (let* ((pos (point))
6539 (ct (org-context))
6540 (a (assoc :link ct)))
6541 (if a (goto-char (nth 2 a)))
6542 (if (re-search-forward org-any-link-re nil t)
6543 (progn
6544 (goto-char (match-beginning 0))
6545 (if (org-invisible-p) (org-show-context)))
6546 (goto-char pos)
6547 (setq org-link-search-failed t)
6548 (error "No further link found"))))
6550 (defun org-previous-link ()
6551 "Move backward to the previous link.
6552 If the link is in hidden text, expose it."
6553 (interactive)
6554 (when (and org-link-search-failed (eq this-command last-command))
6555 (goto-char (point-max))
6556 (message "Link search wrapped back to end of buffer"))
6557 (setq org-link-search-failed nil)
6558 (let* ((pos (point))
6559 (ct (org-context))
6560 (a (assoc :link ct)))
6561 (if a (goto-char (nth 1 a)))
6562 (if (re-search-backward org-any-link-re nil t)
6563 (progn
6564 (goto-char (match-beginning 0))
6565 (if (org-invisible-p) (org-show-context)))
6566 (goto-char pos)
6567 (setq org-link-search-failed t)
6568 (error "No further link found"))))
6570 (defun org-find-file-at-mouse (ev)
6571 "Open file link or URL at mouse."
6572 (interactive "e")
6573 (mouse-set-point ev)
6574 (org-open-at-point 'in-emacs))
6576 (defun org-open-at-mouse (ev)
6577 "Open file link or URL at mouse."
6578 (interactive "e")
6579 (mouse-set-point ev)
6580 (org-open-at-point))
6582 (defvar org-window-config-before-follow-link nil
6583 "The window configuration before following a link.
6584 This is saved in case the need arises to restore it.")
6586 (defvar org-open-link-marker (make-marker)
6587 "Marker pointing to the location where `org-open-at-point; was called.")
6589 ;;;###autoload
6590 (defun org-open-at-point-global ()
6591 "Follow a link like Org-mode does.
6592 This command can be called in any mode to follow a link that has
6593 Org-mode syntax."
6594 (interactive)
6595 (org-run-like-in-org-mode 'org-open-at-point))
6597 ;;;###autoload
6598 (defun org-open-link-from-string (s &optional arg)
6599 "Open a link in the string S, as if it was in Org-mode."
6600 (interactive "sLink: \nP")
6601 (with-temp-buffer
6602 (let ((org-inhibit-startup t))
6603 (org-mode)
6604 (insert s)
6605 (goto-char (point-min))
6606 (org-open-at-point arg))))
6608 (defun org-open-at-point (&optional in-emacs)
6609 "Open link at or after point.
6610 If there is no link at point, this function will search forward up to
6611 the end of the current subtree.
6612 Normally, files will be opened by an appropriate application. If the
6613 optional argument IN-EMACS is non-nil, Emacs will visit the file."
6614 (interactive "P")
6615 (org-load-modules-maybe)
6616 (move-marker org-open-link-marker (point))
6617 (setq org-window-config-before-follow-link (current-window-configuration))
6618 (org-remove-occur-highlights nil nil t)
6619 (if (org-at-timestamp-p t)
6620 (org-follow-timestamp-link)
6621 (let (type path link line search (pos (point)))
6622 (catch 'match
6623 (save-excursion
6624 (skip-chars-forward "^]\n\r")
6625 (when (org-in-regexp org-bracket-link-regexp)
6626 (setq link (org-extract-attributes
6627 (org-link-unescape (org-match-string-no-properties 1))))
6628 (while (string-match " *\n *" link)
6629 (setq link (replace-match " " t t link)))
6630 (setq link (org-link-expand-abbrev link))
6631 (cond
6632 ((or (file-name-absolute-p link)
6633 (string-match "^\\.\\.?/" link))
6634 (setq type "file" path link))
6635 ((string-match org-link-re-with-space2 link)
6636 (setq type (match-string 1 link) path (match-string 2 link)))
6637 (t (setq type "thisfile" path link)))
6638 (throw 'match t)))
6640 (when (get-text-property (point) 'org-linked-text)
6641 (setq type "thisfile"
6642 pos (if (get-text-property (1+ (point)) 'org-linked-text)
6643 (1+ (point)) (point))
6644 path (buffer-substring
6645 (previous-single-property-change pos 'org-linked-text)
6646 (next-single-property-change pos 'org-linked-text)))
6647 (throw 'match t))
6649 (save-excursion
6650 (when (or (org-in-regexp org-angle-link-re)
6651 (org-in-regexp org-plain-link-re))
6652 (setq type (match-string 1) path (match-string 2))
6653 (throw 'match t)))
6654 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
6655 (setq type "tree-match"
6656 path (match-string 1))
6657 (throw 'match t))
6658 (save-excursion
6659 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
6660 (setq type "tags"
6661 path (match-string 1))
6662 (while (string-match ":" path)
6663 (setq path (replace-match "+" t t path)))
6664 (throw 'match t))))
6665 (unless path
6666 (error "No link found"))
6667 ;; Remove any trailing spaces in path
6668 (if (string-match " +\\'" path)
6669 (setq path (replace-match "" t t path)))
6671 (cond
6673 ((assoc type org-link-protocols)
6674 (funcall (nth 1 (assoc type org-link-protocols)) path))
6676 ((equal type "mailto")
6677 (let ((cmd (car org-link-mailto-program))
6678 (args (cdr org-link-mailto-program)) args1
6679 (address path) (subject "") a)
6680 (if (string-match "\\(.*\\)::\\(.*\\)" path)
6681 (setq address (match-string 1 path)
6682 subject (org-link-escape (match-string 2 path))))
6683 (while args
6684 (cond
6685 ((not (stringp (car args))) (push (pop args) args1))
6686 (t (setq a (pop args))
6687 (if (string-match "%a" a)
6688 (setq a (replace-match address t t a)))
6689 (if (string-match "%s" a)
6690 (setq a (replace-match subject t t a)))
6691 (push a args1))))
6692 (apply cmd (nreverse args1))))
6694 ((member type '("http" "https" "ftp" "news"))
6695 (browse-url (concat type ":" (org-link-escape
6696 path org-link-escape-chars-browser))))
6698 ((member type '("message"))
6699 (browse-url (concat type ":" path)))
6701 ((string= type "tags")
6702 (org-tags-view in-emacs path))
6703 ((string= type "thisfile")
6704 (if in-emacs
6705 (switch-to-buffer-other-window
6706 (org-get-buffer-for-internal-link (current-buffer)))
6707 (org-mark-ring-push))
6708 (let ((cmd `(org-link-search
6709 ,path
6710 ,(cond ((equal in-emacs '(4)) 'occur)
6711 ((equal in-emacs '(16)) 'org-occur)
6712 (t nil))
6713 ,pos)))
6714 (condition-case nil (eval cmd)
6715 (error (progn (widen) (eval cmd))))))
6717 ((string= type "tree-match")
6718 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
6720 ((string= type "file")
6721 (if (string-match "::\\([0-9]+\\)\\'" path)
6722 (setq line (string-to-number (match-string 1 path))
6723 path (substring path 0 (match-beginning 0)))
6724 (if (string-match "::\\(.+\\)\\'" path)
6725 (setq search (match-string 1 path)
6726 path (substring path 0 (match-beginning 0)))))
6727 (if (string-match "[*?{]" (file-name-nondirectory path))
6728 (dired path)
6729 (org-open-file path in-emacs line search)))
6731 ((string= type "news")
6732 (require 'org-gnus)
6733 (org-gnus-follow-link path))
6735 ((string= type "shell")
6736 (let ((cmd path))
6737 (if (or (not org-confirm-shell-link-function)
6738 (funcall org-confirm-shell-link-function
6739 (format "Execute \"%s\" in shell? "
6740 (org-add-props cmd nil
6741 'face 'org-warning))))
6742 (progn
6743 (message "Executing %s" cmd)
6744 (shell-command cmd))
6745 (error "Abort"))))
6747 ((string= type "elisp")
6748 (let ((cmd path))
6749 (if (or (not org-confirm-elisp-link-function)
6750 (funcall org-confirm-elisp-link-function
6751 (format "Execute \"%s\" as elisp? "
6752 (org-add-props cmd nil
6753 'face 'org-warning))))
6754 (message "%s => %s" cmd (eval (read cmd)))
6755 (error "Abort"))))
6758 (browse-url-at-point)))))
6759 (move-marker org-open-link-marker nil)
6760 (run-hook-with-args 'org-follow-link-hook))
6762 ;;;; Time estimates
6764 (defun org-get-effort (&optional pom)
6765 "Get the effort estimate for the current entry."
6766 (org-entry-get pom org-effort-property))
6768 ;;; File search
6770 (defvar org-create-file-search-functions nil
6771 "List of functions to construct the right search string for a file link.
6772 These functions are called in turn with point at the location to
6773 which the link should point.
6775 A function in the hook should first test if it would like to
6776 handle this file type, for example by checking the major-mode or
6777 the file extension. If it decides not to handle this file, it
6778 should just return nil to give other functions a chance. If it
6779 does handle the file, it must return the search string to be used
6780 when following the link. The search string will be part of the
6781 file link, given after a double colon, and `org-open-at-point'
6782 will automatically search for it. If special measures must be
6783 taken to make the search successful, another function should be
6784 added to the companion hook `org-execute-file-search-functions',
6785 which see.
6787 A function in this hook may also use `setq' to set the variable
6788 `description' to provide a suggestion for the descriptive text to
6789 be used for this link when it gets inserted into an Org-mode
6790 buffer with \\[org-insert-link].")
6792 (defvar org-execute-file-search-functions nil
6793 "List of functions to execute a file search triggered by a link.
6795 Functions added to this hook must accept a single argument, the
6796 search string that was part of the file link, the part after the
6797 double colon. The function must first check if it would like to
6798 handle this search, for example by checking the major-mode or the
6799 file extension. If it decides not to handle this search, it
6800 should just return nil to give other functions a chance. If it
6801 does handle the search, it must return a non-nil value to keep
6802 other functions from trying.
6804 Each function can access the current prefix argument through the
6805 variable `current-prefix-argument'. Note that a single prefix is
6806 used to force opening a link in Emacs, so it may be good to only
6807 use a numeric or double prefix to guide the search function.
6809 In case this is needed, a function in this hook can also restore
6810 the window configuration before `org-open-at-point' was called using:
6812 (set-window-configuration org-window-config-before-follow-link)")
6814 (defun org-link-search (s &optional type avoid-pos)
6815 "Search for a link search option.
6816 If S is surrounded by forward slashes, it is interpreted as a
6817 regular expression. In org-mode files, this will create an `org-occur'
6818 sparse tree. In ordinary files, `occur' will be used to list matches.
6819 If the current buffer is in `dired-mode', grep will be used to search
6820 in all files. If AVOID-POS is given, ignore matches near that position."
6821 (let ((case-fold-search t)
6822 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
6823 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
6824 (append '(("") (" ") ("\t") ("\n"))
6825 org-emphasis-alist)
6826 "\\|") "\\)"))
6827 (pos (point))
6828 (pre nil) (post nil)
6829 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
6830 (cond
6831 ;; First check if there are any special
6832 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
6833 ;; Now try the builtin stuff
6834 ((save-excursion
6835 (goto-char (point-min))
6836 (and
6837 (re-search-forward
6838 (concat "<<" (regexp-quote s0) ">>") nil t)
6839 (setq type 'dedicated
6840 pos (match-beginning 0))))
6841 ;; There is an exact target for this
6842 (goto-char pos))
6843 ((string-match "^/\\(.*\\)/$" s)
6844 ;; A regular expression
6845 (cond
6846 ((org-mode-p)
6847 (org-occur (match-string 1 s)))
6848 ;;((eq major-mode 'dired-mode)
6849 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
6850 (t (org-do-occur (match-string 1 s)))))
6852 ;; A normal search strings
6853 (when (equal (string-to-char s) ?*)
6854 ;; Anchor on headlines, post may include tags.
6855 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
6856 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
6857 s (substring s 1)))
6858 (remove-text-properties
6859 0 (length s)
6860 '(face nil mouse-face nil keymap nil fontified nil) s)
6861 ;; Make a series of regular expressions to find a match
6862 (setq words (org-split-string s "[ \n\r\t]+")
6864 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
6865 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
6866 "\\)" markers)
6867 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
6868 re2a (concat "[ \t\r\n]" re2a_)
6869 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
6870 re4 (concat "[^a-zA-Z_]" re4_)
6872 re1 (concat pre re2 post)
6873 re3 (concat pre (if pre re4_ re4) post)
6874 re5 (concat pre ".*" re4)
6875 re2 (concat pre re2)
6876 re2a (concat pre (if pre re2a_ re2a))
6877 re4 (concat pre (if pre re4_ re4))
6878 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
6879 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
6880 re5 "\\)"
6882 (cond
6883 ((eq type 'org-occur) (org-occur reall))
6884 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
6885 (t (goto-char (point-min))
6886 (setq type 'fuzzy)
6887 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
6888 (org-search-not-self 1 re1 nil t)
6889 (org-search-not-self 1 re2 nil t)
6890 (org-search-not-self 1 re2a nil t)
6891 (org-search-not-self 1 re3 nil t)
6892 (org-search-not-self 1 re4 nil t)
6893 (org-search-not-self 1 re5 nil t)
6895 (goto-char (match-beginning 1))
6896 (goto-char pos)
6897 (error "No match")))))
6899 ;; Normal string-search
6900 (goto-char (point-min))
6901 (if (search-forward s nil t)
6902 (goto-char (match-beginning 0))
6903 (error "No match"))))
6904 (and (org-mode-p) (org-show-context 'link-search))
6905 type))
6907 (defun org-search-not-self (group &rest args)
6908 "Execute `re-search-forward', but only accept matches that do not
6909 enclose the position of `org-open-link-marker'."
6910 (let ((m org-open-link-marker))
6911 (catch 'exit
6912 (while (apply 're-search-forward args)
6913 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
6914 (goto-char (match-end group))
6915 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
6916 (> (match-beginning 0) (marker-position m))
6917 (< (match-end 0) (marker-position m)))
6918 (save-match-data
6919 (or (not (org-in-regexp
6920 org-bracket-link-analytic-regexp 1))
6921 (not (match-end 4)) ; no description
6922 (and (<= (match-beginning 4) (point))
6923 (>= (match-end 4) (point))))))
6924 (throw 'exit (point))))))))
6926 (defun org-get-buffer-for-internal-link (buffer)
6927 "Return a buffer to be used for displaying the link target of internal links."
6928 (cond
6929 ((not org-display-internal-link-with-indirect-buffer)
6930 buffer)
6931 ((string-match "(Clone)$" (buffer-name buffer))
6932 (message "Buffer is already a clone, not making another one")
6933 ;; we also do not modify visibility in this case
6934 buffer)
6935 (t ; make a new indirect buffer for displaying the link
6936 (let* ((bn (buffer-name buffer))
6937 (ibn (concat bn "(Clone)"))
6938 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
6939 (with-current-buffer ib (org-overview))
6940 ib))))
6942 (defun org-do-occur (regexp &optional cleanup)
6943 "Call the Emacs command `occur'.
6944 If CLEANUP is non-nil, remove the printout of the regular expression
6945 in the *Occur* buffer. This is useful if the regex is long and not useful
6946 to read."
6947 (occur regexp)
6948 (when cleanup
6949 (let ((cwin (selected-window)) win beg end)
6950 (when (setq win (get-buffer-window "*Occur*"))
6951 (select-window win))
6952 (goto-char (point-min))
6953 (when (re-search-forward "match[a-z]+" nil t)
6954 (setq beg (match-end 0))
6955 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
6956 (setq end (1- (match-beginning 0)))))
6957 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
6958 (goto-char (point-min))
6959 (select-window cwin))))
6961 ;;; The mark ring for links jumps
6963 (defvar org-mark-ring nil
6964 "Mark ring for positions before jumps in Org-mode.")
6965 (defvar org-mark-ring-last-goto nil
6966 "Last position in the mark ring used to go back.")
6967 ;; Fill and close the ring
6968 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
6969 (loop for i from 1 to org-mark-ring-length do
6970 (push (make-marker) org-mark-ring))
6971 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
6972 org-mark-ring)
6974 (defun org-mark-ring-push (&optional pos buffer)
6975 "Put the current position or POS into the mark ring and rotate it."
6976 (interactive)
6977 (setq pos (or pos (point)))
6978 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
6979 (move-marker (car org-mark-ring)
6980 (or pos (point))
6981 (or buffer (current-buffer)))
6982 (message "%s"
6983 (substitute-command-keys
6984 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
6986 (defun org-mark-ring-goto (&optional n)
6987 "Jump to the previous position in the mark ring.
6988 With prefix arg N, jump back that many stored positions. When
6989 called several times in succession, walk through the entire ring.
6990 Org-mode commands jumping to a different position in the current file,
6991 or to another Org-mode file, automatically push the old position
6992 onto the ring."
6993 (interactive "p")
6994 (let (p m)
6995 (if (eq last-command this-command)
6996 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
6997 (setq p org-mark-ring))
6998 (setq org-mark-ring-last-goto p)
6999 (setq m (car p))
7000 (switch-to-buffer (marker-buffer m))
7001 (goto-char m)
7002 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
7004 (defun org-remove-angle-brackets (s)
7005 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7006 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7008 (defun org-add-angle-brackets (s)
7009 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7010 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7012 (defun org-remove-double-quotes (s)
7013 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
7014 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
7017 ;;; Following specific links
7019 (defun org-follow-timestamp-link ()
7020 (cond
7021 ((org-at-date-range-p t)
7022 (let ((org-agenda-start-on-weekday)
7023 (t1 (match-string 1))
7024 (t2 (match-string 2)))
7025 (setq t1 (time-to-days (org-time-string-to-time t1))
7026 t2 (time-to-days (org-time-string-to-time t2)))
7027 (org-agenda-list nil t1 (1+ (- t2 t1)))))
7028 ((org-at-timestamp-p t)
7029 (org-agenda-list nil (time-to-days (org-time-string-to-time
7030 (substring (match-string 1) 0 10)))
7032 (t (error "This should not happen"))))
7035 ;;; Following file links
7036 (defvar org-wait nil)
7037 (defun org-open-file (path &optional in-emacs line search)
7038 "Open the file at PATH.
7039 First, this expands any special file name abbreviations. Then the
7040 configuration variable `org-file-apps' is checked if it contains an
7041 entry for this file type, and if yes, the corresponding command is launched.
7042 If no application is found, Emacs simply visits the file.
7043 With optional argument IN-EMACS, Emacs will visit the file.
7044 Optional LINE specifies a line to go to, optional SEARCH a string to
7045 search for. If LINE or SEARCH is given, the file will always be
7046 opened in Emacs.
7047 If the file does not exist, an error is thrown."
7048 (setq in-emacs (or in-emacs line search))
7049 (let* ((file (if (equal path "")
7050 buffer-file-name
7051 (substitute-in-file-name (expand-file-name path))))
7052 (apps (append org-file-apps (org-default-apps)))
7053 (remp (and (assq 'remote apps) (org-file-remote-p file)))
7054 (dirp (if remp nil (file-directory-p file)))
7055 (file (if (and dirp org-open-directory-means-index-dot-org)
7056 (concat (file-name-as-directory file) "index.org")
7057 file))
7058 (a-m-a-p (assq 'auto-mode apps))
7059 (dfile (downcase file))
7060 (old-buffer (current-buffer))
7061 (old-pos (point))
7062 (old-mode major-mode)
7063 ext cmd)
7064 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7065 (setq ext (match-string 1 dfile))
7066 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7067 (setq ext (match-string 1 dfile))))
7068 (if in-emacs
7069 (setq cmd 'emacs)
7070 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
7071 (and dirp (cdr (assoc 'directory apps)))
7072 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
7073 'string-match)
7074 (cdr (assoc ext apps))
7075 (cdr (assoc t apps)))))
7076 (when (eq cmd 'default)
7077 (setq cmd (cdr (assoc t apps))))
7078 (when (eq cmd 'mailcap)
7079 (require 'mailcap)
7080 (mailcap-parse-mailcaps)
7081 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7082 (command (mailcap-mime-info mime-type)))
7083 (if (stringp command)
7084 (setq cmd command)
7085 (setq cmd 'emacs))))
7086 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
7087 (not (file-exists-p file))
7088 (not org-open-non-existing-files))
7089 (error "No such file: %s" file))
7090 (cond
7091 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7092 ;; Remove quotes around the file name - we'll use shell-quote-argument.
7093 (while (string-match "['\"]%s['\"]" cmd)
7094 (setq cmd (replace-match "%s" t t cmd)))
7095 (while (string-match "%s" cmd)
7096 (setq cmd (replace-match
7097 (save-match-data
7098 (shell-quote-argument
7099 (convert-standard-filename file)))
7100 t t cmd)))
7101 (save-window-excursion
7102 (start-process-shell-command cmd nil cmd)
7103 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
7105 ((or (stringp cmd)
7106 (eq cmd 'emacs))
7107 (funcall (cdr (assq 'file org-link-frame-setup)) file)
7108 (widen)
7109 (if line (goto-line line)
7110 (if search (org-link-search search))))
7111 ((consp cmd)
7112 (let ((file (convert-standard-filename file)))
7113 (eval cmd)))
7114 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7115 (and (org-mode-p) (eq old-mode 'org-mode)
7116 (or (not (equal old-buffer (current-buffer)))
7117 (not (equal old-pos (point))))
7118 (org-mark-ring-push old-pos old-buffer))))
7120 (defun org-default-apps ()
7121 "Return the default applications for this operating system."
7122 (cond
7123 ((eq system-type 'darwin)
7124 org-file-apps-defaults-macosx)
7125 ((eq system-type 'windows-nt)
7126 org-file-apps-defaults-windowsnt)
7127 (t org-file-apps-defaults-gnu)))
7129 (defun org-apps-regexp-alist (list &optional add-auto-mode)
7130 "Convert extensions to regular expressions in the cars of LIST.
7131 Also, weed out any non-string entries, because the return value is used
7132 only for regexp matching.
7133 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
7134 point to the symbol `emacs', indicating that the file should
7135 be opened in Emacs."
7136 (append
7137 (delq nil
7138 (mapcar (lambda (x)
7139 (if (not (stringp (car x)))
7141 (if (string-match "\\W" (car x))
7143 (cons (concat "\\." (car x) "\\'") (cdr x)))))
7144 list))
7145 (if add-auto-mode
7146 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
7148 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
7149 (defun org-file-remote-p (file)
7150 "Test whether FILE specifies a location on a remote system.
7151 Return non-nil if the location is indeed remote.
7153 For example, the filename \"/user@host:/foo\" specifies a location
7154 on the system \"/user@host:\"."
7155 (cond ((fboundp 'file-remote-p)
7156 (file-remote-p file))
7157 ((fboundp 'tramp-handle-file-remote-p)
7158 (tramp-handle-file-remote-p file))
7159 ((and (boundp 'ange-ftp-name-format)
7160 (string-match (car ange-ftp-name-format) file))
7162 (t nil)))
7165 ;;;; Refiling
7167 (defun org-get-org-file ()
7168 "Read a filename, with default directory `org-directory'."
7169 (let ((default (or org-default-notes-file remember-data-file)))
7170 (read-file-name (format "File name [%s]: " default)
7171 (file-name-as-directory org-directory)
7172 default)))
7174 (defun org-notes-order-reversed-p ()
7175 "Check if the current file should receive notes in reversed order."
7176 (cond
7177 ((not org-reverse-note-order) nil)
7178 ((eq t org-reverse-note-order) t)
7179 ((not (listp org-reverse-note-order)) nil)
7180 (t (catch 'exit
7181 (let ((all org-reverse-note-order)
7182 entry)
7183 (while (setq entry (pop all))
7184 (if (string-match (car entry) buffer-file-name)
7185 (throw 'exit (cdr entry))))
7186 nil)))))
7188 (defvar org-refile-target-table nil
7189 "The list of refile targets, created by `org-refile'.")
7191 (defvar org-agenda-new-buffers nil
7192 "Buffers created to visit agenda files.")
7194 (defun org-get-refile-targets (&optional default-buffer)
7195 "Produce a table with refile targets."
7196 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
7197 targets txt re files f desc descre)
7198 (with-current-buffer (or default-buffer (current-buffer))
7199 (while (setq entry (pop entries))
7200 (setq files (car entry) desc (cdr entry))
7201 (cond
7202 ((null files) (setq files (list (current-buffer))))
7203 ((eq files 'org-agenda-files)
7204 (setq files (org-agenda-files 'unrestricted)))
7205 ((and (symbolp files) (fboundp files))
7206 (setq files (funcall files)))
7207 ((and (symbolp files) (boundp files))
7208 (setq files (symbol-value files))))
7209 (if (stringp files) (setq files (list files)))
7210 (cond
7211 ((eq (car desc) :tag)
7212 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
7213 ((eq (car desc) :todo)
7214 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
7215 ((eq (car desc) :regexp)
7216 (setq descre (cdr desc)))
7217 ((eq (car desc) :level)
7218 (setq descre (concat "^\\*\\{" (number-to-string
7219 (if org-odd-levels-only
7220 (1- (* 2 (cdr desc)))
7221 (cdr desc)))
7222 "\\}[ \t]")))
7223 ((eq (car desc) :maxlevel)
7224 (setq descre (concat "^\\*\\{1," (number-to-string
7225 (if org-odd-levels-only
7226 (1- (* 2 (cdr desc)))
7227 (cdr desc)))
7228 "\\}[ \t]")))
7229 (t (error "Bad refiling target description %s" desc)))
7230 (while (setq f (pop files))
7231 (save-excursion
7232 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
7233 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
7234 (save-excursion
7235 (save-restriction
7236 (widen)
7237 (goto-char (point-min))
7238 (while (re-search-forward descre nil t)
7239 (goto-char (point-at-bol))
7240 (when (looking-at org-complex-heading-regexp)
7241 (setq txt (org-link-display-format (match-string 4))
7242 re (concat "^" (regexp-quote
7243 (buffer-substring (match-beginning 1)
7244 (match-end 4)))))
7245 (if (match-end 5) (setq re (concat re "[ \t]+"
7246 (regexp-quote
7247 (match-string 5)))))
7248 (setq re (concat re "[ \t]*$"))
7249 (when org-refile-use-outline-path
7250 (setq txt (mapconcat 'org-protect-slash
7251 (append
7252 (if (eq org-refile-use-outline-path 'file)
7253 (list (file-name-nondirectory
7254 (buffer-file-name (buffer-base-buffer))))
7255 (if (eq org-refile-use-outline-path 'full-file-path)
7256 (list (buffer-file-name (buffer-base-buffer)))))
7257 (org-get-outline-path)
7258 (list txt))
7259 "/")))
7260 (push (list txt f re (point)) targets))
7261 (goto-char (point-at-eol))))))))
7262 (nreverse targets))))
7264 (defun org-protect-slash (s)
7265 (while (string-match "/" s)
7266 (setq s (replace-match "\\" t t s)))
7269 (defun org-get-outline-path ()
7270 "Return the outline path to the current entry, as a list."
7271 (let (rtn)
7272 (save-excursion
7273 (while (org-up-heading-safe)
7274 (when (looking-at org-complex-heading-regexp)
7275 (push (org-match-string-no-properties 4) rtn)))
7276 rtn)))
7278 (defvar org-refile-history nil
7279 "History for refiling operations.")
7281 (defun org-refile (&optional goto default-buffer)
7282 "Move the entry at point to another heading.
7283 The list of target headings is compiled using the information in
7284 `org-refile-targets', which see. This list is created before each use
7285 and will therefore always be up-to-date.
7287 At the target location, the entry is filed as a subitem of the target heading.
7288 Depending on `org-reverse-note-order', the new subitem will either be the
7289 first or the last subitem.
7291 With prefix arg GOTO, the command will only visit the target location,
7292 not actually move anything.
7293 With a double prefix `C-u C-u', go to the location where the last refiling
7294 operation has put the subtree."
7295 (interactive "P")
7296 (let* ((cbuf (current-buffer))
7297 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7298 pos it nbuf file re level reversed)
7299 (if (equal goto '(16))
7300 (org-refile-goto-last-stored)
7301 (when (setq it (org-refile-get-location
7302 (if goto "Goto: " "Refile to: ") default-buffer))
7303 (setq file (nth 1 it)
7304 re (nth 2 it)
7305 pos (nth 3 it))
7306 (setq nbuf (or (find-buffer-visiting file)
7307 (find-file-noselect file)))
7308 (if goto
7309 (progn
7310 (switch-to-buffer nbuf)
7311 (goto-char pos)
7312 (org-show-context 'org-goto))
7313 (org-copy-subtree 1 nil t)
7314 (save-excursion
7315 (set-buffer (setq nbuf (or (find-buffer-visiting file)
7316 (find-file-noselect file))))
7317 (setq reversed (org-notes-order-reversed-p))
7318 (save-excursion
7319 (save-restriction
7320 (widen)
7321 (goto-char pos)
7322 (looking-at outline-regexp)
7323 (setq level (org-get-valid-level (funcall outline-level) 1))
7324 (goto-char
7325 (if reversed
7326 (or (outline-next-heading) (point-max))
7327 (or (save-excursion (outline-get-next-sibling))
7328 (org-end-of-subtree t t)
7329 (point-max))))
7330 (if (not (bolp)) (newline))
7331 (bookmark-set "org-refile-last-stored")
7332 (org-paste-subtree level))))
7333 (org-cut-subtree)
7334 (setq org-markers-to-move nil)
7335 (message "Entry refiled to \"%s\"" (car it)))))))
7337 (defun org-refile-goto-last-stored ()
7338 "Go to the location where the last refile was stored."
7339 (interactive)
7340 (bookmark-jump "org-refile-last-stored")
7341 (message "This is the location of the last refile"))
7343 (defun org-refile-get-location (&optional prompt default-buffer)
7344 "Prompt the user for a refile location, using PROMPT."
7345 (let ((org-refile-targets org-refile-targets)
7346 (org-refile-use-outline-path org-refile-use-outline-path))
7347 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
7348 (unless org-refile-target-table
7349 (error "No refile targets"))
7350 (let* ((cbuf (current-buffer))
7351 (cfunc (if org-refile-use-outline-path
7352 'org-olpath-completing-read
7353 'completing-read))
7354 (extra (if org-refile-use-outline-path "/" ""))
7355 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7356 (fname (and filename (file-truename filename)))
7357 (tbl (mapcar
7358 (lambda (x)
7359 (if (not (equal fname (file-truename (nth 1 x))))
7360 (cons (concat (car x) extra " ("
7361 (file-name-nondirectory (nth 1 x)) ")")
7362 (cdr x))
7363 (cons (concat (car x) extra) (cdr x))))
7364 org-refile-target-table))
7365 (completion-ignore-case t))
7366 (assoc (funcall cfunc prompt tbl nil t nil 'org-refile-history)
7367 tbl)))
7369 (defun org-olpath-completing-read (prompt collection &rest args)
7370 "Read an outline path like a file name."
7371 (let ((thetable collection))
7372 (apply
7373 'completing-read prompt
7374 (lambda (string predicate &optional flag)
7375 (let (rtn r s f (l (length string)))
7376 (cond
7377 ((eq flag nil)
7378 ;; try completion
7379 (try-completion string thetable))
7380 ((eq flag t)
7381 ;; all-completions
7382 (setq rtn (all-completions string thetable predicate))
7383 (mapcar
7384 (lambda (x)
7385 (setq r (substring x l))
7386 (if (string-match " ([^)]*)$" x)
7387 (setq f (match-string 0 x))
7388 (setq f ""))
7389 (if (string-match "/" r)
7390 (concat string (substring r 0 (match-end 0)) f)
7392 rtn))
7393 ((eq flag 'lambda)
7394 ;; exact match?
7395 (assoc string thetable)))
7397 args)))
7399 ;;;; Dynamic blocks
7401 (defun org-find-dblock (name)
7402 "Find the first dynamic block with name NAME in the buffer.
7403 If not found, stay at current position and return nil."
7404 (let (pos)
7405 (save-excursion
7406 (goto-char (point-min))
7407 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
7408 nil t)
7409 (match-beginning 0))))
7410 (if pos (goto-char pos))
7411 pos))
7413 (defconst org-dblock-start-re
7414 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
7415 "Matches the startline of a dynamic block, with parameters.")
7417 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
7418 "Matches the end of a dyhamic block.")
7420 (defun org-create-dblock (plist)
7421 "Create a dynamic block section, with parameters taken from PLIST.
7422 PLIST must containe a :name entry which is used as name of the block."
7423 (unless (bolp) (newline))
7424 (let ((name (plist-get plist :name)))
7425 (insert "#+BEGIN: " name)
7426 (while plist
7427 (if (eq (car plist) :name)
7428 (setq plist (cddr plist))
7429 (insert " " (prin1-to-string (pop plist)))))
7430 (insert "\n\n#+END:\n")
7431 (beginning-of-line -2)))
7433 (defun org-prepare-dblock ()
7434 "Prepare dynamic block for refresh.
7435 This empties the block, puts the cursor at the insert position and returns
7436 the property list including an extra property :name with the block name."
7437 (unless (looking-at org-dblock-start-re)
7438 (error "Not at a dynamic block"))
7439 (let* ((begdel (1+ (match-end 0)))
7440 (name (org-no-properties (match-string 1)))
7441 (params (append (list :name name)
7442 (read (concat "(" (match-string 3) ")")))))
7443 (unless (re-search-forward org-dblock-end-re nil t)
7444 (error "Dynamic block not terminated"))
7445 (setq params
7446 (append params
7447 (list :content (buffer-substring
7448 begdel (match-beginning 0)))))
7449 (delete-region begdel (match-beginning 0))
7450 (goto-char begdel)
7451 (open-line 1)
7452 params))
7454 (defun org-map-dblocks (&optional command)
7455 "Apply COMMAND to all dynamic blocks in the current buffer.
7456 If COMMAND is not given, use `org-update-dblock'."
7457 (let ((cmd (or command 'org-update-dblock))
7458 pos)
7459 (save-excursion
7460 (goto-char (point-min))
7461 (while (re-search-forward org-dblock-start-re nil t)
7462 (goto-char (setq pos (match-beginning 0)))
7463 (condition-case nil
7464 (funcall cmd)
7465 (error (message "Error during update of dynamic block")))
7466 (goto-char pos)
7467 (unless (re-search-forward org-dblock-end-re nil t)
7468 (error "Dynamic block not terminated"))))))
7470 (defun org-dblock-update (&optional arg)
7471 "User command for updating dynamic blocks.
7472 Update the dynamic block at point. With prefix ARG, update all dynamic
7473 blocks in the buffer."
7474 (interactive "P")
7475 (if arg
7476 (org-update-all-dblocks)
7477 (or (looking-at org-dblock-start-re)
7478 (org-beginning-of-dblock))
7479 (org-update-dblock)))
7481 (defun org-update-dblock ()
7482 "Update the dynamic block at point
7483 This means to empty the block, parse for parameters and then call
7484 the correct writing function."
7485 (save-window-excursion
7486 (let* ((pos (point))
7487 (line (org-current-line))
7488 (params (org-prepare-dblock))
7489 (name (plist-get params :name))
7490 (cmd (intern (concat "org-dblock-write:" name))))
7491 (message "Updating dynamic block `%s' at line %d..." name line)
7492 (funcall cmd params)
7493 (message "Updating dynamic block `%s' at line %d...done" name line)
7494 (goto-char pos))))
7496 (defun org-beginning-of-dblock ()
7497 "Find the beginning of the dynamic block at point.
7498 Error if there is no scuh block at point."
7499 (let ((pos (point))
7500 beg)
7501 (end-of-line 1)
7502 (if (and (re-search-backward org-dblock-start-re nil t)
7503 (setq beg (match-beginning 0))
7504 (re-search-forward org-dblock-end-re nil t)
7505 (> (match-end 0) pos))
7506 (goto-char beg)
7507 (goto-char pos)
7508 (error "Not in a dynamic block"))))
7510 (defun org-update-all-dblocks ()
7511 "Update all dynamic blocks in the buffer.
7512 This function can be used in a hook."
7513 (when (org-mode-p)
7514 (org-map-dblocks 'org-update-dblock)))
7517 ;;;; Completion
7519 (defconst org-additional-option-like-keywords
7520 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
7521 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
7522 "BEGIN_EXAMPLE" "END_EXAMPLE"
7523 "BEGIN_QUOTE" "END_QUOTE"
7524 "BEGIN_VERSE" "END_VERSE"
7525 "BEGIN_SRC" "END_SRC"))
7527 (defcustom org-structure-template-alist
7529 ("s" "#+begin_src ?\n\n#+end_src"
7530 "<src lang=\"?\">\n\n</src>")
7531 ("e" "#+begin_example\n?\n#+end_example"
7532 "<example>\n?\n</example>")
7533 ("q" "#+begin_quote\n?\n#+end_quote"
7534 "<quote>\n?\n</quote>")
7535 ("v" "#+begin_verse\n?\n#+end_verse"
7536 "<verse>\n?\n/verse>")
7537 ("l" "#+begin_latex\n?\n#+end_latex"
7538 "<literal style=\"latex\">\n?\n</literal>")
7539 ("L" "#+latex: "
7540 "<literal style=\"latex\">?</literal>")
7541 ("h" "#+begin_html\n?\n#+end_html"
7542 "<literal style=\"html\">\n?\n</literal>")
7543 ("H" "#+html: "
7544 "<literal style=\"html\">?</literal>")
7545 ("a" "#+begin_ascii\n?\n#+end_ascii")
7546 ("A" "#+ascii: ")
7547 ("i" "#+include %file ?"
7548 "<include file=%file markup=\"?\">")
7550 "Structure completion elements.
7551 This is a list of abbreviation keys and values. The value gets inserted
7552 it you type @samp{.} followed by the key and then the completion key,
7553 usually `M-TAB'. %file will be replaced by a file name after prompting
7554 for the file uning completion.
7555 There are two templates for each key, the first uses the original Org syntax,
7556 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
7557 the default when the /org-mtags.el/ module has been loaded. See also the
7558 variable `org-mtags-prefere-muse-templates'.
7559 This is an experimental feature, it is undecided if it is going to stay in."
7560 :group 'org-completion
7561 :type '(repeat
7562 (string :tag "Key")
7563 (string :tag "Template")
7564 (string :tag "Muse Template")))
7566 (defun org-try-structure-completion ()
7567 "Try to complete a structure template before point.
7568 This looks for strings like \"<e\" on an otherwise empty line and
7569 expands them."
7570 (let ((l (buffer-substring (point-at-bol) (point)))
7572 (when (and (looking-at "[ \t]*$")
7573 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
7574 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
7575 (org-complete-expand-structure-template (+ -1 (point-at-bol)
7576 (match-beginning 1)) a)
7577 t)))
7579 (defun org-complete-expand-structure-template (start cell)
7580 "Expand a structure template."
7581 (let* ((musep (org-bound-and-true-p org-mtags-prefere-muse-templates))
7582 (rpl (nth (if musep 2 1) cell)))
7583 (delete-region start (point))
7584 (when (string-match "\\`#\\+" rpl)
7585 (cond
7586 ((bolp))
7587 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
7588 (delete-region (point-at-bol) (point)))
7589 (t (newline))))
7590 (setq start (point))
7591 (if (string-match "%file" rpl)
7592 (setq rpl (replace-match
7593 (concat
7594 "\""
7595 (save-match-data
7596 (abbreviate-file-name (read-file-name "Include file: ")))
7597 "\"")
7598 t t rpl)))
7599 (insert rpl)
7600 (if (re-search-backward "\\?" start t) (delete-char 1))))
7603 (defun org-complete (&optional arg)
7604 "Perform completion on word at point.
7605 At the beginning of a headline, this completes TODO keywords as given in
7606 `org-todo-keywords'.
7607 If the current word is preceded by a backslash, completes the TeX symbols
7608 that are supported for HTML support.
7609 If the current word is preceded by \"#+\", completes special words for
7610 setting file options.
7611 In the line after \"#+STARTUP:, complete valid keywords.\"
7612 At all other locations, this simply calls the value of
7613 `org-completion-fallback-command'."
7614 (interactive "P")
7615 (org-without-partial-completion
7616 (catch 'exit
7617 (let* ((a nil)
7618 (end (point))
7619 (beg1 (save-excursion
7620 (skip-chars-backward (org-re "[:alnum:]_@"))
7621 (point)))
7622 (beg (save-excursion
7623 (skip-chars-backward "a-zA-Z0-9_:$")
7624 (point)))
7625 (confirm (lambda (x) (stringp (car x))))
7626 (searchhead (equal (char-before beg) ?*))
7627 (struct
7628 (when (and (member (char-before beg1) '(?. ?<))
7629 (setq a (assoc (buffer-substring beg1 (point))
7630 org-structure-template-alist)))
7631 (org-complete-expand-structure-template (1- beg1) a)
7632 (throw 'exit t)))
7633 (tag (and (equal (char-before beg1) ?:)
7634 (equal (char-after (point-at-bol)) ?*)))
7635 (prop (and (equal (char-before beg1) ?:)
7636 (not (equal (char-after (point-at-bol)) ?*))))
7637 (texp (equal (char-before beg) ?\\))
7638 (link (equal (char-before beg) ?\[))
7639 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
7640 beg)
7641 "#+"))
7642 (startup (string-match "^#\\+STARTUP:.*"
7643 (buffer-substring (point-at-bol) (point))))
7644 (completion-ignore-case opt)
7645 (type nil)
7646 (tbl nil)
7647 (table (cond
7648 (opt
7649 (setq type :opt)
7650 (require 'org-exp)
7651 (append
7652 (mapcar
7653 (lambda (x)
7654 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
7655 (cons (match-string 2 x) (match-string 1 x)))
7656 (org-split-string (org-get-current-options) "\n"))
7657 (mapcar 'list org-additional-option-like-keywords)))
7658 (startup
7659 (setq type :startup)
7660 org-startup-options)
7661 (link (append org-link-abbrev-alist-local
7662 org-link-abbrev-alist))
7663 (texp
7664 (setq type :tex)
7665 org-html-entities)
7666 ((string-match "\\`\\*+[ \t]+\\'"
7667 (buffer-substring (point-at-bol) beg))
7668 (setq type :todo)
7669 (mapcar 'list org-todo-keywords-1))
7670 (searchhead
7671 (setq type :searchhead)
7672 (save-excursion
7673 (goto-char (point-min))
7674 (while (re-search-forward org-todo-line-regexp nil t)
7675 (push (list
7676 (org-make-org-heading-search-string
7677 (match-string 3) t))
7678 tbl)))
7679 tbl)
7680 (tag (setq type :tag beg beg1)
7681 (or org-tag-alist (org-get-buffer-tags)))
7682 (prop (setq type :prop beg beg1)
7683 (mapcar 'list (org-buffer-property-keys nil t t)))
7684 (t (progn
7685 (call-interactively org-completion-fallback-command)
7686 (throw 'exit nil)))))
7687 (pattern (buffer-substring-no-properties beg end))
7688 (completion (try-completion pattern table confirm)))
7689 (cond ((eq completion t)
7690 (if (not (assoc (upcase pattern) table))
7691 (message "Already complete")
7692 (if (and (equal type :opt)
7693 (not (member (car (assoc (upcase pattern) table))
7694 org-additional-option-like-keywords)))
7695 (insert (substring (cdr (assoc (upcase pattern) table))
7696 (length pattern)))
7697 (if (memq type '(:tag :prop)) (insert ":")))))
7698 ((null completion)
7699 (message "Can't find completion for \"%s\"" pattern)
7700 (ding))
7701 ((not (string= pattern completion))
7702 (delete-region beg end)
7703 (if (string-match " +$" completion)
7704 (setq completion (replace-match "" t t completion)))
7705 (insert completion)
7706 (if (get-buffer-window "*Completions*")
7707 (delete-window (get-buffer-window "*Completions*")))
7708 (if (assoc completion table)
7709 (if (eq type :todo) (insert " ")
7710 (if (memq type '(:tag :prop)) (insert ":"))))
7711 (if (and (equal type :opt) (assoc completion table))
7712 (message "%s" (substitute-command-keys
7713 "Press \\[org-complete] again to insert example settings"))))
7715 (message "Making completion list...")
7716 (let ((list (sort (all-completions pattern table confirm)
7717 'string<)))
7718 (with-output-to-temp-buffer "*Completions*"
7719 (condition-case nil
7720 ;; Protection needed for XEmacs and emacs 21
7721 (display-completion-list list pattern)
7722 (error (display-completion-list list)))))
7723 (message "Making completion list...%s" "done")))))))
7725 ;;;; TODO, DEADLINE, Comments
7727 (defun org-toggle-comment ()
7728 "Change the COMMENT state of an entry."
7729 (interactive)
7730 (save-excursion
7731 (org-back-to-heading)
7732 (let (case-fold-search)
7733 (if (looking-at (concat outline-regexp
7734 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
7735 (replace-match "" t t nil 1)
7736 (if (looking-at outline-regexp)
7737 (progn
7738 (goto-char (match-end 0))
7739 (insert org-comment-string " ")))))))
7741 (defvar org-last-todo-state-is-todo nil
7742 "This is non-nil when the last TODO state change led to a TODO state.
7743 If the last change removed the TODO tag or switched to DONE, then
7744 this is nil.")
7746 (defvar org-setting-tags nil) ; dynamically skiped
7748 (defun org-parse-local-options (string var)
7749 "Parse STRING for startup setting relevant for variable VAR."
7750 (let ((rtn (symbol-value var))
7751 e opts)
7752 (save-match-data
7753 (if (or (not string) (not (string-match "\\S-" string)))
7755 (setq opts (delq nil (mapcar (lambda (x)
7756 (setq e (assoc x org-startup-options))
7757 (if (eq (nth 1 e) var) e nil))
7758 (org-split-string string "[ \t]+"))))
7759 (if (not opts)
7761 (setq rtn nil)
7762 (while (setq e (pop opts))
7763 (if (not (nth 3 e))
7764 (setq rtn (nth 2 e))
7765 (if (not (listp rtn)) (setq rtn nil))
7766 (push (nth 2 e) rtn)))
7767 rtn)))))
7769 (defvar org-blocker-hook nil
7770 "Hook for functions that are allowed to block a state change.
7772 Each function gets as its single argument a property list, see
7773 `org-trigger-hook' for more information about this list.
7775 If any of the functions in this hook returns nil, the state change
7776 is blocked.")
7778 (defvar org-trigger-hook nil
7779 "Hook for functions that are triggered by a state change.
7781 Each function gets as its single argument a property list with at least
7782 the following elements:
7784 (:type type-of-change :position pos-at-entry-start
7785 :from old-state :to new-state)
7787 Depending on the type, more properties may be present.
7789 This mechanism is currently implemented for:
7791 TODO state changes
7792 ------------------
7793 :type todo-state-change
7794 :from previous state (keyword as a string), or nil
7795 :to new state (keyword as a string), or nil")
7797 (defvar org-agenda-headline-snapshot-before-repeat)
7798 (defun org-todo (&optional arg)
7799 "Change the TODO state of an item.
7800 The state of an item is given by a keyword at the start of the heading,
7801 like
7802 *** TODO Write paper
7803 *** DONE Call mom
7805 The different keywords are specified in the variable `org-todo-keywords'.
7806 By default the available states are \"TODO\" and \"DONE\".
7807 So for this example: when the item starts with TODO, it is changed to DONE.
7808 When it starts with DONE, the DONE is removed. And when neither TODO nor
7809 DONE are present, add TODO at the beginning of the heading.
7811 With C-u prefix arg, use completion to determine the new state.
7812 With numeric prefix arg, switch to that state.
7814 For calling through lisp, arg is also interpreted in the following way:
7815 'none -> empty state
7816 \"\"(empty string) -> switch to empty state
7817 'done -> switch to DONE
7818 'nextset -> switch to the next set of keywords
7819 'previousset -> switch to the previous set of keywords
7820 \"WAITING\" -> switch to the specified keyword, but only if it
7821 really is a member of `org-todo-keywords'."
7822 (interactive "P")
7823 (save-excursion
7824 (catch 'exit
7825 (org-back-to-heading)
7826 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
7827 (or (looking-at (concat " +" org-todo-regexp " *"))
7828 (looking-at " *"))
7829 (let* ((match-data (match-data))
7830 (startpos (point-at-bol))
7831 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
7832 (org-log-done org-log-done)
7833 (org-log-repeat org-log-repeat)
7834 (org-todo-log-states org-todo-log-states)
7835 (this (match-string 1))
7836 (hl-pos (match-beginning 0))
7837 (head (org-get-todo-sequence-head this))
7838 (ass (assoc head org-todo-kwd-alist))
7839 (interpret (nth 1 ass))
7840 (done-word (nth 3 ass))
7841 (final-done-word (nth 4 ass))
7842 (last-state (or this ""))
7843 (completion-ignore-case t)
7844 (member (member this org-todo-keywords-1))
7845 (tail (cdr member))
7846 (state (cond
7847 ((and org-todo-key-trigger
7848 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
7849 (and (not arg) org-use-fast-todo-selection
7850 (not (eq org-use-fast-todo-selection 'prefix)))))
7851 ;; Use fast selection
7852 (org-fast-todo-selection))
7853 ((and (equal arg '(4))
7854 (or (not org-use-fast-todo-selection)
7855 (not org-todo-key-trigger)))
7856 ;; Read a state with completion
7857 (completing-read "State: " (mapcar (lambda(x) (list x))
7858 org-todo-keywords-1)
7859 nil t))
7860 ((eq arg 'right)
7861 (if this
7862 (if tail (car tail) nil)
7863 (car org-todo-keywords-1)))
7864 ((eq arg 'left)
7865 (if (equal member org-todo-keywords-1)
7867 (if this
7868 (nth (- (length org-todo-keywords-1) (length tail) 2)
7869 org-todo-keywords-1)
7870 (org-last org-todo-keywords-1))))
7871 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
7872 (setq arg nil))) ; hack to fall back to cycling
7873 (arg
7874 ;; user or caller requests a specific state
7875 (cond
7876 ((equal arg "") nil)
7877 ((eq arg 'none) nil)
7878 ((eq arg 'done) (or done-word (car org-done-keywords)))
7879 ((eq arg 'nextset)
7880 (or (car (cdr (member head org-todo-heads)))
7881 (car org-todo-heads)))
7882 ((eq arg 'previousset)
7883 (let ((org-todo-heads (reverse org-todo-heads)))
7884 (or (car (cdr (member head org-todo-heads)))
7885 (car org-todo-heads))))
7886 ((car (member arg org-todo-keywords-1)))
7887 ((nth (1- (prefix-numeric-value arg))
7888 org-todo-keywords-1))))
7889 ((null member) (or head (car org-todo-keywords-1)))
7890 ((equal this final-done-word) nil) ;; -> make empty
7891 ((null tail) nil) ;; -> first entry
7892 ((eq interpret 'sequence)
7893 (car tail))
7894 ((memq interpret '(type priority))
7895 (if (eq this-command last-command)
7896 (car tail)
7897 (if (> (length tail) 0)
7898 (or done-word (car org-done-keywords))
7899 nil)))
7900 (t nil)))
7901 (next (if state (concat " " state " ") " "))
7902 (change-plist (list :type 'todo-state-change :from this :to state
7903 :position startpos))
7904 dolog now-done-p)
7905 (when org-blocker-hook
7906 (unless (save-excursion
7907 (save-match-data
7908 (run-hook-with-args-until-failure
7909 'org-blocker-hook change-plist)))
7910 (if (interactive-p)
7911 (error "TODO state change from %s to %s blocked" this state)
7912 ;; fail silently
7913 (message "TODO state change from %s to %s blocked" this state)
7914 (throw 'exit nil))))
7915 (store-match-data match-data)
7916 (replace-match next t t)
7917 (unless (pos-visible-in-window-p hl-pos)
7918 (message "TODO state changed to %s" (org-trim next)))
7919 (unless head
7920 (setq head (org-get-todo-sequence-head state)
7921 ass (assoc head org-todo-kwd-alist)
7922 interpret (nth 1 ass)
7923 done-word (nth 3 ass)
7924 final-done-word (nth 4 ass)))
7925 (when (memq arg '(nextset previousset))
7926 (message "Keyword-Set %d/%d: %s"
7927 (- (length org-todo-sets) -1
7928 (length (memq (assoc state org-todo-sets) org-todo-sets)))
7929 (length org-todo-sets)
7930 (mapconcat 'identity (assoc state org-todo-sets) " ")))
7931 (setq org-last-todo-state-is-todo
7932 (not (member state org-done-keywords)))
7933 (setq now-done-p (and (member state org-done-keywords)
7934 (not (member this org-done-keywords))))
7935 (and logging (org-local-logging logging))
7936 (when (and (or org-todo-log-states org-log-done)
7937 (not (memq arg '(nextset previousset))))
7938 ;; we need to look at recording a time and note
7939 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
7940 (nth 2 (assoc this org-todo-log-states))))
7941 (when (and state
7942 (member state org-not-done-keywords)
7943 (not (member this org-not-done-keywords)))
7944 ;; This is now a todo state and was not one before
7945 ;; If there was a CLOSED time stamp, get rid of it.
7946 (org-add-planning-info nil nil 'closed))
7947 (when (and now-done-p org-log-done)
7948 ;; It is now done, and it was not done before
7949 (org-add-planning-info 'closed (org-current-time))
7950 (if (and (not dolog) (eq 'note org-log-done))
7951 (org-add-log-setup 'done state 'findpos 'note)))
7952 (when (and state dolog)
7953 ;; This is a non-nil state, and we need to log it
7954 (org-add-log-setup 'state state 'findpos dolog)))
7955 ;; Fixup tag positioning
7956 (org-todo-trigger-tag-changes state)
7957 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
7958 (when org-provide-todo-statistics
7959 (org-update-parent-todo-statistics))
7960 (run-hooks 'org-after-todo-state-change-hook)
7961 (if (and arg (not (member state org-done-keywords)))
7962 (setq head (org-get-todo-sequence-head state)))
7963 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
7964 ;; Do we need to trigger a repeat?
7965 (when now-done-p
7966 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
7967 ;; This is for the agenda, take a snapshot of the headline.
7968 (save-match-data
7969 (setq org-agenda-headline-snapshot-before-repeat
7970 (org-get-heading))))
7971 (org-auto-repeat-maybe state))
7972 ;; Fixup cursor location if close to the keyword
7973 (if (and (outline-on-heading-p)
7974 (not (bolp))
7975 (save-excursion (beginning-of-line 1)
7976 (looking-at org-todo-line-regexp))
7977 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
7978 (progn
7979 (goto-char (or (match-end 2) (match-end 1)))
7980 (just-one-space)))
7981 (when org-trigger-hook
7982 (save-excursion
7983 (run-hook-with-args 'org-trigger-hook change-plist)))))))
7985 (defun org-update-parent-todo-statistics ()
7986 "Update any statistics cookie in the parent of the current headline."
7987 (interactive)
7988 (let ((box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
7989 level (cnt-all 0) (cnt-done 0) is-percent kwd)
7990 (catch 'exit
7991 (save-excursion
7992 (setq level (org-up-heading-safe))
7993 (unless (and level
7994 (re-search-forward box-re (point-at-eol) t))
7995 (throw 'exit nil))
7996 (setq is-percent (match-end 2))
7997 (save-match-data
7998 (unless (outline-next-heading) (throw 'exit nil))
7999 (while (looking-at org-todo-line-regexp)
8000 (setq kwd (match-string 2))
8001 (and kwd (setq cnt-all (1+ cnt-all)))
8002 (and (member kwd org-done-keywords)
8003 (setq cnt-done (1+ cnt-done)))
8004 (condition-case nil
8005 (org-forward-same-level 1)
8006 (error (end-of-line 1)))))
8007 (replace-match
8008 (if is-percent
8009 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
8010 (format "[%d/%d]" cnt-done cnt-all)))
8011 (run-hook-with-args 'org-after-todo-statistics-hook
8012 cnt-done (- cnt-all cnt-done))))))
8014 (defvar org-after-todo-statistics-hook nil
8015 "Hook that is called after a TODO statistics cookie has been updated.
8016 Each function is called with two arguments: the number of not-done entries
8017 and the number of done entries.
8019 For example, the following function, when added to this hook, will switch
8020 an entry to DONE when all children are done, and back to TODO when new
8021 entries are set to a TODO status. Note that this hook is only called
8022 when there is a statistics cookie in the headline!
8024 (defun org-summary-todo (n-done n-not-done)
8025 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
8026 (let (org-log-done org-log-states) ; turn off logging
8027 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
8030 (defun org-todo-trigger-tag-changes (state)
8031 "Apply the changes defined in `org-todo-state-tags-triggers'."
8032 (let ((l org-todo-state-tags-triggers)
8033 changes)
8034 (when (or (not state) (equal state ""))
8035 (setq changes (append changes (cdr (assoc "" l)))))
8036 (when (and (stringp state) (> (length state) 0))
8037 (setq changes (append changes (cdr (assoc state l)))))
8038 (when (member state org-not-done-keywords)
8039 (setq changes (append changes (cdr (assoc 'todo l)))))
8040 (when (member state org-done-keywords)
8041 (setq changes (append changes (cdr (assoc 'done l)))))
8042 (dolist (c changes)
8043 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
8045 (defun org-local-logging (value)
8046 "Get logging settings from a property VALUE."
8047 (let* (words w a)
8048 ;; directly set the variables, they are already local.
8049 (setq org-log-done nil
8050 org-log-repeat nil
8051 org-todo-log-states nil)
8052 (setq words (org-split-string value))
8053 (while (setq w (pop words))
8054 (cond
8055 ((setq a (assoc w org-startup-options))
8056 (and (member (nth 1 a) '(org-log-done org-log-repeat))
8057 (set (nth 1 a) (nth 2 a))))
8058 ((setq a (org-extract-log-state-settings w))
8059 (and (member (car a) org-todo-keywords-1)
8060 (push a org-todo-log-states)))))))
8062 (defun org-get-todo-sequence-head (kwd)
8063 "Return the head of the TODO sequence to which KWD belongs.
8064 If KWD is not set, check if there is a text property remembering the
8065 right sequence."
8066 (let (p)
8067 (cond
8068 ((not kwd)
8069 (or (get-text-property (point-at-bol) 'org-todo-head)
8070 (progn
8071 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
8072 nil (point-at-eol)))
8073 (get-text-property p 'org-todo-head))))
8074 ((not (member kwd org-todo-keywords-1))
8075 (car org-todo-keywords-1))
8076 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
8078 (defun org-fast-todo-selection ()
8079 "Fast TODO keyword selection with single keys.
8080 Returns the new TODO keyword, or nil if no state change should occur."
8081 (let* ((fulltable org-todo-key-alist)
8082 (done-keywords org-done-keywords) ;; needed for the faces.
8083 (maxlen (apply 'max (mapcar
8084 (lambda (x)
8085 (if (stringp (car x)) (string-width (car x)) 0))
8086 fulltable)))
8087 (expert nil)
8088 (fwidth (+ maxlen 3 1 3))
8089 (ncol (/ (- (window-width) 4) fwidth))
8090 tg cnt e c tbl
8091 groups ingroup)
8092 (save-window-excursion
8093 (if expert
8094 (set-buffer (get-buffer-create " *Org todo*"))
8095 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
8096 (erase-buffer)
8097 (org-set-local 'org-done-keywords done-keywords)
8098 (setq tbl fulltable cnt 0)
8099 (while (setq e (pop tbl))
8100 (cond
8101 ((equal e '(:startgroup))
8102 (push '() groups) (setq ingroup t)
8103 (when (not (= cnt 0))
8104 (setq cnt 0)
8105 (insert "\n"))
8106 (insert "{ "))
8107 ((equal e '(:endgroup))
8108 (setq ingroup nil cnt 0)
8109 (insert "}\n"))
8111 (setq tg (car e) c (cdr e))
8112 (if ingroup (push tg (car groups)))
8113 (setq tg (org-add-props tg nil 'face
8114 (org-get-todo-face tg)))
8115 (if (and (= cnt 0) (not ingroup)) (insert " "))
8116 (insert "[" c "] " tg (make-string
8117 (- fwidth 4 (length tg)) ?\ ))
8118 (when (= (setq cnt (1+ cnt)) ncol)
8119 (insert "\n")
8120 (if ingroup (insert " "))
8121 (setq cnt 0)))))
8122 (insert "\n")
8123 (goto-char (point-min))
8124 (if (not expert) (org-fit-window-to-buffer))
8125 (message "[a-z..]:Set [SPC]:clear")
8126 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
8127 (cond
8128 ((or (= c ?\C-g)
8129 (and (= c ?q) (not (rassoc c fulltable))))
8130 (setq quit-flag t))
8131 ((= c ?\ ) nil)
8132 ((setq e (rassoc c fulltable) tg (car e))
8134 (t (setq quit-flag t))))))
8136 (defun org-entry-is-todo-p ()
8137 (member (org-get-todo-state) org-not-done-keywords))
8139 (defun org-entry-is-done-p ()
8140 (member (org-get-todo-state) org-done-keywords))
8142 (defun org-get-todo-state ()
8143 (save-excursion
8144 (org-back-to-heading t)
8145 (and (looking-at org-todo-line-regexp)
8146 (match-end 2)
8147 (match-string 2))))
8149 (defun org-at-date-range-p (&optional inactive-ok)
8150 "Is the cursor inside a date range?"
8151 (interactive)
8152 (save-excursion
8153 (catch 'exit
8154 (let ((pos (point)))
8155 (skip-chars-backward "^[<\r\n")
8156 (skip-chars-backward "<[")
8157 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8158 (>= (match-end 0) pos)
8159 (throw 'exit t))
8160 (skip-chars-backward "^<[\r\n")
8161 (skip-chars-backward "<[")
8162 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8163 (>= (match-end 0) pos)
8164 (throw 'exit t)))
8165 nil)))
8167 (defun org-get-repeat ()
8168 "Check if there is a deadline/schedule with repeater in this entry."
8169 (save-match-data
8170 (save-excursion
8171 (org-back-to-heading t)
8172 (if (re-search-forward
8173 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
8174 (match-string 1)))))
8176 (defvar org-last-changed-timestamp)
8177 (defvar org-last-inserted-timestamp)
8178 (defvar org-log-post-message)
8179 (defvar org-log-note-purpose)
8180 (defvar org-log-note-how)
8181 (defvar org-log-note-extra)
8182 (defun org-auto-repeat-maybe (done-word)
8183 "Check if the current headline contains a repeated deadline/schedule.
8184 If yes, set TODO state back to what it was and change the base date
8185 of repeating deadline/scheduled time stamps to new date.
8186 This function is run automatically after each state change to a DONE state."
8187 ;; last-state is dynamically scoped into this function
8188 (let* ((repeat (org-get-repeat))
8189 (aa (assoc last-state org-todo-kwd-alist))
8190 (interpret (nth 1 aa))
8191 (head (nth 2 aa))
8192 (whata '(("d" . day) ("m" . month) ("y" . year)))
8193 (msg "Entry repeats: ")
8194 (org-log-done nil)
8195 (org-todo-log-states nil)
8196 (nshiftmax 10) (nshift 0)
8197 re type n what ts mb0 time)
8198 (when repeat
8199 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
8200 (org-todo (if (eq interpret 'type) last-state head))
8201 (when org-log-repeat
8202 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
8203 (memq 'org-add-log-note post-command-hook))
8204 ;; OK, we are already setup for some record
8205 (if (eq org-log-repeat 'note)
8206 ;; make sure we take a note, not only a time stamp
8207 (setq org-log-note-how 'note))
8208 ;; Set up for taking a record
8209 (org-add-log-setup 'state (or done-word (car org-done-keywords))
8210 'findpos org-log-repeat)))
8211 (org-back-to-heading t)
8212 (org-add-planning-info nil nil 'closed)
8213 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
8214 org-deadline-time-regexp "\\)\\|\\("
8215 org-ts-regexp "\\)"))
8216 (while (re-search-forward
8217 re (save-excursion (outline-next-heading) (point)) t)
8218 (setq type (if (match-end 1) org-scheduled-string
8219 (if (match-end 3) org-deadline-string "Plain:"))
8220 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0)))
8221 mb0 (match-beginning 0))
8222 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
8223 (setq n (string-to-number (match-string 2 ts))
8224 what (match-string 3 ts))
8225 (if (equal what "w") (setq n (* n 7) what "d"))
8226 ;; Preparation, see if we need to modify the start date for the change
8227 (when (match-end 1)
8228 (setq time (save-match-data (org-time-string-to-time ts)))
8229 (cond
8230 ((equal (match-string 1 ts) ".")
8231 ;; Shift starting date to today
8232 (org-timestamp-change
8233 (- (time-to-days (current-time)) (time-to-days time))
8234 'day))
8235 ((equal (match-string 1 ts) "+")
8236 (while (or (= nshift 0)
8237 (<= (time-to-days time) (time-to-days (current-time))))
8238 (when (= (incf nshift) nshiftmax)
8239 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
8240 (error "Abort")))
8241 (org-timestamp-change n (cdr (assoc what whata)))
8242 (org-at-timestamp-p t)
8243 (setq ts (match-string 1))
8244 (setq time (save-match-data (org-time-string-to-time ts))))
8245 (org-timestamp-change (- n) (cdr (assoc what whata)))
8246 ;; rematch, so that we have everything in place for the real shift
8247 (org-at-timestamp-p t)
8248 (setq ts (match-string 1))
8249 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
8250 (org-timestamp-change n (cdr (assoc what whata)))
8251 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
8252 (setq org-log-post-message msg)
8253 (message "%s" msg))))
8255 (defun org-show-todo-tree (arg)
8256 "Make a compact tree which shows all headlines marked with TODO.
8257 The tree will show the lines where the regexp matches, and all higher
8258 headlines above the match.
8259 With a \\[universal-argument] prefix, also show the DONE entries.
8260 With a numeric prefix N, construct a sparse tree for the Nth element
8261 of `org-todo-keywords-1'."
8262 (interactive "P")
8263 (let ((case-fold-search nil)
8264 (kwd-re
8265 (cond ((null arg) org-not-done-regexp)
8266 ((equal arg '(4))
8267 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
8268 (mapcar 'list org-todo-keywords-1))))
8269 (concat "\\("
8270 (mapconcat 'identity (org-split-string kwd "|") "\\|")
8271 "\\)\\>")))
8272 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
8273 (regexp-quote (nth (1- (prefix-numeric-value arg))
8274 org-todo-keywords-1)))
8275 (t (error "Invalid prefix argument: %s" arg)))))
8276 (message "%d TODO entries found"
8277 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
8279 (defun org-deadline (&optional remove time)
8280 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
8281 With argument REMOVE, remove any deadline from the item.
8282 When TIME is set, it should be an internal time specification, and the
8283 scheduling will use the corresponding date."
8284 (interactive "P")
8285 (if remove
8286 (progn
8287 (org-remove-timestamp-with-keyword org-deadline-string)
8288 (message "Item no longer has a deadline."))
8289 (if (org-get-repeat)
8290 (error "Cannot change deadline on task with repeater, please do that by hand")
8291 (org-add-planning-info 'deadline time 'closed)
8292 (message "Deadline on %s" org-last-inserted-timestamp))))
8294 (defun org-schedule (&optional remove time)
8295 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
8296 With argument REMOVE, remove any scheduling date from the item.
8297 When TIME is set, it should be an internal time specification, and the
8298 scheduling will use the corresponding date."
8299 (interactive "P")
8300 (if remove
8301 (progn
8302 (org-remove-timestamp-with-keyword org-scheduled-string)
8303 (message "Item is no longer scheduled."))
8304 (if (org-get-repeat)
8305 (error "Cannot reschedule task with repeater, please do that by hand")
8306 (org-add-planning-info 'scheduled time 'closed)
8307 (message "Scheduled to %s" org-last-inserted-timestamp))))
8309 (defun org-remove-timestamp-with-keyword (keyword)
8310 "Remove all time stamps with KEYWORD in the current entry."
8311 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
8312 beg)
8313 (save-excursion
8314 (org-back-to-heading t)
8315 (setq beg (point))
8316 (org-end-of-subtree t t)
8317 (while (re-search-backward re beg t)
8318 (replace-match "")
8319 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
8320 (equal (char-before) ?\ ))
8321 (backward-delete-char 1)
8322 (if (string-match "^[ \t]*$" (buffer-substring
8323 (point-at-bol) (point-at-eol)))
8324 (delete-region (point-at-bol)
8325 (min (point-max) (1+ (point-at-eol))))))))))
8327 (defun org-add-planning-info (what &optional time &rest remove)
8328 "Insert new timestamp with keyword in the line directly after the headline.
8329 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
8330 If non is given, the user is prompted for a date.
8331 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
8332 be removed."
8333 (interactive)
8334 (let (org-time-was-given org-end-time-was-given ts
8335 end default-time default-input)
8337 (when (and (not time) (memq what '(scheduled deadline)))
8338 ;; Try to get a default date/time from existing timestamp
8339 (save-excursion
8340 (org-back-to-heading t)
8341 (setq end (save-excursion (outline-next-heading) (point)))
8342 (when (re-search-forward (if (eq what 'scheduled)
8343 org-scheduled-time-regexp
8344 org-deadline-time-regexp)
8345 end t)
8346 (setq ts (match-string 1)
8347 default-time
8348 (apply 'encode-time (org-parse-time-string ts))
8349 default-input (and ts (org-get-compact-tod ts))))))
8350 (when what
8351 ;; If necessary, get the time from the user
8352 (setq time (or time (org-read-date nil 'to-time nil nil
8353 default-time default-input))))
8355 (when (and org-insert-labeled-timestamps-at-point
8356 (member what '(scheduled deadline)))
8357 (insert
8358 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
8359 (org-insert-time-stamp time org-time-was-given
8360 nil nil nil (list org-end-time-was-given))
8361 (setq what nil))
8362 (save-excursion
8363 (save-restriction
8364 (let (col list elt ts buffer-invisibility-spec)
8365 (org-back-to-heading t)
8366 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
8367 (goto-char (match-end 1))
8368 (setq col (current-column))
8369 (goto-char (match-end 0))
8370 (if (eobp) (insert "\n") (forward-char 1))
8371 (if (and (not (looking-at outline-regexp))
8372 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
8373 "[^\r\n]*"))
8374 (not (equal (match-string 1) org-clock-string)))
8375 (narrow-to-region (match-beginning 0) (match-end 0))
8376 (insert-before-markers "\n")
8377 (backward-char 1)
8378 (narrow-to-region (point) (point))
8379 (and org-adapt-indentation (org-indent-to-column col)))
8380 ;; Check if we have to remove something.
8381 (setq list (cons what remove))
8382 (while list
8383 (setq elt (pop list))
8384 (goto-char (point-min))
8385 (when (or (and (eq elt 'scheduled)
8386 (re-search-forward org-scheduled-time-regexp nil t))
8387 (and (eq elt 'deadline)
8388 (re-search-forward org-deadline-time-regexp nil t))
8389 (and (eq elt 'closed)
8390 (re-search-forward org-closed-time-regexp nil t)))
8391 (replace-match "")
8392 (if (looking-at "--+<[^>]+>") (replace-match ""))
8393 (if (looking-at " +") (replace-match ""))))
8394 (goto-char (point-max))
8395 (when what
8396 (insert
8397 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
8398 (cond ((eq what 'scheduled) org-scheduled-string)
8399 ((eq what 'deadline) org-deadline-string)
8400 ((eq what 'closed) org-closed-string))
8401 " ")
8402 (setq ts (org-insert-time-stamp
8403 time
8404 (or org-time-was-given
8405 (and (eq what 'closed) org-log-done-with-time))
8406 (eq what 'closed)
8407 nil nil (list org-end-time-was-given)))
8408 (end-of-line 1))
8409 (goto-char (point-min))
8410 (widen)
8411 (if (and (looking-at "[ \t]+\n")
8412 (equal (char-before) ?\n))
8413 (delete-region (1- (point)) (point-at-eol)))
8414 ts)))))
8416 (defvar org-log-note-marker (make-marker))
8417 (defvar org-log-note-purpose nil)
8418 (defvar org-log-note-state nil)
8419 (defvar org-log-note-how nil)
8420 (defvar org-log-note-extra nil)
8421 (defvar org-log-note-window-configuration nil)
8422 (defvar org-log-note-return-to (make-marker))
8423 (defvar org-log-post-message nil
8424 "Message to be displayed after a log note has been stored.
8425 The auto-repeater uses this.")
8427 (defun org-add-note ()
8428 "Add a note to the current entry.
8429 This is done in the same way as adding a state change note."
8430 (interactive)
8431 (org-add-log-setup 'note nil 'findpos nil))
8433 (defvar org-property-end-re)
8434 (defun org-add-log-setup (&optional purpose state findpos how &optional extra)
8435 "Set up the post command hook to take a note.
8436 If this is about to TODO state change, the new state is expected in STATE.
8437 When FINDPOS is non-nil, find the correct position for the note in
8438 the current entry. If not, assume that it can be inserted at point.
8439 HOW is an indicator what kind of note should be created.
8440 EXTRA is additional text that will be inserted into the notes buffer."
8441 (save-restriction
8442 (save-excursion
8443 (when findpos
8444 (org-back-to-heading t)
8445 (narrow-to-region (point) (save-excursion
8446 (outline-next-heading) (point)))
8447 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
8448 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
8449 "[^\r\n]*\\)?"))
8450 (goto-char (match-end 0))
8451 (when (and org-log-state-notes-insert-after-drawers
8452 (save-excursion
8453 (forward-line) (looking-at org-drawer-regexp)))
8454 (progn (forward-line)
8455 (while (looking-at org-drawer-regexp)
8456 (goto-char (match-end 0))
8457 (re-search-forward org-property-end-re (point-max) t)
8458 (forward-line))
8459 (forward-line -1)))
8460 (unless org-log-states-order-reversed
8461 (and (= (char-after) ?\n) (forward-char 1))
8462 (org-skip-over-state-notes)
8463 (skip-chars-backward " \t\n\r")))
8464 (move-marker org-log-note-marker (point))
8465 (setq org-log-note-purpose purpose
8466 org-log-note-state state
8467 org-log-note-how how
8468 org-log-note-extra extra)
8469 (add-hook 'post-command-hook 'org-add-log-note 'append))))
8471 (defun org-skip-over-state-notes ()
8472 "Skip past the list of State notes in an entry."
8473 (if (looking-at "\n[ \t]*- State") (forward-char 1))
8474 (while (looking-at "[ \t]*- State")
8475 (condition-case nil
8476 (org-next-item)
8477 (error (org-end-of-item)))))
8479 (defun org-add-log-note (&optional purpose)
8480 "Pop up a window for taking a note, and add this note later at point."
8481 (remove-hook 'post-command-hook 'org-add-log-note)
8482 (setq org-log-note-window-configuration (current-window-configuration))
8483 (delete-other-windows)
8484 (move-marker org-log-note-return-to (point))
8485 (switch-to-buffer (marker-buffer org-log-note-marker))
8486 (goto-char org-log-note-marker)
8487 (org-switch-to-buffer-other-window "*Org Note*")
8488 (erase-buffer)
8489 (if (memq org-log-note-how '(time state))
8490 (let (current-prefix-arg) (org-store-log-note))
8491 (let ((org-inhibit-startup t)) (org-mode))
8492 (insert (format "# Insert note for %s.
8493 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
8494 (cond
8495 ((eq org-log-note-purpose 'clock-out) "stopped clock")
8496 ((eq org-log-note-purpose 'done) "closed todo item")
8497 ((eq org-log-note-purpose 'state)
8498 (format "state change to \"%s\"" org-log-note-state))
8499 ((eq org-log-note-purpose 'note)
8500 "this entry")
8501 (t (error "This should not happen")))))
8502 (if org-log-note-extra (insert org-log-note-extra))
8503 (org-set-local 'org-finish-function 'org-store-log-note)))
8505 (defvar org-note-abort nil) ; dynamically scoped
8506 (defun org-store-log-note ()
8507 "Finish taking a log note, and insert it to where it belongs."
8508 (let ((txt (buffer-string))
8509 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
8510 lines ind)
8511 (kill-buffer (current-buffer))
8512 (while (string-match "\\`#.*\n[ \t\n]*" txt)
8513 (setq txt (replace-match "" t t txt)))
8514 (if (string-match "\\s-+\\'" txt)
8515 (setq txt (replace-match "" t t txt)))
8516 (setq lines (org-split-string txt "\n"))
8517 (when (and note (string-match "\\S-" note))
8518 (setq note
8519 (org-replace-escapes
8520 note
8521 (list (cons "%u" (user-login-name))
8522 (cons "%U" user-full-name)
8523 (cons "%t" (format-time-string
8524 (org-time-stamp-format 'long 'inactive)
8525 (current-time)))
8526 (cons "%s" (if org-log-note-state
8527 (concat "\"" org-log-note-state "\"")
8528 "")))))
8529 (if lines (setq note (concat note " \\\\")))
8530 (push note lines))
8531 (when (or current-prefix-arg org-note-abort) (setq lines nil))
8532 (when lines
8533 (save-excursion
8534 (set-buffer (marker-buffer org-log-note-marker))
8535 (save-excursion
8536 (goto-char org-log-note-marker)
8537 (move-marker org-log-note-marker nil)
8538 (end-of-line 1)
8539 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
8540 (indent-relative nil)
8541 (insert "- " (pop lines))
8542 (org-indent-line-function)
8543 (beginning-of-line 1)
8544 (looking-at "[ \t]*")
8545 (setq ind (concat (match-string 0) " "))
8546 (end-of-line 1)
8547 (while lines (insert "\n" ind (pop lines)))))))
8548 (set-window-configuration org-log-note-window-configuration)
8549 (with-current-buffer (marker-buffer org-log-note-return-to)
8550 (goto-char org-log-note-return-to))
8551 (move-marker org-log-note-return-to nil)
8552 (and org-log-post-message (message "%s" org-log-post-message)))
8554 (defun org-sparse-tree (&optional arg)
8555 "Create a sparse tree, prompt for the details.
8556 This command can create sparse trees. You first need to select the type
8557 of match used to create the tree:
8559 t Show entries with a specific TODO keyword.
8560 T Show entries selected by a tags match.
8561 p Enter a property name and its value (both with completion on existing
8562 names/values) and show entries with that property.
8563 r Show entries matching a regular expression
8564 d Show deadlines due within `org-deadline-warning-days'."
8565 (interactive "P")
8566 (let (ans kwd value)
8567 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
8568 (setq ans (read-char-exclusive))
8569 (cond
8570 ((equal ans ?d)
8571 (call-interactively 'org-check-deadlines))
8572 ((equal ans ?b)
8573 (call-interactively 'org-check-before-date))
8574 ((equal ans ?t)
8575 (org-show-todo-tree '(4)))
8576 ((equal ans ?T)
8577 (call-interactively 'org-tags-sparse-tree))
8578 ((member ans '(?p ?P))
8579 (setq kwd (completing-read "Property: "
8580 (mapcar 'list (org-buffer-property-keys))))
8581 (setq value (completing-read "Value: "
8582 (mapcar 'list (org-property-values kwd))))
8583 (unless (string-match "\\`{.*}\\'" value)
8584 (setq value (concat "\"" value "\"")))
8585 (org-tags-sparse-tree arg (concat kwd "=" value)))
8586 ((member ans '(?r ?R ?/))
8587 (call-interactively 'org-occur))
8588 (t (error "No such sparse tree command \"%c\"" ans)))))
8590 (defvar org-occur-highlights nil
8591 "List of overlays used for occur matches.")
8592 (make-variable-buffer-local 'org-occur-highlights)
8593 (defvar org-occur-parameters nil
8594 "Parameters of the active org-occur calls.
8595 This is a list, each call to org-occur pushes as cons cell,
8596 containing the regular expression and the callback, onto the list.
8597 The list can contain several entries if `org-occur' has been called
8598 several time with the KEEP-PREVIOUS argument. Otherwise, this list
8599 will only contain one set of parameters. When the highlights are
8600 removed (for example with `C-c C-c', or with the next edit (depending
8601 on `org-remove-highlights-with-change'), this variable is emptied
8602 as well.")
8603 (make-variable-buffer-local 'org-occur-parameters)
8605 (defun org-occur (regexp &optional keep-previous callback)
8606 "Make a compact tree which shows all matches of REGEXP.
8607 The tree will show the lines where the regexp matches, and all higher
8608 headlines above the match. It will also show the heading after the match,
8609 to make sure editing the matching entry is easy.
8610 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
8611 call to `org-occur' will be kept, to allow stacking of calls to this
8612 command.
8613 If CALLBACK is non-nil, it is a function which is called to confirm
8614 that the match should indeed be shown."
8615 (interactive "sRegexp: \nP")
8616 (unless keep-previous
8617 (org-remove-occur-highlights nil nil t))
8618 (push (cons regexp callback) org-occur-parameters)
8619 (let ((cnt 0))
8620 (save-excursion
8621 (goto-char (point-min))
8622 (if (or (not keep-previous) ; do not want to keep
8623 (not org-occur-highlights)) ; no previous matches
8624 ;; hide everything
8625 (org-overview))
8626 (while (re-search-forward regexp nil t)
8627 (when (or (not callback)
8628 (save-match-data (funcall callback)))
8629 (setq cnt (1+ cnt))
8630 (when org-highlight-sparse-tree-matches
8631 (org-highlight-new-match (match-beginning 0) (match-end 0)))
8632 (org-show-context 'occur-tree))))
8633 (when org-remove-highlights-with-change
8634 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
8635 nil 'local))
8636 (unless org-sparse-tree-open-archived-trees
8637 (org-hide-archived-subtrees (point-min) (point-max)))
8638 (run-hooks 'org-occur-hook)
8639 (if (interactive-p)
8640 (message "%d match(es) for regexp %s" cnt regexp))
8641 cnt))
8643 (defun org-show-context (&optional key)
8644 "Make sure point and context and visible.
8645 How much context is shown depends upon the variables
8646 `org-show-hierarchy-above', `org-show-following-heading'. and
8647 `org-show-siblings'."
8648 (let ((heading-p (org-on-heading-p t))
8649 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
8650 (following-p (org-get-alist-option org-show-following-heading key))
8651 (entry-p (org-get-alist-option org-show-entry-below key))
8652 (siblings-p (org-get-alist-option org-show-siblings key)))
8653 (catch 'exit
8654 ;; Show heading or entry text
8655 (if (and heading-p (not entry-p))
8656 (org-flag-heading nil) ; only show the heading
8657 (and (or entry-p (org-invisible-p) (org-invisible-p2))
8658 (org-show-hidden-entry))) ; show entire entry
8659 (when following-p
8660 ;; Show next sibling, or heading below text
8661 (save-excursion
8662 (and (if heading-p (org-goto-sibling) (outline-next-heading))
8663 (org-flag-heading nil))))
8664 (when siblings-p (org-show-siblings))
8665 (when hierarchy-p
8666 ;; show all higher headings, possibly with siblings
8667 (save-excursion
8668 (while (and (condition-case nil
8669 (progn (org-up-heading-all 1) t)
8670 (error nil))
8671 (not (bobp)))
8672 (org-flag-heading nil)
8673 (when siblings-p (org-show-siblings))))))))
8675 (defun org-reveal (&optional siblings)
8676 "Show current entry, hierarchy above it, and the following headline.
8677 This can be used to show a consistent set of context around locations
8678 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
8679 not t for the search context.
8681 With optional argument SIBLINGS, on each level of the hierarchy all
8682 siblings are shown. This repairs the tree structure to what it would
8683 look like when opened with hierarchical calls to `org-cycle'."
8684 (interactive "P")
8685 (let ((org-show-hierarchy-above t)
8686 (org-show-following-heading t)
8687 (org-show-siblings (if siblings t org-show-siblings)))
8688 (org-show-context nil)))
8690 (defun org-highlight-new-match (beg end)
8691 "Highlight from BEG to END and mark the highlight is an occur headline."
8692 (let ((ov (org-make-overlay beg end)))
8693 (org-overlay-put ov 'face 'secondary-selection)
8694 (push ov org-occur-highlights)))
8696 (defun org-remove-occur-highlights (&optional beg end noremove)
8697 "Remove the occur highlights from the buffer.
8698 BEG and END are ignored. If NOREMOVE is nil, remove this function
8699 from the `before-change-functions' in the current buffer."
8700 (interactive)
8701 (unless org-inhibit-highlight-removal
8702 (mapc 'org-delete-overlay org-occur-highlights)
8703 (setq org-occur-highlights nil)
8704 (setq org-occur-parameters nil)
8705 (unless noremove
8706 (remove-hook 'before-change-functions
8707 'org-remove-occur-highlights 'local))))
8709 ;;;; Priorities
8711 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
8712 "Regular expression matching the priority indicator.")
8714 (defvar org-remove-priority-next-time nil)
8716 (defun org-priority-up ()
8717 "Increase the priority of the current item."
8718 (interactive)
8719 (org-priority 'up))
8721 (defun org-priority-down ()
8722 "Decrease the priority of the current item."
8723 (interactive)
8724 (org-priority 'down))
8726 (defun org-priority (&optional action)
8727 "Change the priority of an item by ARG.
8728 ACTION can be `set', `up', `down', or a character."
8729 (interactive)
8730 (setq action (or action 'set))
8731 (let (current new news have remove)
8732 (save-excursion
8733 (org-back-to-heading)
8734 (if (looking-at org-priority-regexp)
8735 (setq current (string-to-char (match-string 2))
8736 have t)
8737 (setq current org-default-priority))
8738 (cond
8739 ((or (eq action 'set)
8740 (if (featurep 'xemacs) (characterp action) (integerp action)))
8741 (if (not (eq action 'set))
8742 (setq new action)
8743 (message "Priority %c-%c, SPC to remove: "
8744 org-highest-priority org-lowest-priority)
8745 (setq new (read-char-exclusive)))
8746 (if (and (= (upcase org-highest-priority) org-highest-priority)
8747 (= (upcase org-lowest-priority) org-lowest-priority))
8748 (setq new (upcase new)))
8749 (cond ((equal new ?\ ) (setq remove t))
8750 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
8751 (error "Priority must be between `%c' and `%c'"
8752 org-highest-priority org-lowest-priority))))
8753 ((eq action 'up)
8754 (if (and (not have) (eq last-command this-command))
8755 (setq new org-lowest-priority)
8756 (setq new (if (and org-priority-start-cycle-with-default (not have))
8757 org-default-priority (1- current)))))
8758 ((eq action 'down)
8759 (if (and (not have) (eq last-command this-command))
8760 (setq new org-highest-priority)
8761 (setq new (if (and org-priority-start-cycle-with-default (not have))
8762 org-default-priority (1+ current)))))
8763 (t (error "Invalid action")))
8764 (if (or (< (upcase new) org-highest-priority)
8765 (> (upcase new) org-lowest-priority))
8766 (setq remove t))
8767 (setq news (format "%c" new))
8768 (if have
8769 (if remove
8770 (replace-match "" t t nil 1)
8771 (replace-match news t t nil 2))
8772 (if remove
8773 (error "No priority cookie found in line")
8774 (looking-at org-todo-line-regexp)
8775 (if (match-end 2)
8776 (progn
8777 (goto-char (match-end 2))
8778 (insert " [#" news "]"))
8779 (goto-char (match-beginning 3))
8780 (insert "[#" news "] ")))))
8781 (org-preserve-lc (org-set-tags nil 'align))
8782 (if remove
8783 (message "Priority removed")
8784 (message "Priority of current item set to %s" news))))
8787 (defun org-get-priority (s)
8788 "Find priority cookie and return priority."
8789 (save-match-data
8790 (if (not (string-match org-priority-regexp s))
8791 (* 1000 (- org-lowest-priority org-default-priority))
8792 (* 1000 (- org-lowest-priority
8793 (string-to-char (match-string 2 s)))))))
8795 ;;;; Tags
8797 (defvar org-agenda-archives-mode)
8798 (defun org-scan-tags (action matcher &optional todo-only)
8799 "Scan headline tags with inheritance and produce output ACTION.
8801 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
8802 or `agenda' to produce an entry list for an agenda view. It can also be
8803 a Lisp form or a function that should be called at each matched headline, in
8804 this case the return value is a list of all return values from these calls.
8806 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
8807 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
8808 only lines with a TODO keyword are included in the output."
8809 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
8810 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
8811 (org-re
8812 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
8813 (props (list 'face 'default
8814 'done-face 'org-done
8815 'undone-face 'default
8816 'mouse-face 'highlight
8817 'org-not-done-regexp org-not-done-regexp
8818 'org-todo-regexp org-todo-regexp
8819 'keymap org-agenda-keymap
8820 'help-echo
8821 (format "mouse-2 or RET jump to org file %s"
8822 (abbreviate-file-name
8823 (or (buffer-file-name (buffer-base-buffer))
8824 (buffer-name (buffer-base-buffer)))))))
8825 (case-fold-search nil)
8826 lspos tags tags-list
8827 (tags-alist (list (cons 0 (mapcar 'downcase org-file-tags))))
8828 (llast 0) rtn rtn1 level category i txt
8829 todo marker entry priority)
8830 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
8831 (setq action (list 'lambda nil action)))
8832 (save-excursion
8833 (goto-char (point-min))
8834 (when (eq action 'sparse-tree)
8835 (org-overview)
8836 (org-remove-occur-highlights))
8837 (while (re-search-forward re nil t)
8838 (catch :skip
8839 (setq todo (if (match-end 1) (match-string 2))
8840 tags (if (match-end 4) (match-string 4)))
8841 (goto-char (setq lspos (1+ (match-beginning 0))))
8842 (setq level (org-reduced-level (funcall outline-level))
8843 category (org-get-category))
8844 (setq i llast llast level)
8845 ;; remove tag lists from same and sublevels
8846 (while (>= i level)
8847 (when (setq entry (assoc i tags-alist))
8848 (setq tags-alist (delete entry tags-alist)))
8849 (setq i (1- i)))
8850 ;; add the next tags
8851 (when tags
8852 (setq tags (mapcar 'downcase (org-split-string tags ":"))
8853 tags-alist
8854 (cons (cons level tags) tags-alist)))
8855 ;; compile tags for current headline
8856 (setq tags-list
8857 (if org-use-tag-inheritance
8858 (apply 'append (mapcar 'cdr tags-alist))
8859 tags))
8860 (when (and tags org-use-tag-inheritance
8861 (not (eq t org-use-tag-inheritance)))
8862 ;; selective inheritance, remove uninherited ones
8863 (setcdr (car tags-alist)
8864 (org-remove-uniherited-tags (cdar tags-alist))))
8865 (when (and (or (not todo-only) (member todo org-not-done-keywords))
8866 (let ((case-fold-search t)) (eval matcher))
8868 (not (member org-archive-tag tags-list))
8869 ;; we have an archive tag, should we use this anyway?
8870 (or (not org-agenda-skip-archived-trees)
8871 (and (eq action 'agenda) org-agenda-archives-mode))))
8872 (unless (eq action 'sparse-tree) (org-agenda-skip))
8874 ;; select this headline
8876 (cond
8877 ((eq action 'sparse-tree)
8878 (and org-highlight-sparse-tree-matches
8879 (org-get-heading) (match-end 0)
8880 (org-highlight-new-match
8881 (match-beginning 0) (match-beginning 1)))
8882 (org-show-context 'tags-tree))
8883 ((eq action 'agenda)
8884 (setq txt (org-format-agenda-item
8886 (concat
8887 (if org-tags-match-list-sublevels
8888 (make-string (1- level) ?.) "")
8889 (org-get-heading))
8890 category tags-list)
8891 priority (org-get-priority txt))
8892 (goto-char lspos)
8893 (setq marker (org-agenda-new-marker))
8894 (org-add-props txt props
8895 'org-marker marker 'org-hd-marker marker 'org-category category
8896 'priority priority 'type "tagsmatch")
8897 (push txt rtn))
8898 ((functionp action)
8899 (save-excursion
8900 (setq rtn1 (funcall action))
8901 (push rtn1 rtn))
8902 (goto-char (point-at-eol)))
8903 (t (error "Invalid action")))
8905 ;; if we are to skip sublevels, jump to end of subtree
8906 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
8907 (when (and (eq action 'sparse-tree)
8908 (not org-sparse-tree-open-archived-trees))
8909 (org-hide-archived-subtrees (point-min) (point-max)))
8910 (nreverse rtn)))
8912 (defun org-remove-uniherited-tags (tags)
8913 "Remove all tags that are not inherited from the list TAGS."
8914 (cond
8915 ((eq org-use-tag-inheritance t) tags)
8916 ((not org-use-tag-inheritance) nil)
8917 ((stringp org-use-tag-inheritance)
8918 (delq nil (mapcar
8919 (lambda (x) (if (string-match org-use-tag-inheritance x) x nil))
8920 tags)))
8921 ((listp org-use-tag-inheritance)
8922 (delq nil (mapcar
8923 (lambda (x) (if (member x org-use-tag-inheritance) x nil))
8924 tags)))))
8926 (defvar todo-only) ;; dynamically scoped
8928 (defun org-tags-sparse-tree (&optional todo-only match)
8929 "Create a sparse tree according to tags string MATCH.
8930 MATCH can contain positive and negative selection of tags, like
8931 \"+WORK+URGENT-WITHBOSS\".
8932 If optional argument TODO_ONLY is non-nil, only select lines that are
8933 also TODO lines."
8934 (interactive "P")
8935 (org-prepare-agenda-buffers (list (current-buffer)))
8936 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
8938 (defvar org-cached-props nil)
8939 (defun org-cached-entry-get (pom property)
8940 (if (or (eq t org-use-property-inheritance)
8941 (and (stringp org-use-property-inheritance)
8942 (string-match org-use-property-inheritance property))
8943 (and (listp org-use-property-inheritance)
8944 (member property org-use-property-inheritance)))
8945 ;; Caching is not possible, check it directly
8946 (org-entry-get pom property 'inherit)
8947 ;; Get all properties, so that we can do complicated checks easily
8948 (cdr (assoc property (or org-cached-props
8949 (setq org-cached-props
8950 (org-entry-properties pom)))))))
8952 (defun org-global-tags-completion-table (&optional files)
8953 "Return the list of all tags in all agenda buffer/files."
8954 (save-excursion
8955 (org-uniquify
8956 (delq nil
8957 (apply 'append
8958 (mapcar
8959 (lambda (file)
8960 (set-buffer (find-file-noselect file))
8961 (append (org-get-buffer-tags)
8962 (mapcar (lambda (x) (if (stringp (car-safe x))
8963 (list (car-safe x)) nil))
8964 org-tag-alist)))
8965 (if (and files (car files))
8966 files
8967 (org-agenda-files))))))))
8969 (defun org-make-tags-matcher (match)
8970 "Create the TAGS//TODO matcher form for the selection string MATCH."
8971 ;; todo-only is scoped dynamically into this function, and the function
8972 ;; may change it it the matcher asksk for it.
8973 (unless match
8974 ;; Get a new match request, with completion
8975 (let ((org-last-tags-completion-table
8976 (org-global-tags-completion-table)))
8977 (setq match (completing-read
8978 "Match: " 'org-tags-completion-function nil nil nil
8979 'org-tags-history))))
8981 ;; Parse the string and create a lisp form
8982 (let ((match0 match)
8983 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
8984 minus tag mm
8985 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
8986 orterms term orlist re-p str-p level-p level-op time-p
8987 prop-p pn pv po cat-p gv rest)
8988 (if (string-match "/+" match)
8989 ;; match contains also a todo-matching request
8990 (progn
8991 (setq tagsmatch (substring match 0 (match-beginning 0))
8992 todomatch (substring match (match-end 0)))
8993 (if (string-match "^!" todomatch)
8994 (setq todo-only t todomatch (substring todomatch 1)))
8995 (if (string-match "^\\s-*$" todomatch)
8996 (setq todomatch nil)))
8997 ;; only matching tags
8998 (setq tagsmatch match todomatch nil))
9000 ;; Make the tags matcher
9001 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
9002 (setq tagsmatcher t)
9003 (setq orterms (org-split-string tagsmatch "|") orlist nil)
9004 (while (setq term (pop orterms))
9005 (while (and (equal (substring term -1) "\\") orterms)
9006 (setq term (concat term "|" (pop orterms)))) ; repair bad split
9007 (while (string-match re term)
9008 (setq rest (substring term (match-end 0))
9009 minus (and (match-end 1)
9010 (equal (match-string 1 term) "-"))
9011 tag (match-string 2 term)
9012 re-p (equal (string-to-char tag) ?{)
9013 level-p (match-end 4)
9014 prop-p (match-end 5)
9015 mm (cond
9016 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
9017 (level-p
9018 (setq level-op (org-op-to-function (match-string 3 term)))
9019 `(,level-op level ,(string-to-number
9020 (match-string 4 term))))
9021 (prop-p
9022 (setq pn (match-string 5 term)
9023 po (match-string 6 term)
9024 pv (match-string 7 term)
9025 cat-p (equal pn "CATEGORY")
9026 re-p (equal (string-to-char pv) ?{)
9027 str-p (equal (string-to-char pv) ?\")
9028 time-p (save-match-data
9029 (string-match "^\"[[<].*[]>]\"$" pv))
9030 pv (if (or re-p str-p) (substring pv 1 -1) pv))
9031 (if time-p (setq pv (org-matcher-time pv)))
9032 (setq po (org-op-to-function po (if time-p 'time str-p)))
9033 (cond
9034 ((equal pn "CATEGORY")
9035 (setq gv '(get-text-property (point) 'org-category)))
9036 ((equal pn "TODO")
9037 (setq gv 'todo))
9039 (setq gv `(org-cached-entry-get nil ,pn))))
9040 (if re-p
9041 (if (eq po 'org<>)
9042 `(not (string-match ,pv (or ,gv "")))
9043 `(string-match ,pv (or ,gv "")))
9044 (if str-p
9045 `(,po (or ,gv "") ,pv)
9046 `(,po (string-to-number (or ,gv ""))
9047 ,(string-to-number pv) ))))
9048 (t `(member ,(downcase tag) tags-list)))
9049 mm (if minus (list 'not mm) mm)
9050 term rest)
9051 (push mm tagsmatcher))
9052 (push (if (> (length tagsmatcher) 1)
9053 (cons 'and tagsmatcher)
9054 (car tagsmatcher))
9055 orlist)
9056 (setq tagsmatcher nil))
9057 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
9058 (setq tagsmatcher
9059 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
9060 ;; Make the todo matcher
9061 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
9062 (setq todomatcher t)
9063 (setq orterms (org-split-string todomatch "|") orlist nil)
9064 (while (setq term (pop orterms))
9065 (while (string-match re term)
9066 (setq minus (and (match-end 1)
9067 (equal (match-string 1 term) "-"))
9068 kwd (match-string 2 term)
9069 re-p (equal (string-to-char kwd) ?{)
9070 term (substring term (match-end 0))
9071 mm (if re-p
9072 `(string-match ,(substring kwd 1 -1) todo)
9073 (list 'equal 'todo kwd))
9074 mm (if minus (list 'not mm) mm))
9075 (push mm todomatcher))
9076 (push (if (> (length todomatcher) 1)
9077 (cons 'and todomatcher)
9078 (car todomatcher))
9079 orlist)
9080 (setq todomatcher nil))
9081 (setq todomatcher (if (> (length orlist) 1)
9082 (cons 'or orlist) (car orlist))))
9084 ;; Return the string and lisp forms of the matcher
9085 (setq matcher (if todomatcher
9086 (list 'and tagsmatcher todomatcher)
9087 tagsmatcher))
9088 (cons match0 matcher)))
9090 (defun org-op-to-function (op &optional stringp)
9091 "Turn an operator into the appropriate function."
9092 (setq op
9093 (cond
9094 ((equal op "<" ) '(< string< org-time<))
9095 ((equal op ">" ) '(> org-string> org-time>))
9096 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
9097 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
9098 ((member op '("=" "==")) '(= string= org-time=))
9099 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
9100 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
9102 (defun org<> (a b) (not (= a b)))
9103 (defun org-string<= (a b) (or (string= a b) (string< a b)))
9104 (defun org-string>= (a b) (not (string< a b)))
9105 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
9106 (defun org-string<> (a b) (not (string= a b)))
9107 (defun org-time= (a b) (= (org-2ft a) (org-2ft b)))
9108 (defun org-time< (a b) (< (org-2ft a) (org-2ft b)))
9109 (defun org-time<= (a b) (<= (org-2ft a) (org-2ft b)))
9110 (defun org-time> (a b) (> (org-2ft a) (org-2ft b)))
9111 (defun org-time>= (a b) (>= (org-2ft a) (org-2ft b)))
9112 (defun org-time<> (a b) (org<> (org-2ft a) (org-2ft b)))
9113 (defun org-2ft (s)
9114 "Convert S to a floating point time.
9115 If S is already a number, just return it. If it is a string, parse
9116 it as a time string and apply `float-time' to it. f S is nil, just return 0."
9117 (cond
9118 ((numberp s) s)
9119 ((stringp s)
9120 (condition-case nil
9121 (float-time (apply 'encode-time (org-parse-time-string s)))
9122 (error 0.)))
9123 (t 0.)))
9125 (defun org-matcher-time (s)
9126 (cond
9127 ((equal s "<now>") (float-time))
9128 ((equal s "<today>")
9129 (float-time (append '(0 0 0) (nthcdr 3 (decode-time)))))
9130 (t (org-2ft s))))
9132 (defun org-match-any-p (re list)
9133 "Does re match any element of list?"
9134 (setq list (mapcar (lambda (x) (string-match re x)) list))
9135 (delq nil list))
9137 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
9138 (defvar org-tags-overlay (org-make-overlay 1 1))
9139 (org-detach-overlay org-tags-overlay)
9141 (defun org-get-local-tags-at (&optional pos)
9142 "Get a list of tags defined in the current headline."
9143 (org-get-tags-at pos 'local))
9145 (defun org-get-local-tags ()
9146 "Get a list of tags defined in the current headline."
9147 (org-get-tags-at nil 'local))
9149 (defun org-get-tags-at (&optional pos local)
9150 "Get a list of all headline tags applicable at POS.
9151 POS defaults to point. If tags are inherited, the list contains
9152 the targets in the same sequence as the headlines appear, i.e.
9153 the tags of the current headline come last.
9154 When LOCAL is non-nil, only return tags from the current headline,
9155 ignore inherited ones."
9156 (interactive)
9157 (let (tags ltags lastpos parent)
9158 (save-excursion
9159 (save-restriction
9160 (widen)
9161 (goto-char (or pos (point)))
9162 (save-match-data
9163 (catch 'done
9164 (condition-case nil
9165 (progn
9166 (org-back-to-heading t)
9167 (while (not (equal lastpos (point)))
9168 (setq lastpos (point))
9169 (when (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
9170 (setq ltags (org-split-string
9171 (org-match-string-no-properties 1) ":"))
9172 (setq tags (append
9173 (if parent
9174 (org-remove-uniherited-tags ltags)
9175 ltags)
9176 tags)))
9177 (or org-use-tag-inheritance (throw 'done t))
9178 (if local (throw 'done t))
9179 (org-up-heading-all 1)
9180 (setq parent t)))
9181 (error nil)))))
9182 (append (org-remove-uniherited-tags org-file-tags) tags))))
9184 (defun org-toggle-tag (tag &optional onoff)
9185 "Toggle the tag TAG for the current line.
9186 If ONOFF is `on' or `off', don't toggle but set to this state."
9187 (unless (org-on-heading-p t) (error "Not on headling"))
9188 (let (res current)
9189 (save-excursion
9190 (beginning-of-line)
9191 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
9192 (point-at-eol) t)
9193 (progn
9194 (setq current (match-string 1))
9195 (replace-match ""))
9196 (setq current ""))
9197 (setq current (nreverse (org-split-string current ":")))
9198 (cond
9199 ((eq onoff 'on)
9200 (setq res t)
9201 (or (member tag current) (push tag current)))
9202 ((eq onoff 'off)
9203 (or (not (member tag current)) (setq current (delete tag current))))
9204 (t (if (member tag current)
9205 (setq current (delete tag current))
9206 (setq res t)
9207 (push tag current))))
9208 (end-of-line 1)
9209 (if current
9210 (progn
9211 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
9212 (org-set-tags nil t))
9213 (delete-horizontal-space))
9214 (run-hooks 'org-after-tags-change-hook))
9215 res))
9217 (defun org-align-tags-here (to-col)
9218 ;; Assumes that this is a headline
9219 (let ((pos (point)) (col (current-column)) ncol tags-l p)
9220 (beginning-of-line 1)
9221 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9222 (< pos (match-beginning 2)))
9223 (progn
9224 (setq tags-l (- (match-end 2) (match-beginning 2)))
9225 (goto-char (match-beginning 1))
9226 (insert " ")
9227 (delete-region (point) (1+ (match-beginning 2)))
9228 (setq ncol (max (1+ (current-column))
9229 (1+ col)
9230 (if (> to-col 0)
9231 to-col
9232 (- (abs to-col) tags-l))))
9233 (setq p (point))
9234 (insert (make-string (- ncol (current-column)) ?\ ))
9235 (setq ncol (current-column))
9236 (when indent-tabs-mode (tabify p (point-at-eol)))
9237 (org-move-to-column (min ncol col) t))
9238 (goto-char pos))))
9240 (defun org-set-tags-command (&optional arg just-align)
9241 "Call the set-tags command for the current entry."
9242 (interactive "P")
9243 (if (org-on-heading-p)
9244 (org-set-tags arg just-align)
9245 (save-excursion
9246 (org-back-to-heading t)
9247 (org-set-tags arg just-align))))
9249 (defun org-set-tags (&optional arg just-align)
9250 "Set the tags for the current headline.
9251 With prefix ARG, realign all tags in headings in the current buffer."
9252 (interactive "P")
9253 (let* ((re (concat "^" outline-regexp))
9254 (current (org-get-tags-string))
9255 (col (current-column))
9256 (org-setting-tags t)
9257 table current-tags inherited-tags ; computed below when needed
9258 tags p0 c0 c1 rpl)
9259 (if arg
9260 (save-excursion
9261 (goto-char (point-min))
9262 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
9263 (while (re-search-forward re nil t)
9264 (org-set-tags nil t)
9265 (end-of-line 1)))
9266 (message "All tags realigned to column %d" org-tags-column))
9267 (if just-align
9268 (setq tags current)
9269 ;; Get a new set of tags from the user
9270 (save-excursion
9271 (setq table (or org-tag-alist (org-get-buffer-tags))
9272 org-last-tags-completion-table table
9273 current-tags (org-split-string current ":")
9274 inherited-tags (nreverse
9275 (nthcdr (length current-tags)
9276 (nreverse (org-get-tags-at))))
9277 tags
9278 (if (or (eq t org-use-fast-tag-selection)
9279 (and org-use-fast-tag-selection
9280 (delq nil (mapcar 'cdr table))))
9281 (org-fast-tag-selection
9282 current-tags inherited-tags table
9283 (if org-fast-tag-selection-include-todo org-todo-key-alist))
9284 (let ((org-add-colon-after-tag-completion t))
9285 (org-trim
9286 (org-without-partial-completion
9287 (completing-read "Tags: " 'org-tags-completion-function
9288 nil nil current 'org-tags-history)))))))
9289 (while (string-match "[-+&]+" tags)
9290 ;; No boolean logic, just a list
9291 (setq tags (replace-match ":" t t tags))))
9293 (if (string-match "\\`[\t ]*\\'" tags)
9294 (setq tags "")
9295 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
9296 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
9298 ;; Insert new tags at the correct column
9299 (beginning-of-line 1)
9300 (cond
9301 ((and (equal current "") (equal tags "")))
9302 ((re-search-forward
9303 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
9304 (point-at-eol) t)
9305 (if (equal tags "")
9306 (setq rpl "")
9307 (goto-char (match-beginning 0))
9308 (setq c0 (current-column) p0 (point)
9309 c1 (max (1+ c0) (if (> org-tags-column 0)
9310 org-tags-column
9311 (- (- org-tags-column) (length tags))))
9312 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
9313 (replace-match rpl t t)
9314 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
9315 tags)
9316 (t (error "Tags alignment failed")))
9317 (org-move-to-column col)
9318 (unless just-align
9319 (run-hooks 'org-after-tags-change-hook)))))
9321 (defun org-change-tag-in-region (beg end tag off)
9322 "Add or remove TAG for each entry in the region.
9323 This works in the agenda, and also in an org-mode buffer."
9324 (interactive
9325 (list (region-beginning) (region-end)
9326 (let ((org-last-tags-completion-table
9327 (if (org-mode-p)
9328 (org-get-buffer-tags)
9329 (org-global-tags-completion-table))))
9330 (completing-read
9331 "Tag: " 'org-tags-completion-function nil nil nil
9332 'org-tags-history))
9333 (progn
9334 (message "[s]et or [r]emove? ")
9335 (equal (read-char-exclusive) ?r))))
9336 (if (fboundp 'deactivate-mark) (deactivate-mark))
9337 (let ((agendap (equal major-mode 'org-agenda-mode))
9338 l1 l2 m buf pos newhead (cnt 0))
9339 (goto-char end)
9340 (setq l2 (1- (org-current-line)))
9341 (goto-char beg)
9342 (setq l1 (org-current-line))
9343 (loop for l from l1 to l2 do
9344 (goto-line l)
9345 (setq m (get-text-property (point) 'org-hd-marker))
9346 (when (or (and (org-mode-p) (org-on-heading-p))
9347 (and agendap m))
9348 (setq buf (if agendap (marker-buffer m) (current-buffer))
9349 pos (if agendap m (point)))
9350 (with-current-buffer buf
9351 (save-excursion
9352 (save-restriction
9353 (goto-char pos)
9354 (setq cnt (1+ cnt))
9355 (org-toggle-tag tag (if off 'off 'on))
9356 (setq newhead (org-get-heading)))))
9357 (and agendap (org-agenda-change-all-lines newhead m))))
9358 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
9360 (defun org-tags-completion-function (string predicate &optional flag)
9361 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
9362 (confirm (lambda (x) (stringp (car x)))))
9363 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
9364 (setq s1 (match-string 1 string)
9365 s2 (match-string 2 string))
9366 (setq s1 "" s2 string))
9367 (cond
9368 ((eq flag nil)
9369 ;; try completion
9370 (setq rtn (try-completion s2 ctable confirm))
9371 (if (stringp rtn)
9372 (setq rtn
9373 (concat s1 s2 (substring rtn (length s2))
9374 (if (and org-add-colon-after-tag-completion
9375 (assoc rtn ctable))
9376 ":" ""))))
9377 rtn)
9378 ((eq flag t)
9379 ;; all-completions
9380 (all-completions s2 ctable confirm)
9382 ((eq flag 'lambda)
9383 ;; exact match?
9384 (assoc s2 ctable)))
9387 (defun org-fast-tag-insert (kwd tags face &optional end)
9388 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
9389 (insert (format "%-12s" (concat kwd ":"))
9390 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
9391 (or end "")))
9393 (defun org-fast-tag-show-exit (flag)
9394 (save-excursion
9395 (goto-line 3)
9396 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
9397 (replace-match ""))
9398 (when flag
9399 (end-of-line 1)
9400 (org-move-to-column (- (window-width) 19) t)
9401 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
9403 (defun org-set-current-tags-overlay (current prefix)
9404 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
9405 (if (featurep 'xemacs)
9406 (org-overlay-display org-tags-overlay (concat prefix s)
9407 'secondary-selection)
9408 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
9409 (org-overlay-display org-tags-overlay (concat prefix s)))))
9411 (defun org-fast-tag-selection (current inherited table &optional todo-table)
9412 "Fast tag selection with single keys.
9413 CURRENT is the current list of tags in the headline, INHERITED is the
9414 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
9415 possibly with grouping information. TODO-TABLE is a similar table with
9416 TODO keywords, should these have keys assigned to them.
9417 If the keys are nil, a-z are automatically assigned.
9418 Returns the new tags string, or nil to not change the current settings."
9419 (let* ((fulltable (append table todo-table))
9420 (maxlen (apply 'max (mapcar
9421 (lambda (x)
9422 (if (stringp (car x)) (string-width (car x)) 0))
9423 fulltable)))
9424 (buf (current-buffer))
9425 (expert (eq org-fast-tag-selection-single-key 'expert))
9426 (buffer-tags nil)
9427 (fwidth (+ maxlen 3 1 3))
9428 (ncol (/ (- (window-width) 4) fwidth))
9429 (i-face 'org-done)
9430 (c-face 'org-todo)
9431 tg cnt e c char c1 c2 ntable tbl rtn
9432 ov-start ov-end ov-prefix
9433 (exit-after-next org-fast-tag-selection-single-key)
9434 (done-keywords org-done-keywords)
9435 groups ingroup)
9436 (save-excursion
9437 (beginning-of-line 1)
9438 (if (looking-at
9439 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9440 (setq ov-start (match-beginning 1)
9441 ov-end (match-end 1)
9442 ov-prefix "")
9443 (setq ov-start (1- (point-at-eol))
9444 ov-end (1+ ov-start))
9445 (skip-chars-forward "^\n\r")
9446 (setq ov-prefix
9447 (concat
9448 (buffer-substring (1- (point)) (point))
9449 (if (> (current-column) org-tags-column)
9451 (make-string (- org-tags-column (current-column)) ?\ ))))))
9452 (org-move-overlay org-tags-overlay ov-start ov-end)
9453 (save-window-excursion
9454 (if expert
9455 (set-buffer (get-buffer-create " *Org tags*"))
9456 (delete-other-windows)
9457 (split-window-vertically)
9458 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
9459 (erase-buffer)
9460 (org-set-local 'org-done-keywords done-keywords)
9461 (org-fast-tag-insert "Inherited" inherited i-face "\n")
9462 (org-fast-tag-insert "Current" current c-face "\n\n")
9463 (org-fast-tag-show-exit exit-after-next)
9464 (org-set-current-tags-overlay current ov-prefix)
9465 (setq tbl fulltable char ?a cnt 0)
9466 (while (setq e (pop tbl))
9467 (cond
9468 ((equal e '(:startgroup))
9469 (push '() groups) (setq ingroup t)
9470 (when (not (= cnt 0))
9471 (setq cnt 0)
9472 (insert "\n"))
9473 (insert "{ "))
9474 ((equal e '(:endgroup))
9475 (setq ingroup nil cnt 0)
9476 (insert "}\n"))
9478 (setq tg (car e) c2 nil)
9479 (if (cdr e)
9480 (setq c (cdr e))
9481 ;; automatically assign a character.
9482 (setq c1 (string-to-char
9483 (downcase (substring
9484 tg (if (= (string-to-char tg) ?@) 1 0)))))
9485 (if (or (rassoc c1 ntable) (rassoc c1 table))
9486 (while (or (rassoc char ntable) (rassoc char table))
9487 (setq char (1+ char)))
9488 (setq c2 c1))
9489 (setq c (or c2 char)))
9490 (if ingroup (push tg (car groups)))
9491 (setq tg (org-add-props tg nil 'face
9492 (cond
9493 ((not (assoc tg table))
9494 (org-get-todo-face tg))
9495 ((member tg current) c-face)
9496 ((member tg inherited) i-face)
9497 (t nil))))
9498 (if (and (= cnt 0) (not ingroup)) (insert " "))
9499 (insert "[" c "] " tg (make-string
9500 (- fwidth 4 (length tg)) ?\ ))
9501 (push (cons tg c) ntable)
9502 (when (= (setq cnt (1+ cnt)) ncol)
9503 (insert "\n")
9504 (if ingroup (insert " "))
9505 (setq cnt 0)))))
9506 (setq ntable (nreverse ntable))
9507 (insert "\n")
9508 (goto-char (point-min))
9509 (if (not expert) (org-fit-window-to-buffer))
9510 (setq rtn
9511 (catch 'exit
9512 (while t
9513 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
9514 (if groups " [!] no groups" " [!]groups")
9515 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
9516 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9517 (cond
9518 ((= c ?\r) (throw 'exit t))
9519 ((= c ?!)
9520 (setq groups (not groups))
9521 (goto-char (point-min))
9522 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
9523 ((= c ?\C-c)
9524 (if (not expert)
9525 (org-fast-tag-show-exit
9526 (setq exit-after-next (not exit-after-next)))
9527 (setq expert nil)
9528 (delete-other-windows)
9529 (split-window-vertically)
9530 (org-switch-to-buffer-other-window " *Org tags*")
9531 (org-fit-window-to-buffer)))
9532 ((or (= c ?\C-g)
9533 (and (= c ?q) (not (rassoc c ntable))))
9534 (org-detach-overlay org-tags-overlay)
9535 (setq quit-flag t))
9536 ((= c ?\ )
9537 (setq current nil)
9538 (if exit-after-next (setq exit-after-next 'now)))
9539 ((= c ?\t)
9540 (condition-case nil
9541 (setq tg (completing-read
9542 "Tag: "
9543 (or buffer-tags
9544 (with-current-buffer buf
9545 (org-get-buffer-tags)))))
9546 (quit (setq tg "")))
9547 (when (string-match "\\S-" tg)
9548 (add-to-list 'buffer-tags (list tg))
9549 (if (member tg current)
9550 (setq current (delete tg current))
9551 (push tg current)))
9552 (if exit-after-next (setq exit-after-next 'now)))
9553 ((setq e (rassoc c todo-table) tg (car e))
9554 (with-current-buffer buf
9555 (save-excursion (org-todo tg)))
9556 (if exit-after-next (setq exit-after-next 'now)))
9557 ((setq e (rassoc c ntable) tg (car e))
9558 (if (member tg current)
9559 (setq current (delete tg current))
9560 (loop for g in groups do
9561 (if (member tg g)
9562 (mapc (lambda (x)
9563 (setq current (delete x current)))
9564 g)))
9565 (push tg current))
9566 (if exit-after-next (setq exit-after-next 'now))))
9568 ;; Create a sorted list
9569 (setq current
9570 (sort current
9571 (lambda (a b)
9572 (assoc b (cdr (memq (assoc a ntable) ntable))))))
9573 (if (eq exit-after-next 'now) (throw 'exit t))
9574 (goto-char (point-min))
9575 (beginning-of-line 2)
9576 (delete-region (point) (point-at-eol))
9577 (org-fast-tag-insert "Current" current c-face)
9578 (org-set-current-tags-overlay current ov-prefix)
9579 (while (re-search-forward
9580 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
9581 (setq tg (match-string 1))
9582 (add-text-properties
9583 (match-beginning 1) (match-end 1)
9584 (list 'face
9585 (cond
9586 ((member tg current) c-face)
9587 ((member tg inherited) i-face)
9588 (t (get-text-property (match-beginning 1) 'face))))))
9589 (goto-char (point-min)))))
9590 (org-detach-overlay org-tags-overlay)
9591 (if rtn
9592 (mapconcat 'identity current ":")
9593 nil))))
9595 (defun org-get-tags-string ()
9596 "Get the TAGS string in the current headline."
9597 (unless (org-on-heading-p t)
9598 (error "Not on a heading"))
9599 (save-excursion
9600 (beginning-of-line 1)
9601 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9602 (org-match-string-no-properties 1)
9603 "")))
9605 (defun org-get-tags ()
9606 "Get the list of tags specified in the current headline."
9607 (org-split-string (org-get-tags-string) ":"))
9609 (defun org-get-buffer-tags ()
9610 "Get a table of all tags used in the buffer, for completion."
9611 (let (tags)
9612 (save-excursion
9613 (goto-char (point-min))
9614 (while (re-search-forward
9615 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
9616 (when (equal (char-after (point-at-bol 0)) ?*)
9617 (mapc (lambda (x) (add-to-list 'tags x))
9618 (org-split-string (org-match-string-no-properties 1) ":")))))
9619 (mapcar 'list tags)))
9621 ;;;; The mapping API
9623 ;;;###autoload
9624 (defun org-map-entries (func &optional match scope &rest skip)
9625 "Call FUNC at each headline selected by MATCH in SCOPE.
9627 FUNC is a function or a lisp form. The function will be called without
9628 arguments, with the cursor positioned at the beginning of the headline.
9629 The return values of all calls to the function will be collected and
9630 returned as a list.
9632 MATCH is a tags/property/todo match as it is used in the agenda tags view.
9633 Only headlines that are matched by this query will be considered during
9634 the iteration. When MATCH is nil or t, all headlines will be
9635 visited by the iteration.
9637 SCOPE determines the scope of this command. It can be any of:
9639 nil The current buffer, respecting the restriction if any
9640 tree The subtree started with the entry at point
9641 file The current buffer, without restriction
9642 file-with-archives
9643 The current buffer, and any archives associated with it
9644 agenda All agenda files
9645 agenda-with-archives
9646 All agenda files with any archive files associated with them
9647 \(file1 file2 ...)
9648 If this is a list, all files in the list will be scanned
9650 The remaining args are treated as settings for the skipping facilities of
9651 the scanner. The following items can be given here:
9653 archive skip trees with the archive tag.
9654 comment skip trees with the COMMENT keyword
9655 function or Emacs Lisp form:
9656 will be used as value for `org-agenda-skip-function', so whenever
9657 the the function returns t, FUNC will not be called for that
9658 entry and search will continue from the point where the
9659 function leaves it."
9660 (let* ((org-agenda-archives-mode nil) ; just to make sure
9661 (org-agenda-skip-archived-trees (memq 'archive skip))
9662 (org-agenda-skip-comment-trees (memq 'comment skip))
9663 (org-agenda-skip-function
9664 (car (org-delete-all '(comment archive) skip)))
9665 (org-tags-match-list-sublevels t)
9666 matcher pos file
9667 org-todo-keywords-for-agenda
9668 org-done-keywords-for-agenda
9669 org-todo-keyword-alist-for-agenda
9670 org-tag-alist-for-agenda)
9672 (cond
9673 ((eq match t) (setq matcher t))
9674 ((eq match nil) (setq matcher t))
9675 (t (setq matcher (if match (org-make-tags-matcher match) t))))
9677 (when (eq scope 'tree)
9678 (org-back-to-heading t)
9679 (org-narrow-to-subtree)
9680 (setq scope nil))
9682 (if (not scope)
9683 (progn
9684 (org-prepare-agenda-buffers
9685 (list (buffer-file-name (current-buffer))))
9686 (org-scan-tags func matcher))
9687 ;; Get the right scope
9688 (setq pos (point))
9689 (cond
9690 ((and scope (listp scope) (symbolp (car scope)))
9691 (setq scope (eval scope)))
9692 ((eq scope 'agenda)
9693 (setq scope (org-agenda-files t)))
9694 ((eq scope 'agenda-with-archives)
9695 (setq scope (org-agenda-files t))
9696 (setq scope (org-add-archive-files scope)))
9697 ((eq scope 'file)
9698 (setq scope (list (buffer-file-name))))
9699 ((eq scope 'file-with-archives)
9700 (setq scope (org-add-archive-files (list (buffer-file-name))))))
9701 (org-prepare-agenda-buffers scope)
9702 (while (setq file (pop scope))
9703 (with-current-buffer (org-find-base-buffer-visiting file)
9704 (save-excursion
9705 (save-restriction
9706 (widen)
9707 (goto-char (point-min))
9708 (org-scan-tags func matcher))))))))
9710 ;;;; Properties
9712 ;;; Setting and retrieving properties
9714 (defconst org-special-properties
9715 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
9716 "TIMESTAMP" "TIMESTAMP_IA")
9717 "The special properties valid in Org-mode.
9719 These are properties that are not defined in the property drawer,
9720 but in some other way.")
9722 (defconst org-default-properties
9723 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
9724 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
9725 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
9726 "EXPORT_FILE_NAME" "EXPORT_TITLE")
9727 "Some properties that are used by Org-mode for various purposes.
9728 Being in this list makes sure that they are offered for completion.")
9730 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
9731 "Regular expression matching the first line of a property drawer.")
9733 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
9734 "Regular expression matching the first line of a property drawer.")
9736 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
9737 "Regular expression matching the first line of a property drawer.")
9739 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
9740 "Regular expression matching the first line of a property drawer.")
9742 (defconst org-property-drawer-re
9743 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
9744 org-property-end-re "\\)\n?")
9745 "Matches an entire property drawer.")
9747 (defconst org-clock-drawer-re
9748 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
9749 org-property-end-re "\\)\n?")
9750 "Matches an entire clock drawer.")
9752 (defun org-property-action ()
9753 "Do an action on properties."
9754 (interactive)
9755 (let (c)
9756 (org-at-property-p)
9757 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
9758 (setq c (read-char-exclusive))
9759 (cond
9760 ((equal c ?s)
9761 (call-interactively 'org-set-property))
9762 ((equal c ?d)
9763 (call-interactively 'org-delete-property))
9764 ((equal c ?D)
9765 (call-interactively 'org-delete-property-globally))
9766 ((equal c ?c)
9767 (call-interactively 'org-compute-property-at-point))
9768 (t (error "No such property action %c" c)))))
9770 (defun org-at-property-p ()
9771 "Is the cursor in a property line?"
9772 ;; FIXME: Does not check if we are actually in the drawer.
9773 ;; FIXME: also returns true on any drawers.....
9774 ;; This is used by C-c C-c for property action.
9775 (save-excursion
9776 (beginning-of-line 1)
9777 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
9779 (defun org-get-property-block (&optional beg end force)
9780 "Return the (beg . end) range of the body of the property drawer.
9781 BEG and END can be beginning and end of subtree, if not given
9782 they will be found.
9783 If the drawer does not exist and FORCE is non-nil, create the drawer."
9784 (catch 'exit
9785 (save-excursion
9786 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
9787 (end (or end (progn (outline-next-heading) (point)))))
9788 (goto-char beg)
9789 (if (re-search-forward org-property-start-re end t)
9790 (setq beg (1+ (match-end 0)))
9791 (if force
9792 (save-excursion
9793 (org-insert-property-drawer)
9794 (setq end (progn (outline-next-heading) (point))))
9795 (throw 'exit nil))
9796 (goto-char beg)
9797 (if (re-search-forward org-property-start-re end t)
9798 (setq beg (1+ (match-end 0)))))
9799 (if (re-search-forward org-property-end-re end t)
9800 (setq end (match-beginning 0))
9801 (or force (throw 'exit nil))
9802 (goto-char beg)
9803 (setq end beg)
9804 (org-indent-line-function)
9805 (insert ":END:\n"))
9806 (cons beg end)))))
9808 (defun org-entry-properties (&optional pom which)
9809 "Get all properties of the entry at point-or-marker POM.
9810 This includes the TODO keyword, the tags, time strings for deadline,
9811 scheduled, and clocking, and any additional properties defined in the
9812 entry. The return value is an alist, keys may occur multiple times
9813 if the property key was used several times.
9814 POM may also be nil, in which case the current entry is used.
9815 If WHICH is nil or `all', get all properties. If WHICH is
9816 `special' or `standard', only get that subclass."
9817 (setq which (or which 'all))
9818 (org-with-point-at pom
9819 (let ((clockstr (substring org-clock-string 0 -1))
9820 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
9821 beg end range props sum-props key value string clocksum)
9822 (save-excursion
9823 (when (condition-case nil (org-back-to-heading t) (error nil))
9824 (setq beg (point))
9825 (setq sum-props (get-text-property (point) 'org-summaries))
9826 (setq clocksum (get-text-property (point) :org-clock-minutes))
9827 (outline-next-heading)
9828 (setq end (point))
9829 (when (memq which '(all special))
9830 ;; Get the special properties, like TODO and tags
9831 (goto-char beg)
9832 (when (and (looking-at org-todo-line-regexp) (match-end 2))
9833 (push (cons "TODO" (org-match-string-no-properties 2)) props))
9834 (when (looking-at org-priority-regexp)
9835 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
9836 (when (and (setq value (org-get-tags-string))
9837 (string-match "\\S-" value))
9838 (push (cons "TAGS" value) props))
9839 (when (setq value (org-get-tags-at))
9840 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
9841 props))
9842 (while (re-search-forward org-maybe-keyword-time-regexp end t)
9843 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
9844 string (if (equal key clockstr)
9845 (org-no-properties
9846 (org-trim
9847 (buffer-substring
9848 (match-beginning 3) (goto-char (point-at-eol)))))
9849 (substring (org-match-string-no-properties 3) 1 -1)))
9850 (unless key
9851 (if (= (char-after (match-beginning 3)) ?\[)
9852 (setq key "TIMESTAMP_IA")
9853 (setq key "TIMESTAMP")))
9854 (when (or (equal key clockstr) (not (assoc key props)))
9855 (push (cons key string) props)))
9859 (when (memq which '(all standard))
9860 ;; Get the standard properties, like :PORP: ...
9861 (setq range (org-get-property-block beg end))
9862 (when range
9863 (goto-char (car range))
9864 (while (re-search-forward
9865 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
9866 (cdr range) t)
9867 (setq key (org-match-string-no-properties 1)
9868 value (org-trim (or (org-match-string-no-properties 2) "")))
9869 (unless (member key excluded)
9870 (push (cons key (or value "")) props)))))
9871 (if clocksum
9872 (push (cons "CLOCKSUM"
9873 (org-columns-number-to-string (/ (float clocksum) 60.)
9874 'add_times))
9875 props))
9876 (unless (assoc "CATEGORY" props)
9877 (setq value (or (org-get-category)
9878 (progn (org-refresh-category-properties)
9879 (org-get-category))))
9880 (push (cons "CATEGORY" value) props))
9881 (append sum-props (nreverse props)))))))
9883 (defun org-entry-get (pom property &optional inherit)
9884 "Get value of PROPERTY for entry at point-or-marker POM.
9885 If INHERIT is non-nil and the entry does not have the property,
9886 then also check higher levels of the hierarchy.
9887 If INHERIT is the symbol `selective', use inheritance only if the setting
9888 in `org-use-property-inheritance' selects PROPERTY for inheritance.
9889 If the property is present but empty, the return value is the empty string.
9890 If the property is not present at all, nil is returned."
9891 (org-with-point-at pom
9892 (if (and inherit (if (eq inherit 'selective)
9893 (org-property-inherit-p property)
9895 (org-entry-get-with-inheritance property)
9896 (if (member property org-special-properties)
9897 ;; We need a special property. Use brute force, get all properties.
9898 (cdr (assoc property (org-entry-properties nil 'special)))
9899 (let ((range (org-get-property-block)))
9900 (if (and range
9901 (goto-char (car range))
9902 (re-search-forward
9903 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
9904 (cdr range) t))
9905 ;; Found the property, return it.
9906 (if (match-end 1)
9907 (org-match-string-no-properties 1)
9908 "")))))))
9910 (defun org-property-or-variable-value (var &optional inherit)
9911 "Check if there is a property fixing the value of VAR.
9912 If yes, return this value. If not, return the current value of the variable."
9913 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
9914 (if (and prop (stringp prop) (string-match "\\S-" prop))
9915 (read prop)
9916 (symbol-value var))))
9918 (defun org-entry-delete (pom property)
9919 "Delete the property PROPERTY from entry at point-or-marker POM."
9920 (org-with-point-at pom
9921 (if (member property org-special-properties)
9922 nil ; cannot delete these properties.
9923 (let ((range (org-get-property-block)))
9924 (if (and range
9925 (goto-char (car range))
9926 (re-search-forward
9927 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
9928 (cdr range) t))
9929 (progn
9930 (delete-region (match-beginning 0) (1+ (point-at-eol)))
9932 nil)))))
9934 ;; Multi-values properties are properties that contain multiple values
9935 ;; These values are assumed to be single words, separated by whitespace.
9936 (defun org-entry-add-to-multivalued-property (pom property value)
9937 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
9938 (let* ((old (org-entry-get pom property))
9939 (values (and old (org-split-string old "[ \t]"))))
9940 (setq value (org-entry-protect-space value))
9941 (unless (member value values)
9942 (setq values (cons value values))
9943 (org-entry-put pom property
9944 (mapconcat 'identity values " ")))))
9946 (defun org-entry-remove-from-multivalued-property (pom property value)
9947 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
9948 (let* ((old (org-entry-get pom property))
9949 (values (and old (org-split-string old "[ \t]"))))
9950 (setq value (org-entry-protect-space value))
9951 (when (member value values)
9952 (setq values (delete value values))
9953 (org-entry-put pom property
9954 (mapconcat 'identity values " ")))))
9956 (defun org-entry-member-in-multivalued-property (pom property value)
9957 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
9958 (let* ((old (org-entry-get pom property))
9959 (values (and old (org-split-string old "[ \t]"))))
9960 (setq value (org-entry-protect-space value))
9961 (member value values)))
9963 (defun org-entry-get-multivalued-property (pom property)
9964 "Return a list of values in a multivalued property."
9965 (let* ((value (org-entry-get pom property))
9966 (values (and value (org-split-string value "[ \t]"))))
9967 (mapcar 'org-entry-restore-space values)))
9969 (defun org-entry-put-multivalued-property (pom property &rest values)
9970 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
9971 VALUES should be a list of strings. Spaces will be protected."
9972 (org-entry-put pom property
9973 (mapconcat 'org-entry-protect-space values " "))
9974 (let* ((value (org-entry-get pom property))
9975 (values (and value (org-split-string value "[ \t]"))))
9976 (mapcar 'org-entry-restore-space values)))
9978 (defun org-entry-protect-space (s)
9979 "Protect spaces and newline in string S."
9980 (while (string-match " " s)
9981 (setq s (replace-match "%20" t t s)))
9982 (while (string-match "\n" s)
9983 (setq s (replace-match "%0A" t t s)))
9986 (defun org-entry-restore-space (s)
9987 "Restore spaces and newline in string S."
9988 (while (string-match "%20" s)
9989 (setq s (replace-match " " t t s)))
9990 (while (string-match "%0A" s)
9991 (setq s (replace-match "\n" t t s)))
9994 (defvar org-entry-property-inherited-from (make-marker)
9995 "Marker pointing to the entry from where a proerty was inherited.
9996 Each call to `org-entry-get-with-inheritance' will set this marker to the
9997 location of the entry where the inheriance search matched. If there was
9998 no match, the marker will point nowhere.
9999 Note that also `org-entry-get' calls this function, if the INHERIT flag
10000 is set.")
10002 (defun org-entry-get-with-inheritance (property)
10003 "Get entry property, and search higher levels if not present."
10004 (move-marker org-entry-property-inherited-from nil)
10005 (let (tmp)
10006 (save-excursion
10007 (save-restriction
10008 (widen)
10009 (catch 'ex
10010 (while t
10011 (when (setq tmp (org-entry-get nil property))
10012 (org-back-to-heading t)
10013 (move-marker org-entry-property-inherited-from (point))
10014 (throw 'ex tmp))
10015 (or (org-up-heading-safe) (throw 'ex nil)))))
10016 (or tmp
10017 (cdr (assoc property org-file-properties))
10018 (cdr (assoc property org-global-properties))
10019 (cdr (assoc property org-global-properties-fixed))))))
10021 (defun org-entry-put (pom property value)
10022 "Set PROPERTY to VALUE for entry at point-or-marker POM."
10023 (org-with-point-at pom
10024 (org-back-to-heading t)
10025 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
10026 range)
10027 (cond
10028 ((equal property "TODO")
10029 (when (and (stringp value) (string-match "\\S-" value)
10030 (not (member value org-todo-keywords-1)))
10031 (error "\"%s\" is not a valid TODO state" value))
10032 (if (or (not value)
10033 (not (string-match "\\S-" value)))
10034 (setq value 'none))
10035 (org-todo value)
10036 (org-set-tags nil 'align))
10037 ((equal property "PRIORITY")
10038 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
10039 (string-to-char value) ?\ ))
10040 (org-set-tags nil 'align))
10041 ((equal property "SCHEDULED")
10042 (if (re-search-forward org-scheduled-time-regexp end t)
10043 (cond
10044 ((eq value 'earlier) (org-timestamp-change -1 'day))
10045 ((eq value 'later) (org-timestamp-change 1 'day))
10046 (t (call-interactively 'org-schedule)))
10047 (call-interactively 'org-schedule)))
10048 ((equal property "DEADLINE")
10049 (if (re-search-forward org-deadline-time-regexp end t)
10050 (cond
10051 ((eq value 'earlier) (org-timestamp-change -1 'day))
10052 ((eq value 'later) (org-timestamp-change 1 'day))
10053 (t (call-interactively 'org-deadline)))
10054 (call-interactively 'org-deadline)))
10055 ((member property org-special-properties)
10056 (error "The %s property can not yet be set with `org-entry-put'"
10057 property))
10058 (t ; a non-special property
10059 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
10060 (setq range (org-get-property-block beg end 'force))
10061 (goto-char (car range))
10062 (if (re-search-forward
10063 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
10064 (progn
10065 (delete-region (match-beginning 1) (match-end 1))
10066 (goto-char (match-beginning 1)))
10067 (goto-char (cdr range))
10068 (insert "\n")
10069 (backward-char 1)
10070 (org-indent-line-function)
10071 (insert ":" property ":"))
10072 (and value (insert " " value))
10073 (org-indent-line-function)))))))
10075 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
10076 "Get all property keys in the current buffer.
10077 With INCLUDE-SPECIALS, also list the special properties that relect things
10078 like tags and TODO state.
10079 With INCLUDE-DEFAULTS, also include properties that has special meaning
10080 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
10081 With INCLUDE-COLUMNS, also include property names given in COLUMN
10082 formats in the current buffer."
10083 (let (rtn range cfmt cols s p)
10084 (save-excursion
10085 (save-restriction
10086 (widen)
10087 (goto-char (point-min))
10088 (while (re-search-forward org-property-start-re nil t)
10089 (setq range (org-get-property-block))
10090 (goto-char (car range))
10091 (while (re-search-forward
10092 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
10093 (cdr range) t)
10094 (add-to-list 'rtn (org-match-string-no-properties 1)))
10095 (outline-next-heading))))
10097 (when include-specials
10098 (setq rtn (append org-special-properties rtn)))
10100 (when include-defaults
10101 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
10103 (when include-columns
10104 (save-excursion
10105 (save-restriction
10106 (widen)
10107 (goto-char (point-min))
10108 (while (re-search-forward
10109 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
10110 nil t)
10111 (setq cfmt (match-string 2) s 0)
10112 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
10113 cfmt s)
10114 (setq s (match-end 0)
10115 p (match-string 1 cfmt))
10116 (unless (or (equal p "ITEM")
10117 (member p org-special-properties))
10118 (add-to-list 'rtn (match-string 1 cfmt))))))))
10120 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
10122 (defun org-property-values (key)
10123 "Return a list of all values of property KEY."
10124 (save-excursion
10125 (save-restriction
10126 (widen)
10127 (goto-char (point-min))
10128 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
10129 values)
10130 (while (re-search-forward re nil t)
10131 (add-to-list 'values (org-trim (match-string 1))))
10132 (delete "" values)))))
10134 (defun org-insert-property-drawer ()
10135 "Insert a property drawer into the current entry."
10136 (interactive)
10137 (org-back-to-heading t)
10138 (looking-at outline-regexp)
10139 (let ((indent (- (match-end 0)(match-beginning 0)))
10140 (beg (point))
10141 (re (concat "^[ \t]*" org-keyword-time-regexp))
10142 end hiddenp)
10143 (outline-next-heading)
10144 (setq end (point))
10145 (goto-char beg)
10146 (while (re-search-forward re end t))
10147 (setq hiddenp (org-invisible-p))
10148 (end-of-line 1)
10149 (and (equal (char-after) ?\n) (forward-char 1))
10150 (while (looking-at "^[ \t]*\\(:CLOCK:\\|CLOCK\\|:END:\\)")
10151 (beginning-of-line 2))
10152 (org-skip-over-state-notes)
10153 (skip-chars-backward " \t\n\r")
10154 (if (eq (char-before) ?*) (forward-char 1))
10155 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
10156 (beginning-of-line 0)
10157 (org-indent-to-column indent)
10158 (beginning-of-line 2)
10159 (org-indent-to-column indent)
10160 (beginning-of-line 0)
10161 (if hiddenp
10162 (save-excursion
10163 (org-back-to-heading t)
10164 (hide-entry))
10165 (org-flag-drawer t))))
10167 (defun org-set-property (property value)
10168 "In the current entry, set PROPERTY to VALUE.
10169 When called interactively, this will prompt for a property name, offering
10170 completion on existing and default properties. And then it will prompt
10171 for a value, offering competion either on allowed values (via an inherited
10172 xxx_ALL property) or on existing values in other instances of this property
10173 in the current file."
10174 (interactive
10175 (let* ((completion-ignore-case t)
10176 (keys (org-buffer-property-keys nil t t))
10177 (prop0 (completing-read "Property: " (mapcar 'list keys)))
10178 (prop (if (member prop0 keys)
10179 prop0
10180 (or (cdr (assoc (downcase prop0)
10181 (mapcar (lambda (x) (cons (downcase x) x))
10182 keys)))
10183 prop0)))
10184 (cur (org-entry-get nil prop))
10185 (allowed (org-property-get-allowed-values nil prop 'table))
10186 (existing (mapcar 'list (org-property-values prop)))
10187 (val (if allowed
10188 (org-completing-read "Value: " allowed nil 'req-match)
10189 (org-completing-read
10190 (concat "Value" (if (and cur (string-match "\\S-" cur))
10191 (concat "[" cur "]") "")
10192 ": ")
10193 existing nil nil "" nil cur))))
10194 (list prop (if (equal val "") cur val))))
10195 (unless (equal (org-entry-get nil property) value)
10196 (org-entry-put nil property value)))
10198 (defun org-delete-property (property)
10199 "In the current entry, delete PROPERTY."
10200 (interactive
10201 (let* ((completion-ignore-case t)
10202 (prop (completing-read
10203 "Property: " (org-entry-properties nil 'standard))))
10204 (list prop)))
10205 (message "Property %s %s" property
10206 (if (org-entry-delete nil property)
10207 "deleted"
10208 "was not present in the entry")))
10210 (defun org-delete-property-globally (property)
10211 "Remove PROPERTY globally, from all entries."
10212 (interactive
10213 (let* ((completion-ignore-case t)
10214 (prop (completing-read
10215 "Globally remove property: "
10216 (mapcar 'list (org-buffer-property-keys)))))
10217 (list prop)))
10218 (save-excursion
10219 (save-restriction
10220 (widen)
10221 (goto-char (point-min))
10222 (let ((cnt 0))
10223 (while (re-search-forward
10224 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
10225 nil t)
10226 (setq cnt (1+ cnt))
10227 (replace-match ""))
10228 (message "Property \"%s\" removed from %d entries" property cnt)))))
10230 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
10232 (defun org-compute-property-at-point ()
10233 "Compute the property at point.
10234 This looks for an enclosing column format, extracts the operator and
10235 then applies it to the proerty in the column format's scope."
10236 (interactive)
10237 (unless (org-at-property-p)
10238 (error "Not at a property"))
10239 (let ((prop (org-match-string-no-properties 2)))
10240 (org-columns-get-format-and-top-level)
10241 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
10242 (error "No operator defined for property %s" prop))
10243 (org-columns-compute prop)))
10245 (defun org-property-get-allowed-values (pom property &optional table)
10246 "Get allowed values for the property PROPERTY.
10247 When TABLE is non-nil, return an alist that can directly be used for
10248 completion."
10249 (let (vals)
10250 (cond
10251 ((equal property "TODO")
10252 (setq vals (org-with-point-at pom
10253 (append org-todo-keywords-1 '("")))))
10254 ((equal property "PRIORITY")
10255 (let ((n org-lowest-priority))
10256 (while (>= n org-highest-priority)
10257 (push (char-to-string n) vals)
10258 (setq n (1- n)))))
10259 ((member property org-special-properties))
10261 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
10263 (when (and vals (string-match "\\S-" vals))
10264 (setq vals (car (read-from-string (concat "(" vals ")"))))
10265 (setq vals (mapcar (lambda (x)
10266 (cond ((stringp x) x)
10267 ((numberp x) (number-to-string x))
10268 ((symbolp x) (symbol-name x))
10269 (t "???")))
10270 vals)))))
10271 (if table (mapcar 'list vals) vals)))
10273 (defun org-property-previous-allowed-value (&optional previous)
10274 "Switch to the next allowed value for this property."
10275 (interactive)
10276 (org-property-next-allowed-value t))
10278 (defun org-property-next-allowed-value (&optional previous)
10279 "Switch to the next allowed value for this property."
10280 (interactive)
10281 (unless (org-at-property-p)
10282 (error "Not at a property"))
10283 (let* ((key (match-string 2))
10284 (value (match-string 3))
10285 (allowed (or (org-property-get-allowed-values (point) key)
10286 (and (member value '("[ ]" "[-]" "[X]"))
10287 '("[ ]" "[X]"))))
10288 nval)
10289 (unless allowed
10290 (error "Allowed values for this property have not been defined"))
10291 (if previous (setq allowed (reverse allowed)))
10292 (if (member value allowed)
10293 (setq nval (car (cdr (member value allowed)))))
10294 (setq nval (or nval (car allowed)))
10295 (if (equal nval value)
10296 (error "Only one allowed value for this property"))
10297 (org-at-property-p)
10298 (replace-match (concat " :" key ": " nval) t t)
10299 (org-indent-line-function)
10300 (beginning-of-line 1)
10301 (skip-chars-forward " \t")))
10303 (defun org-find-entry-with-id (ident)
10304 "Locate the entry that contains the ID property with exact value IDENT.
10305 IDENT can be a string, a symbol or a number, this function will search for
10306 the string representation of it.
10307 Return the position where this entry starts, or nil if there is no such entry."
10308 (let ((id (cond
10309 ((stringp ident) ident)
10310 ((symbol-name ident) (symbol-name ident))
10311 ((numberp ident) (number-to-string ident))
10312 (t (error "IDENT %s must be a string, symbol or number" ident))))
10313 (case-fold-search nil))
10314 (save-excursion
10315 (save-restriction
10316 (widen)
10317 (goto-char (point-min))
10318 (when (re-search-forward
10319 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
10320 nil t)
10321 (org-back-to-heading)
10322 (point))))))
10324 ;;;; Timestamps
10326 (defvar org-last-changed-timestamp nil)
10327 (defvar org-last-inserted-timestamp nil
10328 "The last time stamp inserted with `org-insert-time-stamp'.")
10329 (defvar org-time-was-given) ; dynamically scoped parameter
10330 (defvar org-end-time-was-given) ; dynamically scoped parameter
10331 (defvar org-ts-what) ; dynamically scoped parameter
10333 (defun org-time-stamp (arg &optional inactive)
10334 "Prompt for a date/time and insert a time stamp.
10335 If the user specifies a time like HH:MM, or if this command is called
10336 with a prefix argument, the time stamp will contain date and time.
10337 Otherwise, only the date will be included. All parts of a date not
10338 specified by the user will be filled in from the current date/time.
10339 So if you press just return without typing anything, the time stamp
10340 will represent the current date/time. If there is already a timestamp
10341 at the cursor, it will be modified."
10342 (interactive "P")
10343 (let* ((ts nil)
10344 (default-time
10345 ;; Default time is either today, or, when entering a range,
10346 ;; the range start.
10347 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
10348 (save-excursion
10349 (re-search-backward
10350 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
10351 (- (point) 20) t)))
10352 (apply 'encode-time (org-parse-time-string (match-string 1)))
10353 (current-time)))
10354 (default-input (and ts (org-get-compact-tod ts)))
10355 org-time-was-given org-end-time-was-given time)
10356 (cond
10357 ((and (org-at-timestamp-p t)
10358 (memq last-command '(org-time-stamp org-time-stamp-inactive))
10359 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
10360 (insert "--")
10361 (setq time (let ((this-command this-command))
10362 (org-read-date arg 'totime nil nil
10363 default-time default-input)))
10364 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
10365 ((org-at-timestamp-p t)
10366 (setq time (let ((this-command this-command))
10367 (org-read-date arg 'totime nil nil default-time default-input)))
10368 (when (org-at-timestamp-p t) ; just to get the match data
10369 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
10370 (replace-match "")
10371 (setq org-last-changed-timestamp
10372 (org-insert-time-stamp
10373 time (or org-time-was-given arg)
10374 inactive nil nil (list org-end-time-was-given))))
10375 (message "Timestamp updated"))
10377 (setq time (let ((this-command this-command))
10378 (org-read-date arg 'totime nil nil default-time default-input)))
10379 (org-insert-time-stamp time (or org-time-was-given arg) inactive
10380 nil nil (list org-end-time-was-given))))))
10382 ;; FIXME: can we use this for something else, like computing time differences?
10383 (defun org-get-compact-tod (s)
10384 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
10385 (let* ((t1 (match-string 1 s))
10386 (h1 (string-to-number (match-string 2 s)))
10387 (m1 (string-to-number (match-string 3 s)))
10388 (t2 (and (match-end 4) (match-string 5 s)))
10389 (h2 (and t2 (string-to-number (match-string 6 s))))
10390 (m2 (and t2 (string-to-number (match-string 7 s))))
10391 dh dm)
10392 (if (not t2)
10394 (setq dh (- h2 h1) dm (- m2 m1))
10395 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
10396 (concat t1 "+" (number-to-string dh)
10397 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
10399 (defun org-time-stamp-inactive (&optional arg)
10400 "Insert an inactive time stamp.
10401 An inactive time stamp is enclosed in square brackets instead of angle
10402 brackets. It is inactive in the sense that it does not trigger agenda entries,
10403 does not link to the calendar and cannot be changed with the S-cursor keys.
10404 So these are more for recording a certain time/date."
10405 (interactive "P")
10406 (org-time-stamp arg 'inactive))
10408 (defvar org-date-ovl (org-make-overlay 1 1))
10409 (org-overlay-put org-date-ovl 'face 'org-warning)
10410 (org-detach-overlay org-date-ovl)
10412 (defvar org-ans1) ; dynamically scoped parameter
10413 (defvar org-ans2) ; dynamically scoped parameter
10415 (defvar org-plain-time-of-day-regexp) ; defined below
10417 (defvar org-overriding-default-time nil) ; dynamically scoped
10418 (defvar org-read-date-overlay nil)
10419 (defvar org-dcst nil) ; dynamically scoped
10421 (defun org-read-date (&optional with-time to-time from-string prompt
10422 default-time default-input)
10423 "Read a date, possibly a time, and make things smooth for the user.
10424 The prompt will suggest to enter an ISO date, but you can also enter anything
10425 which will at least partially be understood by `parse-time-string'.
10426 Unrecognized parts of the date will default to the current day, month, year,
10427 hour and minute. If this command is called to replace a timestamp at point,
10428 of to enter the second timestamp of a range, the default time is taken from the
10429 existing stamp. For example,
10430 3-2-5 --> 2003-02-05
10431 feb 15 --> currentyear-02-15
10432 sep 12 9 --> 2009-09-12
10433 12:45 --> today 12:45
10434 22 sept 0:34 --> currentyear-09-22 0:34
10435 12 --> currentyear-currentmonth-12
10436 Fri --> nearest Friday (today or later)
10437 etc.
10439 Furthermore you can specify a relative date by giving, as the *first* thing
10440 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
10441 change in days weeks, months, years.
10442 With a single plus or minus, the date is relative to today. With a double
10443 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
10444 +4d --> four days from today
10445 +4 --> same as above
10446 +2w --> two weeks from today
10447 ++5 --> five days from default date
10449 The function understands only English month and weekday abbreviations,
10450 but this can be configured with the variables `parse-time-months' and
10451 `parse-time-weekdays'.
10453 While prompting, a calendar is popped up - you can also select the
10454 date with the mouse (button 1). The calendar shows a period of three
10455 months. To scroll it to other months, use the keys `>' and `<'.
10456 If you don't like the calendar, turn it off with
10457 \(setq org-read-date-popup-calendar nil)
10459 With optional argument TO-TIME, the date will immediately be converted
10460 to an internal time.
10461 With an optional argument WITH-TIME, the prompt will suggest to also
10462 insert a time. Note that when WITH-TIME is not set, you can still
10463 enter a time, and this function will inform the calling routine about
10464 this change. The calling routine may then choose to change the format
10465 used to insert the time stamp into the buffer to include the time.
10466 With optional argument FROM-STRING, read from this string instead from
10467 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
10468 the time/date that is used for everything that is not specified by the
10469 user."
10470 (require 'parse-time)
10471 (let* ((org-time-stamp-rounding-minutes
10472 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
10473 (org-dcst org-display-custom-times)
10474 (ct (org-current-time))
10475 (def (or org-overriding-default-time default-time ct))
10476 (defdecode (decode-time def))
10477 (dummy (progn
10478 (when (< (nth 2 defdecode) org-extend-today-until)
10479 (setcar (nthcdr 2 defdecode) -1)
10480 (setcar (nthcdr 1 defdecode) 59)
10481 (setq def (apply 'encode-time defdecode)
10482 defdecode (decode-time def)))))
10483 (calendar-move-hook nil)
10484 (calendar-view-diary-initially-flag nil)
10485 (view-diary-entries-initially nil)
10486 (calendar-view-holidays-initially-flag nil)
10487 (view-calendar-holidays-initially nil)
10488 (timestr (format-time-string
10489 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
10490 (prompt (concat (if prompt (concat prompt " ") "")
10491 (format "Date+time [%s]: " timestr)))
10492 ans (org-ans0 "") org-ans1 org-ans2 final)
10494 (cond
10495 (from-string (setq ans from-string))
10496 (org-read-date-popup-calendar
10497 (save-excursion
10498 (save-window-excursion
10499 (calendar)
10500 (calendar-forward-day (- (time-to-days def)
10501 (calendar-absolute-from-gregorian
10502 (calendar-current-date))))
10503 (org-eval-in-calendar nil t)
10504 (let* ((old-map (current-local-map))
10505 (map (copy-keymap calendar-mode-map))
10506 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
10507 (org-defkey map (kbd "RET") 'org-calendar-select)
10508 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
10509 'org-calendar-select-mouse)
10510 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
10511 'org-calendar-select-mouse)
10512 (org-defkey minibuffer-local-map [(meta shift left)]
10513 (lambda () (interactive)
10514 (org-eval-in-calendar '(calendar-backward-month 1))))
10515 (org-defkey minibuffer-local-map [(meta shift right)]
10516 (lambda () (interactive)
10517 (org-eval-in-calendar '(calendar-forward-month 1))))
10518 (org-defkey minibuffer-local-map [(meta shift up)]
10519 (lambda () (interactive)
10520 (org-eval-in-calendar '(calendar-backward-year 1))))
10521 (org-defkey minibuffer-local-map [(meta shift down)]
10522 (lambda () (interactive)
10523 (org-eval-in-calendar '(calendar-forward-year 1))))
10524 (org-defkey minibuffer-local-map [(shift up)]
10525 (lambda () (interactive)
10526 (org-eval-in-calendar '(calendar-backward-week 1))))
10527 (org-defkey minibuffer-local-map [(shift down)]
10528 (lambda () (interactive)
10529 (org-eval-in-calendar '(calendar-forward-week 1))))
10530 (org-defkey minibuffer-local-map [(shift left)]
10531 (lambda () (interactive)
10532 (org-eval-in-calendar '(calendar-backward-day 1))))
10533 (org-defkey minibuffer-local-map [(shift right)]
10534 (lambda () (interactive)
10535 (org-eval-in-calendar '(calendar-forward-day 1))))
10536 (org-defkey minibuffer-local-map ">"
10537 (lambda () (interactive)
10538 (org-eval-in-calendar '(scroll-calendar-left 1))))
10539 (org-defkey minibuffer-local-map "<"
10540 (lambda () (interactive)
10541 (org-eval-in-calendar '(scroll-calendar-right 1))))
10542 (unwind-protect
10543 (progn
10544 (use-local-map map)
10545 (add-hook 'post-command-hook 'org-read-date-display)
10546 (setq org-ans0 (read-string prompt default-input nil nil))
10547 ;; org-ans0: from prompt
10548 ;; org-ans1: from mouse click
10549 ;; org-ans2: from calendar motion
10550 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
10551 (remove-hook 'post-command-hook 'org-read-date-display)
10552 (use-local-map old-map)
10553 (when org-read-date-overlay
10554 (org-delete-overlay org-read-date-overlay)
10555 (setq org-read-date-overlay nil)))))))
10557 (t ; Naked prompt only
10558 (unwind-protect
10559 (setq ans (read-string prompt default-input nil timestr))
10560 (when org-read-date-overlay
10561 (org-delete-overlay org-read-date-overlay)
10562 (setq org-read-date-overlay nil)))))
10564 (setq final (org-read-date-analyze ans def defdecode))
10566 (if to-time
10567 (apply 'encode-time final)
10568 (if (and (boundp 'org-time-was-given) org-time-was-given)
10569 (format "%04d-%02d-%02d %02d:%02d"
10570 (nth 5 final) (nth 4 final) (nth 3 final)
10571 (nth 2 final) (nth 1 final))
10572 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
10573 (defvar def)
10574 (defvar defdecode)
10575 (defvar with-time)
10576 (defun org-read-date-display ()
10577 "Display the currrent date prompt interpretation in the minibuffer."
10578 (when org-read-date-display-live
10579 (when org-read-date-overlay
10580 (org-delete-overlay org-read-date-overlay))
10581 (let ((p (point)))
10582 (end-of-line 1)
10583 (while (not (equal (buffer-substring
10584 (max (point-min) (- (point) 4)) (point))
10585 " "))
10586 (insert " "))
10587 (goto-char p))
10588 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
10589 " " (or org-ans1 org-ans2)))
10590 (org-end-time-was-given nil)
10591 (f (org-read-date-analyze ans def defdecode))
10592 (fmts (if org-dcst
10593 org-time-stamp-custom-formats
10594 org-time-stamp-formats))
10595 (fmt (if (or with-time
10596 (and (boundp 'org-time-was-given) org-time-was-given))
10597 (cdr fmts)
10598 (car fmts)))
10599 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
10600 (when (and org-end-time-was-given
10601 (string-match org-plain-time-of-day-regexp txt))
10602 (setq txt (concat (substring txt 0 (match-end 0)) "-"
10603 org-end-time-was-given
10604 (substring txt (match-end 0)))))
10605 (setq org-read-date-overlay
10606 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
10607 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
10609 (defun org-read-date-analyze (ans def defdecode)
10610 "Analyze the combined answer of the date prompt."
10611 ;; FIXME: cleanup and comment
10612 (let (delta deltan deltaw deltadef year month day
10613 hour minute second wday pm h2 m2 tl wday1
10614 iso-year iso-weekday iso-week iso-year iso-date)
10616 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
10617 (setq ans "+0"))
10619 (when (setq delta (org-read-date-get-relative ans (current-time) def))
10620 (setq ans (replace-match "" t t ans)
10621 deltan (car delta)
10622 deltaw (nth 1 delta)
10623 deltadef (nth 2 delta)))
10625 ;; Check if there is an iso week date in there
10626 ;; If yes, sore the info and ostpone interpreting it until the rest
10627 ;; of the parsing is done
10628 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
10629 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
10630 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
10631 iso-week (string-to-number (match-string 2 ans)))
10632 (setq ans (replace-match "" t t ans)))
10634 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
10635 (when (string-match
10636 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
10637 (setq year (if (match-end 2)
10638 (string-to-number (match-string 2 ans))
10639 (string-to-number (format-time-string "%Y")))
10640 month (string-to-number (match-string 3 ans))
10641 day (string-to-number (match-string 4 ans)))
10642 (if (< year 100) (setq year (+ 2000 year)))
10643 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
10644 t nil ans)))
10645 ;; Help matching am/pm times, because `parse-time-string' does not do that.
10646 ;; If there is a time with am/pm, and *no* time without it, we convert
10647 ;; so that matching will be successful.
10648 (loop for i from 1 to 2 do ; twice, for end time as well
10649 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
10650 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
10651 (setq hour (string-to-number (match-string 1 ans))
10652 minute (if (match-end 3)
10653 (string-to-number (match-string 3 ans))
10655 pm (equal ?p
10656 (string-to-char (downcase (match-string 4 ans)))))
10657 (if (and (= hour 12) (not pm))
10658 (setq hour 0)
10659 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
10660 (setq ans (replace-match (format "%02d:%02d" hour minute)
10661 t t ans))))
10663 ;; Check if a time range is given as a duration
10664 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
10665 (setq hour (string-to-number (match-string 1 ans))
10666 h2 (+ hour (string-to-number (match-string 3 ans)))
10667 minute (string-to-number (match-string 2 ans))
10668 m2 (+ minute (if (match-end 5) (string-to-number
10669 (match-string 5 ans))0)))
10670 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
10671 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
10672 t t ans)))
10674 ;; Check if there is a time range
10675 (when (boundp 'org-end-time-was-given)
10676 (setq org-time-was-given nil)
10677 (when (and (string-match org-plain-time-of-day-regexp ans)
10678 (match-end 8))
10679 (setq org-end-time-was-given (match-string 8 ans))
10680 (setq ans (concat (substring ans 0 (match-beginning 7))
10681 (substring ans (match-end 7))))))
10683 (setq tl (parse-time-string ans)
10684 day (or (nth 3 tl) (nth 3 defdecode))
10685 month (or (nth 4 tl)
10686 (if (and org-read-date-prefer-future
10687 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
10688 (1+ (nth 4 defdecode))
10689 (nth 4 defdecode)))
10690 year (or (nth 5 tl)
10691 (if (and org-read-date-prefer-future
10692 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
10693 (1+ (nth 5 defdecode))
10694 (nth 5 defdecode)))
10695 hour (or (nth 2 tl) (nth 2 defdecode))
10696 minute (or (nth 1 tl) (nth 1 defdecode))
10697 second (or (nth 0 tl) 0)
10698 wday (nth 6 tl))
10700 ;; Special date definitions below
10701 (cond
10702 (iso-week
10703 ;; There was an iso week
10704 (setq year (or iso-year year)
10705 day (or iso-weekday wday 1)
10706 wday nil ; to make sure that the trigger below does not match
10707 iso-date (calendar-gregorian-from-absolute
10708 (calendar-absolute-from-iso
10709 (list iso-week day year))))
10710 ; FIXME: Should we also push ISO weeks into the future?
10711 ; (when (and org-read-date-prefer-future
10712 ; (not iso-year)
10713 ; (< (calendar-absolute-from-gregorian iso-date)
10714 ; (time-to-days (current-time))))
10715 ; (setq year (1+ year)
10716 ; iso-date (calendar-gregorian-from-absolute
10717 ; (calendar-absolute-from-iso
10718 ; (list iso-week day year)))))
10719 (setq month (car iso-date)
10720 year (nth 2 iso-date)
10721 day (nth 1 iso-date)))
10722 (deltan
10723 (unless deltadef
10724 (let ((now (decode-time (current-time))))
10725 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
10726 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
10727 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
10728 ((equal deltaw "m") (setq month (+ month deltan)))
10729 ((equal deltaw "y") (setq year (+ year deltan)))))
10730 ((and wday (not (nth 3 tl)))
10731 ;; Weekday was given, but no day, so pick that day in the week
10732 ;; on or after the derived date.
10733 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
10734 (unless (equal wday wday1)
10735 (setq day (+ day (% (- wday wday1 -7) 7))))))
10736 (if (and (boundp 'org-time-was-given)
10737 (nth 2 tl))
10738 (setq org-time-was-given t))
10739 (if (< year 100) (setq year (+ 2000 year)))
10740 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
10741 (list second minute hour day month year)))
10743 (defvar parse-time-weekdays)
10745 (defun org-read-date-get-relative (s today default)
10746 "Check string S for special relative date string.
10747 TODAY and DEFAULT are internal times, for today and for a default.
10748 Return shift list (N what def-flag)
10749 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
10750 N is the number of WHATs to shift.
10751 DEF-FLAG is t when a double ++ or -- indicates shift relative to
10752 the DEFAULT date rather than TODAY."
10753 (when (and
10754 (string-match
10755 (concat
10756 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
10757 "\\([0-9]+\\)?"
10758 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
10759 "\\([ \t]\\|$\\)") s)
10760 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
10761 (let* ((dir (if (> (match-end 1) (match-beginning 1))
10762 (string-to-char (substring (match-string 1 s) -1))
10763 ?+))
10764 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
10765 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
10766 (what (if (match-end 3) (match-string 3 s) "d"))
10767 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
10768 (date (if rel default today))
10769 (wday (nth 6 (decode-time date)))
10770 delta)
10771 (if wday1
10772 (progn
10773 (setq delta (mod (+ 7 (- wday1 wday)) 7))
10774 (if (= dir ?-) (setq delta (- delta 7)))
10775 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
10776 (list delta "d" rel))
10777 (list (* n (if (= dir ?-) -1 1)) what rel)))))
10779 (defun org-eval-in-calendar (form &optional keepdate)
10780 "Eval FORM in the calendar window and return to current window.
10781 Also, store the cursor date in variable org-ans2."
10782 (let ((sw (selected-window)))
10783 (select-window (get-buffer-window "*Calendar*"))
10784 (eval form)
10785 (when (and (not keepdate) (calendar-cursor-to-date))
10786 (let* ((date (calendar-cursor-to-date))
10787 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10788 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
10789 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
10790 (select-window sw)))
10792 (defun org-calendar-select ()
10793 "Return to `org-read-date' with the date currently selected.
10794 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
10795 (interactive)
10796 (when (calendar-cursor-to-date)
10797 (let* ((date (calendar-cursor-to-date))
10798 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10799 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
10800 (if (active-minibuffer-window) (exit-minibuffer))))
10802 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
10803 "Insert a date stamp for the date given by the internal TIME.
10804 WITH-HM means, use the stamp format that includes the time of the day.
10805 INACTIVE means use square brackets instead of angular ones, so that the
10806 stamp will not contribute to the agenda.
10807 PRE and POST are optional strings to be inserted before and after the
10808 stamp.
10809 The command returns the inserted time stamp."
10810 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
10811 stamp)
10812 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
10813 (insert-before-markers (or pre ""))
10814 (insert-before-markers (setq stamp (format-time-string fmt time)))
10815 (when (listp extra)
10816 (setq extra (car extra))
10817 (if (and (stringp extra)
10818 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
10819 (setq extra (format "-%02d:%02d"
10820 (string-to-number (match-string 1 extra))
10821 (string-to-number (match-string 2 extra))))
10822 (setq extra nil)))
10823 (when extra
10824 (backward-char 1)
10825 (insert-before-markers extra)
10826 (forward-char 1))
10827 (insert-before-markers (or post ""))
10828 (setq org-last-inserted-timestamp stamp)))
10830 (defun org-toggle-time-stamp-overlays ()
10831 "Toggle the use of custom time stamp formats."
10832 (interactive)
10833 (setq org-display-custom-times (not org-display-custom-times))
10834 (unless org-display-custom-times
10835 (let ((p (point-min)) (bmp (buffer-modified-p)))
10836 (while (setq p (next-single-property-change p 'display))
10837 (if (and (get-text-property p 'display)
10838 (eq (get-text-property p 'face) 'org-date))
10839 (remove-text-properties
10840 p (setq p (next-single-property-change p 'display))
10841 '(display t))))
10842 (set-buffer-modified-p bmp)))
10843 (if (featurep 'xemacs)
10844 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
10845 (org-restart-font-lock)
10846 (setq org-table-may-need-update t)
10847 (if org-display-custom-times
10848 (message "Time stamps are overlayed with custom format")
10849 (message "Time stamp overlays removed")))
10851 (defun org-display-custom-time (beg end)
10852 "Overlay modified time stamp format over timestamp between BEG and END."
10853 (let* ((ts (buffer-substring beg end))
10854 t1 w1 with-hm tf time str w2 (off 0))
10855 (save-match-data
10856 (setq t1 (org-parse-time-string ts t))
10857 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
10858 (setq off (- (match-end 0) (match-beginning 0)))))
10859 (setq end (- end off))
10860 (setq w1 (- end beg)
10861 with-hm (and (nth 1 t1) (nth 2 t1))
10862 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
10863 time (org-fix-decoded-time t1)
10864 str (org-add-props
10865 (format-time-string
10866 (substring tf 1 -1) (apply 'encode-time time))
10867 nil 'mouse-face 'highlight)
10868 w2 (length str))
10869 (if (not (= w2 w1))
10870 (add-text-properties (1+ beg) (+ 2 beg)
10871 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
10872 (if (featurep 'xemacs)
10873 (progn
10874 (put-text-property beg end 'invisible t)
10875 (put-text-property beg end 'end-glyph (make-glyph str)))
10876 (put-text-property beg end 'display str))))
10878 (defun org-translate-time (string)
10879 "Translate all timestamps in STRING to custom format.
10880 But do this only if the variable `org-display-custom-times' is set."
10881 (when org-display-custom-times
10882 (save-match-data
10883 (let* ((start 0)
10884 (re org-ts-regexp-both)
10885 t1 with-hm inactive tf time str beg end)
10886 (while (setq start (string-match re string start))
10887 (setq beg (match-beginning 0)
10888 end (match-end 0)
10889 t1 (save-match-data
10890 (org-parse-time-string (substring string beg end) t))
10891 with-hm (and (nth 1 t1) (nth 2 t1))
10892 inactive (equal (substring string beg (1+ beg)) "[")
10893 tf (funcall (if with-hm 'cdr 'car)
10894 org-time-stamp-custom-formats)
10895 time (org-fix-decoded-time t1)
10896 str (format-time-string
10897 (concat
10898 (if inactive "[" "<") (substring tf 1 -1)
10899 (if inactive "]" ">"))
10900 (apply 'encode-time time))
10901 string (replace-match str t t string)
10902 start (+ start (length str)))))))
10903 string)
10905 (defun org-fix-decoded-time (time)
10906 "Set 0 instead of nil for the first 6 elements of time.
10907 Don't touch the rest."
10908 (let ((n 0))
10909 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
10911 (defun org-days-to-time (timestamp-string)
10912 "Difference between TIMESTAMP-STRING and now in days."
10913 (- (time-to-days (org-time-string-to-time timestamp-string))
10914 (time-to-days (current-time))))
10916 (defun org-deadline-close (timestamp-string &optional ndays)
10917 "Is the time in TIMESTAMP-STRING close to the current date?"
10918 (setq ndays (or ndays (org-get-wdays timestamp-string)))
10919 (and (< (org-days-to-time timestamp-string) ndays)
10920 (not (org-entry-is-done-p))))
10922 (defun org-get-wdays (ts)
10923 "Get the deadline lead time appropriate for timestring TS."
10924 (cond
10925 ((<= org-deadline-warning-days 0)
10926 ;; 0 or negative, enforce this value no matter what
10927 (- org-deadline-warning-days))
10928 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
10929 ;; lead time is specified.
10930 (floor (* (string-to-number (match-string 1 ts))
10931 (cdr (assoc (match-string 2 ts)
10932 '(("d" . 1) ("w" . 7)
10933 ("m" . 30.4) ("y" . 365.25)))))))
10934 ;; go for the default.
10935 (t org-deadline-warning-days)))
10937 (defun org-calendar-select-mouse (ev)
10938 "Return to `org-read-date' with the date currently selected.
10939 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
10940 (interactive "e")
10941 (mouse-set-point ev)
10942 (when (calendar-cursor-to-date)
10943 (let* ((date (calendar-cursor-to-date))
10944 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10945 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
10946 (if (active-minibuffer-window) (exit-minibuffer))))
10948 (defun org-check-deadlines (ndays)
10949 "Check if there are any deadlines due or past due.
10950 A deadline is considered due if it happens within `org-deadline-warning-days'
10951 days from today's date. If the deadline appears in an entry marked DONE,
10952 it is not shown. The prefix arg NDAYS can be used to test that many
10953 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
10954 (interactive "P")
10955 (let* ((org-warn-days
10956 (cond
10957 ((equal ndays '(4)) 100000)
10958 (ndays (prefix-numeric-value ndays))
10959 (t (abs org-deadline-warning-days))))
10960 (case-fold-search nil)
10961 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
10962 (callback
10963 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
10965 (message "%d deadlines past-due or due within %d days"
10966 (org-occur regexp nil callback)
10967 org-warn-days)))
10969 (defun org-check-before-date (date)
10970 "Check if there are deadlines or scheduled entries before DATE."
10971 (interactive (list (org-read-date)))
10972 (let ((case-fold-search nil)
10973 (regexp (concat "\\<\\(" org-deadline-string
10974 "\\|" org-scheduled-string
10975 "\\) *<\\([^>]+\\)>"))
10976 (callback
10977 (lambda () (time-less-p
10978 (org-time-string-to-time (match-string 2))
10979 (org-time-string-to-time date)))))
10980 (message "%d entries before %s"
10981 (org-occur regexp nil callback) date)))
10983 (defun org-evaluate-time-range (&optional to-buffer)
10984 "Evaluate a time range by computing the difference between start and end.
10985 Normally the result is just printed in the echo area, but with prefix arg
10986 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
10987 If the time range is actually in a table, the result is inserted into the
10988 next column.
10989 For time difference computation, a year is assumed to be exactly 365
10990 days in order to avoid rounding problems."
10991 (interactive "P")
10993 (org-clock-update-time-maybe)
10994 (save-excursion
10995 (unless (org-at-date-range-p t)
10996 (goto-char (point-at-bol))
10997 (re-search-forward org-tr-regexp-both (point-at-eol) t))
10998 (if (not (org-at-date-range-p t))
10999 (error "Not at a time-stamp range, and none found in current line")))
11000 (let* ((ts1 (match-string 1))
11001 (ts2 (match-string 2))
11002 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
11003 (match-end (match-end 0))
11004 (time1 (org-time-string-to-time ts1))
11005 (time2 (org-time-string-to-time ts2))
11006 (t1 (time-to-seconds time1))
11007 (t2 (time-to-seconds time2))
11008 (diff (abs (- t2 t1)))
11009 (negative (< (- t2 t1) 0))
11010 ;; (ys (floor (* 365 24 60 60)))
11011 (ds (* 24 60 60))
11012 (hs (* 60 60))
11013 (fy "%dy %dd %02d:%02d")
11014 (fy1 "%dy %dd")
11015 (fd "%dd %02d:%02d")
11016 (fd1 "%dd")
11017 (fh "%02d:%02d")
11018 y d h m align)
11019 (if havetime
11020 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11022 d (floor (/ diff ds)) diff (mod diff ds)
11023 h (floor (/ diff hs)) diff (mod diff hs)
11024 m (floor (/ diff 60)))
11025 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11027 d (floor (+ (/ diff ds) 0.5))
11028 h 0 m 0))
11029 (if (not to-buffer)
11030 (message "%s" (org-make-tdiff-string y d h m))
11031 (if (org-at-table-p)
11032 (progn
11033 (goto-char match-end)
11034 (setq align t)
11035 (and (looking-at " *|") (goto-char (match-end 0))))
11036 (goto-char match-end))
11037 (if (looking-at
11038 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
11039 (replace-match ""))
11040 (if negative (insert " -"))
11041 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
11042 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
11043 (insert " " (format fh h m))))
11044 (if align (org-table-align))
11045 (message "Time difference inserted")))))
11047 (defun org-make-tdiff-string (y d h m)
11048 (let ((fmt "")
11049 (l nil))
11050 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
11051 l (push y l)))
11052 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
11053 l (push d l)))
11054 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
11055 l (push h l)))
11056 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
11057 l (push m l)))
11058 (apply 'format fmt (nreverse l))))
11060 (defun org-time-string-to-time (s)
11061 (apply 'encode-time (org-parse-time-string s)))
11063 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
11064 "Convert a time stamp to an absolute day number.
11065 If there is a specifyer for a cyclic time stamp, get the closest date to
11066 DAYNR.
11067 PREFER and SHOW_ALL are passed through to `org-closest-date'."
11068 (cond
11069 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
11070 (if (org-diary-sexp-entry (match-string 1 s) "" date)
11071 daynr
11072 (+ daynr 1000)))
11073 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
11074 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
11075 (time-to-days (current-time))) (match-string 0 s)
11076 prefer show-all))
11077 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
11079 (defun org-days-to-iso-week (days)
11080 "Return the iso week number."
11081 (require 'cal-iso)
11082 (car (calendar-iso-from-absolute days)))
11084 (defun org-small-year-to-year (year)
11085 "Convert 2-digit years into 4-digit years.
11086 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
11087 The year 2000 cannot be abbreviated. Any year lager than 99
11088 is retrned unchanged."
11089 (if (< year 38)
11090 (setq year (+ 2000 year))
11091 (if (< year 100)
11092 (setq year (+ 1900 year))))
11093 year)
11095 (defun org-time-from-absolute (d)
11096 "Return the time corresponding to date D.
11097 D may be an absolute day number, or a calendar-type list (month day year)."
11098 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
11099 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
11101 (defun org-calendar-holiday ()
11102 "List of holidays, for Diary display in Org-mode."
11103 (require 'holidays)
11104 (let ((hl (funcall
11105 (if (fboundp 'calendar-check-holidays)
11106 'calendar-check-holidays 'check-calendar-holidays) date)))
11107 (if hl (mapconcat 'identity hl "; "))))
11109 (defun org-diary-sexp-entry (sexp entry date)
11110 "Process a SEXP diary ENTRY for DATE."
11111 (require 'diary-lib)
11112 (let ((result (if calendar-debug-sexp
11113 (let ((stack-trace-on-error t))
11114 (eval (car (read-from-string sexp))))
11115 (condition-case nil
11116 (eval (car (read-from-string sexp)))
11117 (error
11118 (beep)
11119 (message "Bad sexp at line %d in %s: %s"
11120 (org-current-line)
11121 (buffer-file-name) sexp)
11122 (sleep-for 2))))))
11123 (cond ((stringp result) result)
11124 ((and (consp result)
11125 (stringp (cdr result))) (cdr result))
11126 (result entry)
11127 (t nil))))
11129 (defun org-diary-to-ical-string (frombuf)
11130 "Get iCalendar entries from diary entries in buffer FROMBUF.
11131 This uses the icalendar.el library."
11132 (let* ((tmpdir (if (featurep 'xemacs)
11133 (temp-directory)
11134 temporary-file-directory))
11135 (tmpfile (make-temp-name
11136 (expand-file-name "orgics" tmpdir)))
11137 buf rtn b e)
11138 (save-excursion
11139 (set-buffer frombuf)
11140 (icalendar-export-region (point-min) (point-max) tmpfile)
11141 (setq buf (find-buffer-visiting tmpfile))
11142 (set-buffer buf)
11143 (goto-char (point-min))
11144 (if (re-search-forward "^BEGIN:VEVENT" nil t)
11145 (setq b (match-beginning 0)))
11146 (goto-char (point-max))
11147 (if (re-search-backward "^END:VEVENT" nil t)
11148 (setq e (match-end 0)))
11149 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
11150 (kill-buffer buf)
11151 (delete-file tmpfile)
11152 rtn))
11154 (defun org-closest-date (start current change prefer show-all)
11155 "Find the date closest to CURRENT that is consistent with START and CHANGE.
11156 When PREFER is `past' return a date that is either CURRENT or past.
11157 When PREFER is `future', return a date that is either CURRENT or future.
11158 When SHOW-ALL is nil, only return the current occurence of a time stamp."
11159 ;; Make the proper lists from the dates
11160 (catch 'exit
11161 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
11162 dn dw sday cday n1 n2
11163 d m y y1 y2 date1 date2 nmonths nm ny m2)
11165 (setq start (org-date-to-gregorian start)
11166 current (org-date-to-gregorian
11167 (if show-all
11168 current
11169 (time-to-days (current-time))))
11170 sday (calendar-absolute-from-gregorian start)
11171 cday (calendar-absolute-from-gregorian current))
11173 (if (<= cday sday) (throw 'exit sday))
11175 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
11176 (setq dn (string-to-number (match-string 1 change))
11177 dw (cdr (assoc (match-string 2 change) a1)))
11178 (error "Invalid change specifyer: %s" change))
11179 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
11180 (cond
11181 ((eq dw 'day)
11182 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
11183 n2 (+ n1 dn)))
11184 ((eq dw 'year)
11185 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
11186 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
11187 (setq date1 (list m d y1)
11188 n1 (calendar-absolute-from-gregorian date1)
11189 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
11190 n2 (calendar-absolute-from-gregorian date2)))
11191 ((eq dw 'month)
11192 ;; approx number of month between the two dates
11193 (setq nmonths (floor (/ (- cday sday) 30.436875)))
11194 ;; How often does dn fit in there?
11195 (setq d (nth 1 start) m (car start) y (nth 2 start)
11196 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
11197 m (+ m nm)
11198 ny (floor (/ m 12))
11199 y (+ y ny)
11200 m (- m (* ny 12)))
11201 (while (> m 12) (setq m (- m 12) y (1+ y)))
11202 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
11203 (setq m2 (+ m dn) y2 y)
11204 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11205 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
11206 (while (<= n2 cday)
11207 (setq n1 n2 m m2 y y2)
11208 (setq m2 (+ m dn) y2 y)
11209 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11210 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
11211 (if show-all
11212 (cond
11213 ((eq prefer 'past) n1)
11214 ((eq prefer 'future) (if (= cday n1) n1 n2))
11215 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
11216 (cond
11217 ((eq prefer 'past) n1)
11218 ((eq prefer 'future) (if (= cday n1) n1 n2))
11219 (t (if (= cday n1) n1 n2)))))))
11221 (defun org-date-to-gregorian (date)
11222 "Turn any specification of DATE into a gregorian date for the calendar."
11223 (cond ((integerp date) (calendar-gregorian-from-absolute date))
11224 ((and (listp date) (= (length date) 3)) date)
11225 ((stringp date)
11226 (setq date (org-parse-time-string date))
11227 (list (nth 4 date) (nth 3 date) (nth 5 date)))
11228 ((listp date)
11229 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
11231 (defun org-parse-time-string (s &optional nodefault)
11232 "Parse the standard Org-mode time string.
11233 This should be a lot faster than the normal `parse-time-string'.
11234 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
11235 hour and minute fields will be nil if not given."
11236 (if (string-match org-ts-regexp0 s)
11237 (list 0
11238 (if (or (match-beginning 8) (not nodefault))
11239 (string-to-number (or (match-string 8 s) "0")))
11240 (if (or (match-beginning 7) (not nodefault))
11241 (string-to-number (or (match-string 7 s) "0")))
11242 (string-to-number (match-string 4 s))
11243 (string-to-number (match-string 3 s))
11244 (string-to-number (match-string 2 s))
11245 nil nil nil)
11246 (make-list 9 0)))
11248 (defun org-timestamp-up (&optional arg)
11249 "Increase the date item at the cursor by one.
11250 If the cursor is on the year, change the year. If it is on the month or
11251 the day, change that.
11252 With prefix ARG, change by that many units."
11253 (interactive "p")
11254 (org-timestamp-change (prefix-numeric-value arg)))
11256 (defun org-timestamp-down (&optional arg)
11257 "Decrease the date item at the cursor by one.
11258 If the cursor is on the year, change the year. If it is on the month or
11259 the day, change that.
11260 With prefix ARG, change by that many units."
11261 (interactive "p")
11262 (org-timestamp-change (- (prefix-numeric-value arg))))
11264 (defun org-timestamp-up-day (&optional arg)
11265 "Increase the date in the time stamp by one day.
11266 With prefix ARG, change that many days."
11267 (interactive "p")
11268 (if (and (not (org-at-timestamp-p t))
11269 (org-on-heading-p))
11270 (org-todo 'up)
11271 (org-timestamp-change (prefix-numeric-value arg) 'day)))
11273 (defun org-timestamp-down-day (&optional arg)
11274 "Decrease the date in the time stamp by one day.
11275 With prefix ARG, change that many days."
11276 (interactive "p")
11277 (if (and (not (org-at-timestamp-p t))
11278 (org-on-heading-p))
11279 (org-todo 'down)
11280 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
11282 (defun org-at-timestamp-p (&optional inactive-ok)
11283 "Determine if the cursor is in or at a timestamp."
11284 (interactive)
11285 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
11286 (pos (point))
11287 (ans (or (looking-at tsr)
11288 (save-excursion
11289 (skip-chars-backward "^[<\n\r\t")
11290 (if (> (point) (point-min)) (backward-char 1))
11291 (and (looking-at tsr)
11292 (> (- (match-end 0) pos) -1))))))
11293 (and ans
11294 (boundp 'org-ts-what)
11295 (setq org-ts-what
11296 (cond
11297 ((= pos (match-beginning 0)) 'bracket)
11298 ((= pos (1- (match-end 0))) 'bracket)
11299 ((org-pos-in-match-range pos 2) 'year)
11300 ((org-pos-in-match-range pos 3) 'month)
11301 ((org-pos-in-match-range pos 7) 'hour)
11302 ((org-pos-in-match-range pos 8) 'minute)
11303 ((or (org-pos-in-match-range pos 4)
11304 (org-pos-in-match-range pos 5)) 'day)
11305 ((and (> pos (or (match-end 8) (match-end 5)))
11306 (< pos (match-end 0)))
11307 (- pos (or (match-end 8) (match-end 5))))
11308 (t 'day))))
11309 ans))
11311 (defun org-toggle-timestamp-type ()
11312 "Toggle the type (<active> or [inactive]) of a time stamp."
11313 (interactive)
11314 (when (org-at-timestamp-p t)
11315 (let ((beg (match-beginning 0)) (end (match-end 0))
11316 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
11317 (save-excursion
11318 (goto-char beg)
11319 (while (re-search-forward "[][<>]" end t)
11320 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
11321 t t)))
11322 (message "Timestamp is now %sactive"
11323 (if (equal (char-after beg) ?<) "" "in")))))
11325 (defun org-timestamp-change (n &optional what)
11326 "Change the date in the time stamp at point.
11327 The date will be changed by N times WHAT. WHAT can be `day', `month',
11328 `year', `minute', `second'. If WHAT is not given, the cursor position
11329 in the timestamp determines what will be changed."
11330 (let ((pos (point))
11331 with-hm inactive
11332 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
11333 org-ts-what
11334 extra rem
11335 ts time time0)
11336 (if (not (org-at-timestamp-p t))
11337 (error "Not at a timestamp"))
11338 (if (and (not what) (eq org-ts-what 'bracket))
11339 (org-toggle-timestamp-type)
11340 (if (and (not what) (not (eq org-ts-what 'day))
11341 org-display-custom-times
11342 (get-text-property (point) 'display)
11343 (not (get-text-property (1- (point)) 'display)))
11344 (setq org-ts-what 'day))
11345 (setq org-ts-what (or what org-ts-what)
11346 inactive (= (char-after (match-beginning 0)) ?\[)
11347 ts (match-string 0))
11348 (replace-match "")
11349 (if (string-match
11350 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
11352 (setq extra (match-string 1 ts)))
11353 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
11354 (setq with-hm t))
11355 (setq time0 (org-parse-time-string ts))
11356 (when (and (eq org-ts-what 'minute)
11357 (eq current-prefix-arg nil))
11358 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
11359 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
11360 (setcar (cdr time0) (+ (nth 1 time0)
11361 (if (> n 0) (- rem) (- dm rem))))))
11362 (setq time
11363 (encode-time (or (car time0) 0)
11364 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
11365 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
11366 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
11367 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
11368 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
11369 (nthcdr 6 time0)))
11370 (when (integerp org-ts-what)
11371 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
11372 (if (eq what 'calendar)
11373 (let ((cal-date (org-get-date-from-calendar)))
11374 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
11375 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
11376 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
11377 (setcar time0 (or (car time0) 0))
11378 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
11379 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
11380 (setq time (apply 'encode-time time0))))
11381 (setq org-last-changed-timestamp
11382 (org-insert-time-stamp time with-hm inactive nil nil extra))
11383 (org-clock-update-time-maybe)
11384 (goto-char pos)
11385 ;; Try to recenter the calendar window, if any
11386 (if (and org-calendar-follow-timestamp-change
11387 (get-buffer-window "*Calendar*" t)
11388 (memq org-ts-what '(day month year)))
11389 (org-recenter-calendar (time-to-days time))))))
11391 (defun org-modify-ts-extra (s pos n dm)
11392 "Change the different parts of the lead-time and repeat fields in timestamp."
11393 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
11394 ng h m new rem)
11395 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
11396 (cond
11397 ((or (org-pos-in-match-range pos 2)
11398 (org-pos-in-match-range pos 3))
11399 (setq m (string-to-number (match-string 3 s))
11400 h (string-to-number (match-string 2 s)))
11401 (if (org-pos-in-match-range pos 2)
11402 (setq h (+ h n))
11403 (setq n (* dm (org-no-warnings (signum n))))
11404 (when (not (= 0 (setq rem (% m dm))))
11405 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
11406 (setq m (+ m n)))
11407 (if (< m 0) (setq m (+ m 60) h (1- h)))
11408 (if (> m 59) (setq m (- m 60) h (1+ h)))
11409 (setq h (min 24 (max 0 h)))
11410 (setq ng 1 new (format "-%02d:%02d" h m)))
11411 ((org-pos-in-match-range pos 6)
11412 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
11413 ((org-pos-in-match-range pos 5)
11414 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
11416 ((org-pos-in-match-range pos 9)
11417 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
11418 ((org-pos-in-match-range pos 8)
11419 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
11421 (when ng
11422 (setq s (concat
11423 (substring s 0 (match-beginning ng))
11425 (substring s (match-end ng))))))
11428 (defun org-recenter-calendar (date)
11429 "If the calendar is visible, recenter it to DATE."
11430 (let* ((win (selected-window))
11431 (cwin (get-buffer-window "*Calendar*" t))
11432 (calendar-move-hook nil))
11433 (when cwin
11434 (select-window cwin)
11435 (calendar-goto-date (if (listp date) date
11436 (calendar-gregorian-from-absolute date)))
11437 (select-window win))))
11439 (defun org-goto-calendar (&optional arg)
11440 "Go to the Emacs calendar at the current date.
11441 If there is a time stamp in the current line, go to that date.
11442 A prefix ARG can be used to force the current date."
11443 (interactive "P")
11444 (let ((tsr org-ts-regexp) diff
11445 (calendar-move-hook nil)
11446 (calendar-view-holidays-initially-flag nil)
11447 (view-calendar-holidays-initially nil)
11448 (calendar-view-diary-initially-flag nil)
11449 (view-diary-entries-initially nil))
11450 (if (or (org-at-timestamp-p)
11451 (save-excursion
11452 (beginning-of-line 1)
11453 (looking-at (concat ".*" tsr))))
11454 (let ((d1 (time-to-days (current-time)))
11455 (d2 (time-to-days
11456 (org-time-string-to-time (match-string 1)))))
11457 (setq diff (- d2 d1))))
11458 (calendar)
11459 (calendar-goto-today)
11460 (if (and diff (not arg)) (calendar-forward-day diff))))
11462 (defun org-get-date-from-calendar ()
11463 "Return a list (month day year) of date at point in calendar."
11464 (with-current-buffer "*Calendar*"
11465 (save-match-data
11466 (calendar-cursor-to-date))))
11468 (defun org-date-from-calendar ()
11469 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
11470 If there is already a time stamp at the cursor position, update it."
11471 (interactive)
11472 (if (org-at-timestamp-p t)
11473 (org-timestamp-change 0 'calendar)
11474 (let ((cal-date (org-get-date-from-calendar)))
11475 (org-insert-time-stamp
11476 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
11478 (defun org-minutes-to-hh:mm-string (m)
11479 "Compute H:MM from a number of minutes."
11480 (let ((h (/ m 60)))
11481 (setq m (- m (* 60 h)))
11482 (format org-time-clocksum-format h m)))
11484 (defun org-hh:mm-string-to-minutes (s)
11485 "Convert a string H:MM to a number of minutes."
11486 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
11487 (+ (* (string-to-number (match-string 1 s)) 60)
11488 (string-to-number (match-string 2 s)))
11491 ;;;; Agenda files
11493 ;;;###autoload
11494 (defun org-iswitchb (&optional arg)
11495 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
11496 With a prefix argument, restrict available to files.
11497 With two prefix arguments, restrict available buffers to agenda files.
11499 Due to some yet unresolved reason, the global function
11500 `iswitchb-mode' needs to be active for this function to work."
11501 (interactive "P")
11502 (require 'iswitchb)
11503 (let ((enabled iswitchb-mode) blist)
11504 (or enabled (iswitchb-mode 1))
11505 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
11506 ((equal arg '(16)) (org-buffer-list 'agenda))
11507 (t (org-buffer-list))))
11508 (unwind-protect
11509 (let ((iswitchb-make-buflist-hook
11510 (lambda ()
11511 (setq iswitchb-temp-buflist
11512 (mapcar 'buffer-name blist)))))
11513 (switch-to-buffer
11514 (iswitchb-read-buffer
11515 "Switch-to: " nil t))
11516 (or enabled (iswitchb-mode -1))))))
11518 (defun org-buffer-list (&optional predicate exclude-tmp)
11519 "Return a list of Org buffers.
11520 PREDICATE can be `export', `files' or `agenda'.
11522 export restrict the list to Export buffers.
11523 files restrict the list to buffers visiting Org files.
11524 agenda restrict the list to buffers visiting agenda files.
11526 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
11527 (let* ((bfn nil)
11528 (agenda-files (and (eq predicate 'agenda)
11529 (mapcar 'file-truename (org-agenda-files t))))
11530 (filter
11531 (cond
11532 ((eq predicate 'files)
11533 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
11534 ((eq predicate 'export)
11535 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
11536 ((eq predicate 'agenda)
11537 (lambda (b)
11538 (with-current-buffer b
11539 (and (eq major-mode 'org-mode)
11540 (setq bfn (buffer-file-name b))
11541 (member (file-truename bfn) agenda-files)))))
11542 (t (lambda (b) (with-current-buffer b
11543 (or (eq major-mode 'org-mode)
11544 (string-match "\*Org .*Export"
11545 (buffer-name b)))))))))
11546 (delq nil
11547 (mapcar
11548 (lambda(b)
11549 (if (and (funcall filter b)
11550 (or (not exclude-tmp)
11551 (not (string-match "tmp" (buffer-name b)))))
11553 nil))
11554 (buffer-list)))))
11556 (defun org-agenda-files (&optional unrestricted archives)
11557 "Get the list of agenda files.
11558 Optional UNRESTRICTED means return the full list even if a restriction
11559 is currently in place.
11560 When ARCHIVES is t, include all archive files hat are really being
11561 used by the agenda files. If ARCHIVE is `ifmode', do this only if
11562 `org-agenda-archives-mode' is t."
11563 (let ((files
11564 (cond
11565 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
11566 ((stringp org-agenda-files) (org-read-agenda-file-list))
11567 ((listp org-agenda-files) org-agenda-files)
11568 (t (error "Invalid value of `org-agenda-files'")))))
11569 (setq files (apply 'append
11570 (mapcar (lambda (f)
11571 (if (file-directory-p f)
11572 (directory-files
11573 f t org-agenda-file-regexp)
11574 (list f)))
11575 files)))
11576 (when org-agenda-skip-unavailable-files
11577 (setq files (delq nil
11578 (mapcar (function
11579 (lambda (file)
11580 (and (file-readable-p file) file)))
11581 files))))
11582 (when (or (eq archives t)
11583 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
11584 (setq files (org-add-archive-files files)))
11585 files))
11587 (defun org-edit-agenda-file-list ()
11588 "Edit the list of agenda files.
11589 Depending on setup, this either uses customize to edit the variable
11590 `org-agenda-files', or it visits the file that is holding the list. In the
11591 latter case, the buffer is set up in a way that saving it automatically kills
11592 the buffer and restores the previous window configuration."
11593 (interactive)
11594 (if (stringp org-agenda-files)
11595 (let ((cw (current-window-configuration)))
11596 (find-file org-agenda-files)
11597 (org-set-local 'org-window-configuration cw)
11598 (org-add-hook 'after-save-hook
11599 (lambda ()
11600 (set-window-configuration
11601 (prog1 org-window-configuration
11602 (kill-buffer (current-buffer))))
11603 (org-install-agenda-files-menu)
11604 (message "New agenda file list installed"))
11605 nil 'local)
11606 (message "%s" (substitute-command-keys
11607 "Edit list and finish with \\[save-buffer]")))
11608 (customize-variable 'org-agenda-files)))
11610 (defun org-store-new-agenda-file-list (list)
11611 "Set new value for the agenda file list and save it correcly."
11612 (if (stringp org-agenda-files)
11613 (let ((f org-agenda-files) b)
11614 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
11615 (with-temp-file f
11616 (insert (mapconcat 'identity list "\n") "\n")))
11617 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
11618 (setq org-agenda-files list)
11619 (customize-save-variable 'org-agenda-files org-agenda-files))))
11621 (defun org-read-agenda-file-list ()
11622 "Read the list of agenda files from a file."
11623 (when (file-directory-p org-agenda-files)
11624 (error "`org-agenda-files' cannot be a single directory"))
11625 (when (stringp org-agenda-files)
11626 (with-temp-buffer
11627 (insert-file-contents org-agenda-files)
11628 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
11631 ;;;###autoload
11632 (defun org-cycle-agenda-files ()
11633 "Cycle through the files in `org-agenda-files'.
11634 If the current buffer visits an agenda file, find the next one in the list.
11635 If the current buffer does not, find the first agenda file."
11636 (interactive)
11637 (let* ((fs (org-agenda-files t))
11638 (files (append fs (list (car fs))))
11639 (tcf (if buffer-file-name (file-truename buffer-file-name)))
11640 file)
11641 (unless files (error "No agenda files"))
11642 (catch 'exit
11643 (while (setq file (pop files))
11644 (if (equal (file-truename file) tcf)
11645 (when (car files)
11646 (find-file (car files))
11647 (throw 'exit t))))
11648 (find-file (car fs)))
11649 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
11651 (defun org-agenda-file-to-front (&optional to-end)
11652 "Move/add the current file to the top of the agenda file list.
11653 If the file is not present in the list, it is added to the front. If it is
11654 present, it is moved there. With optional argument TO-END, add/move to the
11655 end of the list."
11656 (interactive "P")
11657 (let ((org-agenda-skip-unavailable-files nil)
11658 (file-alist (mapcar (lambda (x)
11659 (cons (file-truename x) x))
11660 (org-agenda-files t)))
11661 (ctf (file-truename buffer-file-name))
11662 x had)
11663 (setq x (assoc ctf file-alist) had x)
11665 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
11666 (if to-end
11667 (setq file-alist (append (delq x file-alist) (list x)))
11668 (setq file-alist (cons x (delq x file-alist))))
11669 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
11670 (org-install-agenda-files-menu)
11671 (message "File %s to %s of agenda file list"
11672 (if had "moved" "added") (if to-end "end" "front"))))
11674 (defun org-remove-file (&optional file)
11675 "Remove current file from the list of files in variable `org-agenda-files'.
11676 These are the files which are being checked for agenda entries.
11677 Optional argument FILE means, use this file instead of the current."
11678 (interactive)
11679 (let* ((org-agenda-skip-unavailable-files nil)
11680 (file (or file buffer-file-name))
11681 (true-file (file-truename file))
11682 (afile (abbreviate-file-name file))
11683 (files (delq nil (mapcar
11684 (lambda (x)
11685 (if (equal true-file
11686 (file-truename x))
11687 nil x))
11688 (org-agenda-files t)))))
11689 (if (not (= (length files) (length (org-agenda-files t))))
11690 (progn
11691 (org-store-new-agenda-file-list files)
11692 (org-install-agenda-files-menu)
11693 (message "Removed file: %s" afile))
11694 (message "File was not in list: %s (not removed)" afile))))
11696 (defun org-file-menu-entry (file)
11697 (vector file (list 'find-file file) t))
11699 (defun org-check-agenda-file (file)
11700 "Make sure FILE exists. If not, ask user what to do."
11701 (when (not (file-exists-p file))
11702 (message "non-existent file %s. [R]emove from list or [A]bort?"
11703 (abbreviate-file-name file))
11704 (let ((r (downcase (read-char-exclusive))))
11705 (cond
11706 ((equal r ?r)
11707 (org-remove-file file)
11708 (throw 'nextfile t))
11709 (t (error "Abort"))))))
11711 (defun org-get-agenda-file-buffer (file)
11712 "Get a buffer visiting FILE. If the buffer needs to be created, add
11713 it to the list of buffers which might be released later."
11714 (let ((buf (org-find-base-buffer-visiting file)))
11715 (if buf
11716 buf ; just return it
11717 ;; Make a new buffer and remember it
11718 (setq buf (find-file-noselect file))
11719 (if buf (push buf org-agenda-new-buffers))
11720 buf)))
11722 (defun org-release-buffers (blist)
11723 "Release all buffers in list, asking the user for confirmation when needed.
11724 When a buffer is unmodified, it is just killed. When modified, it is saved
11725 \(if the user agrees) and then killed."
11726 (let (buf file)
11727 (while (setq buf (pop blist))
11728 (setq file (buffer-file-name buf))
11729 (when (and (buffer-modified-p buf)
11730 file
11731 (y-or-n-p (format "Save file %s? " file)))
11732 (with-current-buffer buf (save-buffer)))
11733 (kill-buffer buf))))
11735 (defun org-prepare-agenda-buffers (files)
11736 "Create buffers for all agenda files, protect archived trees and comments."
11737 (interactive)
11738 (let ((pa '(:org-archived t))
11739 (pc '(:org-comment t))
11740 (pall '(:org-archived t :org-comment t))
11741 (inhibit-read-only t)
11742 (rea (concat ":" org-archive-tag ":"))
11743 bmp file re)
11744 (save-excursion
11745 (save-restriction
11746 (while (setq file (pop files))
11747 (if (bufferp file)
11748 (set-buffer file)
11749 (org-check-agenda-file file)
11750 (set-buffer (org-get-agenda-file-buffer file)))
11751 (widen)
11752 (setq bmp (buffer-modified-p))
11753 (org-refresh-category-properties)
11754 (setq org-todo-keywords-for-agenda
11755 (append org-todo-keywords-for-agenda org-todo-keywords-1))
11756 (setq org-done-keywords-for-agenda
11757 (append org-done-keywords-for-agenda org-done-keywords))
11758 (setq org-todo-keyword-alist-for-agenda
11759 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
11760 (setq org-tag-alist-for-agenda
11761 (append org-tag-alist-for-agenda org-tag-alist))
11763 (save-excursion
11764 (remove-text-properties (point-min) (point-max) pall)
11765 (when org-agenda-skip-archived-trees
11766 (goto-char (point-min))
11767 (while (re-search-forward rea nil t)
11768 (if (org-on-heading-p t)
11769 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
11770 (goto-char (point-min))
11771 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
11772 (while (re-search-forward re nil t)
11773 (add-text-properties
11774 (match-beginning 0) (org-end-of-subtree t) pc)))
11775 (set-buffer-modified-p bmp))))
11776 (setq org-todo-keyword-alist-for-agenda
11777 (org-uniquify org-todo-keyword-alist-for-agenda)
11778 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
11780 ;;;; Embedded LaTeX
11782 (defvar org-cdlatex-mode-map (make-sparse-keymap)
11783 "Keymap for the minor `org-cdlatex-mode'.")
11785 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
11786 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
11787 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
11788 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
11789 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
11791 (defvar org-cdlatex-texmathp-advice-is-done nil
11792 "Flag remembering if we have applied the advice to texmathp already.")
11794 (define-minor-mode org-cdlatex-mode
11795 "Toggle the minor `org-cdlatex-mode'.
11796 This mode supports entering LaTeX environment and math in LaTeX fragments
11797 in Org-mode.
11798 \\{org-cdlatex-mode-map}"
11799 nil " OCDL" nil
11800 (when org-cdlatex-mode (require 'cdlatex))
11801 (unless org-cdlatex-texmathp-advice-is-done
11802 (setq org-cdlatex-texmathp-advice-is-done t)
11803 (defadvice texmathp (around org-math-always-on activate)
11804 "Always return t in org-mode buffers.
11805 This is because we want to insert math symbols without dollars even outside
11806 the LaTeX math segments. If Orgmode thinks that point is actually inside
11807 en embedded LaTeX fragement, let texmathp do its job.
11808 \\[org-cdlatex-mode-map]"
11809 (interactive)
11810 (let (p)
11811 (cond
11812 ((not (org-mode-p)) ad-do-it)
11813 ((eq this-command 'cdlatex-math-symbol)
11814 (setq ad-return-value t
11815 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
11817 (let ((p (org-inside-LaTeX-fragment-p)))
11818 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
11819 (setq ad-return-value t
11820 texmathp-why '("Org-mode embedded math" . 0))
11821 (if p ad-do-it)))))))))
11823 (defun turn-on-org-cdlatex ()
11824 "Unconditionally turn on `org-cdlatex-mode'."
11825 (org-cdlatex-mode 1))
11827 (defun org-inside-LaTeX-fragment-p ()
11828 "Test if point is inside a LaTeX fragment.
11829 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
11830 sequence appearing also before point.
11831 Even though the matchers for math are configurable, this function assumes
11832 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
11833 delimiters are skipped when they have been removed by customization.
11834 The return value is nil, or a cons cell with the delimiter and
11835 and the position of this delimiter.
11837 This function does a reasonably good job, but can locally be fooled by
11838 for example currency specifications. For example it will assume being in
11839 inline math after \"$22.34\". The LaTeX fragment formatter will only format
11840 fragments that are properly closed, but during editing, we have to live
11841 with the uncertainty caused by missing closing delimiters. This function
11842 looks only before point, not after."
11843 (catch 'exit
11844 (let ((pos (point))
11845 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
11846 (lim (progn
11847 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
11848 (point)))
11849 dd-on str (start 0) m re)
11850 (goto-char pos)
11851 (when dodollar
11852 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
11853 re (nth 1 (assoc "$" org-latex-regexps)))
11854 (while (string-match re str start)
11855 (cond
11856 ((= (match-end 0) (length str))
11857 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
11858 ((= (match-end 0) (- (length str) 5))
11859 (throw 'exit nil))
11860 (t (setq start (match-end 0))))))
11861 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
11862 (goto-char pos)
11863 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
11864 (and (match-beginning 2) (throw 'exit nil))
11865 ;; count $$
11866 (while (re-search-backward "\\$\\$" lim t)
11867 (setq dd-on (not dd-on)))
11868 (goto-char pos)
11869 (if dd-on (cons "$$" m))))))
11872 (defun org-try-cdlatex-tab ()
11873 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
11874 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
11875 - inside a LaTeX fragment, or
11876 - after the first word in a line, where an abbreviation expansion could
11877 insert a LaTeX environment."
11878 (when org-cdlatex-mode
11879 (cond
11880 ((save-excursion
11881 (skip-chars-backward "a-zA-Z0-9*")
11882 (skip-chars-backward " \t")
11883 (bolp))
11884 (cdlatex-tab) t)
11885 ((org-inside-LaTeX-fragment-p)
11886 (cdlatex-tab) t)
11887 (t nil))))
11889 (defun org-cdlatex-underscore-caret (&optional arg)
11890 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
11891 Revert to the normal definition outside of these fragments."
11892 (interactive "P")
11893 (if (org-inside-LaTeX-fragment-p)
11894 (call-interactively 'cdlatex-sub-superscript)
11895 (let (org-cdlatex-mode)
11896 (call-interactively (key-binding (vector last-input-event))))))
11898 (defun org-cdlatex-math-modify (&optional arg)
11899 "Execute `cdlatex-math-modify' in LaTeX fragments.
11900 Revert to the normal definition outside of these fragments."
11901 (interactive "P")
11902 (if (org-inside-LaTeX-fragment-p)
11903 (call-interactively 'cdlatex-math-modify)
11904 (let (org-cdlatex-mode)
11905 (call-interactively (key-binding (vector last-input-event))))))
11907 (defvar org-latex-fragment-image-overlays nil
11908 "List of overlays carrying the images of latex fragments.")
11909 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
11911 (defun org-remove-latex-fragment-image-overlays ()
11912 "Remove all overlays with LaTeX fragment images in current buffer."
11913 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
11914 (setq org-latex-fragment-image-overlays nil))
11916 (defun org-preview-latex-fragment (&optional subtree)
11917 "Preview the LaTeX fragment at point, or all locally or globally.
11918 If the cursor is in a LaTeX fragment, create the image and overlay
11919 it over the source code. If there is no fragment at point, display
11920 all fragments in the current text, from one headline to the next. With
11921 prefix SUBTREE, display all fragments in the current subtree. With a
11922 double prefix `C-u C-u', or when the cursor is before the first headline,
11923 display all fragments in the buffer.
11924 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
11925 (interactive "P")
11926 (org-remove-latex-fragment-image-overlays)
11927 (save-excursion
11928 (save-restriction
11929 (let (beg end at msg)
11930 (cond
11931 ((or (equal subtree '(16))
11932 (not (save-excursion
11933 (re-search-backward (concat "^" outline-regexp) nil t))))
11934 (setq beg (point-min) end (point-max)
11935 msg "Creating images for buffer...%s"))
11936 ((equal subtree '(4))
11937 (org-back-to-heading)
11938 (setq beg (point) end (org-end-of-subtree t)
11939 msg "Creating images for subtree...%s"))
11941 (if (setq at (org-inside-LaTeX-fragment-p))
11942 (goto-char (max (point-min) (- (cdr at) 2)))
11943 (org-back-to-heading))
11944 (setq beg (point) end (progn (outline-next-heading) (point))
11945 msg (if at "Creating image...%s"
11946 "Creating images for entry...%s"))))
11947 (message msg "")
11948 (narrow-to-region beg end)
11949 (goto-char beg)
11950 (org-format-latex
11951 (concat "ltxpng/" (file-name-sans-extension
11952 (file-name-nondirectory
11953 buffer-file-name)))
11954 default-directory 'overlays msg at 'forbuffer)
11955 (message msg "done. Use `C-c C-c' to remove images.")))))
11957 (defvar org-latex-regexps
11958 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
11959 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
11960 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
11961 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
11962 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
11963 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
11964 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
11965 "Regular expressions for matching embedded LaTeX.")
11967 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
11968 "Replace LaTeX fragments with links to an image, and produce images."
11969 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
11970 (let* ((prefixnodir (file-name-nondirectory prefix))
11971 (absprefix (expand-file-name prefix dir))
11972 (todir (file-name-directory absprefix))
11973 (opt org-format-latex-options)
11974 (matchers (plist-get opt :matchers))
11975 (re-list org-latex-regexps)
11976 (cnt 0) txt link beg end re e checkdir
11977 m n block linkfile movefile ov)
11978 ;; Check if there are old images files with this prefix, and remove them
11979 (when (file-directory-p todir)
11980 (mapc 'delete-file
11981 (directory-files
11982 todir 'full
11983 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
11984 ;; Check the different regular expressions
11985 (while (setq e (pop re-list))
11986 (setq m (car e) re (nth 1 e) n (nth 2 e)
11987 block (if (nth 3 e) "\n\n" ""))
11988 (when (member m matchers)
11989 (goto-char (point-min))
11990 (while (re-search-forward re nil t)
11991 (when (or (not at) (equal (cdr at) (match-beginning n)))
11992 (setq txt (match-string n)
11993 beg (match-beginning n) end (match-end n)
11994 cnt (1+ cnt)
11995 linkfile (format "%s_%04d.png" prefix cnt)
11996 movefile (format "%s_%04d.png" absprefix cnt)
11997 link (concat block "[[file:" linkfile "]]" block))
11998 (if msg (message msg cnt))
11999 (goto-char beg)
12000 (unless checkdir ; make sure the directory exists
12001 (setq checkdir t)
12002 (or (file-directory-p todir) (make-directory todir)))
12003 (org-create-formula-image
12004 txt movefile opt forbuffer)
12005 (if overlays
12006 (progn
12007 (setq ov (org-make-overlay beg end))
12008 (if (featurep 'xemacs)
12009 (progn
12010 (org-overlay-put ov 'invisible t)
12011 (org-overlay-put
12012 ov 'end-glyph
12013 (make-glyph (vector 'png :file movefile))))
12014 (org-overlay-put
12015 ov 'display
12016 (list 'image :type 'png :file movefile :ascent 'center)))
12017 (push ov org-latex-fragment-image-overlays)
12018 (goto-char end))
12019 (delete-region beg end)
12020 (insert link))))))))
12022 ;; This function borrows from Ganesh Swami's latex2png.el
12023 (defun org-create-formula-image (string tofile options buffer)
12024 (let* ((tmpdir (if (featurep 'xemacs)
12025 (temp-directory)
12026 temporary-file-directory))
12027 (texfilebase (make-temp-name
12028 (expand-file-name "orgtex" tmpdir)))
12029 (texfile (concat texfilebase ".tex"))
12030 (dvifile (concat texfilebase ".dvi"))
12031 (pngfile (concat texfilebase ".png"))
12032 (fnh (if (featurep 'xemacs)
12033 (font-height (get-face-font 'default))
12034 (face-attribute 'default :height nil)))
12035 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
12036 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
12037 (fg (or (plist-get options (if buffer :foreground :html-foreground))
12038 "Black"))
12039 (bg (or (plist-get options (if buffer :background :html-background))
12040 "Transparent")))
12041 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
12042 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
12043 (with-temp-file texfile
12044 (insert org-format-latex-header
12045 "\n\\begin{document}\n" string "\n\\end{document}\n"))
12046 (let ((dir default-directory))
12047 (condition-case nil
12048 (progn
12049 (cd tmpdir)
12050 (call-process "latex" nil nil nil texfile))
12051 (error nil))
12052 (cd dir))
12053 (if (not (file-exists-p dvifile))
12054 (progn (message "Failed to create dvi file from %s" texfile) nil)
12055 (condition-case nil
12056 (call-process "dvipng" nil nil nil
12057 "-E" "-fg" fg "-bg" bg
12058 "-D" dpi
12059 ;;"-x" scale "-y" scale
12060 "-T" "tight"
12061 "-o" pngfile
12062 dvifile)
12063 (error nil))
12064 (if (not (file-exists-p pngfile))
12065 (progn (message "Failed to create png file from %s" texfile) nil)
12066 ;; Use the requested file name and clean up
12067 (copy-file pngfile tofile 'replace)
12068 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
12069 (delete-file (concat texfilebase e)))
12070 pngfile))))
12072 (defun org-dvipng-color (attr)
12073 "Return an rgb color specification for dvipng."
12074 (apply 'format "rgb %s %s %s"
12075 (mapcar 'org-normalize-color
12076 (color-values (face-attribute 'default attr nil)))))
12078 (defun org-normalize-color (value)
12079 "Return string to be used as color value for an RGB component."
12080 (format "%g" (/ value 65535.0)))
12083 ;;;; Key bindings
12085 ;; Make `C-c C-x' a prefix key
12086 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
12088 ;; TAB key with modifiers
12089 (org-defkey org-mode-map "\C-i" 'org-cycle)
12090 (org-defkey org-mode-map [(tab)] 'org-cycle)
12091 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
12092 (org-defkey org-mode-map [(meta tab)] 'org-complete)
12093 (org-defkey org-mode-map "\M-\t" 'org-complete)
12094 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
12095 ;; The following line is necessary under Suse GNU/Linux
12096 (unless (featurep 'xemacs)
12097 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
12098 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
12099 (define-key org-mode-map [backtab] 'org-shifttab)
12101 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
12102 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
12103 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
12105 ;; Cursor keys with modifiers
12106 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
12107 (org-defkey org-mode-map [(meta right)] 'org-metaright)
12108 (org-defkey org-mode-map [(meta up)] 'org-metaup)
12109 (org-defkey org-mode-map [(meta down)] 'org-metadown)
12111 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
12112 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
12113 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
12114 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
12116 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
12117 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
12118 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
12119 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
12121 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
12122 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
12124 ;;; Extra keys for tty access.
12125 ;; We only set them when really needed because otherwise the
12126 ;; menus don't show the simple keys
12128 (when (or org-use-extra-keys
12129 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
12130 (not window-system))
12131 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
12132 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
12133 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
12134 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
12135 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
12136 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
12137 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
12138 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
12139 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
12140 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
12141 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
12142 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
12143 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
12144 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
12145 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
12146 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
12147 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
12148 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
12149 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
12150 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
12151 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
12152 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
12154 ;; All the other keys
12156 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
12157 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
12158 (if (boundp 'narrow-map)
12159 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
12160 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
12161 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
12162 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
12163 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
12164 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
12165 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
12166 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
12167 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
12168 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
12169 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
12170 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
12171 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
12172 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
12173 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
12174 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
12175 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
12176 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
12177 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
12178 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
12179 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
12180 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
12181 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
12182 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
12183 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
12184 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
12185 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
12186 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
12187 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
12188 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
12189 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
12190 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
12191 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
12192 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
12193 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
12194 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
12195 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
12196 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
12197 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
12198 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
12199 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
12200 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
12201 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
12202 (org-defkey org-mode-map "\C-c^" 'org-sort)
12203 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
12204 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
12205 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
12206 (org-defkey org-mode-map "\C-m" 'org-return)
12207 (org-defkey org-mode-map "\C-j" 'org-return-indent)
12208 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
12209 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
12210 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
12211 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
12212 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
12213 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
12214 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
12215 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
12216 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
12217 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
12218 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
12219 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
12220 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
12221 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
12222 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
12224 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
12225 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
12226 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
12227 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
12229 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
12230 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
12231 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
12232 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
12233 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
12234 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
12235 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
12236 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
12237 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
12238 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
12239 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
12240 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
12242 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
12244 (when (featurep 'xemacs)
12245 (org-defkey org-mode-map 'button3 'popup-mode-menu))
12247 (defvar org-table-auto-blank-field) ; defined in org-table.el
12248 (defun org-self-insert-command (N)
12249 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
12250 If the cursor is in a table looking at whitespace, the whitespace is
12251 overwritten, and the table is not marked as requiring realignment."
12252 (interactive "p")
12253 (if (and (org-table-p)
12254 (progn
12255 ;; check if we blank the field, and if that triggers align
12256 (and (featurep 'org-table) org-table-auto-blank-field
12257 (member last-command
12258 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
12259 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
12260 ;; got extra space, this field does not determine column width
12261 (let (org-table-may-need-update) (org-table-blank-field))
12262 ;; no extra space, this field may determine column width
12263 (org-table-blank-field)))
12265 (eq N 1)
12266 (looking-at "[^|\n]* |"))
12267 (let (org-table-may-need-update)
12268 (goto-char (1- (match-end 0)))
12269 (delete-backward-char 1)
12270 (goto-char (match-beginning 0))
12271 (self-insert-command N))
12272 (setq org-table-may-need-update t)
12273 (self-insert-command N)
12274 (org-fix-tags-on-the-fly)))
12276 (defun org-fix-tags-on-the-fly ()
12277 (when (and (equal (char-after (point-at-bol)) ?*)
12278 (org-on-heading-p))
12279 (org-align-tags-here org-tags-column)))
12281 (defun org-delete-backward-char (N)
12282 "Like `delete-backward-char', insert whitespace at field end in tables.
12283 When deleting backwards, in tables this function will insert whitespace in
12284 front of the next \"|\" separator, to keep the table aligned. The table will
12285 still be marked for re-alignment if the field did fill the entire column,
12286 because, in this case the deletion might narrow the column."
12287 (interactive "p")
12288 (if (and (org-table-p)
12289 (eq N 1)
12290 (string-match "|" (buffer-substring (point-at-bol) (point)))
12291 (looking-at ".*?|"))
12292 (let ((pos (point))
12293 (noalign (looking-at "[^|\n\r]* |"))
12294 (c org-table-may-need-update))
12295 (backward-delete-char N)
12296 (skip-chars-forward "^|")
12297 (insert " ")
12298 (goto-char (1- pos))
12299 ;; noalign: if there were two spaces at the end, this field
12300 ;; does not determine the width of the column.
12301 (if noalign (setq org-table-may-need-update c)))
12302 (backward-delete-char N)
12303 (org-fix-tags-on-the-fly)))
12305 (defun org-delete-char (N)
12306 "Like `delete-char', but insert whitespace at field end in tables.
12307 When deleting characters, in tables this function will insert whitespace in
12308 front of the next \"|\" separator, to keep the table aligned. The table will
12309 still be marked for re-alignment if the field did fill the entire column,
12310 because, in this case the deletion might narrow the column."
12311 (interactive "p")
12312 (if (and (org-table-p)
12313 (not (bolp))
12314 (not (= (char-after) ?|))
12315 (eq N 1))
12316 (if (looking-at ".*?|")
12317 (let ((pos (point))
12318 (noalign (looking-at "[^|\n\r]* |"))
12319 (c org-table-may-need-update))
12320 (replace-match (concat
12321 (substring (match-string 0) 1 -1)
12322 " |"))
12323 (goto-char pos)
12324 ;; noalign: if there were two spaces at the end, this field
12325 ;; does not determine the width of the column.
12326 (if noalign (setq org-table-may-need-update c)))
12327 (delete-char N))
12328 (delete-char N)
12329 (org-fix-tags-on-the-fly)))
12331 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
12332 (put 'org-self-insert-command 'delete-selection t)
12333 (put 'orgtbl-self-insert-command 'delete-selection t)
12334 (put 'org-delete-char 'delete-selection 'supersede)
12335 (put 'org-delete-backward-char 'delete-selection 'supersede)
12337 ;; Make `flyspell-mode' delay after some commands
12338 (put 'org-self-insert-command 'flyspell-delayed t)
12339 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
12340 (put 'org-delete-char 'flyspell-delayed t)
12341 (put 'org-delete-backward-char 'flyspell-delayed t)
12343 ;; Make pabbrev-mode expand after org-mode commands
12344 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
12345 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
12347 ;; How to do this: Measure non-white length of current string
12348 ;; If equal to column width, we should realign.
12350 (defun org-remap (map &rest commands)
12351 "In MAP, remap the functions given in COMMANDS.
12352 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
12353 (let (new old)
12354 (while commands
12355 (setq old (pop commands) new (pop commands))
12356 (if (fboundp 'command-remapping)
12357 (org-defkey map (vector 'remap old) new)
12358 (substitute-key-definition old new map global-map)))))
12360 (when (eq org-enable-table-editor 'optimized)
12361 ;; If the user wants maximum table support, we need to hijack
12362 ;; some standard editing functions
12363 (org-remap org-mode-map
12364 'self-insert-command 'org-self-insert-command
12365 'delete-char 'org-delete-char
12366 'delete-backward-char 'org-delete-backward-char)
12367 (org-defkey org-mode-map "|" 'org-force-self-insert))
12369 (defun org-shiftcursor-error ()
12370 "Throw an error because Shift-Cursor command was applied in wrong context."
12371 (error "This command is active in special context like tables, headlines or timestamps"))
12373 (defun org-shifttab (&optional arg)
12374 "Global visibility cycling or move to previous table field.
12375 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
12376 on context.
12377 See the individual commands for more information."
12378 (interactive "P")
12379 (cond
12380 ((org-at-table-p) (call-interactively 'org-table-previous-field))
12381 ((integerp arg)
12382 (message "Content view to level: %d" arg)
12383 (org-content (prefix-numeric-value arg))
12384 (setq org-cycle-global-status 'overview))
12385 (t (call-interactively 'org-global-cycle))))
12387 (defun org-shiftmetaleft ()
12388 "Promote subtree or delete table column.
12389 Calls `org-promote-subtree', `org-outdent-item',
12390 or `org-table-delete-column', depending on context.
12391 See the individual commands for more information."
12392 (interactive)
12393 (cond
12394 ((org-at-table-p) (call-interactively 'org-table-delete-column))
12395 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
12396 ((org-at-item-p) (call-interactively 'org-outdent-item))
12397 (t (org-shiftcursor-error))))
12399 (defun org-shiftmetaright ()
12400 "Demote subtree or insert table column.
12401 Calls `org-demote-subtree', `org-indent-item',
12402 or `org-table-insert-column', depending on context.
12403 See the individual commands for more information."
12404 (interactive)
12405 (cond
12406 ((org-at-table-p) (call-interactively 'org-table-insert-column))
12407 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
12408 ((org-at-item-p) (call-interactively 'org-indent-item))
12409 (t (org-shiftcursor-error))))
12411 (defun org-shiftmetaup (&optional arg)
12412 "Move subtree up or kill table row.
12413 Calls `org-move-subtree-up' or `org-table-kill-row' or
12414 `org-move-item-up' depending on context. See the individual commands
12415 for more information."
12416 (interactive "P")
12417 (cond
12418 ((org-at-table-p) (call-interactively 'org-table-kill-row))
12419 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12420 ((org-at-item-p) (call-interactively 'org-move-item-up))
12421 (t (org-shiftcursor-error))))
12422 (defun org-shiftmetadown (&optional arg)
12423 "Move subtree down or insert table row.
12424 Calls `org-move-subtree-down' or `org-table-insert-row' or
12425 `org-move-item-down', depending on context. See the individual
12426 commands for more information."
12427 (interactive "P")
12428 (cond
12429 ((org-at-table-p) (call-interactively 'org-table-insert-row))
12430 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12431 ((org-at-item-p) (call-interactively 'org-move-item-down))
12432 (t (org-shiftcursor-error))))
12434 (defun org-metaleft (&optional arg)
12435 "Promote heading or move table column to left.
12436 Calls `org-do-promote' or `org-table-move-column', depending on context.
12437 With no specific context, calls the Emacs default `backward-word'.
12438 See the individual commands for more information."
12439 (interactive "P")
12440 (cond
12441 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
12442 ((or (org-on-heading-p) (org-region-active-p))
12443 (call-interactively 'org-do-promote))
12444 ((org-at-item-p) (call-interactively 'org-outdent-item))
12445 (t (call-interactively 'backward-word))))
12447 (defun org-metaright (&optional arg)
12448 "Demote subtree or move table column to right.
12449 Calls `org-do-demote' or `org-table-move-column', depending on context.
12450 With no specific context, calls the Emacs default `forward-word'.
12451 See the individual commands for more information."
12452 (interactive "P")
12453 (cond
12454 ((org-at-table-p) (call-interactively 'org-table-move-column))
12455 ((or (org-on-heading-p) (org-region-active-p))
12456 (call-interactively 'org-do-demote))
12457 ((org-at-item-p) (call-interactively 'org-indent-item))
12458 (t (call-interactively 'forward-word))))
12460 (defun org-metaup (&optional arg)
12461 "Move subtree up or move table row up.
12462 Calls `org-move-subtree-up' or `org-table-move-row' or
12463 `org-move-item-up', depending on context. See the individual commands
12464 for more information."
12465 (interactive "P")
12466 (cond
12467 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
12468 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12469 ((org-at-item-p) (call-interactively 'org-move-item-up))
12470 (t (transpose-lines 1) (beginning-of-line -1))))
12472 (defun org-metadown (&optional arg)
12473 "Move subtree down or move table row down.
12474 Calls `org-move-subtree-down' or `org-table-move-row' or
12475 `org-move-item-down', depending on context. See the individual
12476 commands for more information."
12477 (interactive "P")
12478 (cond
12479 ((org-at-table-p) (call-interactively 'org-table-move-row))
12480 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12481 ((org-at-item-p) (call-interactively 'org-move-item-down))
12482 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
12484 (defun org-shiftup (&optional arg)
12485 "Increase item in timestamp or increase priority of current headline.
12486 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
12487 depending on context. See the individual commands for more information."
12488 (interactive "P")
12489 (cond
12490 ((org-at-timestamp-p t)
12491 (call-interactively (if org-edit-timestamp-down-means-later
12492 'org-timestamp-down 'org-timestamp-up)))
12493 ((org-on-heading-p) (call-interactively 'org-priority-up))
12494 ((org-at-item-p) (call-interactively 'org-previous-item))
12495 ((org-clocktable-try-shift 'up arg))
12496 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
12498 (defun org-shiftdown (&optional arg)
12499 "Decrease item in timestamp or decrease priority of current headline.
12500 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
12501 depending on context. See the individual commands for more information."
12502 (interactive "P")
12503 (cond
12504 ((org-at-timestamp-p t)
12505 (call-interactively (if org-edit-timestamp-down-means-later
12506 'org-timestamp-up 'org-timestamp-down)))
12507 ((org-on-heading-p) (call-interactively 'org-priority-down))
12508 ((org-clocktable-try-shift 'down arg))
12509 (t (call-interactively 'org-next-item))))
12511 (defun org-shiftright (&optional arg)
12512 "Next TODO keyword or timestamp one day later, depending on context."
12513 (interactive "P")
12514 (cond
12515 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
12516 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
12517 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
12518 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
12519 ((org-clocktable-try-shift 'right arg))
12520 (t (org-shiftcursor-error))))
12522 (defun org-shiftleft (&optional arg)
12523 "Previous TODO keyword or timestamp one day earlier, depending on context."
12524 (interactive "P")
12525 (cond
12526 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
12527 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
12528 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
12529 ((org-at-property-p)
12530 (call-interactively 'org-property-previous-allowed-value))
12531 ((org-clocktable-try-shift 'left arg))
12532 (t (org-shiftcursor-error))))
12534 (defun org-shiftcontrolright ()
12535 "Switch to next TODO set."
12536 (interactive)
12537 (cond
12538 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
12539 (t (org-shiftcursor-error))))
12541 (defun org-shiftcontrolleft ()
12542 "Switch to previous TODO set."
12543 (interactive)
12544 (cond
12545 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
12546 (t (org-shiftcursor-error))))
12548 (defun org-ctrl-c-ret ()
12549 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
12550 (interactive)
12551 (cond
12552 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
12553 (t (call-interactively 'org-insert-heading))))
12555 (defun org-copy-special ()
12556 "Copy region in table or copy current subtree.
12557 Calls `org-table-copy' or `org-copy-subtree', depending on context.
12558 See the individual commands for more information."
12559 (interactive)
12560 (call-interactively
12561 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
12563 (defun org-cut-special ()
12564 "Cut region in table or cut current subtree.
12565 Calls `org-table-copy' or `org-cut-subtree', depending on context.
12566 See the individual commands for more information."
12567 (interactive)
12568 (call-interactively
12569 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
12571 (defun org-paste-special (arg)
12572 "Paste rectangular region into table, or past subtree relative to level.
12573 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
12574 See the individual commands for more information."
12575 (interactive "P")
12576 (if (org-at-table-p)
12577 (org-table-paste-rectangle)
12578 (org-paste-subtree arg)))
12580 (defun org-edit-special ()
12581 "Call a special editor for the stuff at point.
12582 When at a table, call the formula editor with `org-table-edit-formulas'.
12583 When at the first line of an src example, call `org-edit-src-code'.
12584 When in an #+include line, visit the include file. Otherwise call
12585 `ffap' to visit the file at point."
12586 (interactive)
12587 (cond
12588 ((org-at-table-p)
12589 (call-interactively 'org-table-edit-formulas))
12590 ((save-excursion
12591 (beginning-of-line 1)
12592 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
12593 (find-file (org-trim (match-string 1))))
12594 ((org-edit-src-code))
12595 ((org-edit-fixed-width-region))
12596 (t (call-interactively 'ffap))))
12598 (defun org-ctrl-c-ctrl-c (&optional arg)
12599 "Set tags in headline, or update according to changed information at point.
12601 This command does many different things, depending on context:
12603 - If the cursor is in a headline, prompt for tags and insert them
12604 into the current line, aligned to `org-tags-column'. When called
12605 with prefix arg, realign all tags in the current buffer.
12607 - If the cursor is in one of the special #+KEYWORD lines, this
12608 triggers scanning the buffer for these lines and updating the
12609 information.
12611 - If the cursor is inside a table, realign the table. This command
12612 works even if the automatic table editor has been turned off.
12614 - If the cursor is on a #+TBLFM line, re-apply the formulas to
12615 the entire table.
12617 - If the cursor is a the beginning of a dynamic block, update it.
12619 - If the cursor is inside a table created by the table.el package,
12620 activate that table.
12622 - If the current buffer is a remember buffer, close note and file
12623 it. A prefix argument of 1 files to the default location
12624 without further interaction. A prefix argument of 2 files to
12625 the currently clocking task.
12627 - If the cursor is on a <<<target>>>, update radio targets and corresponding
12628 links in this buffer.
12630 - If the cursor is on a numbered item in a plain list, renumber the
12631 ordered list.
12633 - If the cursor is on a checkbox, toggle it."
12634 (interactive "P")
12635 (let ((org-enable-table-editor t))
12636 (cond
12637 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
12638 org-occur-highlights
12639 org-latex-fragment-image-overlays)
12640 (and (boundp 'org-clock-overlays) (org-remove-clock-overlays))
12641 (org-remove-occur-highlights)
12642 (org-remove-latex-fragment-image-overlays)
12643 (message "Temporary highlights/overlays removed from current buffer"))
12644 ((and (local-variable-p 'org-finish-function (current-buffer))
12645 (fboundp org-finish-function))
12646 (funcall org-finish-function))
12647 ((org-at-property-p)
12648 (call-interactively 'org-property-action))
12649 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
12650 ((org-on-heading-p) (call-interactively 'org-set-tags))
12651 ((org-at-table.el-p)
12652 (require 'table)
12653 (beginning-of-line 1)
12654 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
12655 (call-interactively 'table-recognize-table))
12656 ((org-at-table-p)
12657 (org-table-maybe-eval-formula)
12658 (if arg
12659 (call-interactively 'org-table-recalculate)
12660 (org-table-maybe-recalculate-line))
12661 (call-interactively 'org-table-align))
12662 ((org-at-item-checkbox-p)
12663 (call-interactively 'org-toggle-checkbox))
12664 ((org-at-item-p)
12665 (call-interactively 'org-maybe-renumber-ordered-list))
12666 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
12667 ;; Dynamic block
12668 (beginning-of-line 1)
12669 (save-excursion (org-update-dblock)))
12670 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
12671 (cond
12672 ((equal (match-string 1) "TBLFM")
12673 ;; Recalculate the table before this line
12674 (save-excursion
12675 (beginning-of-line 1)
12676 (skip-chars-backward " \r\n\t")
12677 (if (org-at-table-p)
12678 (org-call-with-arg 'org-table-recalculate t))))
12680 ; (org-set-regexps-and-options)
12681 ; (org-restart-font-lock)
12682 (let ((org-inhibit-startup t)) (org-mode-restart))
12683 (message "Local setup has been refreshed"))))
12684 (t (error "C-c C-c can do nothing useful at this location.")))))
12686 (defun org-mode-restart ()
12687 "Restart Org-mode, to scan again for special lines.
12688 Also updates the keyword regular expressions."
12689 (interactive)
12690 (org-mode)
12691 (message "Org-mode restarted"))
12693 (defun org-kill-note-or-show-branches ()
12694 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
12695 (interactive)
12696 (if (not org-finish-function)
12697 (call-interactively 'show-branches)
12698 (let ((org-note-abort t))
12699 (funcall org-finish-function))))
12701 (defun org-return (&optional indent)
12702 "Goto next table row or insert a newline.
12703 Calls `org-table-next-row' or `newline', depending on context.
12704 See the individual commands for more information."
12705 (interactive)
12706 (cond
12707 ((bobp) (if indent (newline-and-indent) (newline)))
12708 ((and (org-at-heading-p)
12709 (looking-at
12710 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
12711 (org-show-entry)
12712 (end-of-line 1)
12713 (newline))
12714 ((org-at-table-p)
12715 (org-table-justify-field-maybe)
12716 (call-interactively 'org-table-next-row))
12717 (t (if indent (newline-and-indent) (newline)))))
12719 (defun org-return-indent ()
12720 "Goto next table row or insert a newline and indent.
12721 Calls `org-table-next-row' or `newline-and-indent', depending on
12722 context. See the individual commands for more information."
12723 (interactive)
12724 (org-return t))
12726 (defun org-ctrl-c-star ()
12727 "Compute table, or change heading status of lines.
12728 Calls `org-table-recalculate' or `org-toggle-region-headings',
12729 depending on context. This will also turn a plain list item or a normal
12730 line into a subheading."
12731 (interactive)
12732 (cond
12733 ((org-at-table-p)
12734 (call-interactively 'org-table-recalculate))
12735 ((org-region-active-p)
12736 ;; Convert all lines in region to list items
12737 (call-interactively 'org-toggle-region-headings))
12738 ((org-on-heading-p)
12739 (org-toggle-region-headings (point-at-bol)
12740 (min (1+ (point-at-eol)) (point-max))))
12741 ((org-at-item-p)
12742 ;; Convert to heading
12743 (let ((level (save-match-data
12744 (save-excursion
12745 (condition-case nil
12746 (progn
12747 (org-back-to-heading t)
12748 (funcall outline-level))
12749 (error 0))))))
12750 (replace-match
12751 (concat (make-string (org-get-valid-level level 1) ?*) " ") t t)))
12752 (t (org-toggle-region-headings (point-at-bol)
12753 (min (1+ (point-at-eol)) (point-max))))))
12755 (defun org-ctrl-c-minus ()
12756 "Insert separator line in table or modify bullet status of line.
12757 Also turns a plain line or a region of lines into list items.
12758 Calls `org-table-insert-hline', `org-toggle-region-items', or
12759 `org-cycle-list-bullet', depending on context."
12760 (interactive)
12761 (cond
12762 ((org-at-table-p)
12763 (call-interactively 'org-table-insert-hline))
12764 ((org-on-heading-p)
12765 ;; Convert to item
12766 (save-excursion
12767 (beginning-of-line 1)
12768 (if (looking-at "\\*+ ")
12769 (replace-match (concat (make-string (- (match-end 0) (point) 1) ?\ ) "- ")))))
12770 ((org-region-active-p)
12771 ;; Convert all lines in region to list items
12772 (call-interactively 'org-toggle-region-items))
12773 ((org-in-item-p)
12774 (call-interactively 'org-cycle-list-bullet))
12775 (t (org-toggle-region-items (point-at-bol)
12776 (min (1+ (point-at-eol)) (point-max))))))
12778 (defun org-toggle-region-items (beg end)
12779 "Convert all lines in region to list items.
12780 If the first line is already an item, convert all list items in the region
12781 to normal lines."
12782 (interactive "r")
12783 (let (l2 l)
12784 (save-excursion
12785 (goto-char end)
12786 (setq l2 (org-current-line))
12787 (goto-char beg)
12788 (beginning-of-line 1)
12789 (setq l (1- (org-current-line)))
12790 (if (org-at-item-p)
12791 ;; We already have items, de-itemize
12792 (while (< (setq l (1+ l)) l2)
12793 (when (org-at-item-p)
12794 (goto-char (match-beginning 2))
12795 (delete-region (match-beginning 2) (match-end 2))
12796 (and (looking-at "[ \t]+") (replace-match "")))
12797 (beginning-of-line 2))
12798 (while (< (setq l (1+ l)) l2)
12799 (unless (org-at-item-p)
12800 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
12801 (replace-match "\\1- \\2")))
12802 (beginning-of-line 2))))))
12804 (defun org-toggle-region-headings (beg end)
12805 "Convert all lines in region to list items.
12806 If the first line is already an item, convert all list items in the region
12807 to normal lines."
12808 (interactive "r")
12809 (let (l2 l)
12810 (save-excursion
12811 (goto-char end)
12812 (setq l2 (org-current-line))
12813 (goto-char beg)
12814 (beginning-of-line 1)
12815 (setq l (1- (org-current-line)))
12816 (if (org-on-heading-p)
12817 ;; We already have headlines, de-star them
12818 (while (< (setq l (1+ l)) l2)
12819 (when (org-on-heading-p t)
12820 (and (looking-at outline-regexp) (replace-match "")))
12821 (beginning-of-line 2))
12822 (let* ((stars (save-excursion
12823 (re-search-backward org-complex-heading-regexp nil t)
12824 (or (match-string 1) "*")))
12825 (add-stars (if org-odd-levels-only "**" "*"))
12826 (rpl (concat stars add-stars " \\2")))
12827 (while (< (setq l (1+ l)) l2)
12828 (unless (org-on-heading-p)
12829 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
12830 (replace-match rpl)))
12831 (beginning-of-line 2)))))))
12833 (defun org-meta-return (&optional arg)
12834 "Insert a new heading or wrap a region in a table.
12835 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
12836 See the individual commands for more information."
12837 (interactive "P")
12838 (cond
12839 ((org-at-table-p)
12840 (call-interactively 'org-table-wrap-region))
12841 (t (call-interactively 'org-insert-heading))))
12843 ;;; Menu entries
12845 ;; Define the Org-mode menus
12846 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
12847 '("Tbl"
12848 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
12849 ["Next Field" org-cycle (org-at-table-p)]
12850 ["Previous Field" org-shifttab (org-at-table-p)]
12851 ["Next Row" org-return (org-at-table-p)]
12852 "--"
12853 ["Blank Field" org-table-blank-field (org-at-table-p)]
12854 ["Edit Field" org-table-edit-field (org-at-table-p)]
12855 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
12856 "--"
12857 ("Column"
12858 ["Move Column Left" org-metaleft (org-at-table-p)]
12859 ["Move Column Right" org-metaright (org-at-table-p)]
12860 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
12861 ["Insert Column" org-shiftmetaright (org-at-table-p)])
12862 ("Row"
12863 ["Move Row Up" org-metaup (org-at-table-p)]
12864 ["Move Row Down" org-metadown (org-at-table-p)]
12865 ["Delete Row" org-shiftmetaup (org-at-table-p)]
12866 ["Insert Row" org-shiftmetadown (org-at-table-p)]
12867 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
12868 "--"
12869 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
12870 ("Rectangle"
12871 ["Copy Rectangle" org-copy-special (org-at-table-p)]
12872 ["Cut Rectangle" org-cut-special (org-at-table-p)]
12873 ["Paste Rectangle" org-paste-special (org-at-table-p)]
12874 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
12875 "--"
12876 ("Calculate"
12877 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
12878 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
12879 ["Edit Formulas" org-edit-special (org-at-table-p)]
12880 "--"
12881 ["Recalculate line" org-table-recalculate (org-at-table-p)]
12882 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
12883 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
12884 "--"
12885 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
12886 "--"
12887 ["Sum Column/Rectangle" org-table-sum
12888 (or (org-at-table-p) (org-region-active-p))]
12889 ["Which Column?" org-table-current-column (org-at-table-p)])
12890 ["Debug Formulas"
12891 org-table-toggle-formula-debugger
12892 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
12893 ["Show Col/Row Numbers"
12894 org-table-toggle-coordinate-overlays
12895 :style toggle
12896 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
12897 "--"
12898 ["Create" org-table-create (and (not (org-at-table-p))
12899 org-enable-table-editor)]
12900 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
12901 ["Import from File" org-table-import (not (org-at-table-p))]
12902 ["Export to File" org-table-export (org-at-table-p)]
12903 "--"
12904 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
12906 (easy-menu-define org-org-menu org-mode-map "Org menu"
12907 '("Org"
12908 ("Show/Hide"
12909 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
12910 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
12911 ["Sparse Tree..." org-sparse-tree t]
12912 ["Reveal Context" org-reveal t]
12913 ["Show All" show-all t]
12914 "--"
12915 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
12916 "--"
12917 ["New Heading" org-insert-heading t]
12918 ("Navigate Headings"
12919 ["Up" outline-up-heading t]
12920 ["Next" outline-next-visible-heading t]
12921 ["Previous" outline-previous-visible-heading t]
12922 ["Next Same Level" outline-forward-same-level t]
12923 ["Previous Same Level" outline-backward-same-level t]
12924 "--"
12925 ["Jump" org-goto t])
12926 ("Edit Structure"
12927 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
12928 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
12929 "--"
12930 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
12931 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
12932 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
12933 "--"
12934 ["Promote Heading" org-metaleft (not (org-at-table-p))]
12935 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
12936 ["Demote Heading" org-metaright (not (org-at-table-p))]
12937 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
12938 "--"
12939 ["Sort Region/Children" org-sort (not (org-at-table-p))]
12940 "--"
12941 ["Convert to odd levels" org-convert-to-odd-levels t]
12942 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
12943 ("Editing"
12944 ["Emphasis..." org-emphasize t]
12945 ["Edit Source Example" org-edit-special t])
12946 ("Archive"
12947 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
12948 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
12949 ; :active t :keys "C-u C-c C-x C-a"]
12950 ["Sparse trees open ARCHIVE trees"
12951 (setq org-sparse-tree-open-archived-trees
12952 (not org-sparse-tree-open-archived-trees))
12953 :style toggle :selected org-sparse-tree-open-archived-trees]
12954 ["Cycling opens ARCHIVE trees"
12955 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
12956 :style toggle :selected org-cycle-open-archived-trees]
12957 "--"
12958 ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
12959 ["Move Subtree to Archive" org-advertized-archive-subtree t]
12960 ; ["Check and Move Children" (org-archive-subtree '(4))
12961 ; :active t :keys "C-u C-c C-x C-s"]
12963 "--"
12964 ("TODO Lists"
12965 ["TODO/DONE/-" org-todo t]
12966 ("Select keyword"
12967 ["Next keyword" org-shiftright (org-on-heading-p)]
12968 ["Previous keyword" org-shiftleft (org-on-heading-p)]
12969 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
12970 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
12971 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
12972 ["Show TODO Tree" org-show-todo-tree t]
12973 ["Global TODO list" org-todo-list t]
12974 "--"
12975 ["Set Priority" org-priority t]
12976 ["Priority Up" org-shiftup t]
12977 ["Priority Down" org-shiftdown t])
12978 ("TAGS and Properties"
12979 ["Set Tags" 'org-set-tags-command t]
12980 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
12981 "--"
12982 ["Set property" 'org-set-property t]
12983 ["Column view of properties" org-columns t]
12984 ["Insert Column View DBlock" org-insert-columns-dblock t])
12985 ("Dates and Scheduling"
12986 ["Timestamp" org-time-stamp t]
12987 ["Timestamp (inactive)" org-time-stamp-inactive t]
12988 ("Change Date"
12989 ["1 Day Later" org-shiftright t]
12990 ["1 Day Earlier" org-shiftleft t]
12991 ["1 ... Later" org-shiftup t]
12992 ["1 ... Earlier" org-shiftdown t])
12993 ["Compute Time Range" org-evaluate-time-range t]
12994 ["Schedule Item" org-schedule t]
12995 ["Deadline" org-deadline t]
12996 "--"
12997 ["Custom time format" org-toggle-time-stamp-overlays
12998 :style radio :selected org-display-custom-times]
12999 "--"
13000 ["Goto Calendar" org-goto-calendar t]
13001 ["Date from Calendar" org-date-from-calendar t])
13002 ("Logging work"
13003 ["Clock in" org-clock-in t]
13004 ["Clock out" org-clock-out t]
13005 ["Clock cancel" org-clock-cancel t]
13006 ["Goto running clock" org-clock-goto t]
13007 ["Display times" org-clock-display t]
13008 ["Create clock table" org-clock-report t]
13009 "--"
13010 ["Record DONE time"
13011 (progn (setq org-log-done (not org-log-done))
13012 (message "Switching to %s will %s record a timestamp"
13013 (car org-done-keywords)
13014 (if org-log-done "automatically" "not")))
13015 :style toggle :selected org-log-done])
13016 "--"
13017 ["Agenda Command..." org-agenda t]
13018 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
13019 ("File List for Agenda")
13020 ("Special views current file"
13021 ["TODO Tree" org-show-todo-tree t]
13022 ["Check Deadlines" org-check-deadlines t]
13023 ["Timeline" org-timeline t]
13024 ["Tags Tree" org-tags-sparse-tree t])
13025 "--"
13026 ("Hyperlinks"
13027 ["Store Link (Global)" org-store-link t]
13028 ["Insert Link" org-insert-link t]
13029 ["Follow Link" org-open-at-point t]
13030 "--"
13031 ["Next link" org-next-link t]
13032 ["Previous link" org-previous-link t]
13033 "--"
13034 ["Descriptive Links"
13035 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
13036 :style radio
13037 :selected (member '(org-link) buffer-invisibility-spec)]
13038 ["Literal Links"
13039 (progn
13040 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
13041 :style radio
13042 :selected (not (member '(org-link) buffer-invisibility-spec))])
13043 "--"
13044 ["Export/Publish..." org-export t]
13045 ("LaTeX"
13046 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
13047 :selected org-cdlatex-mode]
13048 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
13049 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
13050 ["Modify math symbol" org-cdlatex-math-modify
13051 (org-inside-LaTeX-fragment-p)]
13052 ["Export LaTeX fragments as images"
13053 (if (featurep 'org-exp)
13054 (setq org-export-with-LaTeX-fragments
13055 (not org-export-with-LaTeX-fragments))
13056 (require 'org-exp))
13057 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
13058 org-export-with-LaTeX-fragments)])
13059 "--"
13060 ("Documentation"
13061 ["Show Version" org-version t]
13062 ["Info Documentation" org-info t])
13063 ("Customize"
13064 ["Browse Org Group" org-customize t]
13065 "--"
13066 ["Expand This Menu" org-create-customize-menu
13067 (fboundp 'customize-menu-create)])
13068 "--"
13069 ["Refresh setup" org-mode-restart t]
13072 (defun org-info (&optional node)
13073 "Read documentation for Org-mode in the info system.
13074 With optional NODE, go directly to that node."
13075 (interactive)
13076 (info (format "(org)%s" (or node ""))))
13078 (defun org-install-agenda-files-menu ()
13079 (let ((bl (buffer-list)))
13080 (save-excursion
13081 (while bl
13082 (set-buffer (pop bl))
13083 (if (org-mode-p) (setq bl nil)))
13084 (when (org-mode-p)
13085 (easy-menu-change
13086 '("Org") "File List for Agenda"
13087 (append
13088 (list
13089 ["Edit File List" (org-edit-agenda-file-list) t]
13090 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
13091 ["Remove Current File from List" org-remove-file t]
13092 ["Cycle through agenda files" org-cycle-agenda-files t]
13093 ["Occur in all agenda files" org-occur-in-agenda-files t]
13094 "--")
13095 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
13097 ;;;; Documentation
13099 ;;;###autoload
13100 (defun org-require-autoloaded-modules ()
13101 (interactive)
13102 (mapc 'require
13103 '(org-agenda org-archive org-clock org-colview
13104 org-exp org-id org-export-latex org-publish
13105 org-remember org-table)))
13107 ;;;###autoload
13108 (defun org-customize ()
13109 "Call the customize function with org as argument."
13110 (interactive)
13111 (org-load-modules-maybe)
13112 (org-require-autoloaded-modules)
13113 (customize-browse 'org))
13115 (defun org-create-customize-menu ()
13116 "Create a full customization menu for Org-mode, insert it into the menu."
13117 (interactive)
13118 (org-load-modules-maybe)
13119 (org-require-autoloaded-modules)
13120 (if (fboundp 'customize-menu-create)
13121 (progn
13122 (easy-menu-change
13123 '("Org") "Customize"
13124 `(["Browse Org group" org-customize t]
13125 "--"
13126 ,(customize-menu-create 'org)
13127 ["Set" Custom-set t]
13128 ["Save" Custom-save t]
13129 ["Reset to Current" Custom-reset-current t]
13130 ["Reset to Saved" Custom-reset-saved t]
13131 ["Reset to Standard Settings" Custom-reset-standard t]))
13132 (message "\"Org\"-menu now contains full customization menu"))
13133 (error "Cannot expand menu (outdated version of cus-edit.el)")))
13135 ;;;; Miscellaneous stuff
13137 ;;; Generally useful functions
13139 (defun org-display-warning (message) ;; Copied from Emacs-Muse
13140 "Display the given MESSAGE as a warning."
13141 (if (fboundp 'display-warning)
13142 (display-warning 'org message
13143 (if (featurep 'xemacs)
13144 'warning
13145 :warning))
13146 (let ((buf (get-buffer-create "*Org warnings*")))
13147 (with-current-buffer buf
13148 (goto-char (point-max))
13149 (insert "Warning (Org): " message)
13150 (unless (bolp)
13151 (newline)))
13152 (display-buffer buf)
13153 (sit-for 0))))
13155 (defun org-goto-marker-or-bmk (marker &optional bookmark)
13156 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
13157 (if (and marker (marker-buffer marker)
13158 (buffer-live-p (marker-buffer marker)))
13159 (progn
13160 (switch-to-buffer (marker-buffer marker))
13161 (if (or (> marker (point-max)) (< marker (point-min)))
13162 (widen))
13163 (goto-char marker))
13164 (if bookmark
13165 (bookmark-jump bookmark)
13166 (error "Cannot find location"))))
13168 (defun org-quote-csv-field (s)
13169 "Quote field for inclusion in CSV material."
13170 (if (string-match "[\",]" s)
13171 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
13174 (defun org-plist-delete (plist property)
13175 "Delete PROPERTY from PLIST.
13176 This is in contrast to merely setting it to 0."
13177 (let (p)
13178 (while plist
13179 (if (not (eq property (car plist)))
13180 (setq p (plist-put p (car plist) (nth 1 plist))))
13181 (setq plist (cddr plist)))
13184 (defun org-force-self-insert (N)
13185 "Needed to enforce self-insert under remapping."
13186 (interactive "p")
13187 (self-insert-command N))
13189 (defun org-string-width (s)
13190 "Compute width of string, ignoring invisible characters.
13191 This ignores character with invisibility property `org-link', and also
13192 characters with property `org-cwidth', because these will become invisible
13193 upon the next fontification round."
13194 (let (b l)
13195 (when (or (eq t buffer-invisibility-spec)
13196 (assq 'org-link buffer-invisibility-spec))
13197 (while (setq b (text-property-any 0 (length s)
13198 'invisible 'org-link s))
13199 (setq s (concat (substring s 0 b)
13200 (substring s (or (next-single-property-change
13201 b 'invisible s) (length s)))))))
13202 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
13203 (setq s (concat (substring s 0 b)
13204 (substring s (or (next-single-property-change
13205 b 'org-cwidth s) (length s))))))
13206 (setq l (string-width s) b -1)
13207 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
13208 (setq l (- l (get-text-property b 'org-dwidth-n s))))
13211 (defun org-get-indentation (&optional line)
13212 "Get the indentation of the current line, interpreting tabs.
13213 When LINE is given, assume it represents a line and compute its indentation."
13214 (if line
13215 (if (string-match "^ *" (org-remove-tabs line))
13216 (match-end 0))
13217 (save-excursion
13218 (beginning-of-line 1)
13219 (skip-chars-forward " \t")
13220 (current-column))))
13222 (defun org-remove-tabs (s &optional width)
13223 "Replace tabulators in S with spaces.
13224 Assumes that s is a single line, starting in column 0."
13225 (setq width (or width tab-width))
13226 (while (string-match "\t" s)
13227 (setq s (replace-match
13228 (make-string
13229 (- (* width (/ (+ (match-beginning 0) width) width))
13230 (match-beginning 0)) ?\ )
13231 t t s)))
13234 (defun org-fix-indentation (line ind)
13235 "Fix indentation in LINE.
13236 IND is a cons cell with target and minimum indentation.
13237 If the current indenation in LINE is smaller than the minimum,
13238 leave it alone. If it is larger than ind, set it to the target."
13239 (let* ((l (org-remove-tabs line))
13240 (i (org-get-indentation l))
13241 (i1 (car ind)) (i2 (cdr ind)))
13242 (if (>= i i2) (setq l (substring line i2)))
13243 (if (> i1 0)
13244 (concat (make-string i1 ?\ ) l)
13245 l)))
13247 (defun org-base-buffer (buffer)
13248 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
13249 (if (not buffer)
13250 buffer
13251 (or (buffer-base-buffer buffer)
13252 buffer)))
13254 (defun org-trim (s)
13255 "Remove whitespace at beginning and end of string."
13256 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
13257 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
13260 (defun org-wrap (string &optional width lines)
13261 "Wrap string to either a number of lines, or a width in characters.
13262 If WIDTH is non-nil, the string is wrapped to that width, however many lines
13263 that costs. If there is a word longer than WIDTH, the text is actually
13264 wrapped to the length of that word.
13265 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
13266 many lines, whatever width that takes.
13267 The return value is a list of lines, without newlines at the end."
13268 (let* ((words (org-split-string string "[ \t\n]+"))
13269 (maxword (apply 'max (mapcar 'org-string-width words)))
13270 w ll)
13271 (cond (width
13272 (org-do-wrap words (max maxword width)))
13273 (lines
13274 (setq w maxword)
13275 (setq ll (org-do-wrap words maxword))
13276 (if (<= (length ll) lines)
13278 (setq ll words)
13279 (while (> (length ll) lines)
13280 (setq w (1+ w))
13281 (setq ll (org-do-wrap words w)))
13282 ll))
13283 (t (error "Cannot wrap this")))))
13285 (defun org-do-wrap (words width)
13286 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
13287 (let (lines line)
13288 (while words
13289 (setq line (pop words))
13290 (while (and words (< (+ (length line) (length (car words))) width))
13291 (setq line (concat line " " (pop words))))
13292 (setq lines (push line lines)))
13293 (nreverse lines)))
13295 (defun org-split-string (string &optional separators)
13296 "Splits STRING into substrings at SEPARATORS.
13297 No empty strings are returned if there are matches at the beginning
13298 and end of string."
13299 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
13300 (start 0)
13301 notfirst
13302 (list nil))
13303 (while (and (string-match rexp string
13304 (if (and notfirst
13305 (= start (match-beginning 0))
13306 (< start (length string)))
13307 (1+ start) start))
13308 (< (match-beginning 0) (length string)))
13309 (setq notfirst t)
13310 (or (eq (match-beginning 0) 0)
13311 (and (eq (match-beginning 0) (match-end 0))
13312 (eq (match-beginning 0) start))
13313 (setq list
13314 (cons (substring string start (match-beginning 0))
13315 list)))
13316 (setq start (match-end 0)))
13317 (or (eq start (length string))
13318 (setq list
13319 (cons (substring string start)
13320 list)))
13321 (nreverse list)))
13323 (defun org-context ()
13324 "Return a list of contexts of the current cursor position.
13325 If several contexts apply, all are returned.
13326 Each context entry is a list with a symbol naming the context, and
13327 two positions indicating start and end of the context. Possible
13328 contexts are:
13330 :headline anywhere in a headline
13331 :headline-stars on the leading stars in a headline
13332 :todo-keyword on a TODO keyword (including DONE) in a headline
13333 :tags on the TAGS in a headline
13334 :priority on the priority cookie in a headline
13335 :item on the first line of a plain list item
13336 :item-bullet on the bullet/number of a plain list item
13337 :checkbox on the checkbox in a plain list item
13338 :table in an org-mode table
13339 :table-special on a special filed in a table
13340 :table-table in a table.el table
13341 :link on a hyperlink
13342 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
13343 :target on a <<target>>
13344 :radio-target on a <<<radio-target>>>
13345 :latex-fragment on a LaTeX fragment
13346 :latex-preview on a LaTeX fragment with overlayed preview image
13348 This function expects the position to be visible because it uses font-lock
13349 faces as a help to recognize the following contexts: :table-special, :link,
13350 and :keyword."
13351 (let* ((f (get-text-property (point) 'face))
13352 (faces (if (listp f) f (list f)))
13353 (p (point)) clist o)
13354 ;; First the large context
13355 (cond
13356 ((org-on-heading-p t)
13357 (push (list :headline (point-at-bol) (point-at-eol)) clist)
13358 (when (progn
13359 (beginning-of-line 1)
13360 (looking-at org-todo-line-tags-regexp))
13361 (push (org-point-in-group p 1 :headline-stars) clist)
13362 (push (org-point-in-group p 2 :todo-keyword) clist)
13363 (push (org-point-in-group p 4 :tags) clist))
13364 (goto-char p)
13365 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
13366 (if (looking-at "\\[#[A-Z0-9]\\]")
13367 (push (org-point-in-group p 0 :priority) clist)))
13369 ((org-at-item-p)
13370 (push (org-point-in-group p 2 :item-bullet) clist)
13371 (push (list :item (point-at-bol)
13372 (save-excursion (org-end-of-item) (point)))
13373 clist)
13374 (and (org-at-item-checkbox-p)
13375 (push (org-point-in-group p 0 :checkbox) clist)))
13377 ((org-at-table-p)
13378 (push (list :table (org-table-begin) (org-table-end)) clist)
13379 (if (memq 'org-formula faces)
13380 (push (list :table-special
13381 (previous-single-property-change p 'face)
13382 (next-single-property-change p 'face)) clist)))
13383 ((org-at-table-p 'any)
13384 (push (list :table-table) clist)))
13385 (goto-char p)
13387 ;; Now the small context
13388 (cond
13389 ((org-at-timestamp-p)
13390 (push (org-point-in-group p 0 :timestamp) clist))
13391 ((memq 'org-link faces)
13392 (push (list :link
13393 (previous-single-property-change p 'face)
13394 (next-single-property-change p 'face)) clist))
13395 ((memq 'org-special-keyword faces)
13396 (push (list :keyword
13397 (previous-single-property-change p 'face)
13398 (next-single-property-change p 'face)) clist))
13399 ((org-on-target-p)
13400 (push (org-point-in-group p 0 :target) clist)
13401 (goto-char (1- (match-beginning 0)))
13402 (if (looking-at org-radio-target-regexp)
13403 (push (org-point-in-group p 0 :radio-target) clist))
13404 (goto-char p))
13405 ((setq o (car (delq nil
13406 (mapcar
13407 (lambda (x)
13408 (if (memq x org-latex-fragment-image-overlays) x))
13409 (org-overlays-at (point))))))
13410 (push (list :latex-fragment
13411 (org-overlay-start o) (org-overlay-end o)) clist)
13412 (push (list :latex-preview
13413 (org-overlay-start o) (org-overlay-end o)) clist))
13414 ((org-inside-LaTeX-fragment-p)
13415 ;; FIXME: positions wrong.
13416 (push (list :latex-fragment (point) (point)) clist)))
13418 (setq clist (nreverse (delq nil clist)))
13419 clist))
13421 ;; FIXME: Compare with at-regexp-p Do we need both?
13422 (defun org-in-regexp (re &optional nlines visually)
13423 "Check if point is inside a match of regexp.
13424 Normally only the current line is checked, but you can include NLINES extra
13425 lines both before and after point into the search.
13426 If VISUALLY is set, require that the cursor is not after the match but
13427 really on, so that the block visually is on the match."
13428 (catch 'exit
13429 (let ((pos (point))
13430 (eol (point-at-eol (+ 1 (or nlines 0))))
13431 (inc (if visually 1 0)))
13432 (save-excursion
13433 (beginning-of-line (- 1 (or nlines 0)))
13434 (while (re-search-forward re eol t)
13435 (if (and (<= (match-beginning 0) pos)
13436 (>= (+ inc (match-end 0)) pos))
13437 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
13439 (defun org-at-regexp-p (regexp)
13440 "Is point inside a match of REGEXP in the current line?"
13441 (catch 'exit
13442 (save-excursion
13443 (let ((pos (point)) (end (point-at-eol)))
13444 (beginning-of-line 1)
13445 (while (re-search-forward regexp end t)
13446 (if (and (<= (match-beginning 0) pos)
13447 (>= (match-end 0) pos))
13448 (throw 'exit t)))
13449 nil))))
13451 (defun org-occur-in-agenda-files (regexp &optional nlines)
13452 "Call `multi-occur' with buffers for all agenda files."
13453 (interactive "sOrg-files matching: \np")
13454 (let* ((files (org-agenda-files))
13455 (tnames (mapcar 'file-truename files))
13456 (extra org-agenda-text-search-extra-files)
13458 (when (eq (car extra) 'agenda-archives)
13459 (setq extra (cdr extra))
13460 (setq files (org-add-archive-files files)))
13461 (while (setq f (pop extra))
13462 (unless (member (file-truename f) tnames)
13463 (add-to-list 'files f 'append)
13464 (add-to-list 'tnames (file-truename f) 'append)))
13465 (multi-occur
13466 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
13467 regexp)))
13469 (if (boundp 'occur-mode-find-occurrence-hook)
13470 ;; Emacs 23
13471 (add-hook 'occur-mode-find-occurrence-hook
13472 (lambda ()
13473 (when (org-mode-p)
13474 (org-reveal))))
13475 ;; Emacs 22
13476 (defadvice occur-mode-goto-occurrence
13477 (after org-occur-reveal activate)
13478 (and (org-mode-p) (org-reveal)))
13479 (defadvice occur-mode-goto-occurrence-other-window
13480 (after org-occur-reveal activate)
13481 (and (org-mode-p) (org-reveal)))
13482 (defadvice occur-mode-display-occurrence
13483 (after org-occur-reveal activate)
13484 (when (org-mode-p)
13485 (let ((pos (occur-mode-find-occurrence)))
13486 (with-current-buffer (marker-buffer pos)
13487 (save-excursion
13488 (goto-char pos)
13489 (org-reveal)))))))
13491 (defun org-uniquify (list)
13492 "Remove duplicate elements from LIST."
13493 (let (res)
13494 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
13495 res))
13497 (defun org-delete-all (elts list)
13498 "Remove all elements in ELTS from LIST."
13499 (while elts
13500 (setq list (delete (pop elts) list)))
13501 list)
13503 (defun org-back-over-empty-lines ()
13504 "Move backwards over witespace, to the beginning of the first empty line.
13505 Returns the number of empty lines passed."
13506 (let ((pos (point)))
13507 (skip-chars-backward " \t\n\r")
13508 (beginning-of-line 2)
13509 (goto-char (min (point) pos))
13510 (count-lines (point) pos)))
13512 (defun org-skip-whitespace ()
13513 (skip-chars-forward " \t\n\r"))
13515 (defun org-point-in-group (point group &optional context)
13516 "Check if POINT is in match-group GROUP.
13517 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
13518 match. If the match group does ot exist or point is not inside it,
13519 return nil."
13520 (and (match-beginning group)
13521 (>= point (match-beginning group))
13522 (<= point (match-end group))
13523 (if context
13524 (list context (match-beginning group) (match-end group))
13525 t)))
13527 (defun org-switch-to-buffer-other-window (&rest args)
13528 "Switch to buffer in a second window on the current frame.
13529 In particular, do not allow pop-up frames."
13530 (let (pop-up-frames special-display-buffer-names special-display-regexps
13531 special-display-function)
13532 (apply 'switch-to-buffer-other-window args)))
13534 (defun org-combine-plists (&rest plists)
13535 "Create a single property list from all plists in PLISTS.
13536 The process starts by copying the first list, and then setting properties
13537 from the other lists. Settings in the last list are the most significant
13538 ones and overrule settings in the other lists."
13539 (let ((rtn (copy-sequence (pop plists)))
13540 p v ls)
13541 (while plists
13542 (setq ls (pop plists))
13543 (while ls
13544 (setq p (pop ls) v (pop ls))
13545 (setq rtn (plist-put rtn p v))))
13546 rtn))
13548 (defun org-move-line-down (arg)
13549 "Move the current line down. With prefix argument, move it past ARG lines."
13550 (interactive "p")
13551 (let ((col (current-column))
13552 beg end pos)
13553 (beginning-of-line 1) (setq beg (point))
13554 (beginning-of-line 2) (setq end (point))
13555 (beginning-of-line (+ 1 arg))
13556 (setq pos (move-marker (make-marker) (point)))
13557 (insert (delete-and-extract-region beg end))
13558 (goto-char pos)
13559 (org-move-to-column col)))
13561 (defun org-move-line-up (arg)
13562 "Move the current line up. With prefix argument, move it past ARG lines."
13563 (interactive "p")
13564 (let ((col (current-column))
13565 beg end pos)
13566 (beginning-of-line 1) (setq beg (point))
13567 (beginning-of-line 2) (setq end (point))
13568 (beginning-of-line (- arg))
13569 (setq pos (move-marker (make-marker) (point)))
13570 (insert (delete-and-extract-region beg end))
13571 (goto-char pos)
13572 (org-move-to-column col)))
13574 (defun org-replace-escapes (string table)
13575 "Replace %-escapes in STRING with values in TABLE.
13576 TABLE is an association list with keys like \"%a\" and string values.
13577 The sequences in STRING may contain normal field width and padding information,
13578 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
13579 so values can contain further %-escapes if they are define later in TABLE."
13580 (let ((case-fold-search nil)
13581 e re rpl)
13582 (while (setq e (pop table))
13583 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
13584 (while (string-match re string)
13585 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
13586 (cdr e)))
13587 (setq string (replace-match rpl t t string))))
13588 string))
13591 (defun org-sublist (list start end)
13592 "Return a section of LIST, from START to END.
13593 Counting starts at 1."
13594 (let (rtn (c start))
13595 (setq list (nthcdr (1- start) list))
13596 (while (and list (<= c end))
13597 (push (pop list) rtn)
13598 (setq c (1+ c)))
13599 (nreverse rtn)))
13601 (defun org-find-base-buffer-visiting (file)
13602 "Like `find-buffer-visiting' but alway return the base buffer and
13603 not an indirect buffer."
13604 (let ((buf (find-buffer-visiting file)))
13605 (if buf
13606 (or (buffer-base-buffer buf) buf)
13607 nil)))
13609 (defun org-image-file-name-regexp ()
13610 "Return regexp matching the file names of images."
13611 (if (fboundp 'image-file-name-regexp)
13612 (image-file-name-regexp)
13613 (let ((image-file-name-extensions
13614 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
13615 "xbm" "xpm" "pbm" "pgm" "ppm")))
13616 (concat "\\."
13617 (regexp-opt (nconc (mapcar 'upcase
13618 image-file-name-extensions)
13619 image-file-name-extensions)
13621 "\\'"))))
13623 (defun org-file-image-p (file)
13624 "Return non-nil if FILE is an image."
13625 (save-match-data
13626 (string-match (org-image-file-name-regexp) file)))
13628 (defun org-get-cursor-date ()
13629 "Return the date at cursor in as a time.
13630 This works in the calendar and in the agenda, anywhere else it just
13631 returns the current time."
13632 (let (date day defd)
13633 (cond
13634 ((eq major-mode 'calendar-mode)
13635 (setq date (calendar-cursor-to-date)
13636 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13637 ((eq major-mode 'org-agenda-mode)
13638 (setq day (get-text-property (point) 'day))
13639 (if day
13640 (setq date (calendar-gregorian-from-absolute day)
13641 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
13642 (nth 2 date))))))
13643 (or defd (current-time))))
13645 (defvar org-agenda-action-marker (make-marker)
13646 "Marker pointing to the entry for the next agenda action.")
13648 (defun org-mark-entry-for-agenda-action ()
13649 "Mark the current entry as target of an agenda action.
13650 Agenda actions are actions executed from the agenda with the key `k',
13651 which make use of the date at the cursor."
13652 (interactive)
13653 (move-marker org-agenda-action-marker
13654 (save-excursion (org-back-to-heading t) (point))
13655 (current-buffer))
13656 (message
13657 "Entry marked for action; press `k' at desired date in agenda or calendar"))
13659 ;;; Paragraph filling stuff.
13660 ;; We want this to be just right, so use the full arsenal.
13662 (defun org-indent-line-function ()
13663 "Indent line like previous, but further if previous was headline or item."
13664 (interactive)
13665 (let* ((pos (point))
13666 (itemp (org-at-item-p))
13667 column bpos bcol tpos tcol bullet btype bullet-type)
13668 ;; Find the previous relevant line
13669 (beginning-of-line 1)
13670 (cond
13671 ((looking-at "#") (setq column 0))
13672 ((looking-at "\\*+ ") (setq column 0))
13674 (beginning-of-line 0)
13675 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
13676 (beginning-of-line 0))
13677 (cond
13678 ((looking-at "\\*+[ \t]+")
13679 (if (not org-adapt-indentation)
13680 (setq column 0)
13681 (goto-char (match-end 0))
13682 (setq column (current-column))))
13683 ((org-in-item-p)
13684 (org-beginning-of-item)
13685 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
13686 (setq bpos (match-beginning 1) tpos (match-end 0)
13687 bcol (progn (goto-char bpos) (current-column))
13688 tcol (progn (goto-char tpos) (current-column))
13689 bullet (match-string 1)
13690 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
13691 (if (> tcol (+ bcol org-description-max-indent))
13692 (setq tcol (+ bcol 5)))
13693 (if (not itemp)
13694 (setq column tcol)
13695 (goto-char pos)
13696 (beginning-of-line 1)
13697 (if (looking-at "\\S-")
13698 (progn
13699 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
13700 (setq bullet (match-string 1)
13701 btype (if (string-match "[0-9]" bullet) "n" bullet))
13702 (setq column (if (equal btype bullet-type) bcol tcol)))
13703 (setq column (org-get-indentation)))))
13704 (t (setq column (org-get-indentation))))))
13705 (goto-char pos)
13706 (if (<= (current-column) (current-indentation))
13707 (org-indent-line-to column)
13708 (save-excursion (org-indent-line-to column)))
13709 (setq column (current-column))
13710 (beginning-of-line 1)
13711 (if (looking-at
13712 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
13713 (replace-match (concat "\\1" (format org-property-format
13714 (match-string 2) (match-string 3)))
13715 t nil))
13716 (org-move-to-column column)))
13718 (defun org-set-autofill-regexps ()
13719 (interactive)
13720 ;; In the paragraph separator we include headlines, because filling
13721 ;; text in a line directly attached to a headline would otherwise
13722 ;; fill the headline as well.
13723 (org-set-local 'comment-start-skip "^#+[ \t]*")
13724 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
13725 ;; The paragraph starter includes hand-formatted lists.
13726 (org-set-local 'paragraph-start
13727 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
13728 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
13729 ;; But only if the user has not turned off tables or fixed-width regions
13730 (org-set-local
13731 'auto-fill-inhibit-regexp
13732 (concat "\\*+ \\|#\\+"
13733 "\\|[ \t]*" org-keyword-time-regexp
13734 (if (or org-enable-table-editor org-enable-fixed-width-editor)
13735 (concat
13736 "\\|[ \t]*["
13737 (if org-enable-table-editor "|" "")
13738 (if org-enable-fixed-width-editor ":" "")
13739 "]"))))
13740 ;; We use our own fill-paragraph function, to make sure that tables
13741 ;; and fixed-width regions are not wrapped. That function will pass
13742 ;; through to `fill-paragraph' when appropriate.
13743 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
13744 ; Adaptive filling: To get full control, first make sure that
13745 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
13746 (org-set-local 'adaptive-fill-regexp "\000")
13747 (org-set-local 'adaptive-fill-function
13748 'org-adaptive-fill-function)
13749 (org-set-local
13750 'align-mode-rules-list
13751 '((org-in-buffer-settings
13752 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
13753 (modes . '(org-mode))))))
13755 (defun org-fill-paragraph (&optional justify)
13756 "Re-align a table, pass through to fill-paragraph if no table."
13757 (let ((table-p (org-at-table-p))
13758 (table.el-p (org-at-table.el-p)))
13759 (cond ((and (equal (char-after (point-at-bol)) ?*)
13760 (save-excursion (goto-char (point-at-bol))
13761 (looking-at outline-regexp)))
13762 t) ; skip headlines
13763 (table.el-p t) ; skip table.el tables
13764 (table-p (org-table-align) t) ; align org-mode tables
13765 (t nil)))) ; call paragraph-fill
13767 ;; For reference, this is the default value of adaptive-fill-regexp
13768 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
13770 (defun org-adaptive-fill-function ()
13771 "Return a fill prefix for org-mode files.
13772 In particular, this makes sure hanging paragraphs for hand-formatted lists
13773 work correctly."
13774 (cond ((looking-at "#[ \t]+")
13775 (match-string 0))
13776 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
13777 (save-excursion
13778 (if (> (match-end 1) (+ (match-beginning 1)
13779 org-description-max-indent))
13780 (goto-char (+ (match-beginning 1) 5))
13781 (goto-char (match-end 0)))
13782 (make-string (current-column) ?\ )))
13783 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
13784 (save-excursion
13785 (goto-char (match-end 0))
13786 (make-string (current-column) ?\ )))
13787 (t nil)))
13789 ;;; Other stuff.
13791 (defun org-toggle-fixed-width-section (arg)
13792 "Toggle the fixed-width export.
13793 If there is no active region, the QUOTE keyword at the current headline is
13794 inserted or removed. When present, it causes the text between this headline
13795 and the next to be exported as fixed-width text, and unmodified.
13796 If there is an active region, this command adds or removes a colon as the
13797 first character of this line. If the first character of a line is a colon,
13798 this line is also exported in fixed-width font."
13799 (interactive "P")
13800 (let* ((cc 0)
13801 (regionp (org-region-active-p))
13802 (beg (if regionp (region-beginning) (point)))
13803 (end (if regionp (region-end)))
13804 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
13805 (case-fold-search nil)
13806 (re "[ \t]*\\(:\\)")
13807 off)
13808 (if regionp
13809 (save-excursion
13810 (goto-char beg)
13811 (setq cc (current-column))
13812 (beginning-of-line 1)
13813 (setq off (looking-at re))
13814 (while (> nlines 0)
13815 (setq nlines (1- nlines))
13816 (beginning-of-line 1)
13817 (cond
13818 (arg
13819 (org-move-to-column cc t)
13820 (insert ":\n")
13821 (forward-line -1))
13822 ((and off (looking-at re))
13823 (replace-match "" t t nil 1))
13824 ((not off) (org-move-to-column cc t) (insert ":")))
13825 (forward-line 1)))
13826 (save-excursion
13827 (org-back-to-heading)
13828 (if (looking-at (concat outline-regexp
13829 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
13830 (replace-match "" t t nil 1)
13831 (if (looking-at outline-regexp)
13832 (progn
13833 (goto-char (match-end 0))
13834 (insert org-quote-string " "))))))))
13836 ;;;; Functions extending outline functionality
13838 (defun org-beginning-of-line (&optional arg)
13839 "Go to the beginning of the current line. If that is invisible, continue
13840 to a visible line beginning. This makes the function of C-a more intuitive.
13841 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
13842 first attempt, and only move to after the tags when the cursor is already
13843 beyond the end of the headline."
13844 (interactive "P")
13845 (let ((pos (point)) refpos)
13846 (beginning-of-line 1)
13847 (if (bobp)
13849 (backward-char 1)
13850 (if (org-invisible-p)
13851 (while (and (not (bobp)) (org-invisible-p))
13852 (backward-char 1)
13853 (beginning-of-line 1))
13854 (forward-char 1)))
13855 (when org-special-ctrl-a/e
13856 (cond
13857 ((and (looking-at org-complex-heading-regexp)
13858 (= (char-after (match-end 1)) ?\ ))
13859 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
13860 (point-at-eol)))
13861 (goto-char
13862 (if (eq org-special-ctrl-a/e t)
13863 (cond ((> pos refpos) refpos)
13864 ((= pos (point)) refpos)
13865 (t (point)))
13866 (cond ((> pos (point)) (point))
13867 ((not (eq last-command this-command)) (point))
13868 (t refpos)))))
13869 ((org-at-item-p)
13870 (goto-char
13871 (if (eq org-special-ctrl-a/e t)
13872 (cond ((> pos (match-end 4)) (match-end 4))
13873 ((= pos (point)) (match-end 4))
13874 (t (point)))
13875 (cond ((> pos (point)) (point))
13876 ((not (eq last-command this-command)) (point))
13877 (t (match-end 4))))))))
13878 (org-no-warnings
13879 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
13881 (defun org-end-of-line (&optional arg)
13882 "Go to the end of the line.
13883 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
13884 first attempt, and only move to after the tags when the cursor is already
13885 beyond the end of the headline."
13886 (interactive "P")
13887 (if (or (not org-special-ctrl-a/e)
13888 (not (org-on-heading-p)))
13889 (end-of-line arg)
13890 (let ((pos (point)))
13891 (beginning-of-line 1)
13892 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
13893 (if (eq org-special-ctrl-a/e t)
13894 (if (or (< pos (match-beginning 1))
13895 (= pos (match-end 0)))
13896 (goto-char (match-beginning 1))
13897 (goto-char (match-end 0)))
13898 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
13899 (goto-char (match-end 0))
13900 (goto-char (match-beginning 1))))
13901 (end-of-line arg))))
13902 (org-no-warnings
13903 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
13906 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
13907 (define-key org-mode-map "\C-e" 'org-end-of-line)
13909 (defun org-kill-line (&optional arg)
13910 "Kill line, to tags or end of line."
13911 (interactive "P")
13912 (cond
13913 ((or (not org-special-ctrl-k)
13914 (bolp)
13915 (not (org-on-heading-p)))
13916 (call-interactively 'kill-line))
13917 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
13918 (kill-region (point) (match-beginning 1))
13919 (org-set-tags nil t))
13920 (t (kill-region (point) (point-at-eol)))))
13922 (define-key org-mode-map "\C-k" 'org-kill-line)
13924 (defun org-yank ()
13925 "Yank. If the kill is a subtree, treat it specially.
13926 This command will look at the current kill and check it is a single
13927 subtree, or a series of subtrees[1]. If it passes the test, it is
13928 treated specially, depending on the value of the following variables, both
13929 set by default.
13931 org-yank-folded-subtrees
13932 When set, the subree(s) wiil be folded after insertion.
13934 org-yank-adjusted-subtrees
13935 When set, the subtree will be promoted or demoted in order to
13936 fit into the local outline tree structure.
13939 \[1] Basically, the test checks if the first non-white line is a heading
13940 and if there are no other headings with fewer stars."
13941 (interactive)
13942 (let ((subtreep (org-kill-is-subtree-p)))
13943 (if org-yank-folded-subtrees
13944 (let ((beg (point))
13945 end)
13946 (if (and subtreep org-yank-adjusted-subtrees)
13947 (org-paste-subtree nil nil 'for-yank)
13948 (call-interactively 'yank))
13949 (setq end (point))
13950 (goto-char beg)
13951 (when (and (bolp) subtreep)
13952 (or (looking-at outline-regexp)
13953 (re-search-forward (concat "^" outline-regexp) end t))
13954 (while (and (< (point) end) (looking-at outline-regexp))
13955 (hide-subtree)
13956 (org-cycle-show-empty-lines 'folded)
13957 (condition-case nil
13958 (outline-forward-same-level 1)
13959 (error (goto-char end)))))
13960 (goto-char end)
13961 (skip-chars-forward " \t\n\r"))
13962 (if (and subtreep org-yank-adjusted-subtrees)
13963 (org-paste-subtree nil nil 'for-yank)
13964 (call-interactively 'yank)))))
13966 (define-key org-mode-map "\C-y" 'org-yank)
13968 (defun org-invisible-p ()
13969 "Check if point is at a character currently not visible."
13970 ;; Early versions of noutline don't have `outline-invisible-p'.
13971 (if (fboundp 'outline-invisible-p)
13972 (outline-invisible-p)
13973 (get-char-property (point) 'invisible)))
13975 (defun org-invisible-p2 ()
13976 "Check if point is at a character currently not visible."
13977 (save-excursion
13978 (if (and (eolp) (not (bobp))) (backward-char 1))
13979 ;; Early versions of noutline don't have `outline-invisible-p'.
13980 (if (fboundp 'outline-invisible-p)
13981 (outline-invisible-p)
13982 (get-char-property (point) 'invisible))))
13984 (defalias 'org-back-to-heading 'outline-back-to-heading)
13985 (defalias 'org-on-heading-p 'outline-on-heading-p)
13986 (defalias 'org-at-heading-p 'outline-on-heading-p)
13987 (defun org-at-heading-or-item-p ()
13988 (or (org-on-heading-p) (org-at-item-p)))
13990 (defun org-on-target-p ()
13991 (or (org-in-regexp org-radio-target-regexp)
13992 (org-in-regexp org-target-regexp)))
13994 (defun org-up-heading-all (arg)
13995 "Move to the heading line of which the present line is a subheading.
13996 This function considers both visible and invisible heading lines.
13997 With argument, move up ARG levels."
13998 (if (fboundp 'outline-up-heading-all)
13999 (outline-up-heading-all arg) ; emacs 21 version of outline.el
14000 (outline-up-heading arg t))) ; emacs 22 version of outline.el
14002 (defun org-up-heading-safe ()
14003 "Move to the heading line of which the present line is a subheading.
14004 This version will not throw an error. It will return the level of the
14005 headline found, or nil if no higher level is found."
14006 (let ((pos (point)) start-level level
14007 (re (concat "^" outline-regexp)))
14008 (catch 'exit
14009 (outline-back-to-heading t)
14010 (setq start-level (funcall outline-level))
14011 (if (equal start-level 1) (throw 'exit nil))
14012 (while (re-search-backward re nil t)
14013 (setq level (funcall outline-level))
14014 (if (< level start-level) (throw 'exit level)))
14015 nil)))
14017 (defun org-first-sibling-p ()
14018 "Is this heading the first child of its parents?"
14019 (interactive)
14020 (let ((re (concat "^" outline-regexp))
14021 level l)
14022 (unless (org-at-heading-p t)
14023 (error "Not at a heading"))
14024 (setq level (funcall outline-level))
14025 (save-excursion
14026 (if (not (re-search-backward re nil t))
14028 (setq l (funcall outline-level))
14029 (< l level)))))
14031 (defun org-goto-sibling (&optional previous)
14032 "Goto the next sibling, even if it is invisible.
14033 When PREVIOUS is set, go to the previous sibling instead. Returns t
14034 when a sibling was found. When none is found, return nil and don't
14035 move point."
14036 (let ((fun (if previous 're-search-backward 're-search-forward))
14037 (pos (point))
14038 (re (concat "^" outline-regexp))
14039 level l)
14040 (when (condition-case nil (org-back-to-heading t) (error nil))
14041 (setq level (funcall outline-level))
14042 (catch 'exit
14043 (or previous (forward-char 1))
14044 (while (funcall fun re nil t)
14045 (setq l (funcall outline-level))
14046 (when (< l level) (goto-char pos) (throw 'exit nil))
14047 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
14048 (goto-char pos)
14049 nil))))
14051 (defun org-show-siblings ()
14052 "Show all siblings of the current headline."
14053 (save-excursion
14054 (while (org-goto-sibling) (org-flag-heading nil)))
14055 (save-excursion
14056 (while (org-goto-sibling 'previous)
14057 (org-flag-heading nil))))
14059 (defun org-show-hidden-entry ()
14060 "Show an entry where even the heading is hidden."
14061 (save-excursion
14062 (org-show-entry)))
14064 (defun org-flag-heading (flag &optional entry)
14065 "Flag the current heading. FLAG non-nil means make invisible.
14066 When ENTRY is non-nil, show the entire entry."
14067 (save-excursion
14068 (org-back-to-heading t)
14069 ;; Check if we should show the entire entry
14070 (if entry
14071 (progn
14072 (org-show-entry)
14073 (save-excursion
14074 (and (outline-next-heading)
14075 (org-flag-heading nil))))
14076 (outline-flag-region (max (point-min) (1- (point)))
14077 (save-excursion (outline-end-of-heading) (point))
14078 flag))))
14080 (defun org-forward-same-level (arg)
14081 "Move forward to the ARG'th subheading at same level as this one.
14082 Stop at the first and last subheadings of a superior heading.
14083 This is like outline-forward-same-level, but invisible headings are ok."
14084 (interactive "p")
14085 (outline-back-to-heading t)
14086 (while (> arg 0)
14087 (let ((point-to-move-to (save-excursion
14088 (org-get-next-sibling))))
14089 (if point-to-move-to
14090 (progn
14091 (goto-char point-to-move-to)
14092 (setq arg (1- arg)))
14093 (progn
14094 (setq arg 0)
14095 (error "No following same-level heading"))))))
14097 (defun org-get-next-sibling ()
14098 "Move to next heading of the same level, and return point.
14099 If there is no such heading, return nil.
14100 This is like outline-next-sibling, but invisible headings are ok."
14101 (let ((level (funcall outline-level)))
14102 (outline-next-heading)
14103 (while (and (not (eobp)) (> (funcall outline-level) level))
14104 (outline-next-heading))
14105 (if (or (eobp) (< (funcall outline-level) level))
14107 (point))))
14109 (defun org-end-of-subtree (&optional invisible-OK to-heading)
14110 ;; This is an exact copy of the original function, but it uses
14111 ;; `org-back-to-heading', to make it work also in invisible
14112 ;; trees. And is uses an invisible-OK argument.
14113 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
14114 (org-back-to-heading invisible-OK)
14115 (let ((first t)
14116 (level (funcall outline-level)))
14117 (while (and (not (eobp))
14118 (or first (> (funcall outline-level) level)))
14119 (setq first nil)
14120 (outline-next-heading))
14121 (unless to-heading
14122 (if (memq (preceding-char) '(?\n ?\^M))
14123 (progn
14124 ;; Go to end of line before heading
14125 (forward-char -1)
14126 (if (memq (preceding-char) '(?\n ?\^M))
14127 ;; leave blank line before heading
14128 (forward-char -1))))))
14129 (point))
14131 (defun org-show-subtree ()
14132 "Show everything after this heading at deeper levels."
14133 (outline-flag-region
14134 (point)
14135 (save-excursion
14136 (outline-end-of-subtree) (outline-next-heading) (point))
14137 nil))
14139 (defun org-show-entry ()
14140 "Show the body directly following this heading.
14141 Show the heading too, if it is currently invisible."
14142 (interactive)
14143 (save-excursion
14144 (condition-case nil
14145 (progn
14146 (org-back-to-heading t)
14147 (outline-flag-region
14148 (max (point-min) (1- (point)))
14149 (save-excursion
14150 (re-search-forward
14151 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
14152 (or (match-beginning 1) (point-max)))
14153 nil))
14154 (error nil))))
14156 (defun org-make-options-regexp (kwds)
14157 "Make a regular expression for keyword lines."
14158 (concat
14160 "#?[ \t]*\\+\\("
14161 (mapconcat 'regexp-quote kwds "\\|")
14162 "\\):[ \t]*"
14163 "\\(.+\\)"))
14165 ;; Make isearch reveal the necessary context
14166 (defun org-isearch-end ()
14167 "Reveal context after isearch exits."
14168 (when isearch-success ; only if search was successful
14169 (if (featurep 'xemacs)
14170 ;; Under XEmacs, the hook is run in the correct place,
14171 ;; we directly show the context.
14172 (org-show-context 'isearch)
14173 ;; In Emacs the hook runs *before* restoring the overlays.
14174 ;; So we have to use a one-time post-command-hook to do this.
14175 ;; (Emacs 22 has a special variable, see function `org-mode')
14176 (unless (and (boundp 'isearch-mode-end-hook-quit)
14177 isearch-mode-end-hook-quit)
14178 ;; Only when the isearch was not quitted.
14179 (org-add-hook 'post-command-hook 'org-isearch-post-command
14180 'append 'local)))))
14182 (defun org-isearch-post-command ()
14183 "Remove self from hook, and show context."
14184 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
14185 (org-show-context 'isearch))
14188 ;;;; Integration with and fixes for other packages
14190 ;;; Imenu support
14192 (defvar org-imenu-markers nil
14193 "All markers currently used by Imenu.")
14194 (make-variable-buffer-local 'org-imenu-markers)
14196 (defun org-imenu-new-marker (&optional pos)
14197 "Return a new marker for use by Imenu, and remember the marker."
14198 (let ((m (make-marker)))
14199 (move-marker m (or pos (point)))
14200 (push m org-imenu-markers)
14203 (defun org-imenu-get-tree ()
14204 "Produce the index for Imenu."
14205 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
14206 (setq org-imenu-markers nil)
14207 (let* ((n org-imenu-depth)
14208 (re (concat "^" outline-regexp))
14209 (subs (make-vector (1+ n) nil))
14210 (last-level 0)
14211 m tree level head)
14212 (save-excursion
14213 (save-restriction
14214 (widen)
14215 (goto-char (point-max))
14216 (while (re-search-backward re nil t)
14217 (setq level (org-reduced-level (funcall outline-level)))
14218 (when (<= level n)
14219 (looking-at org-complex-heading-regexp)
14220 (setq head (org-link-display-format
14221 (org-match-string-no-properties 4))
14222 m (org-imenu-new-marker))
14223 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
14224 (if (>= level last-level)
14225 (push (cons head m) (aref subs level))
14226 (push (cons head (aref subs (1+ level))) (aref subs level))
14227 (loop for i from (1+ level) to n do (aset subs i nil)))
14228 (setq last-level level)))))
14229 (aref subs 1)))
14231 (eval-after-load "imenu"
14232 '(progn
14233 (add-hook 'imenu-after-jump-hook
14234 (lambda ()
14235 (if (eq major-mode 'org-mode)
14236 (org-show-context 'org-goto))))))
14238 (defun org-link-display-format (link)
14239 "Replace a link with either the description, or the link target
14240 if no description is present"
14241 (save-match-data
14242 (if (string-match org-bracket-link-analytic-regexp link)
14243 (replace-match (or (match-string 5 link)
14244 (concat (match-string 1 link)
14245 (match-string 3 link)))
14246 nil nil link)
14247 link)))
14249 ;; Speedbar support
14251 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
14252 "Overlay marking the agenda restriction line in speedbar.")
14253 (org-overlay-put org-speedbar-restriction-lock-overlay
14254 'face 'org-agenda-restriction-lock)
14255 (org-overlay-put org-speedbar-restriction-lock-overlay
14256 'help-echo "Agendas are currently limited to this item.")
14257 (org-detach-overlay org-speedbar-restriction-lock-overlay)
14259 (defun org-speedbar-set-agenda-restriction ()
14260 "Restrict future agenda commands to the location at point in speedbar.
14261 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
14262 (interactive)
14263 (require 'org-agenda)
14264 (let (p m tp np dir txt w)
14265 (cond
14266 ((setq p (text-property-any (point-at-bol) (point-at-eol)
14267 'org-imenu t))
14268 (setq m (get-text-property p 'org-imenu-marker))
14269 (save-excursion
14270 (save-restriction
14271 (set-buffer (marker-buffer m))
14272 (goto-char m)
14273 (org-agenda-set-restriction-lock 'subtree))))
14274 ((setq p (text-property-any (point-at-bol) (point-at-eol)
14275 'speedbar-function 'speedbar-find-file))
14276 (setq tp (previous-single-property-change
14277 (1+ p) 'speedbar-function)
14278 np (next-single-property-change
14279 tp 'speedbar-function)
14280 dir (speedbar-line-directory)
14281 txt (buffer-substring-no-properties (or tp (point-min))
14282 (or np (point-max))))
14283 (save-excursion
14284 (save-restriction
14285 (set-buffer (find-file-noselect
14286 (let ((default-directory dir))
14287 (expand-file-name txt))))
14288 (unless (org-mode-p)
14289 (error "Cannot restrict to non-Org-mode file"))
14290 (org-agenda-set-restriction-lock 'file))))
14291 (t (error "Don't know how to restrict Org-mode's agenda")))
14292 (org-move-overlay org-speedbar-restriction-lock-overlay
14293 (point-at-bol) (point-at-eol))
14294 (setq current-prefix-arg nil)
14295 (org-agenda-maybe-redo)))
14297 (eval-after-load "speedbar"
14298 '(progn
14299 (speedbar-add-supported-extension ".org")
14300 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
14301 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
14302 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
14303 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
14304 (add-hook 'speedbar-visiting-tag-hook
14305 (lambda () (org-show-context 'org-goto)))))
14308 ;;; Fixes and Hacks for problems with other packages
14310 ;; Make flyspell not check words in links, to not mess up our keymap
14311 (defun org-mode-flyspell-verify ()
14312 "Don't let flyspell put overlays at active buttons."
14313 (not (get-text-property (point) 'keymap)))
14315 ;; Make `bookmark-jump' show the jump location if it was hidden.
14316 (eval-after-load "bookmark"
14317 '(if (boundp 'bookmark-after-jump-hook)
14318 ;; We can use the hook
14319 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
14320 ;; Hook not available, use advice
14321 (defadvice bookmark-jump (after org-make-visible activate)
14322 "Make the position visible."
14323 (org-bookmark-jump-unhide))))
14325 ;; Make sure saveplace show the location if it was hidden
14326 (eval-after-load "saveplace"
14327 '(defadvice save-place-find-file-hook (after org-make-visible activate)
14328 "Make the position visible."
14329 (org-bookmark-jump-unhide)))
14331 (defun org-bookmark-jump-unhide ()
14332 "Unhide the current position, to show the bookmark location."
14333 (and (org-mode-p)
14334 (or (org-invisible-p)
14335 (save-excursion (goto-char (max (point-min) (1- (point))))
14336 (org-invisible-p)))
14337 (org-show-context 'bookmark-jump)))
14339 ;; Make session.el ignore our circular variable
14340 (eval-after-load "session"
14341 '(add-to-list 'session-globals-exclude 'org-mark-ring))
14343 ;;;; Experimental code
14345 (defun org-closed-in-range ()
14346 "Sparse tree of items closed in a certain time range.
14347 Still experimental, may disappear in the future."
14348 (interactive)
14349 ;; Get the time interval from the user.
14350 (let* ((time1 (time-to-seconds
14351 (org-read-date nil 'to-time nil "Starting date: ")))
14352 (time2 (time-to-seconds
14353 (org-read-date nil 'to-time nil "End date:")))
14354 ;; callback function
14355 (callback (lambda ()
14356 (let ((time
14357 (time-to-seconds
14358 (apply 'encode-time
14359 (org-parse-time-string
14360 (match-string 1))))))
14361 ;; check if time in interval
14362 (and (>= time time1) (<= time time2))))))
14363 ;; make tree, check each match with the callback
14364 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
14367 ;;;; Finish up
14369 (provide 'org)
14371 (run-hooks 'org-load-hook)
14373 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
14375 ;;; org.el ends here