Release 6.19b
[org-mode/org-tableheadings.git] / lisp / org.el
blob88d0e704cfe644a3224463261c16bf844208b7f6
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, 2009 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.19b
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)
90 (require 'org-footnote)
92 ;;;; Customization variables
94 ;;; Version
96 (defconst org-version "6.19b"
97 "The version number of the file org.el.")
99 (defun org-version (&optional here)
100 "Show the org-mode version in the echo area.
101 With prefix arg HERE, insert it at point."
102 (interactive "P")
103 (let ((version (format "Org-mode version %s" org-version)))
104 (message version)
105 (if here
106 (insert version))))
108 ;;; Compatibility constants
110 ;;; The custom variables
112 (defgroup org nil
113 "Outline-based notes management and organizer."
114 :tag "Org"
115 :group 'outlines
116 :group 'hypermedia
117 :group 'calendar)
119 (defcustom org-load-hook nil
120 "Hook that is run after org.el has been loaded."
121 :group 'org
122 :type 'hook)
124 (defvar org-modules) ; defined below
125 (defvar org-modules-loaded nil
126 "Have the modules been loaded already?")
128 (defun org-load-modules-maybe (&optional force)
129 "Load all extensions listed in `org-modules'."
130 (when (or force (not org-modules-loaded))
131 (mapc (lambda (ext)
132 (condition-case nil (require ext)
133 (error (message "Problems while trying to load feature `%s'" ext))))
134 org-modules)
135 (setq org-modules-loaded t)))
137 (defun org-set-modules (var value)
138 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
139 (set var value)
140 (when (featurep 'org)
141 (org-load-modules-maybe 'force)))
143 (when (org-bound-and-true-p org-modules)
144 (let ((a (member 'org-infojs org-modules)))
145 (and a (setcar a 'org-jsinfo))))
147 (defcustom org-modules '(org-bbdb org-bibtex org-gnus org-info org-jsinfo org-irc org-mew org-mhe org-rmail org-vm org-w3m org-wl)
148 "Modules that should always be loaded together with org.el.
149 If a description starts with <C>, the file is not part of Emacs
150 and loading it will require that you have downloaded and properly installed
151 the org-mode distribution.
153 You can also use this system to load external packages (i.e. neither Org
154 core modules, not modules from the CONTRIB directory). Just add symbols
155 to the end of the list. If the package is called org-xyz.el, then you need
156 to add the symbol `xyz', and the package must have a call to
158 (provide 'org-xyz)"
159 :group 'org
160 :set 'org-set-modules
161 :type
162 '(set :greedy t
163 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
164 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
165 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
166 (const :tag " id: Global IDs for identifying entries" org-id)
167 (const :tag " info: Links to Info nodes" org-info)
168 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
169 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
170 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
171 (const :tag " mew Links to Mew folders/messages" org-mew)
172 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
173 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
174 (const :tag " vm: Links to VM folders/messages" org-vm)
175 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
176 (const :tag " w3m: Special cut/past from w3m to Org." org-w3m)
177 (const :tag " mouse: Additional mouse support" org-mouse)
179 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
180 (const :tag "C annotation-helper: Call Remember directly from Browser" org-annotation-helper)
181 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
182 (const :tag "C browser-url: Store link, directly from Browser" org-browser-url)
183 (const :tag "C depend: TODO dependencies for Org-mode" org-depend)
184 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
185 (const :tag "C eval: Include command output as text" org-eval)
186 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
187 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
188 (const :tag "C exp-blocks: Pre-process blocks for export" org-exp-blocks)
189 (const :tag "C interactive-query: Interactive modification of tags query" org-interactive-query)
190 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
191 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
192 (const :tag "C mtags: Support for muse-like tags" org-mtags)
193 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
194 (const :tag "C registry: A registry for Org links" org-registry)
195 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
196 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
197 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
198 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
199 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
202 (defgroup org-startup nil
203 "Options concerning startup of Org-mode."
204 :tag "Org Startup"
205 :group 'org)
207 (defcustom org-startup-folded t
208 "Non-nil means, entering Org-mode will switch to OVERVIEW.
209 This can also be configured on a per-file basis by adding one of
210 the following lines anywhere in the buffer:
212 #+STARTUP: fold
213 #+STARTUP: nofold
214 #+STARTUP: content"
215 :group 'org-startup
216 :type '(choice
217 (const :tag "nofold: show all" nil)
218 (const :tag "fold: overview" t)
219 (const :tag "content: all headlines" content)))
221 (defcustom org-startup-truncated t
222 "Non-nil means, entering Org-mode will set `truncate-lines'.
223 This is useful since some lines containing links can be very long and
224 uninteresting. Also tables look terrible when wrapped."
225 :group 'org-startup
226 :type 'boolean)
228 (defcustom org-startup-align-all-tables nil
229 "Non-nil means, align all tables when visiting a file.
230 This is useful when the column width in tables is forced with <N> cookies
231 in table fields. Such tables will look correct only after the first re-align.
232 This can also be configured on a per-file basis by adding one of
233 the following lines anywhere in the buffer:
234 #+STARTUP: align
235 #+STARTUP: noalign"
236 :group 'org-startup
237 :type 'boolean)
239 (defcustom org-insert-mode-line-in-empty-file nil
240 "Non-nil means insert the first line setting Org-mode in empty files.
241 When the function `org-mode' is called interactively in an empty file, this
242 normally means that the file name does not automatically trigger Org-mode.
243 To ensure that the file will always be in Org-mode in the future, a
244 line enforcing Org-mode will be inserted into the buffer, if this option
245 has been set."
246 :group 'org-startup
247 :type 'boolean)
249 (defcustom org-replace-disputed-keys nil
250 "Non-nil means use alternative key bindings for some keys.
251 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
252 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
253 If you want to use Org-mode together with one of these other modes,
254 or more generally if you would like to move some Org-mode commands to
255 other keys, set this variable and configure the keys with the variable
256 `org-disputed-keys'.
258 This option is only relevant at load-time of Org-mode, and must be set
259 *before* org.el is loaded. Changing it requires a restart of Emacs to
260 become effective."
261 :group 'org-startup
262 :type 'boolean)
264 (defcustom org-use-extra-keys nil
265 "Non-nil means use extra key sequence definitions for certain
266 commands. This happens automatically if you run XEmacs or if
267 window-system is nil. This variable lets you do the same
268 manually. You must set it before loading org.
270 Example: on Carbon Emacs 22 running graphically, with an external
271 keyboard on a Powerbook, the default way of setting M-left might
272 not work for either Alt or ESC. Setting this variable will make
273 it work for ESC."
274 :group 'org-startup
275 :type 'boolean)
277 (if (fboundp 'defvaralias)
278 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
280 (defcustom org-disputed-keys
281 '(([(shift up)] . [(meta p)])
282 ([(shift down)] . [(meta n)])
283 ([(shift left)] . [(meta -)])
284 ([(shift right)] . [(meta +)])
285 ([(control shift right)] . [(meta shift +)])
286 ([(control shift left)] . [(meta shift -)]))
287 "Keys for which Org-mode and other modes compete.
288 This is an alist, cars are the default keys, second element specifies
289 the alternative to use when `org-replace-disputed-keys' is t.
291 Keys can be specified in any syntax supported by `define-key'.
292 The value of this option takes effect only at Org-mode's startup,
293 therefore you'll have to restart Emacs to apply it after changing."
294 :group 'org-startup
295 :type 'alist)
297 (defun org-key (key)
298 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
299 Or return the original if not disputed."
300 (if org-replace-disputed-keys
301 (let* ((nkey (key-description key))
302 (x (org-find-if (lambda (x)
303 (equal (key-description (car x)) nkey))
304 org-disputed-keys)))
305 (if x (cdr x) key))
306 key))
308 (defun org-find-if (predicate seq)
309 (catch 'exit
310 (while seq
311 (if (funcall predicate (car seq))
312 (throw 'exit (car seq))
313 (pop seq)))))
315 (defun org-defkey (keymap key def)
316 "Define a key, possibly translated, as returned by `org-key'."
317 (define-key keymap (org-key key) def))
319 (defcustom org-ellipsis nil
320 "The ellipsis to use in the Org-mode outline.
321 When nil, just use the standard three dots. When a string, use that instead,
322 When a face, use the standard 3 dots, but with the specified face.
323 The change affects only Org-mode (which will then use its own display table).
324 Changing this requires executing `M-x org-mode' in a buffer to become
325 effective."
326 :group 'org-startup
327 :type '(choice (const :tag "Default" nil)
328 (face :tag "Face" :value org-warning)
329 (string :tag "String" :value "...#")))
331 (defvar org-display-table nil
332 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
334 (defgroup org-keywords nil
335 "Keywords in Org-mode."
336 :tag "Org Keywords"
337 :group 'org)
339 (defcustom org-deadline-string "DEADLINE:"
340 "String to mark deadline entries.
341 A deadline is this string, followed by a time stamp. Should be a word,
342 terminated by a colon. You can insert a schedule keyword and
343 a timestamp with \\[org-deadline].
344 Changes become only effective after restarting Emacs."
345 :group 'org-keywords
346 :type 'string)
348 (defcustom org-scheduled-string "SCHEDULED:"
349 "String to mark scheduled TODO entries.
350 A schedule is this string, followed by a time stamp. Should be a word,
351 terminated by a colon. You can insert a schedule keyword and
352 a timestamp with \\[org-schedule].
353 Changes become only effective after restarting Emacs."
354 :group 'org-keywords
355 :type 'string)
357 (defcustom org-closed-string "CLOSED:"
358 "String used as the prefix for timestamps logging closing a TODO entry."
359 :group 'org-keywords
360 :type 'string)
362 (defcustom org-clock-string "CLOCK:"
363 "String used as prefix for timestamps clocking work hours on an item."
364 :group 'org-keywords
365 :type 'string)
367 (defcustom org-comment-string "COMMENT"
368 "Entries starting with this keyword will never be exported.
369 An entry can be toggled between COMMENT and normal with
370 \\[org-toggle-comment].
371 Changes become only effective after restarting Emacs."
372 :group 'org-keywords
373 :type 'string)
375 (defcustom org-quote-string "QUOTE"
376 "Entries starting with this keyword will be exported in fixed-width font.
377 Quoting applies only to the text in the entry following the headline, and does
378 not extend beyond the next headline, even if that is lower level.
379 An entry can be toggled between QUOTE and normal with
380 \\[org-toggle-fixed-width-section]."
381 :group 'org-keywords
382 :type 'string)
384 (defconst org-repeat-re
385 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\([.+]?\\+[0-9]+[dwmy]\\)"
386 "Regular expression for specifying repeated events.
387 After a match, group 1 contains the repeat expression.")
389 (defgroup org-structure nil
390 "Options concerning the general structure of Org-mode files."
391 :tag "Org Structure"
392 :group 'org)
394 (defgroup org-reveal-location nil
395 "Options about how to make context of a location visible."
396 :tag "Org Reveal Location"
397 :group 'org-structure)
399 (defconst org-context-choice
400 '(choice
401 (const :tag "Always" t)
402 (const :tag "Never" nil)
403 (repeat :greedy t :tag "Individual contexts"
404 (cons
405 (choice :tag "Context"
406 (const agenda)
407 (const org-goto)
408 (const occur-tree)
409 (const tags-tree)
410 (const link-search)
411 (const mark-goto)
412 (const bookmark-jump)
413 (const isearch)
414 (const default))
415 (boolean))))
416 "Contexts for the reveal options.")
418 (defcustom org-show-hierarchy-above '((default . t))
419 "Non-nil means, show full hierarchy when revealing a location.
420 Org-mode often shows locations in an org-mode file which might have
421 been invisible before. When this is set, the hierarchy of headings
422 above the exposed location is shown.
423 Turning this off for example for sparse trees makes them very compact.
424 Instead of t, this can also be an alist specifying this option for different
425 contexts. Valid contexts are
426 agenda when exposing an entry from the agenda
427 org-goto when using the command `org-goto' on key C-c C-j
428 occur-tree when using the command `org-occur' on key C-c /
429 tags-tree when constructing a sparse tree based on tags matches
430 link-search when exposing search matches associated with a link
431 mark-goto when exposing the jump goal of a mark
432 bookmark-jump when exposing a bookmark location
433 isearch when exiting from an incremental search
434 default default for all contexts not set explicitly"
435 :group 'org-reveal-location
436 :type org-context-choice)
438 (defcustom org-show-following-heading '((default . nil))
439 "Non-nil means, show following heading when revealing a location.
440 Org-mode often shows locations in an org-mode file which might have
441 been invisible before. When this is set, the heading following the
442 match is shown.
443 Turning this off for example for sparse trees makes them very compact,
444 but makes it harder to edit the location of the match. In such a case,
445 use the command \\[org-reveal] to show more context.
446 Instead of t, this can also be an alist specifying this option for different
447 contexts. See `org-show-hierarchy-above' for valid contexts."
448 :group 'org-reveal-location
449 :type org-context-choice)
451 (defcustom org-show-siblings '((default . nil) (isearch t))
452 "Non-nil means, show all sibling heading when revealing a location.
453 Org-mode often shows locations in an org-mode file which might have
454 been invisible before. When this is set, the sibling of the current entry
455 heading are all made visible. If `org-show-hierarchy-above' is t,
456 the same happens on each level of the hierarchy above the current entry.
458 By default this is on for the isearch context, off for all other contexts.
459 Turning this off for example for sparse trees makes them very compact,
460 but makes it harder to edit the location of the match. In such a case,
461 use the command \\[org-reveal] to show more context.
462 Instead of t, this can also be an alist specifying this option for different
463 contexts. See `org-show-hierarchy-above' for valid contexts."
464 :group 'org-reveal-location
465 :type org-context-choice)
467 (defcustom org-show-entry-below '((default . nil))
468 "Non-nil means, show the entry below a headline when revealing a location.
469 Org-mode often shows locations in an org-mode file which might have
470 been invisible before. When this is set, the text below the headline that is
471 exposed is also shown.
473 By default this is off for all contexts.
474 Instead of t, this can also be an alist specifying this option for different
475 contexts. See `org-show-hierarchy-above' for valid contexts."
476 :group 'org-reveal-location
477 :type org-context-choice)
479 (defcustom org-indirect-buffer-display 'other-window
480 "How should indirect tree buffers be displayed?
481 This applies to indirect buffers created with the commands
482 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
483 Valid values are:
484 current-window Display in the current window
485 other-window Just display in another window.
486 dedicated-frame Create one new frame, and re-use it each time.
487 new-frame Make a new frame each time. Note that in this case
488 previously-made indirect buffers are kept, and you need to
489 kill these buffers yourself."
490 :group 'org-structure
491 :group 'org-agenda-windows
492 :type '(choice
493 (const :tag "In current window" current-window)
494 (const :tag "In current frame, other window" other-window)
495 (const :tag "Each time a new frame" new-frame)
496 (const :tag "One dedicated frame" dedicated-frame)))
498 (defgroup org-cycle nil
499 "Options concerning visibility cycling in Org-mode."
500 :tag "Org Cycle"
501 :group 'org-structure)
503 (defcustom org-drawers '("PROPERTIES" "CLOCK")
504 "Names of drawers. Drawers are not opened by cycling on the headline above.
505 Drawers only open with a TAB on the drawer line itself. A drawer looks like
506 this:
507 :DRAWERNAME:
508 .....
509 :END:
510 The drawer \"PROPERTIES\" is special for capturing properties through
511 the property API.
513 Drawers can be defined on the per-file basis with a line like:
515 #+DRAWERS: HIDDEN STATE PROPERTIES"
516 :group 'org-structure
517 :type '(repeat (string :tag "Drawer Name")))
519 (defcustom org-cycle-global-at-bob nil
520 "Cycle globally if cursor is at beginning of buffer and not at a headline.
521 This makes it possible to do global cycling without having to use S-TAB or
522 C-u TAB. For this special case to work, the first line of the buffer
523 must not be a headline - it may be empty ot some other text. When used in
524 this way, `org-cycle-hook' is disables temporarily, to make sure the
525 cursor stays at the beginning of the buffer.
526 When this option is nil, don't do anything special at the beginning
527 of the buffer."
528 :group 'org-cycle
529 :type 'boolean)
531 (defcustom org-cycle-emulate-tab t
532 "Where should `org-cycle' emulate TAB.
533 nil Never
534 white Only in completely white lines
535 whitestart Only at the beginning of lines, before the first non-white char
536 t Everywhere except in headlines
537 exc-hl-bol Everywhere except at the start of a headline
538 If TAB is used in a place where it does not emulate TAB, the current subtree
539 visibility is cycled."
540 :group 'org-cycle
541 :type '(choice (const :tag "Never" nil)
542 (const :tag "Only in completely white lines" white)
543 (const :tag "Before first char in a line" whitestart)
544 (const :tag "Everywhere except in headlines" t)
545 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
548 (defcustom org-cycle-separator-lines 2
549 "Number of empty lines needed to keep an empty line between collapsed trees.
550 If you leave an empty line between the end of a subtree and the following
551 headline, this empty line is hidden when the subtree is folded.
552 Org-mode will leave (exactly) one empty line visible if the number of
553 empty lines is equal or larger to the number given in this variable.
554 So the default 2 means, at least 2 empty lines after the end of a subtree
555 are needed to produce free space between a collapsed subtree and the
556 following headline.
558 Special case: when 0, never leave empty lines in collapsed view."
559 :group 'org-cycle
560 :type 'integer)
561 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
563 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
564 org-cycle-hide-drawers
565 org-cycle-show-empty-lines
566 org-optimize-window-after-visibility-change)
567 "Hook that is run after `org-cycle' has changed the buffer visibility.
568 The function(s) in this hook must accept a single argument which indicates
569 the new state that was set by the most recent `org-cycle' command. The
570 argument is a symbol. After a global state change, it can have the values
571 `overview', `content', or `all'. After a local state change, it can have
572 the values `folded', `children', or `subtree'."
573 :group 'org-cycle
574 :type 'hook)
576 (defgroup org-edit-structure nil
577 "Options concerning structure editing in Org-mode."
578 :tag "Org Edit Structure"
579 :group 'org-structure)
581 (defcustom org-odd-levels-only nil
582 "Non-nil means, skip even levels and only use odd levels for the outline.
583 This has the effect that two stars are being added/taken away in
584 promotion/demotion commands. It also influences how levels are
585 handled by the exporters.
586 Changing it requires restart of `font-lock-mode' to become effective
587 for fontification also in regions already fontified.
588 You may also set this on a per-file basis by adding one of the following
589 lines to the buffer:
591 #+STARTUP: odd
592 #+STARTUP: oddeven"
593 :group 'org-edit-structure
594 :group 'org-font-lock
595 :type 'boolean)
597 (defcustom org-adapt-indentation t
598 "Non-nil means, adapt indentation when promoting and demoting.
599 When this is set and the *entire* text in an entry is indented, the
600 indentation is increased by one space in a demotion command, and
601 decreased by one in a promotion command. If any line in the entry
602 body starts at column 0, indentation is not changed at all."
603 :group 'org-edit-structure
604 :type 'boolean)
606 (defcustom org-special-ctrl-a/e nil
607 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
608 When t, `C-a' will bring back the cursor to the beginning of the
609 headline text, i.e. after the stars and after a possible TODO keyword.
610 In an item, this will be the position after the bullet.
611 When the cursor is already at that position, another `C-a' will bring
612 it to the beginning of the line.
613 `C-e' will jump to the end of the headline, ignoring the presence of tags
614 in the headline. A second `C-e' will then jump to the true end of the
615 line, after any tags.
616 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
617 and only a directly following, identical keypress will bring the cursor
618 to the special positions."
619 :group 'org-edit-structure
620 :type '(choice
621 (const :tag "off" nil)
622 (const :tag "after bullet first" t)
623 (const :tag "border first" reversed)))
625 (if (fboundp 'defvaralias)
626 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
628 (defcustom org-special-ctrl-k nil
629 "Non-nil means `C-k' will behave specially in headlines.
630 When nil, `C-k' will call the default `kill-line' command.
631 When t, the following will happen while the cursor is in the headline:
633 - When the cursor is at the beginning of a headline, kill the entire
634 line and possible the folded subtree below the line.
635 - When in the middle of the headline text, kill the headline up to the tags.
636 - When after the headline text, kill the tags."
637 :group 'org-edit-structure
638 :type 'boolean)
640 (defcustom org-yank-folded-subtrees t
641 "Non-nil means, when yanking subtrees, fold them.
642 If the kill is a single subtree, or a sequence of subtrees, i.e. if
643 it starts with a heading and all other headings in it are either children
644 or siblings, then fold all the subtrees. However, do this only if no
645 text after the yank would be swallowed into a folded tree by this action."
646 :group 'org-edit-structure
647 :type 'boolean)
649 (defcustom org-yank-adjusted-subtrees t
650 "Non-nil means, when yanking subtrees, adjust the level.
651 With this setting, `org-paste-subtree' is used to insert the subtree, see
652 this function for details."
653 :group 'org-edit-structure
654 :type 'boolean)
656 (defcustom org-M-RET-may-split-line '((default . t))
657 "Non-nil means, M-RET will split the line at the cursor position.
658 When nil, it will go to the end of the line before making a
659 new line.
660 You may also set this option in a different way for different
661 contexts. Valid contexts are:
663 headline when creating a new headline
664 item when creating a new item
665 table in a table field
666 default the value to be used for all contexts not explicitly
667 customized"
668 :group 'org-structure
669 :group 'org-table
670 :type '(choice
671 (const :tag "Always" t)
672 (const :tag "Never" nil)
673 (repeat :greedy t :tag "Individual contexts"
674 (cons
675 (choice :tag "Context"
676 (const headline)
677 (const item)
678 (const table)
679 (const default))
680 (boolean)))))
683 (defcustom org-insert-heading-respect-content nil
684 "Non-nil means, insert new headings after the current subtree.
685 When nil, the new heading is created directly after the current line.
686 The commands \\[org-insert-heading-respect-content] and
687 \\[org-insert-todo-heading-respect-content] turn this variable on
688 for the duration of the command."
689 :group 'org-structure
690 :type 'boolean)
692 (defcustom org-blank-before-new-entry '((heading . auto)
693 (plain-list-item . auto))
694 "Should `org-insert-heading' leave a blank line before new heading/item?
695 The value is an alist, with `heading' and `plain-list-item' as car,
696 and a boolean flag as cdr."
697 :group 'org-edit-structure
698 :type '(list
699 (cons (const heading)
700 (choice (const :tag "Never" nil)
701 (const :tag "Always" t)
702 (const :tag "Auto" auto)))
703 (cons (const plain-list-item)
704 (choice (const :tag "Never" nil)
705 (const :tag "Always" t)
706 (const :tag "Auto" auto)))))
708 (defcustom org-insert-heading-hook nil
709 "Hook being run after inserting a new heading."
710 :group 'org-edit-structure
711 :type 'hook)
713 (defcustom org-enable-fixed-width-editor t
714 "Non-nil means, lines starting with \":\" are treated as fixed-width.
715 This currently only means, they are never auto-wrapped.
716 When nil, such lines will be treated like ordinary lines.
717 See also the QUOTE keyword."
718 :group 'org-edit-structure
719 :type 'boolean)
721 (defcustom org-edit-src-region-extra nil
722 "Additional regexps to identify regions for editing with `org-edit-src-code'.
723 For examples see the function `org-edit-src-find-region-and-lang'.
724 The regular expression identifying the begin marker should end with a newline,
725 and the regexp marking the end line should start with a newline, to make sure
726 there are kept outside the narrowed region."
727 :group 'org-edit-structure
728 :type '(repeat
729 (list
730 (regexp :tag "begin regexp")
731 (regexp :tag "end regexp")
732 (choice :tag "language"
733 (string :tag "specify")
734 (integer :tag "from match group")
735 (const :tag "from `lang' element")
736 (const :tag "from `style' element")))))
738 (defcustom org-coderef-label-format "(ref:%s)"
739 "The default coderef format.
740 This format string will be used to search for coderef labels in literal
741 examples (EXAMPLE and SRC blocks). The format can be overwritten
742 an individual literal example with the -f option, like
744 #+BEGIN_SRC pascal +n -r -l \"((%s))\"
746 #+END_SRC
748 If you want to use this for HTML export, make sure that the format does
749 not introduce special font-locking, and avoid the HTML special
750 characters `<', `>', and `&'. The reason for this restriction is that
751 the labels are searched for only after htmlize has done its job."
752 :group 'org-edit-structure ; FIXME this is not in the right group
753 :type 'string)
755 (defcustom org-edit-fixed-width-region-mode 'artist-mode
756 "The mode that should be used to edit fixed-width regions.
757 These are the regions where each line starts with a colon."
758 :group 'org-edit-structure
759 :type '(choice
760 (const artist-mode)
761 (const picture-mode)
762 (const fundamental-mode)
763 (function :tag "Other (specify)")))
765 (defcustom org-goto-auto-isearch t
766 "Non-nil means, typing characters in org-goto starts incremental search."
767 :group 'org-edit-structure
768 :type 'boolean)
770 (defgroup org-sparse-trees nil
771 "Options concerning sparse trees in Org-mode."
772 :tag "Org Sparse Trees"
773 :group 'org-structure)
775 (defcustom org-highlight-sparse-tree-matches t
776 "Non-nil means, highlight all matches that define a sparse tree.
777 The highlights will automatically disappear the next time the buffer is
778 changed by an edit command."
779 :group 'org-sparse-trees
780 :type 'boolean)
782 (defcustom org-remove-highlights-with-change t
783 "Non-nil means, any change to the buffer will remove temporary highlights.
784 Such highlights are created by `org-occur' and `org-clock-display'.
785 When nil, `C-c C-c needs to be used to get rid of the highlights.
786 The highlights created by `org-preview-latex-fragment' always need
787 `C-c C-c' to be removed."
788 :group 'org-sparse-trees
789 :group 'org-time
790 :type 'boolean)
793 (defcustom org-occur-hook '(org-first-headline-recenter)
794 "Hook that is run after `org-occur' has constructed a sparse tree.
795 This can be used to recenter the window to show as much of the structure
796 as possible."
797 :group 'org-sparse-trees
798 :type 'hook)
800 (defgroup org-imenu-and-speedbar nil
801 "Options concerning imenu and speedbar in Org-mode."
802 :tag "Org Imenu and Speedbar"
803 :group 'org-structure)
805 (defcustom org-imenu-depth 2
806 "The maximum level for Imenu access to Org-mode headlines.
807 This also applied for speedbar access."
808 :group 'org-imenu-and-speedbar
809 :type 'number)
811 (defgroup org-table nil
812 "Options concerning tables in Org-mode."
813 :tag "Org Table"
814 :group 'org)
816 (defcustom org-enable-table-editor 'optimized
817 "Non-nil means, lines starting with \"|\" are handled by the table editor.
818 When nil, such lines will be treated like ordinary lines.
820 When equal to the symbol `optimized', the table editor will be optimized to
821 do the following:
822 - Automatic overwrite mode in front of whitespace in table fields.
823 This makes the structure of the table stay in tact as long as the edited
824 field does not exceed the column width.
825 - Minimize the number of realigns. Normally, the table is aligned each time
826 TAB or RET are pressed to move to another field. With optimization this
827 happens only if changes to a field might have changed the column width.
828 Optimization requires replacing the functions `self-insert-command',
829 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
830 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
831 very good at guessing when a re-align will be necessary, but you can always
832 force one with \\[org-ctrl-c-ctrl-c].
834 If you would like to use the optimized version in Org-mode, but the
835 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
837 This variable can be used to turn on and off the table editor during a session,
838 but in order to toggle optimization, a restart is required.
840 See also the variable `org-table-auto-blank-field'."
841 :group 'org-table
842 :type '(choice
843 (const :tag "off" nil)
844 (const :tag "on" t)
845 (const :tag "on, optimized" optimized)))
847 (defcustom org-table-tab-recognizes-table.el t
848 "Non-nil means, TAB will automatically notice a table.el table.
849 When it sees such a table, it moves point into it and - if necessary -
850 calls `table-recognize-table'."
851 :group 'org-table-editing
852 :type 'boolean)
854 (defgroup org-link nil
855 "Options concerning links in Org-mode."
856 :tag "Org Link"
857 :group 'org)
859 (defvar org-link-abbrev-alist-local nil
860 "Buffer-local version of `org-link-abbrev-alist', which see.
861 The value of this is taken from the #+LINK lines.")
862 (make-variable-buffer-local 'org-link-abbrev-alist-local)
864 (defcustom org-link-abbrev-alist nil
865 "Alist of link abbreviations.
866 The car of each element is a string, to be replaced at the start of a link.
867 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
868 links in Org-mode buffers can have an optional tag after a double colon, e.g.
870 [[linkkey:tag][description]]
872 If REPLACE is a string, the tag will simply be appended to create the link.
873 If the string contains \"%s\", the tag will be inserted there. Alternatively,
874 the placeholder \"%h\" will cause a url-encoded version of the tag to
875 be inserted at that point (see the function `url-hexify-string').
877 REPLACE may also be a function that will be called with the tag as the
878 only argument to create the link, which should be returned as a string.
880 See the manual for examples."
881 :group 'org-link
882 :type '(repeat
883 (cons
884 (string :tag "Protocol")
885 (choice
886 (string :tag "Format")
887 (function)))))
889 (defcustom org-descriptive-links t
890 "Non-nil means, hide link part and only show description of bracket links.
891 Bracket links are like [[link][description]]. This variable sets the initial
892 state in new org-mode buffers. The setting can then be toggled on a
893 per-buffer basis from the Org->Hyperlinks menu."
894 :group 'org-link
895 :type 'boolean)
897 (defcustom org-link-file-path-type 'adaptive
898 "How the path name in file links should be stored.
899 Valid values are:
901 relative Relative to the current directory, i.e. the directory of the file
902 into which the link is being inserted.
903 absolute Absolute path, if possible with ~ for home directory.
904 noabbrev Absolute path, no abbreviation of home directory.
905 adaptive Use relative path for files in the current directory and sub-
906 directories of it. For other files, use an absolute path."
907 :group 'org-link
908 :type '(choice
909 (const relative)
910 (const absolute)
911 (const noabbrev)
912 (const adaptive)))
914 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
915 "Types of links that should be activated in Org-mode files.
916 This is a list of symbols, each leading to the activation of a certain link
917 type. In principle, it does not hurt to turn on most link types - there may
918 be a small gain when turning off unused link types. The types are:
920 bracket The recommended [[link][description]] or [[link]] links with hiding.
921 angular Links in angular brackets that may contain whitespace like
922 <bbdb:Carsten Dominik>.
923 plain Plain links in normal text, no whitespace, like http://google.com.
924 radio Text that is matched by a radio target, see manual for details.
925 tag Tag settings in a headline (link to tag search).
926 date Time stamps (link to calendar).
927 footnote Footnote labels.
929 Changing this variable requires a restart of Emacs to become effective."
930 :group 'org-link
931 :type '(set :greedy t
932 (const :tag "Double bracket links (new style)" bracket)
933 (const :tag "Angular bracket links (old style)" angular)
934 (const :tag "Plain text links" plain)
935 (const :tag "Radio target matches" radio)
936 (const :tag "Tags" tag)
937 (const :tag "Timestamps" date)
938 (const :tag "Footnotes" footnote)))
940 (defcustom org-make-link-description-function nil
941 "Function to use to generate link descriptions from links. If
942 nil the link location will be used. This function must take two
943 parameters; the first is the link and the second the description
944 org-insert-link has generated, and should return the description
945 to use."
946 :group 'org-link
947 :type 'function)
949 (defgroup org-link-store nil
950 "Options concerning storing links in Org-mode."
951 :tag "Org Store Link"
952 :group 'org-link)
954 (defcustom org-email-link-description-format "Email %c: %.30s"
955 "Format of the description part of a link to an email or usenet message.
956 The following %-escapes will be replaced by corresponding information:
958 %F full \"From\" field
959 %f name, taken from \"From\" field, address if no name
960 %T full \"To\" field
961 %t first name in \"To\" field, address if no name
962 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
963 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
964 %s subject
965 %m message-id.
967 You may use normal field width specification between the % and the letter.
968 This is for example useful to limit the length of the subject.
970 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
971 :group 'org-link-store
972 :type 'string)
974 (defcustom org-from-is-user-regexp
975 (let (r1 r2)
976 (when (and user-mail-address (not (string= user-mail-address "")))
977 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
978 (when (and user-full-name (not (string= user-full-name "")))
979 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
980 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
981 "Regexp matched against the \"From:\" header of an email or usenet message.
982 It should match if the message is from the user him/herself."
983 :group 'org-link-store
984 :type 'regexp)
986 (defcustom org-link-to-org-use-id 'create-if-interactive
987 "Non-nil means, storing a link to an Org file will use entry IDs.
989 Note that before this variable is even considered, org-id must be loaded,
990 to please customize `org-modules' and turn it on.
992 The variable can have the following values:
994 t Create an ID if needed to make a link to the current entry.
996 create-if-interactive
997 If `org-store-link' is called directly (interactively, as a user
998 command), do create an ID to support the link. But when doing the
999 job for remember, only use the ID if it already exists. The
1000 purpose of this setting is to avoid proliferation of unwanted
1001 IDs, just because you happen to be in an Org file when you
1002 call `org-remember' that automatically and preemptively
1003 creates a link. If you do want to get an ID link in a remember
1004 template to an entry not having an ID, create it first by
1005 explicitly creating a link to it, using `C-c C-l' first.
1007 use-existing
1008 Use existing ID, do not create one.
1010 nil Never use an ID to make a link, instead link using a text search for
1011 the headline text."
1012 :group 'org-link-store
1013 :type '(choice
1014 (const :tag "Create ID to make link" t)
1015 (const :tag "Create if string link interactively"
1016 'create-if-interactive)
1017 (const :tag "Only use existing" 'use-existing)
1018 (const :tag "Do not use ID to create link" nil)))
1020 (defcustom org-context-in-file-links t
1021 "Non-nil means, file links from `org-store-link' contain context.
1022 A search string will be added to the file name with :: as separator and
1023 used to find the context when the link is activated by the command
1024 `org-open-at-point'.
1025 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1026 negates this setting for the duration of the command."
1027 :group 'org-link-store
1028 :type 'boolean)
1030 (defcustom org-keep-stored-link-after-insertion nil
1031 "Non-nil means, keep link in list for entire session.
1033 The command `org-store-link' adds a link pointing to the current
1034 location to an internal list. These links accumulate during a session.
1035 The command `org-insert-link' can be used to insert links into any
1036 Org-mode file (offering completion for all stored links). When this
1037 option is nil, every link which has been inserted once using \\[org-insert-link]
1038 will be removed from the list, to make completing the unused links
1039 more efficient."
1040 :group 'org-link-store
1041 :type 'boolean)
1043 (defgroup org-link-follow nil
1044 "Options concerning following links in Org-mode."
1045 :tag "Org Follow Link"
1046 :group 'org-link)
1048 (defcustom org-link-translation-function nil
1049 "Function to translate links with different syntax to Org syntax.
1050 This can be used to translate links created for example by the Planner
1051 or emacs-wiki packages to Org syntax.
1052 The function must accept two parameters, a TYPE containing the link
1053 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1054 which is everything after the link protocol. It should return a cons
1055 with possibly modified values of type and path.
1056 Org contains a function for this, so if you set this variable to
1057 `org-translate-link-from-planner', you should be able follow many
1058 links created by planner."
1059 :group 'org-link-follow
1060 :type 'function)
1062 (defcustom org-follow-link-hook nil
1063 "Hook that is run after a link has been followed."
1064 :group 'org-link-follow
1065 :type 'hook)
1067 (defcustom org-tab-follows-link nil
1068 "Non-nil means, on links TAB will follow the link.
1069 Needs to be set before org.el is loaded."
1070 :group 'org-link-follow
1071 :type 'boolean)
1073 (defcustom org-return-follows-link nil
1074 "Non-nil means, on links RET will follow the link.
1075 Needs to be set before org.el is loaded."
1076 :group 'org-link-follow
1077 :type 'boolean)
1079 (defcustom org-mouse-1-follows-link
1080 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1081 "Non-nil means, mouse-1 on a link will follow the link.
1082 A longer mouse click will still set point. Does not work on XEmacs.
1083 Needs to be set before org.el is loaded."
1084 :group 'org-link-follow
1085 :type 'boolean)
1087 (defcustom org-mark-ring-length 4
1088 "Number of different positions to be recorded in the ring
1089 Changing this requires a restart of Emacs to work correctly."
1090 :group 'org-link-follow
1091 :type 'integer)
1093 (defcustom org-link-frame-setup
1094 '((vm . vm-visit-folder-other-frame)
1095 (gnus . gnus-other-frame)
1096 (file . find-file-other-window))
1097 "Setup the frame configuration for following links.
1098 When following a link with Emacs, it may often be useful to display
1099 this link in another window or frame. This variable can be used to
1100 set this up for the different types of links.
1101 For VM, use any of
1102 `vm-visit-folder'
1103 `vm-visit-folder-other-frame'
1104 For Gnus, use any of
1105 `gnus'
1106 `gnus-other-frame'
1107 `org-gnus-no-new-news'
1108 For FILE, use any of
1109 `find-file'
1110 `find-file-other-window'
1111 `find-file-other-frame'
1112 For the calendar, use the variable `calendar-setup'.
1113 For BBDB, it is currently only possible to display the matches in
1114 another window."
1115 :group 'org-link-follow
1116 :type '(list
1117 (cons (const vm)
1118 (choice
1119 (const vm-visit-folder)
1120 (const vm-visit-folder-other-window)
1121 (const vm-visit-folder-other-frame)))
1122 (cons (const gnus)
1123 (choice
1124 (const gnus)
1125 (const gnus-other-frame)
1126 (const org-gnus-no-new-news)))
1127 (cons (const file)
1128 (choice
1129 (const find-file)
1130 (const find-file-other-window)
1131 (const find-file-other-frame)))))
1133 (defcustom org-display-internal-link-with-indirect-buffer nil
1134 "Non-nil means, use indirect buffer to display infile links.
1135 Activating internal links (from one location in a file to another location
1136 in the same file) normally just jumps to the location. When the link is
1137 activated with a C-u prefix (or with mouse-3), the link is displayed in
1138 another window. When this option is set, the other window actually displays
1139 an indirect buffer clone of the current buffer, to avoid any visibility
1140 changes to the current buffer."
1141 :group 'org-link-follow
1142 :type 'boolean)
1144 (defcustom org-open-non-existing-files nil
1145 "Non-nil means, `org-open-file' will open non-existing files.
1146 When nil, an error will be generated."
1147 :group 'org-link-follow
1148 :type 'boolean)
1150 (defcustom org-open-directory-means-index-dot-org nil
1151 "Non-nil means, a link to a directory really means to index.org.
1152 When nil, following a directory link will run dired or open a finder/explorer
1153 window on that directory."
1154 :group 'org-link-follow
1155 :type 'boolean)
1157 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1158 "Function and arguments to call for following mailto links.
1159 This is a list with the first element being a lisp function, and the
1160 remaining elements being arguments to the function. In string arguments,
1161 %a will be replaced by the address, and %s will be replaced by the subject
1162 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1163 :group 'org-link-follow
1164 :type '(choice
1165 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1166 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1167 (const :tag "message-mail" (message-mail "%a" "%s"))
1168 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1170 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1171 "Non-nil means, ask for confirmation before executing shell links.
1172 Shell links can be dangerous: just think about a link
1174 [[shell:rm -rf ~/*][Google Search]]
1176 This link would show up in your Org-mode document as \"Google Search\",
1177 but really it would remove your entire home directory.
1178 Therefore we advise against setting this variable to nil.
1179 Just change it to `y-or-n-p' of you want to confirm with a
1180 single keystroke rather than having to type \"yes\"."
1181 :group 'org-link-follow
1182 :type '(choice
1183 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1184 (const :tag "with y-or-n (faster)" y-or-n-p)
1185 (const :tag "no confirmation (dangerous)" nil)))
1187 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1188 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1189 Elisp links can be dangerous: just think about a link
1191 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1193 This link would show up in your Org-mode document as \"Google Search\",
1194 but really it would remove your entire home directory.
1195 Therefore we advise against setting this variable to nil.
1196 Just change it to `y-or-n-p' of you want to confirm with a
1197 single keystroke rather than having to type \"yes\"."
1198 :group 'org-link-follow
1199 :type '(choice
1200 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1201 (const :tag "with y-or-n (faster)" y-or-n-p)
1202 (const :tag "no confirmation (dangerous)" nil)))
1204 (defconst org-file-apps-defaults-gnu
1205 '((remote . emacs)
1206 (system . mailcap)
1207 (t . mailcap))
1208 "Default file applications on a UNIX or GNU/Linux system.
1209 See `org-file-apps'.")
1211 (defconst org-file-apps-defaults-macosx
1212 '((remote . emacs)
1213 (t . "open %s")
1214 (system . "open %s")
1215 ("ps.gz" . "gv %s")
1216 ("eps.gz" . "gv %s")
1217 ("dvi" . "xdvi %s")
1218 ("fig" . "xfig %s"))
1219 "Default file applications on a MacOS X system.
1220 The system \"open\" is known as a default, but we use X11 applications
1221 for some files for which the OS does not have a good default.
1222 See `org-file-apps'.")
1224 (defconst org-file-apps-defaults-windowsnt
1225 (list
1226 '(remote . emacs)
1227 (cons t
1228 (list (if (featurep 'xemacs)
1229 'mswindows-shell-execute
1230 'w32-shell-execute)
1231 "open" 'file))
1232 (cons 'system
1233 (list (if (featurep 'xemacs)
1234 'mswindows-shell-execute
1235 'w32-shell-execute)
1236 "open" 'file)))
1237 "Default file applications on a Windows NT system.
1238 The system \"open\" is used for most files.
1239 See `org-file-apps'.")
1241 (defcustom org-file-apps
1243 (auto-mode . emacs)
1244 ("\\.x?html?\\'" . default)
1245 ("\\.pdf\\'" . default)
1247 "External applications for opening `file:path' items in a document.
1248 Org-mode uses system defaults for different file types, but
1249 you can use this variable to set the application for a given file
1250 extension. The entries in this list are cons cells where the car identifies
1251 files and the cdr the corresponding command. Possible values for the
1252 file identifier are
1253 \"regex\" Regular expression matched against the file name. For backward
1254 compatibility, this can also be a string with only alphanumeric
1255 characters, which is then interpreted as an extension.
1256 `directory' Matches a directory
1257 `remote' Matches a remote file, accessible through tramp or efs.
1258 Remote files most likely should be visited through Emacs
1259 because external applications cannot handle such paths.
1260 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1261 so all files Emacs knows how to handle. Using this with
1262 command `emacs' will open most files in Emacs. Beware that this
1263 will also open html files inside Emacs, unless you add
1264 (\"html\" . default) to the list as well.
1265 t Default for files not matched by any of the other options.
1266 `system' The system command to open files, like `open' on Windows
1267 and Mac OS X, and mailcap under GNU/Linux. This is the command
1268 that will be selected if you call `C-c C-o' with a double
1269 `C-u C-u' prefix.
1271 Possible values for the command are:
1272 `emacs' The file will be visited by the current Emacs process.
1273 `default' Use the default application for this file type, which is the
1274 association for t in the list, most likely in the system-specific
1275 part.
1276 This can be used to overrule an unwanted setting in the
1277 system-specific variable.
1278 `system' Use the system command for opening files, like \"open\".
1279 This command is specified by the entry whose car is `system'.
1280 Most likely, the system-specific version of this variable
1281 does define this command, but you can overrule/replace it
1282 here.
1283 string A command to be executed by a shell; %s will be replaced
1284 by the path to the file.
1285 sexp A Lisp form which will be evaluated. The file path will
1286 be available in the Lisp variable `file'.
1287 For more examples, see the system specific constants
1288 `org-file-apps-defaults-macosx'
1289 `org-file-apps-defaults-windowsnt'
1290 `org-file-apps-defaults-gnu'."
1291 :group 'org-link-follow
1292 :type '(repeat
1293 (cons (choice :value ""
1294 (string :tag "Extension")
1295 (const :tag "System command to open files" system)
1296 (const :tag "Default for unrecognized files" t)
1297 (const :tag "Remote file" remote)
1298 (const :tag "Links to a directory" directory)
1299 (const :tag "Any files that have Emacs modes"
1300 auto-mode))
1301 (choice :value ""
1302 (const :tag "Visit with Emacs" emacs)
1303 (const :tag "Use default" default)
1304 (const :tag "Use the system command" system)
1305 (string :tag "Command")
1306 (sexp :tag "Lisp form")))))
1308 (defgroup org-refile nil
1309 "Options concerning refiling entries in Org-mode."
1310 :tag "Org Refile"
1311 :group 'org)
1313 (defcustom org-directory "~/org"
1314 "Directory with org files.
1315 This directory will be used as default to prompt for org files.
1316 Used by the hooks for remember.el."
1317 :group 'org-refile
1318 :group 'org-remember
1319 :type 'directory)
1321 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1322 "Default target for storing notes.
1323 Used by the hooks for remember.el. This can be a string, or nil to mean
1324 the value of `remember-data-file'.
1325 You can set this on a per-template basis with the variable
1326 `org-remember-templates'."
1327 :group 'org-refile
1328 :group 'org-remember
1329 :type '(choice
1330 (const :tag "Default from remember-data-file" nil)
1331 file))
1333 (defcustom org-goto-interface 'outline
1334 "The default interface to be used for `org-goto'.
1335 Allowed values are:
1336 outline The interface shows an outline of the relevant file
1337 and the correct heading is found by moving through
1338 the outline or by searching with incremental search.
1339 outline-path-completion Headlines in the current buffer are offered via
1340 completion. This is the interface also used by
1341 the refile command."
1342 :group 'org-refile
1343 :type '(choice
1344 (const :tag "Outline" outline)
1345 (const :tag "Outline-path-completion" outline-path-completion)))
1347 (defcustom org-goto-max-level 5
1348 "Maximum level to be considered when running org-goto with refile interface."
1349 :group 'org-refile
1350 :type 'number)
1352 (defcustom org-reverse-note-order nil
1353 "Non-nil means, store new notes at the beginning of a file or entry.
1354 When nil, new notes will be filed to the end of a file or entry.
1355 This can also be a list with cons cells of regular expressions that
1356 are matched against file names, and values."
1357 :group 'org-remember
1358 :group 'org-refile
1359 :type '(choice
1360 (const :tag "Reverse always" t)
1361 (const :tag "Reverse never" nil)
1362 (repeat :tag "By file name regexp"
1363 (cons regexp boolean))))
1365 (defcustom org-refile-targets nil
1366 "Targets for refiling entries with \\[org-refile].
1367 This is list of cons cells. Each cell contains:
1368 - a specification of the files to be considered, either a list of files,
1369 or a symbol whose function or variable value will be used to retrieve
1370 a file name or a list of file names. If you use `org-agenda-files' for
1371 that, all agenda files will be scanned for targets. Nil means, consider
1372 headings in the current buffer.
1373 - A specification of how to select find candidate refile targets. This
1374 may be any of
1375 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1376 This tag has to be present in all target headlines, inheritance will
1377 not be considered.
1378 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1379 todo keyword.
1380 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1381 headlines that are refiling targets.
1382 - a cons cell (:level . N). Any headline of level N is considered a target.
1383 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1385 When this variable is nil, all top-level headlines in the current buffer
1386 are used, equivalent to the value `((nil . (:level . 1))'."
1387 :group 'org-refile
1388 :type '(repeat
1389 (cons
1390 (choice :value org-agenda-files
1391 (const :tag "All agenda files" org-agenda-files)
1392 (const :tag "Current buffer" nil)
1393 (function) (variable) (file))
1394 (choice :tag "Identify target headline by"
1395 (cons :tag "Specific tag" (const :value :tag) (string))
1396 (cons :tag "TODO keyword" (const :value :todo) (string))
1397 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1398 (cons :tag "Level number" (const :value :level) (integer))
1399 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1401 (defcustom org-refile-use-outline-path nil
1402 "Non-nil means, provide refile targets as paths.
1403 So a level 3 headline will be available as level1/level2/level3.
1404 When the value is `file', also include the file name (without directory)
1405 into the path. When `full-file-path', include the full file path."
1406 :group 'org-refile
1407 :type '(choice
1408 (const :tag "Not" nil)
1409 (const :tag "Yes" t)
1410 (const :tag "Start with file name" file)
1411 (const :tag "Start with full file path" full-file-path)))
1413 (defcustom org-outline-path-complete-in-steps t
1414 "Non-nil means, complete the outline path in hierarchical steps.
1415 When Org-mode uses the refile interface to select an outline path
1416 \(see variable `org-refile-use-outline-path'), the completion of
1417 the path can be done is a single go, or if can be done in steps down
1418 the headline hierarchy. Going in steps is probably the best if you
1419 do not use a special completion package like `ido' or `icicles'.
1420 However, when using these packages, going in one step can be very
1421 fast, while still showing the whole path to the entry."
1422 :group 'org-refile
1423 :type 'boolean)
1425 (defgroup org-todo nil
1426 "Options concerning TODO items in Org-mode."
1427 :tag "Org TODO"
1428 :group 'org)
1430 (defgroup org-progress nil
1431 "Options concerning Progress logging in Org-mode."
1432 :tag "Org Progress"
1433 :group 'org-time)
1435 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1436 "List of TODO entry keyword sequences and their interpretation.
1437 \\<org-mode-map>This is a list of sequences.
1439 Each sequence starts with a symbol, either `sequence' or `type',
1440 indicating if the keywords should be interpreted as a sequence of
1441 action steps, or as different types of TODO items. The first
1442 keywords are states requiring action - these states will select a headline
1443 for inclusion into the global TODO list Org-mode produces. If one of
1444 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1445 signify that no further action is necessary. If \"|\" is not found,
1446 the last keyword is treated as the only DONE state of the sequence.
1448 The command \\[org-todo] cycles an entry through these states, and one
1449 additional state where no keyword is present. For details about this
1450 cycling, see the manual.
1452 TODO keywords and interpretation can also be set on a per-file basis with
1453 the special #+SEQ_TODO and #+TYP_TODO lines.
1455 Each keyword can optionally specify a character for fast state selection
1456 \(in combination with the variable `org-use-fast-todo-selection')
1457 and specifiers for state change logging, using the same syntax
1458 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1459 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1460 indicates to record a time stamp each time this state is selected.
1462 Each keyword may also specify if a timestamp or a note should be
1463 recorded when entering or leaving the state, by adding additional
1464 characters in the parenthesis after the keyword. This looks like this:
1465 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1466 record only the time of the state change. With X and Y being either
1467 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1468 Y when leaving the state if and only if the *target* state does not
1469 define X. You may omit any of the fast-selection key or X or /Y,
1470 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1472 For backward compatibility, this variable may also be just a list
1473 of keywords - in this case the interpretation (sequence or type) will be
1474 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1475 :group 'org-todo
1476 :group 'org-keywords
1477 :type '(choice
1478 (repeat :tag "Old syntax, just keywords"
1479 (string :tag "Keyword"))
1480 (repeat :tag "New syntax"
1481 (cons
1482 (choice
1483 :tag "Interpretation"
1484 (const :tag "Sequence (cycling hits every state)" sequence)
1485 (const :tag "Type (cycling directly to DONE)" type))
1486 (repeat
1487 (string :tag "Keyword"))))))
1489 (defvar org-todo-keywords-1 nil
1490 "All TODO and DONE keywords active in a buffer.")
1491 (make-variable-buffer-local 'org-todo-keywords-1)
1492 (defvar org-todo-keywords-for-agenda nil)
1493 (defvar org-done-keywords-for-agenda nil)
1494 (defvar org-todo-keyword-alist-for-agenda nil)
1495 (defvar org-tag-alist-for-agenda nil)
1496 (defvar org-agenda-contributing-files nil)
1497 (defvar org-not-done-keywords nil)
1498 (make-variable-buffer-local 'org-not-done-keywords)
1499 (defvar org-done-keywords nil)
1500 (make-variable-buffer-local 'org-done-keywords)
1501 (defvar org-todo-heads nil)
1502 (make-variable-buffer-local 'org-todo-heads)
1503 (defvar org-todo-sets nil)
1504 (make-variable-buffer-local 'org-todo-sets)
1505 (defvar org-todo-log-states nil)
1506 (make-variable-buffer-local 'org-todo-log-states)
1507 (defvar org-todo-kwd-alist nil)
1508 (make-variable-buffer-local 'org-todo-kwd-alist)
1509 (defvar org-todo-key-alist nil)
1510 (make-variable-buffer-local 'org-todo-key-alist)
1511 (defvar org-todo-key-trigger nil)
1512 (make-variable-buffer-local 'org-todo-key-trigger)
1514 (defcustom org-todo-interpretation 'sequence
1515 "Controls how TODO keywords are interpreted.
1516 This variable is in principle obsolete and is only used for
1517 backward compatibility, if the interpretation of todo keywords is
1518 not given already in `org-todo-keywords'. See that variable for
1519 more information."
1520 :group 'org-todo
1521 :group 'org-keywords
1522 :type '(choice (const sequence)
1523 (const type)))
1525 (defcustom org-use-fast-todo-selection 'prefix
1526 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1527 This variable describes if and under what circumstances the cycling
1528 mechanism for TODO keywords will be replaced by a single-key, direct
1529 selection scheme.
1531 When nil, fast selection is never used.
1533 When the symbol `prefix', it will be used when `org-todo' is called with
1534 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1535 in an agenda buffer.
1537 When t, fast selection is used by default. In this case, the prefix
1538 argument forces cycling instead.
1540 In all cases, the special interface is only used if access keys have actually
1541 been assigned by the user, i.e. if keywords in the configuration are followed
1542 by a letter in parenthesis, like TODO(t)."
1543 :group 'org-todo
1544 :type '(choice
1545 (const :tag "Never" nil)
1546 (const :tag "By default" t)
1547 (const :tag "Only with C-u C-c C-t" prefix)))
1549 (defcustom org-provide-todo-statistics t
1550 "Non-nil means, update todo statistics after insert and toggle.
1551 When this is set, todo statistics is updated in the parent of the current
1552 entry each time a todo state is changed."
1553 :group 'org-todo
1554 :type 'boolean)
1556 (defcustom org-after-todo-state-change-hook nil
1557 "Hook which is run after the state of a TODO item was changed.
1558 The new state (a string with a TODO keyword, or nil) is available in the
1559 Lisp variable `state'."
1560 :group 'org-todo
1561 :type 'hook)
1563 (defcustom org-todo-state-tags-triggers nil
1564 "Tag changes that should be triggered by TODO state changes.
1565 This is a list. Each entry is
1567 (state-change (tag . flag) .......)
1569 State-change can be a string with a state, and empty string to indicate the
1570 state that has no TODO keyword, or it can be one of the symbols `todo'
1571 or `done', meaning any not-done or done state, respectively."
1572 :group 'org-todo
1573 :group 'org-tags
1574 :type '(repeat
1575 (cons (choice :tag "When changing to"
1576 (const :tag "Not-done state" todo)
1577 (const :tag "Done state" done)
1578 (string :tag "State"))
1579 (repeat
1580 (cons :tag "Tag action"
1581 (string :tag "Tag")
1582 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1584 (defcustom org-log-done nil
1585 "Information to record when a task moves to the DONE state.
1587 Possible values are:
1589 nil Don't add anything, just change the keyword
1590 time Add a time stamp to the task
1591 note Prompt a closing note and add it with template `org-log-note-headings'
1593 This option can also be set with on a per-file-basis with
1595 #+STARTUP: nologdone
1596 #+STARTUP: logdone
1597 #+STARTUP: lognotedone
1599 You can have local logging settings for a subtree by setting the LOGGING
1600 property to one or more of these keywords."
1601 :group 'org-todo
1602 :group 'org-progress
1603 :type '(choice
1604 (const :tag "No logging" nil)
1605 (const :tag "Record CLOSED timestamp" time)
1606 (const :tag "Record CLOSED timestamp with closing note." note)))
1608 ;; Normalize old uses of org-log-done.
1609 (cond
1610 ((eq org-log-done t) (setq org-log-done 'time))
1611 ((and (listp org-log-done) (memq 'done org-log-done))
1612 (setq org-log-done 'note)))
1614 (defcustom org-log-note-clock-out nil
1615 "Non-nil means, record a note when clocking out of an item.
1616 This can also be configured on a per-file basis by adding one of
1617 the following lines anywhere in the buffer:
1619 #+STARTUP: lognoteclock-out
1620 #+STARTUP: nolognoteclock-out"
1621 :group 'org-todo
1622 :group 'org-progress
1623 :type 'boolean)
1625 (defcustom org-log-done-with-time t
1626 "Non-nil means, the CLOSED time stamp will contain date and time.
1627 When nil, only the date will be recorded."
1628 :group 'org-progress
1629 :type 'boolean)
1631 (defcustom org-log-note-headings
1632 '((done . "CLOSING NOTE %t")
1633 (state . "State %-12s %t")
1634 (note . "Note taken on %t")
1635 (clock-out . ""))
1636 "Headings for notes added to entries.
1637 The value is an alist, with the car being a symbol indicating the note
1638 context, and the cdr is the heading to be used. The heading may also be the
1639 empty string.
1640 %t in the heading will be replaced by a time stamp.
1641 %s will be replaced by the new TODO state, in double quotes.
1642 %u will be replaced by the user name.
1643 %U will be replaced by the full user name."
1644 :group 'org-todo
1645 :group 'org-progress
1646 :type '(list :greedy t
1647 (cons (const :tag "Heading when closing an item" done) string)
1648 (cons (const :tag
1649 "Heading when changing todo state (todo sequence only)"
1650 state) string)
1651 (cons (const :tag "Heading when just taking a note" note) string)
1652 (cons (const :tag "Heading when clocking out" clock-out) string)))
1654 (unless (assq 'note org-log-note-headings)
1655 (push '(note . "%t") org-log-note-headings))
1657 (defcustom org-log-state-notes-insert-after-drawers nil
1658 "Non-nil means, insert state change notes after any drawers in entry.
1659 Only the drawers that *immediately* follow the headline and the
1660 deadline/scheduled line are skipped.
1661 When nil, insert notes right after the heading and perhaps the line
1662 with deadline/scheduling if present."
1663 :group 'org-todo
1664 :group 'org-progress
1665 :type 'boolean)
1667 (defcustom org-log-states-order-reversed t
1668 "Non-nil means, the latest state change note will be directly after heading.
1669 When nil, the notes will be orderer according to time."
1670 :group 'org-todo
1671 :group 'org-progress
1672 :type 'boolean)
1674 (defcustom org-log-repeat 'time
1675 "Non-nil means, record moving through the DONE state when triggering repeat.
1676 An auto-repeating tasks is immediately switched back to TODO when marked
1677 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1678 the TODO keyword definition, or recording a closing note by setting
1679 `org-log-done', there will be no record of the task moving through DONE.
1680 This variable forces taking a note anyway. Possible values are:
1682 nil Don't force a record
1683 time Record a time stamp
1684 note Record a note
1686 This option can also be set with on a per-file-basis with
1688 #+STARTUP: logrepeat
1689 #+STARTUP: lognoterepeat
1690 #+STARTUP: nologrepeat
1692 You can have local logging settings for a subtree by setting the LOGGING
1693 property to one or more of these keywords."
1694 :group 'org-todo
1695 :group 'org-progress
1696 :type '(choice
1697 (const :tag "Don't force a record" nil)
1698 (const :tag "Force recording the DONE state" time)
1699 (const :tag "Force recording a note with the DONE state" note)))
1702 (defgroup org-priorities nil
1703 "Priorities in Org-mode."
1704 :tag "Org Priorities"
1705 :group 'org-todo)
1707 (defcustom org-highest-priority ?A
1708 "The highest priority of TODO items. A character like ?A, ?B etc.
1709 Must have a smaller ASCII number than `org-lowest-priority'."
1710 :group 'org-priorities
1711 :type 'character)
1713 (defcustom org-lowest-priority ?C
1714 "The lowest priority of TODO items. A character like ?A, ?B etc.
1715 Must have a larger ASCII number than `org-highest-priority'."
1716 :group 'org-priorities
1717 :type 'character)
1719 (defcustom org-default-priority ?B
1720 "The default priority of TODO items.
1721 This is the priority an item get if no explicit priority is given."
1722 :group 'org-priorities
1723 :type 'character)
1725 (defcustom org-priority-start-cycle-with-default t
1726 "Non-nil means, start with default priority when starting to cycle.
1727 When this is nil, the first step in the cycle will be (depending on the
1728 command used) one higher or lower that the default priority."
1729 :group 'org-priorities
1730 :type 'boolean)
1732 (defgroup org-time nil
1733 "Options concerning time stamps and deadlines in Org-mode."
1734 :tag "Org Time"
1735 :group 'org)
1737 (defcustom org-insert-labeled-timestamps-at-point nil
1738 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1739 When nil, these labeled time stamps are forces into the second line of an
1740 entry, just after the headline. When scheduling from the global TODO list,
1741 the time stamp will always be forced into the second line."
1742 :group 'org-time
1743 :type 'boolean)
1745 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1746 "Formats for `format-time-string' which are used for time stamps.
1747 It is not recommended to change this constant.")
1749 (defcustom org-time-stamp-rounding-minutes '(0 5)
1750 "Number of minutes to round time stamps to.
1751 These are two values, the first applies when first creating a time stamp.
1752 The second applies when changing it with the commands `S-up' and `S-down'.
1753 When changing the time stamp, this means that it will change in steps
1754 of N minutes, as given by the second value.
1756 When a setting is 0 or 1, insert the time unmodified. Useful rounding
1757 numbers should be factors of 60, so for example 5, 10, 15.
1759 When this is larger than 1, you can still force an exact time-stamp by using
1760 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
1761 and by using a prefix arg to `S-up/down' to specify the exact number
1762 of minutes to shift."
1763 :group 'org-time
1764 :get '(lambda (var) ; Make sure all entries have 5 elements
1765 (if (integerp (default-value var))
1766 (list (default-value var) 5)
1767 (default-value var)))
1768 :type '(list
1769 (integer :tag "when inserting times")
1770 (integer :tag "when modifying times")))
1772 ;; Normalize old customizations of this variable.
1773 (when (integerp org-time-stamp-rounding-minutes)
1774 (setq org-time-stamp-rounding-minutes
1775 (list org-time-stamp-rounding-minutes
1776 org-time-stamp-rounding-minutes)))
1778 (defcustom org-display-custom-times nil
1779 "Non-nil means, overlay custom formats over all time stamps.
1780 The formats are defined through the variable `org-time-stamp-custom-formats'.
1781 To turn this on on a per-file basis, insert anywhere in the file:
1782 #+STARTUP: customtime"
1783 :group 'org-time
1784 :set 'set-default
1785 :type 'sexp)
1786 (make-variable-buffer-local 'org-display-custom-times)
1788 (defcustom org-time-stamp-custom-formats
1789 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1790 "Custom formats for time stamps. See `format-time-string' for the syntax.
1791 These are overlayed over the default ISO format if the variable
1792 `org-display-custom-times' is set. Time like %H:%M should be at the
1793 end of the second format."
1794 :group 'org-time
1795 :type 'sexp)
1797 (defun org-time-stamp-format (&optional long inactive)
1798 "Get the right format for a time string."
1799 (let ((f (if long (cdr org-time-stamp-formats)
1800 (car org-time-stamp-formats))))
1801 (if inactive
1802 (concat "[" (substring f 1 -1) "]")
1803 f)))
1805 (defcustom org-time-clocksum-format "%d:%02d"
1806 "The format string used when creating CLOCKSUM lines, or when
1807 org-mode generates a time duration."
1808 :group 'org-time
1809 :type 'string)
1811 (defcustom org-deadline-warning-days 14
1812 "No. of days before expiration during which a deadline becomes active.
1813 This variable governs the display in sparse trees and in the agenda.
1814 When 0 or negative, it means use this number (the absolute value of it)
1815 even if a deadline has a different individual lead time specified."
1816 :group 'org-time
1817 :group 'org-agenda-daily/weekly
1818 :type 'number)
1820 (defcustom org-read-date-prefer-future t
1821 "Non-nil means, assume future for incomplete date input from user.
1822 This affects the following situations:
1823 1. The user gives a day, but no month.
1824 For example, if today is the 15th, and you enter \"3\", Org-mode will
1825 read this as the third of *next* month. However, if you enter \"17\",
1826 it will be considered as *this* month.
1827 2. The user gives a month but not a year.
1828 For example, if it is april and you enter \"feb 2\", this will be read
1829 as feb 2, *next* year. \"May 5\", however, will be this year.
1831 Currently this does not work for ISO week specifications.
1833 When this option is nil, the current month and year will always be used
1834 as defaults."
1835 :group 'org-time
1836 :type 'boolean)
1838 (defcustom org-read-date-display-live t
1839 "Non-nil means, display current interpretation of date prompt live.
1840 This display will be in an overlay, in the minibuffer."
1841 :group 'org-time
1842 :type 'boolean)
1844 (defcustom org-read-date-popup-calendar t
1845 "Non-nil means, pop up a calendar when prompting for a date.
1846 In the calendar, the date can be selected with mouse-1. However, the
1847 minibuffer will also be active, and you can simply enter the date as well.
1848 When nil, only the minibuffer will be available."
1849 :group 'org-time
1850 :type 'boolean)
1851 (if (fboundp 'defvaralias)
1852 (defvaralias 'org-popup-calendar-for-date-prompt
1853 'org-read-date-popup-calendar))
1855 (defcustom org-extend-today-until 0
1856 "The hour when your day really ends. Must be an integer.
1857 This has influence for the following applications:
1858 - When switching the agenda to \"today\". It it is still earlier than
1859 the time given here, the day recognized as TODAY is actually yesterday.
1860 - When a date is read from the user and it is still before the time given
1861 here, the current date and time will be assumed to be yesterday, 23:59.
1862 Also, timestamps inserted in remember templates follow this rule.
1864 IMPORTANT: This is a feature whose implementation is and likely will
1865 remain incomplete. Really, it is only here because past midnight seems to
1866 be the favorite working time of John Wiegley :-)"
1867 :group 'org-time
1868 :type 'number)
1870 (defcustom org-edit-timestamp-down-means-later nil
1871 "Non-nil means, S-down will increase the time in a time stamp.
1872 When nil, S-up will increase."
1873 :group 'org-time
1874 :type 'boolean)
1876 (defcustom org-calendar-follow-timestamp-change t
1877 "Non-nil means, make the calendar window follow timestamp changes.
1878 When a timestamp is modified and the calendar window is visible, it will be
1879 moved to the new date."
1880 :group 'org-time
1881 :type 'boolean)
1883 (defgroup org-tags nil
1884 "Options concerning tags in Org-mode."
1885 :tag "Org Tags"
1886 :group 'org)
1888 (defcustom org-tag-alist nil
1889 "List of tags allowed in Org-mode files.
1890 When this list is nil, Org-mode will base TAG input on what is already in the
1891 buffer.
1892 The value of this variable is an alist, the car of each entry must be a
1893 keyword as a string, the cdr may be a character that is used to select
1894 that tag through the fast-tag-selection interface.
1895 See the manual for details."
1896 :group 'org-tags
1897 :type '(repeat
1898 (choice
1899 (cons (string :tag "Tag name")
1900 (character :tag "Access char"))
1901 (const :tag "Start radio group" (:startgroup))
1902 (const :tag "End radio group" (:endgroup)))))
1904 (defvar org-file-tags nil
1905 "List of tags that can be inherited by all entries in the file.
1906 The tags will be inherited if the variable `org-use-tag-inheritance'
1907 says they should be.
1908 This variable is populated from #+TAG lines.")
1910 (defcustom org-use-fast-tag-selection 'auto
1911 "Non-nil means, use fast tag selection scheme.
1912 This is a special interface to select and deselect tags with single keys.
1913 When nil, fast selection is never used.
1914 When the symbol `auto', fast selection is used if and only if selection
1915 characters for tags have been configured, either through the variable
1916 `org-tag-alist' or through a #+TAGS line in the buffer.
1917 When t, fast selection is always used and selection keys are assigned
1918 automatically if necessary."
1919 :group 'org-tags
1920 :type '(choice
1921 (const :tag "Always" t)
1922 (const :tag "Never" nil)
1923 (const :tag "When selection characters are configured" 'auto)))
1925 (defcustom org-fast-tag-selection-single-key nil
1926 "Non-nil means, fast tag selection exits after first change.
1927 When nil, you have to press RET to exit it.
1928 During fast tag selection, you can toggle this flag with `C-c'.
1929 This variable can also have the value `expert'. In this case, the window
1930 displaying the tags menu is not even shown, until you press C-c again."
1931 :group 'org-tags
1932 :type '(choice
1933 (const :tag "No" nil)
1934 (const :tag "Yes" t)
1935 (const :tag "Expert" expert)))
1937 (defvar org-fast-tag-selection-include-todo nil
1938 "Non-nil means, fast tags selection interface will also offer TODO states.
1939 This is an undocumented feature, you should not rely on it.")
1941 (defcustom org-tags-column (if (featurep 'xemacs) -79 -80)
1942 "The column to which tags should be indented in a headline.
1943 If this number is positive, it specifies the column. If it is negative,
1944 it means that the tags should be flushright to that column. For example,
1945 -80 works well for a normal 80 character screen."
1946 :group 'org-tags
1947 :type 'integer)
1949 (defcustom org-auto-align-tags t
1950 "Non-nil means, realign tags after pro/demotion of TODO state change.
1951 These operations change the length of a headline and therefore shift
1952 the tags around. With this options turned on, after each such operation
1953 the tags are again aligned to `org-tags-column'."
1954 :group 'org-tags
1955 :type 'boolean)
1957 (defcustom org-use-tag-inheritance t
1958 "Non-nil means, tags in levels apply also for sublevels.
1959 When nil, only the tags directly given in a specific line apply there.
1960 This may also be a list of tags that should be inherited, or a regexp that
1961 matches tags that should be inherited. Additional control is possible
1962 with the variable `org-tags-exclude-from-inheritance' which gives an
1963 explicit list of tags to be excluded from inheritance., even if the value of
1964 `org-use-tag-inheritance' would select it for inheritance.
1966 If this option is t, a match early-on in a tree can lead to a large
1967 number of matches in the subtree when constructing the agenda or creating
1968 a sparse tree. If you only want to see the first match in a tree during
1969 a search, check out the variable `org-tags-match-list-sublevels'."
1970 :group 'org-tags
1971 :type '(choice
1972 (const :tag "Not" nil)
1973 (const :tag "Always" t)
1974 (repeat :tag "Specific tags" (string :tag "Tag"))
1975 (regexp :tag "Tags matched by regexp")))
1977 (defcustom org-tags-exclude-from-inheritance nil
1978 "List of tags that should never be inherited.
1979 This is a way to exclude a few tags from inheritance. For way to do
1980 the opposite, to actively allow inheritance for selected tags,
1981 see the variable `org-use-tag-inheritance'."
1982 :group 'org-tags
1983 :type '(repeat (string :tag "Tag")))
1985 (defun org-tag-inherit-p (tag)
1986 "Check if TAG is one that should be inherited."
1987 (cond
1988 ((member tag org-tags-exclude-from-inheritance) nil)
1989 ((eq org-use-tag-inheritance t) t)
1990 ((not org-use-tag-inheritance) nil)
1991 ((stringp org-use-tag-inheritance)
1992 (string-match org-use-tag-inheritance tag))
1993 ((listp org-use-tag-inheritance)
1994 (member tag org-use-tag-inheritance))
1995 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
1997 (defcustom org-tags-match-list-sublevels t
1998 "Non-nil means list also sublevels of headlines matching tag search.
1999 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2000 the sublevels of a headline matching a tag search often also match
2001 the same search. Listing all of them can create very long lists.
2002 Setting this variable to nil causes subtrees of a match to be skipped.
2003 This option is off by default, because inheritance in on. If you turn
2004 inheritance off, you very likely want to turn this option on.
2006 As a special case, if the tag search is restricted to TODO items, the
2007 value of this variable is ignored and sublevels are always checked, to
2008 make sure all corresponding TODO items find their way into the list.
2010 This variable is semi-obsolete and probably should always be true. It
2011 is better to limit inheritance to certain tags using the variables
2012 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2013 :group 'org-tags
2014 :type 'boolean)
2016 (defvar org-tags-history nil
2017 "History of minibuffer reads for tags.")
2018 (defvar org-last-tags-completion-table nil
2019 "The last used completion table for tags.")
2020 (defvar org-after-tags-change-hook nil
2021 "Hook that is run after the tags in a line have changed.")
2023 (defgroup org-properties nil
2024 "Options concerning properties in Org-mode."
2025 :tag "Org Properties"
2026 :group 'org)
2028 (defcustom org-property-format "%-10s %s"
2029 "How property key/value pairs should be formatted by `indent-line'.
2030 When `indent-line' hits a property definition, it will format the line
2031 according to this format, mainly to make sure that the values are
2032 lined-up with respect to each other."
2033 :group 'org-properties
2034 :type 'string)
2036 (defcustom org-use-property-inheritance nil
2037 "Non-nil means, properties apply also for sublevels.
2039 This setting is chiefly used during property searches. Turning it on can
2040 cause significant overhead when doing a search, which is why it is not
2041 on by default.
2043 When nil, only the properties directly given in the current entry count.
2044 When t, every property is inherited. The value may also be a list of
2045 properties that should have inheritance, or a regular expression matching
2046 properties that should be inherited.
2048 However, note that some special properties use inheritance under special
2049 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2050 and the properties ending in \"_ALL\" when they are used as descriptor
2051 for valid values of a property.
2053 Note for programmers:
2054 When querying an entry with `org-entry-get', you can control if inheritance
2055 should be used. By default, `org-entry-get' looks only at the local
2056 properties. You can request inheritance by setting the inherit argument
2057 to t (to force inheritance) or to `selective' (to respect the setting
2058 in this variable)."
2059 :group 'org-properties
2060 :type '(choice
2061 (const :tag "Not" nil)
2062 (const :tag "Always" t)
2063 (repeat :tag "Specific properties" (string :tag "Property"))
2064 (regexp :tag "Properties matched by regexp")))
2066 (defun org-property-inherit-p (property)
2067 "Check if PROPERTY is one that should be inherited."
2068 (cond
2069 ((eq org-use-property-inheritance t) t)
2070 ((not org-use-property-inheritance) nil)
2071 ((stringp org-use-property-inheritance)
2072 (string-match org-use-property-inheritance property))
2073 ((listp org-use-property-inheritance)
2074 (member property org-use-property-inheritance))
2075 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2077 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2078 "The default column format, if no other format has been defined.
2079 This variable can be set on the per-file basis by inserting a line
2081 #+COLUMNS: %25ITEM ....."
2082 :group 'org-properties
2083 :type 'string)
2085 (defcustom org-columns-ellipses ".."
2086 "The ellipses to be used when a field in column view is truncated.
2087 When this is the empty string, as many characters as possible are shown,
2088 but then there will be no visual indication that the field has been truncated.
2089 When this is a string of length N, the last N characters of a truncated
2090 field are replaced by this string. If the column is narrower than the
2091 ellipses string, only part of the ellipses string will be shown."
2092 :group 'org-properties
2093 :type 'string)
2095 (defcustom org-columns-modify-value-for-display-function nil
2096 "Function that modifies values for display in column view.
2097 For example, it can be used to cut out a certain part from a time stamp.
2098 The function must take 2 arguments:
2100 column-title The title of the column (*not* the property name)
2101 value The value that should be modified.
2103 The function should return the value that should be displayed,
2104 or nil if the normal value should be used."
2105 :group 'org-properties
2106 :type 'function)
2108 (defcustom org-effort-property "Effort"
2109 "The property that is being used to keep track of effort estimates.
2110 Effort estimates given in this property need to have the format H:MM."
2111 :group 'org-properties
2112 :group 'org-progress
2113 :type '(string :tag "Property"))
2115 (defconst org-global-properties-fixed
2116 '(("VISIBILITY_ALL" . "folded children content all"))
2117 "List of property/value pairs that can be inherited by any entry.
2118 These are fixed values, for the preset properties.")
2121 (defcustom org-global-properties nil
2122 "List of property/value pairs that can be inherited by any entry.
2123 You can set buffer-local values for the same purpose in the variable
2124 `org-file-properties' this by adding lines like
2126 #+PROPERTY: NAME VALUE"
2127 :group 'org-properties
2128 :type '(repeat
2129 (cons (string :tag "Property")
2130 (string :tag "Value"))))
2132 (defvar org-file-properties nil
2133 "List of property/value pairs that can be inherited by any entry.
2134 Valid for the current buffer.
2135 This variable is populated from #+PROPERTY lines.")
2136 (make-variable-buffer-local 'org-file-properties)
2138 (defgroup org-agenda nil
2139 "Options concerning agenda views in Org-mode."
2140 :tag "Org Agenda"
2141 :group 'org)
2143 (defvar org-category nil
2144 "Variable used by org files to set a category for agenda display.
2145 Such files should use a file variable to set it, for example
2147 # -*- mode: org; org-category: \"ELisp\"
2149 or contain a special line
2151 #+CATEGORY: ELisp
2153 If the file does not specify a category, then file's base name
2154 is used instead.")
2155 (make-variable-buffer-local 'org-category)
2156 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2158 (defcustom org-agenda-files nil
2159 "The files to be used for agenda display.
2160 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2161 \\[org-remove-file]. You can also use customize to edit the list.
2163 If an entry is a directory, all files in that directory that are matched by
2164 `org-agenda-file-regexp' will be part of the file list.
2166 If the value of the variable is not a list but a single file name, then
2167 the list of agenda files is actually stored and maintained in that file, one
2168 agenda file per line."
2169 :group 'org-agenda
2170 :type '(choice
2171 (repeat :tag "List of files and directories" file)
2172 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2174 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2175 "Regular expression to match files for `org-agenda-files'.
2176 If any element in the list in that variable contains a directory instead
2177 of a normal file, all files in that directory that are matched by this
2178 regular expression will be included."
2179 :group 'org-agenda
2180 :type 'regexp)
2182 (defcustom org-agenda-text-search-extra-files nil
2183 "List of extra files to be searched by text search commands.
2184 These files will be search in addition to the agenda files by the
2185 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2186 Note that these files will only be searched for text search commands,
2187 not for the other agenda views like todo lists, tag searches or the weekly
2188 agenda. This variable is intended to list notes and possibly archive files
2189 that should also be searched by these two commands.
2190 In fact, if the first element in the list is the symbol `agenda-archives',
2191 than all archive files of all agenda files will be added to the search
2192 scope."
2193 :group 'org-agenda
2194 :type '(set :greedy t
2195 (const :tag "Agenda Archives" agenda-archives)
2196 (repeat :inline t (file))))
2198 (if (fboundp 'defvaralias)
2199 (defvaralias 'org-agenda-multi-occur-extra-files
2200 'org-agenda-text-search-extra-files))
2202 (defcustom org-agenda-skip-unavailable-files nil
2203 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2204 A nil value means to remove them, after a query, from the list."
2205 :group 'org-agenda
2206 :type 'boolean)
2208 (defcustom org-calendar-to-agenda-key [?c]
2209 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2210 The command `org-calendar-goto-agenda' will be bound to this key. The
2211 default is the character `c' because then `c' can be used to switch back and
2212 forth between agenda and calendar."
2213 :group 'org-agenda
2214 :type 'sexp)
2216 (defcustom org-calendar-agenda-action-key [?k]
2217 "The key to be installed in `calendar-mode-map' for agenda-action.
2218 The command `org-agenda-action' will be bound to this key. The
2219 default is the character `k' because we use the same key in the agenda."
2220 :group 'org-agenda
2221 :type 'sexp)
2223 (eval-after-load "calendar"
2224 '(progn
2225 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2226 'org-calendar-goto-agenda)
2227 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2228 'org-agenda-action)))
2230 (defgroup org-latex nil
2231 "Options for embedding LaTeX code into Org-mode."
2232 :tag "Org LaTeX"
2233 :group 'org)
2235 (defcustom org-format-latex-options
2236 '(:foreground default :background default :scale 1.0
2237 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2238 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
2239 "Options for creating images from LaTeX fragments.
2240 This is a property list with the following properties:
2241 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2242 `default' means use the foreground of the default face.
2243 :background the background color, or \"Transparent\".
2244 `default' means use the background of the default face.
2245 :scale a scaling factor for the size of the images.
2246 :html-foreground, :html-background, :html-scale
2247 the same numbers for HTML export.
2248 :matchers a list indicating which matchers should be used to
2249 find LaTeX fragments. Valid members of this list are:
2250 \"begin\" find environments
2251 \"$1\" find single characters surrounded by $.$
2252 \"$\" find math expressions surrounded by $...$
2253 \"$$\" find math expressions surrounded by $$....$$
2254 \"\\(\" find math expressions surrounded by \\(...\\)
2255 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2256 :group 'org-latex
2257 :type 'plist)
2259 (defcustom org-format-latex-header "\\documentclass{article}
2260 \\usepackage{fullpage} % do not remove
2261 \\usepackage{amssymb}
2262 \\usepackage[usenames]{color}
2263 \\usepackage{amsmath}
2264 \\usepackage{latexsym}
2265 \\usepackage[mathscr]{eucal}
2266 \\pagestyle{empty} % do not remove"
2267 "The document header used for processing LaTeX fragments."
2268 :group 'org-latex
2269 :type 'string)
2272 (defgroup org-font-lock nil
2273 "Font-lock settings for highlighting in Org-mode."
2274 :tag "Org Font Lock"
2275 :group 'org)
2277 (defcustom org-level-color-stars-only nil
2278 "Non-nil means fontify only the stars in each headline.
2279 When nil, the entire headline is fontified.
2280 Changing it requires restart of `font-lock-mode' to become effective
2281 also in regions already fontified."
2282 :group 'org-font-lock
2283 :type 'boolean)
2285 (defcustom org-hide-leading-stars nil
2286 "Non-nil means, hide the first N-1 stars in a headline.
2287 This works by using the face `org-hide' for these stars. This
2288 face is white for a light background, and black for a dark
2289 background. You may have to customize the face `org-hide' to
2290 make this work.
2291 Changing it requires restart of `font-lock-mode' to become effective
2292 also in regions already fontified.
2293 You may also set this on a per-file basis by adding one of the following
2294 lines to the buffer:
2296 #+STARTUP: hidestars
2297 #+STARTUP: showstars"
2298 :group 'org-font-lock
2299 :type 'boolean)
2301 (defcustom org-fontify-done-headline nil
2302 "Non-nil means, change the face of a headline if it is marked DONE.
2303 Normally, only the TODO/DONE keyword indicates the state of a headline.
2304 When this is non-nil, the headline after the keyword is set to the
2305 `org-headline-done' as an additional indication."
2306 :group 'org-font-lock
2307 :type 'boolean)
2309 (defcustom org-fontify-emphasized-text t
2310 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2311 Changing this variable requires a restart of Emacs to take effect."
2312 :group 'org-font-lock
2313 :type 'boolean)
2315 (defcustom org-highlight-latex-fragments-and-specials nil
2316 "Non-nil means, fontify what is treated specially by the exporters."
2317 :group 'org-font-lock
2318 :type 'boolean)
2320 (defcustom org-hide-emphasis-markers nil
2321 "Non-nil mean font-lock should hide the emphasis marker characters."
2322 :group 'org-font-lock
2323 :type 'boolean)
2325 (defvar org-emph-re nil
2326 "Regular expression for matching emphasis.")
2327 (defvar org-verbatim-re nil
2328 "Regular expression for matching verbatim text.")
2329 (defvar org-emphasis-regexp-components) ; defined just below
2330 (defvar org-emphasis-alist) ; defined just below
2331 (defun org-set-emph-re (var val)
2332 "Set variable and compute the emphasis regular expression."
2333 (set var val)
2334 (when (and (boundp 'org-emphasis-alist)
2335 (boundp 'org-emphasis-regexp-components)
2336 org-emphasis-alist org-emphasis-regexp-components)
2337 (let* ((e org-emphasis-regexp-components)
2338 (pre (car e))
2339 (post (nth 1 e))
2340 (border (nth 2 e))
2341 (body (nth 3 e))
2342 (nl (nth 4 e))
2343 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
2344 (body1 (concat body "*?"))
2345 (markers (mapconcat 'car org-emphasis-alist ""))
2346 (vmarkers (mapconcat
2347 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2348 org-emphasis-alist "")))
2349 ;; make sure special characters appear at the right position in the class
2350 (if (string-match "\\^" markers)
2351 (setq markers (concat (replace-match "" t t markers) "^")))
2352 (if (string-match "-" markers)
2353 (setq markers (concat (replace-match "" t t markers) "-")))
2354 (if (string-match "\\^" vmarkers)
2355 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2356 (if (string-match "-" vmarkers)
2357 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2358 (if (> nl 0)
2359 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2360 (int-to-string nl) "\\}")))
2361 ;; Make the regexp
2362 (setq org-emph-re
2363 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
2364 "\\("
2365 "\\([" markers "]\\)"
2366 "\\("
2367 "[^" border "]\\|"
2368 "[^" border (if (and nil stacked) markers) "]"
2369 body1
2370 "[^" border (if (and nil stacked) markers) "]"
2371 "\\)"
2372 "\\3\\)"
2373 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
2374 (setq org-verbatim-re
2375 (concat "\\([" pre "]\\|^\\)"
2376 "\\("
2377 "\\([" vmarkers "]\\)"
2378 "\\("
2379 "[^" border "]\\|"
2380 "[^" border "]"
2381 body1
2382 "[^" border "]"
2383 "\\)"
2384 "\\3\\)"
2385 "\\([" post "]\\|$\\)")))))
2387 (defcustom org-emphasis-regexp-components
2388 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
2389 "Components used to build the regular expression for emphasis.
2390 This is a list with 6 entries. Terminology: In an emphasis string
2391 like \" *strong word* \", we call the initial space PREMATCH, the final
2392 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2393 and \"trong wor\" is the body. The different components in this variable
2394 specify what is allowed/forbidden in each part:
2396 pre Chars allowed as prematch. Beginning of line will be allowed too.
2397 post Chars allowed as postmatch. End of line will be allowed too.
2398 border The chars *forbidden* as border characters.
2399 body-regexp A regexp like \".\" to match a body character. Don't use
2400 non-shy groups here, and don't allow newline here.
2401 newline The maximum number of newlines allowed in an emphasis exp.
2403 Use customize to modify this, or restart Emacs after changing it."
2404 :group 'org-font-lock
2405 :set 'org-set-emph-re
2406 :type '(list
2407 (sexp :tag "Allowed chars in pre ")
2408 (sexp :tag "Allowed chars in post ")
2409 (sexp :tag "Forbidden chars in border ")
2410 (sexp :tag "Regexp for body ")
2411 (integer :tag "number of newlines allowed")
2412 (option (boolean :tag "Please ignore this button"))))
2414 (defcustom org-emphasis-alist
2415 `(("*" bold "<b>" "</b>")
2416 ("/" italic "<i>" "</i>")
2417 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
2418 ("=" org-code "<code>" "</code>" verbatim)
2419 ("~" org-verbatim "<code>" "</code>" verbatim)
2420 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2421 "<del>" "</del>")
2423 "Special syntax for emphasized text.
2424 Text starting and ending with a special character will be emphasized, for
2425 example *bold*, _underlined_ and /italic/. This variable sets the marker
2426 characters, the face to be used by font-lock for highlighting in Org-mode
2427 Emacs buffers, and the HTML tags to be used for this.
2428 Use customize to modify this, or restart Emacs after changing it."
2429 :group 'org-font-lock
2430 :set 'org-set-emph-re
2431 :type '(repeat
2432 (list
2433 (string :tag "Marker character")
2434 (choice
2435 (face :tag "Font-lock-face")
2436 (plist :tag "Face property list"))
2437 (string :tag "HTML start tag")
2438 (string :tag "HTML end tag")
2439 (option (const verbatim)))))
2441 ;;; Miscellaneous options
2443 (defgroup org-completion nil
2444 "Completion in Org-mode."
2445 :tag "Org Completion"
2446 :group 'org)
2448 (defcustom org-completion-use-ido nil
2449 "Non-nil means, use ido completion wherever possible.
2450 Note that `ido-mode' must be active for this variable to be relevant.
2451 If you decide to turn this variable on, you might well want to turn off
2452 `org-outline-path-complete-in-steps'."
2453 :group 'org-completion
2454 :type 'boolean)
2456 (defcustom org-completion-fallback-command 'hippie-expand
2457 "The expansion command called by \\[org-complete] in normal context.
2458 Normal means, no org-mode-specific context."
2459 :group 'org-completion
2460 :type 'function)
2462 ;;; Functions and variables from ther packages
2463 ;; Declared here to avoid compiler warnings
2465 ;; XEmacs only
2466 (defvar outline-mode-menu-heading)
2467 (defvar outline-mode-menu-show)
2468 (defvar outline-mode-menu-hide)
2469 (defvar zmacs-regions) ; XEmacs regions
2471 ;; Emacs only
2472 (defvar mark-active)
2474 ;; Various packages
2475 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2476 (declare-function calendar-forward-day "cal-move" (arg))
2477 (declare-function calendar-goto-date "cal-move" (date))
2478 (declare-function calendar-goto-today "cal-move" ())
2479 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2480 (defvar calc-embedded-close-formula)
2481 (defvar calc-embedded-open-formula)
2482 (declare-function cdlatex-tab "ext:cdlatex" ())
2483 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2484 (defvar font-lock-unfontify-region-function)
2485 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2486 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2487 (defvar iswitchb-temp-buflist)
2488 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2489 (defvar org-agenda-tags-todo-honor-ignore-options)
2490 (declare-function org-agenda-skip "org-agenda" ())
2491 (declare-function org-format-agenda-item "org-agenda"
2492 (extra txt &optional category tags dotime noprefix remove-re))
2493 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2494 (declare-function org-agenda-change-all-lines "org-agenda"
2495 (newhead hdmarker &optional fixface just-this))
2496 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2497 (declare-function org-agenda-maybe-redo "org-agenda" ())
2498 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2499 (beg end))
2500 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
2501 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
2502 "org-agenda" (&optional end))
2504 (declare-function parse-time-string "parse-time" (string))
2505 (declare-function remember "remember" (&optional initial))
2506 (declare-function remember-buffer-desc "remember" ())
2507 (declare-function remember-finalize "remember" ())
2508 (defvar remember-save-after-remembering)
2509 (defvar remember-data-file)
2510 (defvar remember-register)
2511 (defvar remember-buffer)
2512 (defvar remember-handler-functions)
2513 (defvar remember-annotation-functions)
2514 (defvar texmathp-why)
2515 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2516 (declare-function table--at-cell-p "table" (position &optional object at-column))
2518 (defvar w3m-current-url)
2519 (defvar w3m-current-title)
2521 (defvar org-latex-regexps)
2523 ;;; Autoload and prepare some org modules
2525 ;; Some table stuff that needs to be defined here, because it is used
2526 ;; by the functions setting up org-mode or checking for table context.
2528 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2529 "Detects an org-type or table-type table.")
2530 (defconst org-table-line-regexp "^[ \t]*|"
2531 "Detects an org-type table line.")
2532 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2533 "Detects an org-type table line.")
2534 (defconst org-table-hline-regexp "^[ \t]*|-"
2535 "Detects an org-type table hline.")
2536 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2537 "Detects a table-type table hline.")
2538 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2539 "Searching from within a table (any type) this finds the first line
2540 outside the table.")
2542 ;; Autoload the functions in org-table.el that are needed by functions here.
2544 (eval-and-compile
2545 (org-autoload "org-table"
2546 '(org-table-align org-table-begin org-table-blank-field
2547 org-table-convert org-table-convert-region org-table-copy-down
2548 org-table-copy-region org-table-create
2549 org-table-create-or-convert-from-region
2550 org-table-create-with-table.el org-table-current-dline
2551 org-table-cut-region org-table-delete-column org-table-edit-field
2552 org-table-edit-formulas org-table-end org-table-eval-formula
2553 org-table-export org-table-field-info
2554 org-table-get-stored-formulas org-table-goto-column
2555 org-table-hline-and-move org-table-import org-table-insert-column
2556 org-table-insert-hline org-table-insert-row org-table-iterate
2557 org-table-justify-field-maybe org-table-kill-row
2558 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2559 org-table-move-column org-table-move-column-left
2560 org-table-move-column-right org-table-move-row
2561 org-table-move-row-down org-table-move-row-up
2562 org-table-next-field org-table-next-row org-table-paste-rectangle
2563 org-table-previous-field org-table-recalculate
2564 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2565 org-table-toggle-coordinate-overlays
2566 org-table-toggle-formula-debugger org-table-wrap-region
2567 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
2569 (defun org-at-table-p (&optional table-type)
2570 "Return t if the cursor is inside an org-type table.
2571 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2572 (if org-enable-table-editor
2573 (save-excursion
2574 (beginning-of-line 1)
2575 (looking-at (if table-type org-table-any-line-regexp
2576 org-table-line-regexp)))
2577 nil))
2578 (defsubst org-table-p () (org-at-table-p))
2580 (defun org-at-table.el-p ()
2581 "Return t if and only if we are at a table.el table."
2582 (and (org-at-table-p 'any)
2583 (save-excursion
2584 (goto-char (org-table-begin 'any))
2585 (looking-at org-table1-hline-regexp))))
2586 (defun org-table-recognize-table.el ()
2587 "If there is a table.el table nearby, recognize it and move into it."
2588 (if org-table-tab-recognizes-table.el
2589 (if (org-at-table.el-p)
2590 (progn
2591 (beginning-of-line 1)
2592 (if (looking-at org-table-dataline-regexp)
2594 (if (looking-at org-table1-hline-regexp)
2595 (progn
2596 (beginning-of-line 2)
2597 (if (looking-at org-table-any-border-regexp)
2598 (beginning-of-line -1)))))
2599 (if (re-search-forward "|" (org-table-end t) t)
2600 (progn
2601 (require 'table)
2602 (if (table--at-cell-p (point))
2604 (message "recognizing table.el table...")
2605 (table-recognize-table)
2606 (message "recognizing table.el table...done")))
2607 (error "This should not happen..."))
2609 nil)
2610 nil))
2612 (defun org-at-table-hline-p ()
2613 "Return t if the cursor is inside a hline in a table."
2614 (if org-enable-table-editor
2615 (save-excursion
2616 (beginning-of-line 1)
2617 (looking-at org-table-hline-regexp))
2618 nil))
2620 (defvar org-table-clean-did-remove-column nil)
2622 (defun org-table-map-tables (function)
2623 "Apply FUNCTION to the start of all tables in the buffer."
2624 (save-excursion
2625 (save-restriction
2626 (widen)
2627 (goto-char (point-min))
2628 (while (re-search-forward org-table-any-line-regexp nil t)
2629 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2630 (beginning-of-line 1)
2631 (if (looking-at org-table-line-regexp)
2632 (save-excursion (funcall function)))
2633 (re-search-forward org-table-any-border-regexp nil 1))))
2634 (message "Mapping tables: done"))
2636 ;; Declare and autoload functions from org-exp.el
2638 (declare-function org-default-export-plist "org-exp")
2639 (declare-function org-infile-export-plist "org-exp")
2640 (declare-function org-get-current-options "org-exp")
2641 (eval-and-compile
2642 (org-autoload "org-exp"
2643 '(org-export org-export-as-ascii org-export-visible
2644 org-insert-export-options-template org-export-as-html-and-open
2645 org-export-as-html-batch org-export-as-html-to-buffer
2646 org-replace-region-by-html org-export-region-as-html
2647 org-export-as-html org-export-icalendar-this-file
2648 org-export-icalendar-all-agenda-files
2649 org-table-clean-before-export
2650 org-export-icalendar-combine-agenda-files org-export-as-xoxo)))
2652 ;; Declare and autoload functions from org-agenda.el
2654 (eval-and-compile
2655 (org-autoload "org-agenda"
2656 '(org-agenda org-agenda-list org-search-view
2657 org-todo-list org-tags-view org-agenda-list-stuck-projects
2658 org-diary org-agenda-to-appt
2659 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
2661 ;; Autoload org-remember
2663 (eval-and-compile
2664 (org-autoload "org-remember"
2665 '(org-remember-insinuate org-remember-annotation
2666 org-remember-apply-template org-remember org-remember-handler)))
2668 ;; Autoload org-clock.el
2671 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
2672 (beg end))
2673 (declare-function org-clock-update-mode-line "org-clock" ())
2674 (defvar org-clock-start-time)
2675 (defvar org-clock-marker (make-marker)
2676 "Marker recording the last clock-in.")
2678 (eval-and-compile
2679 (org-autoload
2680 "org-clock"
2681 '(org-clock-in org-clock-out org-clock-cancel
2682 org-clock-goto org-clock-sum org-clock-display
2683 org-clock-remove-overlays org-clock-report
2684 org-clocktable-shift org-dblock-write:clocktable
2685 org-get-clocktable)))
2687 (defun org-clock-update-time-maybe ()
2688 "If this is a CLOCK line, update it and return t.
2689 Otherwise, return nil."
2690 (interactive)
2691 (save-excursion
2692 (beginning-of-line 1)
2693 (skip-chars-forward " \t")
2694 (when (looking-at org-clock-string)
2695 (let ((re (concat "[ \t]*" org-clock-string
2696 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
2697 "\\([ \t]*=>.*\\)?\\)?"))
2698 ts te h m s neg)
2699 (cond
2700 ((not (looking-at re))
2701 nil)
2702 ((not (match-end 2))
2703 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2704 (> org-clock-marker (point))
2705 (<= org-clock-marker (point-at-eol)))
2706 ;; The clock is running here
2707 (setq org-clock-start-time
2708 (apply 'encode-time
2709 (org-parse-time-string (match-string 1))))
2710 (org-clock-update-mode-line)))
2712 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
2713 (end-of-line 1)
2714 (setq ts (match-string 1)
2715 te (match-string 3))
2716 (setq s (- (time-to-seconds
2717 (apply 'encode-time (org-parse-time-string te)))
2718 (time-to-seconds
2719 (apply 'encode-time (org-parse-time-string ts))))
2720 neg (< s 0)
2721 s (abs s)
2722 h (floor (/ s 3600))
2723 s (- s (* 3600 h))
2724 m (floor (/ s 60))
2725 s (- s (* 60 s)))
2726 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
2727 t))))))
2729 (defun org-check-running-clock ()
2730 "Check if the current buffer contains the running clock.
2731 If yes, offer to stop it and to save the buffer with the changes."
2732 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2733 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
2734 (buffer-name))))
2735 (org-clock-out)
2736 (when (y-or-n-p "Save changed buffer?")
2737 (save-buffer))))
2739 (defun org-clocktable-try-shift (dir n)
2740 "Check if this line starts a clock table, if yes, shift the time block."
2741 (when (org-match-line "#\\+BEGIN: clocktable\\>")
2742 (org-clocktable-shift dir n)))
2744 ;; Autoload org-timer.el
2746 ;(declare-function org-timer "org-timer")
2748 (eval-and-compile
2749 (org-autoload
2750 "org-timer"
2751 '(org-timer-start org-timer org-timer-item
2752 org-timer-change-times-in-region)))
2755 ;; Autoload archiving code
2756 ;; The stuff that is needed for cycling and tags has to be defined here.
2758 (defgroup org-archive nil
2759 "Options concerning archiving in Org-mode."
2760 :tag "Org Archive"
2761 :group 'org-structure)
2763 (defcustom org-archive-location "%s_archive::"
2764 "The location where subtrees should be archived.
2766 The value of this variable is a string, consisting of two parts,
2767 separated by a double-colon. The first part is a filename and
2768 the second part is a headline.
2770 When the filename is omitted, archiving happens in the same file.
2771 %s in the filename will be replaced by the current file
2772 name (without the directory part). Archiving to a different file
2773 is useful to keep archived entries from contributing to the
2774 Org-mode Agenda.
2776 The archived entries will be filed as subtrees of the specified
2777 headline. When the headline is omitted, the subtrees are simply
2778 filed away at the end of the file, as top-level entries. Also in
2779 the heading you can use %s to represent the file name, this can be
2780 useful when using the same archive for a number of different files.
2782 Here are a few examples:
2783 \"%s_archive::\"
2784 If the current file is Projects.org, archive in file
2785 Projects.org_archive, as top-level trees. This is the default.
2787 \"::* Archived Tasks\"
2788 Archive in the current file, under the top-level headline
2789 \"* Archived Tasks\".
2791 \"~/org/archive.org::\"
2792 Archive in file ~/org/archive.org (absolute path), as top-level trees.
2794 \"~/org/archive.org::From %s\"
2795 Archive in file ~/org/archive.org (absolute path), und headlines
2796 \"From FILENAME\" where file name is the current file name.
2798 \"basement::** Finished Tasks\"
2799 Archive in file ./basement (relative path), as level 3 trees
2800 below the level 2 heading \"** Finished Tasks\".
2802 You may set this option on a per-file basis by adding to the buffer a
2803 line like
2805 #+ARCHIVE: basement::** Finished Tasks
2807 You may also define it locally for a subtree by setting an ARCHIVE property
2808 in the entry. If such a property is found in an entry, or anywhere up
2809 the hierarchy, it will be used."
2810 :group 'org-archive
2811 :type 'string)
2813 (defcustom org-archive-tag "ARCHIVE"
2814 "The tag that marks a subtree as archived.
2815 An archived subtree does not open during visibility cycling, and does
2816 not contribute to the agenda listings.
2817 After changing this, font-lock must be restarted in the relevant buffers to
2818 get the proper fontification."
2819 :group 'org-archive
2820 :group 'org-keywords
2821 :type 'string)
2823 (defcustom org-agenda-skip-archived-trees t
2824 "Non-nil means, the agenda will skip any items located in archived trees.
2825 An archived tree is a tree marked with the tag ARCHIVE. The use of this
2826 variable is no longer recommended, you should leave it at the value t.
2827 Instead, use the key `v' to cycle the archives-mode in the agenda."
2828 :group 'org-archive
2829 :group 'org-agenda-skip
2830 :type 'boolean)
2832 (defcustom org-cycle-open-archived-trees nil
2833 "Non-nil means, `org-cycle' will open archived trees.
2834 An archived tree is a tree marked with the tag ARCHIVE.
2835 When nil, archived trees will stay folded. You can still open them with
2836 normal outline commands like `show-all', but not with the cycling commands."
2837 :group 'org-archive
2838 :group 'org-cycle
2839 :type 'boolean)
2841 (defcustom org-sparse-tree-open-archived-trees nil
2842 "Non-nil means sparse tree construction shows matches in archived trees.
2843 When nil, matches in these trees are highlighted, but the trees are kept in
2844 collapsed state."
2845 :group 'org-archive
2846 :group 'org-sparse-trees
2847 :type 'boolean)
2849 (defun org-cycle-hide-archived-subtrees (state)
2850 "Re-hide all archived subtrees after a visibility state change."
2851 (when (and (not org-cycle-open-archived-trees)
2852 (not (memq state '(overview folded))))
2853 (save-excursion
2854 (let* ((globalp (memq state '(contents all)))
2855 (beg (if globalp (point-min) (point)))
2856 (end (if globalp (point-max) (org-end-of-subtree t))))
2857 (org-hide-archived-subtrees beg end)
2858 (goto-char beg)
2859 (if (looking-at (concat ".*:" org-archive-tag ":"))
2860 (message "%s" (substitute-command-keys
2861 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
2863 (defun org-force-cycle-archived ()
2864 "Cycle subtree even if it is archived."
2865 (interactive)
2866 (setq this-command 'org-cycle)
2867 (let ((org-cycle-open-archived-trees t))
2868 (call-interactively 'org-cycle)))
2870 (defun org-hide-archived-subtrees (beg end)
2871 "Re-hide all archived subtrees after a visibility state change."
2872 (save-excursion
2873 (let* ((re (concat ":" org-archive-tag ":")))
2874 (goto-char beg)
2875 (while (re-search-forward re end t)
2876 (and (org-on-heading-p) (hide-subtree))
2877 (org-end-of-subtree t)))))
2879 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
2881 (eval-and-compile
2882 (org-autoload "org-archive"
2883 '(org-add-archive-files org-archive-subtree
2884 org-archive-to-archive-sibling org-toggle-archive-tag)))
2886 ;; Autoload Column View Code
2888 (declare-function org-columns-number-to-string "org-colview")
2889 (declare-function org-columns-get-format-and-top-level "org-colview")
2890 (declare-function org-columns-compute "org-colview")
2892 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
2893 '(org-columns-number-to-string org-columns-get-format-and-top-level
2894 org-columns-compute org-agenda-columns org-columns-remove-overlays
2895 org-columns org-insert-columns-dblock org-dblock-write:columnview))
2897 ;; Autoload ID code
2899 (declare-function org-id-store-link "org-id")
2900 (org-autoload "org-id"
2901 '(org-id-get-create org-id-new org-id-copy org-id-get
2902 org-id-get-with-outline-path-completion
2903 org-id-get-with-outline-drilling
2904 org-id-goto org-id-find org-id-store-link))
2906 ;;; Variables for pre-computed regular expressions, all buffer local
2908 (defvar org-drawer-regexp nil
2909 "Matches first line of a hidden block.")
2910 (make-variable-buffer-local 'org-drawer-regexp)
2911 (defvar org-todo-regexp nil
2912 "Matches any of the TODO state keywords.")
2913 (make-variable-buffer-local 'org-todo-regexp)
2914 (defvar org-not-done-regexp nil
2915 "Matches any of the TODO state keywords except the last one.")
2916 (make-variable-buffer-local 'org-not-done-regexp)
2917 (defvar org-todo-line-regexp nil
2918 "Matches a headline and puts TODO state into group 2 if present.")
2919 (make-variable-buffer-local 'org-todo-line-regexp)
2920 (defvar org-complex-heading-regexp nil
2921 "Matches a headline and puts everything into groups:
2922 group 1: the stars
2923 group 2: The todo keyword, maybe
2924 group 3: Priority cookie
2925 group 4: True headline
2926 group 5: Tags")
2927 (make-variable-buffer-local 'org-complex-heading-regexp)
2928 (defvar org-todo-line-tags-regexp nil
2929 "Matches a headline and puts TODO state into group 2 if present.
2930 Also put tags into group 4 if tags are present.")
2931 (make-variable-buffer-local 'org-todo-line-tags-regexp)
2932 (defvar org-nl-done-regexp nil
2933 "Matches newline followed by a headline with the DONE keyword.")
2934 (make-variable-buffer-local 'org-nl-done-regexp)
2935 (defvar org-looking-at-done-regexp nil
2936 "Matches the DONE keyword a point.")
2937 (make-variable-buffer-local 'org-looking-at-done-regexp)
2938 (defvar org-ds-keyword-length 12
2939 "Maximum length of the Deadline and SCHEDULED keywords.")
2940 (make-variable-buffer-local 'org-ds-keyword-length)
2941 (defvar org-deadline-regexp nil
2942 "Matches the DEADLINE keyword.")
2943 (make-variable-buffer-local 'org-deadline-regexp)
2944 (defvar org-deadline-time-regexp nil
2945 "Matches the DEADLINE keyword together with a time stamp.")
2946 (make-variable-buffer-local 'org-deadline-time-regexp)
2947 (defvar org-deadline-line-regexp nil
2948 "Matches the DEADLINE keyword and the rest of the line.")
2949 (make-variable-buffer-local 'org-deadline-line-regexp)
2950 (defvar org-scheduled-regexp nil
2951 "Matches the SCHEDULED keyword.")
2952 (make-variable-buffer-local 'org-scheduled-regexp)
2953 (defvar org-scheduled-time-regexp nil
2954 "Matches the SCHEDULED keyword together with a time stamp.")
2955 (make-variable-buffer-local 'org-scheduled-time-regexp)
2956 (defvar org-closed-time-regexp nil
2957 "Matches the CLOSED keyword together with a time stamp.")
2958 (make-variable-buffer-local 'org-closed-time-regexp)
2960 (defvar org-keyword-time-regexp nil
2961 "Matches any of the 4 keywords, together with the time stamp.")
2962 (make-variable-buffer-local 'org-keyword-time-regexp)
2963 (defvar org-keyword-time-not-clock-regexp nil
2964 "Matches any of the 3 keywords, together with the time stamp.")
2965 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
2966 (defvar org-maybe-keyword-time-regexp nil
2967 "Matches a timestamp, possibly preceeded by a keyword.")
2968 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
2969 (defvar org-planning-or-clock-line-re nil
2970 "Matches a line with planning or clock info.")
2971 (make-variable-buffer-local 'org-planning-or-clock-line-re)
2973 (defconst org-plain-time-of-day-regexp
2974 (concat
2975 "\\(\\<[012]?[0-9]"
2976 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2977 "\\(--?"
2978 "\\(\\<[012]?[0-9]"
2979 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2980 "\\)?")
2981 "Regular expression to match a plain time or time range.
2982 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2983 groups carry important information:
2984 0 the full match
2985 1 the first time, range or not
2986 8 the second time, if it is a range.")
2988 (defconst org-plain-time-extension-regexp
2989 (concat
2990 "\\(\\<[012]?[0-9]"
2991 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2992 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
2993 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
2994 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2995 groups carry important information:
2996 0 the full match
2997 7 hours of duration
2998 9 minutes of duration")
3000 (defconst org-stamp-time-of-day-regexp
3001 (concat
3002 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
3003 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
3004 "\\(--?"
3005 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
3006 "Regular expression to match a timestamp time or time range.
3007 After a match, the following groups carry important information:
3008 0 the full match
3009 1 date plus weekday, for backreferencing to make sure both times on same day
3010 2 the first time, range or not
3011 4 the second time, if it is a range.")
3013 (defconst org-startup-options
3014 '(("fold" org-startup-folded t)
3015 ("overview" org-startup-folded t)
3016 ("nofold" org-startup-folded nil)
3017 ("showall" org-startup-folded nil)
3018 ("content" org-startup-folded content)
3019 ("hidestars" org-hide-leading-stars t)
3020 ("showstars" org-hide-leading-stars nil)
3021 ("odd" org-odd-levels-only t)
3022 ("oddeven" org-odd-levels-only nil)
3023 ("align" org-startup-align-all-tables t)
3024 ("noalign" org-startup-align-all-tables nil)
3025 ("customtime" org-display-custom-times t)
3026 ("logdone" org-log-done time)
3027 ("lognotedone" org-log-done note)
3028 ("nologdone" org-log-done nil)
3029 ("lognoteclock-out" org-log-note-clock-out t)
3030 ("nolognoteclock-out" org-log-note-clock-out nil)
3031 ("logrepeat" org-log-repeat state)
3032 ("lognoterepeat" org-log-repeat note)
3033 ("nologrepeat" org-log-repeat nil)
3034 ("fninline" org-footnote-define-inline t)
3035 ("nofninline" org-footnote-define-inline nil)
3036 ("fnlocal" org-footnote-section nil)
3037 ("fnauto" org-footnote-auto-label t)
3038 ("fnprompt" org-footnote-auto-label nil)
3039 ("fnconfirm" org-footnote-auto-label confirm)
3040 ("fnplain" org-footnote-auto-label plain)
3041 ("constcgs" constants-unit-system cgs)
3042 ("constSI" constants-unit-system SI))
3043 "Variable associated with STARTUP options for org-mode.
3044 Each element is a list of three items: The startup options as written
3045 in the #+STARTUP line, the corresponding variable, and the value to
3046 set this variable to if the option is found. An optional forth element PUSH
3047 means to push this value onto the list in the variable.")
3049 (defun org-set-regexps-and-options ()
3050 "Precompute regular expressions for current buffer."
3051 (when (org-mode-p)
3052 (org-set-local 'org-todo-kwd-alist nil)
3053 (org-set-local 'org-todo-key-alist nil)
3054 (org-set-local 'org-todo-key-trigger nil)
3055 (org-set-local 'org-todo-keywords-1 nil)
3056 (org-set-local 'org-done-keywords nil)
3057 (org-set-local 'org-todo-heads nil)
3058 (org-set-local 'org-todo-sets nil)
3059 (org-set-local 'org-todo-log-states nil)
3060 (org-set-local 'org-file-properties nil)
3061 (org-set-local 'org-file-tags nil)
3062 (let ((re (org-make-options-regexp
3063 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
3064 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3065 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")))
3066 (splitre "[ \t]+")
3067 kwds kws0 kwsa key log value cat arch tags const links hw dws
3068 tail sep kws1 prio props ftags drawers
3069 ext-setup-or-nil setup-contents (start 0))
3070 (save-excursion
3071 (save-restriction
3072 (widen)
3073 (goto-char (point-min))
3074 (while (or (and ext-setup-or-nil
3075 (string-match re ext-setup-or-nil start)
3076 (setq start (match-end 0)))
3077 (and (setq ext-setup-or-nil nil start 0)
3078 (re-search-forward re nil t)))
3079 (setq key (upcase (match-string 1 ext-setup-or-nil))
3080 value (org-match-string-no-properties 2 ext-setup-or-nil))
3081 (cond
3082 ((equal key "CATEGORY")
3083 (if (string-match "[ \t]+$" value)
3084 (setq value (replace-match "" t t value)))
3085 (setq cat value))
3086 ((member key '("SEQ_TODO" "TODO"))
3087 (push (cons 'sequence (org-split-string value splitre)) kwds))
3088 ((equal key "TYP_TODO")
3089 (push (cons 'type (org-split-string value splitre)) kwds))
3090 ((equal key "TAGS")
3091 (setq tags (append tags (org-split-string value splitre))))
3092 ((equal key "COLUMNS")
3093 (org-set-local 'org-columns-default-format value))
3094 ((equal key "LINK")
3095 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3096 (push (cons (match-string 1 value)
3097 (org-trim (match-string 2 value)))
3098 links)))
3099 ((equal key "PRIORITIES")
3100 (setq prio (org-split-string value " +")))
3101 ((equal key "PROPERTY")
3102 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3103 (push (cons (match-string 1 value) (match-string 2 value))
3104 props)))
3105 ((equal key "FILETAGS")
3106 (when (string-match "\\S-" value)
3107 (setq ftags
3108 (append
3109 ftags
3110 (apply 'append
3111 (mapcar (lambda (x) (org-split-string x ":"))
3112 (org-split-string value)))))))
3113 ((equal key "DRAWERS")
3114 (setq drawers (org-split-string value splitre)))
3115 ((equal key "CONSTANTS")
3116 (setq const (append const (org-split-string value splitre))))
3117 ((equal key "STARTUP")
3118 (let ((opts (org-split-string value splitre))
3119 l var val)
3120 (while (setq l (pop opts))
3121 (when (setq l (assoc l org-startup-options))
3122 (setq var (nth 1 l) val (nth 2 l))
3123 (if (not (nth 3 l))
3124 (set (make-local-variable var) val)
3125 (if (not (listp (symbol-value var)))
3126 (set (make-local-variable var) nil))
3127 (set (make-local-variable var) (symbol-value var))
3128 (add-to-list var val))))))
3129 ((equal key "ARCHIVE")
3130 (string-match " *$" value)
3131 (setq arch (replace-match "" t t value))
3132 (remove-text-properties 0 (length arch)
3133 '(face t fontified t) arch))
3134 ((equal key "SETUPFILE")
3135 (setq setup-contents (org-file-contents
3136 (expand-file-name
3137 (org-remove-double-quotes value))
3138 'noerror))
3139 (if (not ext-setup-or-nil)
3140 (setq ext-setup-or-nil setup-contents start 0)
3141 (setq ext-setup-or-nil
3142 (concat (substring ext-setup-or-nil 0 start)
3143 "\n" setup-contents "\n"
3144 (substring ext-setup-or-nil start)))))
3145 ))))
3146 (when cat
3147 (org-set-local 'org-category (intern cat))
3148 (push (cons "CATEGORY" cat) props))
3149 (when prio
3150 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3151 (setq prio (mapcar 'string-to-char prio))
3152 (org-set-local 'org-highest-priority (nth 0 prio))
3153 (org-set-local 'org-lowest-priority (nth 1 prio))
3154 (org-set-local 'org-default-priority (nth 2 prio)))
3155 (and props (org-set-local 'org-file-properties (nreverse props)))
3156 (and ftags (org-set-local 'org-file-tags ftags))
3157 (and drawers (org-set-local 'org-drawers drawers))
3158 (and arch (org-set-local 'org-archive-location arch))
3159 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3160 ;; Process the TODO keywords
3161 (unless kwds
3162 ;; Use the global values as if they had been given locally.
3163 (setq kwds (default-value 'org-todo-keywords))
3164 (if (stringp (car kwds))
3165 (setq kwds (list (cons org-todo-interpretation
3166 (default-value 'org-todo-keywords)))))
3167 (setq kwds (reverse kwds)))
3168 (setq kwds (nreverse kwds))
3169 (let (inter kws kw)
3170 (while (setq kws (pop kwds))
3171 (setq inter (pop kws) sep (member "|" kws)
3172 kws0 (delete "|" (copy-sequence kws))
3173 kwsa nil
3174 kws1 (mapcar
3175 (lambda (x)
3176 ;; 1 2
3177 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3178 (progn
3179 (setq kw (match-string 1 x)
3180 key (and (match-end 2) (match-string 2 x))
3181 log (org-extract-log-state-settings x))
3182 (push (cons kw (and key (string-to-char key))) kwsa)
3183 (and log (push log org-todo-log-states))
3185 (error "Invalid TODO keyword %s" x)))
3186 kws0)
3187 kwsa (if kwsa (append '((:startgroup))
3188 (nreverse kwsa)
3189 '((:endgroup))))
3190 hw (car kws1)
3191 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3192 tail (list inter hw (car dws) (org-last dws)))
3193 (add-to-list 'org-todo-heads hw 'append)
3194 (push kws1 org-todo-sets)
3195 (setq org-done-keywords (append org-done-keywords dws nil))
3196 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3197 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3198 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3199 (setq org-todo-sets (nreverse org-todo-sets)
3200 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3201 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3202 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3203 ;; Process the constants
3204 (when const
3205 (let (e cst)
3206 (while (setq e (pop const))
3207 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3208 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3209 (setq org-table-formula-constants-local cst)))
3211 ;; Process the tags.
3212 (when tags
3213 (let (e tgs)
3214 (while (setq e (pop tags))
3215 (cond
3216 ((equal e "{") (push '(:startgroup) tgs))
3217 ((equal e "}") (push '(:endgroup) tgs))
3218 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3219 (push (cons (match-string 1 e)
3220 (string-to-char (match-string 2 e)))
3221 tgs))
3222 (t (push (list e) tgs))))
3223 (org-set-local 'org-tag-alist nil)
3224 (while (setq e (pop tgs))
3225 (or (and (stringp (car e))
3226 (assoc (car e) org-tag-alist))
3227 (push e org-tag-alist)))))
3229 ;; Compute the regular expressions and other local variables
3230 (if (not org-done-keywords)
3231 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
3232 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3233 (length org-scheduled-string)
3234 (length org-clock-string)
3235 (length org-closed-string)))
3236 org-drawer-regexp
3237 (concat "^[ \t]*:\\("
3238 (mapconcat 'regexp-quote org-drawers "\\|")
3239 "\\):[ \t]*$")
3240 org-not-done-keywords
3241 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3242 org-todo-regexp
3243 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3244 "\\|") "\\)\\>")
3245 org-not-done-regexp
3246 (concat "\\<\\("
3247 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3248 "\\)\\>")
3249 org-todo-line-regexp
3250 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3251 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3252 "\\)\\>\\)?[ \t]*\\(.*\\)")
3253 org-complex-heading-regexp
3254 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3255 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3256 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3257 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3258 org-nl-done-regexp
3259 (concat "\n\\*+[ \t]+"
3260 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3261 "\\)" "\\>")
3262 org-todo-line-tags-regexp
3263 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3264 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3265 (org-re
3266 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3267 org-looking-at-done-regexp
3268 (concat "^" "\\(?:"
3269 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3270 "\\>")
3271 org-deadline-regexp (concat "\\<" org-deadline-string)
3272 org-deadline-time-regexp
3273 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3274 org-deadline-line-regexp
3275 (concat "\\<\\(" org-deadline-string "\\).*")
3276 org-scheduled-regexp
3277 (concat "\\<" org-scheduled-string)
3278 org-scheduled-time-regexp
3279 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3280 org-closed-time-regexp
3281 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3282 org-keyword-time-regexp
3283 (concat "\\<\\(" org-scheduled-string
3284 "\\|" org-deadline-string
3285 "\\|" org-closed-string
3286 "\\|" org-clock-string "\\)"
3287 " *[[<]\\([^]>]+\\)[]>]")
3288 org-keyword-time-not-clock-regexp
3289 (concat "\\<\\(" org-scheduled-string
3290 "\\|" org-deadline-string
3291 "\\|" org-closed-string
3292 "\\)"
3293 " *[[<]\\([^]>]+\\)[]>]")
3294 org-maybe-keyword-time-regexp
3295 (concat "\\(\\<\\(" org-scheduled-string
3296 "\\|" org-deadline-string
3297 "\\|" org-closed-string
3298 "\\|" org-clock-string "\\)\\)?"
3299 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3300 org-planning-or-clock-line-re
3301 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3302 "\\|" org-deadline-string
3303 "\\|" org-closed-string "\\|" org-clock-string
3304 "\\)\\>\\)")
3306 (org-compute-latex-and-specials-regexp)
3307 (org-set-font-lock-defaults))))
3309 (defun org-file-contents (file &optional noerror)
3310 "Return the contents of FILE, as a string."
3311 (if (or (not file)
3312 (not (file-readable-p file)))
3313 (if noerror
3314 (progn
3315 (message "Cannot read file %s" file)
3316 (ding) (sit-for 2)
3318 (error "Cannot read file %s" file))
3319 (with-temp-buffer
3320 (insert-file-contents file)
3321 (buffer-string))))
3323 (defun org-extract-log-state-settings (x)
3324 "Extract the log state setting from a TODO keyword string.
3325 This will extract info from a string like \"WAIT(w@/!)\"."
3326 (let (kw key log1 log2)
3327 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3328 (setq kw (match-string 1 x)
3329 key (and (match-end 2) (match-string 2 x))
3330 log1 (and (match-end 3) (match-string 3 x))
3331 log2 (and (match-end 4) (match-string 4 x)))
3332 (and (or log1 log2)
3333 (list kw
3334 (and log1 (if (equal log1 "!") 'time 'note))
3335 (and log2 (if (equal log2 "!") 'time 'note)))))))
3337 (defun org-remove-keyword-keys (list)
3338 "Remove a pair of parenthesis at the end of each string in LIST."
3339 (mapcar (lambda (x)
3340 (if (string-match "(.*)$" x)
3341 (substring x 0 (match-beginning 0))
3343 list))
3345 ;; FIXME: this could be done much better, using second characters etc.
3346 (defun org-assign-fast-keys (alist)
3347 "Assign fast keys to a keyword-key alist.
3348 Respect keys that are already there."
3349 (let (new e k c c1 c2 (char ?a))
3350 (while (setq e (pop alist))
3351 (cond
3352 ((equal e '(:startgroup)) (push e new))
3353 ((equal e '(:endgroup)) (push e new))
3355 (setq k (car e) c2 nil)
3356 (if (cdr e)
3357 (setq c (cdr e))
3358 ;; automatically assign a character.
3359 (setq c1 (string-to-char
3360 (downcase (substring
3361 k (if (= (string-to-char k) ?@) 1 0)))))
3362 (if (or (rassoc c1 new) (rassoc c1 alist))
3363 (while (or (rassoc char new) (rassoc char alist))
3364 (setq char (1+ char)))
3365 (setq c2 c1))
3366 (setq c (or c2 char)))
3367 (push (cons k c) new))))
3368 (nreverse new)))
3370 ;;; Some variables used in various places
3372 (defvar org-window-configuration nil
3373 "Used in various places to store a window configuration.")
3374 (defvar org-finish-function nil
3375 "Function to be called when `C-c C-c' is used.
3376 This is for getting out of special buffers like remember.")
3379 ;; FIXME: Occasionally check by commenting these, to make sure
3380 ;; no other functions uses these, forgetting to let-bind them.
3381 (defvar entry)
3382 (defvar state)
3383 (defvar last-state)
3384 (defvar date)
3385 (defvar description)
3387 ;; Defined somewhere in this file, but used before definition.
3388 (defvar org-html-entities)
3389 (defvar org-struct-menu)
3390 (defvar org-org-menu)
3391 (defvar org-tbl-menu)
3392 (defvar org-agenda-keymap)
3394 ;;;; Define the Org-mode
3396 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3397 (error "Conflict with outdated version of allout.el. Load org.el before allout.el, or upgrade to newer allout, for example by switching to Emacs 22."))
3400 ;; We use a before-change function to check if a table might need
3401 ;; an update.
3402 (defvar org-table-may-need-update t
3403 "Indicates that a table might need an update.
3404 This variable is set by `org-before-change-function'.
3405 `org-table-align' sets it back to nil.")
3406 (defun org-before-change-function (beg end)
3407 "Every change indicates that a table might need an update."
3408 (setq org-table-may-need-update t))
3409 (defvar org-mode-map)
3410 (defvar org-mode-hook nil
3411 "Mode hook for Org-mode, run after the mode was turned on.")
3412 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3413 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3414 (defvar org-table-buffer-is-an nil)
3415 (defconst org-outline-regexp "\\*+ ")
3417 ;;;###autoload
3418 (define-derived-mode org-mode outline-mode "Org"
3419 "Outline-based notes management and organizer, alias
3420 \"Carsten's outline-mode for keeping track of everything.\"
3422 Org-mode develops organizational tasks around a NOTES file which
3423 contains information about projects as plain text. Org-mode is
3424 implemented on top of outline-mode, which is ideal to keep the content
3425 of large files well structured. It supports ToDo items, deadlines and
3426 time stamps, which magically appear in the diary listing of the Emacs
3427 calendar. Tables are easily created with a built-in table editor.
3428 Plain text URL-like links connect to websites, emails (VM), Usenet
3429 messages (Gnus), BBDB entries, and any files related to the project.
3430 For printing and sharing of notes, an Org-mode file (or a part of it)
3431 can be exported as a structured ASCII or HTML file.
3433 The following commands are available:
3435 \\{org-mode-map}"
3437 ;; Get rid of Outline menus, they are not needed
3438 ;; Need to do this here because define-derived-mode sets up
3439 ;; the keymap so late. Still, it is a waste to call this each time
3440 ;; we switch another buffer into org-mode.
3441 (if (featurep 'xemacs)
3442 (when (boundp 'outline-mode-menu-heading)
3443 ;; Assume this is Greg's port, it used easymenu
3444 (easy-menu-remove outline-mode-menu-heading)
3445 (easy-menu-remove outline-mode-menu-show)
3446 (easy-menu-remove outline-mode-menu-hide))
3447 (define-key org-mode-map [menu-bar headings] 'undefined)
3448 (define-key org-mode-map [menu-bar hide] 'undefined)
3449 (define-key org-mode-map [menu-bar show] 'undefined))
3451 (org-load-modules-maybe)
3452 (easy-menu-add org-org-menu)
3453 (easy-menu-add org-tbl-menu)
3454 (org-install-agenda-files-menu)
3455 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3456 (org-add-to-invisibility-spec '(org-cwidth))
3457 (when (featurep 'xemacs)
3458 (org-set-local 'line-move-ignore-invisible t))
3459 (org-set-local 'outline-regexp org-outline-regexp)
3460 (org-set-local 'outline-level 'org-outline-level)
3461 (when (and org-ellipsis
3462 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3463 (fboundp 'make-glyph-code))
3464 (unless org-display-table
3465 (setq org-display-table (make-display-table)))
3466 (set-display-table-slot
3467 org-display-table 4
3468 (vconcat (mapcar
3469 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3470 org-ellipsis)))
3471 (if (stringp org-ellipsis) org-ellipsis "..."))))
3472 (setq buffer-display-table org-display-table))
3473 (org-set-regexps-and-options)
3474 (when (and org-tag-faces (not org-tags-special-faces-re))
3475 ;; tag faces set outside customize.... force initialization.
3476 (org-set-tag-faces 'org-tag-faces org-tag-faces))
3477 ;; Calc embedded
3478 (org-set-local 'calc-embedded-open-mode "# ")
3479 (modify-syntax-entry ?# "<")
3480 (modify-syntax-entry ?@ "w")
3481 (if org-startup-truncated (setq truncate-lines t))
3482 (org-set-local 'font-lock-unfontify-region-function
3483 'org-unfontify-region)
3484 ;; Activate before-change-function
3485 (org-set-local 'org-table-may-need-update t)
3486 (org-add-hook 'before-change-functions 'org-before-change-function nil
3487 'local)
3488 ;; Check for running clock before killing a buffer
3489 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3490 ;; Paragraphs and auto-filling
3491 (org-set-autofill-regexps)
3492 (setq indent-line-function 'org-indent-line-function)
3493 (org-update-radio-target-regexp)
3495 ;; Comment characters
3496 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3497 (org-set-local 'comment-padding " ")
3499 ;; Align options lines
3500 (org-set-local
3501 'align-mode-rules-list
3502 '((org-in-buffer-settings
3503 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3504 (modes . '(org-mode)))))
3506 ;; Imenu
3507 (org-set-local 'imenu-create-index-function
3508 'org-imenu-get-tree)
3510 ;; Make isearch reveal context
3511 (if (or (featurep 'xemacs)
3512 (not (boundp 'outline-isearch-open-invisible-function)))
3513 ;; Emacs 21 and XEmacs make use of the hook
3514 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3515 ;; Emacs 22 deals with this through a special variable
3516 (org-set-local 'outline-isearch-open-invisible-function
3517 (lambda (&rest ignore) (org-show-context 'isearch))))
3519 ;; If empty file that did not turn on org-mode automatically, make it to.
3520 (if (and org-insert-mode-line-in-empty-file
3521 (interactive-p)
3522 (= (point-min) (point-max)))
3523 (insert "# -*- mode: org -*-\n\n"))
3525 (unless org-inhibit-startup
3526 (when org-startup-align-all-tables
3527 (let ((bmp (buffer-modified-p)))
3528 (org-table-map-tables 'org-table-align)
3529 (set-buffer-modified-p bmp)))
3530 (org-set-startup-visibility)))
3532 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3534 (defun org-current-time ()
3535 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3536 (if (> (car org-time-stamp-rounding-minutes) 1)
3537 (let ((r (car org-time-stamp-rounding-minutes))
3538 (time (decode-time)))
3539 (apply 'encode-time
3540 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3541 (nthcdr 2 time))))
3542 (current-time)))
3544 ;;;; Font-Lock stuff, including the activators
3546 (defvar org-mouse-map (make-sparse-keymap))
3547 (org-defkey org-mouse-map
3548 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3549 (org-defkey org-mouse-map
3550 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3551 (when org-mouse-1-follows-link
3552 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3553 (when org-tab-follows-link
3554 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3555 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3556 (when org-return-follows-link
3557 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
3558 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
3560 (require 'font-lock)
3562 (defconst org-non-link-chars "]\t\n\r<>")
3563 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3564 "shell" "elisp"))
3565 (defvar org-link-types-re nil
3566 "Matches a link that has a url-like prefix like \"http:\"")
3567 (defvar org-link-re-with-space nil
3568 "Matches a link with spaces, optional angular brackets around it.")
3569 (defvar org-link-re-with-space2 nil
3570 "Matches a link with spaces, optional angular brackets around it.")
3571 (defvar org-link-re-with-space3 nil
3572 "Matches a link with spaces, only for internal part in bracket links.")
3573 (defvar org-angle-link-re nil
3574 "Matches link with angular brackets, spaces are allowed.")
3575 (defvar org-plain-link-re nil
3576 "Matches plain link, without spaces.")
3577 (defvar org-bracket-link-regexp nil
3578 "Matches a link in double brackets.")
3579 (defvar org-bracket-link-analytic-regexp nil
3580 "Regular expression used to analyze links.
3581 Here is what the match groups contain after a match:
3582 1: http:
3583 2: http
3584 3: path
3585 4: [desc]
3586 5: desc")
3587 (defvar org-bracket-link-analytic-regexp++ nil
3588 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
3589 (defvar org-any-link-re nil
3590 "Regular expression matching any link.")
3592 (defun org-make-link-regexps ()
3593 "Update the link regular expressions.
3594 This should be called after the variable `org-link-types' has changed."
3595 (setq org-link-types-re
3596 (concat
3597 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3598 org-link-re-with-space
3599 (concat
3600 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3601 "\\([^" org-non-link-chars " ]"
3602 "[^" org-non-link-chars "]*"
3603 "[^" org-non-link-chars " ]\\)>?")
3604 org-link-re-with-space2
3605 (concat
3606 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3607 "\\([^" org-non-link-chars " ]"
3608 "[^\t\n\r]*"
3609 "[^" org-non-link-chars " ]\\)>?")
3610 org-link-re-with-space3
3611 (concat
3612 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3613 "\\([^" org-non-link-chars " ]"
3614 "[^\t\n\r]*\\)")
3615 org-angle-link-re
3616 (concat
3617 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3618 "\\([^" org-non-link-chars " ]"
3619 "[^" org-non-link-chars "]*"
3620 "\\)>")
3621 org-plain-link-re
3622 (concat
3623 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3624 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3625 org-bracket-link-regexp
3626 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3627 org-bracket-link-analytic-regexp
3628 (concat
3629 "\\[\\["
3630 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3631 "\\([^]]+\\)"
3632 "\\]"
3633 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3634 "\\]")
3635 org-bracket-link-analytic-regexp++
3636 (concat
3637 "\\[\\["
3638 "\\(\\(" (mapconcat 'identity (cons "coderef" org-link-types) "\\|") "\\):\\)?"
3639 "\\([^]]+\\)"
3640 "\\]"
3641 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3642 "\\]")
3643 org-any-link-re
3644 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3645 org-angle-link-re "\\)\\|\\("
3646 org-plain-link-re "\\)")))
3648 (org-make-link-regexps)
3650 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
3651 "Regular expression for fast time stamp matching.")
3652 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
3653 "Regular expression for fast time stamp matching.")
3654 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3655 "Regular expression matching time strings for analysis.
3656 This one does not require the space after the date, so it can be used
3657 on a string that terminates immediately after the date.")
3658 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3659 "Regular expression matching time strings for analysis.")
3660 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
3661 "Regular expression matching time stamps, with groups.")
3662 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
3663 "Regular expression matching time stamps (also [..]), with groups.")
3664 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3665 "Regular expression matching a time stamp range.")
3666 (defconst org-tr-regexp-both
3667 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3668 "Regular expression matching a time stamp range.")
3669 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3670 org-ts-regexp "\\)?")
3671 "Regular expression matching a time stamp or time stamp range.")
3672 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3673 org-ts-regexp-both "\\)?")
3674 "Regular expression matching a time stamp or time stamp range.
3675 The time stamps may be either active or inactive.")
3677 (defvar org-emph-face nil)
3679 (defun org-do-emphasis-faces (limit)
3680 "Run through the buffer and add overlays to links."
3681 (let (rtn)
3682 (while (and (not rtn) (re-search-forward org-emph-re limit t))
3683 (if (not (= (char-after (match-beginning 3))
3684 (char-after (match-beginning 4))))
3685 (progn
3686 (setq rtn t)
3687 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3688 'face
3689 (nth 1 (assoc (match-string 3)
3690 org-emphasis-alist)))
3691 (add-text-properties (match-beginning 2) (match-end 2)
3692 '(font-lock-multiline t))
3693 (when org-hide-emphasis-markers
3694 (add-text-properties (match-end 4) (match-beginning 5)
3695 '(invisible org-link))
3696 (add-text-properties (match-beginning 3) (match-end 3)
3697 '(invisible org-link)))))
3698 (backward-char 1))
3699 rtn))
3701 (defun org-emphasize (&optional char)
3702 "Insert or change an emphasis, i.e. a font like bold or italic.
3703 If there is an active region, change that region to a new emphasis.
3704 If there is no region, just insert the marker characters and position
3705 the cursor between them.
3706 CHAR should be either the marker character, or the first character of the
3707 HTML tag associated with that emphasis. If CHAR is a space, the means
3708 to remove the emphasis of the selected region.
3709 If char is not given (for example in an interactive call) it
3710 will be prompted for."
3711 (interactive)
3712 (let ((eal org-emphasis-alist) e det
3713 (erc org-emphasis-regexp-components)
3714 (prompt "")
3715 (string "") beg end move tag c s)
3716 (if (org-region-active-p)
3717 (setq beg (region-beginning) end (region-end)
3718 string (buffer-substring beg end))
3719 (setq move t))
3721 (while (setq e (pop eal))
3722 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
3723 c (aref tag 0))
3724 (push (cons c (string-to-char (car e))) det)
3725 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
3726 (substring tag 1)))))
3727 (setq det (nreverse det))
3728 (unless char
3729 (message "%s" (concat "Emphasis marker or tag:" prompt))
3730 (setq char (read-char-exclusive)))
3731 (setq char (or (cdr (assoc char det)) char))
3732 (if (equal char ?\ )
3733 (setq s "" move nil)
3734 (unless (assoc (char-to-string char) org-emphasis-alist)
3735 (error "No such emphasis marker: \"%c\"" char))
3736 (setq s (char-to-string char)))
3737 (while (and (> (length string) 1)
3738 (equal (substring string 0 1) (substring string -1))
3739 (assoc (substring string 0 1) org-emphasis-alist))
3740 (setq string (substring string 1 -1)))
3741 (setq string (concat s string s))
3742 (if beg (delete-region beg end))
3743 (unless (or (bolp)
3744 (string-match (concat "[" (nth 0 erc) "\n]")
3745 (char-to-string (char-before (point)))))
3746 (insert " "))
3747 (unless (string-match (concat "[" (nth 1 erc) "\n]")
3748 (char-to-string (char-after (point))))
3749 (insert " ") (backward-char 1))
3750 (insert string)
3751 (and move (backward-char 1))))
3753 (defconst org-nonsticky-props
3754 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
3757 (defun org-activate-plain-links (limit)
3758 "Run through the buffer and add overlays to links."
3759 (catch 'exit
3760 (let (f)
3761 (while (re-search-forward org-plain-link-re limit t)
3762 (setq f (get-text-property (match-beginning 0) 'face))
3763 (if (or (eq f 'org-tag)
3764 (and (listp f) (memq 'org-tag f)))
3766 (add-text-properties (match-beginning 0) (match-end 0)
3767 (list 'mouse-face 'highlight
3768 'rear-nonsticky org-nonsticky-props
3769 'keymap org-mouse-map
3771 (throw 'exit t))))))
3773 (defun org-activate-code (limit)
3774 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
3775 (progn
3776 (remove-text-properties (match-beginning 0) (match-end 0)
3777 '(display t invisible t intangible t))
3778 t)))
3780 (defun org-activate-angle-links (limit)
3781 "Run through the buffer and add overlays to links."
3782 (if (re-search-forward org-angle-link-re limit t)
3783 (progn
3784 (add-text-properties (match-beginning 0) (match-end 0)
3785 (list 'mouse-face 'highlight
3786 'rear-nonsticky org-nonsticky-props
3787 'keymap org-mouse-map
3789 t)))
3791 (defun org-activate-footnote-links (limit)
3792 "Run through the buffer and add overlays to links."
3793 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
3794 limit t)
3795 (progn
3796 (add-text-properties (match-beginning 2) (match-end 2)
3797 (list 'mouse-face 'highlight
3798 'rear-nonsticky org-nonsticky-props
3799 'keymap org-mouse-map
3800 'help-echo
3801 (if (= (point-at-bol) (match-beginning 2))
3802 "Footnote definition"
3803 "Footnote reference")
3805 t)))
3807 (defun org-activate-bracket-links (limit)
3808 "Run through the buffer and add overlays to bracketed links."
3809 (if (re-search-forward org-bracket-link-regexp limit t)
3810 (let* ((help (concat "LINK: "
3811 (org-match-string-no-properties 1)))
3812 ;; FIXME: above we should remove the escapes.
3813 ;; but that requires another match, protecting match data,
3814 ;; a lot of overhead for font-lock.
3815 (ip (org-maybe-intangible
3816 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
3817 'keymap org-mouse-map 'mouse-face 'highlight
3818 'font-lock-multiline t 'help-echo help)))
3819 (vp (list 'rear-nonsticky org-nonsticky-props
3820 'keymap org-mouse-map 'mouse-face 'highlight
3821 ' font-lock-multiline t 'help-echo help)))
3822 ;; We need to remove the invisible property here. Table narrowing
3823 ;; may have made some of this invisible.
3824 (remove-text-properties (match-beginning 0) (match-end 0)
3825 '(invisible nil))
3826 (if (match-end 3)
3827 (progn
3828 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3829 (add-text-properties (match-beginning 3) (match-end 3) vp)
3830 (add-text-properties (match-end 3) (match-end 0) ip))
3831 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3832 (add-text-properties (match-beginning 1) (match-end 1) vp)
3833 (add-text-properties (match-end 1) (match-end 0) ip))
3834 t)))
3836 (defun org-activate-dates (limit)
3837 "Run through the buffer and add overlays to dates."
3838 (if (re-search-forward org-tsr-regexp-both limit t)
3839 (progn
3840 (add-text-properties (match-beginning 0) (match-end 0)
3841 (list 'mouse-face 'highlight
3842 'rear-nonsticky org-nonsticky-props
3843 'keymap org-mouse-map))
3844 (when org-display-custom-times
3845 (if (match-end 3)
3846 (org-display-custom-time (match-beginning 3) (match-end 3)))
3847 (org-display-custom-time (match-beginning 1) (match-end 1)))
3848 t)))
3850 (defvar org-target-link-regexp nil
3851 "Regular expression matching radio targets in plain text.")
3852 (make-variable-buffer-local 'org-target-link-regexp)
3853 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3854 "Regular expression matching a link target.")
3855 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3856 "Regular expression matching a radio target.")
3857 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
3858 "Regular expression matching any target.")
3860 (defun org-activate-target-links (limit)
3861 "Run through the buffer and add overlays to target matches."
3862 (when org-target-link-regexp
3863 (let ((case-fold-search t))
3864 (if (re-search-forward org-target-link-regexp limit t)
3865 (progn
3866 (add-text-properties (match-beginning 0) (match-end 0)
3867 (list 'mouse-face 'highlight
3868 'rear-nonsticky org-nonsticky-props
3869 'keymap org-mouse-map
3870 'help-echo "Radio target link"
3871 'org-linked-text t))
3872 t)))))
3874 (defun org-update-radio-target-regexp ()
3875 "Find all radio targets in this file and update the regular expression."
3876 (interactive)
3877 (when (memq 'radio org-activate-links)
3878 (setq org-target-link-regexp
3879 (org-make-target-link-regexp (org-all-targets 'radio)))
3880 (org-restart-font-lock)))
3882 (defun org-hide-wide-columns (limit)
3883 (let (s e)
3884 (setq s (text-property-any (point) (or limit (point-max))
3885 'org-cwidth t))
3886 (when s
3887 (setq e (next-single-property-change s 'org-cwidth))
3888 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
3889 (goto-char e)
3890 t)))
3892 (defvar org-latex-and-specials-regexp nil
3893 "Regular expression for highlighting export special stuff.")
3894 (defvar org-match-substring-regexp)
3895 (defvar org-match-substring-with-braces-regexp)
3896 (defvar org-export-html-special-string-regexps)
3898 (defun org-compute-latex-and-specials-regexp ()
3899 "Compute regular expression for stuff treated specially by exporters."
3900 (if (not org-highlight-latex-fragments-and-specials)
3901 (org-set-local 'org-latex-and-specials-regexp nil)
3902 (require 'org-exp)
3903 (let*
3904 ((matchers (plist-get org-format-latex-options :matchers))
3905 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
3906 org-latex-regexps)))
3907 (options (org-combine-plists (org-default-export-plist)
3908 (org-infile-export-plist)))
3909 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
3910 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
3911 (org-export-with-TeX-macros (plist-get options :TeX-macros))
3912 (org-export-html-expand (plist-get options :expand-quoted-html))
3913 (org-export-with-special-strings (plist-get options :special-strings))
3914 (re-sub
3915 (cond
3916 ((equal org-export-with-sub-superscripts '{})
3917 (list org-match-substring-with-braces-regexp))
3918 (org-export-with-sub-superscripts
3919 (list org-match-substring-regexp))
3920 (t nil)))
3921 (re-latex
3922 (if org-export-with-LaTeX-fragments
3923 (mapcar (lambda (x) (nth 1 x)) latexs)))
3924 (re-macros
3925 (if org-export-with-TeX-macros
3926 (list (concat "\\\\"
3927 (regexp-opt
3928 (append (mapcar 'car org-html-entities)
3929 (if (boundp 'org-latex-entities)
3930 org-latex-entities nil))
3931 'words))) ; FIXME
3933 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
3934 (re-special (if org-export-with-special-strings
3935 (mapcar (lambda (x) (car x))
3936 org-export-html-special-string-regexps)))
3937 (re-rest
3938 (delq nil
3939 (list
3940 (if org-export-html-expand "@<[^>\n]+>")
3941 ))))
3942 (org-set-local
3943 'org-latex-and-specials-regexp
3944 (mapconcat 'identity (append re-latex re-sub re-macros re-special
3945 re-rest) "\\|")))))
3947 (defun org-do-latex-and-special-faces (limit)
3948 "Run through the buffer and add overlays to links."
3949 (when org-latex-and-specials-regexp
3950 (let (rtn d)
3951 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
3952 limit t))
3953 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
3954 'face))
3955 '(org-code org-verbatim underline)))
3956 (progn
3957 (setq rtn t
3958 d (cond ((member (char-after (1+ (match-beginning 0)))
3959 '(?_ ?^)) 1)
3960 (t 0)))
3961 (font-lock-prepend-text-property
3962 (+ d (match-beginning 0)) (match-end 0)
3963 'face 'org-latex-and-export-specials)
3964 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
3965 '(font-lock-multiline t)))))
3966 rtn)))
3968 (defun org-restart-font-lock ()
3969 "Restart font-lock-mode, to force refontification."
3970 (when (and (boundp 'font-lock-mode) font-lock-mode)
3971 (font-lock-mode -1)
3972 (font-lock-mode 1)))
3974 (defun org-all-targets (&optional radio)
3975 "Return a list of all targets in this file.
3976 With optional argument RADIO, only find radio targets."
3977 (let ((re (if radio org-radio-target-regexp org-target-regexp))
3978 rtn)
3979 (save-excursion
3980 (goto-char (point-min))
3981 (while (re-search-forward re nil t)
3982 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
3983 rtn)))
3985 (defun org-make-target-link-regexp (targets)
3986 "Make regular expression matching all strings in TARGETS.
3987 The regular expression finds the targets also if there is a line break
3988 between words."
3989 (and targets
3990 (concat
3991 "\\<\\("
3992 (mapconcat
3993 (lambda (x)
3994 (while (string-match " +" x)
3995 (setq x (replace-match "\\s-+" t t x)))
3997 targets
3998 "\\|")
3999 "\\)\\>")))
4001 (defun org-activate-tags (limit)
4002 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
4003 (progn
4004 (add-text-properties (match-beginning 1) (match-end 1)
4005 (list 'mouse-face 'highlight
4006 'rear-nonsticky org-nonsticky-props
4007 'keymap org-mouse-map))
4008 t)))
4010 (defun org-outline-level ()
4011 (save-excursion
4012 (looking-at outline-regexp)
4013 (if (match-beginning 1)
4014 (+ (org-get-string-indentation (match-string 1)) 1000)
4015 (1- (- (match-end 0) (match-beginning 0))))))
4017 (defvar org-font-lock-keywords nil)
4019 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
4020 "Regular expression matching a property line.")
4022 (defvar org-font-lock-hook nil
4023 "Functions to be called for special font lock stuff.")
4025 (defun org-font-lock-hook (limit)
4026 (run-hook-with-args 'org-font-lock-hook limit))
4028 (defun org-set-font-lock-defaults ()
4029 (let* ((em org-fontify-emphasized-text)
4030 (lk org-activate-links)
4031 (org-font-lock-extra-keywords
4032 (list
4033 ;; Call the hook
4034 '(org-font-lock-hook)
4035 ;; Headlines
4036 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
4037 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
4038 ;; Table lines
4039 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4040 (1 'org-table t))
4041 ;; Table internals
4042 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4043 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4044 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4045 ;; Drawers
4046 (list org-drawer-regexp '(0 'org-special-keyword t))
4047 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4048 ;; Properties
4049 (list org-property-re
4050 '(1 'org-special-keyword t)
4051 '(3 'org-property-value t))
4052 (if org-format-transports-properties-p
4053 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
4054 ;; Links
4055 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4056 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4057 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
4058 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4059 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4060 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4061 (if (memq 'footnote lk) '(org-activate-footnote-links
4062 (2 'org-footnote t)))
4063 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4064 '(org-hide-wide-columns (0 nil append))
4065 ;; TODO lines
4066 (list (concat "^\\*+[ \t]+" org-todo-regexp)
4067 '(1 (org-get-todo-face 1) t))
4068 ;; DONE
4069 (if org-fontify-done-headline
4070 (list (concat "^[*]+ +\\<\\("
4071 (mapconcat 'regexp-quote org-done-keywords "\\|")
4072 "\\)\\(.*\\)")
4073 '(2 'org-headline-done t))
4074 nil)
4075 ;; Priorities
4076 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
4077 ;; Tags
4078 '(org-font-lock-add-tag-faces)
4079 ;; Special keywords
4080 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4081 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4082 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4083 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4084 ;; Emphasis
4085 (if em
4086 (if (featurep 'xemacs)
4087 '(org-do-emphasis-faces (0 nil append))
4088 '(org-do-emphasis-faces)))
4089 ;; Checkboxes
4090 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
4091 2 'bold prepend)
4092 (if org-provide-checkbox-statistics
4093 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4094 (0 (org-get-checkbox-statistics-face) t)))
4095 ;; Description list items
4096 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
4097 2 'bold prepend)
4098 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
4099 '(1 'org-archived prepend))
4100 ;; Specials
4101 '(org-do-latex-and-special-faces)
4102 ;; Code
4103 '(org-activate-code (1 'org-code t))
4104 ;; COMMENT
4105 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
4106 "\\|" org-quote-string "\\)\\>")
4107 '(1 'org-special-keyword t))
4108 '("^#.*" (0 'font-lock-comment-face t))
4110 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
4111 ;; Now set the full font-lock-keywords
4112 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
4113 (org-set-local 'font-lock-defaults
4114 '(org-font-lock-keywords t nil nil backward-paragraph))
4115 (kill-local-variable 'font-lock-keywords) nil))
4117 (defvar org-m nil)
4118 (defvar org-l nil)
4119 (defvar org-f nil)
4120 (defun org-get-level-face (n)
4121 "Get the right face for match N in font-lock matching of headlines."
4122 (setq org-l (- (match-end 2) (match-beginning 1) 1))
4123 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
4124 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
4125 (cond
4126 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
4127 ((eq n 2) org-f)
4128 (t (if org-level-color-stars-only nil org-f))))
4130 (defun org-get-todo-face (kwd)
4131 "Get the right face for a TODO keyword KWD.
4132 If KWD is a number, get the corresponding match group."
4133 (if (numberp kwd) (setq kwd (match-string kwd)))
4134 (or (cdr (assoc kwd org-todo-keyword-faces))
4135 (and (member kwd org-done-keywords) 'org-done)
4136 'org-todo))
4138 (defun org-font-lock-add-tag-faces (limit)
4139 "Add the special tag faces."
4140 (when (and org-tag-faces org-tags-special-faces-re)
4141 (while (re-search-forward org-tags-special-faces-re limit t)
4142 (add-text-properties (match-beginning 1) (match-end 1)
4143 (list 'face (org-get-tag-face 1)
4144 'font-lock-fontified t))
4145 (backward-char 1))))
4147 (defun org-get-tag-face (kwd)
4148 "Get the right face for a TODO keyword KWD.
4149 If KWD is a number, get the corresponding match group."
4150 (if (numberp kwd) (setq kwd (match-string kwd)))
4151 (or (cdr (assoc kwd org-tag-faces))
4152 'org-tag))
4154 (defun org-unfontify-region (beg end &optional maybe_loudly)
4155 "Remove fontification and activation overlays from links."
4156 (font-lock-default-unfontify-region beg end)
4157 (let* ((buffer-undo-list t)
4158 (inhibit-read-only t) (inhibit-point-motion-hooks t)
4159 (inhibit-modification-hooks t)
4160 deactivate-mark buffer-file-name buffer-file-truename)
4161 (remove-text-properties beg end
4162 '(mouse-face t keymap t org-linked-text t
4163 invisible t intangible t))))
4165 ;;;; Visibility cycling, including org-goto and indirect buffer
4167 ;;; Cycling
4169 (defvar org-cycle-global-status nil)
4170 (make-variable-buffer-local 'org-cycle-global-status)
4171 (defvar org-cycle-subtree-status nil)
4172 (make-variable-buffer-local 'org-cycle-subtree-status)
4174 ;;;###autoload
4175 (defun org-cycle (&optional arg)
4176 "Visibility cycling for Org-mode.
4178 - When this function is called with a prefix argument, rotate the entire
4179 buffer through 3 states (global cycling)
4180 1. OVERVIEW: Show only top-level headlines.
4181 2. CONTENTS: Show all headlines of all levels, but no body text.
4182 3. SHOW ALL: Show everything.
4183 When called with two C-u C-u prefixes, switch to the startup visibility,
4184 determined by the variable `org-startup-folded', and by any VISIBILITY
4185 properties in the buffer.
4186 When called with three C-u C-u C-u prefixed, show the entire buffer,
4187 including drawers.
4189 - When point is at the beginning of a headline, rotate the subtree started
4190 by this line through 3 different states (local cycling)
4191 1. FOLDED: Only the main headline is shown.
4192 2. CHILDREN: The main headline and the direct children are shown.
4193 From this state, you can move to one of the children
4194 and zoom in further.
4195 3. SUBTREE: Show the entire subtree, including body text.
4197 - When there is a numeric prefix, go up to a heading with level ARG, do
4198 a `show-subtree' and return to the previous cursor position. If ARG
4199 is negative, go up that many levels.
4201 - When point is not at the beginning of a headline, execute the global
4202 binding for TAB, which is re-indenting the line. See the option
4203 `org-cycle-emulate-tab' for details.
4205 - Special case: if point is at the beginning of the buffer and there is
4206 no headline in line 1, this function will act as if called with prefix arg.
4207 But only if also the variable `org-cycle-global-at-bob' is t."
4208 (interactive "P")
4209 (org-load-modules-maybe)
4210 (let* ((outline-regexp
4211 (if (and (org-mode-p) org-cycle-include-plain-lists)
4212 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
4213 outline-regexp))
4214 (bob-special (and org-cycle-global-at-bob (bobp)
4215 (not (looking-at outline-regexp))))
4216 (org-cycle-hook
4217 (if bob-special
4218 (delq 'org-optimize-window-after-visibility-change
4219 (copy-sequence org-cycle-hook))
4220 org-cycle-hook))
4221 (pos (point)))
4223 (if (or bob-special (equal arg '(4)))
4224 ;; special case: use global cycling
4225 (setq arg t))
4227 (cond
4229 ((equal arg '(16))
4230 (org-set-startup-visibility)
4231 (message "Startup visibility, plus VISIBILITY properties"))
4233 ((equal arg '(64))
4234 (show-all)
4235 (message "Entire buffer visible, including drawers"))
4237 ((org-at-table-p 'any)
4238 ;; Enter the table or move to the next field in the table
4239 (or (org-table-recognize-table.el)
4240 (progn
4241 (if arg (org-table-edit-field t)
4242 (org-table-justify-field-maybe)
4243 (call-interactively 'org-table-next-field)))))
4245 ((eq arg t) ;; Global cycling
4247 (cond
4248 ((and (eq last-command this-command)
4249 (eq org-cycle-global-status 'overview))
4250 ;; We just created the overview - now do table of contents
4251 ;; This can be slow in very large buffers, so indicate action
4252 (message "CONTENTS...")
4253 (org-content)
4254 (message "CONTENTS...done")
4255 (setq org-cycle-global-status 'contents)
4256 (run-hook-with-args 'org-cycle-hook 'contents))
4258 ((and (eq last-command this-command)
4259 (eq org-cycle-global-status 'contents))
4260 ;; We just showed the table of contents - now show everything
4261 (show-all)
4262 (message "SHOW ALL")
4263 (setq org-cycle-global-status 'all)
4264 (run-hook-with-args 'org-cycle-hook 'all))
4267 ;; Default action: go to overview
4268 (org-overview)
4269 (message "OVERVIEW")
4270 (setq org-cycle-global-status 'overview)
4271 (run-hook-with-args 'org-cycle-hook 'overview))))
4273 ((and org-drawers org-drawer-regexp
4274 (save-excursion
4275 (beginning-of-line 1)
4276 (looking-at org-drawer-regexp)))
4277 ;; Toggle block visibility
4278 (org-flag-drawer
4279 (not (get-char-property (match-end 0) 'invisible))))
4281 ((integerp arg)
4282 ;; Show-subtree, ARG levels up from here.
4283 (save-excursion
4284 (org-back-to-heading)
4285 (outline-up-heading (if (< arg 0) (- arg)
4286 (- (funcall outline-level) arg)))
4287 (org-show-subtree)))
4289 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4290 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4291 ;; At a heading: rotate between three different views
4292 (org-back-to-heading)
4293 (let ((goal-column 0) eoh eol eos)
4294 ;; First, some boundaries
4295 (save-excursion
4296 (org-back-to-heading)
4297 (save-excursion
4298 (beginning-of-line 2)
4299 (while (and (not (eobp)) ;; this is like `next-line'
4300 (get-char-property (1- (point)) 'invisible))
4301 (beginning-of-line 2)) (setq eol (point)))
4302 (outline-end-of-heading) (setq eoh (point))
4303 (org-end-of-subtree t)
4304 (unless (eobp)
4305 (skip-chars-forward " \t\n")
4306 (beginning-of-line 1) ; in case this is an item
4308 (setq eos (1- (point))))
4309 ;; Find out what to do next and set `this-command'
4310 (cond
4311 ((= eos eoh)
4312 ;; Nothing is hidden behind this heading
4313 (message "EMPTY ENTRY")
4314 (setq org-cycle-subtree-status nil)
4315 (save-excursion
4316 (goto-char eos)
4317 (outline-next-heading)
4318 (if (org-invisible-p) (org-flag-heading nil))))
4319 ((or (>= eol eos)
4320 (not (string-match "\\S-" (buffer-substring eol eos))))
4321 ;; Entire subtree is hidden in one line: open it
4322 (org-show-entry)
4323 (show-children)
4324 (message "CHILDREN")
4325 (save-excursion
4326 (goto-char eos)
4327 (outline-next-heading)
4328 (if (org-invisible-p) (org-flag-heading nil)))
4329 (setq org-cycle-subtree-status 'children)
4330 (run-hook-with-args 'org-cycle-hook 'children))
4331 ((and (eq last-command this-command)
4332 (eq org-cycle-subtree-status 'children))
4333 ;; We just showed the children, now show everything.
4334 (org-show-subtree)
4335 (message "SUBTREE")
4336 (setq org-cycle-subtree-status 'subtree)
4337 (run-hook-with-args 'org-cycle-hook 'subtree))
4339 ;; Default action: hide the subtree.
4340 (hide-subtree)
4341 (message "FOLDED")
4342 (setq org-cycle-subtree-status 'folded)
4343 (run-hook-with-args 'org-cycle-hook 'folded)))))
4345 ;; TAB emulation and template completion
4346 (buffer-read-only (org-back-to-heading))
4348 ((org-try-structure-completion))
4350 ((org-try-cdlatex-tab))
4352 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4353 (or (not (bolp))
4354 (not (looking-at outline-regexp))))
4355 (call-interactively (global-key-binding "\t")))
4357 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4358 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4359 (or (and (eq org-cycle-emulate-tab 'white)
4360 (= (match-end 0) (point-at-eol)))
4361 (and (eq org-cycle-emulate-tab 'whitestart)
4362 (>= (match-end 0) pos))))
4364 (eq org-cycle-emulate-tab t))
4365 (call-interactively (global-key-binding "\t")))
4367 (t (save-excursion
4368 (org-back-to-heading)
4369 (org-cycle))))))
4371 ;;;###autoload
4372 (defun org-global-cycle (&optional arg)
4373 "Cycle the global visibility. For details see `org-cycle'.
4374 With C-u prefix arg, switch to startup visibility.
4375 With a numeric prefix, show all headlines up to that level."
4376 (interactive "P")
4377 (let ((org-cycle-include-plain-lists
4378 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4379 (cond
4380 ((integerp arg)
4381 (show-all)
4382 (hide-sublevels arg)
4383 (setq org-cycle-global-status 'contents))
4384 ((equal arg '(4))
4385 (org-set-startup-visibility)
4386 (message "Startup visibility, plus VISIBILITY properties."))
4388 (org-cycle '(4))))))
4390 (defun org-set-startup-visibility ()
4391 "Set the visibility required by startup options and properties."
4392 (cond
4393 ((eq org-startup-folded t)
4394 (org-cycle '(4)))
4395 ((eq org-startup-folded 'content)
4396 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4397 (org-cycle '(4)) (org-cycle '(4)))))
4398 (org-set-visibility-according-to-property 'no-cleanup)
4399 (org-cycle-hide-archived-subtrees 'all)
4400 (org-cycle-hide-drawers 'all)
4401 (org-cycle-show-empty-lines 'all))
4403 (defun org-set-visibility-according-to-property (&optional no-cleanup)
4404 "Switch subtree visibilities according to :VISIBILITY: property."
4405 (interactive)
4406 (let (state)
4407 (save-excursion
4408 (goto-char (point-min))
4409 (while (re-search-forward
4410 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
4411 nil t)
4412 (setq state (match-string 1))
4413 (save-excursion
4414 (org-back-to-heading t)
4415 (hide-subtree)
4416 (org-reveal)
4417 (cond
4418 ((equal state '("fold" "folded"))
4419 (hide-subtree))
4420 ((equal state "children")
4421 (org-show-hidden-entry)
4422 (show-children))
4423 ((equal state "content")
4424 (save-excursion
4425 (save-restriction
4426 (org-narrow-to-subtree)
4427 (org-content))))
4428 ((member state '("all" "showall"))
4429 (show-subtree)))))
4430 (unless no-cleanup
4431 (org-cycle-hide-archived-subtrees 'all)
4432 (org-cycle-hide-drawers 'all)
4433 (org-cycle-show-empty-lines 'all)))))
4435 (defun org-overview ()
4436 "Switch to overview mode, showing only top-level headlines.
4437 Really, this shows all headlines with level equal or greater than the level
4438 of the first headline in the buffer. This is important, because if the
4439 first headline is not level one, then (hide-sublevels 1) gives confusing
4440 results."
4441 (interactive)
4442 (let ((level (save-excursion
4443 (goto-char (point-min))
4444 (if (re-search-forward (concat "^" outline-regexp) nil t)
4445 (progn
4446 (goto-char (match-beginning 0))
4447 (funcall outline-level))))))
4448 (and level (hide-sublevels level))))
4450 (defun org-content (&optional arg)
4451 "Show all headlines in the buffer, like a table of contents.
4452 With numerical argument N, show content up to level N."
4453 (interactive "P")
4454 (save-excursion
4455 ;; Visit all headings and show their offspring
4456 (and (integerp arg) (org-overview))
4457 (goto-char (point-max))
4458 (catch 'exit
4459 (while (and (progn (condition-case nil
4460 (outline-previous-visible-heading 1)
4461 (error (goto-char (point-min))))
4463 (looking-at outline-regexp))
4464 (if (integerp arg)
4465 (show-children (1- arg))
4466 (show-branches))
4467 (if (bobp) (throw 'exit nil))))))
4470 (defun org-optimize-window-after-visibility-change (state)
4471 "Adjust the window after a change in outline visibility.
4472 This function is the default value of the hook `org-cycle-hook'."
4473 (when (get-buffer-window (current-buffer))
4474 (cond
4475 ; ((eq state 'overview) (org-first-headline-recenter 1))
4476 ; ((eq state 'overview) (org-beginning-of-line))
4477 ((eq state 'content) nil)
4478 ((eq state 'all) nil)
4479 ((eq state 'folded) nil)
4480 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4481 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4483 (defun org-compact-display-after-subtree-move ()
4484 (let (beg end)
4485 (save-excursion
4486 (if (org-up-heading-safe)
4487 (progn
4488 (hide-subtree)
4489 (show-entry)
4490 (show-children)
4491 (org-cycle-show-empty-lines 'children)
4492 (org-cycle-hide-drawers 'children))
4493 (org-overview)))))
4495 (defun org-cycle-show-empty-lines (state)
4496 "Show empty lines above all visible headlines.
4497 The region to be covered depends on STATE when called through
4498 `org-cycle-hook'. Lisp program can use t for STATE to get the
4499 entire buffer covered. Note that an empty line is only shown if there
4500 are at least `org-cycle-separator-lines' empty lines before the headline."
4501 (when (> org-cycle-separator-lines 0)
4502 (save-excursion
4503 (let* ((n org-cycle-separator-lines)
4504 (re (cond
4505 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
4506 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
4507 (t (let ((ns (number-to-string (- n 2))))
4508 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
4509 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
4510 beg end)
4511 (cond
4512 ((memq state '(overview contents t))
4513 (setq beg (point-min) end (point-max)))
4514 ((memq state '(children folded))
4515 (setq beg (point) end (progn (org-end-of-subtree t t)
4516 (beginning-of-line 2)
4517 (point)))))
4518 (when beg
4519 (goto-char beg)
4520 (while (re-search-forward re end t)
4521 (if (not (get-char-property (match-end 1) 'invisible))
4522 (outline-flag-region
4523 (match-beginning 1) (match-end 1) nil)))))))
4524 ;; Never hide empty lines at the end of the file.
4525 (save-excursion
4526 (goto-char (point-max))
4527 (outline-previous-heading)
4528 (outline-end-of-heading)
4529 (if (and (looking-at "[ \t\n]+")
4530 (= (match-end 0) (point-max)))
4531 (outline-flag-region (point) (match-end 0) nil))))
4533 (defun org-show-empty-lines-in-parent ()
4534 "Move to the parent and re-show empty lines before visible headlines."
4535 (save-excursion
4536 (let ((context (if (org-up-heading-safe) 'children 'overview)))
4537 (org-cycle-show-empty-lines context))))
4539 (defun org-cycle-hide-drawers (state)
4540 "Re-hide all drawers after a visibility state change."
4541 (when (and (org-mode-p)
4542 (not (memq state '(overview folded))))
4543 (save-excursion
4544 (let* ((globalp (memq state '(contents all)))
4545 (beg (if globalp (point-min) (point)))
4546 (end (if globalp (point-max) (org-end-of-subtree t))))
4547 (goto-char beg)
4548 (while (re-search-forward org-drawer-regexp end t)
4549 (org-flag-drawer t))))))
4551 (defun org-flag-drawer (flag)
4552 (save-excursion
4553 (beginning-of-line 1)
4554 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
4555 (let ((b (match-end 0))
4556 (outline-regexp org-outline-regexp))
4557 (if (re-search-forward
4558 "^[ \t]*:END:"
4559 (save-excursion (outline-next-heading) (point)) t)
4560 (outline-flag-region b (point-at-eol) flag)
4561 (error ":END: line missing"))))))
4563 (defun org-subtree-end-visible-p ()
4564 "Is the end of the current subtree visible?"
4565 (pos-visible-in-window-p
4566 (save-excursion (org-end-of-subtree t) (point))))
4568 (defun org-first-headline-recenter (&optional N)
4569 "Move cursor to the first headline and recenter the headline.
4570 Optional argument N means, put the headline into the Nth line of the window."
4571 (goto-char (point-min))
4572 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4573 (beginning-of-line)
4574 (recenter (prefix-numeric-value N))))
4576 ;;; Org-goto
4578 (defvar org-goto-window-configuration nil)
4579 (defvar org-goto-marker nil)
4580 (defvar org-goto-map
4581 (let ((map (make-sparse-keymap)))
4582 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
4583 (while (setq cmd (pop cmds))
4584 (substitute-key-definition cmd cmd map global-map)))
4585 (suppress-keymap map)
4586 (org-defkey map "\C-m" 'org-goto-ret)
4587 (org-defkey map [(return)] 'org-goto-ret)
4588 (org-defkey map [(left)] 'org-goto-left)
4589 (org-defkey map [(right)] 'org-goto-right)
4590 (org-defkey map [(control ?g)] 'org-goto-quit)
4591 (org-defkey map "\C-i" 'org-cycle)
4592 (org-defkey map [(tab)] 'org-cycle)
4593 (org-defkey map [(down)] 'outline-next-visible-heading)
4594 (org-defkey map [(up)] 'outline-previous-visible-heading)
4595 (if org-goto-auto-isearch
4596 (if (fboundp 'define-key-after)
4597 (define-key-after map [t] 'org-goto-local-auto-isearch)
4598 nil)
4599 (org-defkey map "q" 'org-goto-quit)
4600 (org-defkey map "n" 'outline-next-visible-heading)
4601 (org-defkey map "p" 'outline-previous-visible-heading)
4602 (org-defkey map "f" 'outline-forward-same-level)
4603 (org-defkey map "b" 'outline-backward-same-level)
4604 (org-defkey map "u" 'outline-up-heading))
4605 (org-defkey map "/" 'org-occur)
4606 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4607 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4608 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
4609 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
4610 (org-defkey map "\C-c\C-u" 'outline-up-heading)
4611 map))
4613 (defconst org-goto-help
4614 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4615 RET=jump to location [Q]uit and return to previous location
4616 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4618 (defvar org-goto-start-pos) ; dynamically scoped parameter
4620 ;; FIXME: Docstring doe not mention both interfaces
4621 (defun org-goto (&optional alternative-interface)
4622 "Look up a different location in the current file, keeping current visibility.
4624 When you want look-up or go to a different location in a document, the
4625 fastest way is often to fold the entire buffer and then dive into the tree.
4626 This method has the disadvantage, that the previous location will be folded,
4627 which may not be what you want.
4629 This command works around this by showing a copy of the current buffer
4630 in an indirect buffer, in overview mode. You can dive into the tree in
4631 that copy, use org-occur and incremental search to find a location.
4632 When pressing RET or `Q', the command returns to the original buffer in
4633 which the visibility is still unchanged. After RET is will also jump to
4634 the location selected in the indirect buffer and expose the
4635 the headline hierarchy above."
4636 (interactive "P")
4637 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
4638 (org-refile-use-outline-path t)
4639 (interface
4640 (if (not alternative-interface)
4641 org-goto-interface
4642 (if (eq org-goto-interface 'outline)
4643 'outline-path-completion
4644 'outline)))
4645 (org-goto-start-pos (point))
4646 (selected-point
4647 (if (eq interface 'outline)
4648 (car (org-get-location (current-buffer) org-goto-help))
4649 (nth 3 (org-refile-get-location "Goto: ")))))
4650 (if selected-point
4651 (progn
4652 (org-mark-ring-push org-goto-start-pos)
4653 (goto-char selected-point)
4654 (if (or (org-invisible-p) (org-invisible-p2))
4655 (org-show-context 'org-goto)))
4656 (message "Quit"))))
4658 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
4659 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
4660 (defvar org-goto-local-auto-isearch-map) ; defined below
4662 (defun org-get-location (buf help)
4663 "Let the user select a location in the Org-mode buffer BUF.
4664 This function uses a recursive edit. It returns the selected position
4665 or nil."
4666 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
4667 (isearch-hide-immediately nil)
4668 (isearch-search-fun-function
4669 (lambda () 'org-goto-local-search-headings))
4670 (org-goto-selected-point org-goto-exit-command))
4671 (save-excursion
4672 (save-window-excursion
4673 (delete-other-windows)
4674 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
4675 (switch-to-buffer
4676 (condition-case nil
4677 (make-indirect-buffer (current-buffer) "*org-goto*")
4678 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
4679 (with-output-to-temp-buffer "*Help*"
4680 (princ help))
4681 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
4682 (setq buffer-read-only nil)
4683 (let ((org-startup-truncated t)
4684 (org-startup-folded nil)
4685 (org-startup-align-all-tables nil))
4686 (org-mode)
4687 (org-overview))
4688 (setq buffer-read-only t)
4689 (if (and (boundp 'org-goto-start-pos)
4690 (integer-or-marker-p org-goto-start-pos))
4691 (let ((org-show-hierarchy-above t)
4692 (org-show-siblings t)
4693 (org-show-following-heading t))
4694 (goto-char org-goto-start-pos)
4695 (and (org-invisible-p) (org-show-context)))
4696 (goto-char (point-min)))
4697 (org-beginning-of-line)
4698 (message "Select location and press RET")
4699 (use-local-map org-goto-map)
4700 (recursive-edit)
4702 (kill-buffer "*org-goto*")
4703 (cons org-goto-selected-point org-goto-exit-command)))
4705 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
4706 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
4707 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
4708 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
4710 (defun org-goto-local-search-headings (string bound noerror)
4711 "Search and make sure that any matches are in headlines."
4712 (catch 'return
4713 (while (if isearch-forward
4714 (search-forward string bound noerror)
4715 (search-backward string bound noerror))
4716 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
4717 (and (member :headline context)
4718 (not (member :tags context))))
4719 (throw 'return (point))))))
4721 (defun org-goto-local-auto-isearch ()
4722 "Start isearch."
4723 (interactive)
4724 (goto-char (point-min))
4725 (let ((keys (this-command-keys)))
4726 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
4727 (isearch-mode t)
4728 (isearch-process-search-char (string-to-char keys)))))
4730 (defun org-goto-ret (&optional arg)
4731 "Finish `org-goto' by going to the new location."
4732 (interactive "P")
4733 (setq org-goto-selected-point (point)
4734 org-goto-exit-command 'return)
4735 (throw 'exit nil))
4737 (defun org-goto-left ()
4738 "Finish `org-goto' by going to the new location."
4739 (interactive)
4740 (if (org-on-heading-p)
4741 (progn
4742 (beginning-of-line 1)
4743 (setq org-goto-selected-point (point)
4744 org-goto-exit-command 'left)
4745 (throw 'exit nil))
4746 (error "Not on a heading")))
4748 (defun org-goto-right ()
4749 "Finish `org-goto' by going to the new location."
4750 (interactive)
4751 (if (org-on-heading-p)
4752 (progn
4753 (setq org-goto-selected-point (point)
4754 org-goto-exit-command 'right)
4755 (throw 'exit nil))
4756 (error "Not on a heading")))
4758 (defun org-goto-quit ()
4759 "Finish `org-goto' without cursor motion."
4760 (interactive)
4761 (setq org-goto-selected-point nil)
4762 (setq org-goto-exit-command 'quit)
4763 (throw 'exit nil))
4765 ;;; Indirect buffer display of subtrees
4767 (defvar org-indirect-dedicated-frame nil
4768 "This is the frame being used for indirect tree display.")
4769 (defvar org-last-indirect-buffer nil)
4771 (defun org-tree-to-indirect-buffer (&optional arg)
4772 "Create indirect buffer and narrow it to current subtree.
4773 With numerical prefix ARG, go up to this level and then take that tree.
4774 If ARG is negative, go up that many levels.
4775 If `org-indirect-buffer-display' is not `new-frame', the command removes the
4776 indirect buffer previously made with this command, to avoid proliferation of
4777 indirect buffers. However, when you call the command with a `C-u' prefix, or
4778 when `org-indirect-buffer-display' is `new-frame', the last buffer
4779 is kept so that you can work with several indirect buffers at the same time.
4780 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
4781 requests that a new frame be made for the new buffer, so that the dedicated
4782 frame is not changed."
4783 (interactive "P")
4784 (let ((cbuf (current-buffer))
4785 (cwin (selected-window))
4786 (pos (point))
4787 beg end level heading ibuf)
4788 (save-excursion
4789 (org-back-to-heading t)
4790 (when (numberp arg)
4791 (setq level (org-outline-level))
4792 (if (< arg 0) (setq arg (+ level arg)))
4793 (while (> (setq level (org-outline-level)) arg)
4794 (outline-up-heading 1 t)))
4795 (setq beg (point)
4796 heading (org-get-heading))
4797 (org-end-of-subtree t) (setq end (point)))
4798 (if (and (buffer-live-p org-last-indirect-buffer)
4799 (not (eq org-indirect-buffer-display 'new-frame))
4800 (not arg))
4801 (kill-buffer org-last-indirect-buffer))
4802 (setq ibuf (org-get-indirect-buffer cbuf)
4803 org-last-indirect-buffer ibuf)
4804 (cond
4805 ((or (eq org-indirect-buffer-display 'new-frame)
4806 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
4807 (select-frame (make-frame))
4808 (delete-other-windows)
4809 (switch-to-buffer ibuf)
4810 (org-set-frame-title heading))
4811 ((eq org-indirect-buffer-display 'dedicated-frame)
4812 (raise-frame
4813 (select-frame (or (and org-indirect-dedicated-frame
4814 (frame-live-p org-indirect-dedicated-frame)
4815 org-indirect-dedicated-frame)
4816 (setq org-indirect-dedicated-frame (make-frame)))))
4817 (delete-other-windows)
4818 (switch-to-buffer ibuf)
4819 (org-set-frame-title (concat "Indirect: " heading)))
4820 ((eq org-indirect-buffer-display 'current-window)
4821 (switch-to-buffer ibuf))
4822 ((eq org-indirect-buffer-display 'other-window)
4823 (pop-to-buffer ibuf))
4824 (t (error "Invalid value.")))
4825 (if (featurep 'xemacs)
4826 (save-excursion (org-mode) (turn-on-font-lock)))
4827 (narrow-to-region beg end)
4828 (show-all)
4829 (goto-char pos)
4830 (and (window-live-p cwin) (select-window cwin))))
4832 (defun org-get-indirect-buffer (&optional buffer)
4833 (setq buffer (or buffer (current-buffer)))
4834 (let ((n 1) (base (buffer-name buffer)) bname)
4835 (while (buffer-live-p
4836 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
4837 (setq n (1+ n)))
4838 (condition-case nil
4839 (make-indirect-buffer buffer bname 'clone)
4840 (error (make-indirect-buffer buffer bname)))))
4842 (defun org-set-frame-title (title)
4843 "Set the title of the current frame to the string TITLE."
4844 ;; FIXME: how to name a single frame in XEmacs???
4845 (unless (featurep 'xemacs)
4846 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
4848 ;;;; Structure editing
4850 ;;; Inserting headlines
4852 (defun org-previous-line-empty-p ()
4853 (save-excursion
4854 (and (not (bobp))
4855 (or (beginning-of-line 0) t)
4856 (save-match-data
4857 (looking-at "[ \t]*$")))))
4859 (defun org-insert-heading (&optional force-heading)
4860 "Insert a new heading or item with same depth at point.
4861 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
4862 If point is at the beginning of a headline, insert a sibling before the
4863 current headline. If point is not at the beginning, do not split the line,
4864 but create the new headline after the current line."
4865 (interactive "P")
4866 (if (= (buffer-size) 0)
4867 (insert "\n* ")
4868 (when (or force-heading (not (org-insert-item)))
4869 (let* ((empty-line-p nil)
4870 (head (save-excursion
4871 (condition-case nil
4872 (progn
4873 (org-back-to-heading)
4874 (setq empty-line-p (org-previous-line-empty-p))
4875 (match-string 0))
4876 (error "*"))))
4877 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
4878 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
4879 pos hide-previous previous-pos)
4880 (cond
4881 ((and (org-on-heading-p) (bolp)
4882 (or (bobp)
4883 (save-excursion (backward-char 1) (not (org-invisible-p)))))
4884 ;; insert before the current line
4885 (open-line (if blank 2 1)))
4886 ((and (bolp)
4887 (or (bobp)
4888 (save-excursion
4889 (backward-char 1) (not (org-invisible-p)))))
4890 ;; insert right here
4891 nil)
4893 ;; somewhere in the line
4894 (save-excursion
4895 (setq previous-pos (point-at-bol))
4896 (end-of-line)
4897 (setq hide-previous (org-invisible-p)))
4898 (and org-insert-heading-respect-content (org-show-subtree))
4899 (let ((split
4900 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
4901 (save-excursion
4902 (let ((p (point)))
4903 (goto-char (point-at-bol))
4904 (and (looking-at org-complex-heading-regexp)
4905 (> p (match-beginning 4)))))))
4906 tags pos)
4907 (cond
4908 (org-insert-heading-respect-content
4909 (org-end-of-subtree nil t)
4910 (or (bolp) (newline))
4911 (or (org-previous-line-empty-p)
4912 (and blank (newline)))
4913 (open-line 1))
4914 ((org-on-heading-p)
4915 (when hide-previous
4916 (show-children)
4917 (org-show-entry))
4918 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4919 (setq tags (and (match-end 2) (match-string 2)))
4920 (and (match-end 1)
4921 (delete-region (match-beginning 1) (match-end 1)))
4922 (setq pos (point-at-bol))
4923 (or split (end-of-line 1))
4924 (delete-horizontal-space)
4925 (newline (if blank 2 1))
4926 (when tags
4927 (save-excursion
4928 (goto-char pos)
4929 (end-of-line 1)
4930 (insert " " tags)
4931 (org-set-tags nil 'align))))
4933 (or split (end-of-line 1))
4934 (newline (if blank 2 1)))))))
4935 (insert head) (just-one-space)
4936 (setq pos (point))
4937 (end-of-line 1)
4938 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
4939 (when (and org-insert-heading-respect-content hide-previous)
4940 (save-excursion
4941 (goto-char previous-pos)
4942 (hide-subtree)))
4943 (run-hooks 'org-insert-heading-hook)))))
4945 (defun org-get-heading (&optional no-tags)
4946 "Return the heading of the current entry, without the stars."
4947 (save-excursion
4948 (org-back-to-heading t)
4949 (if (looking-at
4950 (if no-tags
4951 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
4952 "\\*+[ \t]+\\([^\r\n]*\\)"))
4953 (match-string 1) "")))
4955 (defun org-heading-components ()
4956 "Return the components of the current heading.
4957 This is a list with the following elements:
4958 - the level as an integer
4959 - the reduced level, different if `org-odd-levels-only' is set.
4960 - the TODO keyword, or nil
4961 - the priority character, like ?A, or nil if no priority is given
4962 - the headline text itself, or the tags string if no headline text
4963 - the tags string, or nil."
4964 (save-excursion
4965 (org-back-to-heading t)
4966 (if (looking-at org-complex-heading-regexp)
4967 (list (length (match-string 1))
4968 (org-reduced-level (length (match-string 1)))
4969 (org-match-string-no-properties 2)
4970 (and (match-end 3) (aref (match-string 3) 2))
4971 (org-match-string-no-properties 4)
4972 (org-match-string-no-properties 5)))))
4974 (defun org-insert-heading-after-current ()
4975 "Insert a new heading with same level as current, after current subtree."
4976 (interactive)
4977 (org-back-to-heading)
4978 (org-insert-heading)
4979 (org-move-subtree-down)
4980 (end-of-line 1))
4982 (defun org-insert-heading-respect-content ()
4983 (interactive)
4984 (let ((org-insert-heading-respect-content t))
4985 (org-insert-heading t)))
4987 (defun org-insert-todo-heading-respect-content (&optional force-state)
4988 (interactive "P")
4989 (let ((org-insert-heading-respect-content t))
4990 (org-insert-todo-heading force-state t)))
4992 (defun org-insert-todo-heading (arg &optional force-heading)
4993 "Insert a new heading with the same level and TODO state as current heading.
4994 If the heading has no TODO state, or if the state is DONE, use the first
4995 state (TODO by default). Also with prefix arg, force first state."
4996 (interactive "P")
4997 (when (or force-heading (not (org-insert-item 'checkbox)))
4998 (org-insert-heading force-heading)
4999 (save-excursion
5000 (org-back-to-heading)
5001 (outline-previous-heading)
5002 (looking-at org-todo-line-regexp))
5003 (if (or arg
5004 (not (match-beginning 2))
5005 (member (match-string 2) org-done-keywords))
5006 (insert (car org-todo-keywords-1) " ")
5007 (insert (match-string 2) " "))
5008 (when org-provide-todo-statistics
5009 (org-update-parent-todo-statistics))))
5011 (defun org-insert-subheading (arg)
5012 "Insert a new subheading and demote it.
5013 Works for outline headings and for plain lists alike."
5014 (interactive "P")
5015 (org-insert-heading arg)
5016 (cond
5017 ((org-on-heading-p) (org-do-demote))
5018 ((org-at-item-p) (org-indent-item 1))))
5020 (defun org-insert-todo-subheading (arg)
5021 "Insert a new subheading with TODO keyword or checkbox and demote it.
5022 Works for outline headings and for plain lists alike."
5023 (interactive "P")
5024 (org-insert-todo-heading arg)
5025 (cond
5026 ((org-on-heading-p) (org-do-demote))
5027 ((org-at-item-p) (org-indent-item 1))))
5029 ;;; Promotion and Demotion
5031 (defun org-promote-subtree ()
5032 "Promote the entire subtree.
5033 See also `org-promote'."
5034 (interactive)
5035 (save-excursion
5036 (org-map-tree 'org-promote))
5037 (org-fix-position-after-promote))
5039 (defun org-demote-subtree ()
5040 "Demote the entire subtree. See `org-demote'.
5041 See also `org-promote'."
5042 (interactive)
5043 (save-excursion
5044 (org-map-tree 'org-demote))
5045 (org-fix-position-after-promote))
5048 (defun org-do-promote ()
5049 "Promote the current heading higher up the tree.
5050 If the region is active in `transient-mark-mode', promote all headings
5051 in the region."
5052 (interactive)
5053 (save-excursion
5054 (if (org-region-active-p)
5055 (org-map-region 'org-promote (region-beginning) (region-end))
5056 (org-promote)))
5057 (org-fix-position-after-promote))
5059 (defun org-do-demote ()
5060 "Demote the current heading lower down the tree.
5061 If the region is active in `transient-mark-mode', demote all headings
5062 in the region."
5063 (interactive)
5064 (save-excursion
5065 (if (org-region-active-p)
5066 (org-map-region 'org-demote (region-beginning) (region-end))
5067 (org-demote)))
5068 (org-fix-position-after-promote))
5070 (defun org-fix-position-after-promote ()
5071 "Make sure that after pro/demotion cursor position is right."
5072 (let ((pos (point)))
5073 (when (save-excursion
5074 (beginning-of-line 1)
5075 (looking-at org-todo-line-regexp)
5076 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
5077 (cond ((eobp) (insert " "))
5078 ((eolp) (insert " "))
5079 ((equal (char-after) ?\ ) (forward-char 1))))))
5081 (defun org-reduced-level (l)
5082 "Compute the effective level of a heading.
5083 This takes into account the setting of `org-odd-levels-only'."
5084 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
5086 (defun org-get-valid-level (level &optional change)
5087 "Rectify a level change under the influence of `org-odd-levels-only'
5088 LEVEL is a current level, CHANGE is by how much the level should be
5089 modified. Even if CHANGE is nil, LEVEL may be returned modified because
5090 even level numbers will become the next higher odd number."
5091 (if org-odd-levels-only
5092 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
5093 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
5094 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
5095 (max 1 (+ level change))))
5097 (if (boundp 'define-obsolete-function-alias)
5098 (if (or (featurep 'xemacs) (< emacs-major-version 23))
5099 (define-obsolete-function-alias 'org-get-legal-level
5100 'org-get-valid-level)
5101 (define-obsolete-function-alias 'org-get-legal-level
5102 'org-get-valid-level "23.1")))
5104 (defun org-promote ()
5105 "Promote the current heading higher up the tree.
5106 If the region is active in `transient-mark-mode', promote all headings
5107 in the region."
5108 (org-back-to-heading t)
5109 (let* ((level (save-match-data (funcall outline-level)))
5110 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
5111 (diff (abs (- level (length up-head) -1))))
5112 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
5113 (replace-match up-head nil t)
5114 ;; Fixup tag positioning
5115 (and org-auto-align-tags (org-set-tags nil t))
5116 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
5118 (defun org-demote ()
5119 "Demote the current heading lower down the tree.
5120 If the region is active in `transient-mark-mode', demote all headings
5121 in the region."
5122 (org-back-to-heading t)
5123 (let* ((level (save-match-data (funcall outline-level)))
5124 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
5125 (diff (abs (- level (length down-head) -1))))
5126 (replace-match down-head nil t)
5127 ;; Fixup tag positioning
5128 (and org-auto-align-tags (org-set-tags nil t))
5129 (if org-adapt-indentation (org-fixup-indentation diff))))
5131 (defun org-map-tree (fun)
5132 "Call FUN for every heading underneath the current one."
5133 (org-back-to-heading)
5134 (let ((level (funcall outline-level)))
5135 (save-excursion
5136 (funcall fun)
5137 (while (and (progn
5138 (outline-next-heading)
5139 (> (funcall outline-level) level))
5140 (not (eobp)))
5141 (funcall fun)))))
5143 (defun org-map-region (fun beg end)
5144 "Call FUN for every heading between BEG and END."
5145 (let ((org-ignore-region t))
5146 (save-excursion
5147 (setq end (copy-marker end))
5148 (goto-char beg)
5149 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
5150 (< (point) end))
5151 (funcall fun))
5152 (while (and (progn
5153 (outline-next-heading)
5154 (< (point) end))
5155 (not (eobp)))
5156 (funcall fun)))))
5158 (defun org-fixup-indentation (diff)
5159 "Change the indentation in the current entry by DIFF
5160 However, if any line in the current entry has no indentation, or if it
5161 would end up with no indentation after the change, nothing at all is done."
5162 (save-excursion
5163 (let ((end (save-excursion (outline-next-heading)
5164 (point-marker)))
5165 (prohibit (if (> diff 0)
5166 "^\\S-"
5167 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
5168 col)
5169 (unless (save-excursion (end-of-line 1)
5170 (re-search-forward prohibit end t))
5171 (while (and (< (point) end)
5172 (re-search-forward "^[ \t]+" end t))
5173 (goto-char (match-end 0))
5174 (setq col (current-column))
5175 (if (< diff 0) (replace-match ""))
5176 (org-indent-to-column (+ diff col))))
5177 (move-marker end nil))))
5179 (defun org-convert-to-odd-levels ()
5180 "Convert an org-mode file with all levels allowed to one with odd levels.
5181 This will leave level 1 alone, convert level 2 to level 3, level 3 to
5182 level 5 etc."
5183 (interactive)
5184 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
5185 (let ((org-odd-levels-only nil) n)
5186 (save-excursion
5187 (goto-char (point-min))
5188 (while (re-search-forward "^\\*\\*+ " nil t)
5189 (setq n (- (length (match-string 0)) 2))
5190 (while (>= (setq n (1- n)) 0)
5191 (org-demote))
5192 (end-of-line 1))))))
5195 (defun org-convert-to-oddeven-levels ()
5196 "Convert an org-mode file with only odd levels to one with odd and even levels.
5197 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
5198 section with an even level, conversion would destroy the structure of the file. An error
5199 is signaled in this case."
5200 (interactive)
5201 (goto-char (point-min))
5202 ;; First check if there are no even levels
5203 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
5204 (org-show-context t)
5205 (error "Not all levels are odd in this file. Conversion not possible."))
5206 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
5207 (let ((org-odd-levels-only nil) n)
5208 (save-excursion
5209 (goto-char (point-min))
5210 (while (re-search-forward "^\\*\\*+ " nil t)
5211 (setq n (/ (1- (length (match-string 0))) 2))
5212 (while (>= (setq n (1- n)) 0)
5213 (org-promote))
5214 (end-of-line 1))))))
5216 (defun org-tr-level (n)
5217 "Make N odd if required."
5218 (if org-odd-levels-only (1+ (/ n 2)) n))
5220 ;;; Vertical tree motion, cutting and pasting of subtrees
5222 (defun org-move-subtree-up (&optional arg)
5223 "Move the current subtree up past ARG headlines of the same level."
5224 (interactive "p")
5225 (org-move-subtree-down (- (prefix-numeric-value arg))))
5227 (defun org-move-subtree-down (&optional arg)
5228 "Move the current subtree down past ARG headlines of the same level."
5229 (interactive "p")
5230 (setq arg (prefix-numeric-value arg))
5231 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
5232 'outline-get-last-sibling))
5233 (ins-point (make-marker))
5234 (cnt (abs arg))
5235 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
5236 ;; Select the tree
5237 (org-back-to-heading)
5238 (setq beg0 (point))
5239 (save-excursion
5240 (setq ne-beg (org-back-over-empty-lines))
5241 (setq beg (point)))
5242 (save-match-data
5243 (save-excursion (outline-end-of-heading)
5244 (setq folded (org-invisible-p)))
5245 (outline-end-of-subtree))
5246 (outline-next-heading)
5247 (setq ne-end (org-back-over-empty-lines))
5248 (setq end (point))
5249 (goto-char beg0)
5250 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
5251 ;; include less whitespace
5252 (save-excursion
5253 (goto-char beg)
5254 (forward-line (- ne-beg ne-end))
5255 (setq beg (point))))
5256 ;; Find insertion point, with error handling
5257 (while (> cnt 0)
5258 (or (and (funcall movfunc) (looking-at outline-regexp))
5259 (progn (goto-char beg0)
5260 (error "Cannot move past superior level or buffer limit")))
5261 (setq cnt (1- cnt)))
5262 (if (> arg 0)
5263 ;; Moving forward - still need to move over subtree
5264 (progn (org-end-of-subtree t t)
5265 (save-excursion
5266 (org-back-over-empty-lines)
5267 (or (bolp) (newline)))))
5268 (setq ne-ins (org-back-over-empty-lines))
5269 (move-marker ins-point (point))
5270 (setq txt (buffer-substring beg end))
5271 (org-save-markers-in-region beg end)
5272 (delete-region beg end)
5273 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
5274 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
5275 (let ((bbb (point)))
5276 (insert-before-markers txt)
5277 (org-reinstall-markers-in-region bbb)
5278 (move-marker ins-point bbb))
5279 (or (bolp) (insert "\n"))
5280 (setq ins-end (point))
5281 (goto-char ins-point)
5282 (org-skip-whitespace)
5283 (when (and (< arg 0)
5284 (org-first-sibling-p)
5285 (> ne-ins ne-beg))
5286 ;; Move whitespace back to beginning
5287 (save-excursion
5288 (goto-char ins-end)
5289 (let ((kill-whole-line t))
5290 (kill-line (- ne-ins ne-beg)) (point)))
5291 (insert (make-string (- ne-ins ne-beg) ?\n)))
5292 (move-marker ins-point nil)
5293 (org-compact-display-after-subtree-move)
5294 (org-show-empty-lines-in-parent)
5295 (unless folded
5296 (org-show-entry)
5297 (show-children)
5298 (org-cycle-hide-drawers 'children))))
5300 (defvar org-subtree-clip ""
5301 "Clipboard for cut and paste of subtrees.
5302 This is actually only a copy of the kill, because we use the normal kill
5303 ring. We need it to check if the kill was created by `org-copy-subtree'.")
5305 (defvar org-subtree-clip-folded nil
5306 "Was the last copied subtree folded?
5307 This is used to fold the tree back after pasting.")
5309 (defun org-cut-subtree (&optional n)
5310 "Cut the current subtree into the clipboard.
5311 With prefix arg N, cut this many sequential subtrees.
5312 This is a short-hand for marking the subtree and then cutting it."
5313 (interactive "p")
5314 (org-copy-subtree n 'cut))
5316 (defun org-copy-subtree (&optional n cut force-store-markers)
5317 "Cut the current subtree into the clipboard.
5318 With prefix arg N, cut this many sequential subtrees.
5319 This is a short-hand for marking the subtree and then copying it.
5320 If CUT is non-nil, actually cut the subtree.
5321 If FORCE-STORE-MARKERS is non-nil, store the relative locations
5322 of some markers in the region, even if CUT is non-nil. This is
5323 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
5324 (interactive "p")
5325 (let (beg end folded (beg0 (point)))
5326 (if (interactive-p)
5327 (org-back-to-heading nil) ; take what looks like a subtree
5328 (org-back-to-heading t)) ; take what is really there
5329 (org-back-over-empty-lines)
5330 (setq beg (point))
5331 (skip-chars-forward " \t\r\n")
5332 (save-match-data
5333 (save-excursion (outline-end-of-heading)
5334 (setq folded (org-invisible-p)))
5335 (condition-case nil
5336 (outline-forward-same-level (1- n))
5337 (error nil))
5338 (org-end-of-subtree t t))
5339 (org-back-over-empty-lines)
5340 (setq end (point))
5341 (goto-char beg0)
5342 (when (> end beg)
5343 (setq org-subtree-clip-folded folded)
5344 (when (or cut force-store-markers)
5345 (org-save-markers-in-region beg end))
5346 (if cut (kill-region beg end) (copy-region-as-kill beg end))
5347 (setq org-subtree-clip (current-kill 0))
5348 (message "%s: Subtree(s) with %d characters"
5349 (if cut "Cut" "Copied")
5350 (length org-subtree-clip)))))
5352 (defun org-paste-subtree (&optional level tree for-yank)
5353 "Paste the clipboard as a subtree, with modification of headline level.
5354 The entire subtree is promoted or demoted in order to match a new headline
5355 level.
5357 If the cursor is at the beginning of a headline, the same level as
5358 that headline is used to paste the tree
5360 If not, the new level is derived from the *visible* headings
5361 before and after the insertion point, and taken to be the inferior headline
5362 level of the two. So if the previous visible heading is level 3 and the
5363 next is level 4 (or vice versa), level 4 will be used for insertion.
5364 This makes sure that the subtree remains an independent subtree and does
5365 not swallow low level entries.
5367 You can also force a different level, either by using a numeric prefix
5368 argument, or by inserting the heading marker by hand. For example, if the
5369 cursor is after \"*****\", then the tree will be shifted to level 5.
5371 If optional TREE is given, use this text instead of the kill ring.
5373 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
5374 move back over whitespace before inserting, and move point to the end of
5375 the inserted text when done."
5376 (interactive "P")
5377 (unless (org-kill-is-subtree-p tree)
5378 (error "%s"
5379 (substitute-command-keys
5380 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
5381 (let* ((visp (not (org-invisible-p)))
5382 (txt (or tree (and kill-ring (current-kill 0))))
5383 (^re (concat "^\\(" outline-regexp "\\)"))
5384 (re (concat "\\(" outline-regexp "\\)"))
5385 (^re_ (concat "\\(\\*+\\)[ \t]*"))
5387 (old-level (if (string-match ^re txt)
5388 (- (match-end 0) (match-beginning 0) 1)
5389 -1))
5390 (force-level (cond (level (prefix-numeric-value level))
5391 ((and (looking-at "[ \t]*$")
5392 (string-match
5393 ^re_ (buffer-substring
5394 (point-at-bol) (point))))
5395 (- (match-end 1) (match-beginning 1)))
5396 ((and (bolp)
5397 (looking-at org-outline-regexp))
5398 (- (match-end 0) (point) 1))
5399 (t nil)))
5400 (previous-level (save-excursion
5401 (condition-case nil
5402 (progn
5403 (outline-previous-visible-heading 1)
5404 (if (looking-at re)
5405 (- (match-end 0) (match-beginning 0) 1)
5407 (error 1))))
5408 (next-level (save-excursion
5409 (condition-case nil
5410 (progn
5411 (or (looking-at outline-regexp)
5412 (outline-next-visible-heading 1))
5413 (if (looking-at re)
5414 (- (match-end 0) (match-beginning 0) 1)
5416 (error 1))))
5417 (new-level (or force-level (max previous-level next-level)))
5418 (shift (if (or (= old-level -1)
5419 (= new-level -1)
5420 (= old-level new-level))
5422 (- new-level old-level)))
5423 (delta (if (> shift 0) -1 1))
5424 (func (if (> shift 0) 'org-demote 'org-promote))
5425 (org-odd-levels-only nil)
5426 beg end newend)
5427 ;; Remove the forced level indicator
5428 (if force-level
5429 (delete-region (point-at-bol) (point)))
5430 ;; Paste
5431 (beginning-of-line 1)
5432 (unless for-yank (org-back-over-empty-lines))
5433 (setq beg (point))
5434 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
5435 (insert-before-markers txt)
5436 (unless (string-match "\n\\'" txt) (insert "\n"))
5437 (setq newend (point))
5438 (org-reinstall-markers-in-region beg)
5439 (setq end (point))
5440 (goto-char beg)
5441 (skip-chars-forward " \t\n\r")
5442 (setq beg (point))
5443 (if (and (org-invisible-p) visp)
5444 (save-excursion (outline-show-heading)))
5445 ;; Shift if necessary
5446 (unless (= shift 0)
5447 (save-restriction
5448 (narrow-to-region beg end)
5449 (while (not (= shift 0))
5450 (org-map-region func (point-min) (point-max))
5451 (setq shift (+ delta shift)))
5452 (goto-char (point-min))
5453 (setq newend (point-max))))
5454 (when (or (interactive-p) for-yank)
5455 (message "Clipboard pasted as level %d subtree" new-level))
5456 (if (and (not for-yank) ; in this case, org-yank will decide about folding
5457 kill-ring
5458 (eq org-subtree-clip (current-kill 0))
5459 org-subtree-clip-folded)
5460 ;; The tree was folded before it was killed/copied
5461 (hide-subtree))
5462 (and for-yank (goto-char newend))))
5464 (defun org-kill-is-subtree-p (&optional txt)
5465 "Check if the current kill is an outline subtree, or a set of trees.
5466 Returns nil if kill does not start with a headline, or if the first
5467 headline level is not the largest headline level in the tree.
5468 So this will actually accept several entries of equal levels as well,
5469 which is OK for `org-paste-subtree'.
5470 If optional TXT is given, check this string instead of the current kill."
5471 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
5472 (start-level (and kill
5473 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
5474 org-outline-regexp "\\)")
5475 kill)
5476 (- (match-end 2) (match-beginning 2) 1)))
5477 (re (concat "^" org-outline-regexp))
5478 (start (1+ (or (match-beginning 2) -1))))
5479 (if (not start-level)
5480 (progn
5481 nil) ;; does not even start with a heading
5482 (catch 'exit
5483 (while (setq start (string-match re kill (1+ start)))
5484 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
5485 (throw 'exit nil)))
5486 t))))
5488 (defvar org-markers-to-move nil
5489 "Markers that should be moved with a cut-and-paste operation.
5490 Those markers are stored together with their positions relative to
5491 the start of the region.")
5493 (defun org-save-markers-in-region (beg end)
5494 "Check markers in region.
5495 If these markers are between BEG and END, record their position relative
5496 to BEG, so that after moving the block of text, we can put the markers back
5497 into place.
5498 This function gets called just before an entry or tree gets cut from the
5499 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
5500 called immediately, to move the markers with the entries."
5501 (setq org-markers-to-move nil)
5502 (when (featurep 'org-clock)
5503 (org-clock-save-markers-for-cut-and-paste beg end))
5504 (when (featurep 'org-agenda)
5505 (org-agenda-save-markers-for-cut-and-paste beg end)))
5507 (defun org-check-and-save-marker (marker beg end)
5508 "Check if MARKER is between BEG and END.
5509 If yes, remember the marker and the distance to BEG."
5510 (when (and (marker-buffer marker)
5511 (equal (marker-buffer marker) (current-buffer)))
5512 (if (and (>= marker beg) (< marker end))
5513 (push (cons marker (- marker beg)) org-markers-to-move))))
5515 (defun org-reinstall-markers-in-region (beg)
5516 "Move all remembered markers to their position relative to BEG."
5517 (mapc (lambda (x)
5518 (move-marker (car x) (+ beg (cdr x))))
5519 org-markers-to-move)
5520 (setq org-markers-to-move nil))
5522 (defun org-narrow-to-subtree ()
5523 "Narrow buffer to the current subtree."
5524 (interactive)
5525 (save-excursion
5526 (save-match-data
5527 (narrow-to-region
5528 (progn (org-back-to-heading) (point))
5529 (progn (org-end-of-subtree t) (point))))))
5532 ;;; Outline Sorting
5534 (defun org-sort (with-case)
5535 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
5536 Optional argument WITH-CASE means sort case-sensitively."
5537 (interactive "P")
5538 (if (org-at-table-p)
5539 (org-call-with-arg 'org-table-sort-lines with-case)
5540 (org-call-with-arg 'org-sort-entries-or-items with-case)))
5542 (defun org-sort-remove-invisible (s)
5543 (remove-text-properties 0 (length s) org-rm-props s)
5544 (while (string-match org-bracket-link-regexp s)
5545 (setq s (replace-match (if (match-end 2)
5546 (match-string 3 s)
5547 (match-string 1 s)) t t s)))
5550 (defvar org-priority-regexp) ; defined later in the file
5552 (defun org-sort-entries-or-items
5553 (&optional with-case sorting-type getkey-func compare-func property)
5554 "Sort entries on a certain level of an outline tree.
5555 If there is an active region, the entries in the region are sorted.
5556 Else, if the cursor is before the first entry, sort the top-level items.
5557 Else, the children of the entry at point are sorted.
5559 Sorting can be alphabetically, numerically, and by date/time as given by
5560 the first time stamp in the entry. The command prompts for the sorting
5561 type unless it has been given to the function through the SORTING-TYPE
5562 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
5563 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
5564 called with point at the beginning of the record. It must return either
5565 a string or a number that should serve as the sorting key for that record.
5567 Comparing entries ignores case by default. However, with an optional argument
5568 WITH-CASE, the sorting considers case as well."
5569 (interactive "P")
5570 (let ((case-func (if with-case 'identity 'downcase))
5571 start beg end stars re re2
5572 txt what tmp plain-list-p)
5573 ;; Find beginning and end of region to sort
5574 (cond
5575 ((org-region-active-p)
5576 ;; we will sort the region
5577 (setq end (region-end)
5578 what "region")
5579 (goto-char (region-beginning))
5580 (if (not (org-on-heading-p)) (outline-next-heading))
5581 (setq start (point)))
5582 ((org-at-item-p)
5583 ;; we will sort this plain list
5584 (org-beginning-of-item-list) (setq start (point))
5585 (org-end-of-item-list) (setq end (point))
5586 (goto-char start)
5587 (setq plain-list-p t
5588 what "plain list"))
5589 ((or (org-on-heading-p)
5590 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
5591 ;; we will sort the children of the current headline
5592 (org-back-to-heading)
5593 (setq start (point)
5594 end (progn (org-end-of-subtree t t)
5595 (org-back-over-empty-lines)
5596 (point))
5597 what "children")
5598 (goto-char start)
5599 (show-subtree)
5600 (outline-next-heading))
5602 ;; we will sort the top-level entries in this file
5603 (goto-char (point-min))
5604 (or (org-on-heading-p) (outline-next-heading))
5605 (setq start (point) end (point-max) what "top-level")
5606 (goto-char start)
5607 (show-all)))
5609 (setq beg (point))
5610 (if (>= beg end) (error "Nothing to sort"))
5612 (unless plain-list-p
5613 (looking-at "\\(\\*+\\)")
5614 (setq stars (match-string 1)
5615 re (concat "^" (regexp-quote stars) " +")
5616 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
5617 txt (buffer-substring beg end))
5618 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
5619 (if (and (not (equal stars "*")) (string-match re2 txt))
5620 (error "Region to sort contains a level above the first entry")))
5622 (unless sorting-type
5623 (message
5624 (if plain-list-p
5625 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
5626 "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:")
5627 what)
5628 (setq sorting-type (read-char-exclusive))
5630 (and (= (downcase sorting-type) ?f)
5631 (setq getkey-func
5632 (org-ido-completing-read "Sort using function: "
5633 obarray 'fboundp t nil nil))
5634 (setq getkey-func (intern getkey-func)))
5636 (and (= (downcase sorting-type) ?r)
5637 (setq property
5638 (org-ido-completing-read "Property: "
5639 (mapcar 'list (org-buffer-property-keys t))
5640 nil t))))
5642 (message "Sorting entries...")
5644 (save-restriction
5645 (narrow-to-region start end)
5647 (let ((dcst (downcase sorting-type))
5648 (now (current-time)))
5649 (sort-subr
5650 (/= dcst sorting-type)
5651 ;; This function moves to the beginning character of the "record" to
5652 ;; be sorted.
5653 (if plain-list-p
5654 (lambda nil
5655 (if (org-at-item-p) t (goto-char (point-max))))
5656 (lambda nil
5657 (if (re-search-forward re nil t)
5658 (goto-char (match-beginning 0))
5659 (goto-char (point-max)))))
5660 ;; This function moves to the last character of the "record" being
5661 ;; sorted.
5662 (if plain-list-p
5663 'org-end-of-item
5664 (lambda nil
5665 (save-match-data
5666 (condition-case nil
5667 (outline-forward-same-level 1)
5668 (error
5669 (goto-char (point-max)))))))
5671 ;; This function returns the value that gets sorted against.
5672 (if plain-list-p
5673 (lambda nil
5674 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
5675 (cond
5676 ((= dcst ?n)
5677 (string-to-number (buffer-substring (match-end 0)
5678 (point-at-eol))))
5679 ((= dcst ?a)
5680 (buffer-substring (match-end 0) (point-at-eol)))
5681 ((= dcst ?t)
5682 (if (re-search-forward org-ts-regexp
5683 (point-at-eol) t)
5684 (org-time-string-to-time (match-string 0))
5685 now))
5686 ((= dcst ?f)
5687 (if getkey-func
5688 (progn
5689 (setq tmp (funcall getkey-func))
5690 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5691 tmp)
5692 (error "Invalid key function `%s'" getkey-func)))
5693 (t (error "Invalid sorting type `%c'" sorting-type)))))
5694 (lambda nil
5695 (cond
5696 ((= dcst ?n)
5697 (if (looking-at org-complex-heading-regexp)
5698 (string-to-number (match-string 4))
5699 nil))
5700 ((= dcst ?a)
5701 (if (looking-at org-complex-heading-regexp)
5702 (funcall case-func (match-string 4))
5703 nil))
5704 ((= dcst ?t)
5705 (if (re-search-forward org-ts-regexp
5706 (save-excursion
5707 (forward-line 2)
5708 (point)) t)
5709 (org-time-string-to-time (match-string 0))
5710 now))
5711 ((= dcst ?p)
5712 (if (re-search-forward org-priority-regexp (point-at-eol) t)
5713 (string-to-char (match-string 2))
5714 org-default-priority))
5715 ((= dcst ?r)
5716 (or (org-entry-get nil property) ""))
5717 ((= dcst ?o)
5718 (if (looking-at org-complex-heading-regexp)
5719 (- 9999 (length (member (match-string 2)
5720 org-todo-keywords-1)))))
5721 ((= dcst ?f)
5722 (if getkey-func
5723 (progn
5724 (setq tmp (funcall getkey-func))
5725 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5726 tmp)
5727 (error "Invalid key function `%s'" getkey-func)))
5728 (t (error "Invalid sorting type `%c'" sorting-type)))))
5730 (cond
5731 ((= dcst ?a) 'string<)
5732 ((= dcst ?t) 'time-less-p)
5733 ((= dcst ?f) compare-func)
5734 (t nil)))))
5735 (message "Sorting entries...done")))
5737 (defun org-do-sort (table what &optional with-case sorting-type)
5738 "Sort TABLE of WHAT according to SORTING-TYPE.
5739 The user will be prompted for the SORTING-TYPE if the call to this
5740 function does not specify it. WHAT is only for the prompt, to indicate
5741 what is being sorted. The sorting key will be extracted from
5742 the car of the elements of the table.
5743 If WITH-CASE is non-nil, the sorting will be case-sensitive."
5744 (unless sorting-type
5745 (message
5746 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
5747 what)
5748 (setq sorting-type (read-char-exclusive)))
5749 (let ((dcst (downcase sorting-type))
5750 extractfun comparefun)
5751 ;; Define the appropriate functions
5752 (cond
5753 ((= dcst ?n)
5754 (setq extractfun 'string-to-number
5755 comparefun (if (= dcst sorting-type) '< '>)))
5756 ((= dcst ?a)
5757 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
5758 (lambda(x) (downcase (org-sort-remove-invisible x))))
5759 comparefun (if (= dcst sorting-type)
5760 'string<
5761 (lambda (a b) (and (not (string< a b))
5762 (not (string= a b)))))))
5763 ((= dcst ?t)
5764 (setq extractfun
5765 (lambda (x)
5766 (if (string-match org-ts-regexp x)
5767 (time-to-seconds
5768 (org-time-string-to-time (match-string 0 x)))
5770 comparefun (if (= dcst sorting-type) '< '>)))
5771 (t (error "Invalid sorting type `%c'" sorting-type)))
5773 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5774 table)
5775 (lambda (a b) (funcall comparefun (car a) (car b))))))
5777 ;;; Editing source examples
5779 (defvar org-exit-edit-mode-map (make-sparse-keymap))
5780 (define-key org-exit-edit-mode-map "\C-c'" 'org-edit-src-exit)
5781 (defvar org-edit-src-force-single-line nil)
5782 (defvar org-edit-src-from-org-mode nil)
5783 (defvar org-edit-src-picture nil)
5785 (define-minor-mode org-exit-edit-mode
5786 "Minor mode installing a single key binding, \"C-c '\" to exit special edit.")
5788 (defun org-edit-src-code ()
5789 "Edit the source code example at point.
5790 An indirect buffer is created, and that buffer is then narrowed to the
5791 example at point and switched to the correct language mode. When done,
5792 exit by killing the buffer with \\[org-edit-src-exit]."
5793 (interactive)
5794 (let ((line (org-current-line))
5795 (case-fold-search t)
5796 (msg (substitute-command-keys
5797 "Edit, then exit with C-c ' (C-c and single quote)"))
5798 (info (org-edit-src-find-region-and-lang))
5799 (org-mode-p (eq major-mode 'org-mode))
5800 beg end lang lang-f single lfmt)
5801 (if (not info)
5803 (setq beg (nth 0 info)
5804 end (nth 1 info)
5805 lang (nth 2 info)
5806 single (nth 3 info)
5807 lfmt (nth 4 info)
5808 lang-f (intern (concat lang "-mode")))
5809 (unless (functionp lang-f)
5810 (error "No such language mode: %s" lang-f))
5811 (goto-line line)
5812 (if (get-buffer "*Org Edit Src Example*")
5813 (kill-buffer "*Org Edit Src Example*"))
5814 (switch-to-buffer (make-indirect-buffer (current-buffer)
5815 "*Org Edit Src Example*"))
5816 (narrow-to-region beg end)
5817 (remove-text-properties beg end '(display nil invisible nil
5818 intangible nil))
5819 (let ((org-inhibit-startup t))
5820 (funcall lang-f))
5821 (set (make-local-variable 'org-edit-src-force-single-line) single)
5822 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5823 (when lfmt
5824 (set (make-local-variable 'org-coderef-label-format) lfmt))
5825 (when org-mode-p
5826 (goto-char (point-min))
5827 (while (re-search-forward "^," nil t)
5828 (replace-match "")))
5829 (goto-line line)
5830 (org-exit-edit-mode)
5831 (org-set-local 'header-line-format msg)
5832 (message "%s" msg)
5833 t)))
5835 (defun org-edit-fixed-width-region ()
5836 "Edit the fixed-width ascii drawing at point.
5837 This must be a region where each line starts with a colon followed by
5838 a space character.
5839 An indirect buffer is created, and that buffer is then narrowed to the
5840 example at point and switched to artist-mode. When done,
5841 exit by killing the buffer with \\[org-edit-src-exit]."
5842 (interactive)
5843 (let ((line (org-current-line))
5844 (case-fold-search t)
5845 (msg (substitute-command-keys
5846 "Edit, then exit with C-c ' (C-c and single quote)"))
5847 (org-mode-p (eq major-mode 'org-mode))
5848 beg end lang lang-f)
5849 (beginning-of-line 1)
5850 (if (looking-at "[ \t]*[^:\n \t]")
5852 (if (looking-at "[ \t]*\\(\n\\|\\'\\)")
5853 (setq beg (point) end beg)
5854 (save-excursion
5855 (if (re-search-backward "^[ \t]*[^:]" nil 'move)
5856 (setq beg (point-at-bol 2))
5857 (setq beg (point))))
5858 (save-excursion
5859 (if (re-search-forward "^[ \t]*[^:]" nil 'move)
5860 (setq end (1- (match-beginning 0)))
5861 (setq end (point))))
5862 (goto-line line))
5863 (if (get-buffer "*Org Edit Picture*")
5864 (kill-buffer "*Org Edit Picture*"))
5865 (switch-to-buffer (make-indirect-buffer (current-buffer)
5866 "*Org Edit Picture*"))
5867 (narrow-to-region beg end)
5868 (remove-text-properties beg end '(display nil invisible nil
5869 intangible nil))
5870 (when (fboundp 'font-lock-unfontify-region)
5871 (font-lock-unfontify-region (point-min) (point-max)))
5872 (cond
5873 ((eq org-edit-fixed-width-region-mode 'artist-mode)
5874 (fundamental-mode)
5875 (artist-mode 1))
5876 (t (funcall org-edit-fixed-width-region-mode)))
5877 (set (make-local-variable 'org-edit-src-force-single-line) nil)
5878 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5879 (set (make-local-variable 'org-edit-src-picture) t)
5880 (goto-char (point-min))
5881 (while (re-search-forward "^[ \t]*: ?" nil t)
5882 (replace-match ""))
5883 (goto-line line)
5884 (org-exit-edit-mode)
5885 (org-set-local 'header-line-format msg)
5886 (message "%s" msg)
5887 t)))
5890 (defun org-edit-src-find-region-and-lang ()
5891 "Find the region and language for a local edit.
5892 Return a list with beginning and end of the region, a string representing
5893 the language, a switch telling of the content should be in a single line."
5894 (let ((re-list
5895 (append
5896 org-edit-src-region-extra
5898 ("<src\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</src>" lang)
5899 ("<literal\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</literal>" style)
5900 ("<example>[ \t]*\n?" "\n?[ \t]*</example>" "fundamental")
5901 ("<lisp>[ \t]*\n?" "\n?[ \t]*</lisp>" "emacs-lisp")
5902 ("<perl>[ \t]*\n?" "\n?[ \t]*</perl>" "perl")
5903 ("<python>[ \t]*\n?" "\n?[ \t]*</python>" "python")
5904 ("<ruby>[ \t]*\n?" "\n?[ \t]*</ruby>" "ruby")
5905 ("^#\\+begin_src\\( \\([^ \t\n]+\\)\\)?.*\n" "\n#\\+end_src" 2)
5906 ("^#\\+begin_example.*\n" "\n#\\+end_example" "fundamental")
5907 ("^#\\+html:" "\n" "html" single-line)
5908 ("^#\\+begin_html.*\n" "\n#\\+end_html" "html")
5909 ("^#\\+begin_latex.*\n" "\n#\\+end_latex" "latex")
5910 ("^#\\+latex:" "\n" "latex" single-line)
5911 ("^#\\+begin_ascii.*\n" "\n#\\+end_ascii" "fundamental")
5912 ("^#\\+ascii:" "\n" "ascii" single-line)
5914 (pos (point))
5915 re re1 re2 single beg end lang lfmt match-re1)
5916 (catch 'exit
5917 (while (setq entry (pop re-list))
5918 (setq re1 (car entry) re2 (nth 1 entry) lang (nth 2 entry)
5919 single (nth 3 entry))
5920 (save-excursion
5921 (if (or (looking-at re1)
5922 (re-search-backward re1 nil t))
5923 (progn
5924 (setq match-re1 (match-string 0))
5925 (setq beg (match-end 0)
5926 lang (org-edit-src-get-lang lang)
5927 lfmt (org-edit-src-get-label-format match-re1))
5928 (if (and (re-search-forward re2 nil t)
5929 (>= (match-end 0) pos))
5930 (throw 'exit (list beg (match-beginning 0)
5931 lang single lfmt))))
5932 (if (or (looking-at re2)
5933 (re-search-forward re2 nil t))
5934 (progn
5935 (setq end (match-beginning 0))
5936 (if (and (re-search-backward re1 nil t)
5937 (<= (match-beginning 0) pos))
5938 (progn
5939 (setq lfmt (org-edit-src-get-label-format
5940 (match-string 0)))
5941 (throw 'exit
5942 (list (match-end 0) end
5943 (org-edit-src-get-lang lang)
5944 single lfmt))))))))))))
5946 (defun org-edit-src-get-lang (lang)
5947 "Extract the src language."
5948 (let ((m (match-string 0)))
5949 (cond
5950 ((stringp lang) lang)
5951 ((integerp lang) (match-string lang))
5952 ((and (eq lang 'lang)
5953 (string-match "\\<lang=\"\\([^ \t\n\"]+\\)\"" m))
5954 (match-string 1 m))
5955 ((and (eq lang 'style)
5956 (string-match "\\<style=\"\\([^ \t\n\"]+\\)\"" m))
5957 (match-string 1 m))
5958 (t "fundamental"))))
5960 (defun org-edit-src-get-label-format (s)
5961 "Extract the label format."
5962 (save-match-data
5963 (if (string-match "-l[ \t]+\\\\?\"\\([^\t\r\n\"]+\\)\\\\?\"" s)
5964 (match-string 1 s))))
5966 (defun org-edit-src-exit ()
5967 "Exit special edit and protect problematic lines."
5968 (interactive)
5969 (unless (buffer-base-buffer (current-buffer))
5970 (error "This is not an indirect buffer, something is wrong..."))
5971 (unless (> (point-min) 1)
5972 (error "This buffer is not narrowed, something is wrong..."))
5973 (goto-char (point-min))
5974 (if (looking-at "[ \t\n]*\n") (replace-match ""))
5975 (if (re-search-forward "\n[ \t\n]*\\'" nil t) (replace-match ""))
5976 (when (org-bound-and-true-p org-edit-src-force-single-line)
5977 (goto-char (point-min))
5978 (while (re-search-forward "\n" nil t)
5979 (replace-match " "))
5980 (goto-char (point-min))
5981 (if (looking-at "\\s-*") (replace-match " "))
5982 (if (re-search-forward "\\s-+\\'" nil t)
5983 (replace-match "")))
5984 (when (org-bound-and-true-p org-edit-src-from-org-mode)
5985 (goto-char (point-min))
5986 (while (re-search-forward (if (org-mode-p) "^\\(.\\)" "^\\([*#]\\)") nil t)
5987 (replace-match ",\\1"))
5988 (when font-lock-mode
5989 (font-lock-unfontify-region (point-min) (point-max)))
5990 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
5991 (when (org-bound-and-true-p org-edit-src-picture)
5992 (untabify (point-min) (point-max))
5993 (goto-char (point-min))
5994 (while (re-search-forward "^" nil t)
5995 (replace-match ": "))
5996 (when font-lock-mode
5997 (font-lock-unfontify-region (point-min) (point-max)))
5998 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
5999 (kill-buffer (current-buffer))
6000 (and (org-mode-p) (org-restart-font-lock)))
6003 ;;; The orgstruct minor mode
6005 ;; Define a minor mode which can be used in other modes in order to
6006 ;; integrate the org-mode structure editing commands.
6008 ;; This is really a hack, because the org-mode structure commands use
6009 ;; keys which normally belong to the major mode. Here is how it
6010 ;; works: The minor mode defines all the keys necessary to operate the
6011 ;; structure commands, but wraps the commands into a function which
6012 ;; tests if the cursor is currently at a headline or a plain list
6013 ;; item. If that is the case, the structure command is used,
6014 ;; temporarily setting many Org-mode variables like regular
6015 ;; expressions for filling etc. However, when any of those keys is
6016 ;; used at a different location, function uses `key-binding' to look
6017 ;; up if the key has an associated command in another currently active
6018 ;; keymap (minor modes, major mode, global), and executes that
6019 ;; command. There might be problems if any of the keys is otherwise
6020 ;; used as a prefix key.
6022 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
6023 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
6024 ;; addresses this by checking explicitly for both bindings.
6026 (defvar orgstruct-mode-map (make-sparse-keymap)
6027 "Keymap for the minor `orgstruct-mode'.")
6029 (defvar org-local-vars nil
6030 "List of local variables, for use by `orgstruct-mode'")
6032 ;;;###autoload
6033 (define-minor-mode orgstruct-mode
6034 "Toggle the minor more `orgstruct-mode'.
6035 This mode is for using Org-mode structure commands in other modes.
6036 The following key behave as if Org-mode was active, if the cursor
6037 is on a headline, or on a plain list item (both in the definition
6038 of Org-mode).
6040 M-up Move entry/item up
6041 M-down Move entry/item down
6042 M-left Promote
6043 M-right Demote
6044 M-S-up Move entry/item up
6045 M-S-down Move entry/item down
6046 M-S-left Promote subtree
6047 M-S-right Demote subtree
6048 M-q Fill paragraph and items like in Org-mode
6049 C-c ^ Sort entries
6050 C-c - Cycle list bullet
6051 TAB Cycle item visibility
6052 M-RET Insert new heading/item
6053 S-M-RET Insert new TODO heading / Checkbox item
6054 C-c C-c Set tags / toggle checkbox"
6055 nil " OrgStruct" nil
6056 (org-load-modules-maybe)
6057 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
6059 ;;;###autoload
6060 (defun turn-on-orgstruct ()
6061 "Unconditionally turn on `orgstruct-mode'."
6062 (orgstruct-mode 1))
6064 ;;;###autoload
6065 (defun turn-on-orgstruct++ ()
6066 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
6067 In addition to setting orgstruct-mode, this also exports all indentation and
6068 autofilling variables from org-mode into the buffer. Note that turning
6069 off orgstruct-mode will *not* remove these additional settings."
6070 (orgstruct-mode 1)
6071 (let (var val)
6072 (mapc
6073 (lambda (x)
6074 (when (string-match
6075 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6076 (symbol-name (car x)))
6077 (setq var (car x) val (nth 1 x))
6078 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
6079 org-local-vars)))
6081 (defun orgstruct-error ()
6082 "Error when there is no default binding for a structure key."
6083 (interactive)
6084 (error "This key has no function outside structure elements"))
6086 (defun orgstruct-setup ()
6087 "Setup orgstruct keymaps."
6088 (let ((nfunc 0)
6089 (bindings
6090 (list
6091 '([(meta up)] org-metaup)
6092 '([(meta down)] org-metadown)
6093 '([(meta left)] org-metaleft)
6094 '([(meta right)] org-metaright)
6095 '([(meta shift up)] org-shiftmetaup)
6096 '([(meta shift down)] org-shiftmetadown)
6097 '([(meta shift left)] org-shiftmetaleft)
6098 '([(meta shift right)] org-shiftmetaright)
6099 '([(shift up)] org-shiftup)
6100 '([(shift down)] org-shiftdown)
6101 '([(shift left)] org-shiftleft)
6102 '([(shift right)] org-shiftright)
6103 '("\C-c\C-c" org-ctrl-c-ctrl-c)
6104 '("\M-q" fill-paragraph)
6105 '("\C-c^" org-sort)
6106 '("\C-c-" org-cycle-list-bullet)))
6107 elt key fun cmd)
6108 (while (setq elt (pop bindings))
6109 (setq nfunc (1+ nfunc))
6110 (setq key (org-key (car elt))
6111 fun (nth 1 elt)
6112 cmd (orgstruct-make-binding fun nfunc key))
6113 (org-defkey orgstruct-mode-map key cmd))
6115 ;; Special treatment needed for TAB and RET
6116 (org-defkey orgstruct-mode-map [(tab)]
6117 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
6118 (org-defkey orgstruct-mode-map "\C-i"
6119 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
6121 (org-defkey orgstruct-mode-map "\M-\C-m"
6122 (orgstruct-make-binding 'org-insert-heading 105
6123 "\M-\C-m" [(meta return)]))
6124 (org-defkey orgstruct-mode-map [(meta return)]
6125 (orgstruct-make-binding 'org-insert-heading 106
6126 [(meta return)] "\M-\C-m"))
6128 (org-defkey orgstruct-mode-map [(shift meta return)]
6129 (orgstruct-make-binding 'org-insert-todo-heading 107
6130 [(meta return)] "\M-\C-m"))
6132 (unless org-local-vars
6133 (setq org-local-vars (org-get-local-variables)))
6137 (defun orgstruct-make-binding (fun n &rest keys)
6138 "Create a function for binding in the structure minor mode.
6139 FUN is the command to call inside a table. N is used to create a unique
6140 command name. KEYS are keys that should be checked in for a command
6141 to execute outside of tables."
6142 (eval
6143 (list 'defun
6144 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6145 '(arg)
6146 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6147 "Outside of structure, run the binding of `"
6148 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6149 "'.")
6150 '(interactive "p")
6151 (list 'if
6152 '(org-context-p 'headline 'item)
6153 (list 'org-run-like-in-org-mode (list 'quote fun))
6154 (list 'let '(orgstruct-mode)
6155 (list 'call-interactively
6156 (append '(or)
6157 (mapcar (lambda (k)
6158 (list 'key-binding k))
6159 keys)
6160 '('orgstruct-error))))))))
6162 (defun org-context-p (&rest contexts)
6163 "Check if local context is any of CONTEXTS.
6164 Possible values in the list of contexts are `table', `headline', and `item'."
6165 (let ((pos (point)))
6166 (goto-char (point-at-bol))
6167 (prog1 (or (and (memq 'table contexts)
6168 (looking-at "[ \t]*|"))
6169 (and (memq 'headline contexts)
6170 ;;????????? (looking-at "\\*+"))
6171 (looking-at outline-regexp))
6172 (and (memq 'item contexts)
6173 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
6174 (goto-char pos))))
6176 (defun org-get-local-variables ()
6177 "Return a list of all local variables in an org-mode buffer."
6178 (let (varlist)
6179 (with-current-buffer (get-buffer-create "*Org tmp*")
6180 (erase-buffer)
6181 (org-mode)
6182 (setq varlist (buffer-local-variables)))
6183 (kill-buffer "*Org tmp*")
6184 (delq nil
6185 (mapcar
6186 (lambda (x)
6187 (setq x
6188 (if (symbolp x)
6189 (list x)
6190 (list (car x) (list 'quote (cdr x)))))
6191 (if (string-match
6192 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6193 (symbol-name (car x)))
6194 x nil))
6195 varlist))))
6197 ;;;###autoload
6198 (defun org-run-like-in-org-mode (cmd)
6199 (org-load-modules-maybe)
6200 (unless org-local-vars
6201 (setq org-local-vars (org-get-local-variables)))
6202 (eval (list 'let org-local-vars
6203 (list 'call-interactively (list 'quote cmd)))))
6205 ;;;; Archiving
6207 (defun org-get-category (&optional pos)
6208 "Get the category applying to position POS."
6209 (get-text-property (or pos (point)) 'org-category))
6211 (defun org-refresh-category-properties ()
6212 "Refresh category text properties in the buffer."
6213 (let ((def-cat (cond
6214 ((null org-category)
6215 (if buffer-file-name
6216 (file-name-sans-extension
6217 (file-name-nondirectory buffer-file-name))
6218 "???"))
6219 ((symbolp org-category) (symbol-name org-category))
6220 (t org-category)))
6221 beg end cat pos optionp)
6222 (org-unmodified
6223 (save-excursion
6224 (save-restriction
6225 (widen)
6226 (goto-char (point-min))
6227 (put-text-property (point) (point-max) 'org-category def-cat)
6228 (while (re-search-forward
6229 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6230 (setq pos (match-end 0)
6231 optionp (equal (char-after (match-beginning 0)) ?#)
6232 cat (org-trim (match-string 2)))
6233 (if optionp
6234 (setq beg (point-at-bol) end (point-max))
6235 (org-back-to-heading t)
6236 (setq beg (point) end (org-end-of-subtree t t)))
6237 (put-text-property beg end 'org-category cat)
6238 (goto-char pos)))))))
6241 ;;;; Link Stuff
6243 ;;; Link abbreviations
6245 (defun org-link-expand-abbrev (link)
6246 "Apply replacements as defined in `org-link-abbrev-alist."
6247 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6248 (let* ((key (match-string 1 link))
6249 (as (or (assoc key org-link-abbrev-alist-local)
6250 (assoc key org-link-abbrev-alist)))
6251 (tag (and (match-end 2) (match-string 3 link)))
6252 rpl)
6253 (if (not as)
6254 link
6255 (setq rpl (cdr as))
6256 (cond
6257 ((symbolp rpl) (funcall rpl tag))
6258 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
6259 ((string-match "%h" rpl)
6260 (replace-match (url-hexify-string (or tag "")) t t rpl))
6261 (t (concat rpl tag)))))
6262 link))
6264 ;;; Storing and inserting links
6266 (defvar org-insert-link-history nil
6267 "Minibuffer history for links inserted with `org-insert-link'.")
6269 (defvar org-stored-links nil
6270 "Contains the links stored with `org-store-link'.")
6272 (defvar org-store-link-plist nil
6273 "Plist with info about the most recently link created with `org-store-link'.")
6275 (defvar org-link-protocols nil
6276 "Link protocols added to Org-mode using `org-add-link-type'.")
6278 (defvar org-store-link-functions nil
6279 "List of functions that are called to create and store a link.
6280 Each function will be called in turn until one returns a non-nil
6281 value. Each function should check if it is responsible for creating
6282 this link (for example by looking at the major mode).
6283 If not, it must exit and return nil.
6284 If yes, it should return a non-nil value after a calling
6285 `org-store-link-props' with a list of properties and values.
6286 Special properties are:
6288 :type The link prefix. like \"http\". This must be given.
6289 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6290 This is obligatory as well.
6291 :description Optional default description for the second pair
6292 of brackets in an Org-mode link. The user can still change
6293 this when inserting this link into an Org-mode buffer.
6295 In addition to these, any additional properties can be specified
6296 and then used in remember templates.")
6298 (defun org-add-link-type (type &optional follow export)
6299 "Add TYPE to the list of `org-link-types'.
6300 Re-compute all regular expressions depending on `org-link-types'
6302 FOLLOW and EXPORT are two functions.
6304 FOLLOW should take the link path as the single argument and do whatever
6305 is necessary to follow the link, for example find a file or display
6306 a mail message.
6308 EXPORT should format the link path for export to one of the export formats.
6309 It should be a function accepting three arguments:
6311 path the path of the link, the text after the prefix (like \"http:\")
6312 desc the description of the link, if any, nil if there was no description
6313 format the export format, a symbol like `html' or `latex'.
6315 The function may use the FORMAT information to return different values
6316 depending on the format. The return value will be put literally into
6317 the exported file.
6318 Org-mode has a built-in default for exporting links. If you are happy with
6319 this default, there is no need to define an export function for the link
6320 type. For a simple example of an export function, see `org-bbdb.el'."
6321 (add-to-list 'org-link-types type t)
6322 (org-make-link-regexps)
6323 (if (assoc type org-link-protocols)
6324 (setcdr (assoc type org-link-protocols) (list follow export))
6325 (push (list type follow export) org-link-protocols)))
6327 ;;;###autoload
6328 (defun org-store-link (arg)
6329 "\\<org-mode-map>Store an org-link to the current location.
6330 This link is added to `org-stored-links' and can later be inserted
6331 into an org-buffer with \\[org-insert-link].
6333 For some link types, a prefix arg is interpreted:
6334 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
6335 For file links, arg negates `org-context-in-file-links'."
6336 (interactive "P")
6337 (org-load-modules-maybe)
6338 (setq org-store-link-plist nil) ; reset
6339 (let (link cpltxt desc description search txt)
6340 (cond
6342 ((run-hook-with-args-until-success 'org-store-link-functions)
6343 (setq link (plist-get org-store-link-plist :link)
6344 desc (or (plist-get org-store-link-plist :description) link)))
6346 ((equal (buffer-name) "*Org Edit Src Example*")
6347 (let (label gc)
6348 (while (or (not label)
6349 (save-excursion
6350 (save-restriction
6351 (widen)
6352 (goto-char (point-min))
6353 (re-search-forward
6354 (regexp-quote (format org-coderef-label-format label))
6355 nil t))))
6356 (when label (message "Label exists already") (sit-for 2))
6357 (setq label (read-string "Code line label: " label)))
6358 (end-of-line 1)
6359 (setq link (format org-coderef-label-format label))
6360 (setq gc (- 79 (length link)))
6361 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
6362 (insert link)
6363 (setq link (concat "(" label ")") desc nil)))
6365 ((eq major-mode 'calendar-mode)
6366 (let ((cd (calendar-cursor-to-date)))
6367 (setq link
6368 (format-time-string
6369 (car org-time-stamp-formats)
6370 (apply 'encode-time
6371 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6372 nil nil nil))))
6373 (org-store-link-props :type "calendar" :date cd)))
6375 ((eq major-mode 'w3-mode)
6376 (setq cpltxt (url-view-url t)
6377 link (org-make-link cpltxt))
6378 (org-store-link-props :type "w3" :url (url-view-url t)))
6380 ((eq major-mode 'w3m-mode)
6381 (setq cpltxt (or w3m-current-title w3m-current-url)
6382 link (org-make-link w3m-current-url))
6383 (org-store-link-props :type "w3m" :url (url-view-url t)))
6385 ((setq search (run-hook-with-args-until-success
6386 'org-create-file-search-functions))
6387 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6388 "::" search))
6389 (setq cpltxt (or description link)))
6391 ((eq major-mode 'image-mode)
6392 (setq cpltxt (concat "file:"
6393 (abbreviate-file-name buffer-file-name))
6394 link (org-make-link cpltxt))
6395 (org-store-link-props :type "image" :file buffer-file-name))
6397 ((eq major-mode 'dired-mode)
6398 ;; link to the file in the current line
6399 (setq cpltxt (concat "file:"
6400 (abbreviate-file-name
6401 (expand-file-name
6402 (dired-get-filename nil t))))
6403 link (org-make-link cpltxt)))
6405 ((and buffer-file-name (org-mode-p))
6406 (cond
6407 ((org-in-regexp "<<\\(.*?\\)>>")
6408 (setq cpltxt
6409 (concat "file:"
6410 (abbreviate-file-name buffer-file-name)
6411 "::" (match-string 1))
6412 link (org-make-link cpltxt)))
6413 ((and (featurep 'org-id)
6414 (or (eq org-link-to-org-use-id t)
6415 (and (eq org-link-to-org-use-id 'create-if-interactive)
6416 (interactive-p))
6417 (and org-link-to-org-use-id
6418 (condition-case nil
6419 (org-entry-get nil "ID")
6420 (error nil)))))
6421 ;; We can make a link using the ID.
6422 (setq link (condition-case nil
6423 (prog1 (org-id-store-link)
6424 (setq desc (plist-get org-store-link-plist
6425 :description)))
6426 (error
6427 ;; probably before first headline, link to file only
6428 (concat "file:"
6429 (abbreviate-file-name buffer-file-name))))))
6431 ;; Just link to current headline
6432 (setq cpltxt (concat "file:"
6433 (abbreviate-file-name buffer-file-name)))
6434 ;; Add a context search string
6435 (when (org-xor org-context-in-file-links arg)
6436 (setq txt (cond
6437 ((org-on-heading-p) nil)
6438 ((org-region-active-p)
6439 (buffer-substring (region-beginning) (region-end)))
6440 (t nil)))
6441 (when (or (null txt) (string-match "\\S-" txt))
6442 (setq cpltxt
6443 (concat cpltxt "::"
6444 (condition-case nil
6445 (org-make-org-heading-search-string txt)
6446 (error "")))
6447 desc "NONE")))
6448 (if (string-match "::\\'" cpltxt)
6449 (setq cpltxt (substring cpltxt 0 -2)))
6450 (setq link (org-make-link cpltxt)))))
6452 ((buffer-file-name (buffer-base-buffer))
6453 ;; Just link to this file here.
6454 (setq cpltxt (concat "file:"
6455 (abbreviate-file-name
6456 (buffer-file-name (buffer-base-buffer)))))
6457 ;; Add a context string
6458 (when (org-xor org-context-in-file-links arg)
6459 (setq txt (if (org-region-active-p)
6460 (buffer-substring (region-beginning) (region-end))
6461 (buffer-substring (point-at-bol) (point-at-eol))))
6462 ;; Only use search option if there is some text.
6463 (when (string-match "\\S-" txt)
6464 (setq cpltxt
6465 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6466 desc "NONE")))
6467 (setq link (org-make-link cpltxt)))
6469 ((interactive-p)
6470 (error "Cannot link to a buffer which is not visiting a file"))
6472 (t (setq link nil)))
6474 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6475 (setq link (or link cpltxt)
6476 desc (or desc cpltxt))
6477 (if (equal desc "NONE") (setq desc nil))
6479 (if (and (interactive-p) link)
6480 (progn
6481 (setq org-stored-links
6482 (cons (list link desc) org-stored-links))
6483 (message "Stored: %s" (or desc link)))
6484 (and link (org-make-link-string link desc)))))
6486 (defun org-store-link-props (&rest plist)
6487 "Store link properties, extract names and addresses."
6488 (let (x adr)
6489 (when (setq x (plist-get plist :from))
6490 (setq adr (mail-extract-address-components x))
6491 (setq plist (plist-put plist :fromname (car adr)))
6492 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
6493 (when (setq x (plist-get plist :to))
6494 (setq adr (mail-extract-address-components x))
6495 (setq plist (plist-put plist :toname (car adr)))
6496 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
6497 (let ((from (plist-get plist :from))
6498 (to (plist-get plist :to)))
6499 (when (and from to org-from-is-user-regexp)
6500 (setq plist
6501 (plist-put plist :fromto
6502 (if (string-match org-from-is-user-regexp from)
6503 (concat "to %t")
6504 (concat "from %f"))))))
6505 (setq org-store-link-plist plist))
6507 (defun org-add-link-props (&rest plist)
6508 "Add these properties to the link property list."
6509 (let (key value)
6510 (while plist
6511 (setq key (pop plist) value (pop plist))
6512 (setq org-store-link-plist
6513 (plist-put org-store-link-plist key value)))))
6515 (defun org-email-link-description (&optional fmt)
6516 "Return the description part of an email link.
6517 This takes information from `org-store-link-plist' and formats it
6518 according to FMT (default from `org-email-link-description-format')."
6519 (setq fmt (or fmt org-email-link-description-format))
6520 (let* ((p org-store-link-plist)
6521 (to (plist-get p :toaddress))
6522 (from (plist-get p :fromaddress))
6523 (table
6524 (list
6525 (cons "%c" (plist-get p :fromto))
6526 (cons "%F" (plist-get p :from))
6527 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
6528 (cons "%T" (plist-get p :to))
6529 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
6530 (cons "%s" (plist-get p :subject))
6531 (cons "%m" (plist-get p :message-id)))))
6532 (when (string-match "%c" fmt)
6533 ;; Check if the user wrote this message
6534 (if (and org-from-is-user-regexp from to
6535 (save-match-data (string-match org-from-is-user-regexp from)))
6536 (setq fmt (replace-match "to %t" t t fmt))
6537 (setq fmt (replace-match "from %f" t t fmt))))
6538 (org-replace-escapes fmt table)))
6540 (defun org-make-org-heading-search-string (&optional string heading)
6541 "Make search string for STRING or current headline."
6542 (interactive)
6543 (let ((s (or string (org-get-heading))))
6544 (unless (and string (not heading))
6545 ;; We are using a headline, clean up garbage in there.
6546 (if (string-match org-todo-regexp s)
6547 (setq s (replace-match "" t t s)))
6548 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
6549 (setq s (replace-match "" t t s)))
6550 (setq s (org-trim s))
6551 (if (string-match (concat "^\\(" org-quote-string "\\|"
6552 org-comment-string "\\)") s)
6553 (setq s (replace-match "" t t s)))
6554 (while (string-match org-ts-regexp s)
6555 (setq s (replace-match "" t t s))))
6556 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
6557 (setq s (replace-match " " t t s)))
6558 (or string (setq s (concat "*" s))) ; Add * for headlines
6559 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
6561 (defun org-make-link (&rest strings)
6562 "Concatenate STRINGS."
6563 (apply 'concat strings))
6565 (defun org-make-link-string (link &optional description)
6566 "Make a link with brackets, consisting of LINK and DESCRIPTION."
6567 (unless (string-match "\\S-" link)
6568 (error "Empty link"))
6569 (when (stringp description)
6570 ;; Remove brackets from the description, they are fatal.
6571 (while (string-match "\\[" description)
6572 (setq description (replace-match "{" t t description)))
6573 (while (string-match "\\]" description)
6574 (setq description (replace-match "}" t t description))))
6575 (when (equal (org-link-escape link) description)
6576 ;; No description needed, it is identical
6577 (setq description nil))
6578 (when (and (not description)
6579 (not (equal link (org-link-escape link))))
6580 (setq description (org-extract-attributes link)))
6581 (concat "[[" (org-link-escape link) "]"
6582 (if description (concat "[" description "]") "")
6583 "]"))
6585 (defconst org-link-escape-chars
6586 '((?\ . "%20")
6587 (?\[ . "%5B")
6588 (?\] . "%5D")
6589 (?\340 . "%E0") ; `a
6590 (?\342 . "%E2") ; ^a
6591 (?\347 . "%E7") ; ,c
6592 (?\350 . "%E8") ; `e
6593 (?\351 . "%E9") ; 'e
6594 (?\352 . "%EA") ; ^e
6595 (?\356 . "%EE") ; ^i
6596 (?\364 . "%F4") ; ^o
6597 (?\371 . "%F9") ; `u
6598 (?\373 . "%FB") ; ^u
6599 (?\; . "%3B")
6600 (?? . "%3F")
6601 (?= . "%3D")
6602 (?+ . "%2B")
6604 "Association list of escapes for some characters problematic in links.
6605 This is the list that is used for internal purposes.")
6607 (defconst org-link-escape-chars-browser
6608 '((?\ . "%20")) ; 32 for the SPC char
6609 "Association list of escapes for some characters problematic in links.
6610 This is the list that is used before handing over to the browser.")
6612 (defun org-link-escape (text &optional table)
6613 "Escape characters in TEXT that are problematic for links."
6614 (setq table (or table org-link-escape-chars))
6615 (when text
6616 (let ((re (mapconcat (lambda (x) (regexp-quote
6617 (char-to-string (car x))))
6618 table "\\|")))
6619 (while (string-match re text)
6620 (setq text
6621 (replace-match
6622 (cdr (assoc (string-to-char (match-string 0 text))
6623 table))
6624 t t text)))
6625 text)))
6627 (defun org-link-unescape (text &optional table)
6628 "Reverse the action of `org-link-escape'."
6629 (setq table (or table org-link-escape-chars))
6630 (when text
6631 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
6632 table "\\|")))
6633 (while (string-match re text)
6634 (setq text
6635 (replace-match
6636 (char-to-string (car (rassoc (match-string 0 text) table)))
6637 t t text)))
6638 text)))
6640 (defun org-xor (a b)
6641 "Exclusive or."
6642 (if a (not b) b))
6644 (defun org-fixup-message-id-for-http (s)
6645 "Replace special characters in a message id, so it can be used in an http query."
6646 (while (string-match "<" s)
6647 (setq s (replace-match "%3C" t t s)))
6648 (while (string-match ">" s)
6649 (setq s (replace-match "%3E" t t s)))
6650 (while (string-match "@" s)
6651 (setq s (replace-match "%40" t t s)))
6654 ;;;###autoload
6655 (defun org-insert-link-global ()
6656 "Insert a link like Org-mode does.
6657 This command can be called in any mode to insert a link in Org-mode syntax."
6658 (interactive)
6659 (org-load-modules-maybe)
6660 (org-run-like-in-org-mode 'org-insert-link))
6662 (defun org-insert-link (&optional complete-file link-location)
6663 "Insert a link. At the prompt, enter the link.
6665 Completion can be used to insert any of the link protocol prefixes like
6666 http or ftp in use.
6668 The history can be used to select a link previously stored with
6669 `org-store-link'. When the empty string is entered (i.e. if you just
6670 press RET at the prompt), the link defaults to the most recently
6671 stored link. As SPC triggers completion in the minibuffer, you need to
6672 use M-SPC or C-q SPC to force the insertion of a space character.
6674 You will also be prompted for a description, and if one is given, it will
6675 be displayed in the buffer instead of the link.
6677 If there is already a link at point, this command will allow you to edit link
6678 and description parts.
6680 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
6681 be selected using completion. The path to the file will be relative to the
6682 current directory if the file is in the current directory or a subdirectory.
6683 Otherwise, the link will be the absolute path as completed in the minibuffer
6684 \(i.e. normally ~/path/to/file). You can configure this behavior using the
6685 option `org-link-file-path-type'.
6687 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
6688 the current directory or below.
6690 With three \\[universal-argument] prefixes, negate the meaning of
6691 `org-keep-stored-link-after-insertion'.
6693 If `org-make-link-description-function' is non-nil, this function will be
6694 called with the link target, and the result will be the default
6695 link description.
6697 If the LINK-LOCATION parameter is non-nil, this value will be
6698 used as the link location instead of reading one interactively."
6699 (interactive "P")
6700 (let* ((wcf (current-window-configuration))
6701 (region (if (org-region-active-p)
6702 (buffer-substring (region-beginning) (region-end))))
6703 (remove (and region (list (region-beginning) (region-end))))
6704 (desc region)
6705 tmphist ; byte-compile incorrectly complains about this
6706 (link link-location)
6707 entry file)
6708 (cond
6709 (link-location) ; specified by arg, just use it.
6710 ((org-in-regexp org-bracket-link-regexp 1)
6711 ;; We do have a link at point, and we are going to edit it.
6712 (setq remove (list (match-beginning 0) (match-end 0)))
6713 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
6714 (setq link (read-string "Link: "
6715 (org-link-unescape
6716 (org-match-string-no-properties 1)))))
6717 ((or (org-in-regexp org-angle-link-re)
6718 (org-in-regexp org-plain-link-re))
6719 ;; Convert to bracket link
6720 (setq remove (list (match-beginning 0) (match-end 0))
6721 link (read-string "Link: "
6722 (org-remove-angle-brackets (match-string 0)))))
6723 ((member complete-file '((4) (16)))
6724 ;; Completing read for file names.
6725 (setq file (read-file-name "File: "))
6726 (let ((pwd (file-name-as-directory (expand-file-name ".")))
6727 (pwd1 (file-name-as-directory (abbreviate-file-name
6728 (expand-file-name ".")))))
6729 (cond
6730 ((equal complete-file '(16))
6731 (setq link (org-make-link
6732 "file:"
6733 (abbreviate-file-name (expand-file-name file)))))
6734 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
6735 (setq link (org-make-link "file:" (match-string 1 file))))
6736 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
6737 (expand-file-name file))
6738 (setq link (org-make-link
6739 "file:" (match-string 1 (expand-file-name file)))))
6740 (t (setq link (org-make-link "file:" file))))))
6742 ;; Read link, with completion for stored links.
6743 (with-output-to-temp-buffer "*Org Links*"
6744 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
6745 (when org-stored-links
6746 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
6747 (princ (mapconcat
6748 (lambda (x)
6749 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
6750 (reverse org-stored-links) "\n"))))
6751 (let ((cw (selected-window)))
6752 (select-window (get-buffer-window "*Org Links*"))
6753 (setq truncate-lines t)
6754 (org-fit-window-to-buffer)
6755 (select-window cw))
6756 ;; Fake a link history, containing the stored links.
6757 (setq tmphist (append (mapcar 'car org-stored-links)
6758 org-insert-link-history))
6759 (unwind-protect
6760 (setq link
6761 (let ((org-completion-use-ido nil))
6762 (org-completing-read
6763 "Link: "
6764 (append
6765 (mapcar (lambda (x) (list (concat (car x) ":")))
6766 (append org-link-abbrev-alist-local org-link-abbrev-alist))
6767 (mapcar (lambda (x) (list (concat x ":")))
6768 org-link-types))
6769 nil nil nil
6770 'tmphist
6771 (or (car (car org-stored-links))))))
6772 (set-window-configuration wcf)
6773 (kill-buffer "*Org Links*"))
6774 (setq entry (assoc link org-stored-links))
6775 (or entry (push link org-insert-link-history))
6776 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
6777 (not org-keep-stored-link-after-insertion))
6778 (setq org-stored-links (delq (assoc link org-stored-links)
6779 org-stored-links)))
6780 (setq desc (or desc (nth 1 entry)))))
6782 (if (string-match org-plain-link-re link)
6783 ;; URL-like link, normalize the use of angular brackets.
6784 (setq link (org-make-link (org-remove-angle-brackets link))))
6786 ;; Check if we are linking to the current file with a search option
6787 ;; If yes, simplify the link by using only the search option.
6788 (when (and buffer-file-name
6789 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
6790 (let* ((path (match-string 1 link))
6791 (case-fold-search nil)
6792 (search (match-string 2 link)))
6793 (save-match-data
6794 (if (equal (file-truename buffer-file-name) (file-truename path))
6795 ;; We are linking to this same file, with a search option
6796 (setq link search)))))
6798 ;; Check if we can/should use a relative path. If yes, simplify the link
6799 (when (string-match "^file:\\(.*\\)" link)
6800 (let* ((path (match-string 1 link))
6801 (origpath path)
6802 (case-fold-search nil))
6803 (cond
6804 ((or (eq org-link-file-path-type 'absolute)
6805 (equal complete-file '(16)))
6806 (setq path (abbreviate-file-name (expand-file-name path))))
6807 ((eq org-link-file-path-type 'noabbrev)
6808 (setq path (expand-file-name path)))
6809 ((eq org-link-file-path-type 'relative)
6810 (setq path (file-relative-name path)))
6812 (save-match-data
6813 (if (string-match (concat "^" (regexp-quote
6814 (file-name-as-directory
6815 (expand-file-name "."))))
6816 (expand-file-name path))
6817 ;; We are linking a file with relative path name.
6818 (setq path (substring (expand-file-name path)
6819 (match-end 0)))
6820 (setq path (abbreviate-file-name (expand-file-name path)))))))
6821 (setq link (concat "file:" path))
6822 (if (equal desc origpath)
6823 (setq desc path))))
6825 (if org-make-link-description-function
6826 (setq desc (funcall org-make-link-description-function link desc)))
6828 (setq desc (read-string "Description: " desc))
6829 (unless (string-match "\\S-" desc) (setq desc nil))
6830 (if remove (apply 'delete-region remove))
6831 (insert (org-make-link-string link desc))))
6833 (defun org-completing-read (&rest args)
6834 "Completing-read with SPACE being a normal character."
6835 (let ((minibuffer-local-completion-map
6836 (copy-keymap minibuffer-local-completion-map)))
6837 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
6838 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
6839 (apply 'org-ido-completing-read args)))
6841 (defun org-ido-completing-read (&rest args)
6842 "Completing-read using `ido-mode' speedups if available"
6843 (if (and org-completion-use-ido
6844 (fboundp 'ido-completing-read)
6845 (boundp 'ido-mode) ido-mode
6846 (listp (second args)))
6847 (apply 'ido-completing-read (concat (car args)) (cdr args))
6848 (apply 'completing-read args)))
6850 (defun org-extract-attributes (s)
6851 "Extract the attributes cookie from a string and set as text property."
6852 (let (a attr (start 0) key value)
6853 (save-match-data
6854 (when (string-match "{{\\([^}]+\\)}}$" s)
6855 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
6856 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
6857 (setq key (match-string 1 a) value (match-string 2 a)
6858 start (match-end 0)
6859 attr (plist-put attr (intern key) value))))
6860 (org-add-props s nil 'org-attr attr))
6863 (defun org-attributes-to-string (plist)
6864 "Format a property list into an HTML attribute list."
6865 (let ((s "") key value)
6866 (while plist
6867 (setq key (pop plist) value (pop plist))
6868 (and value
6869 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
6872 ;;; Opening/following a link
6874 (defvar org-link-search-failed nil)
6876 (defun org-next-link ()
6877 "Move forward to the next link.
6878 If the link is in hidden text, expose it."
6879 (interactive)
6880 (when (and org-link-search-failed (eq this-command last-command))
6881 (goto-char (point-min))
6882 (message "Link search wrapped back to beginning of buffer"))
6883 (setq org-link-search-failed nil)
6884 (let* ((pos (point))
6885 (ct (org-context))
6886 (a (assoc :link ct)))
6887 (if a (goto-char (nth 2 a)))
6888 (if (re-search-forward org-any-link-re nil t)
6889 (progn
6890 (goto-char (match-beginning 0))
6891 (if (org-invisible-p) (org-show-context)))
6892 (goto-char pos)
6893 (setq org-link-search-failed t)
6894 (error "No further link found"))))
6896 (defun org-previous-link ()
6897 "Move backward to the previous link.
6898 If the link is in hidden text, expose it."
6899 (interactive)
6900 (when (and org-link-search-failed (eq this-command last-command))
6901 (goto-char (point-max))
6902 (message "Link search wrapped back to end of buffer"))
6903 (setq org-link-search-failed nil)
6904 (let* ((pos (point))
6905 (ct (org-context))
6906 (a (assoc :link ct)))
6907 (if a (goto-char (nth 1 a)))
6908 (if (re-search-backward org-any-link-re nil t)
6909 (progn
6910 (goto-char (match-beginning 0))
6911 (if (org-invisible-p) (org-show-context)))
6912 (goto-char pos)
6913 (setq org-link-search-failed t)
6914 (error "No further link found"))))
6916 (defun org-translate-link (s)
6917 "Translate a link string if a translation function has been defined."
6918 (if (and org-link-translation-function
6919 (fboundp org-link-translation-function)
6920 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
6921 (progn
6922 (setq s (funcall org-link-translation-function
6923 (match-string 1) (match-string 2)))
6924 (concat (car s) ":" (cdr s)))
6927 (defun org-translate-link-from-planner (type path)
6928 "Translate a link from Emacs Planner syntax so that Org can follow it.
6929 This is still an experimental function, your mileage may vary."
6930 (cond
6931 ((member type '("http" "https" "news" "ftp"))
6932 ;; standard Internet links are the same.
6933 nil)
6934 ((and (equal type "irc") (string-match "^//" path))
6935 ;; Planner has two / at the beginning of an irc link, we have 1.
6936 ;; We should have zero, actually....
6937 (setq path (substring path 1)))
6938 ((and (equal type "lisp") (string-match "^/" path))
6939 ;; Planner has a slash, we do not.
6940 (setq type "elisp" path (substring path 1)))
6941 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
6942 ;; A typical message link. Planner has the id after the fina slash,
6943 ;; we separate it with a hash mark
6944 (setq path (concat (match-string 1 path) "#"
6945 (org-remove-angle-brackets (match-string 2 path)))))
6947 (cons type path))
6949 (defun org-find-file-at-mouse (ev)
6950 "Open file link or URL at mouse."
6951 (interactive "e")
6952 (mouse-set-point ev)
6953 (org-open-at-point 'in-emacs))
6955 (defun org-open-at-mouse (ev)
6956 "Open file link or URL at mouse."
6957 (interactive "e")
6958 (mouse-set-point ev)
6959 (if (eq major-mode 'org-agenda-mode)
6960 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
6961 (org-open-at-point))
6963 (defvar org-window-config-before-follow-link nil
6964 "The window configuration before following a link.
6965 This is saved in case the need arises to restore it.")
6967 (defvar org-open-link-marker (make-marker)
6968 "Marker pointing to the location where `org-open-at-point; was called.")
6970 ;;;###autoload
6971 (defun org-open-at-point-global ()
6972 "Follow a link like Org-mode does.
6973 This command can be called in any mode to follow a link that has
6974 Org-mode syntax."
6975 (interactive)
6976 (org-run-like-in-org-mode 'org-open-at-point))
6978 ;;;###autoload
6979 (defun org-open-link-from-string (s &optional arg)
6980 "Open a link in the string S, as if it was in Org-mode."
6981 (interactive "sLink: \nP")
6982 (with-temp-buffer
6983 (let ((org-inhibit-startup t))
6984 (org-mode)
6985 (insert s)
6986 (goto-char (point-min))
6987 (org-open-at-point arg))))
6989 (defun org-open-at-point (&optional in-emacs)
6990 "Open link at or after point.
6991 If there is no link at point, this function will search forward up to
6992 the end of the current subtree.
6993 Normally, files will be opened by an appropriate application. If the
6994 optional argument IN-EMACS is non-nil, Emacs will visit the file.
6995 With a double prefix argument, try to open outside of Emacs, in the
6996 application the system uses for this file type."
6997 (interactive "P")
6998 (org-load-modules-maybe)
6999 (move-marker org-open-link-marker (point))
7000 (setq org-window-config-before-follow-link (current-window-configuration))
7001 (org-remove-occur-highlights nil nil t)
7002 (cond
7003 ((org-at-timestamp-p t) (org-follow-timestamp-link))
7004 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
7005 (org-footnote-action))
7007 (let (type path link line search (pos (point)))
7008 (catch 'match
7009 (save-excursion
7010 (skip-chars-forward "^]\n\r")
7011 (when (org-in-regexp org-bracket-link-regexp)
7012 (setq link (org-extract-attributes
7013 (org-link-unescape (org-match-string-no-properties 1))))
7014 (while (string-match " *\n *" link)
7015 (setq link (replace-match " " t t link)))
7016 (setq link (org-link-expand-abbrev link))
7017 (cond
7018 ((or (file-name-absolute-p link)
7019 (string-match "^\\.\\.?/" link))
7020 (setq type "file" path link))
7021 ((string-match org-link-re-with-space3 link)
7022 (setq type (match-string 1 link) path (match-string 2 link)))
7023 (t (setq type "thisfile" path link)))
7024 (throw 'match t)))
7026 (when (get-text-property (point) 'org-linked-text)
7027 (setq type "thisfile"
7028 pos (if (get-text-property (1+ (point)) 'org-linked-text)
7029 (1+ (point)) (point))
7030 path (buffer-substring
7031 (previous-single-property-change pos 'org-linked-text)
7032 (next-single-property-change pos 'org-linked-text)))
7033 (throw 'match t))
7035 (save-excursion
7036 (when (or (org-in-regexp org-angle-link-re)
7037 (org-in-regexp org-plain-link-re))
7038 (setq type (match-string 1) path (match-string 2))
7039 (throw 'match t)))
7040 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
7041 (setq type "tree-match"
7042 path (match-string 1))
7043 (throw 'match t))
7044 (save-excursion
7045 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
7046 (setq type "tags"
7047 path (match-string 1))
7048 (while (string-match ":" path)
7049 (setq path (replace-match "+" t t path)))
7050 (throw 'match t))))
7051 (unless path
7052 (error "No link found"))
7053 ;; Remove any trailing spaces in path
7054 (if (string-match " +\\'" path)
7055 (setq path (replace-match "" t t path)))
7056 (if (and org-link-translation-function
7057 (fboundp org-link-translation-function))
7058 ;; Check if we need to translate the link
7059 (let ((tmp (funcall org-link-translation-function type path)))
7060 (setq type (car tmp) path (cdr tmp))))
7062 (cond
7064 ((assoc type org-link-protocols)
7065 (funcall (nth 1 (assoc type org-link-protocols)) path))
7067 ((equal type "mailto")
7068 (let ((cmd (car org-link-mailto-program))
7069 (args (cdr org-link-mailto-program)) args1
7070 (address path) (subject "") a)
7071 (if (string-match "\\(.*\\)::\\(.*\\)" path)
7072 (setq address (match-string 1 path)
7073 subject (org-link-escape (match-string 2 path))))
7074 (while args
7075 (cond
7076 ((not (stringp (car args))) (push (pop args) args1))
7077 (t (setq a (pop args))
7078 (if (string-match "%a" a)
7079 (setq a (replace-match address t t a)))
7080 (if (string-match "%s" a)
7081 (setq a (replace-match subject t t a)))
7082 (push a args1))))
7083 (apply cmd (nreverse args1))))
7085 ((member type '("http" "https" "ftp" "news"))
7086 (browse-url (concat type ":" (org-link-escape
7087 path org-link-escape-chars-browser))))
7089 ((member type '("message"))
7090 (browse-url (concat type ":" path)))
7092 ((string= type "tags")
7093 (org-tags-view in-emacs path))
7094 ((string= type "thisfile")
7095 (if in-emacs
7096 (switch-to-buffer-other-window
7097 (org-get-buffer-for-internal-link (current-buffer)))
7098 (org-mark-ring-push))
7099 (let ((cmd `(org-link-search
7100 ,path
7101 ,(cond ((equal in-emacs '(4)) 'occur)
7102 ((equal in-emacs '(16)) 'org-occur)
7103 (t nil))
7104 ,pos)))
7105 (condition-case nil (eval cmd)
7106 (error (progn (widen) (eval cmd))))))
7108 ((string= type "tree-match")
7109 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
7111 ((string= type "file")
7112 (if (string-match "::\\([0-9]+\\)\\'" path)
7113 (setq line (string-to-number (match-string 1 path))
7114 path (substring path 0 (match-beginning 0)))
7115 (if (string-match "::\\(.+\\)\\'" path)
7116 (setq search (match-string 1 path)
7117 path (substring path 0 (match-beginning 0)))))
7118 (if (string-match "[*?{]" (file-name-nondirectory path))
7119 (dired path)
7120 (org-open-file path in-emacs line search)))
7122 ((string= type "news")
7123 (require 'org-gnus)
7124 (org-gnus-follow-link path))
7126 ((string= type "shell")
7127 (let ((cmd path))
7128 (if (or (not org-confirm-shell-link-function)
7129 (funcall org-confirm-shell-link-function
7130 (format "Execute \"%s\" in shell? "
7131 (org-add-props cmd nil
7132 'face 'org-warning))))
7133 (progn
7134 (message "Executing %s" cmd)
7135 (shell-command cmd))
7136 (error "Abort"))))
7138 ((string= type "elisp")
7139 (let ((cmd path))
7140 (if (or (not org-confirm-elisp-link-function)
7141 (funcall org-confirm-elisp-link-function
7142 (format "Execute \"%s\" as elisp? "
7143 (org-add-props cmd nil
7144 'face 'org-warning))))
7145 (message "%s => %s" cmd
7146 (if (equal (string-to-char cmd) ?\()
7147 (eval (read cmd))
7148 (call-interactively (read cmd))))
7149 (error "Abort"))))
7152 (browse-url-at-point))))))
7153 (move-marker org-open-link-marker nil)
7154 (run-hook-with-args 'org-follow-link-hook))
7156 ;;;; Time estimates
7158 (defun org-get-effort (&optional pom)
7159 "Get the effort estimate for the current entry."
7160 (org-entry-get pom org-effort-property))
7162 ;;; File search
7164 (defvar org-create-file-search-functions nil
7165 "List of functions to construct the right search string for a file link.
7166 These functions are called in turn with point at the location to
7167 which the link should point.
7169 A function in the hook should first test if it would like to
7170 handle this file type, for example by checking the major-mode or
7171 the file extension. If it decides not to handle this file, it
7172 should just return nil to give other functions a chance. If it
7173 does handle the file, it must return the search string to be used
7174 when following the link. The search string will be part of the
7175 file link, given after a double colon, and `org-open-at-point'
7176 will automatically search for it. If special measures must be
7177 taken to make the search successful, another function should be
7178 added to the companion hook `org-execute-file-search-functions',
7179 which see.
7181 A function in this hook may also use `setq' to set the variable
7182 `description' to provide a suggestion for the descriptive text to
7183 be used for this link when it gets inserted into an Org-mode
7184 buffer with \\[org-insert-link].")
7186 (defvar org-execute-file-search-functions nil
7187 "List of functions to execute a file search triggered by a link.
7189 Functions added to this hook must accept a single argument, the
7190 search string that was part of the file link, the part after the
7191 double colon. The function must first check if it would like to
7192 handle this search, for example by checking the major-mode or the
7193 file extension. If it decides not to handle this search, it
7194 should just return nil to give other functions a chance. If it
7195 does handle the search, it must return a non-nil value to keep
7196 other functions from trying.
7198 Each function can access the current prefix argument through the
7199 variable `current-prefix-argument'. Note that a single prefix is
7200 used to force opening a link in Emacs, so it may be good to only
7201 use a numeric or double prefix to guide the search function.
7203 In case this is needed, a function in this hook can also restore
7204 the window configuration before `org-open-at-point' was called using:
7206 (set-window-configuration org-window-config-before-follow-link)")
7208 (defun org-link-search (s &optional type avoid-pos)
7209 "Search for a link search option.
7210 If S is surrounded by forward slashes, it is interpreted as a
7211 regular expression. In org-mode files, this will create an `org-occur'
7212 sparse tree. In ordinary files, `occur' will be used to list matches.
7213 If the current buffer is in `dired-mode', grep will be used to search
7214 in all files. If AVOID-POS is given, ignore matches near that position."
7215 (let ((case-fold-search t)
7216 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
7217 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
7218 (append '(("") (" ") ("\t") ("\n"))
7219 org-emphasis-alist)
7220 "\\|") "\\)"))
7221 (pos (point))
7222 (pre nil) (post nil)
7223 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
7224 (cond
7225 ;; First check if there are any special
7226 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
7227 ;; Now try the builtin stuff
7228 ((save-excursion
7229 (goto-char (point-min))
7230 (and
7231 (re-search-forward
7232 (concat "<<" (regexp-quote s0) ">>") nil t)
7233 (setq type 'dedicated
7234 pos (match-beginning 0))))
7235 ;; There is an exact target for this
7236 (goto-char pos))
7237 ((and (string-match "^(\\(.*\\))$" s0)
7238 (save-excursion
7239 (goto-char (point-min))
7240 (and
7241 (re-search-forward
7242 (concat "[^[]" (regexp-quote
7243 (format org-coderef-label-format
7244 (match-string 1 s0))))
7245 nil t)
7246 (setq type 'dedicated
7247 pos (1+ (match-beginning 0))))))
7248 ;; There is a coderef target for this
7249 (goto-char pos))
7250 ((string-match "^/\\(.*\\)/$" s)
7251 ;; A regular expression
7252 (cond
7253 ((org-mode-p)
7254 (org-occur (match-string 1 s)))
7255 ;;((eq major-mode 'dired-mode)
7256 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
7257 (t (org-do-occur (match-string 1 s)))))
7259 ;; A normal search strings
7260 (when (equal (string-to-char s) ?*)
7261 ;; Anchor on headlines, post may include tags.
7262 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
7263 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
7264 s (substring s 1)))
7265 (remove-text-properties
7266 0 (length s)
7267 '(face nil mouse-face nil keymap nil fontified nil) s)
7268 ;; Make a series of regular expressions to find a match
7269 (setq words (org-split-string s "[ \n\r\t]+")
7271 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
7272 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
7273 "\\)" markers)
7274 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
7275 re2a (concat "[ \t\r\n]" re2a_)
7276 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
7277 re4 (concat "[^a-zA-Z_]" re4_)
7279 re1 (concat pre re2 post)
7280 re3 (concat pre (if pre re4_ re4) post)
7281 re5 (concat pre ".*" re4)
7282 re2 (concat pre re2)
7283 re2a (concat pre (if pre re2a_ re2a))
7284 re4 (concat pre (if pre re4_ re4))
7285 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7286 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7287 re5 "\\)"
7289 (cond
7290 ((eq type 'org-occur) (org-occur reall))
7291 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7292 (t (goto-char (point-min))
7293 (setq type 'fuzzy)
7294 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
7295 (org-search-not-self 1 re1 nil t)
7296 (org-search-not-self 1 re2 nil t)
7297 (org-search-not-self 1 re2a nil t)
7298 (org-search-not-self 1 re3 nil t)
7299 (org-search-not-self 1 re4 nil t)
7300 (org-search-not-self 1 re5 nil t)
7302 (goto-char (match-beginning 1))
7303 (goto-char pos)
7304 (error "No match")))))
7306 ;; Normal string-search
7307 (goto-char (point-min))
7308 (if (search-forward s nil t)
7309 (goto-char (match-beginning 0))
7310 (error "No match"))))
7311 (and (org-mode-p) (org-show-context 'link-search))
7312 type))
7314 (defun org-search-not-self (group &rest args)
7315 "Execute `re-search-forward', but only accept matches that do not
7316 enclose the position of `org-open-link-marker'."
7317 (let ((m org-open-link-marker))
7318 (catch 'exit
7319 (while (apply 're-search-forward args)
7320 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
7321 (goto-char (match-end group))
7322 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
7323 (> (match-beginning 0) (marker-position m))
7324 (< (match-end 0) (marker-position m)))
7325 (save-match-data
7326 (or (not (org-in-regexp
7327 org-bracket-link-analytic-regexp 1))
7328 (not (match-end 4)) ; no description
7329 (and (<= (match-beginning 4) (point))
7330 (>= (match-end 4) (point))))))
7331 (throw 'exit (point))))))))
7333 (defun org-get-buffer-for-internal-link (buffer)
7334 "Return a buffer to be used for displaying the link target of internal links."
7335 (cond
7336 ((not org-display-internal-link-with-indirect-buffer)
7337 buffer)
7338 ((string-match "(Clone)$" (buffer-name buffer))
7339 (message "Buffer is already a clone, not making another one")
7340 ;; we also do not modify visibility in this case
7341 buffer)
7342 (t ; make a new indirect buffer for displaying the link
7343 (let* ((bn (buffer-name buffer))
7344 (ibn (concat bn "(Clone)"))
7345 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
7346 (with-current-buffer ib (org-overview))
7347 ib))))
7349 (defun org-do-occur (regexp &optional cleanup)
7350 "Call the Emacs command `occur'.
7351 If CLEANUP is non-nil, remove the printout of the regular expression
7352 in the *Occur* buffer. This is useful if the regex is long and not useful
7353 to read."
7354 (occur regexp)
7355 (when cleanup
7356 (let ((cwin (selected-window)) win beg end)
7357 (when (setq win (get-buffer-window "*Occur*"))
7358 (select-window win))
7359 (goto-char (point-min))
7360 (when (re-search-forward "match[a-z]+" nil t)
7361 (setq beg (match-end 0))
7362 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7363 (setq end (1- (match-beginning 0)))))
7364 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
7365 (goto-char (point-min))
7366 (select-window cwin))))
7368 ;;; The mark ring for links jumps
7370 (defvar org-mark-ring nil
7371 "Mark ring for positions before jumps in Org-mode.")
7372 (defvar org-mark-ring-last-goto nil
7373 "Last position in the mark ring used to go back.")
7374 ;; Fill and close the ring
7375 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7376 (loop for i from 1 to org-mark-ring-length do
7377 (push (make-marker) org-mark-ring))
7378 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7379 org-mark-ring)
7381 (defun org-mark-ring-push (&optional pos buffer)
7382 "Put the current position or POS into the mark ring and rotate it."
7383 (interactive)
7384 (setq pos (or pos (point)))
7385 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7386 (move-marker (car org-mark-ring)
7387 (or pos (point))
7388 (or buffer (current-buffer)))
7389 (message "%s"
7390 (substitute-command-keys
7391 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7393 (defun org-mark-ring-goto (&optional n)
7394 "Jump to the previous position in the mark ring.
7395 With prefix arg N, jump back that many stored positions. When
7396 called several times in succession, walk through the entire ring.
7397 Org-mode commands jumping to a different position in the current file,
7398 or to another Org-mode file, automatically push the old position
7399 onto the ring."
7400 (interactive "p")
7401 (let (p m)
7402 (if (eq last-command this-command)
7403 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7404 (setq p org-mark-ring))
7405 (setq org-mark-ring-last-goto p)
7406 (setq m (car p))
7407 (switch-to-buffer (marker-buffer m))
7408 (goto-char m)
7409 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
7411 (defun org-remove-angle-brackets (s)
7412 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7413 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7415 (defun org-add-angle-brackets (s)
7416 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7417 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7419 (defun org-remove-double-quotes (s)
7420 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
7421 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
7424 ;;; Following specific links
7426 (defun org-follow-timestamp-link ()
7427 (cond
7428 ((org-at-date-range-p t)
7429 (let ((org-agenda-start-on-weekday)
7430 (t1 (match-string 1))
7431 (t2 (match-string 2)))
7432 (setq t1 (time-to-days (org-time-string-to-time t1))
7433 t2 (time-to-days (org-time-string-to-time t2)))
7434 (org-agenda-list nil t1 (1+ (- t2 t1)))))
7435 ((org-at-timestamp-p t)
7436 (org-agenda-list nil (time-to-days (org-time-string-to-time
7437 (substring (match-string 1) 0 10)))
7439 (t (error "This should not happen"))))
7442 ;;; Following file links
7443 (defvar org-wait nil)
7444 (defun org-open-file (path &optional in-emacs line search)
7445 "Open the file at PATH.
7446 First, this expands any special file name abbreviations. Then the
7447 configuration variable `org-file-apps' is checked if it contains an
7448 entry for this file type, and if yes, the corresponding command is launched.
7450 If no application is found, Emacs simply visits the file.
7452 With optional prefix argument IN-EMACS, Emacs will visit the file.
7453 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
7454 and o use an external application to visit the file.
7456 Optional LINE specifies a line to go to, optional SEARCH a string to
7457 search for. If LINE or SEARCH is given, the file will always be
7458 opened in Emacs.
7459 If the file does not exist, an error is thrown."
7460 (setq in-emacs (or in-emacs line search))
7461 (let* ((file (if (equal path "")
7462 buffer-file-name
7463 (substitute-in-file-name (expand-file-name path))))
7464 (apps (append org-file-apps (org-default-apps)))
7465 (remp (and (assq 'remote apps) (org-file-remote-p file)))
7466 (dirp (if remp nil (file-directory-p file)))
7467 (file (if (and dirp org-open-directory-means-index-dot-org)
7468 (concat (file-name-as-directory file) "index.org")
7469 file))
7470 (a-m-a-p (assq 'auto-mode apps))
7471 (dfile (downcase file))
7472 (old-buffer (current-buffer))
7473 (old-pos (point))
7474 (old-mode major-mode)
7475 ext cmd)
7476 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7477 (setq ext (match-string 1 dfile))
7478 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7479 (setq ext (match-string 1 dfile))))
7480 (cond
7481 ((equal in-emacs '(16))
7482 (setq cmd (cdr (assoc 'system apps))))
7483 (in-emacs (setq cmd 'emacs))
7485 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
7486 (and dirp (cdr (assoc 'directory apps)))
7487 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
7488 'string-match)
7489 (cdr (assoc ext apps))
7490 (cdr (assoc t apps))))))
7491 (when (eq cmd 'system)
7492 (setq cmd (cdr (assoc 'system apps))))
7493 (when (eq cmd 'default)
7494 (setq cmd (cdr (assoc t apps))))
7495 (when (eq cmd 'mailcap)
7496 (require 'mailcap)
7497 (mailcap-parse-mailcaps)
7498 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7499 (command (mailcap-mime-info mime-type)))
7500 (if (stringp command)
7501 (setq cmd command)
7502 (setq cmd 'emacs))))
7503 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
7504 (not (file-exists-p file))
7505 (not org-open-non-existing-files))
7506 (error "No such file: %s" file))
7507 (cond
7508 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7509 ;; Remove quotes around the file name - we'll use shell-quote-argument.
7510 (while (string-match "['\"]%s['\"]" cmd)
7511 (setq cmd (replace-match "%s" t t cmd)))
7512 (while (string-match "%s" cmd)
7513 (setq cmd (replace-match
7514 (save-match-data
7515 (shell-quote-argument
7516 (convert-standard-filename file)))
7517 t t cmd)))
7518 (save-window-excursion
7519 (start-process-shell-command cmd nil cmd)
7520 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
7522 ((or (stringp cmd)
7523 (eq cmd 'emacs))
7524 (funcall (cdr (assq 'file org-link-frame-setup)) file)
7525 (widen)
7526 (if line (goto-line line)
7527 (if search (org-link-search search))))
7528 ((consp cmd)
7529 (let ((file (convert-standard-filename file)))
7530 (eval cmd)))
7531 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7532 (and (org-mode-p) (eq old-mode 'org-mode)
7533 (or (not (equal old-buffer (current-buffer)))
7534 (not (equal old-pos (point))))
7535 (org-mark-ring-push old-pos old-buffer))))
7537 (defun org-default-apps ()
7538 "Return the default applications for this operating system."
7539 (cond
7540 ((eq system-type 'darwin)
7541 org-file-apps-defaults-macosx)
7542 ((eq system-type 'windows-nt)
7543 org-file-apps-defaults-windowsnt)
7544 (t org-file-apps-defaults-gnu)))
7546 (defun org-apps-regexp-alist (list &optional add-auto-mode)
7547 "Convert extensions to regular expressions in the cars of LIST.
7548 Also, weed out any non-string entries, because the return value is used
7549 only for regexp matching.
7550 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
7551 point to the symbol `emacs', indicating that the file should
7552 be opened in Emacs."
7553 (append
7554 (delq nil
7555 (mapcar (lambda (x)
7556 (if (not (stringp (car x)))
7558 (if (string-match "\\W" (car x))
7560 (cons (concat "\\." (car x) "\\'") (cdr x)))))
7561 list))
7562 (if add-auto-mode
7563 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
7565 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
7566 (defun org-file-remote-p (file)
7567 "Test whether FILE specifies a location on a remote system.
7568 Return non-nil if the location is indeed remote.
7570 For example, the filename \"/user@host:/foo\" specifies a location
7571 on the system \"/user@host:\"."
7572 (cond ((fboundp 'file-remote-p)
7573 (file-remote-p file))
7574 ((fboundp 'tramp-handle-file-remote-p)
7575 (tramp-handle-file-remote-p file))
7576 ((and (boundp 'ange-ftp-name-format)
7577 (string-match (car ange-ftp-name-format) file))
7579 (t nil)))
7582 ;;;; Refiling
7584 (defun org-get-org-file ()
7585 "Read a filename, with default directory `org-directory'."
7586 (let ((default (or org-default-notes-file remember-data-file)))
7587 (read-file-name (format "File name [%s]: " default)
7588 (file-name-as-directory org-directory)
7589 default)))
7591 (defun org-notes-order-reversed-p ()
7592 "Check if the current file should receive notes in reversed order."
7593 (cond
7594 ((not org-reverse-note-order) nil)
7595 ((eq t org-reverse-note-order) t)
7596 ((not (listp org-reverse-note-order)) nil)
7597 (t (catch 'exit
7598 (let ((all org-reverse-note-order)
7599 entry)
7600 (while (setq entry (pop all))
7601 (if (string-match (car entry) buffer-file-name)
7602 (throw 'exit (cdr entry))))
7603 nil)))))
7605 (defvar org-refile-target-table nil
7606 "The list of refile targets, created by `org-refile'.")
7608 (defvar org-agenda-new-buffers nil
7609 "Buffers created to visit agenda files.")
7611 (defun org-get-refile-targets (&optional default-buffer)
7612 "Produce a table with refile targets."
7613 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
7614 targets txt re files f desc descre fast-path-p level)
7615 (message "Getting targets...")
7616 (with-current-buffer (or default-buffer (current-buffer))
7617 (while (setq entry (pop entries))
7618 (setq files (car entry) desc (cdr entry))
7619 (setq fast-path-p nil)
7620 (cond
7621 ((null files) (setq files (list (current-buffer))))
7622 ((eq files 'org-agenda-files)
7623 (setq files (org-agenda-files 'unrestricted)))
7624 ((and (symbolp files) (fboundp files))
7625 (setq files (funcall files)))
7626 ((and (symbolp files) (boundp files))
7627 (setq files (symbol-value files))))
7628 (if (stringp files) (setq files (list files)))
7629 (cond
7630 ((eq (car desc) :tag)
7631 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
7632 ((eq (car desc) :todo)
7633 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
7634 ((eq (car desc) :regexp)
7635 (setq descre (cdr desc)))
7636 ((eq (car desc) :level)
7637 (setq descre (concat "^\\*\\{" (number-to-string
7638 (if org-odd-levels-only
7639 (1- (* 2 (cdr desc)))
7640 (cdr desc)))
7641 "\\}[ \t]")))
7642 ((eq (car desc) :maxlevel)
7643 (setq fast-path-p t)
7644 (setq descre (concat "^\\*\\{1," (number-to-string
7645 (if org-odd-levels-only
7646 (1- (* 2 (cdr desc)))
7647 (cdr desc)))
7648 "\\}[ \t]")))
7649 (t (error "Bad refiling target description %s" desc)))
7650 (while (setq f (pop files))
7651 (save-excursion
7652 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
7653 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
7654 (setq f (expand-file-name f))
7655 (save-excursion
7656 (save-restriction
7657 (widen)
7658 (goto-char (point-min))
7659 (while (re-search-forward descre nil t)
7660 (goto-char (point-at-bol))
7661 (when (looking-at org-complex-heading-regexp)
7662 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
7663 txt (org-link-display-format (match-string 4))
7664 re (concat "^" (regexp-quote
7665 (buffer-substring (match-beginning 1)
7666 (match-end 4)))))
7667 (if (match-end 5) (setq re (concat re "[ \t]+"
7668 (regexp-quote
7669 (match-string 5)))))
7670 (setq re (concat re "[ \t]*$"))
7671 (when org-refile-use-outline-path
7672 (setq txt (mapconcat 'org-protect-slash
7673 (append
7674 (if (eq org-refile-use-outline-path 'file)
7675 (list (file-name-nondirectory
7676 (buffer-file-name (buffer-base-buffer))))
7677 (if (eq org-refile-use-outline-path 'full-file-path)
7678 (list (buffer-file-name (buffer-base-buffer)))))
7679 (org-get-outline-path fast-path-p level txt)
7680 (list txt))
7681 "/")))
7682 (push (list txt f re (point)) targets))
7683 (goto-char (point-at-eol))))))))
7684 (message "Getting targets...done")
7685 (nreverse targets))))
7687 (defun org-protect-slash (s)
7688 (while (string-match "/" s)
7689 (setq s (replace-match "\\" t t s)))
7692 (defvar org-olpa (make-vector 20 nil))
7694 (defun org-get-outline-path (&optional fastp level heading)
7695 "Return the outline path to the current entry, as a list."
7696 (if fastp
7697 (progn
7698 (if (> level 19)
7699 (error "Outline path failure, more than 19 levels."))
7700 (loop for i from level upto 19 do
7701 (aset org-olpa i nil))
7702 (prog1
7703 (delq nil (append org-olpa nil))
7704 (aset org-olpa level heading)))
7705 (let (rtn)
7706 (save-excursion
7707 (while (org-up-heading-safe)
7708 (when (looking-at org-complex-heading-regexp)
7709 (push (org-match-string-no-properties 4) rtn)))
7710 rtn))))
7712 (defvar org-refile-history nil
7713 "History for refiling operations.")
7715 (defun org-refile (&optional goto default-buffer)
7716 "Move the entry at point to another heading.
7717 The list of target headings is compiled using the information in
7718 `org-refile-targets', which see. This list is created before each use
7719 and will therefore always be up-to-date.
7721 At the target location, the entry is filed as a subitem of the target heading.
7722 Depending on `org-reverse-note-order', the new subitem will either be the
7723 first or the last subitem.
7725 If there is an active region, all entries in that region will be moved.
7726 However, the region must fulfil the requirement that the first heading
7727 is the first one sets the top-level of the moved text - at most siblings
7728 below it are allowed.
7730 With prefix arg GOTO, the command will only visit the target location,
7731 not actually move anything.
7732 With a double prefix `C-u C-u', go to the location where the last refiling
7733 operation has put the subtree."
7734 (interactive "P")
7735 (let* ((cbuf (current-buffer))
7736 (regionp (org-region-active-p))
7737 (region-start (and regionp (region-beginning)))
7738 (region-end (and regionp (region-end)))
7739 (region-length (and regionp (- region-end region-start)))
7740 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7741 pos it nbuf file re level reversed)
7742 (when regionp (goto-char region-start)
7743 (unless (org-kill-is-subtree-p
7744 (buffer-substring region-start region-end))
7745 (error "The region is not a (sequence of) subtree(s)")))
7746 (if (equal goto '(16))
7747 (org-refile-goto-last-stored)
7748 (when (setq it (org-refile-get-location
7749 (if goto "Goto: " "Refile to: ") default-buffer))
7750 (setq file (nth 1 it)
7751 re (nth 2 it)
7752 pos (nth 3 it))
7753 (if (and (equal (buffer-file-name) file)
7754 (if regionp
7755 (and (>= pos region-start)
7756 (<= pos region-end))
7757 (and (>= pos (point))
7758 (< pos (save-excursion
7759 (org-end-of-subtree t t))))))
7760 (error "Cannot refile to position inside the tree or region"))
7762 (setq nbuf (or (find-buffer-visiting file)
7763 (find-file-noselect file)))
7764 (if goto
7765 (progn
7766 (switch-to-buffer nbuf)
7767 (goto-char pos)
7768 (org-show-context 'org-goto))
7769 (if regionp
7770 (progn
7771 (kill-new (buffer-substring region-start region-end))
7772 (org-save-markers-in-region region-start region-end))
7773 (org-copy-subtree 1 nil t))
7774 (save-excursion
7775 (set-buffer (setq nbuf (or (find-buffer-visiting file)
7776 (find-file-noselect file))))
7777 (setq reversed (org-notes-order-reversed-p))
7778 (save-excursion
7779 (save-restriction
7780 (widen)
7781 (goto-char pos)
7782 (looking-at outline-regexp)
7783 (setq level (org-get-valid-level (funcall outline-level) 1))
7784 (goto-char
7785 (if reversed
7786 (or (outline-next-heading) (point-max))
7787 (or (save-excursion (outline-get-next-sibling))
7788 (org-end-of-subtree t t)
7789 (point-max))))
7790 (if (not (bolp)) (newline))
7791 (bookmark-set "org-refile-last-stored")
7792 (org-paste-subtree level))))
7793 (if regionp
7794 (delete-region (point) (+ (point) region-length))
7795 (org-cut-subtree))
7796 (setq org-markers-to-move nil)
7797 (message "Refiled to \"%s\"" (car it)))))))
7799 (defun org-refile-goto-last-stored ()
7800 "Go to the location where the last refile was stored."
7801 (interactive)
7802 (bookmark-jump "org-refile-last-stored")
7803 (message "This is the location of the last refile"))
7805 (defun org-refile-get-location (&optional prompt default-buffer)
7806 "Prompt the user for a refile location, using PROMPT."
7807 (let ((org-refile-targets org-refile-targets)
7808 (org-refile-use-outline-path org-refile-use-outline-path))
7809 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
7810 (unless org-refile-target-table
7811 (error "No refile targets"))
7812 (let* ((cbuf (current-buffer))
7813 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
7814 (cfunc (if (and org-refile-use-outline-path
7815 org-outline-path-complete-in-steps)
7816 'org-olpath-completing-read
7817 'org-ido-completing-read))
7818 (extra (if org-refile-use-outline-path "/" ""))
7819 (filename (and cfn (expand-file-name cfn)))
7820 (tbl (mapcar
7821 (lambda (x)
7822 (if (not (equal filename (nth 1 x)))
7823 (cons (concat (car x) extra " ("
7824 (file-name-nondirectory (nth 1 x)) ")")
7825 (cdr x))
7826 (cons (concat (car x) extra) (cdr x))))
7827 org-refile-target-table))
7828 (completion-ignore-case t))
7829 (assoc (funcall cfunc prompt tbl nil t nil 'org-refile-history)
7830 tbl)))
7832 (defun org-olpath-completing-read (prompt collection &rest args)
7833 "Read an outline path like a file name."
7834 (let ((thetable collection))
7835 (apply
7836 'org-ido-completing-read prompt
7837 (lambda (string predicate &optional flag)
7838 (let (rtn r s f (l (length string)))
7839 (cond
7840 ((eq flag nil)
7841 ;; try completion
7842 (try-completion string thetable))
7843 ((eq flag t)
7844 ;; all-completions
7845 (setq rtn (all-completions string thetable predicate))
7846 (mapcar
7847 (lambda (x)
7848 (setq r (substring x l))
7849 (if (string-match " ([^)]*)$" x)
7850 (setq f (match-string 0 x))
7851 (setq f ""))
7852 (if (string-match "/" r)
7853 (concat string (substring r 0 (match-end 0)) f)
7855 rtn))
7856 ((eq flag 'lambda)
7857 ;; exact match?
7858 (assoc string thetable)))
7860 args)))
7862 ;;;; Dynamic blocks
7864 (defun org-find-dblock (name)
7865 "Find the first dynamic block with name NAME in the buffer.
7866 If not found, stay at current position and return nil."
7867 (let (pos)
7868 (save-excursion
7869 (goto-char (point-min))
7870 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
7871 nil t)
7872 (match-beginning 0))))
7873 (if pos (goto-char pos))
7874 pos))
7876 (defconst org-dblock-start-re
7877 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
7878 "Matches the startline of a dynamic block, with parameters.")
7880 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
7881 "Matches the end of a dynamic block.")
7883 (defun org-create-dblock (plist)
7884 "Create a dynamic block section, with parameters taken from PLIST.
7885 PLIST must contain a :name entry which is used as name of the block."
7886 (unless (bolp) (newline))
7887 (let ((name (plist-get plist :name)))
7888 (insert "#+BEGIN: " name)
7889 (while plist
7890 (if (eq (car plist) :name)
7891 (setq plist (cddr plist))
7892 (insert " " (prin1-to-string (pop plist)))))
7893 (insert "\n\n#+END:\n")
7894 (beginning-of-line -2)))
7896 (defun org-prepare-dblock ()
7897 "Prepare dynamic block for refresh.
7898 This empties the block, puts the cursor at the insert position and returns
7899 the property list including an extra property :name with the block name."
7900 (unless (looking-at org-dblock-start-re)
7901 (error "Not at a dynamic block"))
7902 (let* ((begdel (1+ (match-end 0)))
7903 (name (org-no-properties (match-string 1)))
7904 (params (append (list :name name)
7905 (read (concat "(" (match-string 3) ")")))))
7906 (unless (re-search-forward org-dblock-end-re nil t)
7907 (error "Dynamic block not terminated"))
7908 (setq params
7909 (append params
7910 (list :content (buffer-substring
7911 begdel (match-beginning 0)))))
7912 (delete-region begdel (match-beginning 0))
7913 (goto-char begdel)
7914 (open-line 1)
7915 params))
7917 (defun org-map-dblocks (&optional command)
7918 "Apply COMMAND to all dynamic blocks in the current buffer.
7919 If COMMAND is not given, use `org-update-dblock'."
7920 (let ((cmd (or command 'org-update-dblock))
7921 pos)
7922 (save-excursion
7923 (goto-char (point-min))
7924 (while (re-search-forward org-dblock-start-re nil t)
7925 (goto-char (setq pos (match-beginning 0)))
7926 (condition-case nil
7927 (funcall cmd)
7928 (error (message "Error during update of dynamic block")))
7929 (goto-char pos)
7930 (unless (re-search-forward org-dblock-end-re nil t)
7931 (error "Dynamic block not terminated"))))))
7933 (defun org-dblock-update (&optional arg)
7934 "User command for updating dynamic blocks.
7935 Update the dynamic block at point. With prefix ARG, update all dynamic
7936 blocks in the buffer."
7937 (interactive "P")
7938 (if arg
7939 (org-update-all-dblocks)
7940 (or (looking-at org-dblock-start-re)
7941 (org-beginning-of-dblock))
7942 (org-update-dblock)))
7944 (defun org-update-dblock ()
7945 "Update the dynamic block at point
7946 This means to empty the block, parse for parameters and then call
7947 the correct writing function."
7948 (save-window-excursion
7949 (let* ((pos (point))
7950 (line (org-current-line))
7951 (params (org-prepare-dblock))
7952 (name (plist-get params :name))
7953 (cmd (intern (concat "org-dblock-write:" name))))
7954 (message "Updating dynamic block `%s' at line %d..." name line)
7955 (funcall cmd params)
7956 (message "Updating dynamic block `%s' at line %d...done" name line)
7957 (goto-char pos))))
7959 (defun org-beginning-of-dblock ()
7960 "Find the beginning of the dynamic block at point.
7961 Error if there is no such block at point."
7962 (let ((pos (point))
7963 beg)
7964 (end-of-line 1)
7965 (if (and (re-search-backward org-dblock-start-re nil t)
7966 (setq beg (match-beginning 0))
7967 (re-search-forward org-dblock-end-re nil t)
7968 (> (match-end 0) pos))
7969 (goto-char beg)
7970 (goto-char pos)
7971 (error "Not in a dynamic block"))))
7973 (defun org-update-all-dblocks ()
7974 "Update all dynamic blocks in the buffer.
7975 This function can be used in a hook."
7976 (when (org-mode-p)
7977 (org-map-dblocks 'org-update-dblock)))
7980 ;;;; Completion
7982 (defconst org-additional-option-like-keywords
7983 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
7984 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
7985 "BEGIN_EXAMPLE" "END_EXAMPLE"
7986 "BEGIN_QUOTE" "END_QUOTE"
7987 "BEGIN_VERSE" "END_VERSE"
7988 "BEGIN_SRC" "END_SRC"
7989 "CAPTION" "LABEL" "ATTR_HTML" "ATTR_LaTeX"))
7991 (defcustom org-structure-template-alist
7993 ("s" "#+begin_src ?\n\n#+end_src"
7994 "<src lang=\"?\">\n\n</src>")
7995 ("e" "#+begin_example\n?\n#+end_example"
7996 "<example>\n?\n</example>")
7997 ("q" "#+begin_quote\n?\n#+end_quote"
7998 "<quote>\n?\n</quote>")
7999 ("v" "#+begin_verse\n?\n#+end_verse"
8000 "<verse>\n?\n/verse>")
8001 ("l" "#+begin_latex\n?\n#+end_latex"
8002 "<literal style=\"latex\">\n?\n</literal>")
8003 ("L" "#+latex: "
8004 "<literal style=\"latex\">?</literal>")
8005 ("h" "#+begin_html\n?\n#+end_html"
8006 "<literal style=\"html\">\n?\n</literal>")
8007 ("H" "#+html: "
8008 "<literal style=\"html\">?</literal>")
8009 ("a" "#+begin_ascii\n?\n#+end_ascii")
8010 ("A" "#+ascii: ")
8011 ("i" "#+include %file ?"
8012 "<include file=%file markup=\"?\">")
8014 "Structure completion elements.
8015 This is a list of abbreviation keys and values. The value gets inserted
8016 it you type @samp{.} followed by the key and then the completion key,
8017 usually `M-TAB'. %file will be replaced by a file name after prompting
8018 for the file using completion.
8019 There are two templates for each key, the first uses the original Org syntax,
8020 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
8021 the default when the /org-mtags.el/ module has been loaded. See also the
8022 variable `org-mtags-prefer-muse-templates'.
8023 This is an experimental feature, it is undecided if it is going to stay in."
8024 :group 'org-completion
8025 :type '(repeat
8026 (string :tag "Key")
8027 (string :tag "Template")
8028 (string :tag "Muse Template")))
8030 (defun org-try-structure-completion ()
8031 "Try to complete a structure template before point.
8032 This looks for strings like \"<e\" on an otherwise empty line and
8033 expands them."
8034 (let ((l (buffer-substring (point-at-bol) (point)))
8036 (when (and (looking-at "[ \t]*$")
8037 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
8038 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
8039 (org-complete-expand-structure-template (+ -1 (point-at-bol)
8040 (match-beginning 1)) a)
8041 t)))
8043 (defun org-complete-expand-structure-template (start cell)
8044 "Expand a structure template."
8045 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
8046 (rpl (nth (if musep 2 1) cell)))
8047 (delete-region start (point))
8048 (when (string-match "\\`#\\+" rpl)
8049 (cond
8050 ((bolp))
8051 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
8052 (delete-region (point-at-bol) (point)))
8053 (t (newline))))
8054 (setq start (point))
8055 (if (string-match "%file" rpl)
8056 (setq rpl (replace-match
8057 (concat
8058 "\""
8059 (save-match-data
8060 (abbreviate-file-name (read-file-name "Include file: ")))
8061 "\"")
8062 t t rpl)))
8063 (insert rpl)
8064 (if (re-search-backward "\\?" start t) (delete-char 1))))
8067 (defun org-complete (&optional arg)
8068 "Perform completion on word at point.
8069 At the beginning of a headline, this completes TODO keywords as given in
8070 `org-todo-keywords'.
8071 If the current word is preceded by a backslash, completes the TeX symbols
8072 that are supported for HTML support.
8073 If the current word is preceded by \"#+\", completes special words for
8074 setting file options.
8075 In the line after \"#+STARTUP:, complete valid keywords.\"
8076 At all other locations, this simply calls the value of
8077 `org-completion-fallback-command'."
8078 (interactive "P")
8079 (org-without-partial-completion
8080 (catch 'exit
8081 (let* ((a nil)
8082 (end (point))
8083 (beg1 (save-excursion
8084 (skip-chars-backward (org-re "[:alnum:]_@"))
8085 (point)))
8086 (beg (save-excursion
8087 (skip-chars-backward "a-zA-Z0-9_:$")
8088 (point)))
8089 (confirm (lambda (x) (stringp (car x))))
8090 (searchhead (equal (char-before beg) ?*))
8091 (struct
8092 (when (and (member (char-before beg1) '(?. ?<))
8093 (setq a (assoc (buffer-substring beg1 (point))
8094 org-structure-template-alist)))
8095 (org-complete-expand-structure-template (1- beg1) a)
8096 (throw 'exit t)))
8097 (tag (and (equal (char-before beg1) ?:)
8098 (equal (char-after (point-at-bol)) ?*)))
8099 (prop (and (equal (char-before beg1) ?:)
8100 (not (equal (char-after (point-at-bol)) ?*))))
8101 (texp (equal (char-before beg) ?\\))
8102 (link (equal (char-before beg) ?\[))
8103 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
8104 beg)
8105 "#+"))
8106 (startup (string-match "^#\\+STARTUP:.*"
8107 (buffer-substring (point-at-bol) (point))))
8108 (completion-ignore-case opt)
8109 (type nil)
8110 (tbl nil)
8111 (table (cond
8112 (opt
8113 (setq type :opt)
8114 (require 'org-exp)
8115 (append
8116 (mapcar
8117 (lambda (x)
8118 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
8119 (cons (match-string 2 x) (match-string 1 x)))
8120 (org-split-string (org-get-current-options) "\n"))
8121 (mapcar 'list org-additional-option-like-keywords)))
8122 (startup
8123 (setq type :startup)
8124 org-startup-options)
8125 (link (append org-link-abbrev-alist-local
8126 org-link-abbrev-alist))
8127 (texp
8128 (setq type :tex)
8129 org-html-entities)
8130 ((string-match "\\`\\*+[ \t]+\\'"
8131 (buffer-substring (point-at-bol) beg))
8132 (setq type :todo)
8133 (mapcar 'list org-todo-keywords-1))
8134 (searchhead
8135 (setq type :searchhead)
8136 (save-excursion
8137 (goto-char (point-min))
8138 (while (re-search-forward org-todo-line-regexp nil t)
8139 (push (list
8140 (org-make-org-heading-search-string
8141 (match-string 3) t))
8142 tbl)))
8143 tbl)
8144 (tag (setq type :tag beg beg1)
8145 (or org-tag-alist (org-get-buffer-tags)))
8146 (prop (setq type :prop beg beg1)
8147 (mapcar 'list (org-buffer-property-keys nil t t)))
8148 (t (progn
8149 (call-interactively org-completion-fallback-command)
8150 (throw 'exit nil)))))
8151 (pattern (buffer-substring-no-properties beg end))
8152 (completion (try-completion pattern table confirm)))
8153 (cond ((eq completion t)
8154 (if (not (assoc (upcase pattern) table))
8155 (message "Already complete")
8156 (if (and (equal type :opt)
8157 (not (member (car (assoc (upcase pattern) table))
8158 org-additional-option-like-keywords)))
8159 (insert (substring (cdr (assoc (upcase pattern) table))
8160 (length pattern)))
8161 (if (memq type '(:tag :prop)) (insert ":")))))
8162 ((null completion)
8163 (message "Can't find completion for \"%s\"" pattern)
8164 (ding))
8165 ((not (string= pattern completion))
8166 (delete-region beg end)
8167 (if (string-match " +$" completion)
8168 (setq completion (replace-match "" t t completion)))
8169 (insert completion)
8170 (if (get-buffer-window "*Completions*")
8171 (delete-window (get-buffer-window "*Completions*")))
8172 (if (assoc completion table)
8173 (if (eq type :todo) (insert " ")
8174 (if (memq type '(:tag :prop)) (insert ":"))))
8175 (if (and (equal type :opt) (assoc completion table))
8176 (message "%s" (substitute-command-keys
8177 "Press \\[org-complete] again to insert example settings"))))
8179 (message "Making completion list...")
8180 (let ((list (sort (all-completions pattern table confirm)
8181 'string<)))
8182 (with-output-to-temp-buffer "*Completions*"
8183 (condition-case nil
8184 ;; Protection needed for XEmacs and emacs 21
8185 (display-completion-list list pattern)
8186 (error (display-completion-list list)))))
8187 (message "Making completion list...%s" "done")))))))
8189 ;;;; TODO, DEADLINE, Comments
8191 (defun org-toggle-comment ()
8192 "Change the COMMENT state of an entry."
8193 (interactive)
8194 (save-excursion
8195 (org-back-to-heading)
8196 (let (case-fold-search)
8197 (if (looking-at (concat outline-regexp
8198 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
8199 (replace-match "" t t nil 1)
8200 (if (looking-at outline-regexp)
8201 (progn
8202 (goto-char (match-end 0))
8203 (insert org-comment-string " ")))))))
8205 (defvar org-last-todo-state-is-todo nil
8206 "This is non-nil when the last TODO state change led to a TODO state.
8207 If the last change removed the TODO tag or switched to DONE, then
8208 this is nil.")
8210 (defvar org-setting-tags nil) ; dynamically skipped
8212 (defun org-parse-local-options (string var)
8213 "Parse STRING for startup setting relevant for variable VAR."
8214 (let ((rtn (symbol-value var))
8215 e opts)
8216 (save-match-data
8217 (if (or (not string) (not (string-match "\\S-" string)))
8219 (setq opts (delq nil (mapcar (lambda (x)
8220 (setq e (assoc x org-startup-options))
8221 (if (eq (nth 1 e) var) e nil))
8222 (org-split-string string "[ \t]+"))))
8223 (if (not opts)
8225 (setq rtn nil)
8226 (while (setq e (pop opts))
8227 (if (not (nth 3 e))
8228 (setq rtn (nth 2 e))
8229 (if (not (listp rtn)) (setq rtn nil))
8230 (push (nth 2 e) rtn)))
8231 rtn)))))
8233 (defvar org-blocker-hook nil
8234 "Hook for functions that are allowed to block a state change.
8236 Each function gets as its single argument a property list, see
8237 `org-trigger-hook' for more information about this list.
8239 If any of the functions in this hook returns nil, the state change
8240 is blocked.")
8242 (defvar org-trigger-hook nil
8243 "Hook for functions that are triggered by a state change.
8245 Each function gets as its single argument a property list with at least
8246 the following elements:
8248 (:type type-of-change :position pos-at-entry-start
8249 :from old-state :to new-state)
8251 Depending on the type, more properties may be present.
8253 This mechanism is currently implemented for:
8255 TODO state changes
8256 ------------------
8257 :type todo-state-change
8258 :from previous state (keyword as a string), or nil
8259 :to new state (keyword as a string), or nil")
8261 (defvar org-agenda-headline-snapshot-before-repeat)
8262 (defun org-todo (&optional arg)
8263 "Change the TODO state of an item.
8264 The state of an item is given by a keyword at the start of the heading,
8265 like
8266 *** TODO Write paper
8267 *** DONE Call mom
8269 The different keywords are specified in the variable `org-todo-keywords'.
8270 By default the available states are \"TODO\" and \"DONE\".
8271 So for this example: when the item starts with TODO, it is changed to DONE.
8272 When it starts with DONE, the DONE is removed. And when neither TODO nor
8273 DONE are present, add TODO at the beginning of the heading.
8275 With C-u prefix arg, use completion to determine the new state.
8276 With numeric prefix arg, switch to that state.
8278 For calling through lisp, arg is also interpreted in the following way:
8279 'none -> empty state
8280 \"\"(empty string) -> switch to empty state
8281 'done -> switch to DONE
8282 'nextset -> switch to the next set of keywords
8283 'previousset -> switch to the previous set of keywords
8284 \"WAITING\" -> switch to the specified keyword, but only if it
8285 really is a member of `org-todo-keywords'."
8286 (interactive "P")
8287 (save-excursion
8288 (catch 'exit
8289 (org-back-to-heading)
8290 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
8291 (or (looking-at (concat " +" org-todo-regexp " *"))
8292 (looking-at " *"))
8293 (let* ((match-data (match-data))
8294 (startpos (point-at-bol))
8295 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
8296 (org-log-done org-log-done)
8297 (org-log-repeat org-log-repeat)
8298 (org-todo-log-states org-todo-log-states)
8299 (this (match-string 1))
8300 (hl-pos (match-beginning 0))
8301 (head (org-get-todo-sequence-head this))
8302 (ass (assoc head org-todo-kwd-alist))
8303 (interpret (nth 1 ass))
8304 (done-word (nth 3 ass))
8305 (final-done-word (nth 4 ass))
8306 (last-state (or this ""))
8307 (completion-ignore-case t)
8308 (member (member this org-todo-keywords-1))
8309 (tail (cdr member))
8310 (state (cond
8311 ((and org-todo-key-trigger
8312 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
8313 (and (not arg) org-use-fast-todo-selection
8314 (not (eq org-use-fast-todo-selection 'prefix)))))
8315 ;; Use fast selection
8316 (org-fast-todo-selection))
8317 ((and (equal arg '(4))
8318 (or (not org-use-fast-todo-selection)
8319 (not org-todo-key-trigger)))
8320 ;; Read a state with completion
8321 (org-ido-completing-read "State: " (mapcar (lambda(x) (list x))
8322 org-todo-keywords-1)
8323 nil t))
8324 ((eq arg 'right)
8325 (if this
8326 (if tail (car tail) nil)
8327 (car org-todo-keywords-1)))
8328 ((eq arg 'left)
8329 (if (equal member org-todo-keywords-1)
8331 (if this
8332 (nth (- (length org-todo-keywords-1) (length tail) 2)
8333 org-todo-keywords-1)
8334 (org-last org-todo-keywords-1))))
8335 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
8336 (setq arg nil))) ; hack to fall back to cycling
8337 (arg
8338 ;; user or caller requests a specific state
8339 (cond
8340 ((equal arg "") nil)
8341 ((eq arg 'none) nil)
8342 ((eq arg 'done) (or done-word (car org-done-keywords)))
8343 ((eq arg 'nextset)
8344 (or (car (cdr (member head org-todo-heads)))
8345 (car org-todo-heads)))
8346 ((eq arg 'previousset)
8347 (let ((org-todo-heads (reverse org-todo-heads)))
8348 (or (car (cdr (member head org-todo-heads)))
8349 (car org-todo-heads))))
8350 ((car (member arg org-todo-keywords-1)))
8351 ((nth (1- (prefix-numeric-value arg))
8352 org-todo-keywords-1))))
8353 ((null member) (or head (car org-todo-keywords-1)))
8354 ((equal this final-done-word) nil) ;; -> make empty
8355 ((null tail) nil) ;; -> first entry
8356 ((eq interpret 'sequence)
8357 (car tail))
8358 ((memq interpret '(type priority))
8359 (if (eq this-command last-command)
8360 (car tail)
8361 (if (> (length tail) 0)
8362 (or done-word (car org-done-keywords))
8363 nil)))
8364 (t nil)))
8365 (next (if state (concat " " state " ") " "))
8366 (change-plist (list :type 'todo-state-change :from this :to state
8367 :position startpos))
8368 dolog now-done-p)
8369 (when org-blocker-hook
8370 (unless (save-excursion
8371 (save-match-data
8372 (run-hook-with-args-until-failure
8373 'org-blocker-hook change-plist)))
8374 (if (interactive-p)
8375 (error "TODO state change from %s to %s blocked" this state)
8376 ;; fail silently
8377 (message "TODO state change from %s to %s blocked" this state)
8378 (throw 'exit nil))))
8379 (store-match-data match-data)
8380 (replace-match next t t)
8381 (unless (pos-visible-in-window-p hl-pos)
8382 (message "TODO state changed to %s" (org-trim next)))
8383 (unless head
8384 (setq head (org-get-todo-sequence-head state)
8385 ass (assoc head org-todo-kwd-alist)
8386 interpret (nth 1 ass)
8387 done-word (nth 3 ass)
8388 final-done-word (nth 4 ass)))
8389 (when (memq arg '(nextset previousset))
8390 (message "Keyword-Set %d/%d: %s"
8391 (- (length org-todo-sets) -1
8392 (length (memq (assoc state org-todo-sets) org-todo-sets)))
8393 (length org-todo-sets)
8394 (mapconcat 'identity (assoc state org-todo-sets) " ")))
8395 (setq org-last-todo-state-is-todo
8396 (not (member state org-done-keywords)))
8397 (setq now-done-p (and (member state org-done-keywords)
8398 (not (member this org-done-keywords))))
8399 (and logging (org-local-logging logging))
8400 (when (and (or org-todo-log-states org-log-done)
8401 (not (memq arg '(nextset previousset))))
8402 ;; we need to look at recording a time and note
8403 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
8404 (nth 2 (assoc this org-todo-log-states))))
8405 (when (and state
8406 (member state org-not-done-keywords)
8407 (not (member this org-not-done-keywords)))
8408 ;; This is now a todo state and was not one before
8409 ;; If there was a CLOSED time stamp, get rid of it.
8410 (org-add-planning-info nil nil 'closed))
8411 (when (and now-done-p org-log-done)
8412 ;; It is now done, and it was not done before
8413 (org-add-planning-info 'closed (org-current-time))
8414 (if (and (not dolog) (eq 'note org-log-done))
8415 (org-add-log-setup 'done state 'findpos 'note)))
8416 (when (and state dolog)
8417 ;; This is a non-nil state, and we need to log it
8418 (org-add-log-setup 'state state 'findpos dolog)))
8419 ;; Fixup tag positioning
8420 (org-todo-trigger-tag-changes state)
8421 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
8422 (when org-provide-todo-statistics
8423 (org-update-parent-todo-statistics))
8424 (run-hooks 'org-after-todo-state-change-hook)
8425 (if (and arg (not (member state org-done-keywords)))
8426 (setq head (org-get-todo-sequence-head state)))
8427 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
8428 ;; Do we need to trigger a repeat?
8429 (when now-done-p
8430 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
8431 ;; This is for the agenda, take a snapshot of the headline.
8432 (save-match-data
8433 (setq org-agenda-headline-snapshot-before-repeat
8434 (org-get-heading))))
8435 (org-auto-repeat-maybe state))
8436 ;; Fixup cursor location if close to the keyword
8437 (if (and (outline-on-heading-p)
8438 (not (bolp))
8439 (save-excursion (beginning-of-line 1)
8440 (looking-at org-todo-line-regexp))
8441 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
8442 (progn
8443 (goto-char (or (match-end 2) (match-end 1)))
8444 (just-one-space)))
8445 (when org-trigger-hook
8446 (save-excursion
8447 (run-hook-with-args 'org-trigger-hook change-plist)))))))
8449 (defun org-update-parent-todo-statistics ()
8450 "Update any statistics cookie in the parent of the current headline."
8451 (interactive)
8452 (let ((box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
8453 level (cnt-all 0) (cnt-done 0) is-percent kwd)
8454 (catch 'exit
8455 (save-excursion
8456 (setq level (org-up-heading-safe))
8457 (unless (and level
8458 (re-search-forward box-re (point-at-eol) t))
8459 (throw 'exit nil))
8460 (setq is-percent (match-end 2))
8461 (save-match-data
8462 (unless (outline-next-heading) (throw 'exit nil))
8463 (while (looking-at org-todo-line-regexp)
8464 (setq kwd (match-string 2))
8465 (and kwd (setq cnt-all (1+ cnt-all)))
8466 (and (member kwd org-done-keywords)
8467 (setq cnt-done (1+ cnt-done)))
8468 (condition-case nil
8469 (org-forward-same-level 1)
8470 (error (end-of-line 1)))))
8471 (replace-match
8472 (if is-percent
8473 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
8474 (format "[%d/%d]" cnt-done cnt-all)))
8475 (run-hook-with-args 'org-after-todo-statistics-hook
8476 cnt-done (- cnt-all cnt-done))))))
8478 (defvar org-after-todo-statistics-hook nil
8479 "Hook that is called after a TODO statistics cookie has been updated.
8480 Each function is called with two arguments: the number of not-done entries
8481 and the number of done entries.
8483 For example, the following function, when added to this hook, will switch
8484 an entry to DONE when all children are done, and back to TODO when new
8485 entries are set to a TODO status. Note that this hook is only called
8486 when there is a statistics cookie in the headline!
8488 (defun org-summary-todo (n-done n-not-done)
8489 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
8490 (let (org-log-done org-log-states) ; turn off logging
8491 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
8494 (defun org-todo-trigger-tag-changes (state)
8495 "Apply the changes defined in `org-todo-state-tags-triggers'."
8496 (let ((l org-todo-state-tags-triggers)
8497 changes)
8498 (when (or (not state) (equal state ""))
8499 (setq changes (append changes (cdr (assoc "" l)))))
8500 (when (and (stringp state) (> (length state) 0))
8501 (setq changes (append changes (cdr (assoc state l)))))
8502 (when (member state org-not-done-keywords)
8503 (setq changes (append changes (cdr (assoc 'todo l)))))
8504 (when (member state org-done-keywords)
8505 (setq changes (append changes (cdr (assoc 'done l)))))
8506 (dolist (c changes)
8507 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
8509 (defun org-local-logging (value)
8510 "Get logging settings from a property VALUE."
8511 (let* (words w a)
8512 ;; directly set the variables, they are already local.
8513 (setq org-log-done nil
8514 org-log-repeat nil
8515 org-todo-log-states nil)
8516 (setq words (org-split-string value))
8517 (while (setq w (pop words))
8518 (cond
8519 ((setq a (assoc w org-startup-options))
8520 (and (member (nth 1 a) '(org-log-done org-log-repeat))
8521 (set (nth 1 a) (nth 2 a))))
8522 ((setq a (org-extract-log-state-settings w))
8523 (and (member (car a) org-todo-keywords-1)
8524 (push a org-todo-log-states)))))))
8526 (defun org-get-todo-sequence-head (kwd)
8527 "Return the head of the TODO sequence to which KWD belongs.
8528 If KWD is not set, check if there is a text property remembering the
8529 right sequence."
8530 (let (p)
8531 (cond
8532 ((not kwd)
8533 (or (get-text-property (point-at-bol) 'org-todo-head)
8534 (progn
8535 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
8536 nil (point-at-eol)))
8537 (get-text-property p 'org-todo-head))))
8538 ((not (member kwd org-todo-keywords-1))
8539 (car org-todo-keywords-1))
8540 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
8542 (defun org-fast-todo-selection ()
8543 "Fast TODO keyword selection with single keys.
8544 Returns the new TODO keyword, or nil if no state change should occur."
8545 (let* ((fulltable org-todo-key-alist)
8546 (done-keywords org-done-keywords) ;; needed for the faces.
8547 (maxlen (apply 'max (mapcar
8548 (lambda (x)
8549 (if (stringp (car x)) (string-width (car x)) 0))
8550 fulltable)))
8551 (expert nil)
8552 (fwidth (+ maxlen 3 1 3))
8553 (ncol (/ (- (window-width) 4) fwidth))
8554 tg cnt e c tbl
8555 groups ingroup)
8556 (save-window-excursion
8557 (if expert
8558 (set-buffer (get-buffer-create " *Org todo*"))
8559 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
8560 (erase-buffer)
8561 (org-set-local 'org-done-keywords done-keywords)
8562 (setq tbl fulltable cnt 0)
8563 (while (setq e (pop tbl))
8564 (cond
8565 ((equal e '(:startgroup))
8566 (push '() groups) (setq ingroup t)
8567 (when (not (= cnt 0))
8568 (setq cnt 0)
8569 (insert "\n"))
8570 (insert "{ "))
8571 ((equal e '(:endgroup))
8572 (setq ingroup nil cnt 0)
8573 (insert "}\n"))
8575 (setq tg (car e) c (cdr e))
8576 (if ingroup (push tg (car groups)))
8577 (setq tg (org-add-props tg nil 'face
8578 (org-get-todo-face tg)))
8579 (if (and (= cnt 0) (not ingroup)) (insert " "))
8580 (insert "[" c "] " tg (make-string
8581 (- fwidth 4 (length tg)) ?\ ))
8582 (when (= (setq cnt (1+ cnt)) ncol)
8583 (insert "\n")
8584 (if ingroup (insert " "))
8585 (setq cnt 0)))))
8586 (insert "\n")
8587 (goto-char (point-min))
8588 (if (not expert) (org-fit-window-to-buffer))
8589 (message "[a-z..]:Set [SPC]:clear")
8590 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
8591 (cond
8592 ((or (= c ?\C-g)
8593 (and (= c ?q) (not (rassoc c fulltable))))
8594 (setq quit-flag t))
8595 ((= c ?\ ) nil)
8596 ((setq e (rassoc c fulltable) tg (car e))
8598 (t (setq quit-flag t))))))
8600 (defun org-entry-is-todo-p ()
8601 (member (org-get-todo-state) org-not-done-keywords))
8603 (defun org-entry-is-done-p ()
8604 (member (org-get-todo-state) org-done-keywords))
8606 (defun org-get-todo-state ()
8607 (save-excursion
8608 (org-back-to-heading t)
8609 (and (looking-at org-todo-line-regexp)
8610 (match-end 2)
8611 (match-string 2))))
8613 (defun org-at-date-range-p (&optional inactive-ok)
8614 "Is the cursor inside a date range?"
8615 (interactive)
8616 (save-excursion
8617 (catch 'exit
8618 (let ((pos (point)))
8619 (skip-chars-backward "^[<\r\n")
8620 (skip-chars-backward "<[")
8621 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8622 (>= (match-end 0) pos)
8623 (throw 'exit t))
8624 (skip-chars-backward "^<[\r\n")
8625 (skip-chars-backward "<[")
8626 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8627 (>= (match-end 0) pos)
8628 (throw 'exit t)))
8629 nil)))
8631 (defun org-get-repeat ()
8632 "Check if there is a deadline/schedule with repeater in this entry."
8633 (save-match-data
8634 (save-excursion
8635 (org-back-to-heading t)
8636 (if (re-search-forward
8637 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
8638 (match-string 1)))))
8640 (defvar org-last-changed-timestamp)
8641 (defvar org-last-inserted-timestamp)
8642 (defvar org-log-post-message)
8643 (defvar org-log-note-purpose)
8644 (defvar org-log-note-how)
8645 (defvar org-log-note-extra)
8646 (defun org-auto-repeat-maybe (done-word)
8647 "Check if the current headline contains a repeated deadline/schedule.
8648 If yes, set TODO state back to what it was and change the base date
8649 of repeating deadline/scheduled time stamps to new date.
8650 This function is run automatically after each state change to a DONE state."
8651 ;; last-state is dynamically scoped into this function
8652 (let* ((repeat (org-get-repeat))
8653 (aa (assoc last-state org-todo-kwd-alist))
8654 (interpret (nth 1 aa))
8655 (head (nth 2 aa))
8656 (whata '(("d" . day) ("m" . month) ("y" . year)))
8657 (msg "Entry repeats: ")
8658 (org-log-done nil)
8659 (org-todo-log-states nil)
8660 (nshiftmax 10) (nshift 0)
8661 re type n what ts mb0 time)
8662 (when repeat
8663 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
8664 (org-todo (if (eq interpret 'type) last-state head))
8665 (when org-log-repeat
8666 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
8667 (memq 'org-add-log-note post-command-hook))
8668 ;; OK, we are already setup for some record
8669 (if (eq org-log-repeat 'note)
8670 ;; make sure we take a note, not only a time stamp
8671 (setq org-log-note-how 'note))
8672 ;; Set up for taking a record
8673 (org-add-log-setup 'state (or done-word (car org-done-keywords))
8674 'findpos org-log-repeat)))
8675 (org-back-to-heading t)
8676 (org-add-planning-info nil nil 'closed)
8677 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
8678 org-deadline-time-regexp "\\)\\|\\("
8679 org-ts-regexp "\\)"))
8680 (while (re-search-forward
8681 re (save-excursion (outline-next-heading) (point)) t)
8682 (setq type (if (match-end 1) org-scheduled-string
8683 (if (match-end 3) org-deadline-string "Plain:"))
8684 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0)))
8685 mb0 (match-beginning 0))
8686 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
8687 (setq n (string-to-number (match-string 2 ts))
8688 what (match-string 3 ts))
8689 (if (equal what "w") (setq n (* n 7) what "d"))
8690 ;; Preparation, see if we need to modify the start date for the change
8691 (when (match-end 1)
8692 (setq time (save-match-data (org-time-string-to-time ts)))
8693 (cond
8694 ((equal (match-string 1 ts) ".")
8695 ;; Shift starting date to today
8696 (org-timestamp-change
8697 (- (time-to-days (current-time)) (time-to-days time))
8698 'day))
8699 ((equal (match-string 1 ts) "+")
8700 (while (or (= nshift 0)
8701 (<= (time-to-days time) (time-to-days (current-time))))
8702 (when (= (incf nshift) nshiftmax)
8703 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
8704 (error "Abort")))
8705 (org-timestamp-change n (cdr (assoc what whata)))
8706 (org-at-timestamp-p t)
8707 (setq ts (match-string 1))
8708 (setq time (save-match-data (org-time-string-to-time ts))))
8709 (org-timestamp-change (- n) (cdr (assoc what whata)))
8710 ;; rematch, so that we have everything in place for the real shift
8711 (org-at-timestamp-p t)
8712 (setq ts (match-string 1))
8713 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
8714 (org-timestamp-change n (cdr (assoc what whata)))
8715 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
8716 (setq org-log-post-message msg)
8717 (message "%s" msg))))
8719 (defun org-show-todo-tree (arg)
8720 "Make a compact tree which shows all headlines marked with TODO.
8721 The tree will show the lines where the regexp matches, and all higher
8722 headlines above the match.
8723 With a \\[universal-argument] prefix, also show the DONE entries.
8724 With a numeric prefix N, construct a sparse tree for the Nth element
8725 of `org-todo-keywords-1'."
8726 (interactive "P")
8727 (let ((case-fold-search nil)
8728 (kwd-re
8729 (cond ((null arg) org-not-done-regexp)
8730 ((equal arg '(4))
8731 (let ((kwd (org-ido-completing-read "Keyword (or KWD1|KWD2|...): "
8732 (mapcar 'list org-todo-keywords-1))))
8733 (concat "\\("
8734 (mapconcat 'identity (org-split-string kwd "|") "\\|")
8735 "\\)\\>")))
8736 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
8737 (regexp-quote (nth (1- (prefix-numeric-value arg))
8738 org-todo-keywords-1)))
8739 (t (error "Invalid prefix argument: %s" arg)))))
8740 (message "%d TODO entries found"
8741 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
8743 (defun org-deadline (&optional remove time)
8744 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
8745 With argument REMOVE, remove any deadline from the item.
8746 When TIME is set, it should be an internal time specification, and the
8747 scheduling will use the corresponding date."
8748 (interactive "P")
8749 (if remove
8750 (progn
8751 (org-remove-timestamp-with-keyword org-deadline-string)
8752 (message "Item no longer has a deadline."))
8753 (if (org-get-repeat)
8754 (error "Cannot change deadline on task with repeater, please do that by hand")
8755 (org-add-planning-info 'deadline time 'closed)
8756 (message "Deadline on %s" org-last-inserted-timestamp))))
8758 (defun org-schedule (&optional remove time)
8759 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
8760 With argument REMOVE, remove any scheduling date from the item.
8761 When TIME is set, it should be an internal time specification, and the
8762 scheduling will use the corresponding date."
8763 (interactive "P")
8764 (if remove
8765 (progn
8766 (org-remove-timestamp-with-keyword org-scheduled-string)
8767 (message "Item is no longer scheduled."))
8768 (if (org-get-repeat)
8769 (error "Cannot reschedule task with repeater, please do that by hand")
8770 (org-add-planning-info 'scheduled time 'closed)
8771 (message "Scheduled to %s" org-last-inserted-timestamp))))
8773 (defun org-remove-timestamp-with-keyword (keyword)
8774 "Remove all time stamps with KEYWORD in the current entry."
8775 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
8776 beg)
8777 (save-excursion
8778 (org-back-to-heading t)
8779 (setq beg (point))
8780 (org-end-of-subtree t t)
8781 (while (re-search-backward re beg t)
8782 (replace-match "")
8783 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
8784 (equal (char-before) ?\ ))
8785 (backward-delete-char 1)
8786 (if (string-match "^[ \t]*$" (buffer-substring
8787 (point-at-bol) (point-at-eol)))
8788 (delete-region (point-at-bol)
8789 (min (point-max) (1+ (point-at-eol))))))))))
8791 (defun org-add-planning-info (what &optional time &rest remove)
8792 "Insert new timestamp with keyword in the line directly after the headline.
8793 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
8794 If non is given, the user is prompted for a date.
8795 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
8796 be removed."
8797 (interactive)
8798 (let (org-time-was-given org-end-time-was-given ts
8799 end default-time default-input)
8801 (when (and (not time) (memq what '(scheduled deadline)))
8802 ;; Try to get a default date/time from existing timestamp
8803 (save-excursion
8804 (org-back-to-heading t)
8805 (setq end (save-excursion (outline-next-heading) (point)))
8806 (when (re-search-forward (if (eq what 'scheduled)
8807 org-scheduled-time-regexp
8808 org-deadline-time-regexp)
8809 end t)
8810 (setq ts (match-string 1)
8811 default-time
8812 (apply 'encode-time (org-parse-time-string ts))
8813 default-input (and ts (org-get-compact-tod ts))))))
8814 (when what
8815 ;; If necessary, get the time from the user
8816 (setq time (or time (org-read-date nil 'to-time nil nil
8817 default-time default-input))))
8819 (when (and org-insert-labeled-timestamps-at-point
8820 (member what '(scheduled deadline)))
8821 (insert
8822 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
8823 (org-insert-time-stamp time org-time-was-given
8824 nil nil nil (list org-end-time-was-given))
8825 (setq what nil))
8826 (save-excursion
8827 (save-restriction
8828 (let (col list elt ts buffer-invisibility-spec)
8829 (org-back-to-heading t)
8830 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
8831 (goto-char (match-end 1))
8832 (setq col (current-column))
8833 (goto-char (match-end 0))
8834 (if (eobp) (insert "\n") (forward-char 1))
8835 (if (and (not (looking-at outline-regexp))
8836 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
8837 "[^\r\n]*"))
8838 (not (equal (match-string 1) org-clock-string)))
8839 (narrow-to-region (match-beginning 0) (match-end 0))
8840 (insert-before-markers "\n")
8841 (backward-char 1)
8842 (narrow-to-region (point) (point))
8843 (and org-adapt-indentation (org-indent-to-column col)))
8844 ;; Check if we have to remove something.
8845 (setq list (cons what remove))
8846 (while list
8847 (setq elt (pop list))
8848 (goto-char (point-min))
8849 (when (or (and (eq elt 'scheduled)
8850 (re-search-forward org-scheduled-time-regexp nil t))
8851 (and (eq elt 'deadline)
8852 (re-search-forward org-deadline-time-regexp nil t))
8853 (and (eq elt 'closed)
8854 (re-search-forward org-closed-time-regexp nil t)))
8855 (replace-match "")
8856 (if (looking-at "--+<[^>]+>") (replace-match ""))
8857 (if (looking-at " +") (replace-match ""))))
8858 (goto-char (point-max))
8859 (when what
8860 (insert
8861 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
8862 (cond ((eq what 'scheduled) org-scheduled-string)
8863 ((eq what 'deadline) org-deadline-string)
8864 ((eq what 'closed) org-closed-string))
8865 " ")
8866 (setq ts (org-insert-time-stamp
8867 time
8868 (or org-time-was-given
8869 (and (eq what 'closed) org-log-done-with-time))
8870 (eq what 'closed)
8871 nil nil (list org-end-time-was-given)))
8872 (end-of-line 1))
8873 (goto-char (point-min))
8874 (widen)
8875 (if (and (looking-at "[ \t]+\n")
8876 (equal (char-before) ?\n))
8877 (delete-region (1- (point)) (point-at-eol)))
8878 ts)))))
8880 (defvar org-log-note-marker (make-marker))
8881 (defvar org-log-note-purpose nil)
8882 (defvar org-log-note-state nil)
8883 (defvar org-log-note-how nil)
8884 (defvar org-log-note-extra nil)
8885 (defvar org-log-note-window-configuration nil)
8886 (defvar org-log-note-return-to (make-marker))
8887 (defvar org-log-post-message nil
8888 "Message to be displayed after a log note has been stored.
8889 The auto-repeater uses this.")
8891 (defun org-add-note ()
8892 "Add a note to the current entry.
8893 This is done in the same way as adding a state change note."
8894 (interactive)
8895 (org-add-log-setup 'note nil 'findpos nil))
8897 (defvar org-property-end-re)
8898 (defun org-add-log-setup (&optional purpose state findpos how &optional extra)
8899 "Set up the post command hook to take a note.
8900 If this is about to TODO state change, the new state is expected in STATE.
8901 When FINDPOS is non-nil, find the correct position for the note in
8902 the current entry. If not, assume that it can be inserted at point.
8903 HOW is an indicator what kind of note should be created.
8904 EXTRA is additional text that will be inserted into the notes buffer."
8905 (save-restriction
8906 (save-excursion
8907 (when findpos
8908 (org-back-to-heading t)
8909 (narrow-to-region (point) (save-excursion
8910 (outline-next-heading) (point)))
8911 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
8912 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
8913 "[^\r\n]*\\)?"))
8914 (goto-char (match-end 0))
8915 (when (and org-log-state-notes-insert-after-drawers
8916 (save-excursion
8917 (forward-line) (looking-at org-drawer-regexp)))
8918 (progn (forward-line)
8919 (while (looking-at org-drawer-regexp)
8920 (goto-char (match-end 0))
8921 (re-search-forward org-property-end-re (point-max) t)
8922 (forward-line))
8923 (forward-line -1)))
8924 (unless org-log-states-order-reversed
8925 (and (= (char-after) ?\n) (forward-char 1))
8926 (org-skip-over-state-notes)
8927 (skip-chars-backward " \t\n\r")))
8928 (move-marker org-log-note-marker (point))
8929 (setq org-log-note-purpose purpose
8930 org-log-note-state state
8931 org-log-note-how how
8932 org-log-note-extra extra)
8933 (add-hook 'post-command-hook 'org-add-log-note 'append))))
8935 (defun org-skip-over-state-notes ()
8936 "Skip past the list of State notes in an entry."
8937 (if (looking-at "\n[ \t]*- State") (forward-char 1))
8938 (while (looking-at "[ \t]*- State")
8939 (condition-case nil
8940 (org-next-item)
8941 (error (org-end-of-item)))))
8943 (defun org-add-log-note (&optional purpose)
8944 "Pop up a window for taking a note, and add this note later at point."
8945 (remove-hook 'post-command-hook 'org-add-log-note)
8946 (setq org-log-note-window-configuration (current-window-configuration))
8947 (delete-other-windows)
8948 (move-marker org-log-note-return-to (point))
8949 (switch-to-buffer (marker-buffer org-log-note-marker))
8950 (goto-char org-log-note-marker)
8951 (org-switch-to-buffer-other-window "*Org Note*")
8952 (erase-buffer)
8953 (if (memq org-log-note-how '(time state))
8954 (let (current-prefix-arg) (org-store-log-note))
8955 (let ((org-inhibit-startup t)) (org-mode))
8956 (insert (format "# Insert note for %s.
8957 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
8958 (cond
8959 ((eq org-log-note-purpose 'clock-out) "stopped clock")
8960 ((eq org-log-note-purpose 'done) "closed todo item")
8961 ((eq org-log-note-purpose 'state)
8962 (format "state change to \"%s\"" org-log-note-state))
8963 ((eq org-log-note-purpose 'note)
8964 "this entry")
8965 (t (error "This should not happen")))))
8966 (if org-log-note-extra (insert org-log-note-extra))
8967 (org-set-local 'org-finish-function 'org-store-log-note)))
8969 (defvar org-note-abort nil) ; dynamically scoped
8970 (defun org-store-log-note ()
8971 "Finish taking a log note, and insert it to where it belongs."
8972 (let ((txt (buffer-string))
8973 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
8974 lines ind)
8975 (kill-buffer (current-buffer))
8976 (while (string-match "\\`#.*\n[ \t\n]*" txt)
8977 (setq txt (replace-match "" t t txt)))
8978 (if (string-match "\\s-+\\'" txt)
8979 (setq txt (replace-match "" t t txt)))
8980 (setq lines (org-split-string txt "\n"))
8981 (when (and note (string-match "\\S-" note))
8982 (setq note
8983 (org-replace-escapes
8984 note
8985 (list (cons "%u" (user-login-name))
8986 (cons "%U" user-full-name)
8987 (cons "%t" (format-time-string
8988 (org-time-stamp-format 'long 'inactive)
8989 (current-time)))
8990 (cons "%s" (if org-log-note-state
8991 (concat "\"" org-log-note-state "\"")
8992 "")))))
8993 (if lines (setq note (concat note " \\\\")))
8994 (push note lines))
8995 (when (or current-prefix-arg org-note-abort) (setq lines nil))
8996 (when lines
8997 (save-excursion
8998 (set-buffer (marker-buffer org-log-note-marker))
8999 (save-excursion
9000 (goto-char org-log-note-marker)
9001 (move-marker org-log-note-marker nil)
9002 (end-of-line 1)
9003 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
9004 (indent-relative nil)
9005 (insert "- " (pop lines))
9006 (org-indent-line-function)
9007 (beginning-of-line 1)
9008 (looking-at "[ \t]*")
9009 (setq ind (concat (match-string 0) " "))
9010 (end-of-line 1)
9011 (while lines (insert "\n" ind (pop lines)))))))
9012 (set-window-configuration org-log-note-window-configuration)
9013 (with-current-buffer (marker-buffer org-log-note-return-to)
9014 (goto-char org-log-note-return-to))
9015 (move-marker org-log-note-return-to nil)
9016 (and org-log-post-message (message "%s" org-log-post-message)))
9018 (defun org-sparse-tree (&optional arg)
9019 "Create a sparse tree, prompt for the details.
9020 This command can create sparse trees. You first need to select the type
9021 of match used to create the tree:
9023 t Show entries with a specific TODO keyword.
9024 T Show entries selected by a tags match.
9025 p Enter a property name and its value (both with completion on existing
9026 names/values) and show entries with that property.
9027 r Show entries matching a regular expression
9028 d Show deadlines due within `org-deadline-warning-days'."
9029 (interactive "P")
9030 (let (ans kwd value)
9031 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
9032 (setq ans (read-char-exclusive))
9033 (cond
9034 ((equal ans ?d)
9035 (call-interactively 'org-check-deadlines))
9036 ((equal ans ?b)
9037 (call-interactively 'org-check-before-date))
9038 ((equal ans ?t)
9039 (org-show-todo-tree '(4)))
9040 ((equal ans ?T)
9041 (call-interactively 'org-tags-sparse-tree))
9042 ((member ans '(?p ?P))
9043 (setq kwd (org-ido-completing-read "Property: "
9044 (mapcar 'list (org-buffer-property-keys))))
9045 (setq value (org-ido-completing-read "Value: "
9046 (mapcar 'list (org-property-values kwd))))
9047 (unless (string-match "\\`{.*}\\'" value)
9048 (setq value (concat "\"" value "\"")))
9049 (org-tags-sparse-tree arg (concat kwd "=" value)))
9050 ((member ans '(?r ?R ?/))
9051 (call-interactively 'org-occur))
9052 (t (error "No such sparse tree command \"%c\"" ans)))))
9054 (defvar org-occur-highlights nil
9055 "List of overlays used for occur matches.")
9056 (make-variable-buffer-local 'org-occur-highlights)
9057 (defvar org-occur-parameters nil
9058 "Parameters of the active org-occur calls.
9059 This is a list, each call to org-occur pushes as cons cell,
9060 containing the regular expression and the callback, onto the list.
9061 The list can contain several entries if `org-occur' has been called
9062 several time with the KEEP-PREVIOUS argument. Otherwise, this list
9063 will only contain one set of parameters. When the highlights are
9064 removed (for example with `C-c C-c', or with the next edit (depending
9065 on `org-remove-highlights-with-change'), this variable is emptied
9066 as well.")
9067 (make-variable-buffer-local 'org-occur-parameters)
9069 (defun org-occur (regexp &optional keep-previous callback)
9070 "Make a compact tree which shows all matches of REGEXP.
9071 The tree will show the lines where the regexp matches, and all higher
9072 headlines above the match. It will also show the heading after the match,
9073 to make sure editing the matching entry is easy.
9074 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
9075 call to `org-occur' will be kept, to allow stacking of calls to this
9076 command.
9077 If CALLBACK is non-nil, it is a function which is called to confirm
9078 that the match should indeed be shown."
9079 (interactive "sRegexp: \nP")
9080 (unless keep-previous
9081 (org-remove-occur-highlights nil nil t))
9082 (push (cons regexp callback) org-occur-parameters)
9083 (let ((cnt 0))
9084 (save-excursion
9085 (goto-char (point-min))
9086 (if (or (not keep-previous) ; do not want to keep
9087 (not org-occur-highlights)) ; no previous matches
9088 ;; hide everything
9089 (org-overview))
9090 (while (re-search-forward regexp nil t)
9091 (when (or (not callback)
9092 (save-match-data (funcall callback)))
9093 (setq cnt (1+ cnt))
9094 (when org-highlight-sparse-tree-matches
9095 (org-highlight-new-match (match-beginning 0) (match-end 0)))
9096 (org-show-context 'occur-tree))))
9097 (when org-remove-highlights-with-change
9098 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
9099 nil 'local))
9100 (unless org-sparse-tree-open-archived-trees
9101 (org-hide-archived-subtrees (point-min) (point-max)))
9102 (run-hooks 'org-occur-hook)
9103 (if (interactive-p)
9104 (message "%d match(es) for regexp %s" cnt regexp))
9105 cnt))
9107 (defun org-show-context (&optional key)
9108 "Make sure point and context and visible.
9109 How much context is shown depends upon the variables
9110 `org-show-hierarchy-above', `org-show-following-heading'. and
9111 `org-show-siblings'."
9112 (let ((heading-p (org-on-heading-p t))
9113 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
9114 (following-p (org-get-alist-option org-show-following-heading key))
9115 (entry-p (org-get-alist-option org-show-entry-below key))
9116 (siblings-p (org-get-alist-option org-show-siblings key)))
9117 (catch 'exit
9118 ;; Show heading or entry text
9119 (if (and heading-p (not entry-p))
9120 (org-flag-heading nil) ; only show the heading
9121 (and (or entry-p (org-invisible-p) (org-invisible-p2))
9122 (org-show-hidden-entry))) ; show entire entry
9123 (when following-p
9124 ;; Show next sibling, or heading below text
9125 (save-excursion
9126 (and (if heading-p (org-goto-sibling) (outline-next-heading))
9127 (org-flag-heading nil))))
9128 (when siblings-p (org-show-siblings))
9129 (when hierarchy-p
9130 ;; show all higher headings, possibly with siblings
9131 (save-excursion
9132 (while (and (condition-case nil
9133 (progn (org-up-heading-all 1) t)
9134 (error nil))
9135 (not (bobp)))
9136 (org-flag-heading nil)
9137 (when siblings-p (org-show-siblings))))))))
9139 (defun org-reveal (&optional siblings)
9140 "Show current entry, hierarchy above it, and the following headline.
9141 This can be used to show a consistent set of context around locations
9142 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
9143 not t for the search context.
9145 With optional argument SIBLINGS, on each level of the hierarchy all
9146 siblings are shown. This repairs the tree structure to what it would
9147 look like when opened with hierarchical calls to `org-cycle'."
9148 (interactive "P")
9149 (let ((org-show-hierarchy-above t)
9150 (org-show-following-heading t)
9151 (org-show-siblings (if siblings t org-show-siblings)))
9152 (org-show-context nil)))
9154 (defun org-highlight-new-match (beg end)
9155 "Highlight from BEG to END and mark the highlight is an occur headline."
9156 (let ((ov (org-make-overlay beg end)))
9157 (org-overlay-put ov 'face 'secondary-selection)
9158 (push ov org-occur-highlights)))
9160 (defun org-remove-occur-highlights (&optional beg end noremove)
9161 "Remove the occur highlights from the buffer.
9162 BEG and END are ignored. If NOREMOVE is nil, remove this function
9163 from the `before-change-functions' in the current buffer."
9164 (interactive)
9165 (unless org-inhibit-highlight-removal
9166 (mapc 'org-delete-overlay org-occur-highlights)
9167 (setq org-occur-highlights nil)
9168 (setq org-occur-parameters nil)
9169 (unless noremove
9170 (remove-hook 'before-change-functions
9171 'org-remove-occur-highlights 'local))))
9173 ;;;; Priorities
9175 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
9176 "Regular expression matching the priority indicator.")
9178 (defvar org-remove-priority-next-time nil)
9180 (defun org-priority-up ()
9181 "Increase the priority of the current item."
9182 (interactive)
9183 (org-priority 'up))
9185 (defun org-priority-down ()
9186 "Decrease the priority of the current item."
9187 (interactive)
9188 (org-priority 'down))
9190 (defun org-priority (&optional action)
9191 "Change the priority of an item by ARG.
9192 ACTION can be `set', `up', `down', or a character."
9193 (interactive)
9194 (setq action (or action 'set))
9195 (let (current new news have remove)
9196 (save-excursion
9197 (org-back-to-heading)
9198 (if (looking-at org-priority-regexp)
9199 (setq current (string-to-char (match-string 2))
9200 have t)
9201 (setq current org-default-priority))
9202 (cond
9203 ((or (eq action 'set)
9204 (if (featurep 'xemacs) (characterp action) (integerp action)))
9205 (if (not (eq action 'set))
9206 (setq new action)
9207 (message "Priority %c-%c, SPC to remove: "
9208 org-highest-priority org-lowest-priority)
9209 (setq new (read-char-exclusive)))
9210 (if (and (= (upcase org-highest-priority) org-highest-priority)
9211 (= (upcase org-lowest-priority) org-lowest-priority))
9212 (setq new (upcase new)))
9213 (cond ((equal new ?\ ) (setq remove t))
9214 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
9215 (error "Priority must be between `%c' and `%c'"
9216 org-highest-priority org-lowest-priority))))
9217 ((eq action 'up)
9218 (if (and (not have) (eq last-command this-command))
9219 (setq new org-lowest-priority)
9220 (setq new (if (and org-priority-start-cycle-with-default (not have))
9221 org-default-priority (1- current)))))
9222 ((eq action 'down)
9223 (if (and (not have) (eq last-command this-command))
9224 (setq new org-highest-priority)
9225 (setq new (if (and org-priority-start-cycle-with-default (not have))
9226 org-default-priority (1+ current)))))
9227 (t (error "Invalid action")))
9228 (if (or (< (upcase new) org-highest-priority)
9229 (> (upcase new) org-lowest-priority))
9230 (setq remove t))
9231 (setq news (format "%c" new))
9232 (if have
9233 (if remove
9234 (replace-match "" t t nil 1)
9235 (replace-match news t t nil 2))
9236 (if remove
9237 (error "No priority cookie found in line")
9238 (looking-at org-todo-line-regexp)
9239 (if (match-end 2)
9240 (progn
9241 (goto-char (match-end 2))
9242 (insert " [#" news "]"))
9243 (goto-char (match-beginning 3))
9244 (insert "[#" news "] ")))))
9245 (org-preserve-lc (org-set-tags nil 'align))
9246 (if remove
9247 (message "Priority removed")
9248 (message "Priority of current item set to %s" news))))
9251 (defun org-get-priority (s)
9252 "Find priority cookie and return priority."
9253 (save-match-data
9254 (if (not (string-match org-priority-regexp s))
9255 (* 1000 (- org-lowest-priority org-default-priority))
9256 (* 1000 (- org-lowest-priority
9257 (string-to-char (match-string 2 s)))))))
9259 ;;;; Tags
9261 (defvar org-agenda-archives-mode)
9262 (defun org-scan-tags (action matcher &optional todo-only)
9263 "Scan headline tags with inheritance and produce output ACTION.
9265 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
9266 or `agenda' to produce an entry list for an agenda view. It can also be
9267 a Lisp form or a function that should be called at each matched headline, in
9268 this case the return value is a list of all return values from these calls.
9270 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
9271 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
9272 only lines with a TODO keyword are included in the output."
9273 (require 'org-agenda)
9274 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
9275 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
9276 (org-re
9277 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
9278 (props (list 'face 'default
9279 'done-face 'org-done
9280 'undone-face 'default
9281 'mouse-face 'highlight
9282 'org-not-done-regexp org-not-done-regexp
9283 'org-todo-regexp org-todo-regexp
9284 'keymap org-agenda-keymap
9285 'help-echo
9286 (format "mouse-2 or RET jump to org file %s"
9287 (abbreviate-file-name
9288 (or (buffer-file-name (buffer-base-buffer))
9289 (buffer-name (buffer-base-buffer)))))))
9290 (case-fold-search nil)
9291 lspos tags tags-list
9292 (tags-alist (list (cons 0 (mapcar 'downcase org-file-tags))))
9293 (llast 0) rtn rtn1 level category i txt
9294 todo marker entry priority)
9295 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
9296 (setq action (list 'lambda nil action)))
9297 (save-excursion
9298 (goto-char (point-min))
9299 (when (eq action 'sparse-tree)
9300 (org-overview)
9301 (org-remove-occur-highlights))
9302 (while (re-search-forward re nil t)
9303 (catch :skip
9304 (setq todo (if (match-end 1) (match-string 2))
9305 tags (if (match-end 4) (match-string 4)))
9306 (goto-char (setq lspos (1+ (match-beginning 0))))
9307 (setq level (org-reduced-level (funcall outline-level))
9308 category (org-get-category))
9309 (setq i llast llast level)
9310 ;; remove tag lists from same and sublevels
9311 (while (>= i level)
9312 (when (setq entry (assoc i tags-alist))
9313 (setq tags-alist (delete entry tags-alist)))
9314 (setq i (1- i)))
9315 ;; add the next tags
9316 (when tags
9317 (setq tags (mapcar 'downcase (org-split-string tags ":"))
9318 tags-alist
9319 (cons (cons level tags) tags-alist)))
9320 ;; compile tags for current headline
9321 (setq tags-list
9322 (if org-use-tag-inheritance
9323 (apply 'append (mapcar 'cdr (reverse tags-alist)))
9324 tags))
9325 (when org-use-tag-inheritance
9326 (setcdr (car tags-alist)
9327 (mapcar (lambda (x)
9328 (setq x (copy-sequence x))
9329 (org-add-prop-inherited x))
9330 (cdar tags-alist))))
9331 (when (and tags org-use-tag-inheritance
9332 (not (eq t org-use-tag-inheritance)))
9333 ;; selective inheritance, remove uninherited ones
9334 (setcdr (car tags-alist)
9335 (org-remove-uniherited-tags (cdar tags-alist))))
9336 (when (and (or (not todo-only)
9337 (and (member todo org-not-done-keywords)
9338 (or (not org-agenda-tags-todo-honor-ignore-options)
9339 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
9340 (let ((case-fold-search t)) (eval matcher))
9342 (not (member org-archive-tag tags-list))
9343 ;; we have an archive tag, should we use this anyway?
9344 (or (not org-agenda-skip-archived-trees)
9345 (and (eq action 'agenda) org-agenda-archives-mode))))
9346 (unless (eq action 'sparse-tree) (org-agenda-skip))
9348 ;; select this headline
9350 (cond
9351 ((eq action 'sparse-tree)
9352 (and org-highlight-sparse-tree-matches
9353 (org-get-heading) (match-end 0)
9354 (org-highlight-new-match
9355 (match-beginning 0) (match-beginning 1)))
9356 (org-show-context 'tags-tree))
9357 ((eq action 'agenda)
9358 (setq txt (org-format-agenda-item
9360 (concat
9361 (if org-tags-match-list-sublevels
9362 (make-string (1- level) ?.) "")
9363 (org-get-heading))
9364 category (org-get-tags-at))
9365 priority (org-get-priority txt))
9366 (goto-char lspos)
9367 (setq marker (org-agenda-new-marker))
9368 (org-add-props txt props
9369 'org-marker marker 'org-hd-marker marker 'org-category category
9370 'priority priority 'type "tagsmatch")
9371 (push txt rtn))
9372 ((functionp action)
9373 (save-excursion
9374 (setq rtn1 (funcall action))
9375 (push rtn1 rtn))
9376 (goto-char (point-at-eol)))
9377 (t (error "Invalid action")))
9379 ;; if we are to skip sublevels, jump to end of subtree
9380 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
9381 (when (and (eq action 'sparse-tree)
9382 (not org-sparse-tree-open-archived-trees))
9383 (org-hide-archived-subtrees (point-min) (point-max)))
9384 (nreverse rtn)))
9386 (defun org-remove-uniherited-tags (tags)
9387 "Remove all tags that are not inherited from the list TAGS."
9388 (cond
9389 ((eq org-use-tag-inheritance t)
9390 (if org-tags-exclude-from-inheritance
9391 (org-delete-all org-tags-exclude-from-inheritance tags)
9392 tags))
9393 ((not org-use-tag-inheritance) nil)
9394 ((stringp org-use-tag-inheritance)
9395 (delq nil (mapcar
9396 (lambda (x)
9397 (if (and (string-match org-use-tag-inheritance x)
9398 (not (member x org-tags-exclude-from-inheritance)))
9399 x nil))
9400 tags)))
9401 ((listp org-use-tag-inheritance)
9402 (delq nil (mapcar
9403 (lambda (x)
9404 (if (member x org-use-tag-inheritance) x nil))
9405 tags)))))
9407 (defvar todo-only) ;; dynamically scoped
9409 (defun org-tags-sparse-tree (&optional todo-only match)
9410 "Create a sparse tree according to tags string MATCH.
9411 MATCH can contain positive and negative selection of tags, like
9412 \"+WORK+URGENT-WITHBOSS\".
9413 If optional argument TODO-ONLY is non-nil, only select lines that are
9414 also TODO lines."
9415 (interactive "P")
9416 (org-prepare-agenda-buffers (list (current-buffer)))
9417 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
9419 (defvar org-cached-props nil)
9420 (defun org-cached-entry-get (pom property)
9421 (if (or (eq t org-use-property-inheritance)
9422 (and (stringp org-use-property-inheritance)
9423 (string-match org-use-property-inheritance property))
9424 (and (listp org-use-property-inheritance)
9425 (member property org-use-property-inheritance)))
9426 ;; Caching is not possible, check it directly
9427 (org-entry-get pom property 'inherit)
9428 ;; Get all properties, so that we can do complicated checks easily
9429 (cdr (assoc property (or org-cached-props
9430 (setq org-cached-props
9431 (org-entry-properties pom)))))))
9433 (defun org-global-tags-completion-table (&optional files)
9434 "Return the list of all tags in all agenda buffer/files."
9435 (save-excursion
9436 (org-uniquify
9437 (delq nil
9438 (apply 'append
9439 (mapcar
9440 (lambda (file)
9441 (set-buffer (find-file-noselect file))
9442 (append (org-get-buffer-tags)
9443 (mapcar (lambda (x) (if (stringp (car-safe x))
9444 (list (car-safe x)) nil))
9445 org-tag-alist)))
9446 (if (and files (car files))
9447 files
9448 (org-agenda-files))))))))
9450 (defun org-make-tags-matcher (match)
9451 "Create the TAGS//TODO matcher form for the selection string MATCH."
9452 ;; todo-only is scoped dynamically into this function, and the function
9453 ;; may change it if the matcher asks for it.
9454 (unless match
9455 ;; Get a new match request, with completion
9456 (let ((org-last-tags-completion-table
9457 (org-global-tags-completion-table)))
9458 (setq match (org-completing-read
9459 "Match: " 'org-tags-completion-function nil nil nil
9460 'org-tags-history))))
9462 ;; Parse the string and create a lisp form
9463 (let ((match0 match)
9464 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
9465 minus tag mm
9466 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
9467 orterms term orlist re-p str-p level-p level-op time-p
9468 prop-p pn pv po cat-p gv rest)
9469 (if (string-match "/+" match)
9470 ;; match contains also a todo-matching request
9471 (progn
9472 (setq tagsmatch (substring match 0 (match-beginning 0))
9473 todomatch (substring match (match-end 0)))
9474 (if (string-match "^!" todomatch)
9475 (setq todo-only t todomatch (substring todomatch 1)))
9476 (if (string-match "^\\s-*$" todomatch)
9477 (setq todomatch nil)))
9478 ;; only matching tags
9479 (setq tagsmatch match todomatch nil))
9481 ;; Make the tags matcher
9482 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
9483 (setq tagsmatcher t)
9484 (setq orterms (org-split-string tagsmatch "|") orlist nil)
9485 (while (setq term (pop orterms))
9486 (while (and (equal (substring term -1) "\\") orterms)
9487 (setq term (concat term "|" (pop orterms)))) ; repair bad split
9488 (while (string-match re term)
9489 (setq rest (substring term (match-end 0))
9490 minus (and (match-end 1)
9491 (equal (match-string 1 term) "-"))
9492 tag (match-string 2 term)
9493 re-p (equal (string-to-char tag) ?{)
9494 level-p (match-end 4)
9495 prop-p (match-end 5)
9496 mm (cond
9497 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
9498 (level-p
9499 (setq level-op (org-op-to-function (match-string 3 term)))
9500 `(,level-op level ,(string-to-number
9501 (match-string 4 term))))
9502 (prop-p
9503 (setq pn (match-string 5 term)
9504 po (match-string 6 term)
9505 pv (match-string 7 term)
9506 cat-p (equal pn "CATEGORY")
9507 re-p (equal (string-to-char pv) ?{)
9508 str-p (equal (string-to-char pv) ?\")
9509 time-p (save-match-data
9510 (string-match "^\"[[<].*[]>]\"$" pv))
9511 pv (if (or re-p str-p) (substring pv 1 -1) pv))
9512 (if time-p (setq pv (org-matcher-time pv)))
9513 (setq po (org-op-to-function po (if time-p 'time str-p)))
9514 (cond
9515 ((equal pn "CATEGORY")
9516 (setq gv '(get-text-property (point) 'org-category)))
9517 ((equal pn "TODO")
9518 (setq gv 'todo))
9520 (setq gv `(org-cached-entry-get nil ,pn))))
9521 (if re-p
9522 (if (eq po 'org<>)
9523 `(not (string-match ,pv (or ,gv "")))
9524 `(string-match ,pv (or ,gv "")))
9525 (if str-p
9526 `(,po (or ,gv "") ,pv)
9527 `(,po (string-to-number (or ,gv ""))
9528 ,(string-to-number pv) ))))
9529 (t `(member ,(downcase tag) tags-list)))
9530 mm (if minus (list 'not mm) mm)
9531 term rest)
9532 (push mm tagsmatcher))
9533 (push (if (> (length tagsmatcher) 1)
9534 (cons 'and tagsmatcher)
9535 (car tagsmatcher))
9536 orlist)
9537 (setq tagsmatcher nil))
9538 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
9539 (setq tagsmatcher
9540 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
9541 ;; Make the todo matcher
9542 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
9543 (setq todomatcher t)
9544 (setq orterms (org-split-string todomatch "|") orlist nil)
9545 (while (setq term (pop orterms))
9546 (while (string-match re term)
9547 (setq minus (and (match-end 1)
9548 (equal (match-string 1 term) "-"))
9549 kwd (match-string 2 term)
9550 re-p (equal (string-to-char kwd) ?{)
9551 term (substring term (match-end 0))
9552 mm (if re-p
9553 `(string-match ,(substring kwd 1 -1) todo)
9554 (list 'equal 'todo kwd))
9555 mm (if minus (list 'not mm) mm))
9556 (push mm todomatcher))
9557 (push (if (> (length todomatcher) 1)
9558 (cons 'and todomatcher)
9559 (car todomatcher))
9560 orlist)
9561 (setq todomatcher nil))
9562 (setq todomatcher (if (> (length orlist) 1)
9563 (cons 'or orlist) (car orlist))))
9565 ;; Return the string and lisp forms of the matcher
9566 (setq matcher (if todomatcher
9567 (list 'and tagsmatcher todomatcher)
9568 tagsmatcher))
9569 (cons match0 matcher)))
9571 (defun org-op-to-function (op &optional stringp)
9572 "Turn an operator into the appropriate function."
9573 (setq op
9574 (cond
9575 ((equal op "<" ) '(< string< org-time<))
9576 ((equal op ">" ) '(> org-string> org-time>))
9577 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
9578 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
9579 ((member op '("=" "==")) '(= string= org-time=))
9580 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
9581 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
9583 (defun org<> (a b) (not (= a b)))
9584 (defun org-string<= (a b) (or (string= a b) (string< a b)))
9585 (defun org-string>= (a b) (not (string< a b)))
9586 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
9587 (defun org-string<> (a b) (not (string= a b)))
9588 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
9589 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
9590 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
9591 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
9592 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
9593 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
9594 (defun org-2ft (s)
9595 "Convert S to a floating point time.
9596 If S is already a number, just return it. If it is a string, parse
9597 it as a time string and apply `float-time' to it. If S is nil, just return 0."
9598 (cond
9599 ((numberp s) s)
9600 ((stringp s)
9601 (condition-case nil
9602 (float-time (apply 'encode-time (org-parse-time-string s)))
9603 (error 0.)))
9604 (t 0.)))
9606 (defun org-time-today ()
9607 "Time in seconds today at 0:00.
9608 Returns the float number of seconds since the beginning of the
9609 epoch to the beginning of today (00:00)."
9610 (float-time (apply 'encode-time
9611 (append '(0 0 0) (nthcdr 3 (decode-time))))))
9613 (defun org-matcher-time (s)
9614 "Interpret a time comparison value."
9615 (save-match-data
9616 (cond
9617 ((string= s "<now>") (float-time))
9618 ((string= s "<today>") (org-time-today))
9619 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
9620 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
9621 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
9622 (+ (org-time-today)
9623 (* (string-to-number (match-string 1 s))
9624 (cdr (assoc (match-string 2 s)
9625 '(("d" . 86400.0) ("w" . 604800.0)
9626 ("m" . 2678400.0) ("y" . 31557600.0)))))))
9627 (t (org-2ft s)))))
9629 (defun org-match-any-p (re list)
9630 "Does re match any element of list?"
9631 (setq list (mapcar (lambda (x) (string-match re x)) list))
9632 (delq nil list))
9634 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
9635 (defvar org-tags-overlay (org-make-overlay 1 1))
9636 (org-detach-overlay org-tags-overlay)
9638 (defun org-get-local-tags-at (&optional pos)
9639 "Get a list of tags defined in the current headline."
9640 (org-get-tags-at pos 'local))
9642 (defun org-get-local-tags ()
9643 "Get a list of tags defined in the current headline."
9644 (org-get-tags-at nil 'local))
9646 (defun org-get-tags-at (&optional pos local)
9647 "Get a list of all headline tags applicable at POS.
9648 POS defaults to point. If tags are inherited, the list contains
9649 the targets in the same sequence as the headlines appear, i.e.
9650 the tags of the current headline come last.
9651 When LOCAL is non-nil, only return tags from the current headline,
9652 ignore inherited ones."
9653 (interactive)
9654 (let (tags ltags lastpos parent)
9655 (save-excursion
9656 (save-restriction
9657 (widen)
9658 (goto-char (or pos (point)))
9659 (save-match-data
9660 (catch 'done
9661 (condition-case nil
9662 (progn
9663 (org-back-to-heading t)
9664 (while (not (equal lastpos (point)))
9665 (setq lastpos (point))
9666 (when (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
9667 (setq ltags (org-split-string
9668 (org-match-string-no-properties 1) ":"))
9669 (when parent
9670 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
9671 (setq tags (append
9672 (if parent
9673 (org-remove-uniherited-tags ltags)
9674 ltags)
9675 tags)))
9676 (or org-use-tag-inheritance (throw 'done t))
9677 (if local (throw 'done t))
9678 (org-up-heading-all 1)
9679 (setq parent t)))
9680 (error nil)))))
9681 (append (org-remove-uniherited-tags org-file-tags) tags))))
9683 (defun org-add-prop-inherited (s)
9684 (add-text-properties 0 (length s) '(inherited t) s)
9687 (defun org-toggle-tag (tag &optional onoff)
9688 "Toggle the tag TAG for the current line.
9689 If ONOFF is `on' or `off', don't toggle but set to this state."
9690 (let (res current)
9691 (save-excursion
9692 (org-back-to-heading t)
9693 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
9694 (point-at-eol) t)
9695 (progn
9696 (setq current (match-string 1))
9697 (replace-match ""))
9698 (setq current ""))
9699 (setq current (nreverse (org-split-string current ":")))
9700 (cond
9701 ((eq onoff 'on)
9702 (setq res t)
9703 (or (member tag current) (push tag current)))
9704 ((eq onoff 'off)
9705 (or (not (member tag current)) (setq current (delete tag current))))
9706 (t (if (member tag current)
9707 (setq current (delete tag current))
9708 (setq res t)
9709 (push tag current))))
9710 (end-of-line 1)
9711 (if current
9712 (progn
9713 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
9714 (org-set-tags nil t))
9715 (delete-horizontal-space))
9716 (run-hooks 'org-after-tags-change-hook))
9717 res))
9719 (defun org-align-tags-here (to-col)
9720 ;; Assumes that this is a headline
9721 (let ((pos (point)) (col (current-column)) ncol tags-l p)
9722 (beginning-of-line 1)
9723 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9724 (< pos (match-beginning 2)))
9725 (progn
9726 (setq tags-l (- (match-end 2) (match-beginning 2)))
9727 (goto-char (match-beginning 1))
9728 (insert " ")
9729 (delete-region (point) (1+ (match-beginning 2)))
9730 (setq ncol (max (1+ (current-column))
9731 (1+ col)
9732 (if (> to-col 0)
9733 to-col
9734 (- (abs to-col) tags-l))))
9735 (setq p (point))
9736 (insert (make-string (- ncol (current-column)) ?\ ))
9737 (setq ncol (current-column))
9738 (when indent-tabs-mode (tabify p (point-at-eol)))
9739 (org-move-to-column (min ncol col) t))
9740 (goto-char pos))))
9742 (defun org-set-tags-command (&optional arg just-align)
9743 "Call the set-tags command for the current entry."
9744 (interactive "P")
9745 (if (org-on-heading-p)
9746 (org-set-tags arg just-align)
9747 (save-excursion
9748 (org-back-to-heading t)
9749 (org-set-tags arg just-align))))
9751 (defun org-set-tags (&optional arg just-align)
9752 "Set the tags for the current headline.
9753 With prefix ARG, realign all tags in headings in the current buffer."
9754 (interactive "P")
9755 (let* ((re (concat "^" outline-regexp))
9756 (current (org-get-tags-string))
9757 (col (current-column))
9758 (org-setting-tags t)
9759 table current-tags inherited-tags ; computed below when needed
9760 tags p0 c0 c1 rpl)
9761 (if arg
9762 (save-excursion
9763 (goto-char (point-min))
9764 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
9765 (while (re-search-forward re nil t)
9766 (org-set-tags nil t)
9767 (end-of-line 1)))
9768 (message "All tags realigned to column %d" org-tags-column))
9769 (if just-align
9770 (setq tags current)
9771 ;; Get a new set of tags from the user
9772 (save-excursion
9773 (setq table (or org-tag-alist (org-get-buffer-tags))
9774 org-last-tags-completion-table table
9775 current-tags (org-split-string current ":")
9776 inherited-tags (nreverse
9777 (nthcdr (length current-tags)
9778 (nreverse (org-get-tags-at))))
9779 tags
9780 (if (or (eq t org-use-fast-tag-selection)
9781 (and org-use-fast-tag-selection
9782 (delq nil (mapcar 'cdr table))))
9783 (org-fast-tag-selection
9784 current-tags inherited-tags table
9785 (if org-fast-tag-selection-include-todo org-todo-key-alist))
9786 (let ((org-add-colon-after-tag-completion t))
9787 (org-trim
9788 (org-without-partial-completion
9789 (org-ido-completing-read "Tags: " 'org-tags-completion-function
9790 nil nil current 'org-tags-history)))))))
9791 (while (string-match "[-+&]+" tags)
9792 ;; No boolean logic, just a list
9793 (setq tags (replace-match ":" t t tags))))
9795 (if (string-match "\\`[\t ]*\\'" tags)
9796 (setq tags "")
9797 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
9798 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
9800 ;; Insert new tags at the correct column
9801 (beginning-of-line 1)
9802 (cond
9803 ((and (equal current "") (equal tags "")))
9804 ((re-search-forward
9805 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
9806 (point-at-eol) t)
9807 (if (equal tags "")
9808 (setq rpl "")
9809 (goto-char (match-beginning 0))
9810 (setq c0 (current-column) p0 (point)
9811 c1 (max (1+ c0) (if (> org-tags-column 0)
9812 org-tags-column
9813 (- (- org-tags-column) (length tags))))
9814 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
9815 (replace-match rpl t t)
9816 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
9817 tags)
9818 (t (error "Tags alignment failed")))
9819 (org-move-to-column col)
9820 (unless just-align
9821 (run-hooks 'org-after-tags-change-hook)))))
9823 (defun org-change-tag-in-region (beg end tag off)
9824 "Add or remove TAG for each entry in the region.
9825 This works in the agenda, and also in an org-mode buffer."
9826 (interactive
9827 (list (region-beginning) (region-end)
9828 (let ((org-last-tags-completion-table
9829 (if (org-mode-p)
9830 (org-get-buffer-tags)
9831 (org-global-tags-completion-table))))
9832 (org-ido-completing-read
9833 "Tag: " 'org-tags-completion-function nil nil nil
9834 'org-tags-history))
9835 (progn
9836 (message "[s]et or [r]emove? ")
9837 (equal (read-char-exclusive) ?r))))
9838 (if (fboundp 'deactivate-mark) (deactivate-mark))
9839 (let ((agendap (equal major-mode 'org-agenda-mode))
9840 l1 l2 m buf pos newhead (cnt 0))
9841 (goto-char end)
9842 (setq l2 (1- (org-current-line)))
9843 (goto-char beg)
9844 (setq l1 (org-current-line))
9845 (loop for l from l1 to l2 do
9846 (goto-line l)
9847 (setq m (get-text-property (point) 'org-hd-marker))
9848 (when (or (and (org-mode-p) (org-on-heading-p))
9849 (and agendap m))
9850 (setq buf (if agendap (marker-buffer m) (current-buffer))
9851 pos (if agendap m (point)))
9852 (with-current-buffer buf
9853 (save-excursion
9854 (save-restriction
9855 (goto-char pos)
9856 (setq cnt (1+ cnt))
9857 (org-toggle-tag tag (if off 'off 'on))
9858 (setq newhead (org-get-heading)))))
9859 (and agendap (org-agenda-change-all-lines newhead m))))
9860 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
9862 (defun org-tags-completion-function (string predicate &optional flag)
9863 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
9864 (confirm (lambda (x) (stringp (car x)))))
9865 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
9866 (setq s1 (match-string 1 string)
9867 s2 (match-string 2 string))
9868 (setq s1 "" s2 string))
9869 (cond
9870 ((eq flag nil)
9871 ;; try completion
9872 (setq rtn (try-completion s2 ctable confirm))
9873 (if (stringp rtn)
9874 (setq rtn
9875 (concat s1 s2 (substring rtn (length s2))
9876 (if (and org-add-colon-after-tag-completion
9877 (assoc rtn ctable))
9878 ":" ""))))
9879 rtn)
9880 ((eq flag t)
9881 ;; all-completions
9882 (all-completions s2 ctable confirm)
9884 ((eq flag 'lambda)
9885 ;; exact match?
9886 (assoc s2 ctable)))
9889 (defun org-fast-tag-insert (kwd tags face &optional end)
9890 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
9891 (insert (format "%-12s" (concat kwd ":"))
9892 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
9893 (or end "")))
9895 (defun org-fast-tag-show-exit (flag)
9896 (save-excursion
9897 (goto-line 3)
9898 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
9899 (replace-match ""))
9900 (when flag
9901 (end-of-line 1)
9902 (org-move-to-column (- (window-width) 19) t)
9903 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
9905 (defun org-set-current-tags-overlay (current prefix)
9906 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
9907 (if (featurep 'xemacs)
9908 (org-overlay-display org-tags-overlay (concat prefix s)
9909 'secondary-selection)
9910 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
9911 (org-overlay-display org-tags-overlay (concat prefix s)))))
9913 (defun org-fast-tag-selection (current inherited table &optional todo-table)
9914 "Fast tag selection with single keys.
9915 CURRENT is the current list of tags in the headline, INHERITED is the
9916 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
9917 possibly with grouping information. TODO-TABLE is a similar table with
9918 TODO keywords, should these have keys assigned to them.
9919 If the keys are nil, a-z are automatically assigned.
9920 Returns the new tags string, or nil to not change the current settings."
9921 (let* ((fulltable (append table todo-table))
9922 (maxlen (apply 'max (mapcar
9923 (lambda (x)
9924 (if (stringp (car x)) (string-width (car x)) 0))
9925 fulltable)))
9926 (buf (current-buffer))
9927 (expert (eq org-fast-tag-selection-single-key 'expert))
9928 (buffer-tags nil)
9929 (fwidth (+ maxlen 3 1 3))
9930 (ncol (/ (- (window-width) 4) fwidth))
9931 (i-face 'org-done)
9932 (c-face 'org-todo)
9933 tg cnt e c char c1 c2 ntable tbl rtn
9934 ov-start ov-end ov-prefix
9935 (exit-after-next org-fast-tag-selection-single-key)
9936 (done-keywords org-done-keywords)
9937 groups ingroup)
9938 (save-excursion
9939 (beginning-of-line 1)
9940 (if (looking-at
9941 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9942 (setq ov-start (match-beginning 1)
9943 ov-end (match-end 1)
9944 ov-prefix "")
9945 (setq ov-start (1- (point-at-eol))
9946 ov-end (1+ ov-start))
9947 (skip-chars-forward "^\n\r")
9948 (setq ov-prefix
9949 (concat
9950 (buffer-substring (1- (point)) (point))
9951 (if (> (current-column) org-tags-column)
9953 (make-string (- org-tags-column (current-column)) ?\ ))))))
9954 (org-move-overlay org-tags-overlay ov-start ov-end)
9955 (save-window-excursion
9956 (if expert
9957 (set-buffer (get-buffer-create " *Org tags*"))
9958 (delete-other-windows)
9959 (split-window-vertically)
9960 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
9961 (erase-buffer)
9962 (org-set-local 'org-done-keywords done-keywords)
9963 (org-fast-tag-insert "Inherited" inherited i-face "\n")
9964 (org-fast-tag-insert "Current" current c-face "\n\n")
9965 (org-fast-tag-show-exit exit-after-next)
9966 (org-set-current-tags-overlay current ov-prefix)
9967 (setq tbl fulltable char ?a cnt 0)
9968 (while (setq e (pop tbl))
9969 (cond
9970 ((equal e '(:startgroup))
9971 (push '() groups) (setq ingroup t)
9972 (when (not (= cnt 0))
9973 (setq cnt 0)
9974 (insert "\n"))
9975 (insert "{ "))
9976 ((equal e '(:endgroup))
9977 (setq ingroup nil cnt 0)
9978 (insert "}\n"))
9980 (setq tg (car e) c2 nil)
9981 (if (cdr e)
9982 (setq c (cdr e))
9983 ;; automatically assign a character.
9984 (setq c1 (string-to-char
9985 (downcase (substring
9986 tg (if (= (string-to-char tg) ?@) 1 0)))))
9987 (if (or (rassoc c1 ntable) (rassoc c1 table))
9988 (while (or (rassoc char ntable) (rassoc char table))
9989 (setq char (1+ char)))
9990 (setq c2 c1))
9991 (setq c (or c2 char)))
9992 (if ingroup (push tg (car groups)))
9993 (setq tg (org-add-props tg nil 'face
9994 (cond
9995 ((not (assoc tg table))
9996 (org-get-todo-face tg))
9997 ((member tg current) c-face)
9998 ((member tg inherited) i-face)
9999 (t nil))))
10000 (if (and (= cnt 0) (not ingroup)) (insert " "))
10001 (insert "[" c "] " tg (make-string
10002 (- fwidth 4 (length tg)) ?\ ))
10003 (push (cons tg c) ntable)
10004 (when (= (setq cnt (1+ cnt)) ncol)
10005 (insert "\n")
10006 (if ingroup (insert " "))
10007 (setq cnt 0)))))
10008 (setq ntable (nreverse ntable))
10009 (insert "\n")
10010 (goto-char (point-min))
10011 (if (not expert) (org-fit-window-to-buffer))
10012 (setq rtn
10013 (catch 'exit
10014 (while t
10015 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
10016 (if groups " [!] no groups" " [!]groups")
10017 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
10018 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
10019 (cond
10020 ((= c ?\r) (throw 'exit t))
10021 ((= c ?!)
10022 (setq groups (not groups))
10023 (goto-char (point-min))
10024 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
10025 ((= c ?\C-c)
10026 (if (not expert)
10027 (org-fast-tag-show-exit
10028 (setq exit-after-next (not exit-after-next)))
10029 (setq expert nil)
10030 (delete-other-windows)
10031 (split-window-vertically)
10032 (org-switch-to-buffer-other-window " *Org tags*")
10033 (org-fit-window-to-buffer)))
10034 ((or (= c ?\C-g)
10035 (and (= c ?q) (not (rassoc c ntable))))
10036 (org-detach-overlay org-tags-overlay)
10037 (setq quit-flag t))
10038 ((= c ?\ )
10039 (setq current nil)
10040 (if exit-after-next (setq exit-after-next 'now)))
10041 ((= c ?\t)
10042 (condition-case nil
10043 (setq tg (org-ido-completing-read
10044 "Tag: "
10045 (or buffer-tags
10046 (with-current-buffer buf
10047 (org-get-buffer-tags)))))
10048 (quit (setq tg "")))
10049 (when (string-match "\\S-" tg)
10050 (add-to-list 'buffer-tags (list tg))
10051 (if (member tg current)
10052 (setq current (delete tg current))
10053 (push tg current)))
10054 (if exit-after-next (setq exit-after-next 'now)))
10055 ((setq e (rassoc c todo-table) tg (car e))
10056 (with-current-buffer buf
10057 (save-excursion (org-todo tg)))
10058 (if exit-after-next (setq exit-after-next 'now)))
10059 ((setq e (rassoc c ntable) tg (car e))
10060 (if (member tg current)
10061 (setq current (delete tg current))
10062 (loop for g in groups do
10063 (if (member tg g)
10064 (mapc (lambda (x)
10065 (setq current (delete x current)))
10066 g)))
10067 (push tg current))
10068 (if exit-after-next (setq exit-after-next 'now))))
10070 ;; Create a sorted list
10071 (setq current
10072 (sort current
10073 (lambda (a b)
10074 (assoc b (cdr (memq (assoc a ntable) ntable))))))
10075 (if (eq exit-after-next 'now) (throw 'exit t))
10076 (goto-char (point-min))
10077 (beginning-of-line 2)
10078 (delete-region (point) (point-at-eol))
10079 (org-fast-tag-insert "Current" current c-face)
10080 (org-set-current-tags-overlay current ov-prefix)
10081 (while (re-search-forward
10082 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
10083 (setq tg (match-string 1))
10084 (add-text-properties
10085 (match-beginning 1) (match-end 1)
10086 (list 'face
10087 (cond
10088 ((member tg current) c-face)
10089 ((member tg inherited) i-face)
10090 (t (get-text-property (match-beginning 1) 'face))))))
10091 (goto-char (point-min)))))
10092 (org-detach-overlay org-tags-overlay)
10093 (if rtn
10094 (mapconcat 'identity current ":")
10095 nil))))
10097 (defun org-get-tags-string ()
10098 "Get the TAGS string in the current headline."
10099 (unless (org-on-heading-p t)
10100 (error "Not on a heading"))
10101 (save-excursion
10102 (beginning-of-line 1)
10103 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10104 (org-match-string-no-properties 1)
10105 "")))
10107 (defun org-get-tags ()
10108 "Get the list of tags specified in the current headline."
10109 (org-split-string (org-get-tags-string) ":"))
10111 (defun org-get-buffer-tags ()
10112 "Get a table of all tags used in the buffer, for completion."
10113 (let (tags)
10114 (save-excursion
10115 (goto-char (point-min))
10116 (while (re-search-forward
10117 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
10118 (when (equal (char-after (point-at-bol 0)) ?*)
10119 (mapc (lambda (x) (add-to-list 'tags x))
10120 (org-split-string (org-match-string-no-properties 1) ":")))))
10121 (mapcar 'list tags)))
10123 ;;;; The mapping API
10125 ;;;###autoload
10126 (defun org-map-entries (func &optional match scope &rest skip)
10127 "Call FUNC at each headline selected by MATCH in SCOPE.
10129 FUNC is a function or a lisp form. The function will be called without
10130 arguments, with the cursor positioned at the beginning of the headline.
10131 The return values of all calls to the function will be collected and
10132 returned as a list.
10134 MATCH is a tags/property/todo match as it is used in the agenda tags view.
10135 Only headlines that are matched by this query will be considered during
10136 the iteration. When MATCH is nil or t, all headlines will be
10137 visited by the iteration.
10139 SCOPE determines the scope of this command. It can be any of:
10141 nil The current buffer, respecting the restriction if any
10142 tree The subtree started with the entry at point
10143 file The current buffer, without restriction
10144 file-with-archives
10145 The current buffer, and any archives associated with it
10146 agenda All agenda files
10147 agenda-with-archives
10148 All agenda files with any archive files associated with them
10149 \(file1 file2 ...)
10150 If this is a list, all files in the list will be scanned
10152 The remaining args are treated as settings for the skipping facilities of
10153 the scanner. The following items can be given here:
10155 archive skip trees with the archive tag.
10156 comment skip trees with the COMMENT keyword
10157 function or Emacs Lisp form:
10158 will be used as value for `org-agenda-skip-function', so whenever
10159 the the function returns t, FUNC will not be called for that
10160 entry and search will continue from the point where the
10161 function leaves it."
10162 (let* ((org-agenda-archives-mode nil) ; just to make sure
10163 (org-agenda-skip-archived-trees (memq 'archive skip))
10164 (org-agenda-skip-comment-trees (memq 'comment skip))
10165 (org-agenda-skip-function
10166 (car (org-delete-all '(comment archive) skip)))
10167 (org-tags-match-list-sublevels t)
10168 matcher pos file res
10169 org-todo-keywords-for-agenda
10170 org-done-keywords-for-agenda
10171 org-todo-keyword-alist-for-agenda
10172 org-tag-alist-for-agenda)
10174 (cond
10175 ((eq match t) (setq matcher t))
10176 ((eq match nil) (setq matcher t))
10177 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
10179 (save-excursion
10180 (save-restriction
10181 (when (eq scope 'tree)
10182 (org-back-to-heading t)
10183 (org-narrow-to-subtree)
10184 (setq scope nil))
10186 (if (not scope)
10187 (progn
10188 (org-prepare-agenda-buffers
10189 (list (buffer-file-name (current-buffer))))
10190 (setq res (org-scan-tags func matcher)))
10191 ;; Get the right scope
10192 (setq pos (point))
10193 (cond
10194 ((and scope (listp scope) (symbolp (car scope)))
10195 (setq scope (eval scope)))
10196 ((eq scope 'agenda)
10197 (setq scope (org-agenda-files t)))
10198 ((eq scope 'agenda-with-archives)
10199 (setq scope (org-agenda-files t))
10200 (setq scope (org-add-archive-files scope)))
10201 ((eq scope 'file)
10202 (setq scope (list (buffer-file-name))))
10203 ((eq scope 'file-with-archives)
10204 (setq scope (org-add-archive-files (list (buffer-file-name))))))
10205 (org-prepare-agenda-buffers scope)
10206 (while (setq file (pop scope))
10207 (with-current-buffer (org-find-base-buffer-visiting file)
10208 (save-excursion
10209 (save-restriction
10210 (widen)
10211 (goto-char (point-min))
10212 (setq res (append res (org-scan-tags func matcher))))))))))
10213 res))
10215 ;;;; Properties
10217 ;;; Setting and retrieving properties
10219 (defconst org-special-properties
10220 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
10221 "TIMESTAMP" "TIMESTAMP_IA")
10222 "The special properties valid in Org-mode.
10224 These are properties that are not defined in the property drawer,
10225 but in some other way.")
10227 (defconst org-default-properties
10228 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
10229 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
10230 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
10231 "EXPORT_FILE_NAME" "EXPORT_TITLE")
10232 "Some properties that are used by Org-mode for various purposes.
10233 Being in this list makes sure that they are offered for completion.")
10235 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
10236 "Regular expression matching the first line of a property drawer.")
10238 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
10239 "Regular expression matching the first line of a property drawer.")
10241 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
10242 "Regular expression matching the first line of a property drawer.")
10244 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
10245 "Regular expression matching the first line of a property drawer.")
10247 (defconst org-property-drawer-re
10248 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
10249 org-property-end-re "\\)\n?")
10250 "Matches an entire property drawer.")
10252 (defconst org-clock-drawer-re
10253 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
10254 org-property-end-re "\\)\n?")
10255 "Matches an entire clock drawer.")
10257 (defun org-property-action ()
10258 "Do an action on properties."
10259 (interactive)
10260 (let (c)
10261 (org-at-property-p)
10262 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
10263 (setq c (read-char-exclusive))
10264 (cond
10265 ((equal c ?s)
10266 (call-interactively 'org-set-property))
10267 ((equal c ?d)
10268 (call-interactively 'org-delete-property))
10269 ((equal c ?D)
10270 (call-interactively 'org-delete-property-globally))
10271 ((equal c ?c)
10272 (call-interactively 'org-compute-property-at-point))
10273 (t (error "No such property action %c" c)))))
10275 (defun org-at-property-p ()
10276 "Is the cursor in a property line?"
10277 ;; FIXME: Does not check if we are actually in the drawer.
10278 ;; FIXME: also returns true on any drawers.....
10279 ;; This is used by C-c C-c for property action.
10280 (save-excursion
10281 (beginning-of-line 1)
10282 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
10284 (defun org-get-property-block (&optional beg end force)
10285 "Return the (beg . end) range of the body of the property drawer.
10286 BEG and END can be beginning and end of subtree, if not given
10287 they will be found.
10288 If the drawer does not exist and FORCE is non-nil, create the drawer."
10289 (catch 'exit
10290 (save-excursion
10291 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
10292 (end (or end (progn (outline-next-heading) (point)))))
10293 (goto-char beg)
10294 (if (re-search-forward org-property-start-re end t)
10295 (setq beg (1+ (match-end 0)))
10296 (if force
10297 (save-excursion
10298 (org-insert-property-drawer)
10299 (setq end (progn (outline-next-heading) (point))))
10300 (throw 'exit nil))
10301 (goto-char beg)
10302 (if (re-search-forward org-property-start-re end t)
10303 (setq beg (1+ (match-end 0)))))
10304 (if (re-search-forward org-property-end-re end t)
10305 (setq end (match-beginning 0))
10306 (or force (throw 'exit nil))
10307 (goto-char beg)
10308 (setq end beg)
10309 (org-indent-line-function)
10310 (insert ":END:\n"))
10311 (cons beg end)))))
10313 (defun org-entry-properties (&optional pom which)
10314 "Get all properties of the entry at point-or-marker POM.
10315 This includes the TODO keyword, the tags, time strings for deadline,
10316 scheduled, and clocking, and any additional properties defined in the
10317 entry. The return value is an alist, keys may occur multiple times
10318 if the property key was used several times.
10319 POM may also be nil, in which case the current entry is used.
10320 If WHICH is nil or `all', get all properties. If WHICH is
10321 `special' or `standard', only get that subclass."
10322 (setq which (or which 'all))
10323 (org-with-point-at pom
10324 (let ((clockstr (substring org-clock-string 0 -1))
10325 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
10326 beg end range props sum-props key value string clocksum)
10327 (save-excursion
10328 (when (condition-case nil
10329 (and (org-mode-p) (org-back-to-heading t))
10330 (error nil))
10331 (setq beg (point))
10332 (setq sum-props (get-text-property (point) 'org-summaries))
10333 (setq clocksum (get-text-property (point) :org-clock-minutes))
10334 (outline-next-heading)
10335 (setq end (point))
10336 (when (memq which '(all special))
10337 ;; Get the special properties, like TODO and tags
10338 (goto-char beg)
10339 (when (and (looking-at org-todo-line-regexp) (match-end 2))
10340 (push (cons "TODO" (org-match-string-no-properties 2)) props))
10341 (when (looking-at org-priority-regexp)
10342 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
10343 (when (and (setq value (org-get-tags-string))
10344 (string-match "\\S-" value))
10345 (push (cons "TAGS" value) props))
10346 (when (setq value (org-get-tags-at))
10347 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
10348 props))
10349 (while (re-search-forward org-maybe-keyword-time-regexp end t)
10350 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
10351 string (if (equal key clockstr)
10352 (org-no-properties
10353 (org-trim
10354 (buffer-substring
10355 (match-beginning 3) (goto-char (point-at-eol)))))
10356 (substring (org-match-string-no-properties 3) 1 -1)))
10357 (unless key
10358 (if (= (char-after (match-beginning 3)) ?\[)
10359 (setq key "TIMESTAMP_IA")
10360 (setq key "TIMESTAMP")))
10361 (when (or (equal key clockstr) (not (assoc key props)))
10362 (push (cons key string) props)))
10366 (when (memq which '(all standard))
10367 ;; Get the standard properties, like :PORP: ...
10368 (setq range (org-get-property-block beg end))
10369 (when range
10370 (goto-char (car range))
10371 (while (re-search-forward
10372 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
10373 (cdr range) t)
10374 (setq key (org-match-string-no-properties 1)
10375 value (org-trim (or (org-match-string-no-properties 2) "")))
10376 (unless (member key excluded)
10377 (push (cons key (or value "")) props)))))
10378 (if clocksum
10379 (push (cons "CLOCKSUM"
10380 (org-columns-number-to-string (/ (float clocksum) 60.)
10381 'add_times))
10382 props))
10383 (unless (assoc "CATEGORY" props)
10384 (setq value (or (org-get-category)
10385 (progn (org-refresh-category-properties)
10386 (org-get-category))))
10387 (push (cons "CATEGORY" value) props))
10388 (append sum-props (nreverse props)))))))
10390 (defun org-entry-get (pom property &optional inherit)
10391 "Get value of PROPERTY for entry at point-or-marker POM.
10392 If INHERIT is non-nil and the entry does not have the property,
10393 then also check higher levels of the hierarchy.
10394 If INHERIT is the symbol `selective', use inheritance only if the setting
10395 in `org-use-property-inheritance' selects PROPERTY for inheritance.
10396 If the property is present but empty, the return value is the empty string.
10397 If the property is not present at all, nil is returned."
10398 (org-with-point-at pom
10399 (if (and inherit (if (eq inherit 'selective)
10400 (org-property-inherit-p property)
10402 (org-entry-get-with-inheritance property)
10403 (if (member property org-special-properties)
10404 ;; We need a special property. Use brute force, get all properties.
10405 (cdr (assoc property (org-entry-properties nil 'special)))
10406 (let ((range (org-get-property-block)))
10407 (if (and range
10408 (goto-char (car range))
10409 (re-search-forward
10410 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
10411 (cdr range) t))
10412 ;; Found the property, return it.
10413 (if (match-end 1)
10414 (org-match-string-no-properties 1)
10415 "")))))))
10417 (defun org-property-or-variable-value (var &optional inherit)
10418 "Check if there is a property fixing the value of VAR.
10419 If yes, return this value. If not, return the current value of the variable."
10420 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
10421 (if (and prop (stringp prop) (string-match "\\S-" prop))
10422 (read prop)
10423 (symbol-value var))))
10425 (defun org-entry-delete (pom property)
10426 "Delete the property PROPERTY from entry at point-or-marker POM."
10427 (org-with-point-at pom
10428 (if (member property org-special-properties)
10429 nil ; cannot delete these properties.
10430 (let ((range (org-get-property-block)))
10431 (if (and range
10432 (goto-char (car range))
10433 (re-search-forward
10434 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
10435 (cdr range) t))
10436 (progn
10437 (delete-region (match-beginning 0) (1+ (point-at-eol)))
10439 nil)))))
10441 ;; Multi-values properties are properties that contain multiple values
10442 ;; These values are assumed to be single words, separated by whitespace.
10443 (defun org-entry-add-to-multivalued-property (pom property value)
10444 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
10445 (let* ((old (org-entry-get pom property))
10446 (values (and old (org-split-string old "[ \t]"))))
10447 (setq value (org-entry-protect-space value))
10448 (unless (member value values)
10449 (setq values (cons value values))
10450 (org-entry-put pom property
10451 (mapconcat 'identity values " ")))))
10453 (defun org-entry-remove-from-multivalued-property (pom property value)
10454 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
10455 (let* ((old (org-entry-get pom property))
10456 (values (and old (org-split-string old "[ \t]"))))
10457 (setq value (org-entry-protect-space value))
10458 (when (member value values)
10459 (setq values (delete value values))
10460 (org-entry-put pom property
10461 (mapconcat 'identity values " ")))))
10463 (defun org-entry-member-in-multivalued-property (pom property value)
10464 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
10465 (let* ((old (org-entry-get pom property))
10466 (values (and old (org-split-string old "[ \t]"))))
10467 (setq value (org-entry-protect-space value))
10468 (member value values)))
10470 (defun org-entry-get-multivalued-property (pom property)
10471 "Return a list of values in a multivalued property."
10472 (let* ((value (org-entry-get pom property))
10473 (values (and value (org-split-string value "[ \t]"))))
10474 (mapcar 'org-entry-restore-space values)))
10476 (defun org-entry-put-multivalued-property (pom property &rest values)
10477 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
10478 VALUES should be a list of strings. Spaces will be protected."
10479 (org-entry-put pom property
10480 (mapconcat 'org-entry-protect-space values " "))
10481 (let* ((value (org-entry-get pom property))
10482 (values (and value (org-split-string value "[ \t]"))))
10483 (mapcar 'org-entry-restore-space values)))
10485 (defun org-entry-protect-space (s)
10486 "Protect spaces and newline in string S."
10487 (while (string-match " " s)
10488 (setq s (replace-match "%20" t t s)))
10489 (while (string-match "\n" s)
10490 (setq s (replace-match "%0A" t t s)))
10493 (defun org-entry-restore-space (s)
10494 "Restore spaces and newline in string S."
10495 (while (string-match "%20" s)
10496 (setq s (replace-match " " t t s)))
10497 (while (string-match "%0A" s)
10498 (setq s (replace-match "\n" t t s)))
10501 (defvar org-entry-property-inherited-from (make-marker)
10502 "Marker pointing to the entry from where a property was inherited.
10503 Each call to `org-entry-get-with-inheritance' will set this marker to the
10504 location of the entry where the inheritance search matched. If there was
10505 no match, the marker will point nowhere.
10506 Note that also `org-entry-get' calls this function, if the INHERIT flag
10507 is set.")
10509 (defun org-entry-get-with-inheritance (property)
10510 "Get entry property, and search higher levels if not present."
10511 (move-marker org-entry-property-inherited-from nil)
10512 (let (tmp)
10513 (save-excursion
10514 (save-restriction
10515 (widen)
10516 (catch 'ex
10517 (while t
10518 (when (setq tmp (org-entry-get nil property))
10519 (org-back-to-heading t)
10520 (move-marker org-entry-property-inherited-from (point))
10521 (throw 'ex tmp))
10522 (or (org-up-heading-safe) (throw 'ex nil)))))
10523 (or tmp
10524 (cdr (assoc property org-file-properties))
10525 (cdr (assoc property org-global-properties))
10526 (cdr (assoc property org-global-properties-fixed))))))
10528 (defun org-entry-put (pom property value)
10529 "Set PROPERTY to VALUE for entry at point-or-marker POM."
10530 (org-with-point-at pom
10531 (org-back-to-heading t)
10532 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
10533 range)
10534 (cond
10535 ((equal property "TODO")
10536 (when (and (stringp value) (string-match "\\S-" value)
10537 (not (member value org-todo-keywords-1)))
10538 (error "\"%s\" is not a valid TODO state" value))
10539 (if (or (not value)
10540 (not (string-match "\\S-" value)))
10541 (setq value 'none))
10542 (org-todo value)
10543 (org-set-tags nil 'align))
10544 ((equal property "PRIORITY")
10545 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
10546 (string-to-char value) ?\ ))
10547 (org-set-tags nil 'align))
10548 ((equal property "SCHEDULED")
10549 (if (re-search-forward org-scheduled-time-regexp end t)
10550 (cond
10551 ((eq value 'earlier) (org-timestamp-change -1 'day))
10552 ((eq value 'later) (org-timestamp-change 1 'day))
10553 (t (call-interactively 'org-schedule)))
10554 (call-interactively 'org-schedule)))
10555 ((equal property "DEADLINE")
10556 (if (re-search-forward org-deadline-time-regexp end t)
10557 (cond
10558 ((eq value 'earlier) (org-timestamp-change -1 'day))
10559 ((eq value 'later) (org-timestamp-change 1 'day))
10560 (t (call-interactively 'org-deadline)))
10561 (call-interactively 'org-deadline)))
10562 ((member property org-special-properties)
10563 (error "The %s property can not yet be set with `org-entry-put'"
10564 property))
10565 (t ; a non-special property
10566 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
10567 (setq range (org-get-property-block beg end 'force))
10568 (goto-char (car range))
10569 (if (re-search-forward
10570 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
10571 (progn
10572 (delete-region (match-beginning 1) (match-end 1))
10573 (goto-char (match-beginning 1)))
10574 (goto-char (cdr range))
10575 (insert "\n")
10576 (backward-char 1)
10577 (org-indent-line-function)
10578 (insert ":" property ":"))
10579 (and value (insert " " value))
10580 (org-indent-line-function)))))))
10582 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
10583 "Get all property keys in the current buffer.
10584 With INCLUDE-SPECIALS, also list the special properties that reflect things
10585 like tags and TODO state.
10586 With INCLUDE-DEFAULTS, also include properties that has special meaning
10587 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
10588 With INCLUDE-COLUMNS, also include property names given in COLUMN
10589 formats in the current buffer."
10590 (let (rtn range cfmt cols s p)
10591 (save-excursion
10592 (save-restriction
10593 (widen)
10594 (goto-char (point-min))
10595 (while (re-search-forward org-property-start-re nil t)
10596 (setq range (org-get-property-block))
10597 (goto-char (car range))
10598 (while (re-search-forward
10599 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
10600 (cdr range) t)
10601 (add-to-list 'rtn (org-match-string-no-properties 1)))
10602 (outline-next-heading))))
10604 (when include-specials
10605 (setq rtn (append org-special-properties rtn)))
10607 (when include-defaults
10608 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
10610 (when include-columns
10611 (save-excursion
10612 (save-restriction
10613 (widen)
10614 (goto-char (point-min))
10615 (while (re-search-forward
10616 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
10617 nil t)
10618 (setq cfmt (match-string 2) s 0)
10619 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
10620 cfmt s)
10621 (setq s (match-end 0)
10622 p (match-string 1 cfmt))
10623 (unless (or (equal p "ITEM")
10624 (member p org-special-properties))
10625 (add-to-list 'rtn (match-string 1 cfmt))))))))
10627 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
10629 (defun org-property-values (key)
10630 "Return a list of all values of property KEY."
10631 (save-excursion
10632 (save-restriction
10633 (widen)
10634 (goto-char (point-min))
10635 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
10636 values)
10637 (while (re-search-forward re nil t)
10638 (add-to-list 'values (org-trim (match-string 1))))
10639 (delete "" values)))))
10641 (defun org-insert-property-drawer ()
10642 "Insert a property drawer into the current entry."
10643 (interactive)
10644 (org-back-to-heading t)
10645 (looking-at outline-regexp)
10646 (let ((indent (- (match-end 0)(match-beginning 0)))
10647 (beg (point))
10648 (re (concat "^[ \t]*" org-keyword-time-regexp))
10649 end hiddenp)
10650 (outline-next-heading)
10651 (setq end (point))
10652 (goto-char beg)
10653 (while (re-search-forward re end t))
10654 (setq hiddenp (org-invisible-p))
10655 (end-of-line 1)
10656 (and (equal (char-after) ?\n) (forward-char 1))
10657 (while (looking-at "^[ \t]*\\(:CLOCK:\\|CLOCK\\|:END:\\)")
10658 (beginning-of-line 2))
10659 (org-skip-over-state-notes)
10660 (skip-chars-backward " \t\n\r")
10661 (if (eq (char-before) ?*) (forward-char 1))
10662 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
10663 (beginning-of-line 0)
10664 (org-indent-to-column indent)
10665 (beginning-of-line 2)
10666 (org-indent-to-column indent)
10667 (beginning-of-line 0)
10668 (if hiddenp
10669 (save-excursion
10670 (org-back-to-heading t)
10671 (hide-entry))
10672 (org-flag-drawer t))))
10674 (defun org-set-property (property value)
10675 "In the current entry, set PROPERTY to VALUE.
10676 When called interactively, this will prompt for a property name, offering
10677 completion on existing and default properties. And then it will prompt
10678 for a value, offering completion either on allowed values (via an inherited
10679 xxx_ALL property) or on existing values in other instances of this property
10680 in the current file."
10681 (interactive
10682 (let* ((completion-ignore-case t)
10683 (keys (org-buffer-property-keys nil t t))
10684 (prop0 (org-ido-completing-read "Property: " (mapcar 'list keys)))
10685 (prop (if (member prop0 keys)
10686 prop0
10687 (or (cdr (assoc (downcase prop0)
10688 (mapcar (lambda (x) (cons (downcase x) x))
10689 keys)))
10690 prop0)))
10691 (cur (org-entry-get nil prop))
10692 (allowed (org-property-get-allowed-values nil prop 'table))
10693 (existing (mapcar 'list (org-property-values prop)))
10694 (val (if allowed
10695 (org-completing-read "Value: " allowed nil 'req-match)
10696 (org-completing-read
10697 (concat "Value" (if (and cur (string-match "\\S-" cur))
10698 (concat "[" cur "]") "")
10699 ": ")
10700 existing nil nil "" nil cur))))
10701 (list prop (if (equal val "") cur val))))
10702 (unless (equal (org-entry-get nil property) value)
10703 (org-entry-put nil property value)))
10705 (defun org-delete-property (property)
10706 "In the current entry, delete PROPERTY."
10707 (interactive
10708 (let* ((completion-ignore-case t)
10709 (prop (org-ido-completing-read
10710 "Property: " (org-entry-properties nil 'standard))))
10711 (list prop)))
10712 (message "Property %s %s" property
10713 (if (org-entry-delete nil property)
10714 "deleted"
10715 "was not present in the entry")))
10717 (defun org-delete-property-globally (property)
10718 "Remove PROPERTY globally, from all entries."
10719 (interactive
10720 (let* ((completion-ignore-case t)
10721 (prop (org-ido-completing-read
10722 "Globally remove property: "
10723 (mapcar 'list (org-buffer-property-keys)))))
10724 (list prop)))
10725 (save-excursion
10726 (save-restriction
10727 (widen)
10728 (goto-char (point-min))
10729 (let ((cnt 0))
10730 (while (re-search-forward
10731 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
10732 nil t)
10733 (setq cnt (1+ cnt))
10734 (replace-match ""))
10735 (message "Property \"%s\" removed from %d entries" property cnt)))))
10737 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
10739 (defun org-compute-property-at-point ()
10740 "Compute the property at point.
10741 This looks for an enclosing column format, extracts the operator and
10742 then applies it to the property in the column format's scope."
10743 (interactive)
10744 (unless (org-at-property-p)
10745 (error "Not at a property"))
10746 (let ((prop (org-match-string-no-properties 2)))
10747 (org-columns-get-format-and-top-level)
10748 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
10749 (error "No operator defined for property %s" prop))
10750 (org-columns-compute prop)))
10752 (defun org-property-get-allowed-values (pom property &optional table)
10753 "Get allowed values for the property PROPERTY.
10754 When TABLE is non-nil, return an alist that can directly be used for
10755 completion."
10756 (let (vals)
10757 (cond
10758 ((equal property "TODO")
10759 (setq vals (org-with-point-at pom
10760 (append org-todo-keywords-1 '("")))))
10761 ((equal property "PRIORITY")
10762 (let ((n org-lowest-priority))
10763 (while (>= n org-highest-priority)
10764 (push (char-to-string n) vals)
10765 (setq n (1- n)))))
10766 ((member property org-special-properties))
10768 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
10770 (when (and vals (string-match "\\S-" vals))
10771 (setq vals (car (read-from-string (concat "(" vals ")"))))
10772 (setq vals (mapcar (lambda (x)
10773 (cond ((stringp x) x)
10774 ((numberp x) (number-to-string x))
10775 ((symbolp x) (symbol-name x))
10776 (t "???")))
10777 vals)))))
10778 (if table (mapcar 'list vals) vals)))
10780 (defun org-property-previous-allowed-value (&optional previous)
10781 "Switch to the next allowed value for this property."
10782 (interactive)
10783 (org-property-next-allowed-value t))
10785 (defun org-property-next-allowed-value (&optional previous)
10786 "Switch to the next allowed value for this property."
10787 (interactive)
10788 (unless (org-at-property-p)
10789 (error "Not at a property"))
10790 (let* ((key (match-string 2))
10791 (value (match-string 3))
10792 (allowed (or (org-property-get-allowed-values (point) key)
10793 (and (member value '("[ ]" "[-]" "[X]"))
10794 '("[ ]" "[X]"))))
10795 nval)
10796 (unless allowed
10797 (error "Allowed values for this property have not been defined"))
10798 (if previous (setq allowed (reverse allowed)))
10799 (if (member value allowed)
10800 (setq nval (car (cdr (member value allowed)))))
10801 (setq nval (or nval (car allowed)))
10802 (if (equal nval value)
10803 (error "Only one allowed value for this property"))
10804 (org-at-property-p)
10805 (replace-match (concat " :" key ": " nval) t t)
10806 (org-indent-line-function)
10807 (beginning-of-line 1)
10808 (skip-chars-forward " \t")))
10810 (defun org-find-entry-with-id (ident)
10811 "Locate the entry that contains the ID property with exact value IDENT.
10812 IDENT can be a string, a symbol or a number, this function will search for
10813 the string representation of it.
10814 Return the position where this entry starts, or nil if there is no such entry."
10815 (interactive "sID: ")
10816 (let ((id (cond
10817 ((stringp ident) ident)
10818 ((symbol-name ident) (symbol-name ident))
10819 ((numberp ident) (number-to-string ident))
10820 (t (error "IDENT %s must be a string, symbol or number" ident))))
10821 (case-fold-search nil))
10822 (save-excursion
10823 (save-restriction
10824 (widen)
10825 (goto-char (point-min))
10826 (when (re-search-forward
10827 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
10828 nil t)
10829 (org-back-to-heading)
10830 (point))))))
10832 ;;;; Timestamps
10834 (defvar org-last-changed-timestamp nil)
10835 (defvar org-last-inserted-timestamp nil
10836 "The last time stamp inserted with `org-insert-time-stamp'.")
10837 (defvar org-time-was-given) ; dynamically scoped parameter
10838 (defvar org-end-time-was-given) ; dynamically scoped parameter
10839 (defvar org-ts-what) ; dynamically scoped parameter
10841 (defun org-time-stamp (arg &optional inactive)
10842 "Prompt for a date/time and insert a time stamp.
10843 If the user specifies a time like HH:MM, or if this command is called
10844 with a prefix argument, the time stamp will contain date and time.
10845 Otherwise, only the date will be included. All parts of a date not
10846 specified by the user will be filled in from the current date/time.
10847 So if you press just return without typing anything, the time stamp
10848 will represent the current date/time. If there is already a timestamp
10849 at the cursor, it will be modified."
10850 (interactive "P")
10851 (let* ((ts nil)
10852 (default-time
10853 ;; Default time is either today, or, when entering a range,
10854 ;; the range start.
10855 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
10856 (save-excursion
10857 (re-search-backward
10858 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
10859 (- (point) 20) t)))
10860 (apply 'encode-time (org-parse-time-string (match-string 1)))
10861 (current-time)))
10862 (default-input (and ts (org-get-compact-tod ts)))
10863 org-time-was-given org-end-time-was-given time)
10864 (cond
10865 ((and (org-at-timestamp-p t)
10866 (memq last-command '(org-time-stamp org-time-stamp-inactive))
10867 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
10868 (insert "--")
10869 (setq time (let ((this-command this-command))
10870 (org-read-date arg 'totime nil nil
10871 default-time default-input)))
10872 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
10873 ((org-at-timestamp-p t)
10874 (setq time (let ((this-command this-command))
10875 (org-read-date arg 'totime nil nil default-time default-input)))
10876 (when (org-at-timestamp-p t) ; just to get the match data
10877 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
10878 (replace-match "")
10879 (setq org-last-changed-timestamp
10880 (org-insert-time-stamp
10881 time (or org-time-was-given arg)
10882 inactive nil nil (list org-end-time-was-given))))
10883 (message "Timestamp updated"))
10885 (setq time (let ((this-command this-command))
10886 (org-read-date arg 'totime nil nil default-time default-input)))
10887 (org-insert-time-stamp time (or org-time-was-given arg) inactive
10888 nil nil (list org-end-time-was-given))))))
10890 ;; FIXME: can we use this for something else, like computing time differences?
10891 (defun org-get-compact-tod (s)
10892 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
10893 (let* ((t1 (match-string 1 s))
10894 (h1 (string-to-number (match-string 2 s)))
10895 (m1 (string-to-number (match-string 3 s)))
10896 (t2 (and (match-end 4) (match-string 5 s)))
10897 (h2 (and t2 (string-to-number (match-string 6 s))))
10898 (m2 (and t2 (string-to-number (match-string 7 s))))
10899 dh dm)
10900 (if (not t2)
10902 (setq dh (- h2 h1) dm (- m2 m1))
10903 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
10904 (concat t1 "+" (number-to-string dh)
10905 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
10907 (defun org-time-stamp-inactive (&optional arg)
10908 "Insert an inactive time stamp.
10909 An inactive time stamp is enclosed in square brackets instead of angle
10910 brackets. It is inactive in the sense that it does not trigger agenda entries,
10911 does not link to the calendar and cannot be changed with the S-cursor keys.
10912 So these are more for recording a certain time/date."
10913 (interactive "P")
10914 (org-time-stamp arg 'inactive))
10916 (defvar org-date-ovl (org-make-overlay 1 1))
10917 (org-overlay-put org-date-ovl 'face 'org-warning)
10918 (org-detach-overlay org-date-ovl)
10920 (defvar org-ans1) ; dynamically scoped parameter
10921 (defvar org-ans2) ; dynamically scoped parameter
10923 (defvar org-plain-time-of-day-regexp) ; defined below
10925 (defvar org-overriding-default-time nil) ; dynamically scoped
10926 (defvar org-read-date-overlay nil)
10927 (defvar org-dcst nil) ; dynamically scoped
10929 (defun org-read-date (&optional with-time to-time from-string prompt
10930 default-time default-input)
10931 "Read a date, possibly a time, and make things smooth for the user.
10932 The prompt will suggest to enter an ISO date, but you can also enter anything
10933 which will at least partially be understood by `parse-time-string'.
10934 Unrecognized parts of the date will default to the current day, month, year,
10935 hour and minute. If this command is called to replace a timestamp at point,
10936 of to enter the second timestamp of a range, the default time is taken from the
10937 existing stamp. For example,
10938 3-2-5 --> 2003-02-05
10939 feb 15 --> currentyear-02-15
10940 sep 12 9 --> 2009-09-12
10941 12:45 --> today 12:45
10942 22 sept 0:34 --> currentyear-09-22 0:34
10943 12 --> currentyear-currentmonth-12
10944 Fri --> nearest Friday (today or later)
10945 etc.
10947 Furthermore you can specify a relative date by giving, as the *first* thing
10948 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
10949 change in days weeks, months, years.
10950 With a single plus or minus, the date is relative to today. With a double
10951 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
10952 +4d --> four days from today
10953 +4 --> same as above
10954 +2w --> two weeks from today
10955 ++5 --> five days from default date
10957 The function understands only English month and weekday abbreviations,
10958 but this can be configured with the variables `parse-time-months' and
10959 `parse-time-weekdays'.
10961 While prompting, a calendar is popped up - you can also select the
10962 date with the mouse (button 1). The calendar shows a period of three
10963 months. To scroll it to other months, use the keys `>' and `<'.
10964 If you don't like the calendar, turn it off with
10965 \(setq org-read-date-popup-calendar nil)
10967 With optional argument TO-TIME, the date will immediately be converted
10968 to an internal time.
10969 With an optional argument WITH-TIME, the prompt will suggest to also
10970 insert a time. Note that when WITH-TIME is not set, you can still
10971 enter a time, and this function will inform the calling routine about
10972 this change. The calling routine may then choose to change the format
10973 used to insert the time stamp into the buffer to include the time.
10974 With optional argument FROM-STRING, read from this string instead from
10975 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
10976 the time/date that is used for everything that is not specified by the
10977 user."
10978 (require 'parse-time)
10979 (let* ((org-time-stamp-rounding-minutes
10980 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
10981 (org-dcst org-display-custom-times)
10982 (ct (org-current-time))
10983 (def (or org-overriding-default-time default-time ct))
10984 (defdecode (decode-time def))
10985 (dummy (progn
10986 (when (< (nth 2 defdecode) org-extend-today-until)
10987 (setcar (nthcdr 2 defdecode) -1)
10988 (setcar (nthcdr 1 defdecode) 59)
10989 (setq def (apply 'encode-time defdecode)
10990 defdecode (decode-time def)))))
10991 (calendar-move-hook nil)
10992 (calendar-view-diary-initially-flag nil)
10993 (view-diary-entries-initially nil)
10994 (calendar-view-holidays-initially-flag nil)
10995 (view-calendar-holidays-initially nil)
10996 (timestr (format-time-string
10997 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
10998 (prompt (concat (if prompt (concat prompt " ") "")
10999 (format "Date+time [%s]: " timestr)))
11000 ans (org-ans0 "") org-ans1 org-ans2 final)
11002 (cond
11003 (from-string (setq ans from-string))
11004 (org-read-date-popup-calendar
11005 (save-excursion
11006 (save-window-excursion
11007 (calendar)
11008 (calendar-forward-day (- (time-to-days def)
11009 (calendar-absolute-from-gregorian
11010 (calendar-current-date))))
11011 (org-eval-in-calendar nil t)
11012 (let* ((old-map (current-local-map))
11013 (map (copy-keymap calendar-mode-map))
11014 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
11015 (org-defkey map (kbd "RET") 'org-calendar-select)
11016 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
11017 'org-calendar-select-mouse)
11018 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
11019 'org-calendar-select-mouse)
11020 (org-defkey minibuffer-local-map [(meta shift left)]
11021 (lambda () (interactive)
11022 (org-eval-in-calendar '(calendar-backward-month 1))))
11023 (org-defkey minibuffer-local-map [(meta shift right)]
11024 (lambda () (interactive)
11025 (org-eval-in-calendar '(calendar-forward-month 1))))
11026 (org-defkey minibuffer-local-map [(meta shift up)]
11027 (lambda () (interactive)
11028 (org-eval-in-calendar '(calendar-backward-year 1))))
11029 (org-defkey minibuffer-local-map [(meta shift down)]
11030 (lambda () (interactive)
11031 (org-eval-in-calendar '(calendar-forward-year 1))))
11032 (org-defkey minibuffer-local-map [(shift up)]
11033 (lambda () (interactive)
11034 (org-eval-in-calendar '(calendar-backward-week 1))))
11035 (org-defkey minibuffer-local-map [(shift down)]
11036 (lambda () (interactive)
11037 (org-eval-in-calendar '(calendar-forward-week 1))))
11038 (org-defkey minibuffer-local-map [(shift left)]
11039 (lambda () (interactive)
11040 (org-eval-in-calendar '(calendar-backward-day 1))))
11041 (org-defkey minibuffer-local-map [(shift right)]
11042 (lambda () (interactive)
11043 (org-eval-in-calendar '(calendar-forward-day 1))))
11044 (org-defkey minibuffer-local-map ">"
11045 (lambda () (interactive)
11046 (org-eval-in-calendar '(scroll-calendar-left 1))))
11047 (org-defkey minibuffer-local-map "<"
11048 (lambda () (interactive)
11049 (org-eval-in-calendar '(scroll-calendar-right 1))))
11050 (unwind-protect
11051 (progn
11052 (use-local-map map)
11053 (add-hook 'post-command-hook 'org-read-date-display)
11054 (setq org-ans0 (read-string prompt default-input nil nil))
11055 ;; org-ans0: from prompt
11056 ;; org-ans1: from mouse click
11057 ;; org-ans2: from calendar motion
11058 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
11059 (remove-hook 'post-command-hook 'org-read-date-display)
11060 (use-local-map old-map)
11061 (when org-read-date-overlay
11062 (org-delete-overlay org-read-date-overlay)
11063 (setq org-read-date-overlay nil)))))))
11065 (t ; Naked prompt only
11066 (unwind-protect
11067 (setq ans (read-string prompt default-input nil timestr))
11068 (when org-read-date-overlay
11069 (org-delete-overlay org-read-date-overlay)
11070 (setq org-read-date-overlay nil)))))
11072 (setq final (org-read-date-analyze ans def defdecode))
11074 (if to-time
11075 (apply 'encode-time final)
11076 (if (and (boundp 'org-time-was-given) org-time-was-given)
11077 (format "%04d-%02d-%02d %02d:%02d"
11078 (nth 5 final) (nth 4 final) (nth 3 final)
11079 (nth 2 final) (nth 1 final))
11080 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
11081 (defvar def)
11082 (defvar defdecode)
11083 (defvar with-time)
11084 (defun org-read-date-display ()
11085 "Display the current date prompt interpretation in the minibuffer."
11086 (when org-read-date-display-live
11087 (when org-read-date-overlay
11088 (org-delete-overlay org-read-date-overlay))
11089 (let ((p (point)))
11090 (end-of-line 1)
11091 (while (not (equal (buffer-substring
11092 (max (point-min) (- (point) 4)) (point))
11093 " "))
11094 (insert " "))
11095 (goto-char p))
11096 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
11097 " " (or org-ans1 org-ans2)))
11098 (org-end-time-was-given nil)
11099 (f (org-read-date-analyze ans def defdecode))
11100 (fmts (if org-dcst
11101 org-time-stamp-custom-formats
11102 org-time-stamp-formats))
11103 (fmt (if (or with-time
11104 (and (boundp 'org-time-was-given) org-time-was-given))
11105 (cdr fmts)
11106 (car fmts)))
11107 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
11108 (when (and org-end-time-was-given
11109 (string-match org-plain-time-of-day-regexp txt))
11110 (setq txt (concat (substring txt 0 (match-end 0)) "-"
11111 org-end-time-was-given
11112 (substring txt (match-end 0)))))
11113 (setq org-read-date-overlay
11114 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
11115 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
11117 (defun org-read-date-analyze (ans def defdecode)
11118 "Analyse the combined answer of the date prompt."
11119 ;; FIXME: cleanup and comment
11120 (let (delta deltan deltaw deltadef year month day
11121 hour minute second wday pm h2 m2 tl wday1
11122 iso-year iso-weekday iso-week iso-year iso-date)
11124 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
11125 (setq ans "+0"))
11127 (when (setq delta (org-read-date-get-relative ans (current-time) def))
11128 (setq ans (replace-match "" t t ans)
11129 deltan (car delta)
11130 deltaw (nth 1 delta)
11131 deltadef (nth 2 delta)))
11133 ;; Check if there is an iso week date in there
11134 ;; If yes, sore the info and postpone interpreting it until the rest
11135 ;; of the parsing is done
11136 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
11137 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
11138 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
11139 iso-week (string-to-number (match-string 2 ans)))
11140 (setq ans (replace-match "" t t ans)))
11142 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
11143 (when (string-match
11144 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
11145 (setq year (if (match-end 2)
11146 (string-to-number (match-string 2 ans))
11147 (string-to-number (format-time-string "%Y")))
11148 month (string-to-number (match-string 3 ans))
11149 day (string-to-number (match-string 4 ans)))
11150 (if (< year 100) (setq year (+ 2000 year)))
11151 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
11152 t nil ans)))
11153 ;; Help matching am/pm times, because `parse-time-string' does not do that.
11154 ;; If there is a time with am/pm, and *no* time without it, we convert
11155 ;; so that matching will be successful.
11156 (loop for i from 1 to 2 do ; twice, for end time as well
11157 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
11158 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
11159 (setq hour (string-to-number (match-string 1 ans))
11160 minute (if (match-end 3)
11161 (string-to-number (match-string 3 ans))
11163 pm (equal ?p
11164 (string-to-char (downcase (match-string 4 ans)))))
11165 (if (and (= hour 12) (not pm))
11166 (setq hour 0)
11167 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
11168 (setq ans (replace-match (format "%02d:%02d" hour minute)
11169 t t ans))))
11171 ;; Check if a time range is given as a duration
11172 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
11173 (setq hour (string-to-number (match-string 1 ans))
11174 h2 (+ hour (string-to-number (match-string 3 ans)))
11175 minute (string-to-number (match-string 2 ans))
11176 m2 (+ minute (if (match-end 5) (string-to-number
11177 (match-string 5 ans))0)))
11178 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
11179 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
11180 t t ans)))
11182 ;; Check if there is a time range
11183 (when (boundp 'org-end-time-was-given)
11184 (setq org-time-was-given nil)
11185 (when (and (string-match org-plain-time-of-day-regexp ans)
11186 (match-end 8))
11187 (setq org-end-time-was-given (match-string 8 ans))
11188 (setq ans (concat (substring ans 0 (match-beginning 7))
11189 (substring ans (match-end 7))))))
11191 (setq tl (parse-time-string ans)
11192 day (or (nth 3 tl) (nth 3 defdecode))
11193 month (or (nth 4 tl)
11194 (if (and org-read-date-prefer-future
11195 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
11196 (1+ (nth 4 defdecode))
11197 (nth 4 defdecode)))
11198 year (or (nth 5 tl)
11199 (if (and org-read-date-prefer-future
11200 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
11201 (1+ (nth 5 defdecode))
11202 (nth 5 defdecode)))
11203 hour (or (nth 2 tl) (nth 2 defdecode))
11204 minute (or (nth 1 tl) (nth 1 defdecode))
11205 second (or (nth 0 tl) 0)
11206 wday (nth 6 tl))
11208 ;; Special date definitions below
11209 (cond
11210 (iso-week
11211 ;; There was an iso week
11212 (setq year (or iso-year year)
11213 day (or iso-weekday wday 1)
11214 wday nil ; to make sure that the trigger below does not match
11215 iso-date (calendar-gregorian-from-absolute
11216 (calendar-absolute-from-iso
11217 (list iso-week day year))))
11218 ; FIXME: Should we also push ISO weeks into the future?
11219 ; (when (and org-read-date-prefer-future
11220 ; (not iso-year)
11221 ; (< (calendar-absolute-from-gregorian iso-date)
11222 ; (time-to-days (current-time))))
11223 ; (setq year (1+ year)
11224 ; iso-date (calendar-gregorian-from-absolute
11225 ; (calendar-absolute-from-iso
11226 ; (list iso-week day year)))))
11227 (setq month (car iso-date)
11228 year (nth 2 iso-date)
11229 day (nth 1 iso-date)))
11230 (deltan
11231 (unless deltadef
11232 (let ((now (decode-time (current-time))))
11233 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
11234 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
11235 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
11236 ((equal deltaw "m") (setq month (+ month deltan)))
11237 ((equal deltaw "y") (setq year (+ year deltan)))))
11238 ((and wday (not (nth 3 tl)))
11239 ;; Weekday was given, but no day, so pick that day in the week
11240 ;; on or after the derived date.
11241 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
11242 (unless (equal wday wday1)
11243 (setq day (+ day (% (- wday wday1 -7) 7))))))
11244 (if (and (boundp 'org-time-was-given)
11245 (nth 2 tl))
11246 (setq org-time-was-given t))
11247 (if (< year 100) (setq year (+ 2000 year)))
11248 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
11249 (list second minute hour day month year)))
11251 (defvar parse-time-weekdays)
11253 (defun org-read-date-get-relative (s today default)
11254 "Check string S for special relative date string.
11255 TODAY and DEFAULT are internal times, for today and for a default.
11256 Return shift list (N what def-flag)
11257 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
11258 N is the number of WHATs to shift.
11259 DEF-FLAG is t when a double ++ or -- indicates shift relative to
11260 the DEFAULT date rather than TODAY."
11261 (when (and
11262 (string-match
11263 (concat
11264 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
11265 "\\([0-9]+\\)?"
11266 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
11267 "\\([ \t]\\|$\\)") s)
11268 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
11269 (let* ((dir (if (> (match-end 1) (match-beginning 1))
11270 (string-to-char (substring (match-string 1 s) -1))
11271 ?+))
11272 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
11273 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
11274 (what (if (match-end 3) (match-string 3 s) "d"))
11275 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
11276 (date (if rel default today))
11277 (wday (nth 6 (decode-time date)))
11278 delta)
11279 (if wday1
11280 (progn
11281 (setq delta (mod (+ 7 (- wday1 wday)) 7))
11282 (if (= dir ?-) (setq delta (- delta 7)))
11283 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
11284 (list delta "d" rel))
11285 (list (* n (if (= dir ?-) -1 1)) what rel)))))
11287 (defun org-eval-in-calendar (form &optional keepdate)
11288 "Eval FORM in the calendar window and return to current window.
11289 Also, store the cursor date in variable org-ans2."
11290 (let ((sw (selected-window)))
11291 (select-window (get-buffer-window "*Calendar*"))
11292 (eval form)
11293 (when (and (not keepdate) (calendar-cursor-to-date))
11294 (let* ((date (calendar-cursor-to-date))
11295 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11296 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
11297 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
11298 (select-window sw)))
11300 (defun org-calendar-select ()
11301 "Return to `org-read-date' with the date currently selected.
11302 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11303 (interactive)
11304 (when (calendar-cursor-to-date)
11305 (let* ((date (calendar-cursor-to-date))
11306 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11307 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11308 (if (active-minibuffer-window) (exit-minibuffer))))
11310 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
11311 "Insert a date stamp for the date given by the internal TIME.
11312 WITH-HM means, use the stamp format that includes the time of the day.
11313 INACTIVE means use square brackets instead of angular ones, so that the
11314 stamp will not contribute to the agenda.
11315 PRE and POST are optional strings to be inserted before and after the
11316 stamp.
11317 The command returns the inserted time stamp."
11318 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
11319 stamp)
11320 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
11321 (insert-before-markers (or pre ""))
11322 (insert-before-markers (setq stamp (format-time-string fmt time)))
11323 (when (listp extra)
11324 (setq extra (car extra))
11325 (if (and (stringp extra)
11326 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
11327 (setq extra (format "-%02d:%02d"
11328 (string-to-number (match-string 1 extra))
11329 (string-to-number (match-string 2 extra))))
11330 (setq extra nil)))
11331 (when extra
11332 (backward-char 1)
11333 (insert-before-markers extra)
11334 (forward-char 1))
11335 (insert-before-markers (or post ""))
11336 (setq org-last-inserted-timestamp stamp)))
11338 (defun org-toggle-time-stamp-overlays ()
11339 "Toggle the use of custom time stamp formats."
11340 (interactive)
11341 (setq org-display-custom-times (not org-display-custom-times))
11342 (unless org-display-custom-times
11343 (let ((p (point-min)) (bmp (buffer-modified-p)))
11344 (while (setq p (next-single-property-change p 'display))
11345 (if (and (get-text-property p 'display)
11346 (eq (get-text-property p 'face) 'org-date))
11347 (remove-text-properties
11348 p (setq p (next-single-property-change p 'display))
11349 '(display t))))
11350 (set-buffer-modified-p bmp)))
11351 (if (featurep 'xemacs)
11352 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
11353 (org-restart-font-lock)
11354 (setq org-table-may-need-update t)
11355 (if org-display-custom-times
11356 (message "Time stamps are overlayed with custom format")
11357 (message "Time stamp overlays removed")))
11359 (defun org-display-custom-time (beg end)
11360 "Overlay modified time stamp format over timestamp between BEG and END."
11361 (let* ((ts (buffer-substring beg end))
11362 t1 w1 with-hm tf time str w2 (off 0))
11363 (save-match-data
11364 (setq t1 (org-parse-time-string ts t))
11365 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
11366 (setq off (- (match-end 0) (match-beginning 0)))))
11367 (setq end (- end off))
11368 (setq w1 (- end beg)
11369 with-hm (and (nth 1 t1) (nth 2 t1))
11370 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
11371 time (org-fix-decoded-time t1)
11372 str (org-add-props
11373 (format-time-string
11374 (substring tf 1 -1) (apply 'encode-time time))
11375 nil 'mouse-face 'highlight)
11376 w2 (length str))
11377 (if (not (= w2 w1))
11378 (add-text-properties (1+ beg) (+ 2 beg)
11379 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
11380 (if (featurep 'xemacs)
11381 (progn
11382 (put-text-property beg end 'invisible t)
11383 (put-text-property beg end 'end-glyph (make-glyph str)))
11384 (put-text-property beg end 'display str))))
11386 (defun org-translate-time (string)
11387 "Translate all timestamps in STRING to custom format.
11388 But do this only if the variable `org-display-custom-times' is set."
11389 (when org-display-custom-times
11390 (save-match-data
11391 (let* ((start 0)
11392 (re org-ts-regexp-both)
11393 t1 with-hm inactive tf time str beg end)
11394 (while (setq start (string-match re string start))
11395 (setq beg (match-beginning 0)
11396 end (match-end 0)
11397 t1 (save-match-data
11398 (org-parse-time-string (substring string beg end) t))
11399 with-hm (and (nth 1 t1) (nth 2 t1))
11400 inactive (equal (substring string beg (1+ beg)) "[")
11401 tf (funcall (if with-hm 'cdr 'car)
11402 org-time-stamp-custom-formats)
11403 time (org-fix-decoded-time t1)
11404 str (format-time-string
11405 (concat
11406 (if inactive "[" "<") (substring tf 1 -1)
11407 (if inactive "]" ">"))
11408 (apply 'encode-time time))
11409 string (replace-match str t t string)
11410 start (+ start (length str)))))))
11411 string)
11413 (defun org-fix-decoded-time (time)
11414 "Set 0 instead of nil for the first 6 elements of time.
11415 Don't touch the rest."
11416 (let ((n 0))
11417 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
11419 (defun org-days-to-time (timestamp-string)
11420 "Difference between TIMESTAMP-STRING and now in days."
11421 (- (time-to-days (org-time-string-to-time timestamp-string))
11422 (time-to-days (current-time))))
11424 (defun org-deadline-close (timestamp-string &optional ndays)
11425 "Is the time in TIMESTAMP-STRING close to the current date?"
11426 (setq ndays (or ndays (org-get-wdays timestamp-string)))
11427 (and (< (org-days-to-time timestamp-string) ndays)
11428 (not (org-entry-is-done-p))))
11430 (defun org-get-wdays (ts)
11431 "Get the deadline lead time appropriate for timestring TS."
11432 (cond
11433 ((<= org-deadline-warning-days 0)
11434 ;; 0 or negative, enforce this value no matter what
11435 (- org-deadline-warning-days))
11436 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
11437 ;; lead time is specified.
11438 (floor (* (string-to-number (match-string 1 ts))
11439 (cdr (assoc (match-string 2 ts)
11440 '(("d" . 1) ("w" . 7)
11441 ("m" . 30.4) ("y" . 365.25)))))))
11442 ;; go for the default.
11443 (t org-deadline-warning-days)))
11445 (defun org-calendar-select-mouse (ev)
11446 "Return to `org-read-date' with the date currently selected.
11447 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11448 (interactive "e")
11449 (mouse-set-point ev)
11450 (when (calendar-cursor-to-date)
11451 (let* ((date (calendar-cursor-to-date))
11452 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11453 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11454 (if (active-minibuffer-window) (exit-minibuffer))))
11456 (defun org-check-deadlines (ndays)
11457 "Check if there are any deadlines due or past due.
11458 A deadline is considered due if it happens within `org-deadline-warning-days'
11459 days from today's date. If the deadline appears in an entry marked DONE,
11460 it is not shown. The prefix arg NDAYS can be used to test that many
11461 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
11462 (interactive "P")
11463 (let* ((org-warn-days
11464 (cond
11465 ((equal ndays '(4)) 100000)
11466 (ndays (prefix-numeric-value ndays))
11467 (t (abs org-deadline-warning-days))))
11468 (case-fold-search nil)
11469 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
11470 (callback
11471 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
11473 (message "%d deadlines past-due or due within %d days"
11474 (org-occur regexp nil callback)
11475 org-warn-days)))
11477 (defun org-check-before-date (date)
11478 "Check if there are deadlines or scheduled entries before DATE."
11479 (interactive (list (org-read-date)))
11480 (let ((case-fold-search nil)
11481 (regexp (concat "\\<\\(" org-deadline-string
11482 "\\|" org-scheduled-string
11483 "\\) *<\\([^>]+\\)>"))
11484 (callback
11485 (lambda () (time-less-p
11486 (org-time-string-to-time (match-string 2))
11487 (org-time-string-to-time date)))))
11488 (message "%d entries before %s"
11489 (org-occur regexp nil callback) date)))
11491 (defun org-evaluate-time-range (&optional to-buffer)
11492 "Evaluate a time range by computing the difference between start and end.
11493 Normally the result is just printed in the echo area, but with prefix arg
11494 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
11495 If the time range is actually in a table, the result is inserted into the
11496 next column.
11497 For time difference computation, a year is assumed to be exactly 365
11498 days in order to avoid rounding problems."
11499 (interactive "P")
11501 (org-clock-update-time-maybe)
11502 (save-excursion
11503 (unless (org-at-date-range-p t)
11504 (goto-char (point-at-bol))
11505 (re-search-forward org-tr-regexp-both (point-at-eol) t))
11506 (if (not (org-at-date-range-p t))
11507 (error "Not at a time-stamp range, and none found in current line")))
11508 (let* ((ts1 (match-string 1))
11509 (ts2 (match-string 2))
11510 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
11511 (match-end (match-end 0))
11512 (time1 (org-time-string-to-time ts1))
11513 (time2 (org-time-string-to-time ts2))
11514 (t1 (time-to-seconds time1))
11515 (t2 (time-to-seconds time2))
11516 (diff (abs (- t2 t1)))
11517 (negative (< (- t2 t1) 0))
11518 ;; (ys (floor (* 365 24 60 60)))
11519 (ds (* 24 60 60))
11520 (hs (* 60 60))
11521 (fy "%dy %dd %02d:%02d")
11522 (fy1 "%dy %dd")
11523 (fd "%dd %02d:%02d")
11524 (fd1 "%dd")
11525 (fh "%02d:%02d")
11526 y d h m align)
11527 (if havetime
11528 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11530 d (floor (/ diff ds)) diff (mod diff ds)
11531 h (floor (/ diff hs)) diff (mod diff hs)
11532 m (floor (/ diff 60)))
11533 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11535 d (floor (+ (/ diff ds) 0.5))
11536 h 0 m 0))
11537 (if (not to-buffer)
11538 (message "%s" (org-make-tdiff-string y d h m))
11539 (if (org-at-table-p)
11540 (progn
11541 (goto-char match-end)
11542 (setq align t)
11543 (and (looking-at " *|") (goto-char (match-end 0))))
11544 (goto-char match-end))
11545 (if (looking-at
11546 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
11547 (replace-match ""))
11548 (if negative (insert " -"))
11549 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
11550 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
11551 (insert " " (format fh h m))))
11552 (if align (org-table-align))
11553 (message "Time difference inserted")))))
11555 (defun org-make-tdiff-string (y d h m)
11556 (let ((fmt "")
11557 (l nil))
11558 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
11559 l (push y l)))
11560 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
11561 l (push d l)))
11562 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
11563 l (push h l)))
11564 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
11565 l (push m l)))
11566 (apply 'format fmt (nreverse l))))
11568 (defun org-time-string-to-time (s)
11569 (apply 'encode-time (org-parse-time-string s)))
11571 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
11572 "Convert a time stamp to an absolute day number.
11573 If there is a specifyer for a cyclic time stamp, get the closest date to
11574 DAYNR.
11575 PREFER and SHOW-ALL are passed through to `org-closest-date'."
11576 (cond
11577 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
11578 (if (org-diary-sexp-entry (match-string 1 s) "" date)
11579 daynr
11580 (+ daynr 1000)))
11581 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
11582 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
11583 (time-to-days (current-time))) (match-string 0 s)
11584 prefer show-all))
11585 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
11587 (defun org-days-to-iso-week (days)
11588 "Return the iso week number."
11589 (require 'cal-iso)
11590 (car (calendar-iso-from-absolute days)))
11592 (defun org-small-year-to-year (year)
11593 "Convert 2-digit years into 4-digit years.
11594 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
11595 The year 2000 cannot be abbreviated. Any year larger than 99
11596 is returned unchanged."
11597 (if (< year 38)
11598 (setq year (+ 2000 year))
11599 (if (< year 100)
11600 (setq year (+ 1900 year))))
11601 year)
11603 (defun org-time-from-absolute (d)
11604 "Return the time corresponding to date D.
11605 D may be an absolute day number, or a calendar-type list (month day year)."
11606 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
11607 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
11609 (defun org-calendar-holiday ()
11610 "List of holidays, for Diary display in Org-mode."
11611 (require 'holidays)
11612 (let ((hl (funcall
11613 (if (fboundp 'calendar-check-holidays)
11614 'calendar-check-holidays 'check-calendar-holidays) date)))
11615 (if hl (mapconcat 'identity hl "; "))))
11617 (defun org-diary-sexp-entry (sexp entry date)
11618 "Process a SEXP diary ENTRY for DATE."
11619 (require 'diary-lib)
11620 (let ((result (if calendar-debug-sexp
11621 (let ((stack-trace-on-error t))
11622 (eval (car (read-from-string sexp))))
11623 (condition-case nil
11624 (eval (car (read-from-string sexp)))
11625 (error
11626 (beep)
11627 (message "Bad sexp at line %d in %s: %s"
11628 (org-current-line)
11629 (buffer-file-name) sexp)
11630 (sleep-for 2))))))
11631 (cond ((stringp result) result)
11632 ((and (consp result)
11633 (stringp (cdr result))) (cdr result))
11634 (result entry)
11635 (t nil))))
11637 (defun org-diary-to-ical-string (frombuf)
11638 "Get iCalendar entries from diary entries in buffer FROMBUF.
11639 This uses the icalendar.el library."
11640 (let* ((tmpdir (if (featurep 'xemacs)
11641 (temp-directory)
11642 temporary-file-directory))
11643 (tmpfile (make-temp-name
11644 (expand-file-name "orgics" tmpdir)))
11645 buf rtn b e)
11646 (save-excursion
11647 (set-buffer frombuf)
11648 (icalendar-export-region (point-min) (point-max) tmpfile)
11649 (setq buf (find-buffer-visiting tmpfile))
11650 (set-buffer buf)
11651 (goto-char (point-min))
11652 (if (re-search-forward "^BEGIN:VEVENT" nil t)
11653 (setq b (match-beginning 0)))
11654 (goto-char (point-max))
11655 (if (re-search-backward "^END:VEVENT" nil t)
11656 (setq e (match-end 0)))
11657 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
11658 (kill-buffer buf)
11659 (delete-file tmpfile)
11660 rtn))
11662 (defun org-closest-date (start current change prefer show-all)
11663 "Find the date closest to CURRENT that is consistent with START and CHANGE.
11664 When PREFER is `past' return a date that is either CURRENT or past.
11665 When PREFER is `future', return a date that is either CURRENT or future.
11666 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
11667 ;; Make the proper lists from the dates
11668 (catch 'exit
11669 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
11670 dn dw sday cday n1 n2 n0
11671 d m y y1 y2 date1 date2 nmonths nm ny m2)
11673 (setq start (org-date-to-gregorian start)
11674 current (org-date-to-gregorian
11675 (if show-all
11676 current
11677 (time-to-days (current-time))))
11678 sday (calendar-absolute-from-gregorian start)
11679 cday (calendar-absolute-from-gregorian current))
11681 (if (<= cday sday) (throw 'exit sday))
11683 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
11684 (setq dn (string-to-number (match-string 1 change))
11685 dw (cdr (assoc (match-string 2 change) a1)))
11686 (error "Invalid change specifyer: %s" change))
11687 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
11688 (cond
11689 ((eq dw 'day)
11690 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
11691 n2 (+ n1 dn)))
11692 ((eq dw 'year)
11693 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
11694 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
11695 (setq date1 (list m d y1)
11696 n1 (calendar-absolute-from-gregorian date1)
11697 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
11698 n2 (calendar-absolute-from-gregorian date2)))
11699 ((eq dw 'month)
11700 ;; approx number of month between the two dates
11701 (setq nmonths (floor (/ (- cday sday) 30.436875)))
11702 ;; How often does dn fit in there?
11703 (setq d (nth 1 start) m (car start) y (nth 2 start)
11704 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
11705 m (+ m nm)
11706 ny (floor (/ m 12))
11707 y (+ y ny)
11708 m (- m (* ny 12)))
11709 (while (> m 12) (setq m (- m 12) y (1+ y)))
11710 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
11711 (setq m2 (+ m dn) y2 y)
11712 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11713 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
11714 (while (<= n2 cday)
11715 (setq n1 n2 m m2 y y2)
11716 (setq m2 (+ m dn) y2 y)
11717 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11718 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
11719 ;; Make sure n1 is the earlier date
11720 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
11721 (if show-all
11722 (cond
11723 ((eq prefer 'past) n1)
11724 ((eq prefer 'future) (if (= cday n1) n1 n2))
11725 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
11726 (cond
11727 ((eq prefer 'past) n1)
11728 ((eq prefer 'future) (if (= cday n1) n1 n2))
11729 (t (if (= cday n1) n1 n2)))))))
11731 (defun org-date-to-gregorian (date)
11732 "Turn any specification of DATE into a gregorian date for the calendar."
11733 (cond ((integerp date) (calendar-gregorian-from-absolute date))
11734 ((and (listp date) (= (length date) 3)) date)
11735 ((stringp date)
11736 (setq date (org-parse-time-string date))
11737 (list (nth 4 date) (nth 3 date) (nth 5 date)))
11738 ((listp date)
11739 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
11741 (defun org-parse-time-string (s &optional nodefault)
11742 "Parse the standard Org-mode time string.
11743 This should be a lot faster than the normal `parse-time-string'.
11744 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
11745 hour and minute fields will be nil if not given."
11746 (if (string-match org-ts-regexp0 s)
11747 (list 0
11748 (if (or (match-beginning 8) (not nodefault))
11749 (string-to-number (or (match-string 8 s) "0")))
11750 (if (or (match-beginning 7) (not nodefault))
11751 (string-to-number (or (match-string 7 s) "0")))
11752 (string-to-number (match-string 4 s))
11753 (string-to-number (match-string 3 s))
11754 (string-to-number (match-string 2 s))
11755 nil nil nil)
11756 (make-list 9 0)))
11758 (defun org-timestamp-up (&optional arg)
11759 "Increase the date item at the cursor by one.
11760 If the cursor is on the year, change the year. If it is on the month or
11761 the day, change that.
11762 With prefix ARG, change by that many units."
11763 (interactive "p")
11764 (org-timestamp-change (prefix-numeric-value arg)))
11766 (defun org-timestamp-down (&optional arg)
11767 "Decrease the date item at the cursor by one.
11768 If the cursor is on the year, change the year. If it is on the month or
11769 the day, change that.
11770 With prefix ARG, change by that many units."
11771 (interactive "p")
11772 (org-timestamp-change (- (prefix-numeric-value arg))))
11774 (defun org-timestamp-up-day (&optional arg)
11775 "Increase the date in the time stamp by one day.
11776 With prefix ARG, change that many days."
11777 (interactive "p")
11778 (if (and (not (org-at-timestamp-p t))
11779 (org-on-heading-p))
11780 (org-todo 'up)
11781 (org-timestamp-change (prefix-numeric-value arg) 'day)))
11783 (defun org-timestamp-down-day (&optional arg)
11784 "Decrease the date in the time stamp by one day.
11785 With prefix ARG, change that many days."
11786 (interactive "p")
11787 (if (and (not (org-at-timestamp-p t))
11788 (org-on-heading-p))
11789 (org-todo 'down)
11790 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
11792 (defun org-at-timestamp-p (&optional inactive-ok)
11793 "Determine if the cursor is in or at a timestamp."
11794 (interactive)
11795 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
11796 (pos (point))
11797 (ans (or (looking-at tsr)
11798 (save-excursion
11799 (skip-chars-backward "^[<\n\r\t")
11800 (if (> (point) (point-min)) (backward-char 1))
11801 (and (looking-at tsr)
11802 (> (- (match-end 0) pos) -1))))))
11803 (and ans
11804 (boundp 'org-ts-what)
11805 (setq org-ts-what
11806 (cond
11807 ((= pos (match-beginning 0)) 'bracket)
11808 ((= pos (1- (match-end 0))) 'bracket)
11809 ((org-pos-in-match-range pos 2) 'year)
11810 ((org-pos-in-match-range pos 3) 'month)
11811 ((org-pos-in-match-range pos 7) 'hour)
11812 ((org-pos-in-match-range pos 8) 'minute)
11813 ((or (org-pos-in-match-range pos 4)
11814 (org-pos-in-match-range pos 5)) 'day)
11815 ((and (> pos (or (match-end 8) (match-end 5)))
11816 (< pos (match-end 0)))
11817 (- pos (or (match-end 8) (match-end 5))))
11818 (t 'day))))
11819 ans))
11821 (defun org-toggle-timestamp-type ()
11822 "Toggle the type (<active> or [inactive]) of a time stamp."
11823 (interactive)
11824 (when (org-at-timestamp-p t)
11825 (let ((beg (match-beginning 0)) (end (match-end 0))
11826 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
11827 (save-excursion
11828 (goto-char beg)
11829 (while (re-search-forward "[][<>]" end t)
11830 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
11831 t t)))
11832 (message "Timestamp is now %sactive"
11833 (if (equal (char-after beg) ?<) "" "in")))))
11835 (defun org-timestamp-change (n &optional what)
11836 "Change the date in the time stamp at point.
11837 The date will be changed by N times WHAT. WHAT can be `day', `month',
11838 `year', `minute', `second'. If WHAT is not given, the cursor position
11839 in the timestamp determines what will be changed."
11840 (let ((pos (point))
11841 with-hm inactive
11842 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
11843 org-ts-what
11844 extra rem
11845 ts time time0)
11846 (if (not (org-at-timestamp-p t))
11847 (error "Not at a timestamp"))
11848 (if (and (not what) (eq org-ts-what 'bracket))
11849 (org-toggle-timestamp-type)
11850 (if (and (not what) (not (eq org-ts-what 'day))
11851 org-display-custom-times
11852 (get-text-property (point) 'display)
11853 (not (get-text-property (1- (point)) 'display)))
11854 (setq org-ts-what 'day))
11855 (setq org-ts-what (or what org-ts-what)
11856 inactive (= (char-after (match-beginning 0)) ?\[)
11857 ts (match-string 0))
11858 (replace-match "")
11859 (if (string-match
11860 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
11862 (setq extra (match-string 1 ts)))
11863 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
11864 (setq with-hm t))
11865 (setq time0 (org-parse-time-string ts))
11866 (when (and (eq org-ts-what 'minute)
11867 (eq current-prefix-arg nil))
11868 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
11869 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
11870 (setcar (cdr time0) (+ (nth 1 time0)
11871 (if (> n 0) (- rem) (- dm rem))))))
11872 (setq time
11873 (encode-time (or (car time0) 0)
11874 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
11875 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
11876 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
11877 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
11878 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
11879 (nthcdr 6 time0)))
11880 (when (integerp org-ts-what)
11881 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
11882 (if (eq what 'calendar)
11883 (let ((cal-date (org-get-date-from-calendar)))
11884 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
11885 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
11886 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
11887 (setcar time0 (or (car time0) 0))
11888 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
11889 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
11890 (setq time (apply 'encode-time time0))))
11891 (setq org-last-changed-timestamp
11892 (org-insert-time-stamp time with-hm inactive nil nil extra))
11893 (org-clock-update-time-maybe)
11894 (goto-char pos)
11895 ;; Try to recenter the calendar window, if any
11896 (if (and org-calendar-follow-timestamp-change
11897 (get-buffer-window "*Calendar*" t)
11898 (memq org-ts-what '(day month year)))
11899 (org-recenter-calendar (time-to-days time))))))
11901 (defun org-modify-ts-extra (s pos n dm)
11902 "Change the different parts of the lead-time and repeat fields in timestamp."
11903 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
11904 ng h m new rem)
11905 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
11906 (cond
11907 ((or (org-pos-in-match-range pos 2)
11908 (org-pos-in-match-range pos 3))
11909 (setq m (string-to-number (match-string 3 s))
11910 h (string-to-number (match-string 2 s)))
11911 (if (org-pos-in-match-range pos 2)
11912 (setq h (+ h n))
11913 (setq n (* dm (org-no-warnings (signum n))))
11914 (when (not (= 0 (setq rem (% m dm))))
11915 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
11916 (setq m (+ m n)))
11917 (if (< m 0) (setq m (+ m 60) h (1- h)))
11918 (if (> m 59) (setq m (- m 60) h (1+ h)))
11919 (setq h (min 24 (max 0 h)))
11920 (setq ng 1 new (format "-%02d:%02d" h m)))
11921 ((org-pos-in-match-range pos 6)
11922 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
11923 ((org-pos-in-match-range pos 5)
11924 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
11926 ((org-pos-in-match-range pos 9)
11927 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
11928 ((org-pos-in-match-range pos 8)
11929 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
11931 (when ng
11932 (setq s (concat
11933 (substring s 0 (match-beginning ng))
11935 (substring s (match-end ng))))))
11938 (defun org-recenter-calendar (date)
11939 "If the calendar is visible, recenter it to DATE."
11940 (let* ((win (selected-window))
11941 (cwin (get-buffer-window "*Calendar*" t))
11942 (calendar-move-hook nil))
11943 (when cwin
11944 (select-window cwin)
11945 (calendar-goto-date (if (listp date) date
11946 (calendar-gregorian-from-absolute date)))
11947 (select-window win))))
11949 (defun org-goto-calendar (&optional arg)
11950 "Go to the Emacs calendar at the current date.
11951 If there is a time stamp in the current line, go to that date.
11952 A prefix ARG can be used to force the current date."
11953 (interactive "P")
11954 (let ((tsr org-ts-regexp) diff
11955 (calendar-move-hook nil)
11956 (calendar-view-holidays-initially-flag nil)
11957 (view-calendar-holidays-initially nil)
11958 (calendar-view-diary-initially-flag nil)
11959 (view-diary-entries-initially nil))
11960 (if (or (org-at-timestamp-p)
11961 (save-excursion
11962 (beginning-of-line 1)
11963 (looking-at (concat ".*" tsr))))
11964 (let ((d1 (time-to-days (current-time)))
11965 (d2 (time-to-days
11966 (org-time-string-to-time (match-string 1)))))
11967 (setq diff (- d2 d1))))
11968 (calendar)
11969 (calendar-goto-today)
11970 (if (and diff (not arg)) (calendar-forward-day diff))))
11972 (defun org-get-date-from-calendar ()
11973 "Return a list (month day year) of date at point in calendar."
11974 (with-current-buffer "*Calendar*"
11975 (save-match-data
11976 (calendar-cursor-to-date))))
11978 (defun org-date-from-calendar ()
11979 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
11980 If there is already a time stamp at the cursor position, update it."
11981 (interactive)
11982 (if (org-at-timestamp-p t)
11983 (org-timestamp-change 0 'calendar)
11984 (let ((cal-date (org-get-date-from-calendar)))
11985 (org-insert-time-stamp
11986 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
11988 (defun org-minutes-to-hh:mm-string (m)
11989 "Compute H:MM from a number of minutes."
11990 (let ((h (/ m 60)))
11991 (setq m (- m (* 60 h)))
11992 (format org-time-clocksum-format h m)))
11994 (defun org-hh:mm-string-to-minutes (s)
11995 "Convert a string H:MM to a number of minutes."
11996 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
11997 (+ (* (string-to-number (match-string 1 s)) 60)
11998 (string-to-number (match-string 2 s)))
12001 ;;;; Agenda files
12003 ;;;###autoload
12004 (defun org-iswitchb (&optional arg)
12005 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
12006 With a prefix argument, restrict available to files.
12007 With two prefix arguments, restrict available buffers to agenda files.
12009 Due to some yet unresolved reason, the global function
12010 `iswitchb-mode' needs to be active for this function to work."
12011 (interactive "P")
12012 (require 'iswitchb)
12013 (let ((enabled iswitchb-mode) blist)
12014 (or enabled (iswitchb-mode 1))
12015 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
12016 ((equal arg '(16)) (org-buffer-list 'agenda))
12017 (t (org-buffer-list))))
12018 (unwind-protect
12019 (let ((iswitchb-make-buflist-hook
12020 (lambda ()
12021 (setq iswitchb-temp-buflist
12022 (mapcar 'buffer-name blist)))))
12023 (switch-to-buffer
12024 (iswitchb-read-buffer
12025 "Switch-to: " nil t))
12026 (or enabled (iswitchb-mode -1))))))
12028 ;;;###autoload
12029 (defun org-ido-switchb (&optional arg)
12030 "Use `org-ido-completing-read' to prompt for an Org buffer to switch to.
12031 With a prefix argument, restrict available to files.
12032 With two prefix arguments, restrict available buffers to agenda files."
12033 (interactive "P")
12034 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
12035 ((equal arg '(16)) (org-buffer-list 'agenda))
12036 (t (org-buffer-list)))))
12037 (switch-to-buffer
12038 (org-ido-completing-read "Org buffer: "
12039 (mapcar 'buffer-name blist)
12040 nil t))))
12042 (defun org-buffer-list (&optional predicate exclude-tmp)
12043 "Return a list of Org buffers.
12044 PREDICATE can be `export', `files' or `agenda'.
12046 export restrict the list to Export buffers.
12047 files restrict the list to buffers visiting Org files.
12048 agenda restrict the list to buffers visiting agenda files.
12050 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
12051 (let* ((bfn nil)
12052 (agenda-files (and (eq predicate 'agenda)
12053 (mapcar 'file-truename (org-agenda-files t))))
12054 (filter
12055 (cond
12056 ((eq predicate 'files)
12057 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
12058 ((eq predicate 'export)
12059 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
12060 ((eq predicate 'agenda)
12061 (lambda (b)
12062 (with-current-buffer b
12063 (and (eq major-mode 'org-mode)
12064 (setq bfn (buffer-file-name b))
12065 (member (file-truename bfn) agenda-files)))))
12066 (t (lambda (b) (with-current-buffer b
12067 (or (eq major-mode 'org-mode)
12068 (string-match "\*Org .*Export"
12069 (buffer-name b)))))))))
12070 (delq nil
12071 (mapcar
12072 (lambda(b)
12073 (if (and (funcall filter b)
12074 (or (not exclude-tmp)
12075 (not (string-match "tmp" (buffer-name b)))))
12077 nil))
12078 (buffer-list)))))
12080 (defun org-agenda-files (&optional unrestricted archives)
12081 "Get the list of agenda files.
12082 Optional UNRESTRICTED means return the full list even if a restriction
12083 is currently in place.
12084 When ARCHIVES is t, include all archive files hat are really being
12085 used by the agenda files. If ARCHIVE is `ifmode', do this only if
12086 `org-agenda-archives-mode' is t."
12087 (let ((files
12088 (cond
12089 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
12090 ((stringp org-agenda-files) (org-read-agenda-file-list))
12091 ((listp org-agenda-files) org-agenda-files)
12092 (t (error "Invalid value of `org-agenda-files'")))))
12093 (setq files (apply 'append
12094 (mapcar (lambda (f)
12095 (if (file-directory-p f)
12096 (directory-files
12097 f t org-agenda-file-regexp)
12098 (list f)))
12099 files)))
12100 (when org-agenda-skip-unavailable-files
12101 (setq files (delq nil
12102 (mapcar (function
12103 (lambda (file)
12104 (and (file-readable-p file) file)))
12105 files))))
12106 (when (or (eq archives t)
12107 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
12108 (setq files (org-add-archive-files files)))
12109 files))
12111 (defun org-edit-agenda-file-list ()
12112 "Edit the list of agenda files.
12113 Depending on setup, this either uses customize to edit the variable
12114 `org-agenda-files', or it visits the file that is holding the list. In the
12115 latter case, the buffer is set up in a way that saving it automatically kills
12116 the buffer and restores the previous window configuration."
12117 (interactive)
12118 (if (stringp org-agenda-files)
12119 (let ((cw (current-window-configuration)))
12120 (find-file org-agenda-files)
12121 (org-set-local 'org-window-configuration cw)
12122 (org-add-hook 'after-save-hook
12123 (lambda ()
12124 (set-window-configuration
12125 (prog1 org-window-configuration
12126 (kill-buffer (current-buffer))))
12127 (org-install-agenda-files-menu)
12128 (message "New agenda file list installed"))
12129 nil 'local)
12130 (message "%s" (substitute-command-keys
12131 "Edit list and finish with \\[save-buffer]")))
12132 (customize-variable 'org-agenda-files)))
12134 (defun org-store-new-agenda-file-list (list)
12135 "Set new value for the agenda file list and save it correctly."
12136 (if (stringp org-agenda-files)
12137 (let ((f org-agenda-files) b)
12138 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
12139 (with-temp-file f
12140 (insert (mapconcat 'identity list "\n") "\n")))
12141 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
12142 (setq org-agenda-files list)
12143 (customize-save-variable 'org-agenda-files org-agenda-files))))
12145 (defun org-read-agenda-file-list ()
12146 "Read the list of agenda files from a file."
12147 (when (file-directory-p org-agenda-files)
12148 (error "`org-agenda-files' cannot be a single directory"))
12149 (when (stringp org-agenda-files)
12150 (with-temp-buffer
12151 (insert-file-contents org-agenda-files)
12152 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
12155 ;;;###autoload
12156 (defun org-cycle-agenda-files ()
12157 "Cycle through the files in `org-agenda-files'.
12158 If the current buffer visits an agenda file, find the next one in the list.
12159 If the current buffer does not, find the first agenda file."
12160 (interactive)
12161 (let* ((fs (org-agenda-files t))
12162 (files (append fs (list (car fs))))
12163 (tcf (if buffer-file-name (file-truename buffer-file-name)))
12164 file)
12165 (unless files (error "No agenda files"))
12166 (catch 'exit
12167 (while (setq file (pop files))
12168 (if (equal (file-truename file) tcf)
12169 (when (car files)
12170 (find-file (car files))
12171 (throw 'exit t))))
12172 (find-file (car fs)))
12173 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
12175 (defun org-agenda-file-to-front (&optional to-end)
12176 "Move/add the current file to the top of the agenda file list.
12177 If the file is not present in the list, it is added to the front. If it is
12178 present, it is moved there. With optional argument TO-END, add/move to the
12179 end of the list."
12180 (interactive "P")
12181 (let ((org-agenda-skip-unavailable-files nil)
12182 (file-alist (mapcar (lambda (x)
12183 (cons (file-truename x) x))
12184 (org-agenda-files t)))
12185 (ctf (file-truename buffer-file-name))
12186 x had)
12187 (setq x (assoc ctf file-alist) had x)
12189 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
12190 (if to-end
12191 (setq file-alist (append (delq x file-alist) (list x)))
12192 (setq file-alist (cons x (delq x file-alist))))
12193 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
12194 (org-install-agenda-files-menu)
12195 (message "File %s to %s of agenda file list"
12196 (if had "moved" "added") (if to-end "end" "front"))))
12198 (defun org-remove-file (&optional file)
12199 "Remove current file from the list of files in variable `org-agenda-files'.
12200 These are the files which are being checked for agenda entries.
12201 Optional argument FILE means, use this file instead of the current."
12202 (interactive)
12203 (let* ((org-agenda-skip-unavailable-files nil)
12204 (file (or file buffer-file-name))
12205 (true-file (file-truename file))
12206 (afile (abbreviate-file-name file))
12207 (files (delq nil (mapcar
12208 (lambda (x)
12209 (if (equal true-file
12210 (file-truename x))
12211 nil x))
12212 (org-agenda-files t)))))
12213 (if (not (= (length files) (length (org-agenda-files t))))
12214 (progn
12215 (org-store-new-agenda-file-list files)
12216 (org-install-agenda-files-menu)
12217 (message "Removed file: %s" afile))
12218 (message "File was not in list: %s (not removed)" afile))))
12220 (defun org-file-menu-entry (file)
12221 (vector file (list 'find-file file) t))
12223 (defun org-check-agenda-file (file)
12224 "Make sure FILE exists. If not, ask user what to do."
12225 (when (not (file-exists-p file))
12226 (message "non-existent file %s. [R]emove from list or [A]bort?"
12227 (abbreviate-file-name file))
12228 (let ((r (downcase (read-char-exclusive))))
12229 (cond
12230 ((equal r ?r)
12231 (org-remove-file file)
12232 (throw 'nextfile t))
12233 (t (error "Abort"))))))
12235 (defun org-get-agenda-file-buffer (file)
12236 "Get a buffer visiting FILE. If the buffer needs to be created, add
12237 it to the list of buffers which might be released later."
12238 (let ((buf (org-find-base-buffer-visiting file)))
12239 (if buf
12240 buf ; just return it
12241 ;; Make a new buffer and remember it
12242 (setq buf (find-file-noselect file))
12243 (if buf (push buf org-agenda-new-buffers))
12244 buf)))
12246 (defun org-release-buffers (blist)
12247 "Release all buffers in list, asking the user for confirmation when needed.
12248 When a buffer is unmodified, it is just killed. When modified, it is saved
12249 \(if the user agrees) and then killed."
12250 (let (buf file)
12251 (while (setq buf (pop blist))
12252 (setq file (buffer-file-name buf))
12253 (when (and (buffer-modified-p buf)
12254 file
12255 (y-or-n-p (format "Save file %s? " file)))
12256 (with-current-buffer buf (save-buffer)))
12257 (kill-buffer buf))))
12259 (defun org-prepare-agenda-buffers (files)
12260 "Create buffers for all agenda files, protect archived trees and comments."
12261 (interactive)
12262 (let ((pa '(:org-archived t))
12263 (pc '(:org-comment t))
12264 (pall '(:org-archived t :org-comment t))
12265 (inhibit-read-only t)
12266 (rea (concat ":" org-archive-tag ":"))
12267 bmp file re)
12268 (save-excursion
12269 (save-restriction
12270 (while (setq file (pop files))
12271 (if (bufferp file)
12272 (set-buffer file)
12273 (org-check-agenda-file file)
12274 (set-buffer (org-get-agenda-file-buffer file)))
12275 (widen)
12276 (setq bmp (buffer-modified-p))
12277 (org-refresh-category-properties)
12278 (setq org-todo-keywords-for-agenda
12279 (append org-todo-keywords-for-agenda org-todo-keywords-1))
12280 (setq org-done-keywords-for-agenda
12281 (append org-done-keywords-for-agenda org-done-keywords))
12282 (setq org-todo-keyword-alist-for-agenda
12283 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
12284 (setq org-tag-alist-for-agenda
12285 (append org-tag-alist-for-agenda org-tag-alist))
12287 (save-excursion
12288 (remove-text-properties (point-min) (point-max) pall)
12289 (when org-agenda-skip-archived-trees
12290 (goto-char (point-min))
12291 (while (re-search-forward rea nil t)
12292 (if (org-on-heading-p t)
12293 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
12294 (goto-char (point-min))
12295 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
12296 (while (re-search-forward re nil t)
12297 (add-text-properties
12298 (match-beginning 0) (org-end-of-subtree t) pc)))
12299 (set-buffer-modified-p bmp))))
12300 (setq org-todo-keyword-alist-for-agenda
12301 (org-uniquify org-todo-keyword-alist-for-agenda)
12302 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
12304 ;;;; Embedded LaTeX
12306 (defvar org-cdlatex-mode-map (make-sparse-keymap)
12307 "Keymap for the minor `org-cdlatex-mode'.")
12309 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
12310 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
12311 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
12312 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
12313 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
12315 (defvar org-cdlatex-texmathp-advice-is-done nil
12316 "Flag remembering if we have applied the advice to texmathp already.")
12318 (define-minor-mode org-cdlatex-mode
12319 "Toggle the minor `org-cdlatex-mode'.
12320 This mode supports entering LaTeX environment and math in LaTeX fragments
12321 in Org-mode.
12322 \\{org-cdlatex-mode-map}"
12323 nil " OCDL" nil
12324 (when org-cdlatex-mode (require 'cdlatex))
12325 (unless org-cdlatex-texmathp-advice-is-done
12326 (setq org-cdlatex-texmathp-advice-is-done t)
12327 (defadvice texmathp (around org-math-always-on activate)
12328 "Always return t in org-mode buffers.
12329 This is because we want to insert math symbols without dollars even outside
12330 the LaTeX math segments. If Orgmode thinks that point is actually inside
12331 an embedded LaTeX fragment, let texmathp do its job.
12332 \\[org-cdlatex-mode-map]"
12333 (interactive)
12334 (let (p)
12335 (cond
12336 ((not (org-mode-p)) ad-do-it)
12337 ((eq this-command 'cdlatex-math-symbol)
12338 (setq ad-return-value t
12339 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
12341 (let ((p (org-inside-LaTeX-fragment-p)))
12342 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
12343 (setq ad-return-value t
12344 texmathp-why '("Org-mode embedded math" . 0))
12345 (if p ad-do-it)))))))))
12347 (defun turn-on-org-cdlatex ()
12348 "Unconditionally turn on `org-cdlatex-mode'."
12349 (org-cdlatex-mode 1))
12351 (defun org-inside-LaTeX-fragment-p ()
12352 "Test if point is inside a LaTeX fragment.
12353 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
12354 sequence appearing also before point.
12355 Even though the matchers for math are configurable, this function assumes
12356 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
12357 delimiters are skipped when they have been removed by customization.
12358 The return value is nil, or a cons cell with the delimiter and
12359 and the position of this delimiter.
12361 This function does a reasonably good job, but can locally be fooled by
12362 for example currency specifications. For example it will assume being in
12363 inline math after \"$22.34\". The LaTeX fragment formatter will only format
12364 fragments that are properly closed, but during editing, we have to live
12365 with the uncertainty caused by missing closing delimiters. This function
12366 looks only before point, not after."
12367 (catch 'exit
12368 (let ((pos (point))
12369 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
12370 (lim (progn
12371 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
12372 (point)))
12373 dd-on str (start 0) m re)
12374 (goto-char pos)
12375 (when dodollar
12376 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
12377 re (nth 1 (assoc "$" org-latex-regexps)))
12378 (while (string-match re str start)
12379 (cond
12380 ((= (match-end 0) (length str))
12381 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
12382 ((= (match-end 0) (- (length str) 5))
12383 (throw 'exit nil))
12384 (t (setq start (match-end 0))))))
12385 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
12386 (goto-char pos)
12387 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
12388 (and (match-beginning 2) (throw 'exit nil))
12389 ;; count $$
12390 (while (re-search-backward "\\$\\$" lim t)
12391 (setq dd-on (not dd-on)))
12392 (goto-char pos)
12393 (if dd-on (cons "$$" m))))))
12396 (defun org-try-cdlatex-tab ()
12397 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
12398 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
12399 - inside a LaTeX fragment, or
12400 - after the first word in a line, where an abbreviation expansion could
12401 insert a LaTeX environment."
12402 (when org-cdlatex-mode
12403 (cond
12404 ((save-excursion
12405 (skip-chars-backward "a-zA-Z0-9*")
12406 (skip-chars-backward " \t")
12407 (bolp))
12408 (cdlatex-tab) t)
12409 ((org-inside-LaTeX-fragment-p)
12410 (cdlatex-tab) t)
12411 (t nil))))
12413 (defun org-cdlatex-underscore-caret (&optional arg)
12414 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
12415 Revert to the normal definition outside of these fragments."
12416 (interactive "P")
12417 (if (org-inside-LaTeX-fragment-p)
12418 (call-interactively 'cdlatex-sub-superscript)
12419 (let (org-cdlatex-mode)
12420 (call-interactively (key-binding (vector last-input-event))))))
12422 (defun org-cdlatex-math-modify (&optional arg)
12423 "Execute `cdlatex-math-modify' in LaTeX fragments.
12424 Revert to the normal definition outside of these fragments."
12425 (interactive "P")
12426 (if (org-inside-LaTeX-fragment-p)
12427 (call-interactively 'cdlatex-math-modify)
12428 (let (org-cdlatex-mode)
12429 (call-interactively (key-binding (vector last-input-event))))))
12431 (defvar org-latex-fragment-image-overlays nil
12432 "List of overlays carrying the images of latex fragments.")
12433 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
12435 (defun org-remove-latex-fragment-image-overlays ()
12436 "Remove all overlays with LaTeX fragment images in current buffer."
12437 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
12438 (setq org-latex-fragment-image-overlays nil))
12440 (defun org-preview-latex-fragment (&optional subtree)
12441 "Preview the LaTeX fragment at point, or all locally or globally.
12442 If the cursor is in a LaTeX fragment, create the image and overlay
12443 it over the source code. If there is no fragment at point, display
12444 all fragments in the current text, from one headline to the next. With
12445 prefix SUBTREE, display all fragments in the current subtree. With a
12446 double prefix `C-u C-u', or when the cursor is before the first headline,
12447 display all fragments in the buffer.
12448 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
12449 (interactive "P")
12450 (org-remove-latex-fragment-image-overlays)
12451 (save-excursion
12452 (save-restriction
12453 (let (beg end at msg)
12454 (cond
12455 ((or (equal subtree '(16))
12456 (not (save-excursion
12457 (re-search-backward (concat "^" outline-regexp) nil t))))
12458 (setq beg (point-min) end (point-max)
12459 msg "Creating images for buffer...%s"))
12460 ((equal subtree '(4))
12461 (org-back-to-heading)
12462 (setq beg (point) end (org-end-of-subtree t)
12463 msg "Creating images for subtree...%s"))
12465 (if (setq at (org-inside-LaTeX-fragment-p))
12466 (goto-char (max (point-min) (- (cdr at) 2)))
12467 (org-back-to-heading))
12468 (setq beg (point) end (progn (outline-next-heading) (point))
12469 msg (if at "Creating image...%s"
12470 "Creating images for entry...%s"))))
12471 (message msg "")
12472 (narrow-to-region beg end)
12473 (goto-char beg)
12474 (org-format-latex
12475 (concat "ltxpng/" (file-name-sans-extension
12476 (file-name-nondirectory
12477 buffer-file-name)))
12478 default-directory 'overlays msg at 'forbuffer)
12479 (message msg "done. Use `C-c C-c' to remove images.")))))
12481 (defvar org-latex-regexps
12482 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
12483 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
12484 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
12485 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
12486 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
12487 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
12488 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
12489 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
12490 "Regular expressions for matching embedded LaTeX.")
12492 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
12493 "Replace LaTeX fragments with links to an image, and produce images."
12494 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
12495 (let* ((prefixnodir (file-name-nondirectory prefix))
12496 (absprefix (expand-file-name prefix dir))
12497 (todir (file-name-directory absprefix))
12498 (opt org-format-latex-options)
12499 (matchers (plist-get opt :matchers))
12500 (re-list org-latex-regexps)
12501 (cnt 0) txt link beg end re e checkdir
12502 m n block linkfile movefile ov)
12503 ;; Check if there are old images files with this prefix, and remove them
12504 (when (file-directory-p todir)
12505 (mapc 'delete-file
12506 (directory-files
12507 todir 'full
12508 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
12509 ;; Check the different regular expressions
12510 (while (setq e (pop re-list))
12511 (setq m (car e) re (nth 1 e) n (nth 2 e)
12512 block (if (nth 3 e) "\n\n" ""))
12513 (when (member m matchers)
12514 (goto-char (point-min))
12515 (while (re-search-forward re nil t)
12516 (when (or (not at) (equal (cdr at) (match-beginning n)))
12517 (setq txt (match-string n)
12518 beg (match-beginning n) end (match-end n)
12519 cnt (1+ cnt)
12520 linkfile (format "%s_%04d.png" prefix cnt)
12521 movefile (format "%s_%04d.png" absprefix cnt)
12522 link (concat block "[[file:" linkfile "]]" block))
12523 (if msg (message msg cnt))
12524 (goto-char beg)
12525 (unless checkdir ; make sure the directory exists
12526 (setq checkdir t)
12527 (or (file-directory-p todir) (make-directory todir)))
12528 (org-create-formula-image
12529 txt movefile opt forbuffer)
12530 (if overlays
12531 (progn
12532 (setq ov (org-make-overlay beg end))
12533 (if (featurep 'xemacs)
12534 (progn
12535 (org-overlay-put ov 'invisible t)
12536 (org-overlay-put
12537 ov 'end-glyph
12538 (make-glyph (vector 'png :file movefile))))
12539 (org-overlay-put
12540 ov 'display
12541 (list 'image :type 'png :file movefile :ascent 'center)))
12542 (push ov org-latex-fragment-image-overlays)
12543 (goto-char end))
12544 (delete-region beg end)
12545 (insert link))))))))
12547 ;; This function borrows from Ganesh Swami's latex2png.el
12548 (defun org-create-formula-image (string tofile options buffer)
12549 (let* ((tmpdir (if (featurep 'xemacs)
12550 (temp-directory)
12551 temporary-file-directory))
12552 (texfilebase (make-temp-name
12553 (expand-file-name "orgtex" tmpdir)))
12554 (texfile (concat texfilebase ".tex"))
12555 (dvifile (concat texfilebase ".dvi"))
12556 (pngfile (concat texfilebase ".png"))
12557 (fnh (if (featurep 'xemacs)
12558 (font-height (get-face-font 'default))
12559 (face-attribute 'default :height nil)))
12560 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
12561 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
12562 (fg (or (plist-get options (if buffer :foreground :html-foreground))
12563 "Black"))
12564 (bg (or (plist-get options (if buffer :background :html-background))
12565 "Transparent")))
12566 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
12567 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
12568 (with-temp-file texfile
12569 (insert org-format-latex-header
12570 "\n\\begin{document}\n" string "\n\\end{document}\n"))
12571 (let ((dir default-directory))
12572 (condition-case nil
12573 (progn
12574 (cd tmpdir)
12575 (call-process "latex" nil nil nil texfile))
12576 (error nil))
12577 (cd dir))
12578 (if (not (file-exists-p dvifile))
12579 (progn (message "Failed to create dvi file from %s" texfile) nil)
12580 (condition-case nil
12581 (call-process "dvipng" nil nil nil
12582 "-E" "-fg" fg "-bg" bg
12583 "-D" dpi
12584 ;;"-x" scale "-y" scale
12585 "-T" "tight"
12586 "-o" pngfile
12587 dvifile)
12588 (error nil))
12589 (if (not (file-exists-p pngfile))
12590 (progn (message "Failed to create png file from %s" texfile) nil)
12591 ;; Use the requested file name and clean up
12592 (copy-file pngfile tofile 'replace)
12593 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
12594 (delete-file (concat texfilebase e)))
12595 pngfile))))
12597 (defun org-dvipng-color (attr)
12598 "Return an rgb color specification for dvipng."
12599 (apply 'format "rgb %s %s %s"
12600 (mapcar 'org-normalize-color
12601 (color-values (face-attribute 'default attr nil)))))
12603 (defun org-normalize-color (value)
12604 "Return string to be used as color value for an RGB component."
12605 (format "%g" (/ value 65535.0)))
12607 ;;;; Key bindings
12609 ;; Make `C-c C-x' a prefix key
12610 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
12612 ;; TAB key with modifiers
12613 (org-defkey org-mode-map "\C-i" 'org-cycle)
12614 (org-defkey org-mode-map [(tab)] 'org-cycle)
12615 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
12616 (org-defkey org-mode-map [(meta tab)] 'org-complete)
12617 (org-defkey org-mode-map "\M-\t" 'org-complete)
12618 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
12619 ;; The following line is necessary under Suse GNU/Linux
12620 (unless (featurep 'xemacs)
12621 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
12622 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
12623 (define-key org-mode-map [backtab] 'org-shifttab)
12625 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
12626 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
12627 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
12629 ;; Cursor keys with modifiers
12630 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
12631 (org-defkey org-mode-map [(meta right)] 'org-metaright)
12632 (org-defkey org-mode-map [(meta up)] 'org-metaup)
12633 (org-defkey org-mode-map [(meta down)] 'org-metadown)
12635 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
12636 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
12637 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
12638 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
12640 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
12641 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
12642 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
12643 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
12645 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
12646 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
12648 ;;; Extra keys for tty access.
12649 ;; We only set them when really needed because otherwise the
12650 ;; menus don't show the simple keys
12652 (when (or org-use-extra-keys
12653 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
12654 (not window-system))
12655 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
12656 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
12657 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
12658 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
12659 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
12660 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
12661 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
12662 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
12663 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
12664 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
12665 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
12666 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
12667 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
12668 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
12669 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
12670 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
12671 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
12672 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
12673 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
12674 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
12675 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
12676 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
12678 ;; All the other keys
12680 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
12681 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
12682 (if (boundp 'narrow-map)
12683 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
12684 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
12685 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
12686 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
12687 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
12688 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
12689 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
12690 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
12691 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
12692 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
12693 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
12694 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
12695 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
12696 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
12697 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
12698 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
12699 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
12700 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
12701 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
12702 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
12703 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
12704 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
12705 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
12706 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
12707 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
12708 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
12709 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
12710 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
12711 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
12712 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
12713 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
12714 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
12715 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
12716 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
12717 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
12718 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
12719 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
12720 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
12721 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
12722 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
12723 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
12724 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
12725 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
12726 (org-defkey org-mode-map "\C-c^" 'org-sort)
12727 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
12728 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
12729 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
12730 (org-defkey org-mode-map "\C-m" 'org-return)
12731 (org-defkey org-mode-map "\C-j" 'org-return-indent)
12732 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
12733 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
12734 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
12735 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
12736 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
12737 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
12738 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
12739 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
12740 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
12741 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
12742 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
12743 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
12744 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
12745 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
12746 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
12747 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
12749 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
12750 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
12751 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
12752 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
12754 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
12755 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
12756 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
12757 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
12758 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
12759 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
12760 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
12761 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
12762 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
12763 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
12764 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
12765 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
12767 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
12768 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
12769 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
12770 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
12772 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
12774 (when (featurep 'xemacs)
12775 (org-defkey org-mode-map 'button3 'popup-mode-menu))
12777 (defvar org-table-auto-blank-field) ; defined in org-table.el
12778 (defun org-self-insert-command (N)
12779 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
12780 If the cursor is in a table looking at whitespace, the whitespace is
12781 overwritten, and the table is not marked as requiring realignment."
12782 (interactive "p")
12783 (if (and (org-table-p)
12784 (progn
12785 ;; check if we blank the field, and if that triggers align
12786 (and (featurep 'org-table) org-table-auto-blank-field
12787 (member last-command
12788 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
12789 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
12790 ;; got extra space, this field does not determine column width
12791 (let (org-table-may-need-update) (org-table-blank-field))
12792 ;; no extra space, this field may determine column width
12793 (org-table-blank-field)))
12795 (eq N 1)
12796 (looking-at "[^|\n]* |"))
12797 (let (org-table-may-need-update)
12798 (goto-char (1- (match-end 0)))
12799 (delete-backward-char 1)
12800 (goto-char (match-beginning 0))
12801 (self-insert-command N))
12802 (setq org-table-may-need-update t)
12803 (self-insert-command N)
12804 (org-fix-tags-on-the-fly)))
12806 (defun org-fix-tags-on-the-fly ()
12807 (when (and (equal (char-after (point-at-bol)) ?*)
12808 (org-on-heading-p))
12809 (org-align-tags-here org-tags-column)))
12811 (defun org-delete-backward-char (N)
12812 "Like `delete-backward-char', insert whitespace at field end in tables.
12813 When deleting backwards, in tables this function will insert whitespace in
12814 front of the next \"|\" separator, to keep the table aligned. The table will
12815 still be marked for re-alignment if the field did fill the entire column,
12816 because, in this case the deletion might narrow the column."
12817 (interactive "p")
12818 (if (and (org-table-p)
12819 (eq N 1)
12820 (string-match "|" (buffer-substring (point-at-bol) (point)))
12821 (looking-at ".*?|"))
12822 (let ((pos (point))
12823 (noalign (looking-at "[^|\n\r]* |"))
12824 (c org-table-may-need-update))
12825 (backward-delete-char N)
12826 (skip-chars-forward "^|")
12827 (insert " ")
12828 (goto-char (1- pos))
12829 ;; noalign: if there were two spaces at the end, this field
12830 ;; does not determine the width of the column.
12831 (if noalign (setq org-table-may-need-update c)))
12832 (backward-delete-char N)
12833 (org-fix-tags-on-the-fly)))
12835 (defun org-delete-char (N)
12836 "Like `delete-char', but insert whitespace at field end in tables.
12837 When deleting characters, in tables this function will insert whitespace in
12838 front of the next \"|\" separator, to keep the table aligned. The table will
12839 still be marked for re-alignment if the field did fill the entire column,
12840 because, in this case the deletion might narrow the column."
12841 (interactive "p")
12842 (if (and (org-table-p)
12843 (not (bolp))
12844 (not (= (char-after) ?|))
12845 (eq N 1))
12846 (if (looking-at ".*?|")
12847 (let ((pos (point))
12848 (noalign (looking-at "[^|\n\r]* |"))
12849 (c org-table-may-need-update))
12850 (replace-match (concat
12851 (substring (match-string 0) 1 -1)
12852 " |"))
12853 (goto-char pos)
12854 ;; noalign: if there were two spaces at the end, this field
12855 ;; does not determine the width of the column.
12856 (if noalign (setq org-table-may-need-update c)))
12857 (delete-char N))
12858 (delete-char N)
12859 (org-fix-tags-on-the-fly)))
12861 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
12862 (put 'org-self-insert-command 'delete-selection t)
12863 (put 'orgtbl-self-insert-command 'delete-selection t)
12864 (put 'org-delete-char 'delete-selection 'supersede)
12865 (put 'org-delete-backward-char 'delete-selection 'supersede)
12866 (put 'org-yank 'delete-selection 'yank)
12868 ;; Make `flyspell-mode' delay after some commands
12869 (put 'org-self-insert-command 'flyspell-delayed t)
12870 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
12871 (put 'org-delete-char 'flyspell-delayed t)
12872 (put 'org-delete-backward-char 'flyspell-delayed t)
12874 ;; Make pabbrev-mode expand after org-mode commands
12875 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
12876 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
12878 ;; How to do this: Measure non-white length of current string
12879 ;; If equal to column width, we should realign.
12881 (defun org-remap (map &rest commands)
12882 "In MAP, remap the functions given in COMMANDS.
12883 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
12884 (let (new old)
12885 (while commands
12886 (setq old (pop commands) new (pop commands))
12887 (if (fboundp 'command-remapping)
12888 (org-defkey map (vector 'remap old) new)
12889 (substitute-key-definition old new map global-map)))))
12891 (when (eq org-enable-table-editor 'optimized)
12892 ;; If the user wants maximum table support, we need to hijack
12893 ;; some standard editing functions
12894 (org-remap org-mode-map
12895 'self-insert-command 'org-self-insert-command
12896 'delete-char 'org-delete-char
12897 'delete-backward-char 'org-delete-backward-char)
12898 (org-defkey org-mode-map "|" 'org-force-self-insert))
12900 (defun org-shiftcursor-error ()
12901 "Throw an error because Shift-Cursor command was applied in wrong context."
12902 (error "This command is active in special context like tables, headlines or timestamps"))
12904 (defun org-shifttab (&optional arg)
12905 "Global visibility cycling or move to previous table field.
12906 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
12907 on context.
12908 See the individual commands for more information."
12909 (interactive "P")
12910 (cond
12911 ((org-at-table-p) (call-interactively 'org-table-previous-field))
12912 ((integerp arg)
12913 (message "Content view to level: %d" arg)
12914 (org-content (prefix-numeric-value arg))
12915 (setq org-cycle-global-status 'overview))
12916 (t (call-interactively 'org-global-cycle))))
12918 (defun org-shiftmetaleft ()
12919 "Promote subtree or delete table column.
12920 Calls `org-promote-subtree', `org-outdent-item',
12921 or `org-table-delete-column', depending on context.
12922 See the individual commands for more information."
12923 (interactive)
12924 (cond
12925 ((org-at-table-p) (call-interactively 'org-table-delete-column))
12926 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
12927 ((org-at-item-p) (call-interactively 'org-outdent-item))
12928 (t (org-shiftcursor-error))))
12930 (defun org-shiftmetaright ()
12931 "Demote subtree or insert table column.
12932 Calls `org-demote-subtree', `org-indent-item',
12933 or `org-table-insert-column', depending on context.
12934 See the individual commands for more information."
12935 (interactive)
12936 (cond
12937 ((org-at-table-p) (call-interactively 'org-table-insert-column))
12938 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
12939 ((org-at-item-p) (call-interactively 'org-indent-item))
12940 (t (org-shiftcursor-error))))
12942 (defun org-shiftmetaup (&optional arg)
12943 "Move subtree up or kill table row.
12944 Calls `org-move-subtree-up' or `org-table-kill-row' or
12945 `org-move-item-up' depending on context. See the individual commands
12946 for more information."
12947 (interactive "P")
12948 (cond
12949 ((org-at-table-p) (call-interactively 'org-table-kill-row))
12950 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12951 ((org-at-item-p) (call-interactively 'org-move-item-up))
12952 (t (org-shiftcursor-error))))
12953 (defun org-shiftmetadown (&optional arg)
12954 "Move subtree down or insert table row.
12955 Calls `org-move-subtree-down' or `org-table-insert-row' or
12956 `org-move-item-down', depending on context. See the individual
12957 commands for more information."
12958 (interactive "P")
12959 (cond
12960 ((org-at-table-p) (call-interactively 'org-table-insert-row))
12961 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12962 ((org-at-item-p) (call-interactively 'org-move-item-down))
12963 (t (org-shiftcursor-error))))
12965 (defun org-metaleft (&optional arg)
12966 "Promote heading or move table column to left.
12967 Calls `org-do-promote' or `org-table-move-column', depending on context.
12968 With no specific context, calls the Emacs default `backward-word'.
12969 See the individual commands for more information."
12970 (interactive "P")
12971 (cond
12972 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
12973 ((or (org-on-heading-p) (org-region-active-p))
12974 (call-interactively 'org-do-promote))
12975 ((org-at-item-p) (call-interactively 'org-outdent-item))
12976 (t (call-interactively 'backward-word))))
12978 (defun org-metaright (&optional arg)
12979 "Demote subtree or move table column to right.
12980 Calls `org-do-demote' or `org-table-move-column', depending on context.
12981 With no specific context, calls the Emacs default `forward-word'.
12982 See the individual commands for more information."
12983 (interactive "P")
12984 (cond
12985 ((org-at-table-p) (call-interactively 'org-table-move-column))
12986 ((or (org-on-heading-p) (org-region-active-p))
12987 (call-interactively 'org-do-demote))
12988 ((org-at-item-p) (call-interactively 'org-indent-item))
12989 (t (call-interactively 'forward-word))))
12991 (defun org-metaup (&optional arg)
12992 "Move subtree up or move table row up.
12993 Calls `org-move-subtree-up' or `org-table-move-row' or
12994 `org-move-item-up', depending on context. See the individual commands
12995 for more information."
12996 (interactive "P")
12997 (cond
12998 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
12999 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
13000 ((org-at-item-p) (call-interactively 'org-move-item-up))
13001 (t (transpose-lines 1) (beginning-of-line -1))))
13003 (defun org-metadown (&optional arg)
13004 "Move subtree down or move table row down.
13005 Calls `org-move-subtree-down' or `org-table-move-row' or
13006 `org-move-item-down', depending on context. See the individual
13007 commands for more information."
13008 (interactive "P")
13009 (cond
13010 ((org-at-table-p) (call-interactively 'org-table-move-row))
13011 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
13012 ((org-at-item-p) (call-interactively 'org-move-item-down))
13013 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
13015 (defun org-shiftup (&optional arg)
13016 "Increase item in timestamp or increase priority of current headline.
13017 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
13018 depending on context. See the individual commands for more information."
13019 (interactive "P")
13020 (cond
13021 ((org-at-timestamp-p t)
13022 (call-interactively (if org-edit-timestamp-down-means-later
13023 'org-timestamp-down 'org-timestamp-up)))
13024 ((org-on-heading-p) (call-interactively 'org-priority-up))
13025 ((org-at-item-p) (call-interactively 'org-previous-item))
13026 ((org-clocktable-try-shift 'up arg))
13027 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
13029 (defun org-shiftdown (&optional arg)
13030 "Decrease item in timestamp or decrease priority of current headline.
13031 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
13032 depending on context. See the individual commands for more information."
13033 (interactive "P")
13034 (cond
13035 ((org-at-timestamp-p t)
13036 (call-interactively (if org-edit-timestamp-down-means-later
13037 'org-timestamp-up 'org-timestamp-down)))
13038 ((org-on-heading-p) (call-interactively 'org-priority-down))
13039 ((org-clocktable-try-shift 'down arg))
13040 (t (call-interactively 'org-next-item))))
13042 (defun org-shiftright (&optional arg)
13043 "Cycle the thing at point or in the current line, depending on context.
13044 Depending on context, this does one of the following:
13046 - switch a timestamp at point one day into the future
13047 - on a headline, switch to the next TODO keyword.
13048 - on an item, switch entire list to the next bullet type
13049 - on a property line, switch to the next allowed value
13050 - on a clocktable definition line, move time block into the future"
13051 (interactive "P")
13052 (cond
13053 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
13054 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
13055 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
13056 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
13057 ((org-clocktable-try-shift 'right arg))
13058 (t (org-shiftcursor-error))))
13060 (defun org-shiftleft (&optional arg)
13061 "Cycle the thing at point or in the current line, depending on context.
13062 Depending on context, this does one of the following:
13064 - switch a timestamp at point one day into the past
13065 - on a headline, switch to the previous TODO keyword.
13066 - on an item, switch entire list to the previous bullet type
13067 - on a property line, switch to the previous allowed value
13068 - on a clocktable definition line, move time block into the past"
13069 (interactive "P")
13070 (cond
13071 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
13072 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
13073 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
13074 ((org-at-property-p)
13075 (call-interactively 'org-property-previous-allowed-value))
13076 ((org-clocktable-try-shift 'left arg))
13077 (t (org-shiftcursor-error))))
13079 (defun org-shiftcontrolright ()
13080 "Switch to next TODO set."
13081 (interactive)
13082 (cond
13083 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
13084 (t (org-shiftcursor-error))))
13086 (defun org-shiftcontrolleft ()
13087 "Switch to previous TODO set."
13088 (interactive)
13089 (cond
13090 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
13091 (t (org-shiftcursor-error))))
13093 (defun org-ctrl-c-ret ()
13094 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
13095 (interactive)
13096 (cond
13097 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
13098 (t (call-interactively 'org-insert-heading))))
13100 (defun org-copy-special ()
13101 "Copy region in table or copy current subtree.
13102 Calls `org-table-copy' or `org-copy-subtree', depending on context.
13103 See the individual commands for more information."
13104 (interactive)
13105 (call-interactively
13106 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
13108 (defun org-cut-special ()
13109 "Cut region in table or cut current subtree.
13110 Calls `org-table-copy' or `org-cut-subtree', depending on context.
13111 See the individual commands for more information."
13112 (interactive)
13113 (call-interactively
13114 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
13116 (defun org-paste-special (arg)
13117 "Paste rectangular region into table, or past subtree relative to level.
13118 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
13119 See the individual commands for more information."
13120 (interactive "P")
13121 (if (org-at-table-p)
13122 (org-table-paste-rectangle)
13123 (org-paste-subtree arg)))
13125 (defun org-edit-special ()
13126 "Call a special editor for the stuff at point.
13127 When at a table, call the formula editor with `org-table-edit-formulas'.
13128 When at the first line of an src example, call `org-edit-src-code'.
13129 When in an #+include line, visit the include file. Otherwise call
13130 `ffap' to visit the file at point."
13131 (interactive)
13132 (cond
13133 ((org-at-table-p)
13134 (call-interactively 'org-table-edit-formulas))
13135 ((save-excursion
13136 (beginning-of-line 1)
13137 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
13138 (find-file (org-trim (match-string 1))))
13139 ((org-edit-src-code))
13140 ((org-edit-fixed-width-region))
13141 (t (call-interactively 'ffap))))
13143 (defun org-ctrl-c-ctrl-c (&optional arg)
13144 "Set tags in headline, or update according to changed information at point.
13146 This command does many different things, depending on context:
13148 - If the cursor is in a headline, prompt for tags and insert them
13149 into the current line, aligned to `org-tags-column'. When called
13150 with prefix arg, realign all tags in the current buffer.
13152 - If the cursor is in one of the special #+KEYWORD lines, this
13153 triggers scanning the buffer for these lines and updating the
13154 information.
13156 - If the cursor is inside a table, realign the table. This command
13157 works even if the automatic table editor has been turned off.
13159 - If the cursor is on a #+TBLFM line, re-apply the formulas to
13160 the entire table.
13162 - If the cursor is at a footnote reference or definition, jump to
13163 the corresponding definition or references, respectively.
13165 - If the cursor is a the beginning of a dynamic block, update it.
13167 - If the cursor is inside a table created by the table.el package,
13168 activate that table.
13170 - If the current buffer is a remember buffer, close note and file
13171 it. A prefix argument of 1 files to the default location
13172 without further interaction. A prefix argument of 2 files to
13173 the currently clocking task.
13175 - If the cursor is on a <<<target>>>, update radio targets and corresponding
13176 links in this buffer.
13178 - If the cursor is on a numbered item in a plain list, renumber the
13179 ordered list.
13181 - If the cursor is on a checkbox, toggle it."
13182 (interactive "P")
13183 (let ((org-enable-table-editor t))
13184 (cond
13185 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
13186 org-occur-highlights
13187 org-latex-fragment-image-overlays)
13188 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
13189 (org-remove-occur-highlights)
13190 (org-remove-latex-fragment-image-overlays)
13191 (message "Temporary highlights/overlays removed from current buffer"))
13192 ((and (local-variable-p 'org-finish-function (current-buffer))
13193 (fboundp org-finish-function))
13194 (funcall org-finish-function))
13195 ((org-at-property-p)
13196 (call-interactively 'org-property-action))
13197 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
13198 ((org-on-heading-p) (call-interactively 'org-set-tags))
13199 ((org-at-table.el-p)
13200 (require 'table)
13201 (beginning-of-line 1)
13202 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
13203 (call-interactively 'table-recognize-table))
13204 ((org-at-table-p)
13205 (org-table-maybe-eval-formula)
13206 (if arg
13207 (call-interactively 'org-table-recalculate)
13208 (org-table-maybe-recalculate-line))
13209 (call-interactively 'org-table-align))
13210 ((or (org-footnote-at-reference-p)
13211 (org-footnote-at-definition-p))
13212 (call-interactively 'org-footnote-action))
13213 ((org-at-item-checkbox-p)
13214 (call-interactively 'org-toggle-checkbox))
13215 ((org-at-item-p)
13216 (call-interactively 'org-maybe-renumber-ordered-list))
13217 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
13218 ;; Dynamic block
13219 (beginning-of-line 1)
13220 (save-excursion (org-update-dblock)))
13221 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
13222 (cond
13223 ((equal (match-string 1) "TBLFM")
13224 ;; Recalculate the table before this line
13225 (save-excursion
13226 (beginning-of-line 1)
13227 (skip-chars-backward " \r\n\t")
13228 (if (org-at-table-p)
13229 (org-call-with-arg 'org-table-recalculate t))))
13231 ; (org-set-regexps-and-options)
13232 ; (org-restart-font-lock)
13233 (let ((org-inhibit-startup t)) (org-mode-restart))
13234 (message "Local setup has been refreshed"))))
13235 (t (error "C-c C-c can do nothing useful at this location.")))))
13237 (defun org-mode-restart ()
13238 "Restart Org-mode, to scan again for special lines.
13239 Also updates the keyword regular expressions."
13240 (interactive)
13241 (org-mode)
13242 (message "Org-mode restarted"))
13244 (defun org-kill-note-or-show-branches ()
13245 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
13246 (interactive)
13247 (if (not org-finish-function)
13248 (call-interactively 'show-branches)
13249 (let ((org-note-abort t))
13250 (funcall org-finish-function))))
13252 (defun org-return (&optional indent)
13253 "Goto next table row or insert a newline.
13254 Calls `org-table-next-row' or `newline', depending on context.
13255 See the individual commands for more information."
13256 (interactive)
13257 (cond
13258 ((bobp) (if indent (newline-and-indent) (newline)))
13259 ((and (org-at-heading-p)
13260 (looking-at
13261 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
13262 (org-show-entry)
13263 (end-of-line 1)
13264 (newline))
13265 ((org-at-table-p)
13266 (org-table-justify-field-maybe)
13267 (call-interactively 'org-table-next-row))
13268 (t (if indent (newline-and-indent) (newline)))))
13270 (defun org-return-indent ()
13271 "Goto next table row or insert a newline and indent.
13272 Calls `org-table-next-row' or `newline-and-indent', depending on
13273 context. See the individual commands for more information."
13274 (interactive)
13275 (org-return t))
13277 (defun org-ctrl-c-star ()
13278 "Compute table, or change heading status of lines.
13279 Calls `org-table-recalculate' or `org-toggle-heading',
13280 depending on context."
13281 (interactive)
13282 (cond
13283 ((org-at-table-p)
13284 (call-interactively 'org-table-recalculate))
13286 ;; Convert all lines in region to list items
13287 (call-interactively 'org-toggle-heading))))
13289 (defun org-ctrl-c-minus ()
13290 "Insert separator line in table or modify bullet status of line.
13291 Also turns a plain line or a region of lines into list items.
13292 Calls `org-table-insert-hline', `org-toggle-item', or
13293 `org-cycle-list-bullet', depending on context."
13294 (interactive)
13295 (cond
13296 ((org-at-table-p)
13297 (call-interactively 'org-table-insert-hline))
13298 ((org-region-active-p)
13299 (call-interactively 'org-toggle-item))
13300 ((org-in-item-p)
13301 (call-interactively 'org-cycle-list-bullet))
13303 (call-interactively 'org-toggle-item))))
13305 (defun org-toggle-item ()
13306 "Convert headings or normal lines to items, items to normal lines.
13307 If there is no active region, only the current line is considered.
13309 If the first line in the region is a headline, convert all headlines to items.
13311 If the first line in the region is an item, convert all items to normal lines.
13313 If the first line is normal text, add an item bullet to each line."
13314 (interactive)
13315 (let (l2 l beg end)
13316 (if (org-region-active-p)
13317 (setq beg (region-beginning) end (region-end))
13318 (setq beg (point-at-bol)
13319 end (min (1+ (point-at-eol)) (point-max))))
13320 (save-excursion
13321 (goto-char end)
13322 (setq l2 (org-current-line))
13323 (goto-char beg)
13324 (beginning-of-line 1)
13325 (setq l (1- (org-current-line)))
13326 (if (org-at-item-p)
13327 ;; We already have items, de-itemize
13328 (while (< (setq l (1+ l)) l2)
13329 (when (org-at-item-p)
13330 (goto-char (match-beginning 2))
13331 (delete-region (match-beginning 2) (match-end 2))
13332 (and (looking-at "[ \t]+") (replace-match "")))
13333 (beginning-of-line 2))
13334 (if (org-on-heading-p)
13335 ;; Headings, convert to items
13336 (while (< (setq l (1+ l)) l2)
13337 (if (looking-at org-outline-regexp)
13338 (replace-match "- " t t))
13339 (beginning-of-line 2))
13340 ;; normal lines, turn them into items
13341 (while (< (setq l (1+ l)) l2)
13342 (unless (org-at-item-p)
13343 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
13344 (replace-match "\\1- \\2")))
13345 (beginning-of-line 2)))))))
13347 (defun org-toggle-heading (&optional nstars)
13348 "Convert headings to normal text, or items or text to headings.
13349 If there is no active region, only the current line is considered.
13351 If the first line is a heading, remove the stars from all headlines
13352 in the region.
13354 If the first line is a plain list item, turn all plain list items into
13355 headings.
13357 If the first line is a normal line, turn each and every line in the region
13358 into a heading.
13360 When converting a line into a heading, the number of stars is chosen
13361 such that the lines become children of the current entry. However, when
13362 a prefix argument is given, its value determines the number of stars to add."
13363 (interactive "P")
13364 (let (l2 l itemp beg end)
13365 (if (org-region-active-p)
13366 (setq beg (region-beginning) end (region-end))
13367 (setq beg (point-at-bol)
13368 end (min (1+ (point-at-eol)) (point-max))))
13369 (save-excursion
13370 (goto-char end)
13371 (setq l2 (org-current-line))
13372 (goto-char beg)
13373 (beginning-of-line 1)
13374 (setq l (1- (org-current-line)))
13375 (if (org-on-heading-p)
13376 ;; We already have headlines, de-star them
13377 (while (< (setq l (1+ l)) l2)
13378 (when (org-on-heading-p t)
13379 (and (looking-at outline-regexp) (replace-match "")))
13380 (beginning-of-line 2))
13381 (setq itemp (org-at-item-p))
13382 (let* ((stars
13383 (if nstars
13384 (make-string (prefix-numeric-value current-prefix-arg)
13386 (save-excursion
13387 (re-search-backward org-complex-heading-regexp nil t)
13388 (or (match-string 1) "*"))))
13389 (add-stars (if nstars "" (if org-odd-levels-only "**" "*")))
13390 (rpl (concat stars add-stars " ")))
13391 (while (< (setq l (1+ l)) l2)
13392 (if itemp
13393 (and (org-at-item-p) (replace-match rpl t t))
13394 (unless (org-on-heading-p)
13395 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
13396 (replace-match (concat rpl (match-string 2))))))
13397 (beginning-of-line 2)))))))
13399 (defun org-meta-return (&optional arg)
13400 "Insert a new heading or wrap a region in a table.
13401 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
13402 See the individual commands for more information."
13403 (interactive "P")
13404 (cond
13405 ((org-at-table-p)
13406 (call-interactively 'org-table-wrap-region))
13407 (t (call-interactively 'org-insert-heading))))
13409 ;;; Menu entries
13411 ;; Define the Org-mode menus
13412 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
13413 '("Tbl"
13414 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
13415 ["Next Field" org-cycle (org-at-table-p)]
13416 ["Previous Field" org-shifttab (org-at-table-p)]
13417 ["Next Row" org-return (org-at-table-p)]
13418 "--"
13419 ["Blank Field" org-table-blank-field (org-at-table-p)]
13420 ["Edit Field" org-table-edit-field (org-at-table-p)]
13421 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
13422 "--"
13423 ("Column"
13424 ["Move Column Left" org-metaleft (org-at-table-p)]
13425 ["Move Column Right" org-metaright (org-at-table-p)]
13426 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
13427 ["Insert Column" org-shiftmetaright (org-at-table-p)])
13428 ("Row"
13429 ["Move Row Up" org-metaup (org-at-table-p)]
13430 ["Move Row Down" org-metadown (org-at-table-p)]
13431 ["Delete Row" org-shiftmetaup (org-at-table-p)]
13432 ["Insert Row" org-shiftmetadown (org-at-table-p)]
13433 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
13434 "--"
13435 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
13436 ("Rectangle"
13437 ["Copy Rectangle" org-copy-special (org-at-table-p)]
13438 ["Cut Rectangle" org-cut-special (org-at-table-p)]
13439 ["Paste Rectangle" org-paste-special (org-at-table-p)]
13440 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
13441 "--"
13442 ("Calculate"
13443 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
13444 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
13445 ["Edit Formulas" org-edit-special (org-at-table-p)]
13446 "--"
13447 ["Recalculate line" org-table-recalculate (org-at-table-p)]
13448 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
13449 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
13450 "--"
13451 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
13452 "--"
13453 ["Sum Column/Rectangle" org-table-sum
13454 (or (org-at-table-p) (org-region-active-p))]
13455 ["Which Column?" org-table-current-column (org-at-table-p)])
13456 ["Debug Formulas"
13457 org-table-toggle-formula-debugger
13458 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
13459 ["Show Col/Row Numbers"
13460 org-table-toggle-coordinate-overlays
13461 :style toggle
13462 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
13463 "--"
13464 ["Create" org-table-create (and (not (org-at-table-p))
13465 org-enable-table-editor)]
13466 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
13467 ["Import from File" org-table-import (not (org-at-table-p))]
13468 ["Export to File" org-table-export (org-at-table-p)]
13469 "--"
13470 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
13472 (easy-menu-define org-org-menu org-mode-map "Org menu"
13473 '("Org"
13474 ("Show/Hide"
13475 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
13476 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
13477 ["Sparse Tree..." org-sparse-tree t]
13478 ["Reveal Context" org-reveal t]
13479 ["Show All" show-all t]
13480 "--"
13481 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
13482 "--"
13483 ["New Heading" org-insert-heading t]
13484 ("Navigate Headings"
13485 ["Up" outline-up-heading t]
13486 ["Next" outline-next-visible-heading t]
13487 ["Previous" outline-previous-visible-heading t]
13488 ["Next Same Level" outline-forward-same-level t]
13489 ["Previous Same Level" outline-backward-same-level t]
13490 "--"
13491 ["Jump" org-goto t])
13492 ("Edit Structure"
13493 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
13494 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
13495 "--"
13496 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
13497 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
13498 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
13499 "--"
13500 ["Promote Heading" org-metaleft (not (org-at-table-p))]
13501 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
13502 ["Demote Heading" org-metaright (not (org-at-table-p))]
13503 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
13504 "--"
13505 ["Sort Region/Children" org-sort (not (org-at-table-p))]
13506 "--"
13507 ["Convert to odd levels" org-convert-to-odd-levels t]
13508 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
13509 ("Editing"
13510 ["Emphasis..." org-emphasize t]
13511 ["Edit Source Example" org-edit-special t]
13512 "--"
13513 ["Footnote new/jump" org-footnote-action t]
13514 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
13515 ("Archive"
13516 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
13517 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
13518 ; :active t :keys "C-u C-c C-x C-a"]
13519 ["Sparse trees open ARCHIVE trees"
13520 (setq org-sparse-tree-open-archived-trees
13521 (not org-sparse-tree-open-archived-trees))
13522 :style toggle :selected org-sparse-tree-open-archived-trees]
13523 ["Cycling opens ARCHIVE trees"
13524 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
13525 :style toggle :selected org-cycle-open-archived-trees]
13526 "--"
13527 ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
13528 ["Move Subtree to Archive" org-advertized-archive-subtree t]
13529 ; ["Check and Move Children" (org-archive-subtree '(4))
13530 ; :active t :keys "C-u C-c C-x C-s"]
13532 "--"
13533 ("TODO Lists"
13534 ["TODO/DONE/-" org-todo t]
13535 ("Select keyword"
13536 ["Next keyword" org-shiftright (org-on-heading-p)]
13537 ["Previous keyword" org-shiftleft (org-on-heading-p)]
13538 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
13539 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
13540 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
13541 ["Show TODO Tree" org-show-todo-tree t]
13542 ["Global TODO list" org-todo-list t]
13543 "--"
13544 ["Set Priority" org-priority t]
13545 ["Priority Up" org-shiftup t]
13546 ["Priority Down" org-shiftdown t])
13547 ("TAGS and Properties"
13548 ["Set Tags" org-set-tags-command t]
13549 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
13550 "--"
13551 ["Set property" org-set-property t]
13552 ["Column view of properties" org-columns t]
13553 ["Insert Column View DBlock" org-insert-columns-dblock t])
13554 ("Dates and Scheduling"
13555 ["Timestamp" org-time-stamp t]
13556 ["Timestamp (inactive)" org-time-stamp-inactive t]
13557 ("Change Date"
13558 ["1 Day Later" org-shiftright t]
13559 ["1 Day Earlier" org-shiftleft t]
13560 ["1 ... Later" org-shiftup t]
13561 ["1 ... Earlier" org-shiftdown t])
13562 ["Compute Time Range" org-evaluate-time-range t]
13563 ["Schedule Item" org-schedule t]
13564 ["Deadline" org-deadline t]
13565 "--"
13566 ["Custom time format" org-toggle-time-stamp-overlays
13567 :style radio :selected org-display-custom-times]
13568 "--"
13569 ["Goto Calendar" org-goto-calendar t]
13570 ["Date from Calendar" org-date-from-calendar t]
13571 "--"
13572 ["Start/Restart Timer" org-timer-start t]
13573 ["Pause/Continue Timer" org-timer-pause-or-continue t]
13574 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
13575 ["Insert Timer String" org-timer t]
13576 ["Insert Timer Item" org-timer-item t])
13577 ("Logging work"
13578 ["Clock in" org-clock-in t]
13579 ["Clock out" org-clock-out t]
13580 ["Clock cancel" org-clock-cancel t]
13581 ["Goto running clock" org-clock-goto t]
13582 ["Display times" org-clock-display t]
13583 ["Create clock table" org-clock-report t]
13584 "--"
13585 ["Record DONE time"
13586 (progn (setq org-log-done (not org-log-done))
13587 (message "Switching to %s will %s record a timestamp"
13588 (car org-done-keywords)
13589 (if org-log-done "automatically" "not")))
13590 :style toggle :selected org-log-done])
13591 "--"
13592 ["Agenda Command..." org-agenda t]
13593 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
13594 ("File List for Agenda")
13595 ("Special views current file"
13596 ["TODO Tree" org-show-todo-tree t]
13597 ["Check Deadlines" org-check-deadlines t]
13598 ["Timeline" org-timeline t]
13599 ["Tags Tree" org-tags-sparse-tree t])
13600 "--"
13601 ("Hyperlinks"
13602 ["Store Link (Global)" org-store-link t]
13603 ["Insert Link" org-insert-link t]
13604 ["Follow Link" org-open-at-point t]
13605 "--"
13606 ["Next link" org-next-link t]
13607 ["Previous link" org-previous-link t]
13608 "--"
13609 ["Descriptive Links"
13610 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
13611 :style radio
13612 :selected (member '(org-link) buffer-invisibility-spec)]
13613 ["Literal Links"
13614 (progn
13615 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
13616 :style radio
13617 :selected (not (member '(org-link) buffer-invisibility-spec))])
13618 "--"
13619 ["Export/Publish..." org-export t]
13620 ("LaTeX"
13621 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
13622 :selected org-cdlatex-mode]
13623 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
13624 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
13625 ["Modify math symbol" org-cdlatex-math-modify
13626 (org-inside-LaTeX-fragment-p)]
13627 ["Export LaTeX fragments as images"
13628 (if (featurep 'org-exp)
13629 (setq org-export-with-LaTeX-fragments
13630 (not org-export-with-LaTeX-fragments))
13631 (require 'org-exp))
13632 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
13633 org-export-with-LaTeX-fragments)])
13634 "--"
13635 ("Documentation"
13636 ["Show Version" org-version t]
13637 ["Info Documentation" org-info t])
13638 ("Customize"
13639 ["Browse Org Group" org-customize t]
13640 "--"
13641 ["Expand This Menu" org-create-customize-menu
13642 (fboundp 'customize-menu-create)])
13643 "--"
13644 ["Refresh setup" org-mode-restart t]
13647 (defun org-info (&optional node)
13648 "Read documentation for Org-mode in the info system.
13649 With optional NODE, go directly to that node."
13650 (interactive)
13651 (info (format "(org)%s" (or node ""))))
13653 (defun org-install-agenda-files-menu ()
13654 (let ((bl (buffer-list)))
13655 (save-excursion
13656 (while bl
13657 (set-buffer (pop bl))
13658 (if (org-mode-p) (setq bl nil)))
13659 (when (org-mode-p)
13660 (easy-menu-change
13661 '("Org") "File List for Agenda"
13662 (append
13663 (list
13664 ["Edit File List" (org-edit-agenda-file-list) t]
13665 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
13666 ["Remove Current File from List" org-remove-file t]
13667 ["Cycle through agenda files" org-cycle-agenda-files t]
13668 ["Occur in all agenda files" org-occur-in-agenda-files t]
13669 "--")
13670 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
13672 ;;;; Documentation
13674 ;;;###autoload
13675 (defun org-require-autoloaded-modules ()
13676 (interactive)
13677 (mapc 'require
13678 '(org-agenda org-archive org-clock org-colview
13679 org-exp org-id org-export-latex org-publish
13680 org-remember org-table)))
13682 ;;;###autoload
13683 (defun org-customize ()
13684 "Call the customize function with org as argument."
13685 (interactive)
13686 (org-load-modules-maybe)
13687 (org-require-autoloaded-modules)
13688 (customize-browse 'org))
13690 (defun org-create-customize-menu ()
13691 "Create a full customization menu for Org-mode, insert it into the menu."
13692 (interactive)
13693 (org-load-modules-maybe)
13694 (org-require-autoloaded-modules)
13695 (if (fboundp 'customize-menu-create)
13696 (progn
13697 (easy-menu-change
13698 '("Org") "Customize"
13699 `(["Browse Org group" org-customize t]
13700 "--"
13701 ,(customize-menu-create 'org)
13702 ["Set" Custom-set t]
13703 ["Save" Custom-save t]
13704 ["Reset to Current" Custom-reset-current t]
13705 ["Reset to Saved" Custom-reset-saved t]
13706 ["Reset to Standard Settings" Custom-reset-standard t]))
13707 (message "\"Org\"-menu now contains full customization menu"))
13708 (error "Cannot expand menu (outdated version of cus-edit.el)")))
13710 ;;;; Miscellaneous stuff
13712 ;;; Generally useful functions
13714 (defun org-find-text-property-in-string (prop s)
13715 "Return the first non-nil value of property PROP in string S."
13716 (or (get-text-property 0 prop s)
13717 (get-text-property (or (next-single-property-change 0 prop s) 0)
13718 prop s)))
13720 (defun org-display-warning (message) ;; Copied from Emacs-Muse
13721 "Display the given MESSAGE as a warning."
13722 (if (fboundp 'display-warning)
13723 (display-warning 'org message
13724 (if (featurep 'xemacs)
13725 'warning
13726 :warning))
13727 (let ((buf (get-buffer-create "*Org warnings*")))
13728 (with-current-buffer buf
13729 (goto-char (point-max))
13730 (insert "Warning (Org): " message)
13731 (unless (bolp)
13732 (newline)))
13733 (display-buffer buf)
13734 (sit-for 0))))
13736 (defun org-goto-marker-or-bmk (marker &optional bookmark)
13737 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
13738 (if (and marker (marker-buffer marker)
13739 (buffer-live-p (marker-buffer marker)))
13740 (progn
13741 (switch-to-buffer (marker-buffer marker))
13742 (if (or (> marker (point-max)) (< marker (point-min)))
13743 (widen))
13744 (goto-char marker)
13745 (org-show-context 'org-goto))
13746 (if bookmark
13747 (bookmark-jump bookmark)
13748 (error "Cannot find location"))))
13750 (defun org-quote-csv-field (s)
13751 "Quote field for inclusion in CSV material."
13752 (if (string-match "[\",]" s)
13753 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
13756 (defun org-plist-delete (plist property)
13757 "Delete PROPERTY from PLIST.
13758 This is in contrast to merely setting it to 0."
13759 (let (p)
13760 (while plist
13761 (if (not (eq property (car plist)))
13762 (setq p (plist-put p (car plist) (nth 1 plist))))
13763 (setq plist (cddr plist)))
13766 (defun org-force-self-insert (N)
13767 "Needed to enforce self-insert under remapping."
13768 (interactive "p")
13769 (self-insert-command N))
13771 (defun org-string-width (s)
13772 "Compute width of string, ignoring invisible characters.
13773 This ignores character with invisibility property `org-link', and also
13774 characters with property `org-cwidth', because these will become invisible
13775 upon the next fontification round."
13776 (let (b l)
13777 (when (or (eq t buffer-invisibility-spec)
13778 (assq 'org-link buffer-invisibility-spec))
13779 (while (setq b (text-property-any 0 (length s)
13780 'invisible 'org-link s))
13781 (setq s (concat (substring s 0 b)
13782 (substring s (or (next-single-property-change
13783 b 'invisible s) (length s)))))))
13784 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
13785 (setq s (concat (substring s 0 b)
13786 (substring s (or (next-single-property-change
13787 b 'org-cwidth s) (length s))))))
13788 (setq l (string-width s) b -1)
13789 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
13790 (setq l (- l (get-text-property b 'org-dwidth-n s))))
13793 (defun org-get-indentation (&optional line)
13794 "Get the indentation of the current line, interpreting tabs.
13795 When LINE is given, assume it represents a line and compute its indentation."
13796 (if line
13797 (if (string-match "^ *" (org-remove-tabs line))
13798 (match-end 0))
13799 (save-excursion
13800 (beginning-of-line 1)
13801 (skip-chars-forward " \t")
13802 (current-column))))
13804 (defun org-remove-tabs (s &optional width)
13805 "Replace tabulators in S with spaces.
13806 Assumes that s is a single line, starting in column 0."
13807 (setq width (or width tab-width))
13808 (while (string-match "\t" s)
13809 (setq s (replace-match
13810 (make-string
13811 (- (* width (/ (+ (match-beginning 0) width) width))
13812 (match-beginning 0)) ?\ )
13813 t t s)))
13816 (defun org-fix-indentation (line ind)
13817 "Fix indentation in LINE.
13818 IND is a cons cell with target and minimum indentation.
13819 If the current indentation in LINE is smaller than the minimum,
13820 leave it alone. If it is larger than ind, set it to the target."
13821 (let* ((l (org-remove-tabs line))
13822 (i (org-get-indentation l))
13823 (i1 (car ind)) (i2 (cdr ind)))
13824 (if (>= i i2) (setq l (substring line i2)))
13825 (if (> i1 0)
13826 (concat (make-string i1 ?\ ) l)
13827 l)))
13829 (defun org-base-buffer (buffer)
13830 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
13831 (if (not buffer)
13832 buffer
13833 (or (buffer-base-buffer buffer)
13834 buffer)))
13836 (defun org-trim (s)
13837 "Remove whitespace at beginning and end of string."
13838 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
13839 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
13842 (defun org-wrap (string &optional width lines)
13843 "Wrap string to either a number of lines, or a width in characters.
13844 If WIDTH is non-nil, the string is wrapped to that width, however many lines
13845 that costs. If there is a word longer than WIDTH, the text is actually
13846 wrapped to the length of that word.
13847 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
13848 many lines, whatever width that takes.
13849 The return value is a list of lines, without newlines at the end."
13850 (let* ((words (org-split-string string "[ \t\n]+"))
13851 (maxword (apply 'max (mapcar 'org-string-width words)))
13852 w ll)
13853 (cond (width
13854 (org-do-wrap words (max maxword width)))
13855 (lines
13856 (setq w maxword)
13857 (setq ll (org-do-wrap words maxword))
13858 (if (<= (length ll) lines)
13860 (setq ll words)
13861 (while (> (length ll) lines)
13862 (setq w (1+ w))
13863 (setq ll (org-do-wrap words w)))
13864 ll))
13865 (t (error "Cannot wrap this")))))
13867 (defun org-do-wrap (words width)
13868 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
13869 (let (lines line)
13870 (while words
13871 (setq line (pop words))
13872 (while (and words (< (+ (length line) (length (car words))) width))
13873 (setq line (concat line " " (pop words))))
13874 (setq lines (push line lines)))
13875 (nreverse lines)))
13877 (defun org-split-string (string &optional separators)
13878 "Splits STRING into substrings at SEPARATORS.
13879 No empty strings are returned if there are matches at the beginning
13880 and end of string."
13881 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
13882 (start 0)
13883 notfirst
13884 (list nil))
13885 (while (and (string-match rexp string
13886 (if (and notfirst
13887 (= start (match-beginning 0))
13888 (< start (length string)))
13889 (1+ start) start))
13890 (< (match-beginning 0) (length string)))
13891 (setq notfirst t)
13892 (or (eq (match-beginning 0) 0)
13893 (and (eq (match-beginning 0) (match-end 0))
13894 (eq (match-beginning 0) start))
13895 (setq list
13896 (cons (substring string start (match-beginning 0))
13897 list)))
13898 (setq start (match-end 0)))
13899 (or (eq start (length string))
13900 (setq list
13901 (cons (substring string start)
13902 list)))
13903 (nreverse list)))
13905 (defun org-context ()
13906 "Return a list of contexts of the current cursor position.
13907 If several contexts apply, all are returned.
13908 Each context entry is a list with a symbol naming the context, and
13909 two positions indicating start and end of the context. Possible
13910 contexts are:
13912 :headline anywhere in a headline
13913 :headline-stars on the leading stars in a headline
13914 :todo-keyword on a TODO keyword (including DONE) in a headline
13915 :tags on the TAGS in a headline
13916 :priority on the priority cookie in a headline
13917 :item on the first line of a plain list item
13918 :item-bullet on the bullet/number of a plain list item
13919 :checkbox on the checkbox in a plain list item
13920 :table in an org-mode table
13921 :table-special on a special filed in a table
13922 :table-table in a table.el table
13923 :link on a hyperlink
13924 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
13925 :target on a <<target>>
13926 :radio-target on a <<<radio-target>>>
13927 :latex-fragment on a LaTeX fragment
13928 :latex-preview on a LaTeX fragment with overlayed preview image
13930 This function expects the position to be visible because it uses font-lock
13931 faces as a help to recognize the following contexts: :table-special, :link,
13932 and :keyword."
13933 (let* ((f (get-text-property (point) 'face))
13934 (faces (if (listp f) f (list f)))
13935 (p (point)) clist o)
13936 ;; First the large context
13937 (cond
13938 ((org-on-heading-p t)
13939 (push (list :headline (point-at-bol) (point-at-eol)) clist)
13940 (when (progn
13941 (beginning-of-line 1)
13942 (looking-at org-todo-line-tags-regexp))
13943 (push (org-point-in-group p 1 :headline-stars) clist)
13944 (push (org-point-in-group p 2 :todo-keyword) clist)
13945 (push (org-point-in-group p 4 :tags) clist))
13946 (goto-char p)
13947 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
13948 (if (looking-at "\\[#[A-Z0-9]\\]")
13949 (push (org-point-in-group p 0 :priority) clist)))
13951 ((org-at-item-p)
13952 (push (org-point-in-group p 2 :item-bullet) clist)
13953 (push (list :item (point-at-bol)
13954 (save-excursion (org-end-of-item) (point)))
13955 clist)
13956 (and (org-at-item-checkbox-p)
13957 (push (org-point-in-group p 0 :checkbox) clist)))
13959 ((org-at-table-p)
13960 (push (list :table (org-table-begin) (org-table-end)) clist)
13961 (if (memq 'org-formula faces)
13962 (push (list :table-special
13963 (previous-single-property-change p 'face)
13964 (next-single-property-change p 'face)) clist)))
13965 ((org-at-table-p 'any)
13966 (push (list :table-table) clist)))
13967 (goto-char p)
13969 ;; Now the small context
13970 (cond
13971 ((org-at-timestamp-p)
13972 (push (org-point-in-group p 0 :timestamp) clist))
13973 ((memq 'org-link faces)
13974 (push (list :link
13975 (previous-single-property-change p 'face)
13976 (next-single-property-change p 'face)) clist))
13977 ((memq 'org-special-keyword faces)
13978 (push (list :keyword
13979 (previous-single-property-change p 'face)
13980 (next-single-property-change p 'face)) clist))
13981 ((org-on-target-p)
13982 (push (org-point-in-group p 0 :target) clist)
13983 (goto-char (1- (match-beginning 0)))
13984 (if (looking-at org-radio-target-regexp)
13985 (push (org-point-in-group p 0 :radio-target) clist))
13986 (goto-char p))
13987 ((setq o (car (delq nil
13988 (mapcar
13989 (lambda (x)
13990 (if (memq x org-latex-fragment-image-overlays) x))
13991 (org-overlays-at (point))))))
13992 (push (list :latex-fragment
13993 (org-overlay-start o) (org-overlay-end o)) clist)
13994 (push (list :latex-preview
13995 (org-overlay-start o) (org-overlay-end o)) clist))
13996 ((org-inside-LaTeX-fragment-p)
13997 ;; FIXME: positions wrong.
13998 (push (list :latex-fragment (point) (point)) clist)))
14000 (setq clist (nreverse (delq nil clist)))
14001 clist))
14003 ;; FIXME: Compare with at-regexp-p Do we need both?
14004 (defun org-in-regexp (re &optional nlines visually)
14005 "Check if point is inside a match of regexp.
14006 Normally only the current line is checked, but you can include NLINES extra
14007 lines both before and after point into the search.
14008 If VISUALLY is set, require that the cursor is not after the match but
14009 really on, so that the block visually is on the match."
14010 (catch 'exit
14011 (let ((pos (point))
14012 (eol (point-at-eol (+ 1 (or nlines 0))))
14013 (inc (if visually 1 0)))
14014 (save-excursion
14015 (beginning-of-line (- 1 (or nlines 0)))
14016 (while (re-search-forward re eol t)
14017 (if (and (<= (match-beginning 0) pos)
14018 (>= (+ inc (match-end 0)) pos))
14019 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
14021 (defun org-at-regexp-p (regexp)
14022 "Is point inside a match of REGEXP in the current line?"
14023 (catch 'exit
14024 (save-excursion
14025 (let ((pos (point)) (end (point-at-eol)))
14026 (beginning-of-line 1)
14027 (while (re-search-forward regexp end t)
14028 (if (and (<= (match-beginning 0) pos)
14029 (>= (match-end 0) pos))
14030 (throw 'exit t)))
14031 nil))))
14033 (defun org-occur-in-agenda-files (regexp &optional nlines)
14034 "Call `multi-occur' with buffers for all agenda files."
14035 (interactive "sOrg-files matching: \np")
14036 (let* ((files (org-agenda-files))
14037 (tnames (mapcar 'file-truename files))
14038 (extra org-agenda-text-search-extra-files)
14040 (when (eq (car extra) 'agenda-archives)
14041 (setq extra (cdr extra))
14042 (setq files (org-add-archive-files files)))
14043 (while (setq f (pop extra))
14044 (unless (member (file-truename f) tnames)
14045 (add-to-list 'files f 'append)
14046 (add-to-list 'tnames (file-truename f) 'append)))
14047 (multi-occur
14048 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
14049 regexp)))
14051 (if (boundp 'occur-mode-find-occurrence-hook)
14052 ;; Emacs 23
14053 (add-hook 'occur-mode-find-occurrence-hook
14054 (lambda ()
14055 (when (org-mode-p)
14056 (org-reveal))))
14057 ;; Emacs 22
14058 (defadvice occur-mode-goto-occurrence
14059 (after org-occur-reveal activate)
14060 (and (org-mode-p) (org-reveal)))
14061 (defadvice occur-mode-goto-occurrence-other-window
14062 (after org-occur-reveal activate)
14063 (and (org-mode-p) (org-reveal)))
14064 (defadvice occur-mode-display-occurrence
14065 (after org-occur-reveal activate)
14066 (when (org-mode-p)
14067 (let ((pos (occur-mode-find-occurrence)))
14068 (with-current-buffer (marker-buffer pos)
14069 (save-excursion
14070 (goto-char pos)
14071 (org-reveal)))))))
14073 (defun org-uniquify (list)
14074 "Remove duplicate elements from LIST."
14075 (let (res)
14076 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
14077 res))
14079 (defun org-delete-all (elts list)
14080 "Remove all elements in ELTS from LIST."
14081 (while elts
14082 (setq list (delete (pop elts) list)))
14083 list)
14085 (defun org-back-over-empty-lines ()
14086 "Move backwards over whitespace, to the beginning of the first empty line.
14087 Returns the number of empty lines passed."
14088 (let ((pos (point)))
14089 (skip-chars-backward " \t\n\r")
14090 (beginning-of-line 2)
14091 (goto-char (min (point) pos))
14092 (count-lines (point) pos)))
14094 (defun org-skip-whitespace ()
14095 (skip-chars-forward " \t\n\r"))
14097 (defun org-point-in-group (point group &optional context)
14098 "Check if POINT is in match-group GROUP.
14099 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
14100 match. If the match group does ot exist or point is not inside it,
14101 return nil."
14102 (and (match-beginning group)
14103 (>= point (match-beginning group))
14104 (<= point (match-end group))
14105 (if context
14106 (list context (match-beginning group) (match-end group))
14107 t)))
14109 (defun org-switch-to-buffer-other-window (&rest args)
14110 "Switch to buffer in a second window on the current frame.
14111 In particular, do not allow pop-up frames."
14112 (let (pop-up-frames special-display-buffer-names special-display-regexps
14113 special-display-function)
14114 (apply 'switch-to-buffer-other-window args)))
14116 (defun org-combine-plists (&rest plists)
14117 "Create a single property list from all plists in PLISTS.
14118 The process starts by copying the first list, and then setting properties
14119 from the other lists. Settings in the last list are the most significant
14120 ones and overrule settings in the other lists."
14121 (let ((rtn (copy-sequence (pop plists)))
14122 p v ls)
14123 (while plists
14124 (setq ls (pop plists))
14125 (while ls
14126 (setq p (pop ls) v (pop ls))
14127 (setq rtn (plist-put rtn p v))))
14128 rtn))
14130 (defun org-move-line-down (arg)
14131 "Move the current line down. With prefix argument, move it past ARG lines."
14132 (interactive "p")
14133 (let ((col (current-column))
14134 beg end pos)
14135 (beginning-of-line 1) (setq beg (point))
14136 (beginning-of-line 2) (setq end (point))
14137 (beginning-of-line (+ 1 arg))
14138 (setq pos (move-marker (make-marker) (point)))
14139 (insert (delete-and-extract-region beg end))
14140 (goto-char pos)
14141 (org-move-to-column col)))
14143 (defun org-move-line-up (arg)
14144 "Move the current line up. With prefix argument, move it past ARG lines."
14145 (interactive "p")
14146 (let ((col (current-column))
14147 beg end pos)
14148 (beginning-of-line 1) (setq beg (point))
14149 (beginning-of-line 2) (setq end (point))
14150 (beginning-of-line (- arg))
14151 (setq pos (move-marker (make-marker) (point)))
14152 (insert (delete-and-extract-region beg end))
14153 (goto-char pos)
14154 (org-move-to-column col)))
14156 (defun org-replace-escapes (string table)
14157 "Replace %-escapes in STRING with values in TABLE.
14158 TABLE is an association list with keys like \"%a\" and string values.
14159 The sequences in STRING may contain normal field width and padding information,
14160 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
14161 so values can contain further %-escapes if they are define later in TABLE."
14162 (let ((case-fold-search nil)
14163 e re rpl)
14164 (while (setq e (pop table))
14165 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
14166 (while (string-match re string)
14167 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
14168 (cdr e)))
14169 (setq string (replace-match rpl t t string))))
14170 string))
14173 (defun org-sublist (list start end)
14174 "Return a section of LIST, from START to END.
14175 Counting starts at 1."
14176 (let (rtn (c start))
14177 (setq list (nthcdr (1- start) list))
14178 (while (and list (<= c end))
14179 (push (pop list) rtn)
14180 (setq c (1+ c)))
14181 (nreverse rtn)))
14183 (defun org-find-base-buffer-visiting (file)
14184 "Like `find-buffer-visiting' but alway return the base buffer and
14185 not an indirect buffer."
14186 (let ((buf (find-buffer-visiting file)))
14187 (if buf
14188 (or (buffer-base-buffer buf) buf)
14189 nil)))
14191 (defun org-image-file-name-regexp (&optional extensions)
14192 "Return regexp matching the file names of images.
14193 If EXTENSIONS is given, only match these."
14194 (if (and (not extensions) (fboundp 'image-file-name-regexp))
14195 (image-file-name-regexp)
14196 (let ((image-file-name-extensions
14197 (or extensions
14198 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
14199 "xbm" "xpm" "pbm" "pgm" "ppm"))))
14200 (concat "\\."
14201 (regexp-opt (nconc (mapcar 'upcase
14202 image-file-name-extensions)
14203 image-file-name-extensions)
14205 "\\'"))))
14207 (defun org-file-image-p (file &optional extensions)
14208 "Return non-nil if FILE is an image."
14209 (save-match-data
14210 (string-match (org-image-file-name-regexp extensions) file)))
14212 (defun org-get-cursor-date ()
14213 "Return the date at cursor in as a time.
14214 This works in the calendar and in the agenda, anywhere else it just
14215 returns the current time."
14216 (let (date day defd)
14217 (cond
14218 ((eq major-mode 'calendar-mode)
14219 (setq date (calendar-cursor-to-date)
14220 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14221 ((eq major-mode 'org-agenda-mode)
14222 (setq day (get-text-property (point) 'day))
14223 (if day
14224 (setq date (calendar-gregorian-from-absolute day)
14225 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
14226 (nth 2 date))))))
14227 (or defd (current-time))))
14229 (defvar org-agenda-action-marker (make-marker)
14230 "Marker pointing to the entry for the next agenda action.")
14232 (defun org-mark-entry-for-agenda-action ()
14233 "Mark the current entry as target of an agenda action.
14234 Agenda actions are actions executed from the agenda with the key `k',
14235 which make use of the date at the cursor."
14236 (interactive)
14237 (move-marker org-agenda-action-marker
14238 (save-excursion (org-back-to-heading t) (point))
14239 (current-buffer))
14240 (message
14241 "Entry marked for action; press `k' at desired date in agenda or calendar"))
14243 ;;; Paragraph filling stuff.
14244 ;; We want this to be just right, so use the full arsenal.
14246 (defun org-indent-line-function ()
14247 "Indent line like previous, but further if previous was headline or item."
14248 (interactive)
14249 (let* ((pos (point))
14250 (itemp (org-at-item-p))
14251 column bpos bcol tpos tcol bullet btype bullet-type)
14252 ;; Find the previous relevant line
14253 (beginning-of-line 1)
14254 (cond
14255 ((looking-at "#") (setq column 0))
14256 ((looking-at "\\*+ ") (setq column 0))
14258 (beginning-of-line 0)
14259 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
14260 (beginning-of-line 0))
14261 (cond
14262 ((looking-at "\\*+[ \t]+")
14263 (if (not org-adapt-indentation)
14264 (setq column 0)
14265 (goto-char (match-end 0))
14266 (setq column (current-column))))
14267 ((org-in-item-p)
14268 (org-beginning-of-item)
14269 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
14270 (setq bpos (match-beginning 1) tpos (match-end 0)
14271 bcol (progn (goto-char bpos) (current-column))
14272 tcol (progn (goto-char tpos) (current-column))
14273 bullet (match-string 1)
14274 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
14275 (if (> tcol (+ bcol org-description-max-indent))
14276 (setq tcol (+ bcol 5)))
14277 (if (not itemp)
14278 (setq column tcol)
14279 (goto-char pos)
14280 (beginning-of-line 1)
14281 (if (looking-at "\\S-")
14282 (progn
14283 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
14284 (setq bullet (match-string 1)
14285 btype (if (string-match "[0-9]" bullet) "n" bullet))
14286 (setq column (if (equal btype bullet-type) bcol tcol)))
14287 (setq column (org-get-indentation)))))
14288 (t (setq column (org-get-indentation))))))
14289 (goto-char pos)
14290 (if (<= (current-column) (current-indentation))
14291 (org-indent-line-to column)
14292 (save-excursion (org-indent-line-to column)))
14293 (setq column (current-column))
14294 (beginning-of-line 1)
14295 (if (looking-at
14296 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
14297 (replace-match (concat "\\1" (format org-property-format
14298 (match-string 2) (match-string 3)))
14299 t nil))
14300 (org-move-to-column column)))
14302 (defun org-set-autofill-regexps ()
14303 (interactive)
14304 ;; In the paragraph separator we include headlines, because filling
14305 ;; text in a line directly attached to a headline would otherwise
14306 ;; fill the headline as well.
14307 (org-set-local 'comment-start-skip "^#+[ \t]*")
14308 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
14309 ;; The paragraph starter includes hand-formatted lists.
14310 (org-set-local 'paragraph-start
14311 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
14312 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
14313 ;; But only if the user has not turned off tables or fixed-width regions
14314 (org-set-local
14315 'auto-fill-inhibit-regexp
14316 (concat "\\*+ \\|#\\+"
14317 "\\|[ \t]*" org-keyword-time-regexp
14318 (if (or org-enable-table-editor org-enable-fixed-width-editor)
14319 (concat
14320 "\\|[ \t]*["
14321 (if org-enable-table-editor "|" "")
14322 (if org-enable-fixed-width-editor ":" "")
14323 "]"))))
14324 ;; We use our own fill-paragraph function, to make sure that tables
14325 ;; and fixed-width regions are not wrapped. That function will pass
14326 ;; through to `fill-paragraph' when appropriate.
14327 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
14328 ; Adaptive filling: To get full control, first make sure that
14329 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
14330 (org-set-local 'adaptive-fill-regexp "\000")
14331 (org-set-local 'adaptive-fill-function
14332 'org-adaptive-fill-function)
14333 (org-set-local
14334 'align-mode-rules-list
14335 '((org-in-buffer-settings
14336 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
14337 (modes . '(org-mode))))))
14339 (defun org-fill-paragraph (&optional justify)
14340 "Re-align a table, pass through to fill-paragraph if no table."
14341 (let ((table-p (org-at-table-p))
14342 (table.el-p (org-at-table.el-p)))
14343 (cond ((and (equal (char-after (point-at-bol)) ?*)
14344 (save-excursion (goto-char (point-at-bol))
14345 (looking-at outline-regexp)))
14346 t) ; skip headlines
14347 (table.el-p t) ; skip table.el tables
14348 (table-p (org-table-align) t) ; align org-mode tables
14349 (t nil)))) ; call paragraph-fill
14351 ;; For reference, this is the default value of adaptive-fill-regexp
14352 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
14354 (defun org-adaptive-fill-function ()
14355 "Return a fill prefix for org-mode files.
14356 In particular, this makes sure hanging paragraphs for hand-formatted lists
14357 work correctly."
14358 (cond ((looking-at "#[ \t]+")
14359 (match-string 0))
14360 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
14361 (save-excursion
14362 (if (> (match-end 1) (+ (match-beginning 1)
14363 org-description-max-indent))
14364 (goto-char (+ (match-beginning 1) 5))
14365 (goto-char (match-end 0)))
14366 (make-string (current-column) ?\ )))
14367 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
14368 (save-excursion
14369 (goto-char (match-end 0))
14370 (make-string (current-column) ?\ )))
14371 (t nil)))
14373 ;;; Other stuff.
14375 (defun org-toggle-fixed-width-section (arg)
14376 "Toggle the fixed-width export.
14377 If there is no active region, the QUOTE keyword at the current headline is
14378 inserted or removed. When present, it causes the text between this headline
14379 and the next to be exported as fixed-width text, and unmodified.
14380 If there is an active region, this command adds or removes a colon as the
14381 first character of this line. If the first character of a line is a colon,
14382 this line is also exported in fixed-width font."
14383 (interactive "P")
14384 (let* ((cc 0)
14385 (regionp (org-region-active-p))
14386 (beg (if regionp (region-beginning) (point)))
14387 (end (if regionp (region-end)))
14388 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
14389 (case-fold-search nil)
14390 (re "[ \t]*\\(:\\)")
14391 off)
14392 (if regionp
14393 (save-excursion
14394 (goto-char beg)
14395 (setq cc (current-column))
14396 (beginning-of-line 1)
14397 (setq off (looking-at re))
14398 (while (> nlines 0)
14399 (setq nlines (1- nlines))
14400 (beginning-of-line 1)
14401 (cond
14402 (arg
14403 (org-move-to-column cc t)
14404 (insert ":\n")
14405 (forward-line -1))
14406 ((and off (looking-at re))
14407 (replace-match "" t t nil 1))
14408 ((not off) (org-move-to-column cc t) (insert ":")))
14409 (forward-line 1)))
14410 (save-excursion
14411 (org-back-to-heading)
14412 (if (looking-at (concat outline-regexp
14413 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
14414 (replace-match "" t t nil 1)
14415 (if (looking-at outline-regexp)
14416 (progn
14417 (goto-char (match-end 0))
14418 (insert org-quote-string " "))))))))
14420 ;;;; Functions extending outline functionality
14422 (defun org-beginning-of-line (&optional arg)
14423 "Go to the beginning of the current line. If that is invisible, continue
14424 to a visible line beginning. This makes the function of C-a more intuitive.
14425 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
14426 first attempt, and only move to after the tags when the cursor is already
14427 beyond the end of the headline."
14428 (interactive "P")
14429 (let ((pos (point)) refpos)
14430 (beginning-of-line 1)
14431 (if (bobp)
14433 (backward-char 1)
14434 (if (org-invisible-p)
14435 (while (and (not (bobp)) (org-invisible-p))
14436 (backward-char 1)
14437 (beginning-of-line 1))
14438 (forward-char 1)))
14439 (when org-special-ctrl-a/e
14440 (cond
14441 ((and (looking-at org-complex-heading-regexp)
14442 (= (char-after (match-end 1)) ?\ ))
14443 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
14444 (point-at-eol)))
14445 (goto-char
14446 (if (eq org-special-ctrl-a/e t)
14447 (cond ((> pos refpos) refpos)
14448 ((= pos (point)) refpos)
14449 (t (point)))
14450 (cond ((> pos (point)) (point))
14451 ((not (eq last-command this-command)) (point))
14452 (t refpos)))))
14453 ((org-at-item-p)
14454 (goto-char
14455 (if (eq org-special-ctrl-a/e t)
14456 (cond ((> pos (match-end 4)) (match-end 4))
14457 ((= pos (point)) (match-end 4))
14458 (t (point)))
14459 (cond ((> pos (point)) (point))
14460 ((not (eq last-command this-command)) (point))
14461 (t (match-end 4))))))))
14462 (org-no-warnings
14463 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
14465 (defun org-end-of-line (&optional arg)
14466 "Go to the end of the line.
14467 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
14468 first attempt, and only move to after the tags when the cursor is already
14469 beyond the end of the headline."
14470 (interactive "P")
14471 (if (or (not org-special-ctrl-a/e)
14472 (not (org-on-heading-p)))
14473 (end-of-line arg)
14474 (let ((pos (point)))
14475 (beginning-of-line 1)
14476 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
14477 (if (eq org-special-ctrl-a/e t)
14478 (if (or (< pos (match-beginning 1))
14479 (= pos (match-end 0)))
14480 (goto-char (match-beginning 1))
14481 (goto-char (match-end 0)))
14482 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
14483 (goto-char (match-end 0))
14484 (goto-char (match-beginning 1))))
14485 (end-of-line arg))))
14486 (org-no-warnings
14487 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
14490 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
14491 (define-key org-mode-map "\C-e" 'org-end-of-line)
14493 (defun org-kill-line (&optional arg)
14494 "Kill line, to tags or end of line."
14495 (interactive "P")
14496 (cond
14497 ((or (not org-special-ctrl-k)
14498 (bolp)
14499 (not (org-on-heading-p)))
14500 (call-interactively 'kill-line))
14501 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
14502 (kill-region (point) (match-beginning 1))
14503 (org-set-tags nil t))
14504 (t (kill-region (point) (point-at-eol)))))
14506 (define-key org-mode-map "\C-k" 'org-kill-line)
14508 (defun org-yank (&optional arg)
14509 "Yank. If the kill is a subtree, treat it specially.
14510 This command will look at the current kill and check if is a single
14511 subtree, or a series of subtrees[1]. If it passes the test, and if the
14512 cursor is at the beginning of a line or after the stars of a currently
14513 empty headline, then the yank is handled specially. How exactly depends
14514 on the value of the following variables, both set by default.
14516 org-yank-folded-subtrees
14517 When set, the subtree(s) will be folded after insertion, but only
14518 if doing so would now swallow text after the yanked text.
14520 org-yank-adjusted-subtrees
14521 When set, the subtree will be promoted or demoted in order to
14522 fit into the local outline tree structure, which means that the level
14523 will be adjusted so that it becomes the smaller one of the two
14524 *visible* surrounding headings.
14526 Any prefix to this command will cause `yank' to be called directly with
14527 no special treatment. In particular, a simple `C-u' prefix will just
14528 plainly yank the text as it is.
14530 \[1] Basically, the test checks if the first non-white line is a heading
14531 and if there are no other headings with fewer stars."
14532 (interactive "P")
14533 (setq this-command 'yank)
14534 (if arg
14535 (call-interactively 'yank)
14536 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
14537 (and (org-kill-is-subtree-p)
14538 (or (bolp)
14539 (and (looking-at "[ \t]*$")
14540 (string-match
14541 "\\`\\*+\\'"
14542 (buffer-substring (point-at-bol) (point)))))))
14543 swallowp)
14544 (cond
14545 ((and subtreep org-yank-folded-subtrees)
14546 (let ((beg (point))
14547 end)
14548 (if (and subtreep org-yank-adjusted-subtrees)
14549 (org-paste-subtree nil nil 'for-yank)
14550 (call-interactively 'yank))
14551 (setq end (point))
14552 (goto-char beg)
14553 (when (and (bolp) subtreep
14554 (not (setq swallowp
14555 (org-yank-folding-would-swallow-text beg end))))
14556 (or (looking-at outline-regexp)
14557 (re-search-forward (concat "^" outline-regexp) end t))
14558 (while (and (< (point) end) (looking-at outline-regexp))
14559 (hide-subtree)
14560 (org-cycle-show-empty-lines 'folded)
14561 (condition-case nil
14562 (outline-forward-same-level 1)
14563 (error (goto-char end)))))
14564 (when swallowp
14565 (message
14566 "Yanked text not folded because that would swallow text"))
14567 (goto-char end)
14568 (skip-chars-forward " \t\n\r")
14569 (beginning-of-line 1)
14570 (push-mark beg 'nomsg)))
14571 ((and subtreep org-yank-adjusted-subtrees)
14572 (let ((beg (point-at-bol)))
14573 (org-paste-subtree nil nil 'for-yank)
14574 (push-mark beg 'nomsg)))
14576 (call-interactively 'yank))))))
14578 (defun org-yank-folding-would-swallow-text (beg end)
14579 "Would hide-subtree at BEG swallow any text after END?"
14580 (let (level)
14581 (save-excursion
14582 (goto-char beg)
14583 (when (or (looking-at outline-regexp)
14584 (re-search-forward (concat "^" outline-regexp) end t))
14585 (setq level (org-outline-level)))
14586 (goto-char end)
14587 (skip-chars-forward " \t\r\n\v\f")
14588 (if (or (eobp)
14589 (and (bolp) (looking-at org-outline-regexp)
14590 (<= (org-outline-level) level)))
14591 nil ; Nothing would be swallowed
14592 t)))) ; something would swallow
14594 (define-key org-mode-map "\C-y" 'org-yank)
14596 (defun org-invisible-p ()
14597 "Check if point is at a character currently not visible."
14598 ;; Early versions of noutline don't have `outline-invisible-p'.
14599 (if (fboundp 'outline-invisible-p)
14600 (outline-invisible-p)
14601 (get-char-property (point) 'invisible)))
14603 (defun org-invisible-p2 ()
14604 "Check if point is at a character currently not visible."
14605 (save-excursion
14606 (if (and (eolp) (not (bobp))) (backward-char 1))
14607 ;; Early versions of noutline don't have `outline-invisible-p'.
14608 (if (fboundp 'outline-invisible-p)
14609 (outline-invisible-p)
14610 (get-char-property (point) 'invisible))))
14612 (defun org-back-to-heading (&optional invisible-ok)
14613 "Call `outline-back-to-heading', but provide a better error message."
14614 (condition-case nil
14615 (outline-back-to-heading invisible-ok)
14616 (error (error "Before first headline at position %d in buffer %s"
14617 (point) (current-buffer)))))
14619 (defun org-before-first-heading-p ()
14620 "Before first heading?"
14621 (save-excursion
14622 (null (re-search-backward "^\\*+ " nil t))))
14624 (defalias 'org-on-heading-p 'outline-on-heading-p)
14625 (defalias 'org-at-heading-p 'outline-on-heading-p)
14626 (defun org-at-heading-or-item-p ()
14627 (or (org-on-heading-p) (org-at-item-p)))
14629 (defun org-on-target-p ()
14630 (or (org-in-regexp org-radio-target-regexp)
14631 (org-in-regexp org-target-regexp)))
14633 (defun org-up-heading-all (arg)
14634 "Move to the heading line of which the present line is a subheading.
14635 This function considers both visible and invisible heading lines.
14636 With argument, move up ARG levels."
14637 (if (fboundp 'outline-up-heading-all)
14638 (outline-up-heading-all arg) ; emacs 21 version of outline.el
14639 (outline-up-heading arg t))) ; emacs 22 version of outline.el
14641 (defun org-up-heading-safe ()
14642 "Move to the heading line of which the present line is a subheading.
14643 This version will not throw an error. It will return the level of the
14644 headline found, or nil if no higher level is found."
14645 (let (start-level re)
14646 (org-back-to-heading t)
14647 (setq start-level (funcall outline-level))
14648 (if (equal start-level 1)
14650 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
14651 (if (re-search-backward re nil t)
14652 (funcall outline-level)))))
14654 (defun org-first-sibling-p ()
14655 "Is this heading the first child of its parents?"
14656 (interactive)
14657 (let ((re (concat "^" outline-regexp))
14658 level l)
14659 (unless (org-at-heading-p t)
14660 (error "Not at a heading"))
14661 (setq level (funcall outline-level))
14662 (save-excursion
14663 (if (not (re-search-backward re nil t))
14665 (setq l (funcall outline-level))
14666 (< l level)))))
14668 (defun org-goto-sibling (&optional previous)
14669 "Goto the next sibling, even if it is invisible.
14670 When PREVIOUS is set, go to the previous sibling instead. Returns t
14671 when a sibling was found. When none is found, return nil and don't
14672 move point."
14673 (let ((fun (if previous 're-search-backward 're-search-forward))
14674 (pos (point))
14675 (re (concat "^" outline-regexp))
14676 level l)
14677 (when (condition-case nil (org-back-to-heading t) (error nil))
14678 (setq level (funcall outline-level))
14679 (catch 'exit
14680 (or previous (forward-char 1))
14681 (while (funcall fun re nil t)
14682 (setq l (funcall outline-level))
14683 (when (< l level) (goto-char pos) (throw 'exit nil))
14684 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
14685 (goto-char pos)
14686 nil))))
14688 (defun org-show-siblings ()
14689 "Show all siblings of the current headline."
14690 (save-excursion
14691 (while (org-goto-sibling) (org-flag-heading nil)))
14692 (save-excursion
14693 (while (org-goto-sibling 'previous)
14694 (org-flag-heading nil))))
14696 (defun org-show-hidden-entry ()
14697 "Show an entry where even the heading is hidden."
14698 (save-excursion
14699 (org-show-entry)))
14701 (defun org-flag-heading (flag &optional entry)
14702 "Flag the current heading. FLAG non-nil means make invisible.
14703 When ENTRY is non-nil, show the entire entry."
14704 (save-excursion
14705 (org-back-to-heading t)
14706 ;; Check if we should show the entire entry
14707 (if entry
14708 (progn
14709 (org-show-entry)
14710 (save-excursion
14711 (and (outline-next-heading)
14712 (org-flag-heading nil))))
14713 (outline-flag-region (max (point-min) (1- (point)))
14714 (save-excursion (outline-end-of-heading) (point))
14715 flag))))
14717 (defun org-forward-same-level (arg)
14718 "Move forward to the ARG'th subheading at same level as this one.
14719 Stop at the first and last subheadings of a superior heading.
14720 This is like outline-forward-same-level, but invisible headings are ok."
14721 (interactive "p")
14722 (org-back-to-heading t)
14723 (while (> arg 0)
14724 (let ((point-to-move-to (save-excursion
14725 (org-get-next-sibling))))
14726 (if point-to-move-to
14727 (progn
14728 (goto-char point-to-move-to)
14729 (setq arg (1- arg)))
14730 (progn
14731 (setq arg 0)
14732 (error "No following same-level heading"))))))
14734 (defun org-get-next-sibling ()
14735 "Move to next heading of the same level, and return point.
14736 If there is no such heading, return nil.
14737 This is like outline-next-sibling, but invisible headings are ok."
14738 (let ((level (funcall outline-level)))
14739 (outline-next-heading)
14740 (while (and (not (eobp)) (> (funcall outline-level) level))
14741 (outline-next-heading))
14742 (if (or (eobp) (< (funcall outline-level) level))
14744 (point))))
14746 (defun org-end-of-subtree (&optional invisible-OK to-heading)
14747 ;; This is an exact copy of the original function, but it uses
14748 ;; `org-back-to-heading', to make it work also in invisible
14749 ;; trees. And is uses an invisible-OK argument.
14750 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
14751 (org-back-to-heading invisible-OK)
14752 (let ((first t)
14753 (level (funcall outline-level)))
14754 (while (and (not (eobp))
14755 (or first (> (funcall outline-level) level)))
14756 (setq first nil)
14757 (outline-next-heading))
14758 (unless to-heading
14759 (if (memq (preceding-char) '(?\n ?\^M))
14760 (progn
14761 ;; Go to end of line before heading
14762 (forward-char -1)
14763 (if (memq (preceding-char) '(?\n ?\^M))
14764 ;; leave blank line before heading
14765 (forward-char -1))))))
14766 (point))
14768 (defun org-show-subtree ()
14769 "Show everything after this heading at deeper levels."
14770 (outline-flag-region
14771 (point)
14772 (save-excursion
14773 (outline-end-of-subtree) (outline-next-heading) (point))
14774 nil))
14776 (defun org-show-entry ()
14777 "Show the body directly following this heading.
14778 Show the heading too, if it is currently invisible."
14779 (interactive)
14780 (save-excursion
14781 (condition-case nil
14782 (progn
14783 (org-back-to-heading t)
14784 (outline-flag-region
14785 (max (point-min) (1- (point)))
14786 (save-excursion
14787 (re-search-forward
14788 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
14789 (or (match-beginning 1) (point-max)))
14790 nil))
14791 (error nil))))
14793 (defun org-make-options-regexp (kwds)
14794 "Make a regular expression for keyword lines."
14795 (concat
14797 "#?[ \t]*\\+\\("
14798 (mapconcat 'regexp-quote kwds "\\|")
14799 "\\):[ \t]*"
14800 "\\(.+\\)"))
14802 ;; Make isearch reveal the necessary context
14803 (defun org-isearch-end ()
14804 "Reveal context after isearch exits."
14805 (when isearch-success ; only if search was successful
14806 (if (featurep 'xemacs)
14807 ;; Under XEmacs, the hook is run in the correct place,
14808 ;; we directly show the context.
14809 (org-show-context 'isearch)
14810 ;; In Emacs the hook runs *before* restoring the overlays.
14811 ;; So we have to use a one-time post-command-hook to do this.
14812 ;; (Emacs 22 has a special variable, see function `org-mode')
14813 (unless (and (boundp 'isearch-mode-end-hook-quit)
14814 isearch-mode-end-hook-quit)
14815 ;; Only when the isearch was not quitted.
14816 (org-add-hook 'post-command-hook 'org-isearch-post-command
14817 'append 'local)))))
14819 (defun org-isearch-post-command ()
14820 "Remove self from hook, and show context."
14821 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
14822 (org-show-context 'isearch))
14825 ;;;; Integration with and fixes for other packages
14827 ;;; Imenu support
14829 (defvar org-imenu-markers nil
14830 "All markers currently used by Imenu.")
14831 (make-variable-buffer-local 'org-imenu-markers)
14833 (defun org-imenu-new-marker (&optional pos)
14834 "Return a new marker for use by Imenu, and remember the marker."
14835 (let ((m (make-marker)))
14836 (move-marker m (or pos (point)))
14837 (push m org-imenu-markers)
14840 (defun org-imenu-get-tree ()
14841 "Produce the index for Imenu."
14842 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
14843 (setq org-imenu-markers nil)
14844 (let* ((n org-imenu-depth)
14845 (re (concat "^" outline-regexp))
14846 (subs (make-vector (1+ n) nil))
14847 (last-level 0)
14848 m tree level head)
14849 (save-excursion
14850 (save-restriction
14851 (widen)
14852 (goto-char (point-max))
14853 (while (re-search-backward re nil t)
14854 (setq level (org-reduced-level (funcall outline-level)))
14855 (when (<= level n)
14856 (looking-at org-complex-heading-regexp)
14857 (setq head (org-link-display-format
14858 (org-match-string-no-properties 4))
14859 m (org-imenu-new-marker))
14860 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
14861 (if (>= level last-level)
14862 (push (cons head m) (aref subs level))
14863 (push (cons head (aref subs (1+ level))) (aref subs level))
14864 (loop for i from (1+ level) to n do (aset subs i nil)))
14865 (setq last-level level)))))
14866 (aref subs 1)))
14868 (eval-after-load "imenu"
14869 '(progn
14870 (add-hook 'imenu-after-jump-hook
14871 (lambda ()
14872 (if (eq major-mode 'org-mode)
14873 (org-show-context 'org-goto))))))
14875 (defun org-link-display-format (link)
14876 "Replace a link with either the description, or the link target
14877 if no description is present"
14878 (save-match-data
14879 (if (string-match org-bracket-link-analytic-regexp link)
14880 (replace-match (or (match-string 5 link)
14881 (concat (match-string 1 link)
14882 (match-string 3 link)))
14883 nil nil link)
14884 link)))
14886 ;; Speedbar support
14888 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
14889 "Overlay marking the agenda restriction line in speedbar.")
14890 (org-overlay-put org-speedbar-restriction-lock-overlay
14891 'face 'org-agenda-restriction-lock)
14892 (org-overlay-put org-speedbar-restriction-lock-overlay
14893 'help-echo "Agendas are currently limited to this item.")
14894 (org-detach-overlay org-speedbar-restriction-lock-overlay)
14896 (defun org-speedbar-set-agenda-restriction ()
14897 "Restrict future agenda commands to the location at point in speedbar.
14898 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
14899 (interactive)
14900 (require 'org-agenda)
14901 (let (p m tp np dir txt w)
14902 (cond
14903 ((setq p (text-property-any (point-at-bol) (point-at-eol)
14904 'org-imenu t))
14905 (setq m (get-text-property p 'org-imenu-marker))
14906 (save-excursion
14907 (save-restriction
14908 (set-buffer (marker-buffer m))
14909 (goto-char m)
14910 (org-agenda-set-restriction-lock 'subtree))))
14911 ((setq p (text-property-any (point-at-bol) (point-at-eol)
14912 'speedbar-function 'speedbar-find-file))
14913 (setq tp (previous-single-property-change
14914 (1+ p) 'speedbar-function)
14915 np (next-single-property-change
14916 tp 'speedbar-function)
14917 dir (speedbar-line-directory)
14918 txt (buffer-substring-no-properties (or tp (point-min))
14919 (or np (point-max))))
14920 (save-excursion
14921 (save-restriction
14922 (set-buffer (find-file-noselect
14923 (let ((default-directory dir))
14924 (expand-file-name txt))))
14925 (unless (org-mode-p)
14926 (error "Cannot restrict to non-Org-mode file"))
14927 (org-agenda-set-restriction-lock 'file))))
14928 (t (error "Don't know how to restrict Org-mode's agenda")))
14929 (org-move-overlay org-speedbar-restriction-lock-overlay
14930 (point-at-bol) (point-at-eol))
14931 (setq current-prefix-arg nil)
14932 (org-agenda-maybe-redo)))
14934 (eval-after-load "speedbar"
14935 '(progn
14936 (speedbar-add-supported-extension ".org")
14937 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
14938 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
14939 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
14940 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
14941 (add-hook 'speedbar-visiting-tag-hook
14942 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
14945 ;;; Fixes and Hacks for problems with other packages
14947 ;; Make flyspell not check words in links, to not mess up our keymap
14948 (defun org-mode-flyspell-verify ()
14949 "Don't let flyspell put overlays at active buttons."
14950 (not (get-text-property (point) 'keymap)))
14952 ;; Make `bookmark-jump' show the jump location if it was hidden.
14953 (eval-after-load "bookmark"
14954 '(if (boundp 'bookmark-after-jump-hook)
14955 ;; We can use the hook
14956 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
14957 ;; Hook not available, use advice
14958 (defadvice bookmark-jump (after org-make-visible activate)
14959 "Make the position visible."
14960 (org-bookmark-jump-unhide))))
14962 ;; Make sure saveplace show the location if it was hidden
14963 (eval-after-load "saveplace"
14964 '(defadvice save-place-find-file-hook (after org-make-visible activate)
14965 "Make the position visible."
14966 (org-bookmark-jump-unhide)))
14968 (defun org-bookmark-jump-unhide ()
14969 "Unhide the current position, to show the bookmark location."
14970 (and (org-mode-p)
14971 (or (org-invisible-p)
14972 (save-excursion (goto-char (max (point-min) (1- (point))))
14973 (org-invisible-p)))
14974 (org-show-context 'bookmark-jump)))
14976 ;; Make session.el ignore our circular variable
14977 (eval-after-load "session"
14978 '(add-to-list 'session-globals-exclude 'org-mark-ring))
14980 ;;;; Experimental code
14982 (defun org-closed-in-range ()
14983 "Sparse tree of items closed in a certain time range.
14984 Still experimental, may disappear in the future."
14985 (interactive)
14986 ;; Get the time interval from the user.
14987 (let* ((time1 (time-to-seconds
14988 (org-read-date nil 'to-time nil "Starting date: ")))
14989 (time2 (time-to-seconds
14990 (org-read-date nil 'to-time nil "End date:")))
14991 ;; callback function
14992 (callback (lambda ()
14993 (let ((time
14994 (time-to-seconds
14995 (apply 'encode-time
14996 (org-parse-time-string
14997 (match-string 1))))))
14998 ;; check if time in interval
14999 (and (>= time time1) (<= time time2))))))
15000 ;; make tree, check each match with the callback
15001 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
15004 ;;;; Finish up
15006 (provide 'org)
15008 (run-hooks 'org-load-hook)
15010 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
15012 ;;; org.el ends here