Footnotes: Fix some bugs.
[org-mode.git] / lisp / org.el
blob978c1f9b10f9175beef8f0e53ad5607cb2192fb7
1 ;;; org.el --- Outline-based notes management and organizer
2 ;; Carstens outline-mode for keeping track of everything.
3 ;; Copyright (C) 2004, 2005, 2006, 2007, 2008 Free Software Foundation, Inc.
4 ;;
5 ;; Author: Carsten Dominik <carsten at orgmode dot org>
6 ;; Keywords: outlines, hypermedia, calendar, wp
7 ;; Homepage: http://orgmode.org
8 ;; Version: 6.16trans
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.16trans"
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 . nil)
693 (plain-list-item . nil))
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) (boolean))
700 (cons (const plain-list-item) (boolean))))
702 (defcustom org-insert-heading-hook nil
703 "Hook being run after inserting a new heading."
704 :group 'org-edit-structure
705 :type 'hook)
707 (defcustom org-enable-fixed-width-editor t
708 "Non-nil means, lines starting with \":\" are treated as fixed-width.
709 This currently only means, they are never auto-wrapped.
710 When nil, such lines will be treated like ordinary lines.
711 See also the QUOTE keyword."
712 :group 'org-edit-structure
713 :type 'boolean)
715 (defcustom org-edit-src-region-extra nil
716 "Additional regexps to identify regions for editing with `org-edit-src-code'.
717 For examples see the function `org-edit-src-find-region-and-lang'.
718 The regular expression identifying the begin marker should end with a newline,
719 and the regexp marking the end line should start with a newline, to make sure
720 there are kept outside the narrowed region."
721 :group 'org-edit-structure
722 :type '(repeat
723 (list
724 (regexp :tag "begin regexp")
725 (regexp :tag "end regexp")
726 (choice :tag "language"
727 (string :tag "specify")
728 (integer :tag "from match group")
729 (const :tag "from `lang' element")
730 (const :tag "from `style' element")))))
732 (defcustom org-edit-fixed-width-region-mode 'artist-mode
733 "The mode that should be used to edit fixed-width regions.
734 These are the regions where each line starts with a colon."
735 :group 'org-edit-structure
736 :type '(choice
737 (const artist-mode)
738 (const picture-mode)
739 (const fundamental-mode)
740 (function :tag "Other (specify)")))
742 (defcustom org-goto-auto-isearch t
743 "Non-nil means, typing characters in org-goto starts incremental search."
744 :group 'org-edit-structure
745 :type 'boolean)
747 (defgroup org-sparse-trees nil
748 "Options concerning sparse trees in Org-mode."
749 :tag "Org Sparse Trees"
750 :group 'org-structure)
752 (defcustom org-highlight-sparse-tree-matches t
753 "Non-nil means, highlight all matches that define a sparse tree.
754 The highlights will automatically disappear the next time the buffer is
755 changed by an edit command."
756 :group 'org-sparse-trees
757 :type 'boolean)
759 (defcustom org-remove-highlights-with-change t
760 "Non-nil means, any change to the buffer will remove temporary highlights.
761 Such highlights are created by `org-occur' and `org-clock-display'.
762 When nil, `C-c C-c needs to be used to get rid of the highlights.
763 The highlights created by `org-preview-latex-fragment' always need
764 `C-c C-c' to be removed."
765 :group 'org-sparse-trees
766 :group 'org-time
767 :type 'boolean)
770 (defcustom org-occur-hook '(org-first-headline-recenter)
771 "Hook that is run after `org-occur' has constructed a sparse tree.
772 This can be used to recenter the window to show as much of the structure
773 as possible."
774 :group 'org-sparse-trees
775 :type 'hook)
777 (defgroup org-imenu-and-speedbar nil
778 "Options concerning imenu and speedbar in Org-mode."
779 :tag "Org Imenu and Speedbar"
780 :group 'org-structure)
782 (defcustom org-imenu-depth 2
783 "The maximum level for Imenu access to Org-mode headlines.
784 This also applied for speedbar access."
785 :group 'org-imenu-and-speedbar
786 :type 'number)
788 (defgroup org-table nil
789 "Options concerning tables in Org-mode."
790 :tag "Org Table"
791 :group 'org)
793 (defcustom org-enable-table-editor 'optimized
794 "Non-nil means, lines starting with \"|\" are handled by the table editor.
795 When nil, such lines will be treated like ordinary lines.
797 When equal to the symbol `optimized', the table editor will be optimized to
798 do the following:
799 - Automatic overwrite mode in front of whitespace in table fields.
800 This makes the structure of the table stay in tact as long as the edited
801 field does not exceed the column width.
802 - Minimize the number of realigns. Normally, the table is aligned each time
803 TAB or RET are pressed to move to another field. With optimization this
804 happens only if changes to a field might have changed the column width.
805 Optimization requires replacing the functions `self-insert-command',
806 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
807 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
808 very good at guessing when a re-align will be necessary, but you can always
809 force one with \\[org-ctrl-c-ctrl-c].
811 If you would like to use the optimized version in Org-mode, but the
812 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
814 This variable can be used to turn on and off the table editor during a session,
815 but in order to toggle optimization, a restart is required.
817 See also the variable `org-table-auto-blank-field'."
818 :group 'org-table
819 :type '(choice
820 (const :tag "off" nil)
821 (const :tag "on" t)
822 (const :tag "on, optimized" optimized)))
824 (defcustom org-table-tab-recognizes-table.el t
825 "Non-nil means, TAB will automatically notice a table.el table.
826 When it sees such a table, it moves point into it and - if necessary -
827 calls `table-recognize-table'."
828 :group 'org-table-editing
829 :type 'boolean)
831 (defgroup org-link nil
832 "Options concerning links in Org-mode."
833 :tag "Org Link"
834 :group 'org)
836 (defvar org-link-abbrev-alist-local nil
837 "Buffer-local version of `org-link-abbrev-alist', which see.
838 The value of this is taken from the #+LINK lines.")
839 (make-variable-buffer-local 'org-link-abbrev-alist-local)
841 (defcustom org-link-abbrev-alist nil
842 "Alist of link abbreviations.
843 The car of each element is a string, to be replaced at the start of a link.
844 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
845 links in Org-mode buffers can have an optional tag after a double colon, e.g.
847 [[linkkey:tag][description]]
849 If REPLACE is a string, the tag will simply be appended to create the link.
850 If the string contains \"%s\", the tag will be inserted there. Alternatively,
851 the placeholder \"%h\" will cause a url-encoded version of the tag to
852 be inserted at that point (see the function `url-hexify-string').
854 REPLACE may also be a function that will be called with the tag as the
855 only argument to create the link, which should be returned as a string.
857 See the manual for examples."
858 :group 'org-link
859 :type '(repeat
860 (cons
861 (string :tag "Protocol")
862 (choice
863 (string :tag "Format")
864 (function)))))
866 (defcustom org-descriptive-links t
867 "Non-nil means, hide link part and only show description of bracket links.
868 Bracket links are like [[link][description]]. This variable sets the initial
869 state in new org-mode buffers. The setting can then be toggled on a
870 per-buffer basis from the Org->Hyperlinks menu."
871 :group 'org-link
872 :type 'boolean)
874 (defcustom org-link-file-path-type 'adaptive
875 "How the path name in file links should be stored.
876 Valid values are:
878 relative Relative to the current directory, i.e. the directory of the file
879 into which the link is being inserted.
880 absolute Absolute path, if possible with ~ for home directory.
881 noabbrev Absolute path, no abbreviation of home directory.
882 adaptive Use relative path for files in the current directory and sub-
883 directories of it. For other files, use an absolute path."
884 :group 'org-link
885 :type '(choice
886 (const relative)
887 (const absolute)
888 (const noabbrev)
889 (const adaptive)))
891 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
892 "Types of links that should be activated in Org-mode files.
893 This is a list of symbols, each leading to the activation of a certain link
894 type. In principle, it does not hurt to turn on most link types - there may
895 be a small gain when turning off unused link types. The types are:
897 bracket The recommended [[link][description]] or [[link]] links with hiding.
898 angular Links in angular brackets that may contain whitespace like
899 <bbdb:Carsten Dominik>.
900 plain Plain links in normal text, no whitespace, like http://google.com.
901 radio Text that is matched by a radio target, see manual for details.
902 tag Tag settings in a headline (link to tag search).
903 date Time stamps (link to calendar).
904 footnote Footnote labels.
906 Changing this variable requires a restart of Emacs to become effective."
907 :group 'org-link
908 :type '(set :greedy t
909 (const :tag "Double bracket links (new style)" bracket)
910 (const :tag "Angular bracket links (old style)" angular)
911 (const :tag "Plain text links" plain)
912 (const :tag "Radio target matches" radio)
913 (const :tag "Tags" tag)
914 (const :tag "Timestamps" date)
915 (const :tag "Footnotes" footnote)))
917 (defcustom org-make-link-description-function nil
918 "Function to use to generate link descriptions from links. If
919 nil the link location will be used. This function must take two
920 parameters; the first is the link and the second the description
921 org-insert-link has generated, and should return the description
922 to use."
923 :group 'org-link
924 :type 'function)
926 (defgroup org-link-store nil
927 "Options concerning storing links in Org-mode."
928 :tag "Org Store Link"
929 :group 'org-link)
931 (defcustom org-email-link-description-format "Email %c: %.30s"
932 "Format of the description part of a link to an email or usenet message.
933 The following %-escapes will be replaced by corresponding information:
935 %F full \"From\" field
936 %f name, taken from \"From\" field, address if no name
937 %T full \"To\" field
938 %t first name in \"To\" field, address if no name
939 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
940 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
941 %s subject
942 %m message-id.
944 You may use normal field width specification between the % and the letter.
945 This is for example useful to limit the length of the subject.
947 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
948 :group 'org-link-store
949 :type 'string)
951 (defcustom org-from-is-user-regexp
952 (let (r1 r2)
953 (when (and user-mail-address (not (string= user-mail-address "")))
954 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
955 (when (and user-full-name (not (string= user-full-name "")))
956 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
957 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
958 "Regexp matched against the \"From:\" header of an email or usenet message.
959 It should match if the message is from the user him/herself."
960 :group 'org-link-store
961 :type 'regexp)
963 (defcustom org-link-to-org-use-id 'create-if-interactive
964 "Non-nil means, storing a link to an Org file will use entry IDs.
966 Note that before this variable is even considered, org-id must be loaded,
967 to please customize `org-modules' and turn it on.
969 The variable can have the following values:
971 t Create an ID if needed to make a link to the current entry.
973 create-if-interactive
974 If `org-store-link' is called directly (interactively, as a user
975 command), do create an ID to support the link. But when doing the
976 job for remember, only use the ID if it already exists. The
977 purpose of this setting is to avoid proliferation of unwanted
978 IDs, just because you happen to be in an Org file when you
979 call `org-remember' that automatically and preemptively
980 creates a link. If you do want to get an ID link in a remember
981 template to an entry not having an ID, create it first by
982 explicitly creating a link to it, using `C-c C-l' first.
984 use-existing
985 Use existing ID, do not create one.
987 nil Never use an ID to make a link, instead link using a text search for
988 the headline text."
989 :group 'org-link-store
990 :type '(choice
991 (const :tag "Create ID to make link" t)
992 (const :tag "Create if string link interactively"
993 'create-if-interactive)
994 (const :tag "Only use existing" 'use-existing)
995 (const :tag "Do not use ID to create link" nil)))
997 (defcustom org-context-in-file-links t
998 "Non-nil means, file links from `org-store-link' contain context.
999 A search string will be added to the file name with :: as separator and
1000 used to find the context when the link is activated by the command
1001 `org-open-at-point'.
1002 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1003 negates this setting for the duration of the command."
1004 :group 'org-link-store
1005 :type 'boolean)
1007 (defcustom org-keep-stored-link-after-insertion nil
1008 "Non-nil means, keep link in list for entire session.
1010 The command `org-store-link' adds a link pointing to the current
1011 location to an internal list. These links accumulate during a session.
1012 The command `org-insert-link' can be used to insert links into any
1013 Org-mode file (offering completion for all stored links). When this
1014 option is nil, every link which has been inserted once using \\[org-insert-link]
1015 will be removed from the list, to make completing the unused links
1016 more efficient."
1017 :group 'org-link-store
1018 :type 'boolean)
1020 (defgroup org-link-follow nil
1021 "Options concerning following links in Org-mode."
1022 :tag "Org Follow Link"
1023 :group 'org-link)
1025 (defcustom org-link-translation-function nil
1026 "Function to translate links with different syntax to Org syntax.
1027 This can be used to translate links created for example by the Planner
1028 or emacs-wiki packages to Org syntax.
1029 The function must accept two parameters, a TYPE containing the link
1030 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1031 which is everything after the link protocol. It should return a cons
1032 with possibly modified values of type and path.
1033 Org contains a function for this, so if you set this variable to
1034 `org-translate-link-from-planner', you should be able follow many
1035 links created by planner."
1036 :group 'org-link-follow
1037 :type 'function)
1039 (defcustom org-follow-link-hook nil
1040 "Hook that is run after a link has been followed."
1041 :group 'org-link-follow
1042 :type 'hook)
1044 (defcustom org-tab-follows-link nil
1045 "Non-nil means, on links TAB will follow the link.
1046 Needs to be set before org.el is loaded."
1047 :group 'org-link-follow
1048 :type 'boolean)
1050 (defcustom org-return-follows-link nil
1051 "Non-nil means, on links RET will follow the link.
1052 Needs to be set before org.el is loaded."
1053 :group 'org-link-follow
1054 :type 'boolean)
1056 (defcustom org-mouse-1-follows-link
1057 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1058 "Non-nil means, mouse-1 on a link will follow the link.
1059 A longer mouse click will still set point. Does not work on XEmacs.
1060 Needs to be set before org.el is loaded."
1061 :group 'org-link-follow
1062 :type 'boolean)
1064 (defcustom org-mark-ring-length 4
1065 "Number of different positions to be recorded in the ring
1066 Changing this requires a restart of Emacs to work correctly."
1067 :group 'org-link-follow
1068 :type 'integer)
1070 (defcustom org-link-frame-setup
1071 '((vm . vm-visit-folder-other-frame)
1072 (gnus . gnus-other-frame)
1073 (file . find-file-other-window))
1074 "Setup the frame configuration for following links.
1075 When following a link with Emacs, it may often be useful to display
1076 this link in another window or frame. This variable can be used to
1077 set this up for the different types of links.
1078 For VM, use any of
1079 `vm-visit-folder'
1080 `vm-visit-folder-other-frame'
1081 For Gnus, use any of
1082 `gnus'
1083 `gnus-other-frame'
1084 `org-gnus-no-new-news'
1085 For FILE, use any of
1086 `find-file'
1087 `find-file-other-window'
1088 `find-file-other-frame'
1089 For the calendar, use the variable `calendar-setup'.
1090 For BBDB, it is currently only possible to display the matches in
1091 another window."
1092 :group 'org-link-follow
1093 :type '(list
1094 (cons (const vm)
1095 (choice
1096 (const vm-visit-folder)
1097 (const vm-visit-folder-other-window)
1098 (const vm-visit-folder-other-frame)))
1099 (cons (const gnus)
1100 (choice
1101 (const gnus)
1102 (const gnus-other-frame)
1103 (const org-gnus-no-new-news)))
1104 (cons (const file)
1105 (choice
1106 (const find-file)
1107 (const find-file-other-window)
1108 (const find-file-other-frame)))))
1110 (defcustom org-display-internal-link-with-indirect-buffer nil
1111 "Non-nil means, use indirect buffer to display infile links.
1112 Activating internal links (from one location in a file to another location
1113 in the same file) normally just jumps to the location. When the link is
1114 activated with a C-u prefix (or with mouse-3), the link is displayed in
1115 another window. When this option is set, the other window actually displays
1116 an indirect buffer clone of the current buffer, to avoid any visibility
1117 changes to the current buffer."
1118 :group 'org-link-follow
1119 :type 'boolean)
1121 (defcustom org-open-non-existing-files nil
1122 "Non-nil means, `org-open-file' will open non-existing files.
1123 When nil, an error will be generated."
1124 :group 'org-link-follow
1125 :type 'boolean)
1127 (defcustom org-open-directory-means-index-dot-org nil
1128 "Non-nil means, a link to a directory really means to index.org.
1129 When nil, following a directory link will run dired or open a finder/explorer
1130 window on that directory."
1131 :group 'org-link-follow
1132 :type 'boolean)
1134 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1135 "Function and arguments to call for following mailto links.
1136 This is a list with the first element being a lisp function, and the
1137 remaining elements being arguments to the function. In string arguments,
1138 %a will be replaced by the address, and %s will be replaced by the subject
1139 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1140 :group 'org-link-follow
1141 :type '(choice
1142 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1143 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1144 (const :tag "message-mail" (message-mail "%a" "%s"))
1145 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1147 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1148 "Non-nil means, ask for confirmation before executing shell links.
1149 Shell links can be dangerous: just think about a link
1151 [[shell:rm -rf ~/*][Google Search]]
1153 This link would show up in your Org-mode document as \"Google Search\",
1154 but really it would remove your entire home directory.
1155 Therefore we advise against setting this variable to nil.
1156 Just change it to `y-or-n-p' of you want to confirm with a
1157 single keystroke rather than having to type \"yes\"."
1158 :group 'org-link-follow
1159 :type '(choice
1160 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1161 (const :tag "with y-or-n (faster)" y-or-n-p)
1162 (const :tag "no confirmation (dangerous)" nil)))
1164 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1165 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1166 Elisp links can be dangerous: just think about a link
1168 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1170 This link would show up in your Org-mode document as \"Google Search\",
1171 but really it would remove your entire home directory.
1172 Therefore we advise against setting this variable to nil.
1173 Just change it to `y-or-n-p' of you want to confirm with a
1174 single keystroke rather than having to type \"yes\"."
1175 :group 'org-link-follow
1176 :type '(choice
1177 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1178 (const :tag "with y-or-n (faster)" y-or-n-p)
1179 (const :tag "no confirmation (dangerous)" nil)))
1181 (defconst org-file-apps-defaults-gnu
1182 '((remote . emacs)
1183 (system . mailcap)
1184 (t . mailcap))
1185 "Default file applications on a UNIX or GNU/Linux system.
1186 See `org-file-apps'.")
1188 (defconst org-file-apps-defaults-macosx
1189 '((remote . emacs)
1190 (t . "open %s")
1191 (system . "open %s")
1192 ("ps.gz" . "gv %s")
1193 ("eps.gz" . "gv %s")
1194 ("dvi" . "xdvi %s")
1195 ("fig" . "xfig %s"))
1196 "Default file applications on a MacOS X system.
1197 The system \"open\" is known as a default, but we use X11 applications
1198 for some files for which the OS does not have a good default.
1199 See `org-file-apps'.")
1201 (defconst org-file-apps-defaults-windowsnt
1202 (list
1203 '(remote . emacs)
1204 (cons t
1205 (list (if (featurep 'xemacs)
1206 'mswindows-shell-execute
1207 'w32-shell-execute)
1208 "open" 'file))
1209 (cons 'system
1210 (list (if (featurep 'xemacs)
1211 'mswindows-shell-execute
1212 'w32-shell-execute)
1213 "open" 'file)))
1214 "Default file applications on a Windows NT system.
1215 The system \"open\" is used for most files.
1216 See `org-file-apps'.")
1218 (defcustom org-file-apps
1220 (auto-mode . emacs)
1221 ("\\.x?html?\\'" . default)
1222 ("\\.pdf\\'" . default)
1224 "External applications for opening `file:path' items in a document.
1225 Org-mode uses system defaults for different file types, but
1226 you can use this variable to set the application for a given file
1227 extension. The entries in this list are cons cells where the car identifies
1228 files and the cdr the corresponding command. Possible values for the
1229 file identifier are
1230 \"regex\" Regular expression matched against the file name. For backward
1231 compatibility, this can also be a string with only alphanumeric
1232 characters, which is then interpreted as an extension.
1233 `directory' Matches a directory
1234 `remote' Matches a remote file, accessible through tramp or efs.
1235 Remote files most likely should be visited through Emacs
1236 because external applications cannot handle such paths.
1237 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1238 so all files Emacs knows how to handle. Using this with
1239 command `emacs' will open most files in Emacs. Beware that this
1240 will also open html files inside Emacs, unless you add
1241 (\"html\" . default) to the list as well.
1242 t Default for files not matched by any of the other options.
1243 `system' The system command to open files, like `open' on Windows
1244 and Mac OS X, and mailcap under GNU/Linux. This is the command
1245 that will be selected if you call `C-c C-o' with a double
1246 `C-u C-u' prefix.
1248 Possible values for the command are:
1249 `emacs' The file will be visited by the current Emacs process.
1250 `default' Use the default application for this file type, which is the
1251 association for t in the list, most likely in the system-specific
1252 part.
1253 This can be used to overrule an unwanted setting in the
1254 system-specific variable.
1255 `system' Use the system command for opening files, like \"open\".
1256 This command is specified by the entry whose car is `system'.
1257 Most likely, the system-specific version of this variable
1258 does define this command, but you can overrule/replace it
1259 here.
1260 string A command to be executed by a shell; %s will be replaced
1261 by the path to the file.
1262 sexp A Lisp form which will be evaluated. The file path will
1263 be available in the Lisp variable `file'.
1264 For more examples, see the system specific constants
1265 `org-file-apps-defaults-macosx'
1266 `org-file-apps-defaults-windowsnt'
1267 `org-file-apps-defaults-gnu'."
1268 :group 'org-link-follow
1269 :type '(repeat
1270 (cons (choice :value ""
1271 (string :tag "Extension")
1272 (const :tag "System command to open files" system)
1273 (const :tag "Default for unrecognized files" t)
1274 (const :tag "Remote file" remote)
1275 (const :tag "Links to a directory" directory)
1276 (const :tag "Any files that have Emacs modes"
1277 auto-mode))
1278 (choice :value ""
1279 (const :tag "Visit with Emacs" emacs)
1280 (const :tag "Use default" default)
1281 (const :tag "Use the system command" system)
1282 (string :tag "Command")
1283 (sexp :tag "Lisp form")))))
1285 (defgroup org-refile nil
1286 "Options concerning refiling entries in Org-mode."
1287 :tag "Org Refile"
1288 :group 'org)
1290 (defcustom org-directory "~/org"
1291 "Directory with org files.
1292 This directory will be used as default to prompt for org files.
1293 Used by the hooks for remember.el."
1294 :group 'org-refile
1295 :group 'org-remember
1296 :type 'directory)
1298 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1299 "Default target for storing notes.
1300 Used by the hooks for remember.el. This can be a string, or nil to mean
1301 the value of `remember-data-file'.
1302 You can set this on a per-template basis with the variable
1303 `org-remember-templates'."
1304 :group 'org-refile
1305 :group 'org-remember
1306 :type '(choice
1307 (const :tag "Default from remember-data-file" nil)
1308 file))
1310 (defcustom org-goto-interface 'outline
1311 "The default interface to be used for `org-goto'.
1312 Allowed values are:
1313 outline The interface shows an outline of the relevant file
1314 and the correct heading is found by moving through
1315 the outline or by searching with incremental search.
1316 outline-path-completion Headlines in the current buffer are offered via
1317 completion. This is the interface also used by
1318 the refile command."
1319 :group 'org-refile
1320 :type '(choice
1321 (const :tag "Outline" outline)
1322 (const :tag "Outline-path-completion" outline-path-completion)))
1324 (defcustom org-goto-max-level 5
1325 "Maximum level to be considered when running org-goto with refile interface."
1326 :group 'org-refile
1327 :type 'number)
1329 (defcustom org-reverse-note-order nil
1330 "Non-nil means, store new notes at the beginning of a file or entry.
1331 When nil, new notes will be filed to the end of a file or entry.
1332 This can also be a list with cons cells of regular expressions that
1333 are matched against file names, and values."
1334 :group 'org-remember
1335 :group 'org-refile
1336 :type '(choice
1337 (const :tag "Reverse always" t)
1338 (const :tag "Reverse never" nil)
1339 (repeat :tag "By file name regexp"
1340 (cons regexp boolean))))
1342 (defcustom org-refile-targets nil
1343 "Targets for refiling entries with \\[org-refile].
1344 This is list of cons cells. Each cell contains:
1345 - a specification of the files to be considered, either a list of files,
1346 or a symbol whose function or variable value will be used to retrieve
1347 a file name or a list of file names. If you use `org-agenda-files' for
1348 that, all agenda files will be scanned for targets. Nil means, consider
1349 headings in the current buffer.
1350 - A specification of how to select find candidate refile targets. This
1351 may be any of
1352 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1353 This tag has to be present in all target headlines, inheritance will
1354 not be considered.
1355 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1356 todo keyword.
1357 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1358 headlines that are refiling targets.
1359 - a cons cell (:level . N). Any headline of level N is considered a target.
1360 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1362 When this variable is nil, all top-level headlines in the current buffer
1363 are used, equivalent to the value `((nil . (:level . 1))'."
1364 :group 'org-refile
1365 :type '(repeat
1366 (cons
1367 (choice :value org-agenda-files
1368 (const :tag "All agenda files" org-agenda-files)
1369 (const :tag "Current buffer" nil)
1370 (function) (variable) (file))
1371 (choice :tag "Identify target headline by"
1372 (cons :tag "Specific tag" (const :value :tag) (string))
1373 (cons :tag "TODO keyword" (const :value :todo) (string))
1374 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1375 (cons :tag "Level number" (const :value :level) (integer))
1376 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1378 (defcustom org-refile-use-outline-path nil
1379 "Non-nil means, provide refile targets as paths.
1380 So a level 3 headline will be available as level1/level2/level3.
1381 When the value is `file', also include the file name (without directory)
1382 into the path. When `full-file-path', include the full file path."
1383 :group 'org-refile
1384 :type '(choice
1385 (const :tag "Not" nil)
1386 (const :tag "Yes" t)
1387 (const :tag "Start with file name" file)
1388 (const :tag "Start with full file path" full-file-path)))
1390 (defcustom org-outline-path-complete-in-steps t
1391 "Non-nil means, complete the outline path in hierarchical steps.
1392 When Org-mode uses the refile interface to select an outline path
1393 \(see variable `org-refile-use-outline-path'), the completion of
1394 the path can be done is a single go, or if can be done in steps down
1395 the headline hierarchy. Going in steps is probably the best if you
1396 do not use a special completion package like `ido' or `icicles'.
1397 However, when using these packages, going in one step can be very
1398 fast, while still showing the whole path to the entry."
1399 :group 'org-refile
1400 :type 'boolean)
1402 (defgroup org-todo nil
1403 "Options concerning TODO items in Org-mode."
1404 :tag "Org TODO"
1405 :group 'org)
1407 (defgroup org-progress nil
1408 "Options concerning Progress logging in Org-mode."
1409 :tag "Org Progress"
1410 :group 'org-time)
1412 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1413 "List of TODO entry keyword sequences and their interpretation.
1414 \\<org-mode-map>This is a list of sequences.
1416 Each sequence starts with a symbol, either `sequence' or `type',
1417 indicating if the keywords should be interpreted as a sequence of
1418 action steps, or as different types of TODO items. The first
1419 keywords are states requiring action - these states will select a headline
1420 for inclusion into the global TODO list Org-mode produces. If one of
1421 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1422 signify that no further action is necessary. If \"|\" is not found,
1423 the last keyword is treated as the only DONE state of the sequence.
1425 The command \\[org-todo] cycles an entry through these states, and one
1426 additional state where no keyword is present. For details about this
1427 cycling, see the manual.
1429 TODO keywords and interpretation can also be set on a per-file basis with
1430 the special #+SEQ_TODO and #+TYP_TODO lines.
1432 Each keyword can optionally specify a character for fast state selection
1433 \(in combination with the variable `org-use-fast-todo-selection')
1434 and specifiers for state change logging, using the same syntax
1435 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1436 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1437 indicates to record a time stamp each time this state is selected.
1439 Each keyword may also specify if a timestamp or a note should be
1440 recorded when entering or leaving the state, by adding additional
1441 characters in the parenthesis after the keyword. This looks like this:
1442 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1443 record only the time of the state change. With X and Y being either
1444 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1445 Y when leaving the state if and only if the *target* state does not
1446 define X. You may omit any of the fast-selection key or X or /Y,
1447 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1449 For backward compatibility, this variable may also be just a list
1450 of keywords - in this case the interpretation (sequence or type) will be
1451 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1452 :group 'org-todo
1453 :group 'org-keywords
1454 :type '(choice
1455 (repeat :tag "Old syntax, just keywords"
1456 (string :tag "Keyword"))
1457 (repeat :tag "New syntax"
1458 (cons
1459 (choice
1460 :tag "Interpretation"
1461 (const :tag "Sequence (cycling hits every state)" sequence)
1462 (const :tag "Type (cycling directly to DONE)" type))
1463 (repeat
1464 (string :tag "Keyword"))))))
1466 (defvar org-todo-keywords-1 nil
1467 "All TODO and DONE keywords active in a buffer.")
1468 (make-variable-buffer-local 'org-todo-keywords-1)
1469 (defvar org-todo-keywords-for-agenda nil)
1470 (defvar org-done-keywords-for-agenda nil)
1471 (defvar org-todo-keyword-alist-for-agenda nil)
1472 (defvar org-tag-alist-for-agenda nil)
1473 (defvar org-agenda-contributing-files nil)
1474 (defvar org-not-done-keywords nil)
1475 (make-variable-buffer-local 'org-not-done-keywords)
1476 (defvar org-done-keywords nil)
1477 (make-variable-buffer-local 'org-done-keywords)
1478 (defvar org-todo-heads nil)
1479 (make-variable-buffer-local 'org-todo-heads)
1480 (defvar org-todo-sets nil)
1481 (make-variable-buffer-local 'org-todo-sets)
1482 (defvar org-todo-log-states nil)
1483 (make-variable-buffer-local 'org-todo-log-states)
1484 (defvar org-todo-kwd-alist nil)
1485 (make-variable-buffer-local 'org-todo-kwd-alist)
1486 (defvar org-todo-key-alist nil)
1487 (make-variable-buffer-local 'org-todo-key-alist)
1488 (defvar org-todo-key-trigger nil)
1489 (make-variable-buffer-local 'org-todo-key-trigger)
1491 (defcustom org-todo-interpretation 'sequence
1492 "Controls how TODO keywords are interpreted.
1493 This variable is in principle obsolete and is only used for
1494 backward compatibility, if the interpretation of todo keywords is
1495 not given already in `org-todo-keywords'. See that variable for
1496 more information."
1497 :group 'org-todo
1498 :group 'org-keywords
1499 :type '(choice (const sequence)
1500 (const type)))
1502 (defcustom org-use-fast-todo-selection 'prefix
1503 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1504 This variable describes if and under what circumstances the cycling
1505 mechanism for TODO keywords will be replaced by a single-key, direct
1506 selection scheme.
1508 When nil, fast selection is never used.
1510 When the symbol `prefix', it will be used when `org-todo' is called with
1511 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1512 in an agenda buffer.
1514 When t, fast selection is used by default. In this case, the prefix
1515 argument forces cycling instead.
1517 In all cases, the special interface is only used if access keys have actually
1518 been assigned by the user, i.e. if keywords in the configuration are followed
1519 by a letter in parenthesis, like TODO(t)."
1520 :group 'org-todo
1521 :type '(choice
1522 (const :tag "Never" nil)
1523 (const :tag "By default" t)
1524 (const :tag "Only with C-u C-c C-t" prefix)))
1526 (defcustom org-provide-todo-statistics t
1527 "Non-nil means, update todo statistics after insert and toggle.
1528 When this is set, todo statistics is updated in the parent of the current
1529 entry each time a todo state is changed."
1530 :group 'org-todo
1531 :type 'boolean)
1533 (defcustom org-after-todo-state-change-hook nil
1534 "Hook which is run after the state of a TODO item was changed.
1535 The new state (a string with a TODO keyword, or nil) is available in the
1536 Lisp variable `state'."
1537 :group 'org-todo
1538 :type 'hook)
1540 (defcustom org-todo-state-tags-triggers nil
1541 "Tag changes that should be triggered by TODO state changes.
1542 This is a list. Each entry is
1544 (state-change (tag . flag) .......)
1546 State-change can be a string with a state, and empty string to indicate the
1547 state that has no TODO keyword, or it can be one of the symbols `todo'
1548 or `done', meaning any not-done or done state, respectively."
1549 :group 'org-todo
1550 :group 'org-tags
1551 :type '(repeat
1552 (cons (choice :tag "When changing to"
1553 (const :tag "Not-done state" todo)
1554 (const :tag "Done state" done)
1555 (string :tag "State"))
1556 (repeat
1557 (cons :tag "Tag action"
1558 (string :tag "Tag")
1559 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1561 (defcustom org-log-done nil
1562 "Information to record when a task moves to the DONE state.
1564 Possible values are:
1566 nil Don't add anything, just change the keyword
1567 time Add a time stamp to the task
1568 note Prompt a closing note and add it with template `org-log-note-headings'
1570 This option can also be set with on a per-file-basis with
1572 #+STARTUP: nologdone
1573 #+STARTUP: logdone
1574 #+STARTUP: lognotedone
1576 You can have local logging settings for a subtree by setting the LOGGING
1577 property to one or more of these keywords."
1578 :group 'org-todo
1579 :group 'org-progress
1580 :type '(choice
1581 (const :tag "No logging" nil)
1582 (const :tag "Record CLOSED timestamp" time)
1583 (const :tag "Record CLOSED timestamp with closing note." note)))
1585 ;; Normalize old uses of org-log-done.
1586 (cond
1587 ((eq org-log-done t) (setq org-log-done 'time))
1588 ((and (listp org-log-done) (memq 'done org-log-done))
1589 (setq org-log-done 'note)))
1591 (defcustom org-log-note-clock-out nil
1592 "Non-nil means, record a note when clocking out of an item.
1593 This can also be configured on a per-file basis by adding one of
1594 the following lines anywhere in the buffer:
1596 #+STARTUP: lognoteclock-out
1597 #+STARTUP: nolognoteclock-out"
1598 :group 'org-todo
1599 :group 'org-progress
1600 :type 'boolean)
1602 (defcustom org-log-done-with-time t
1603 "Non-nil means, the CLOSED time stamp will contain date and time.
1604 When nil, only the date will be recorded."
1605 :group 'org-progress
1606 :type 'boolean)
1608 (defcustom org-log-note-headings
1609 '((done . "CLOSING NOTE %t")
1610 (state . "State %-12s %t")
1611 (note . "Note taken on %t")
1612 (clock-out . ""))
1613 "Headings for notes added to entries.
1614 The value is an alist, with the car being a symbol indicating the note
1615 context, and the cdr is the heading to be used. The heading may also be the
1616 empty string.
1617 %t in the heading will be replaced by a time stamp.
1618 %s will be replaced by the new TODO state, in double quotes.
1619 %u will be replaced by the user name.
1620 %U will be replaced by the full user name."
1621 :group 'org-todo
1622 :group 'org-progress
1623 :type '(list :greedy t
1624 (cons (const :tag "Heading when closing an item" done) string)
1625 (cons (const :tag
1626 "Heading when changing todo state (todo sequence only)"
1627 state) string)
1628 (cons (const :tag "Heading when just taking a note" note) string)
1629 (cons (const :tag "Heading when clocking out" clock-out) string)))
1631 (unless (assq 'note org-log-note-headings)
1632 (push '(note . "%t") org-log-note-headings))
1634 (defcustom org-log-state-notes-insert-after-drawers nil
1635 "Non-nil means, insert state change notes after any drawers in entry.
1636 Only the drawers that *immediately* follow the headline and the
1637 deadline/scheduled line are skipped.
1638 When nil, insert notes right after the heading and perhaps the line
1639 with deadline/scheduling if present."
1640 :group 'org-todo
1641 :group 'org-progress
1642 :type 'boolean)
1644 (defcustom org-log-states-order-reversed t
1645 "Non-nil means, the latest state change note will be directly after heading.
1646 When nil, the notes will be orderer according to time."
1647 :group 'org-todo
1648 :group 'org-progress
1649 :type 'boolean)
1651 (defcustom org-log-repeat 'time
1652 "Non-nil means, record moving through the DONE state when triggering repeat.
1653 An auto-repeating tasks is immediately switched back to TODO when marked
1654 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1655 the TODO keyword definition, or recording a closing note by setting
1656 `org-log-done', there will be no record of the task moving through DONE.
1657 This variable forces taking a note anyway. Possible values are:
1659 nil Don't force a record
1660 time Record a time stamp
1661 note Record a note
1663 This option can also be set with on a per-file-basis with
1665 #+STARTUP: logrepeat
1666 #+STARTUP: lognoterepeat
1667 #+STARTUP: nologrepeat
1669 You can have local logging settings for a subtree by setting the LOGGING
1670 property to one or more of these keywords."
1671 :group 'org-todo
1672 :group 'org-progress
1673 :type '(choice
1674 (const :tag "Don't force a record" nil)
1675 (const :tag "Force recording the DONE state" time)
1676 (const :tag "Force recording a note with the DONE state" note)))
1679 (defgroup org-priorities nil
1680 "Priorities in Org-mode."
1681 :tag "Org Priorities"
1682 :group 'org-todo)
1684 (defcustom org-highest-priority ?A
1685 "The highest priority of TODO items. A character like ?A, ?B etc.
1686 Must have a smaller ASCII number than `org-lowest-priority'."
1687 :group 'org-priorities
1688 :type 'character)
1690 (defcustom org-lowest-priority ?C
1691 "The lowest priority of TODO items. A character like ?A, ?B etc.
1692 Must have a larger ASCII number than `org-highest-priority'."
1693 :group 'org-priorities
1694 :type 'character)
1696 (defcustom org-default-priority ?B
1697 "The default priority of TODO items.
1698 This is the priority an item get if no explicit priority is given."
1699 :group 'org-priorities
1700 :type 'character)
1702 (defcustom org-priority-start-cycle-with-default t
1703 "Non-nil means, start with default priority when starting to cycle.
1704 When this is nil, the first step in the cycle will be (depending on the
1705 command used) one higher or lower that the default priority."
1706 :group 'org-priorities
1707 :type 'boolean)
1709 (defgroup org-time nil
1710 "Options concerning time stamps and deadlines in Org-mode."
1711 :tag "Org Time"
1712 :group 'org)
1714 (defcustom org-insert-labeled-timestamps-at-point nil
1715 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1716 When nil, these labeled time stamps are forces into the second line of an
1717 entry, just after the headline. When scheduling from the global TODO list,
1718 the time stamp will always be forced into the second line."
1719 :group 'org-time
1720 :type 'boolean)
1722 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1723 "Formats for `format-time-string' which are used for time stamps.
1724 It is not recommended to change this constant.")
1726 (defcustom org-time-stamp-rounding-minutes '(0 5)
1727 "Number of minutes to round time stamps to.
1728 These are two values, the first applies when first creating a time stamp.
1729 The second applies when changing it with the commands `S-up' and `S-down'.
1730 When changing the time stamp, this means that it will change in steps
1731 of N minutes, as given by the second value.
1733 When a setting is 0 or 1, insert the time unmodified. Useful rounding
1734 numbers should be factors of 60, so for example 5, 10, 15.
1736 When this is larger than 1, you can still force an exact time-stamp by using
1737 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
1738 and by using a prefix arg to `S-up/down' to specify the exact number
1739 of minutes to shift."
1740 :group 'org-time
1741 :get '(lambda (var) ; Make sure all entries have 5 elements
1742 (if (integerp (default-value var))
1743 (list (default-value var) 5)
1744 (default-value var)))
1745 :type '(list
1746 (integer :tag "when inserting times")
1747 (integer :tag "when modifying times")))
1749 ;; Normalize old customizations of this variable.
1750 (when (integerp org-time-stamp-rounding-minutes)
1751 (setq org-time-stamp-rounding-minutes
1752 (list org-time-stamp-rounding-minutes
1753 org-time-stamp-rounding-minutes)))
1755 (defcustom org-display-custom-times nil
1756 "Non-nil means, overlay custom formats over all time stamps.
1757 The formats are defined through the variable `org-time-stamp-custom-formats'.
1758 To turn this on on a per-file basis, insert anywhere in the file:
1759 #+STARTUP: customtime"
1760 :group 'org-time
1761 :set 'set-default
1762 :type 'sexp)
1763 (make-variable-buffer-local 'org-display-custom-times)
1765 (defcustom org-time-stamp-custom-formats
1766 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1767 "Custom formats for time stamps. See `format-time-string' for the syntax.
1768 These are overlayed over the default ISO format if the variable
1769 `org-display-custom-times' is set. Time like %H:%M should be at the
1770 end of the second format."
1771 :group 'org-time
1772 :type 'sexp)
1774 (defun org-time-stamp-format (&optional long inactive)
1775 "Get the right format for a time string."
1776 (let ((f (if long (cdr org-time-stamp-formats)
1777 (car org-time-stamp-formats))))
1778 (if inactive
1779 (concat "[" (substring f 1 -1) "]")
1780 f)))
1782 (defcustom org-time-clocksum-format "%d:%02d"
1783 "The format string used when creating CLOCKSUM lines, or when
1784 org-mode generates a time duration."
1785 :group 'org-time
1786 :type 'string)
1788 (defcustom org-deadline-warning-days 14
1789 "No. of days before expiration during which a deadline becomes active.
1790 This variable governs the display in sparse trees and in the agenda.
1791 When 0 or negative, it means use this number (the absolute value of it)
1792 even if a deadline has a different individual lead time specified."
1793 :group 'org-time
1794 :group 'org-agenda-daily/weekly
1795 :type 'number)
1797 (defcustom org-read-date-prefer-future t
1798 "Non-nil means, assume future for incomplete date input from user.
1799 This affects the following situations:
1800 1. The user gives a day, but no month.
1801 For example, if today is the 15th, and you enter \"3\", Org-mode will
1802 read this as the third of *next* month. However, if you enter \"17\",
1803 it will be considered as *this* month.
1804 2. The user gives a month but not a year.
1805 For example, if it is april and you enter \"feb 2\", this will be read
1806 as feb 2, *next* year. \"May 5\", however, will be this year.
1808 Currently this does not work for ISO week specifications.
1810 When this option is nil, the current month and year will always be used
1811 as defaults."
1812 :group 'org-time
1813 :type 'boolean)
1815 (defcustom org-read-date-display-live t
1816 "Non-nil means, display current interpretation of date prompt live.
1817 This display will be in an overlay, in the minibuffer."
1818 :group 'org-time
1819 :type 'boolean)
1821 (defcustom org-read-date-popup-calendar t
1822 "Non-nil means, pop up a calendar when prompting for a date.
1823 In the calendar, the date can be selected with mouse-1. However, the
1824 minibuffer will also be active, and you can simply enter the date as well.
1825 When nil, only the minibuffer will be available."
1826 :group 'org-time
1827 :type 'boolean)
1828 (if (fboundp 'defvaralias)
1829 (defvaralias 'org-popup-calendar-for-date-prompt
1830 'org-read-date-popup-calendar))
1832 (defcustom org-extend-today-until 0
1833 "The hour when your day really ends. Must be an integer.
1834 This has influence for the following applications:
1835 - When switching the agenda to \"today\". It it is still earlier than
1836 the time given here, the day recognized as TODAY is actually yesterday.
1837 - When a date is read from the user and it is still before the time given
1838 here, the current date and time will be assumed to be yesterday, 23:59.
1839 Also, timestamps inserted in remember templates follow this rule.
1841 IMPORTANT: This is a feature whose implementation is and likely will
1842 remain incomplete. Really, it is only here because past midnight seems to
1843 be the favorite working time of John Wiegley :-)"
1844 :group 'org-time
1845 :type 'number)
1847 (defcustom org-edit-timestamp-down-means-later nil
1848 "Non-nil means, S-down will increase the time in a time stamp.
1849 When nil, S-up will increase."
1850 :group 'org-time
1851 :type 'boolean)
1853 (defcustom org-calendar-follow-timestamp-change t
1854 "Non-nil means, make the calendar window follow timestamp changes.
1855 When a timestamp is modified and the calendar window is visible, it will be
1856 moved to the new date."
1857 :group 'org-time
1858 :type 'boolean)
1860 (defgroup org-tags nil
1861 "Options concerning tags in Org-mode."
1862 :tag "Org Tags"
1863 :group 'org)
1865 (defcustom org-tag-alist nil
1866 "List of tags allowed in Org-mode files.
1867 When this list is nil, Org-mode will base TAG input on what is already in the
1868 buffer.
1869 The value of this variable is an alist, the car of each entry must be a
1870 keyword as a string, the cdr may be a character that is used to select
1871 that tag through the fast-tag-selection interface.
1872 See the manual for details."
1873 :group 'org-tags
1874 :type '(repeat
1875 (choice
1876 (cons (string :tag "Tag name")
1877 (character :tag "Access char"))
1878 (const :tag "Start radio group" (:startgroup))
1879 (const :tag "End radio group" (:endgroup)))))
1881 (defvar org-file-tags nil
1882 "List of tags that can be inherited by all entries in the file.
1883 The tags will be inherited if the variable `org-use-tag-inheritance'
1884 says they should be.
1885 This variable is populated from #+TAG lines.")
1887 (defcustom org-use-fast-tag-selection 'auto
1888 "Non-nil means, use fast tag selection scheme.
1889 This is a special interface to select and deselect tags with single keys.
1890 When nil, fast selection is never used.
1891 When the symbol `auto', fast selection is used if and only if selection
1892 characters for tags have been configured, either through the variable
1893 `org-tag-alist' or through a #+TAGS line in the buffer.
1894 When t, fast selection is always used and selection keys are assigned
1895 automatically if necessary."
1896 :group 'org-tags
1897 :type '(choice
1898 (const :tag "Always" t)
1899 (const :tag "Never" nil)
1900 (const :tag "When selection characters are configured" 'auto)))
1902 (defcustom org-fast-tag-selection-single-key nil
1903 "Non-nil means, fast tag selection exits after first change.
1904 When nil, you have to press RET to exit it.
1905 During fast tag selection, you can toggle this flag with `C-c'.
1906 This variable can also have the value `expert'. In this case, the window
1907 displaying the tags menu is not even shown, until you press C-c again."
1908 :group 'org-tags
1909 :type '(choice
1910 (const :tag "No" nil)
1911 (const :tag "Yes" t)
1912 (const :tag "Expert" expert)))
1914 (defvar org-fast-tag-selection-include-todo nil
1915 "Non-nil means, fast tags selection interface will also offer TODO states.
1916 This is an undocumented feature, you should not rely on it.")
1918 (defcustom org-tags-column (if (featurep 'xemacs) -79 -80)
1919 "The column to which tags should be indented in a headline.
1920 If this number is positive, it specifies the column. If it is negative,
1921 it means that the tags should be flushright to that column. For example,
1922 -80 works well for a normal 80 character screen."
1923 :group 'org-tags
1924 :type 'integer)
1926 (defcustom org-auto-align-tags t
1927 "Non-nil means, realign tags after pro/demotion of TODO state change.
1928 These operations change the length of a headline and therefore shift
1929 the tags around. With this options turned on, after each such operation
1930 the tags are again aligned to `org-tags-column'."
1931 :group 'org-tags
1932 :type 'boolean)
1934 (defcustom org-use-tag-inheritance t
1935 "Non-nil means, tags in levels apply also for sublevels.
1936 When nil, only the tags directly given in a specific line apply there.
1937 This may also be a list of tags that should be inherited, or a regexp that
1938 matches tags that should be inherited. Additional control is possible
1939 with the variable `org-tags-exclude-from-inheritance' which gives an
1940 explicit list of tags to be excluded from inheritance., even if the value of
1941 `org-use-tag-inheritance' would select it for inheritance.
1943 If this option is t, a match early-on in a tree can lead to a large
1944 number of matches in the subtree when constructing the agenda or creating
1945 a sparse tree. If you only want to see the first match in a tree during
1946 a search, check out the variable `org-tags-match-list-sublevels'."
1947 :group 'org-tags
1948 :type '(choice
1949 (const :tag "Not" nil)
1950 (const :tag "Always" t)
1951 (repeat :tag "Specific tags" (string :tag "Tag"))
1952 (regexp :tag "Tags matched by regexp")))
1954 (defcustom org-tags-exclude-from-inheritance nil
1955 "List of tags that should never be inherited.
1956 This is a way to exclude a few tags from inheritance. For way to do
1957 the opposite, to actively allow inheritance for selected tags,
1958 see the variable `org-use-tag-inheritance'."
1959 :group 'org-tags
1960 :type '(repeat (string :tag "Tag")))
1962 (defun org-tag-inherit-p (tag)
1963 "Check if TAG is one that should be inherited."
1964 (cond
1965 ((member tag org-tags-exclude-from-inheritance) nil)
1966 ((eq org-use-tag-inheritance t) t)
1967 ((not org-use-tag-inheritance) nil)
1968 ((stringp org-use-tag-inheritance)
1969 (string-match org-use-tag-inheritance tag))
1970 ((listp org-use-tag-inheritance)
1971 (member tag org-use-tag-inheritance))
1972 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
1974 (defcustom org-tags-match-list-sublevels t
1975 "Non-nil means list also sublevels of headlines matching tag search.
1976 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1977 the sublevels of a headline matching a tag search often also match
1978 the same search. Listing all of them can create very long lists.
1979 Setting this variable to nil causes subtrees of a match to be skipped.
1980 This option is off by default, because inheritance in on. If you turn
1981 inheritance off, you very likely want to turn this option on.
1983 As a special case, if the tag search is restricted to TODO items, the
1984 value of this variable is ignored and sublevels are always checked, to
1985 make sure all corresponding TODO items find their way into the list.
1987 This variable is semi-obsolete and probably should always be true. It
1988 is better to limit inheritance to certain tags using the variables
1989 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
1990 :group 'org-tags
1991 :type 'boolean)
1993 (defvar org-tags-history nil
1994 "History of minibuffer reads for tags.")
1995 (defvar org-last-tags-completion-table nil
1996 "The last used completion table for tags.")
1997 (defvar org-after-tags-change-hook nil
1998 "Hook that is run after the tags in a line have changed.")
2000 (defgroup org-properties nil
2001 "Options concerning properties in Org-mode."
2002 :tag "Org Properties"
2003 :group 'org)
2005 (defcustom org-property-format "%-10s %s"
2006 "How property key/value pairs should be formatted by `indent-line'.
2007 When `indent-line' hits a property definition, it will format the line
2008 according to this format, mainly to make sure that the values are
2009 lined-up with respect to each other."
2010 :group 'org-properties
2011 :type 'string)
2013 (defcustom org-use-property-inheritance nil
2014 "Non-nil means, properties apply also for sublevels.
2016 This setting is chiefly used during property searches. Turning it on can
2017 cause significant overhead when doing a search, which is why it is not
2018 on by default.
2020 When nil, only the properties directly given in the current entry count.
2021 When t, every property is inherited. The value may also be a list of
2022 properties that should have inheritance, or a regular expression matching
2023 properties that should be inherited.
2025 However, note that some special properties use inheritance under special
2026 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2027 and the properties ending in \"_ALL\" when they are used as descriptor
2028 for valid values of a property.
2030 Note for programmers:
2031 When querying an entry with `org-entry-get', you can control if inheritance
2032 should be used. By default, `org-entry-get' looks only at the local
2033 properties. You can request inheritance by setting the inherit argument
2034 to t (to force inheritance) or to `selective' (to respect the setting
2035 in this variable)."
2036 :group 'org-properties
2037 :type '(choice
2038 (const :tag "Not" nil)
2039 (const :tag "Always" t)
2040 (repeat :tag "Specific properties" (string :tag "Property"))
2041 (regexp :tag "Properties matched by regexp")))
2043 (defun org-property-inherit-p (property)
2044 "Check if PROPERTY is one that should be inherited."
2045 (cond
2046 ((eq org-use-property-inheritance t) t)
2047 ((not org-use-property-inheritance) nil)
2048 ((stringp org-use-property-inheritance)
2049 (string-match org-use-property-inheritance property))
2050 ((listp org-use-property-inheritance)
2051 (member property org-use-property-inheritance))
2052 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2054 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2055 "The default column format, if no other format has been defined.
2056 This variable can be set on the per-file basis by inserting a line
2058 #+COLUMNS: %25ITEM ....."
2059 :group 'org-properties
2060 :type 'string)
2062 (defcustom org-columns-ellipses ".."
2063 "The ellipses to be used when a field in column view is truncated.
2064 When this is the empty string, as many characters as possible are shown,
2065 but then there will be no visual indication that the field has been truncated.
2066 When this is a string of length N, the last N characters of a truncated
2067 field are replaced by this string. If the column is narrower than the
2068 ellipses string, only part of the ellipses string will be shown."
2069 :group 'org-properties
2070 :type 'string)
2072 (defcustom org-columns-modify-value-for-display-function nil
2073 "Function that modifies values for display in column view.
2074 For example, it can be used to cut out a certain part from a time stamp.
2075 The function must take 2 arguments:
2077 column-title The title of the column (*not* the property name)
2078 value The value that should be modified.
2080 The function should return the value that should be displayed,
2081 or nil if the normal value should be used."
2082 :group 'org-properties
2083 :type 'function)
2085 (defcustom org-effort-property "Effort"
2086 "The property that is being used to keep track of effort estimates.
2087 Effort estimates given in this property need to have the format H:MM."
2088 :group 'org-properties
2089 :group 'org-progress
2090 :type '(string :tag "Property"))
2092 (defconst org-global-properties-fixed
2093 '(("VISIBILITY_ALL" . "folded children content all"))
2094 "List of property/value pairs that can be inherited by any entry.
2095 These are fixed values, for the preset properties.")
2098 (defcustom org-global-properties nil
2099 "List of property/value pairs that can be inherited by any entry.
2100 You can set buffer-local values for the same purpose in the variable
2101 `org-file-properties' this by adding lines like
2103 #+PROPERTY: NAME VALUE"
2104 :group 'org-properties
2105 :type '(repeat
2106 (cons (string :tag "Property")
2107 (string :tag "Value"))))
2109 (defvar org-file-properties nil
2110 "List of property/value pairs that can be inherited by any entry.
2111 Valid for the current buffer.
2112 This variable is populated from #+PROPERTY lines.")
2113 (make-variable-buffer-local 'org-file-properties)
2115 (defgroup org-agenda nil
2116 "Options concerning agenda views in Org-mode."
2117 :tag "Org Agenda"
2118 :group 'org)
2120 (defvar org-category nil
2121 "Variable used by org files to set a category for agenda display.
2122 Such files should use a file variable to set it, for example
2124 # -*- mode: org; org-category: \"ELisp\"
2126 or contain a special line
2128 #+CATEGORY: ELisp
2130 If the file does not specify a category, then file's base name
2131 is used instead.")
2132 (make-variable-buffer-local 'org-category)
2133 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2135 (defcustom org-agenda-files nil
2136 "The files to be used for agenda display.
2137 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2138 \\[org-remove-file]. You can also use customize to edit the list.
2140 If an entry is a directory, all files in that directory that are matched by
2141 `org-agenda-file-regexp' will be part of the file list.
2143 If the value of the variable is not a list but a single file name, then
2144 the list of agenda files is actually stored and maintained in that file, one
2145 agenda file per line."
2146 :group 'org-agenda
2147 :type '(choice
2148 (repeat :tag "List of files and directories" file)
2149 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2151 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2152 "Regular expression to match files for `org-agenda-files'.
2153 If any element in the list in that variable contains a directory instead
2154 of a normal file, all files in that directory that are matched by this
2155 regular expression will be included."
2156 :group 'org-agenda
2157 :type 'regexp)
2159 (defcustom org-agenda-text-search-extra-files nil
2160 "List of extra files to be searched by text search commands.
2161 These files will be search in addition to the agenda files by the
2162 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2163 Note that these files will only be searched for text search commands,
2164 not for the other agenda views like todo lists, tag searches or the weekly
2165 agenda. This variable is intended to list notes and possibly archive files
2166 that should also be searched by these two commands.
2167 In fact, if the first element in the list is the symbol `agenda-archives',
2168 than all archive files of all agenda files will be added to the search
2169 scope."
2170 :group 'org-agenda
2171 :type '(set :greedy t
2172 (const :tag "Agenda Archives" agenda-archives)
2173 (repeat :inline t (file))))
2175 (if (fboundp 'defvaralias)
2176 (defvaralias 'org-agenda-multi-occur-extra-files
2177 'org-agenda-text-search-extra-files))
2179 (defcustom org-agenda-skip-unavailable-files nil
2180 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2181 A nil value means to remove them, after a query, from the list."
2182 :group 'org-agenda
2183 :type 'boolean)
2185 (defcustom org-calendar-to-agenda-key [?c]
2186 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2187 The command `org-calendar-goto-agenda' will be bound to this key. The
2188 default is the character `c' because then `c' can be used to switch back and
2189 forth between agenda and calendar."
2190 :group 'org-agenda
2191 :type 'sexp)
2193 (defcustom org-calendar-agenda-action-key [?k]
2194 "The key to be installed in `calendar-mode-map' for agenda-action.
2195 The command `org-agenda-action' will be bound to this key. The
2196 default is the character `k' because we use the same key in the agenda."
2197 :group 'org-agenda
2198 :type 'sexp)
2200 (eval-after-load "calendar"
2201 '(progn
2202 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2203 'org-calendar-goto-agenda)
2204 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2205 'org-agenda-action)))
2207 (defgroup org-latex nil
2208 "Options for embedding LaTeX code into Org-mode."
2209 :tag "Org LaTeX"
2210 :group 'org)
2212 (defcustom org-format-latex-options
2213 '(:foreground default :background default :scale 1.0
2214 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2215 :matchers ("begin" "$" "$$" "\\(" "\\["))
2216 "Options for creating images from LaTeX fragments.
2217 This is a property list with the following properties:
2218 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2219 `default' means use the foreground of the default face.
2220 :background the background color, or \"Transparent\".
2221 `default' means use the background of the default face.
2222 :scale a scaling factor for the size of the images.
2223 :html-foreground, :html-background, :html-scale
2224 the same numbers for HTML export.
2225 :matchers a list indicating which matchers should be used to
2226 find LaTeX fragments. Valid members of this list are:
2227 \"begin\" find environments
2228 \"$\" find math expressions surrounded by $...$
2229 \"$$\" find math expressions surrounded by $$....$$
2230 \"\\(\" find math expressions surrounded by \\(...\\)
2231 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2232 :group 'org-latex
2233 :type 'plist)
2235 (defcustom org-format-latex-header "\\documentclass{article}
2236 \\usepackage{fullpage} % do not remove
2237 \\usepackage{amssymb}
2238 \\usepackage[usenames]{color}
2239 \\usepackage{amsmath}
2240 \\usepackage{latexsym}
2241 \\usepackage[mathscr]{eucal}
2242 \\pagestyle{empty} % do not remove"
2243 "The document header used for processing LaTeX fragments."
2244 :group 'org-latex
2245 :type 'string)
2248 (defgroup org-font-lock nil
2249 "Font-lock settings for highlighting in Org-mode."
2250 :tag "Org Font Lock"
2251 :group 'org)
2253 (defcustom org-level-color-stars-only nil
2254 "Non-nil means fontify only the stars in each headline.
2255 When nil, the entire headline is fontified.
2256 Changing it requires restart of `font-lock-mode' to become effective
2257 also in regions already fontified."
2258 :group 'org-font-lock
2259 :type 'boolean)
2261 (defcustom org-hide-leading-stars nil
2262 "Non-nil means, hide the first N-1 stars in a headline.
2263 This works by using the face `org-hide' for these stars. This
2264 face is white for a light background, and black for a dark
2265 background. You may have to customize the face `org-hide' to
2266 make this work.
2267 Changing it requires restart of `font-lock-mode' to become effective
2268 also in regions already fontified.
2269 You may also set this on a per-file basis by adding one of the following
2270 lines to the buffer:
2272 #+STARTUP: hidestars
2273 #+STARTUP: showstars"
2274 :group 'org-font-lock
2275 :type 'boolean)
2277 (defcustom org-fontify-done-headline nil
2278 "Non-nil means, change the face of a headline if it is marked DONE.
2279 Normally, only the TODO/DONE keyword indicates the state of a headline.
2280 When this is non-nil, the headline after the keyword is set to the
2281 `org-headline-done' as an additional indication."
2282 :group 'org-font-lock
2283 :type 'boolean)
2285 (defcustom org-fontify-emphasized-text t
2286 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2287 Changing this variable requires a restart of Emacs to take effect."
2288 :group 'org-font-lock
2289 :type 'boolean)
2291 (defcustom org-highlight-latex-fragments-and-specials nil
2292 "Non-nil means, fontify what is treated specially by the exporters."
2293 :group 'org-font-lock
2294 :type 'boolean)
2296 (defcustom org-hide-emphasis-markers nil
2297 "Non-nil mean font-lock should hide the emphasis marker characters."
2298 :group 'org-font-lock
2299 :type 'boolean)
2301 (defvar org-emph-re nil
2302 "Regular expression for matching emphasis.")
2303 (defvar org-verbatim-re nil
2304 "Regular expression for matching verbatim text.")
2305 (defvar org-emphasis-regexp-components) ; defined just below
2306 (defvar org-emphasis-alist) ; defined just below
2307 (defun org-set-emph-re (var val)
2308 "Set variable and compute the emphasis regular expression."
2309 (set var val)
2310 (when (and (boundp 'org-emphasis-alist)
2311 (boundp 'org-emphasis-regexp-components)
2312 org-emphasis-alist org-emphasis-regexp-components)
2313 (let* ((e org-emphasis-regexp-components)
2314 (pre (car e))
2315 (post (nth 1 e))
2316 (border (nth 2 e))
2317 (body (nth 3 e))
2318 (nl (nth 4 e))
2319 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
2320 (body1 (concat body "*?"))
2321 (markers (mapconcat 'car org-emphasis-alist ""))
2322 (vmarkers (mapconcat
2323 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2324 org-emphasis-alist "")))
2325 ;; make sure special characters appear at the right position in the class
2326 (if (string-match "\\^" markers)
2327 (setq markers (concat (replace-match "" t t markers) "^")))
2328 (if (string-match "-" markers)
2329 (setq markers (concat (replace-match "" t t markers) "-")))
2330 (if (string-match "\\^" vmarkers)
2331 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2332 (if (string-match "-" vmarkers)
2333 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2334 (if (> nl 0)
2335 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2336 (int-to-string nl) "\\}")))
2337 ;; Make the regexp
2338 (setq org-emph-re
2339 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
2340 "\\("
2341 "\\([" markers "]\\)"
2342 "\\("
2343 "[^" border "]\\|"
2344 "[^" border (if (and nil stacked) markers) "]"
2345 body1
2346 "[^" border (if (and nil stacked) markers) "]"
2347 "\\)"
2348 "\\3\\)"
2349 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
2350 (setq org-verbatim-re
2351 (concat "\\([" pre "]\\|^\\)"
2352 "\\("
2353 "\\([" vmarkers "]\\)"
2354 "\\("
2355 "[^" border "]\\|"
2356 "[^" border "]"
2357 body1
2358 "[^" border "]"
2359 "\\)"
2360 "\\3\\)"
2361 "\\([" post "]\\|$\\)")))))
2363 (defcustom org-emphasis-regexp-components
2364 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
2365 "Components used to build the regular expression for emphasis.
2366 This is a list with 6 entries. Terminology: In an emphasis string
2367 like \" *strong word* \", we call the initial space PREMATCH, the final
2368 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2369 and \"trong wor\" is the body. The different components in this variable
2370 specify what is allowed/forbidden in each part:
2372 pre Chars allowed as prematch. Beginning of line will be allowed too.
2373 post Chars allowed as postmatch. End of line will be allowed too.
2374 border The chars *forbidden* as border characters.
2375 body-regexp A regexp like \".\" to match a body character. Don't use
2376 non-shy groups here, and don't allow newline here.
2377 newline The maximum number of newlines allowed in an emphasis exp.
2379 Use customize to modify this, or restart Emacs after changing it."
2380 :group 'org-font-lock
2381 :set 'org-set-emph-re
2382 :type '(list
2383 (sexp :tag "Allowed chars in pre ")
2384 (sexp :tag "Allowed chars in post ")
2385 (sexp :tag "Forbidden chars in border ")
2386 (sexp :tag "Regexp for body ")
2387 (integer :tag "number of newlines allowed")
2388 (option (boolean :tag "Please ignore this button"))))
2390 (defcustom org-emphasis-alist
2391 `(("*" bold "<b>" "</b>")
2392 ("/" italic "<i>" "</i>")
2393 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
2394 ("=" org-code "<code>" "</code>" verbatim)
2395 ("~" org-verbatim "<code>" "</code>" verbatim)
2396 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2397 "<del>" "</del>")
2399 "Special syntax for emphasized text.
2400 Text starting and ending with a special character will be emphasized, for
2401 example *bold*, _underlined_ and /italic/. This variable sets the marker
2402 characters, the face to be used by font-lock for highlighting in Org-mode
2403 Emacs buffers, and the HTML tags to be used for this.
2404 Use customize to modify this, or restart Emacs after changing it."
2405 :group 'org-font-lock
2406 :set 'org-set-emph-re
2407 :type '(repeat
2408 (list
2409 (string :tag "Marker character")
2410 (choice
2411 (face :tag "Font-lock-face")
2412 (plist :tag "Face property list"))
2413 (string :tag "HTML start tag")
2414 (string :tag "HTML end tag")
2415 (option (const verbatim)))))
2417 ;;; Miscellaneous options
2419 (defgroup org-completion nil
2420 "Completion in Org-mode."
2421 :tag "Org Completion"
2422 :group 'org)
2424 (defcustom org-completion-use-ido nil
2425 "Non-nil means, use ido completion wherever possible.
2426 Note that `ido-mode' must be active for this variable to be relevant.
2427 If you decide to turn this variable on, you might well want to turn off
2428 `org-outline-path-complete-in-steps'."
2429 :group 'org-completion
2430 :type 'boolean)
2432 (defcustom org-completion-fallback-command 'hippie-expand
2433 "The expansion command called by \\[org-complete] in normal context.
2434 Normal means, no org-mode-specific context."
2435 :group 'org-completion
2436 :type 'function)
2438 ;;; Functions and variables from ther packages
2439 ;; Declared here to avoid compiler warnings
2441 ;; XEmacs only
2442 (defvar outline-mode-menu-heading)
2443 (defvar outline-mode-menu-show)
2444 (defvar outline-mode-menu-hide)
2445 (defvar zmacs-regions) ; XEmacs regions
2447 ;; Emacs only
2448 (defvar mark-active)
2450 ;; Various packages
2451 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2452 (declare-function calendar-forward-day "cal-move" (arg))
2453 (declare-function calendar-goto-date "cal-move" (date))
2454 (declare-function calendar-goto-today "cal-move" ())
2455 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2456 (defvar calc-embedded-close-formula)
2457 (defvar calc-embedded-open-formula)
2458 (declare-function cdlatex-tab "ext:cdlatex" ())
2459 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2460 (defvar font-lock-unfontify-region-function)
2461 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2462 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2463 (defvar iswitchb-temp-buflist)
2464 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2465 (declare-function org-agenda-skip "org-agenda" ())
2466 (declare-function org-format-agenda-item "org-agenda"
2467 (extra txt &optional category tags dotime noprefix remove-re))
2468 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2469 (declare-function org-agenda-change-all-lines "org-agenda"
2470 (newhead hdmarker &optional fixface just-this))
2471 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2472 (declare-function org-agenda-maybe-redo "org-agenda" ())
2473 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2474 (beg end))
2475 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
2476 (declare-function parse-time-string "parse-time" (string))
2477 (declare-function remember "remember" (&optional initial))
2478 (declare-function remember-buffer-desc "remember" ())
2479 (declare-function remember-finalize "remember" ())
2480 (defvar remember-save-after-remembering)
2481 (defvar remember-data-file)
2482 (defvar remember-register)
2483 (defvar remember-buffer)
2484 (defvar remember-handler-functions)
2485 (defvar remember-annotation-functions)
2486 (defvar texmathp-why)
2487 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2488 (declare-function table--at-cell-p "table" (position &optional object at-column))
2490 (defvar w3m-current-url)
2491 (defvar w3m-current-title)
2493 (defvar org-latex-regexps)
2495 ;;; Autoload and prepare some org modules
2497 ;; Some table stuff that needs to be defined here, because it is used
2498 ;; by the functions setting up org-mode or checking for table context.
2500 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2501 "Detects an org-type or table-type table.")
2502 (defconst org-table-line-regexp "^[ \t]*|"
2503 "Detects an org-type table line.")
2504 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2505 "Detects an org-type table line.")
2506 (defconst org-table-hline-regexp "^[ \t]*|-"
2507 "Detects an org-type table hline.")
2508 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2509 "Detects a table-type table hline.")
2510 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2511 "Searching from within a table (any type) this finds the first line
2512 outside the table.")
2514 ;; Autoload the functions in org-table.el that are needed by functions here.
2516 (eval-and-compile
2517 (org-autoload "org-table"
2518 '(org-table-align org-table-begin org-table-blank-field
2519 org-table-convert org-table-convert-region org-table-copy-down
2520 org-table-copy-region org-table-create
2521 org-table-create-or-convert-from-region
2522 org-table-create-with-table.el org-table-current-dline
2523 org-table-cut-region org-table-delete-column org-table-edit-field
2524 org-table-edit-formulas org-table-end org-table-eval-formula
2525 org-table-export org-table-field-info
2526 org-table-get-stored-formulas org-table-goto-column
2527 org-table-hline-and-move org-table-import org-table-insert-column
2528 org-table-insert-hline org-table-insert-row org-table-iterate
2529 org-table-justify-field-maybe org-table-kill-row
2530 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2531 org-table-move-column org-table-move-column-left
2532 org-table-move-column-right org-table-move-row
2533 org-table-move-row-down org-table-move-row-up
2534 org-table-next-field org-table-next-row org-table-paste-rectangle
2535 org-table-previous-field org-table-recalculate
2536 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2537 org-table-toggle-coordinate-overlays
2538 org-table-toggle-formula-debugger org-table-wrap-region
2539 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
2541 (defun org-at-table-p (&optional table-type)
2542 "Return t if the cursor is inside an org-type table.
2543 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2544 (if org-enable-table-editor
2545 (save-excursion
2546 (beginning-of-line 1)
2547 (looking-at (if table-type org-table-any-line-regexp
2548 org-table-line-regexp)))
2549 nil))
2550 (defsubst org-table-p () (org-at-table-p))
2552 (defun org-at-table.el-p ()
2553 "Return t if and only if we are at a table.el table."
2554 (and (org-at-table-p 'any)
2555 (save-excursion
2556 (goto-char (org-table-begin 'any))
2557 (looking-at org-table1-hline-regexp))))
2558 (defun org-table-recognize-table.el ()
2559 "If there is a table.el table nearby, recognize it and move into it."
2560 (if org-table-tab-recognizes-table.el
2561 (if (org-at-table.el-p)
2562 (progn
2563 (beginning-of-line 1)
2564 (if (looking-at org-table-dataline-regexp)
2566 (if (looking-at org-table1-hline-regexp)
2567 (progn
2568 (beginning-of-line 2)
2569 (if (looking-at org-table-any-border-regexp)
2570 (beginning-of-line -1)))))
2571 (if (re-search-forward "|" (org-table-end t) t)
2572 (progn
2573 (require 'table)
2574 (if (table--at-cell-p (point))
2576 (message "recognizing table.el table...")
2577 (table-recognize-table)
2578 (message "recognizing table.el table...done")))
2579 (error "This should not happen..."))
2581 nil)
2582 nil))
2584 (defun org-at-table-hline-p ()
2585 "Return t if the cursor is inside a hline in a table."
2586 (if org-enable-table-editor
2587 (save-excursion
2588 (beginning-of-line 1)
2589 (looking-at org-table-hline-regexp))
2590 nil))
2592 (defvar org-table-clean-did-remove-column nil)
2594 (defun org-table-map-tables (function)
2595 "Apply FUNCTION to the start of all tables in the buffer."
2596 (save-excursion
2597 (save-restriction
2598 (widen)
2599 (goto-char (point-min))
2600 (while (re-search-forward org-table-any-line-regexp nil t)
2601 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2602 (beginning-of-line 1)
2603 (if (looking-at org-table-line-regexp)
2604 (save-excursion (funcall function)))
2605 (re-search-forward org-table-any-border-regexp nil 1))))
2606 (message "Mapping tables: done"))
2608 ;; Declare and autoload functions from org-exp.el
2610 (declare-function org-default-export-plist "org-exp")
2611 (declare-function org-infile-export-plist "org-exp")
2612 (declare-function org-get-current-options "org-exp")
2613 (eval-and-compile
2614 (org-autoload "org-exp"
2615 '(org-export org-export-as-ascii org-export-visible
2616 org-insert-export-options-template org-export-as-html-and-open
2617 org-export-as-html-batch org-export-as-html-to-buffer
2618 org-replace-region-by-html org-export-region-as-html
2619 org-export-as-html org-export-icalendar-this-file
2620 org-export-icalendar-all-agenda-files
2621 org-table-clean-before-export
2622 org-export-icalendar-combine-agenda-files org-export-as-xoxo)))
2624 ;; Declare and autoload functions from org-agenda.el
2626 (eval-and-compile
2627 (org-autoload "org-agenda"
2628 '(org-agenda org-agenda-list org-search-view
2629 org-todo-list org-tags-view org-agenda-list-stuck-projects
2630 org-diary org-agenda-to-appt)))
2632 ;; Autoload org-remember
2634 (eval-and-compile
2635 (org-autoload "org-remember"
2636 '(org-remember-insinuate org-remember-annotation
2637 org-remember-apply-template org-remember org-remember-handler)))
2639 ;; Autoload org-clock.el
2642 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
2643 (beg end))
2644 (declare-function org-update-mode-line "org-clock" ())
2645 (defvar org-clock-start-time)
2646 (defvar org-clock-marker (make-marker)
2647 "Marker recording the last clock-in.")
2649 (eval-and-compile
2650 (org-autoload
2651 "org-clock"
2652 '(org-clock-in org-clock-out org-clock-cancel
2653 org-clock-goto org-clock-sum org-clock-display
2654 org-remove-clock-overlays org-clock-report
2655 org-clocktable-shift org-dblock-write:clocktable
2656 org-get-clocktable)))
2658 (defun org-clock-update-time-maybe ()
2659 "If this is a CLOCK line, update it and return t.
2660 Otherwise, return nil."
2661 (interactive)
2662 (save-excursion
2663 (beginning-of-line 1)
2664 (skip-chars-forward " \t")
2665 (when (looking-at org-clock-string)
2666 (let ((re (concat "[ \t]*" org-clock-string
2667 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
2668 "\\([ \t]*=>.*\\)?\\)?"))
2669 ts te h m s neg)
2670 (cond
2671 ((not (looking-at re))
2672 nil)
2673 ((not (match-end 2))
2674 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2675 (> org-clock-marker (point))
2676 (<= org-clock-marker (point-at-eol)))
2677 ;; The clock is running here
2678 (setq org-clock-start-time
2679 (apply 'encode-time
2680 (org-parse-time-string (match-string 1))))
2681 (org-update-mode-line)))
2683 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
2684 (end-of-line 1)
2685 (setq ts (match-string 1)
2686 te (match-string 3))
2687 (setq s (- (time-to-seconds
2688 (apply 'encode-time (org-parse-time-string te)))
2689 (time-to-seconds
2690 (apply 'encode-time (org-parse-time-string ts))))
2691 neg (< s 0)
2692 s (abs s)
2693 h (floor (/ s 3600))
2694 s (- s (* 3600 h))
2695 m (floor (/ s 60))
2696 s (- s (* 60 s)))
2697 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
2698 t))))))
2700 (defun org-check-running-clock ()
2701 "Check if the current buffer contains the running clock.
2702 If yes, offer to stop it and to save the buffer with the changes."
2703 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2704 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
2705 (buffer-name))))
2706 (org-clock-out)
2707 (when (y-or-n-p "Save changed buffer?")
2708 (save-buffer))))
2710 (defun org-clocktable-try-shift (dir n)
2711 "Check if this line starts a clock table, if yes, shift the time block."
2712 (when (org-match-line "#\\+BEGIN: clocktable\\>")
2713 (org-clocktable-shift dir n)))
2715 ;; Autoload org-timer.el
2717 ;(declare-function org-timer "org-timer")
2719 (eval-and-compile
2720 (org-autoload
2721 "org-timer"
2722 '(org-timer-start org-timer org-timer-item
2723 org-timer-change-times-in-region)))
2726 ;; Autoload archiving code
2727 ;; The stuff that is needed for cycling and tags has to be defined here.
2729 (defgroup org-archive nil
2730 "Options concerning archiving in Org-mode."
2731 :tag "Org Archive"
2732 :group 'org-structure)
2734 (defcustom org-archive-location "%s_archive::"
2735 "The location where subtrees should be archived.
2737 The value of this variable is a string, consisting of two parts,
2738 separated by a double-colon. The first part is a filename and
2739 the second part is a headline.
2741 When the filename is omitted, archiving happens in the same file.
2742 %s in the filename will be replaced by the current file
2743 name (without the directory part). Archiving to a different file
2744 is useful to keep archived entries from contributing to the
2745 Org-mode Agenda.
2747 The archived entries will be filed as subtrees of the specified
2748 headline. When the headline is omitted, the subtrees are simply
2749 filed away at the end of the file, as top-level entries.
2751 Here are a few examples:
2752 \"%s_archive::\"
2753 If the current file is Projects.org, archive in file
2754 Projects.org_archive, as top-level trees. This is the default.
2756 \"::* Archived Tasks\"
2757 Archive in the current file, under the top-level headline
2758 \"* Archived Tasks\".
2760 \"~/org/archive.org::\"
2761 Archive in file ~/org/archive.org (absolute path), as top-level trees.
2763 \"basement::** Finished Tasks\"
2764 Archive in file ./basement (relative path), as level 3 trees
2765 below the level 2 heading \"** Finished Tasks\".
2767 You may set this option on a per-file basis by adding to the buffer a
2768 line like
2770 #+ARCHIVE: basement::** Finished Tasks
2772 You may also define it locally for a subtree by setting an ARCHIVE property
2773 in the entry. If such a property is found in an entry, or anywhere up
2774 the hierarchy, it will be used."
2775 :group 'org-archive
2776 :type 'string)
2778 (defcustom org-archive-tag "ARCHIVE"
2779 "The tag that marks a subtree as archived.
2780 An archived subtree does not open during visibility cycling, and does
2781 not contribute to the agenda listings.
2782 After changing this, font-lock must be restarted in the relevant buffers to
2783 get the proper fontification."
2784 :group 'org-archive
2785 :group 'org-keywords
2786 :type 'string)
2788 (defcustom org-agenda-skip-archived-trees t
2789 "Non-nil means, the agenda will skip any items located in archived trees.
2790 An archived tree is a tree marked with the tag ARCHIVE. The use of this
2791 variable is no longer recommended, you should leave it at the value t.
2792 Instead, use the key `v' to cycle the archives-mode in the agenda."
2793 :group 'org-archive
2794 :group 'org-agenda-skip
2795 :type 'boolean)
2797 (defcustom org-cycle-open-archived-trees nil
2798 "Non-nil means, `org-cycle' will open archived trees.
2799 An archived tree is a tree marked with the tag ARCHIVE.
2800 When nil, archived trees will stay folded. You can still open them with
2801 normal outline commands like `show-all', but not with the cycling commands."
2802 :group 'org-archive
2803 :group 'org-cycle
2804 :type 'boolean)
2806 (defcustom org-sparse-tree-open-archived-trees nil
2807 "Non-nil means sparse tree construction shows matches in archived trees.
2808 When nil, matches in these trees are highlighted, but the trees are kept in
2809 collapsed state."
2810 :group 'org-archive
2811 :group 'org-sparse-trees
2812 :type 'boolean)
2814 (defun org-cycle-hide-archived-subtrees (state)
2815 "Re-hide all archived subtrees after a visibility state change."
2816 (when (and (not org-cycle-open-archived-trees)
2817 (not (memq state '(overview folded))))
2818 (save-excursion
2819 (let* ((globalp (memq state '(contents all)))
2820 (beg (if globalp (point-min) (point)))
2821 (end (if globalp (point-max) (org-end-of-subtree t))))
2822 (org-hide-archived-subtrees beg end)
2823 (goto-char beg)
2824 (if (looking-at (concat ".*:" org-archive-tag ":"))
2825 (message "%s" (substitute-command-keys
2826 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
2828 (defun org-force-cycle-archived ()
2829 "Cycle subtree even if it is archived."
2830 (interactive)
2831 (setq this-command 'org-cycle)
2832 (let ((org-cycle-open-archived-trees t))
2833 (call-interactively 'org-cycle)))
2835 (defun org-hide-archived-subtrees (beg end)
2836 "Re-hide all archived subtrees after a visibility state change."
2837 (save-excursion
2838 (let* ((re (concat ":" org-archive-tag ":")))
2839 (goto-char beg)
2840 (while (re-search-forward re end t)
2841 (and (org-on-heading-p) (hide-subtree))
2842 (org-end-of-subtree t)))))
2844 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
2846 (eval-and-compile
2847 (org-autoload "org-archive"
2848 '(org-add-archive-files org-archive-subtree
2849 org-archive-to-archive-sibling org-toggle-archive-tag)))
2851 ;; Autoload Column View Code
2853 (declare-function org-columns-number-to-string "org-colview")
2854 (declare-function org-columns-get-format-and-top-level "org-colview")
2855 (declare-function org-columns-compute "org-colview")
2857 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
2858 '(org-columns-number-to-string org-columns-get-format-and-top-level
2859 org-columns-compute org-agenda-columns org-columns-remove-overlays
2860 org-columns org-insert-columns-dblock org-dblock-write:columnview))
2862 ;; Autoload ID code
2864 (declare-function org-id-store-link "org-id")
2865 (org-autoload "org-id"
2866 '(org-id-get-create org-id-new org-id-copy org-id-get
2867 org-id-get-with-outline-path-completion
2868 org-id-get-with-outline-drilling
2869 org-id-goto org-id-find org-id-store-link))
2871 ;;; Variables for pre-computed regular expressions, all buffer local
2873 (defvar org-drawer-regexp nil
2874 "Matches first line of a hidden block.")
2875 (make-variable-buffer-local 'org-drawer-regexp)
2876 (defvar org-todo-regexp nil
2877 "Matches any of the TODO state keywords.")
2878 (make-variable-buffer-local 'org-todo-regexp)
2879 (defvar org-not-done-regexp nil
2880 "Matches any of the TODO state keywords except the last one.")
2881 (make-variable-buffer-local 'org-not-done-regexp)
2882 (defvar org-todo-line-regexp nil
2883 "Matches a headline and puts TODO state into group 2 if present.")
2884 (make-variable-buffer-local 'org-todo-line-regexp)
2885 (defvar org-complex-heading-regexp nil
2886 "Matches a headline and puts everything into groups:
2887 group 1: the stars
2888 group 2: The todo keyword, maybe
2889 group 3: Priority cookie
2890 group 4: True headline
2891 group 5: Tags")
2892 (make-variable-buffer-local 'org-complex-heading-regexp)
2893 (defvar org-todo-line-tags-regexp nil
2894 "Matches a headline and puts TODO state into group 2 if present.
2895 Also put tags into group 4 if tags are present.")
2896 (make-variable-buffer-local 'org-todo-line-tags-regexp)
2897 (defvar org-nl-done-regexp nil
2898 "Matches newline followed by a headline with the DONE keyword.")
2899 (make-variable-buffer-local 'org-nl-done-regexp)
2900 (defvar org-looking-at-done-regexp nil
2901 "Matches the DONE keyword a point.")
2902 (make-variable-buffer-local 'org-looking-at-done-regexp)
2903 (defvar org-ds-keyword-length 12
2904 "Maximum length of the Deadline and SCHEDULED keywords.")
2905 (make-variable-buffer-local 'org-ds-keyword-length)
2906 (defvar org-deadline-regexp nil
2907 "Matches the DEADLINE keyword.")
2908 (make-variable-buffer-local 'org-deadline-regexp)
2909 (defvar org-deadline-time-regexp nil
2910 "Matches the DEADLINE keyword together with a time stamp.")
2911 (make-variable-buffer-local 'org-deadline-time-regexp)
2912 (defvar org-deadline-line-regexp nil
2913 "Matches the DEADLINE keyword and the rest of the line.")
2914 (make-variable-buffer-local 'org-deadline-line-regexp)
2915 (defvar org-scheduled-regexp nil
2916 "Matches the SCHEDULED keyword.")
2917 (make-variable-buffer-local 'org-scheduled-regexp)
2918 (defvar org-scheduled-time-regexp nil
2919 "Matches the SCHEDULED keyword together with a time stamp.")
2920 (make-variable-buffer-local 'org-scheduled-time-regexp)
2921 (defvar org-closed-time-regexp nil
2922 "Matches the CLOSED keyword together with a time stamp.")
2923 (make-variable-buffer-local 'org-closed-time-regexp)
2925 (defvar org-keyword-time-regexp nil
2926 "Matches any of the 4 keywords, together with the time stamp.")
2927 (make-variable-buffer-local 'org-keyword-time-regexp)
2928 (defvar org-keyword-time-not-clock-regexp nil
2929 "Matches any of the 3 keywords, together with the time stamp.")
2930 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
2931 (defvar org-maybe-keyword-time-regexp nil
2932 "Matches a timestamp, possibly preceeded by a keyword.")
2933 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
2934 (defvar org-planning-or-clock-line-re nil
2935 "Matches a line with planning or clock info.")
2936 (make-variable-buffer-local 'org-planning-or-clock-line-re)
2938 (defconst org-plain-time-of-day-regexp
2939 (concat
2940 "\\(\\<[012]?[0-9]"
2941 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2942 "\\(--?"
2943 "\\(\\<[012]?[0-9]"
2944 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2945 "\\)?")
2946 "Regular expression to match a plain time or time range.
2947 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2948 groups carry important information:
2949 0 the full match
2950 1 the first time, range or not
2951 8 the second time, if it is a range.")
2953 (defconst org-plain-time-extension-regexp
2954 (concat
2955 "\\(\\<[012]?[0-9]"
2956 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2957 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
2958 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
2959 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2960 groups carry important information:
2961 0 the full match
2962 7 hours of duration
2963 9 minutes of duration")
2965 (defconst org-stamp-time-of-day-regexp
2966 (concat
2967 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
2968 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
2969 "\\(--?"
2970 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
2971 "Regular expression to match a timestamp time or time range.
2972 After a match, the following groups carry important information:
2973 0 the full match
2974 1 date plus weekday, for backreferencing to make sure both times on same day
2975 2 the first time, range or not
2976 4 the second time, if it is a range.")
2978 (defconst org-startup-options
2979 '(("fold" org-startup-folded t)
2980 ("overview" org-startup-folded t)
2981 ("nofold" org-startup-folded nil)
2982 ("showall" org-startup-folded nil)
2983 ("content" org-startup-folded content)
2984 ("hidestars" org-hide-leading-stars t)
2985 ("showstars" org-hide-leading-stars nil)
2986 ("odd" org-odd-levels-only t)
2987 ("oddeven" org-odd-levels-only nil)
2988 ("align" org-startup-align-all-tables t)
2989 ("noalign" org-startup-align-all-tables nil)
2990 ("customtime" org-display-custom-times t)
2991 ("logdone" org-log-done time)
2992 ("lognotedone" org-log-done note)
2993 ("nologdone" org-log-done nil)
2994 ("lognoteclock-out" org-log-note-clock-out t)
2995 ("nolognoteclock-out" org-log-note-clock-out nil)
2996 ("logrepeat" org-log-repeat state)
2997 ("lognoterepeat" org-log-repeat note)
2998 ("nologrepeat" org-log-repeat nil)
2999 ("fninline" org-footnote-define-inline t)
3000 ("nofninline" org-footnote-define-inline nil)
3001 ("fnauto" org-footnote-auto-label t)
3002 ("fnprompt" org-footnote-auto-label nil)
3003 ("fnconfirm" org-footnote-auto-label confirm)
3004 ("fnplain" org-footnote-auto-label plain)
3005 ("constcgs" constants-unit-system cgs)
3006 ("constSI" constants-unit-system SI))
3007 "Variable associated with STARTUP options for org-mode.
3008 Each element is a list of three items: The startup options as written
3009 in the #+STARTUP line, the corresponding variable, and the value to
3010 set this variable to if the option is found. An optional forth element PUSH
3011 means to push this value onto the list in the variable.")
3013 (defun org-set-regexps-and-options ()
3014 "Precompute regular expressions for current buffer."
3015 (when (org-mode-p)
3016 (org-set-local 'org-todo-kwd-alist nil)
3017 (org-set-local 'org-todo-key-alist nil)
3018 (org-set-local 'org-todo-key-trigger nil)
3019 (org-set-local 'org-todo-keywords-1 nil)
3020 (org-set-local 'org-done-keywords nil)
3021 (org-set-local 'org-todo-heads nil)
3022 (org-set-local 'org-todo-sets nil)
3023 (org-set-local 'org-todo-log-states nil)
3024 (org-set-local 'org-file-properties nil)
3025 (org-set-local 'org-file-tags nil)
3026 (let ((re (org-make-options-regexp
3027 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
3028 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3029 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")))
3030 (splitre "[ \t]+")
3031 kwds kws0 kwsa key log value cat arch tags const links hw dws
3032 tail sep kws1 prio props ftags drawers
3033 ext-setup-or-nil setup-contents (start 0))
3034 (save-excursion
3035 (save-restriction
3036 (widen)
3037 (goto-char (point-min))
3038 (while (or (and ext-setup-or-nil
3039 (string-match re ext-setup-or-nil start)
3040 (setq start (match-end 0)))
3041 (and (setq ext-setup-or-nil nil start 0)
3042 (re-search-forward re nil t)))
3043 (setq key (upcase (match-string 1 ext-setup-or-nil))
3044 value (org-match-string-no-properties 2 ext-setup-or-nil))
3045 (cond
3046 ((equal key "CATEGORY")
3047 (if (string-match "[ \t]+$" value)
3048 (setq value (replace-match "" t t value)))
3049 (setq cat value))
3050 ((member key '("SEQ_TODO" "TODO"))
3051 (push (cons 'sequence (org-split-string value splitre)) kwds))
3052 ((equal key "TYP_TODO")
3053 (push (cons 'type (org-split-string value splitre)) kwds))
3054 ((equal key "TAGS")
3055 (setq tags (append tags (org-split-string value splitre))))
3056 ((equal key "COLUMNS")
3057 (org-set-local 'org-columns-default-format value))
3058 ((equal key "LINK")
3059 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3060 (push (cons (match-string 1 value)
3061 (org-trim (match-string 2 value)))
3062 links)))
3063 ((equal key "PRIORITIES")
3064 (setq prio (org-split-string value " +")))
3065 ((equal key "PROPERTY")
3066 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3067 (push (cons (match-string 1 value) (match-string 2 value))
3068 props)))
3069 ((equal key "FILETAGS")
3070 (when (string-match "\\S-" value)
3071 (setq ftags
3072 (append
3073 ftags
3074 (apply 'append
3075 (mapcar (lambda (x) (org-split-string x ":"))
3076 (org-split-string value)))))))
3077 ((equal key "DRAWERS")
3078 (setq drawers (org-split-string value splitre)))
3079 ((equal key "CONSTANTS")
3080 (setq const (append const (org-split-string value splitre))))
3081 ((equal key "STARTUP")
3082 (let ((opts (org-split-string value splitre))
3083 l var val)
3084 (while (setq l (pop opts))
3085 (when (setq l (assoc l org-startup-options))
3086 (setq var (nth 1 l) val (nth 2 l))
3087 (if (not (nth 3 l))
3088 (set (make-local-variable var) val)
3089 (if (not (listp (symbol-value var)))
3090 (set (make-local-variable var) nil))
3091 (set (make-local-variable var) (symbol-value var))
3092 (add-to-list var val))))))
3093 ((equal key "ARCHIVE")
3094 (string-match " *$" value)
3095 (setq arch (replace-match "" t t value))
3096 (remove-text-properties 0 (length arch)
3097 '(face t fontified t) arch))
3098 ((equal key "SETUPFILE")
3099 (setq setup-contents (org-file-contents
3100 (expand-file-name
3101 (org-remove-double-quotes value))
3102 'noerror))
3103 (if (not ext-setup-or-nil)
3104 (setq ext-setup-or-nil setup-contents start 0)
3105 (setq ext-setup-or-nil
3106 (concat (substring ext-setup-or-nil 0 start)
3107 "\n" setup-contents "\n"
3108 (substring ext-setup-or-nil start)))))
3109 ))))
3110 (when cat
3111 (org-set-local 'org-category (intern cat))
3112 (push (cons "CATEGORY" cat) props))
3113 (when prio
3114 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3115 (setq prio (mapcar 'string-to-char prio))
3116 (org-set-local 'org-highest-priority (nth 0 prio))
3117 (org-set-local 'org-lowest-priority (nth 1 prio))
3118 (org-set-local 'org-default-priority (nth 2 prio)))
3119 (and props (org-set-local 'org-file-properties (nreverse props)))
3120 (and ftags (org-set-local 'org-file-tags ftags))
3121 (and drawers (org-set-local 'org-drawers drawers))
3122 (and arch (org-set-local 'org-archive-location arch))
3123 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3124 ;; Process the TODO keywords
3125 (unless kwds
3126 ;; Use the global values as if they had been given locally.
3127 (setq kwds (default-value 'org-todo-keywords))
3128 (if (stringp (car kwds))
3129 (setq kwds (list (cons org-todo-interpretation
3130 (default-value 'org-todo-keywords)))))
3131 (setq kwds (reverse kwds)))
3132 (setq kwds (nreverse kwds))
3133 (let (inter kws kw)
3134 (while (setq kws (pop kwds))
3135 (setq inter (pop kws) sep (member "|" kws)
3136 kws0 (delete "|" (copy-sequence kws))
3137 kwsa nil
3138 kws1 (mapcar
3139 (lambda (x)
3140 ;; 1 2
3141 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3142 (progn
3143 (setq kw (match-string 1 x)
3144 key (and (match-end 2) (match-string 2 x))
3145 log (org-extract-log-state-settings x))
3146 (push (cons kw (and key (string-to-char key))) kwsa)
3147 (and log (push log org-todo-log-states))
3149 (error "Invalid TODO keyword %s" x)))
3150 kws0)
3151 kwsa (if kwsa (append '((:startgroup))
3152 (nreverse kwsa)
3153 '((:endgroup))))
3154 hw (car kws1)
3155 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3156 tail (list inter hw (car dws) (org-last dws)))
3157 (add-to-list 'org-todo-heads hw 'append)
3158 (push kws1 org-todo-sets)
3159 (setq org-done-keywords (append org-done-keywords dws nil))
3160 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3161 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3162 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3163 (setq org-todo-sets (nreverse org-todo-sets)
3164 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3165 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3166 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3167 ;; Process the constants
3168 (when const
3169 (let (e cst)
3170 (while (setq e (pop const))
3171 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3172 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3173 (setq org-table-formula-constants-local cst)))
3175 ;; Process the tags.
3176 (when tags
3177 (let (e tgs)
3178 (while (setq e (pop tags))
3179 (cond
3180 ((equal e "{") (push '(:startgroup) tgs))
3181 ((equal e "}") (push '(:endgroup) tgs))
3182 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3183 (push (cons (match-string 1 e)
3184 (string-to-char (match-string 2 e)))
3185 tgs))
3186 (t (push (list e) tgs))))
3187 (org-set-local 'org-tag-alist nil)
3188 (while (setq e (pop tgs))
3189 (or (and (stringp (car e))
3190 (assoc (car e) org-tag-alist))
3191 (push e org-tag-alist)))))
3193 ;; Compute the regular expressions and other local variables
3194 (if (not org-done-keywords)
3195 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
3196 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3197 (length org-scheduled-string)
3198 (length org-clock-string)
3199 (length org-closed-string)))
3200 org-drawer-regexp
3201 (concat "^[ \t]*:\\("
3202 (mapconcat 'regexp-quote org-drawers "\\|")
3203 "\\):[ \t]*$")
3204 org-not-done-keywords
3205 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3206 org-todo-regexp
3207 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3208 "\\|") "\\)\\>")
3209 org-not-done-regexp
3210 (concat "\\<\\("
3211 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3212 "\\)\\>")
3213 org-todo-line-regexp
3214 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3215 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3216 "\\)\\>\\)?[ \t]*\\(.*\\)")
3217 org-complex-heading-regexp
3218 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
3219 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3220 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3221 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3222 org-nl-done-regexp
3223 (concat "\n\\*+[ \t]+"
3224 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3225 "\\)" "\\>")
3226 org-todo-line-tags-regexp
3227 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3228 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3229 (org-re
3230 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3231 org-looking-at-done-regexp
3232 (concat "^" "\\(?:"
3233 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3234 "\\>")
3235 org-deadline-regexp (concat "\\<" org-deadline-string)
3236 org-deadline-time-regexp
3237 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3238 org-deadline-line-regexp
3239 (concat "\\<\\(" org-deadline-string "\\).*")
3240 org-scheduled-regexp
3241 (concat "\\<" org-scheduled-string)
3242 org-scheduled-time-regexp
3243 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3244 org-closed-time-regexp
3245 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3246 org-keyword-time-regexp
3247 (concat "\\<\\(" org-scheduled-string
3248 "\\|" org-deadline-string
3249 "\\|" org-closed-string
3250 "\\|" org-clock-string "\\)"
3251 " *[[<]\\([^]>]+\\)[]>]")
3252 org-keyword-time-not-clock-regexp
3253 (concat "\\<\\(" org-scheduled-string
3254 "\\|" org-deadline-string
3255 "\\|" org-closed-string
3256 "\\)"
3257 " *[[<]\\([^]>]+\\)[]>]")
3258 org-maybe-keyword-time-regexp
3259 (concat "\\(\\<\\(" org-scheduled-string
3260 "\\|" org-deadline-string
3261 "\\|" org-closed-string
3262 "\\|" org-clock-string "\\)\\)?"
3263 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3264 org-planning-or-clock-line-re
3265 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3266 "\\|" org-deadline-string
3267 "\\|" org-closed-string "\\|" org-clock-string
3268 "\\)\\>\\)")
3270 (org-compute-latex-and-specials-regexp)
3271 (org-set-font-lock-defaults))))
3273 (defun org-file-contents (file &optional noerror)
3274 "Return the contents of FILE, as a string."
3275 (if (or (not file)
3276 (not (file-readable-p file)))
3277 (if noerror
3278 (progn
3279 (message "Cannot read file %s" file)
3280 (ding) (sit-for 2)
3282 (error "Cannot read file %s" file))
3283 (with-temp-buffer
3284 (insert-file-contents file)
3285 (buffer-string))))
3287 (defun org-extract-log-state-settings (x)
3288 "Extract the log state setting from a TODO keyword string.
3289 This will extract info from a string like \"WAIT(w@/!)\"."
3290 (let (kw key log1 log2)
3291 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3292 (setq kw (match-string 1 x)
3293 key (and (match-end 2) (match-string 2 x))
3294 log1 (and (match-end 3) (match-string 3 x))
3295 log2 (and (match-end 4) (match-string 4 x)))
3296 (and (or log1 log2)
3297 (list kw
3298 (and log1 (if (equal log1 "!") 'time 'note))
3299 (and log2 (if (equal log2 "!") 'time 'note)))))))
3301 (defun org-remove-keyword-keys (list)
3302 "Remove a pair of parenthesis at the end of each string in LIST."
3303 (mapcar (lambda (x)
3304 (if (string-match "(.*)$" x)
3305 (substring x 0 (match-beginning 0))
3307 list))
3309 ;; FIXME: this could be done much better, using second characters etc.
3310 (defun org-assign-fast-keys (alist)
3311 "Assign fast keys to a keyword-key alist.
3312 Respect keys that are already there."
3313 (let (new e k c c1 c2 (char ?a))
3314 (while (setq e (pop alist))
3315 (cond
3316 ((equal e '(:startgroup)) (push e new))
3317 ((equal e '(:endgroup)) (push e new))
3319 (setq k (car e) c2 nil)
3320 (if (cdr e)
3321 (setq c (cdr e))
3322 ;; automatically assign a character.
3323 (setq c1 (string-to-char
3324 (downcase (substring
3325 k (if (= (string-to-char k) ?@) 1 0)))))
3326 (if (or (rassoc c1 new) (rassoc c1 alist))
3327 (while (or (rassoc char new) (rassoc char alist))
3328 (setq char (1+ char)))
3329 (setq c2 c1))
3330 (setq c (or c2 char)))
3331 (push (cons k c) new))))
3332 (nreverse new)))
3334 ;;; Some variables used in various places
3336 (defvar org-window-configuration nil
3337 "Used in various places to store a window configuration.")
3338 (defvar org-finish-function nil
3339 "Function to be called when `C-c C-c' is used.
3340 This is for getting out of special buffers like remember.")
3343 ;; FIXME: Occasionally check by commenting these, to make sure
3344 ;; no other functions uses these, forgetting to let-bind them.
3345 (defvar entry)
3346 (defvar state)
3347 (defvar last-state)
3348 (defvar date)
3349 (defvar description)
3351 ;; Defined somewhere in this file, but used before definition.
3352 (defvar org-html-entities)
3353 (defvar org-struct-menu)
3354 (defvar org-org-menu)
3355 (defvar org-tbl-menu)
3356 (defvar org-agenda-keymap)
3358 ;;;; Define the Org-mode
3360 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3361 (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."))
3364 ;; We use a before-change function to check if a table might need
3365 ;; an update.
3366 (defvar org-table-may-need-update t
3367 "Indicates that a table might need an update.
3368 This variable is set by `org-before-change-function'.
3369 `org-table-align' sets it back to nil.")
3370 (defun org-before-change-function (beg end)
3371 "Every change indicates that a table might need an update."
3372 (setq org-table-may-need-update t))
3373 (defvar org-mode-map)
3374 (defvar org-mode-hook nil
3375 "Mode hook for Org-mode, run after the mode was turned on.")
3376 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3377 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3378 (defvar org-table-buffer-is-an nil)
3379 (defconst org-outline-regexp "\\*+ ")
3381 ;;;###autoload
3382 (define-derived-mode org-mode outline-mode "Org"
3383 "Outline-based notes management and organizer, alias
3384 \"Carsten's outline-mode for keeping track of everything.\"
3386 Org-mode develops organizational tasks around a NOTES file which
3387 contains information about projects as plain text. Org-mode is
3388 implemented on top of outline-mode, which is ideal to keep the content
3389 of large files well structured. It supports ToDo items, deadlines and
3390 time stamps, which magically appear in the diary listing of the Emacs
3391 calendar. Tables are easily created with a built-in table editor.
3392 Plain text URL-like links connect to websites, emails (VM), Usenet
3393 messages (Gnus), BBDB entries, and any files related to the project.
3394 For printing and sharing of notes, an Org-mode file (or a part of it)
3395 can be exported as a structured ASCII or HTML file.
3397 The following commands are available:
3399 \\{org-mode-map}"
3401 ;; Get rid of Outline menus, they are not needed
3402 ;; Need to do this here because define-derived-mode sets up
3403 ;; the keymap so late. Still, it is a waste to call this each time
3404 ;; we switch another buffer into org-mode.
3405 (if (featurep 'xemacs)
3406 (when (boundp 'outline-mode-menu-heading)
3407 ;; Assume this is Greg's port, it used easymenu
3408 (easy-menu-remove outline-mode-menu-heading)
3409 (easy-menu-remove outline-mode-menu-show)
3410 (easy-menu-remove outline-mode-menu-hide))
3411 (define-key org-mode-map [menu-bar headings] 'undefined)
3412 (define-key org-mode-map [menu-bar hide] 'undefined)
3413 (define-key org-mode-map [menu-bar show] 'undefined))
3415 (org-load-modules-maybe)
3416 (easy-menu-add org-org-menu)
3417 (easy-menu-add org-tbl-menu)
3418 (org-install-agenda-files-menu)
3419 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3420 (org-add-to-invisibility-spec '(org-cwidth))
3421 (when (featurep 'xemacs)
3422 (org-set-local 'line-move-ignore-invisible t))
3423 (org-set-local 'outline-regexp org-outline-regexp)
3424 (org-set-local 'outline-level 'org-outline-level)
3425 (when (and org-ellipsis
3426 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3427 (fboundp 'make-glyph-code))
3428 (unless org-display-table
3429 (setq org-display-table (make-display-table)))
3430 (set-display-table-slot
3431 org-display-table 4
3432 (vconcat (mapcar
3433 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3434 org-ellipsis)))
3435 (if (stringp org-ellipsis) org-ellipsis "..."))))
3436 (setq buffer-display-table org-display-table))
3437 (org-set-regexps-and-options)
3438 (when (and org-tag-faces (not org-tags-special-faces-re))
3439 ;; tag faces set outside customize.... force initialization.
3440 (org-set-tag-faces 'org-tag-faces org-tag-faces))
3441 ;; Calc embedded
3442 (org-set-local 'calc-embedded-open-mode "# ")
3443 (modify-syntax-entry ?# "<")
3444 (modify-syntax-entry ?@ "w")
3445 (if org-startup-truncated (setq truncate-lines t))
3446 (org-set-local 'font-lock-unfontify-region-function
3447 'org-unfontify-region)
3448 ;; Activate before-change-function
3449 (org-set-local 'org-table-may-need-update t)
3450 (org-add-hook 'before-change-functions 'org-before-change-function nil
3451 'local)
3452 ;; Check for running clock before killing a buffer
3453 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3454 ;; Paragraphs and auto-filling
3455 (org-set-autofill-regexps)
3456 (setq indent-line-function 'org-indent-line-function)
3457 (org-update-radio-target-regexp)
3459 ;; Comment characters
3460 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3461 (org-set-local 'comment-padding " ")
3463 ;; Align options lines
3464 (org-set-local
3465 'align-mode-rules-list
3466 '((org-in-buffer-settings
3467 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3468 (modes . '(org-mode)))))
3470 ;; Imenu
3471 (org-set-local 'imenu-create-index-function
3472 'org-imenu-get-tree)
3474 ;; Make isearch reveal context
3475 (if (or (featurep 'xemacs)
3476 (not (boundp 'outline-isearch-open-invisible-function)))
3477 ;; Emacs 21 and XEmacs make use of the hook
3478 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3479 ;; Emacs 22 deals with this through a special variable
3480 (org-set-local 'outline-isearch-open-invisible-function
3481 (lambda (&rest ignore) (org-show-context 'isearch))))
3483 ;; If empty file that did not turn on org-mode automatically, make it to.
3484 (if (and org-insert-mode-line-in-empty-file
3485 (interactive-p)
3486 (= (point-min) (point-max)))
3487 (insert "# -*- mode: org -*-\n\n"))
3489 (unless org-inhibit-startup
3490 (when org-startup-align-all-tables
3491 (let ((bmp (buffer-modified-p)))
3492 (org-table-map-tables 'org-table-align)
3493 (set-buffer-modified-p bmp)))
3494 (org-set-startup-visibility)))
3496 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3498 (defun org-current-time ()
3499 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3500 (if (> (car org-time-stamp-rounding-minutes) 1)
3501 (let ((r (car org-time-stamp-rounding-minutes))
3502 (time (decode-time)))
3503 (apply 'encode-time
3504 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3505 (nthcdr 2 time))))
3506 (current-time)))
3508 ;;;; Font-Lock stuff, including the activators
3510 (defvar org-mouse-map (make-sparse-keymap))
3511 (org-defkey org-mouse-map
3512 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3513 (org-defkey org-mouse-map
3514 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3515 (when org-mouse-1-follows-link
3516 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3517 (when org-tab-follows-link
3518 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3519 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3520 (when org-return-follows-link
3521 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
3522 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
3524 (require 'font-lock)
3526 (defconst org-non-link-chars "]\t\n\r<>")
3527 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3528 "shell" "elisp"))
3529 (defvar org-link-types-re nil
3530 "Matches a link that has a url-like prefix like \"http:\"")
3531 (defvar org-link-re-with-space nil
3532 "Matches a link with spaces, optional angular brackets around it.")
3533 (defvar org-link-re-with-space2 nil
3534 "Matches a link with spaces, optional angular brackets around it.")
3535 (defvar org-link-re-with-space3 nil
3536 "Matches a link with spaces, only for internal part in bracket links.")
3537 (defvar org-angle-link-re nil
3538 "Matches link with angular brackets, spaces are allowed.")
3539 (defvar org-plain-link-re nil
3540 "Matches plain link, without spaces.")
3541 (defvar org-bracket-link-regexp nil
3542 "Matches a link in double brackets.")
3543 (defvar org-bracket-link-analytic-regexp nil
3544 "Regular expression used to analyze links.
3545 Here is what the match groups contain after a match:
3546 1: http:
3547 2: http
3548 3: path
3549 4: [desc]
3550 5: desc")
3551 (defvar org-bracket-link-analytic-regexp++ nil
3552 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
3553 (defvar org-any-link-re nil
3554 "Regular expression matching any link.")
3556 (defun org-make-link-regexps ()
3557 "Update the link regular expressions.
3558 This should be called after the variable `org-link-types' has changed."
3559 (setq org-link-types-re
3560 (concat
3561 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3562 org-link-re-with-space
3563 (concat
3564 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3565 "\\([^" org-non-link-chars " ]"
3566 "[^" org-non-link-chars "]*"
3567 "[^" org-non-link-chars " ]\\)>?")
3568 org-link-re-with-space2
3569 (concat
3570 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3571 "\\([^" org-non-link-chars " ]"
3572 "[^\t\n\r]*"
3573 "[^" org-non-link-chars " ]\\)>?")
3574 org-link-re-with-space3
3575 (concat
3576 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3577 "\\([^" org-non-link-chars " ]"
3578 "[^\t\n\r]*\\)")
3579 org-angle-link-re
3580 (concat
3581 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3582 "\\([^" org-non-link-chars " ]"
3583 "[^" org-non-link-chars "]*"
3584 "\\)>")
3585 org-plain-link-re
3586 (concat
3587 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3588 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3589 org-bracket-link-regexp
3590 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3591 org-bracket-link-analytic-regexp
3592 (concat
3593 "\\[\\["
3594 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3595 "\\([^]]+\\)"
3596 "\\]"
3597 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3598 "\\]")
3599 org-bracket-link-analytic-regexp++
3600 (concat
3601 "\\[\\["
3602 "\\(\\(" (mapconcat 'identity (cons "coderef" org-link-types) "\\|") "\\):\\)?"
3603 "\\([^]]+\\)"
3604 "\\]"
3605 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3606 "\\]")
3607 org-any-link-re
3608 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3609 org-angle-link-re "\\)\\|\\("
3610 org-plain-link-re "\\)")))
3612 (org-make-link-regexps)
3614 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
3615 "Regular expression for fast time stamp matching.")
3616 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
3617 "Regular expression for fast time stamp matching.")
3618 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3619 "Regular expression matching time strings for analysis.
3620 This one does not require the space after the date, so it can be used
3621 on a string that terminates immediately after the date.")
3622 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3623 "Regular expression matching time strings for analysis.")
3624 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
3625 "Regular expression matching time stamps, with groups.")
3626 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
3627 "Regular expression matching time stamps (also [..]), with groups.")
3628 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3629 "Regular expression matching a time stamp range.")
3630 (defconst org-tr-regexp-both
3631 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3632 "Regular expression matching a time stamp range.")
3633 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3634 org-ts-regexp "\\)?")
3635 "Regular expression matching a time stamp or time stamp range.")
3636 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3637 org-ts-regexp-both "\\)?")
3638 "Regular expression matching a time stamp or time stamp range.
3639 The time stamps may be either active or inactive.")
3641 (defvar org-emph-face nil)
3643 (defun org-do-emphasis-faces (limit)
3644 "Run through the buffer and add overlays to links."
3645 (let (rtn)
3646 (while (and (not rtn) (re-search-forward org-emph-re limit t))
3647 (if (not (= (char-after (match-beginning 3))
3648 (char-after (match-beginning 4))))
3649 (progn
3650 (setq rtn t)
3651 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3652 'face
3653 (nth 1 (assoc (match-string 3)
3654 org-emphasis-alist)))
3655 (add-text-properties (match-beginning 2) (match-end 2)
3656 '(font-lock-multiline t))
3657 (when org-hide-emphasis-markers
3658 (add-text-properties (match-end 4) (match-beginning 5)
3659 '(invisible org-link))
3660 (add-text-properties (match-beginning 3) (match-end 3)
3661 '(invisible org-link)))))
3662 (backward-char 1))
3663 rtn))
3665 (defun org-emphasize (&optional char)
3666 "Insert or change an emphasis, i.e. a font like bold or italic.
3667 If there is an active region, change that region to a new emphasis.
3668 If there is no region, just insert the marker characters and position
3669 the cursor between them.
3670 CHAR should be either the marker character, or the first character of the
3671 HTML tag associated with that emphasis. If CHAR is a space, the means
3672 to remove the emphasis of the selected region.
3673 If char is not given (for example in an interactive call) it
3674 will be prompted for."
3675 (interactive)
3676 (let ((eal org-emphasis-alist) e det
3677 (erc org-emphasis-regexp-components)
3678 (prompt "")
3679 (string "") beg end move tag c s)
3680 (if (org-region-active-p)
3681 (setq beg (region-beginning) end (region-end)
3682 string (buffer-substring beg end))
3683 (setq move t))
3685 (while (setq e (pop eal))
3686 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
3687 c (aref tag 0))
3688 (push (cons c (string-to-char (car e))) det)
3689 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
3690 (substring tag 1)))))
3691 (setq det (nreverse det))
3692 (unless char
3693 (message "%s" (concat "Emphasis marker or tag:" prompt))
3694 (setq char (read-char-exclusive)))
3695 (setq char (or (cdr (assoc char det)) char))
3696 (if (equal char ?\ )
3697 (setq s "" move nil)
3698 (unless (assoc (char-to-string char) org-emphasis-alist)
3699 (error "No such emphasis marker: \"%c\"" char))
3700 (setq s (char-to-string char)))
3701 (while (and (> (length string) 1)
3702 (equal (substring string 0 1) (substring string -1))
3703 (assoc (substring string 0 1) org-emphasis-alist))
3704 (setq string (substring string 1 -1)))
3705 (setq string (concat s string s))
3706 (if beg (delete-region beg end))
3707 (unless (or (bolp)
3708 (string-match (concat "[" (nth 0 erc) "\n]")
3709 (char-to-string (char-before (point)))))
3710 (insert " "))
3711 (unless (string-match (concat "[" (nth 1 erc) "\n]")
3712 (char-to-string (char-after (point))))
3713 (insert " ") (backward-char 1))
3714 (insert string)
3715 (and move (backward-char 1))))
3717 (defconst org-nonsticky-props
3718 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
3721 (defun org-activate-plain-links (limit)
3722 "Run through the buffer and add overlays to links."
3723 (catch 'exit
3724 (let (f)
3725 (while (re-search-forward org-plain-link-re limit t)
3726 (setq f (get-text-property (match-beginning 0) 'face))
3727 (if (or (eq f 'org-tag)
3728 (and (listp f) (memq 'org-tag f)))
3730 (add-text-properties (match-beginning 0) (match-end 0)
3731 (list 'mouse-face 'highlight
3732 'rear-nonsticky org-nonsticky-props
3733 'keymap org-mouse-map
3735 (throw 'exit t))))))
3737 (defun org-activate-code (limit)
3738 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
3739 (progn
3740 (remove-text-properties (match-beginning 0) (match-end 0)
3741 '(display t invisible t intangible t))
3742 t)))
3744 (defun org-activate-angle-links (limit)
3745 "Run through the buffer and add overlays to links."
3746 (if (re-search-forward org-angle-link-re limit t)
3747 (progn
3748 (add-text-properties (match-beginning 0) (match-end 0)
3749 (list 'mouse-face 'highlight
3750 'rear-nonsticky org-nonsticky-props
3751 'keymap org-mouse-map
3753 t)))
3755 (defun org-activate-footnote-links (limit)
3756 "Run through the buffer and add overlays to links."
3757 (if (re-search-forward "\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)"
3758 limit t)
3759 (progn
3760 (add-text-properties (match-beginning 0) (match-end 0)
3761 (list 'mouse-face 'highlight
3762 'rear-nonsticky org-nonsticky-props
3763 'keymap org-mouse-map
3764 'help-echo
3765 (if (= (point-at-bol) (match-beginning 0))
3766 "Footnote definition"
3767 "Footnote reference")
3769 t)))
3771 (defun org-activate-bracket-links (limit)
3772 "Run through the buffer and add overlays to bracketed links."
3773 (if (re-search-forward org-bracket-link-regexp limit t)
3774 (let* ((help (concat "LINK: "
3775 (org-match-string-no-properties 1)))
3776 ;; FIXME: above we should remove the escapes.
3777 ;; but that requires another match, protecting match data,
3778 ;; a lot of overhead for font-lock.
3779 (ip (org-maybe-intangible
3780 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
3781 'keymap org-mouse-map 'mouse-face 'highlight
3782 'font-lock-multiline t 'help-echo help)))
3783 (vp (list 'rear-nonsticky org-nonsticky-props
3784 'keymap org-mouse-map 'mouse-face 'highlight
3785 ' font-lock-multiline t 'help-echo help)))
3786 ;; We need to remove the invisible property here. Table narrowing
3787 ;; may have made some of this invisible.
3788 (remove-text-properties (match-beginning 0) (match-end 0)
3789 '(invisible nil))
3790 (if (match-end 3)
3791 (progn
3792 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3793 (add-text-properties (match-beginning 3) (match-end 3) vp)
3794 (add-text-properties (match-end 3) (match-end 0) ip))
3795 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3796 (add-text-properties (match-beginning 1) (match-end 1) vp)
3797 (add-text-properties (match-end 1) (match-end 0) ip))
3798 t)))
3800 (defun org-activate-dates (limit)
3801 "Run through the buffer and add overlays to dates."
3802 (if (re-search-forward org-tsr-regexp-both limit t)
3803 (progn
3804 (add-text-properties (match-beginning 0) (match-end 0)
3805 (list 'mouse-face 'highlight
3806 'rear-nonsticky org-nonsticky-props
3807 'keymap org-mouse-map))
3808 (when org-display-custom-times
3809 (if (match-end 3)
3810 (org-display-custom-time (match-beginning 3) (match-end 3)))
3811 (org-display-custom-time (match-beginning 1) (match-end 1)))
3812 t)))
3814 (defvar org-target-link-regexp nil
3815 "Regular expression matching radio targets in plain text.")
3816 (make-variable-buffer-local 'org-target-link-regexp)
3817 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3818 "Regular expression matching a link target.")
3819 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3820 "Regular expression matching a radio target.")
3821 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
3822 "Regular expression matching any target.")
3824 (defun org-activate-target-links (limit)
3825 "Run through the buffer and add overlays to target matches."
3826 (when org-target-link-regexp
3827 (let ((case-fold-search t))
3828 (if (re-search-forward org-target-link-regexp limit t)
3829 (progn
3830 (add-text-properties (match-beginning 0) (match-end 0)
3831 (list 'mouse-face 'highlight
3832 'rear-nonsticky org-nonsticky-props
3833 'keymap org-mouse-map
3834 'help-echo "Radio target link"
3835 'org-linked-text t))
3836 t)))))
3838 (defun org-update-radio-target-regexp ()
3839 "Find all radio targets in this file and update the regular expression."
3840 (interactive)
3841 (when (memq 'radio org-activate-links)
3842 (setq org-target-link-regexp
3843 (org-make-target-link-regexp (org-all-targets 'radio)))
3844 (org-restart-font-lock)))
3846 (defun org-hide-wide-columns (limit)
3847 (let (s e)
3848 (setq s (text-property-any (point) (or limit (point-max))
3849 'org-cwidth t))
3850 (when s
3851 (setq e (next-single-property-change s 'org-cwidth))
3852 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
3853 (goto-char e)
3854 t)))
3856 (defvar org-latex-and-specials-regexp nil
3857 "Regular expression for highlighting export special stuff.")
3858 (defvar org-match-substring-regexp)
3859 (defvar org-match-substring-with-braces-regexp)
3860 (defvar org-export-html-special-string-regexps)
3862 (defun org-compute-latex-and-specials-regexp ()
3863 "Compute regular expression for stuff treated specially by exporters."
3864 (if (not org-highlight-latex-fragments-and-specials)
3865 (org-set-local 'org-latex-and-specials-regexp nil)
3866 (require 'org-exp)
3867 (let*
3868 ((matchers (plist-get org-format-latex-options :matchers))
3869 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
3870 org-latex-regexps)))
3871 (options (org-combine-plists (org-default-export-plist)
3872 (org-infile-export-plist)))
3873 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
3874 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
3875 (org-export-with-TeX-macros (plist-get options :TeX-macros))
3876 (org-export-html-expand (plist-get options :expand-quoted-html))
3877 (org-export-with-special-strings (plist-get options :special-strings))
3878 (re-sub
3879 (cond
3880 ((equal org-export-with-sub-superscripts '{})
3881 (list org-match-substring-with-braces-regexp))
3882 (org-export-with-sub-superscripts
3883 (list org-match-substring-regexp))
3884 (t nil)))
3885 (re-latex
3886 (if org-export-with-LaTeX-fragments
3887 (mapcar (lambda (x) (nth 1 x)) latexs)))
3888 (re-macros
3889 (if org-export-with-TeX-macros
3890 (list (concat "\\\\"
3891 (regexp-opt
3892 (append (mapcar 'car org-html-entities)
3893 (if (boundp 'org-latex-entities)
3894 org-latex-entities nil))
3895 'words))) ; FIXME
3897 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
3898 (re-special (if org-export-with-special-strings
3899 (mapcar (lambda (x) (car x))
3900 org-export-html-special-string-regexps)))
3901 (re-rest
3902 (delq nil
3903 (list
3904 (if org-export-html-expand "@<[^>\n]+>")
3905 ))))
3906 (org-set-local
3907 'org-latex-and-specials-regexp
3908 (mapconcat 'identity (append re-latex re-sub re-macros re-special
3909 re-rest) "\\|")))))
3911 (defun org-do-latex-and-special-faces (limit)
3912 "Run through the buffer and add overlays to links."
3913 (when org-latex-and-specials-regexp
3914 (let (rtn d)
3915 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
3916 limit t))
3917 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
3918 'face))
3919 '(org-code org-verbatim underline)))
3920 (progn
3921 (setq rtn t
3922 d (cond ((member (char-after (1+ (match-beginning 0)))
3923 '(?_ ?^)) 1)
3924 (t 0)))
3925 (font-lock-prepend-text-property
3926 (+ d (match-beginning 0)) (match-end 0)
3927 'face 'org-latex-and-export-specials)
3928 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
3929 '(font-lock-multiline t)))))
3930 rtn)))
3932 (defun org-restart-font-lock ()
3933 "Restart font-lock-mode, to force refontification."
3934 (when (and (boundp 'font-lock-mode) font-lock-mode)
3935 (font-lock-mode -1)
3936 (font-lock-mode 1)))
3938 (defun org-all-targets (&optional radio)
3939 "Return a list of all targets in this file.
3940 With optional argument RADIO, only find radio targets."
3941 (let ((re (if radio org-radio-target-regexp org-target-regexp))
3942 rtn)
3943 (save-excursion
3944 (goto-char (point-min))
3945 (while (re-search-forward re nil t)
3946 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
3947 rtn)))
3949 (defun org-make-target-link-regexp (targets)
3950 "Make regular expression matching all strings in TARGETS.
3951 The regular expression finds the targets also if there is a line break
3952 between words."
3953 (and targets
3954 (concat
3955 "\\<\\("
3956 (mapconcat
3957 (lambda (x)
3958 (while (string-match " +" x)
3959 (setq x (replace-match "\\s-+" t t x)))
3961 targets
3962 "\\|")
3963 "\\)\\>")))
3965 (defun org-activate-tags (limit)
3966 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
3967 (progn
3968 (add-text-properties (match-beginning 1) (match-end 1)
3969 (list 'mouse-face 'highlight
3970 'rear-nonsticky org-nonsticky-props
3971 'keymap org-mouse-map))
3972 t)))
3974 (defun org-outline-level ()
3975 (save-excursion
3976 (looking-at outline-regexp)
3977 (if (match-beginning 1)
3978 (+ (org-get-string-indentation (match-string 1)) 1000)
3979 (1- (- (match-end 0) (match-beginning 0))))))
3981 (defvar org-font-lock-keywords nil)
3983 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
3984 "Regular expression matching a property line.")
3986 (defvar org-font-lock-hook nil
3987 "Functions to be called for special font lock stuff.")
3989 (defun org-font-lock-hook (limit)
3990 (run-hook-with-args 'org-font-lock-hook limit))
3992 (defun org-set-font-lock-defaults ()
3993 (let* ((em org-fontify-emphasized-text)
3994 (lk org-activate-links)
3995 (org-font-lock-extra-keywords
3996 (list
3997 ;; Call the hook
3998 '(org-font-lock-hook)
3999 ;; Headlines
4000 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
4001 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
4002 ;; Table lines
4003 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4004 (1 'org-table t))
4005 ;; Table internals
4006 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4007 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4008 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4009 ;; Drawers
4010 (list org-drawer-regexp '(0 'org-special-keyword t))
4011 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4012 ;; Properties
4013 (list org-property-re
4014 '(1 'org-special-keyword t)
4015 '(3 'org-property-value t))
4016 (if org-format-transports-properties-p
4017 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
4018 ;; Links
4019 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4020 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4021 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
4022 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4023 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4024 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4025 (if (memq 'footnote lk) '(org-activate-footnote-links
4026 (0 'org-footnote t)))
4027 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4028 '(org-hide-wide-columns (0 nil append))
4029 ;; TODO lines
4030 (list (concat "^\\*+[ \t]+" org-todo-regexp)
4031 '(1 (org-get-todo-face 1) t))
4032 ;; DONE
4033 (if org-fontify-done-headline
4034 (list (concat "^[*]+ +\\<\\("
4035 (mapconcat 'regexp-quote org-done-keywords "\\|")
4036 "\\)\\(.*\\)")
4037 '(2 'org-headline-done t))
4038 nil)
4039 ;; Priorities
4040 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
4041 ;; Tags
4042 '(org-font-lock-add-tag-faces)
4043 ;; Special keywords
4044 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4045 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4046 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4047 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4048 ;; Emphasis
4049 (if em
4050 (if (featurep 'xemacs)
4051 '(org-do-emphasis-faces (0 nil append))
4052 '(org-do-emphasis-faces)))
4053 ;; Checkboxes
4054 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
4055 2 'bold prepend)
4056 (if org-provide-checkbox-statistics
4057 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4058 (0 (org-get-checkbox-statistics-face) t)))
4059 ;; Description list items
4060 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
4061 2 'bold prepend)
4062 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
4063 '(1 'org-archived prepend))
4064 ;; Specials
4065 '(org-do-latex-and-special-faces)
4066 ;; Code
4067 '(org-activate-code (1 'org-code t))
4068 ;; COMMENT
4069 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
4070 "\\|" org-quote-string "\\)\\>")
4071 '(1 'org-special-keyword t))
4072 '("^#.*" (0 'font-lock-comment-face t))
4074 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
4075 ;; Now set the full font-lock-keywords
4076 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
4077 (org-set-local 'font-lock-defaults
4078 '(org-font-lock-keywords t nil nil backward-paragraph))
4079 (kill-local-variable 'font-lock-keywords) nil))
4081 (defvar org-m nil)
4082 (defvar org-l nil)
4083 (defvar org-f nil)
4084 (defun org-get-level-face (n)
4085 "Get the right face for match N in font-lock matching of headlines."
4086 (setq org-l (- (match-end 2) (match-beginning 1) 1))
4087 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
4088 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
4089 (cond
4090 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
4091 ((eq n 2) org-f)
4092 (t (if org-level-color-stars-only nil org-f))))
4094 (defun org-get-todo-face (kwd)
4095 "Get the right face for a TODO keyword KWD.
4096 If KWD is a number, get the corresponding match group."
4097 (if (numberp kwd) (setq kwd (match-string kwd)))
4098 (or (cdr (assoc kwd org-todo-keyword-faces))
4099 (and (member kwd org-done-keywords) 'org-done)
4100 'org-todo))
4102 (defun org-font-lock-add-tag-faces (limit)
4103 "Add the special tag faces."
4104 (when (and org-tag-faces org-tags-special-faces-re)
4105 (while (re-search-forward org-tags-special-faces-re limit t)
4106 (add-text-properties (match-beginning 1) (match-end 1)
4107 (list 'face (org-get-tag-face 1)
4108 'font-lock-fontified t))
4109 (backward-char 1))))
4111 (defun org-get-tag-face (kwd)
4112 "Get the right face for a TODO keyword KWD.
4113 If KWD is a number, get the corresponding match group."
4114 (if (numberp kwd) (setq kwd (match-string kwd)))
4115 (or (cdr (assoc kwd org-tag-faces))
4116 'org-tag))
4118 (defun org-unfontify-region (beg end &optional maybe_loudly)
4119 "Remove fontification and activation overlays from links."
4120 (font-lock-default-unfontify-region beg end)
4121 (let* ((buffer-undo-list t)
4122 (inhibit-read-only t) (inhibit-point-motion-hooks t)
4123 (inhibit-modification-hooks t)
4124 deactivate-mark buffer-file-name buffer-file-truename)
4125 (remove-text-properties beg end
4126 '(mouse-face t keymap t org-linked-text t
4127 invisible t intangible t))))
4129 ;;;; Visibility cycling, including org-goto and indirect buffer
4131 ;;; Cycling
4133 (defvar org-cycle-global-status nil)
4134 (make-variable-buffer-local 'org-cycle-global-status)
4135 (defvar org-cycle-subtree-status nil)
4136 (make-variable-buffer-local 'org-cycle-subtree-status)
4138 ;;;###autoload
4139 (defun org-cycle (&optional arg)
4140 "Visibility cycling for Org-mode.
4142 - When this function is called with a prefix argument, rotate the entire
4143 buffer through 3 states (global cycling)
4144 1. OVERVIEW: Show only top-level headlines.
4145 2. CONTENTS: Show all headlines of all levels, but no body text.
4146 3. SHOW ALL: Show everything.
4147 When called with two C-u C-u prefixes, switch to the startup visibility,
4148 determined by the variable `org-startup-folded', and by any VISIBILITY
4149 properties in the buffer.
4150 When called with three C-u C-u C-u prefixed, show the entire buffer,
4151 including drawers.
4153 - When point is at the beginning of a headline, rotate the subtree started
4154 by this line through 3 different states (local cycling)
4155 1. FOLDED: Only the main headline is shown.
4156 2. CHILDREN: The main headline and the direct children are shown.
4157 From this state, you can move to one of the children
4158 and zoom in further.
4159 3. SUBTREE: Show the entire subtree, including body text.
4161 - When there is a numeric prefix, go up to a heading with level ARG, do
4162 a `show-subtree' and return to the previous cursor position. If ARG
4163 is negative, go up that many levels.
4165 - When point is not at the beginning of a headline, execute the global
4166 binding for TAB, which is re-indenting the line. See the option
4167 `org-cycle-emulate-tab' for details.
4169 - Special case: if point is at the beginning of the buffer and there is
4170 no headline in line 1, this function will act as if called with prefix arg.
4171 But only if also the variable `org-cycle-global-at-bob' is t."
4172 (interactive "P")
4173 (org-load-modules-maybe)
4174 (let* ((outline-regexp
4175 (if (and (org-mode-p) org-cycle-include-plain-lists)
4176 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
4177 outline-regexp))
4178 (bob-special (and org-cycle-global-at-bob (bobp)
4179 (not (looking-at outline-regexp))))
4180 (org-cycle-hook
4181 (if bob-special
4182 (delq 'org-optimize-window-after-visibility-change
4183 (copy-sequence org-cycle-hook))
4184 org-cycle-hook))
4185 (pos (point)))
4187 (if (or bob-special (equal arg '(4)))
4188 ;; special case: use global cycling
4189 (setq arg t))
4191 (cond
4193 ((equal arg '(16))
4194 (org-set-startup-visibility)
4195 (message "Startup visibility, plus VISIBILITY properties"))
4197 ((equal arg '(64))
4198 (show-all)
4199 (message "Entire buffer visible, including drawers"))
4201 ((org-at-table-p 'any)
4202 ;; Enter the table or move to the next field in the table
4203 (or (org-table-recognize-table.el)
4204 (progn
4205 (if arg (org-table-edit-field t)
4206 (org-table-justify-field-maybe)
4207 (call-interactively 'org-table-next-field)))))
4209 ((eq arg t) ;; Global cycling
4211 (cond
4212 ((and (eq last-command this-command)
4213 (eq org-cycle-global-status 'overview))
4214 ;; We just created the overview - now do table of contents
4215 ;; This can be slow in very large buffers, so indicate action
4216 (message "CONTENTS...")
4217 (org-content)
4218 (message "CONTENTS...done")
4219 (setq org-cycle-global-status 'contents)
4220 (run-hook-with-args 'org-cycle-hook 'contents))
4222 ((and (eq last-command this-command)
4223 (eq org-cycle-global-status 'contents))
4224 ;; We just showed the table of contents - now show everything
4225 (show-all)
4226 (message "SHOW ALL")
4227 (setq org-cycle-global-status 'all)
4228 (run-hook-with-args 'org-cycle-hook 'all))
4231 ;; Default action: go to overview
4232 (org-overview)
4233 (message "OVERVIEW")
4234 (setq org-cycle-global-status 'overview)
4235 (run-hook-with-args 'org-cycle-hook 'overview))))
4237 ((and org-drawers org-drawer-regexp
4238 (save-excursion
4239 (beginning-of-line 1)
4240 (looking-at org-drawer-regexp)))
4241 ;; Toggle block visibility
4242 (org-flag-drawer
4243 (not (get-char-property (match-end 0) 'invisible))))
4245 ((integerp arg)
4246 ;; Show-subtree, ARG levels up from here.
4247 (save-excursion
4248 (org-back-to-heading)
4249 (outline-up-heading (if (< arg 0) (- arg)
4250 (- (funcall outline-level) arg)))
4251 (org-show-subtree)))
4253 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4254 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4255 ;; At a heading: rotate between three different views
4256 (org-back-to-heading)
4257 (let ((goal-column 0) eoh eol eos)
4258 ;; First, some boundaries
4259 (save-excursion
4260 (org-back-to-heading)
4261 (save-excursion
4262 (beginning-of-line 2)
4263 (while (and (not (eobp)) ;; this is like `next-line'
4264 (get-char-property (1- (point)) 'invisible))
4265 (beginning-of-line 2)) (setq eol (point)))
4266 (outline-end-of-heading) (setq eoh (point))
4267 (org-end-of-subtree t)
4268 (unless (eobp)
4269 (skip-chars-forward " \t\n")
4270 (beginning-of-line 1) ; in case this is an item
4272 (setq eos (1- (point))))
4273 ;; Find out what to do next and set `this-command'
4274 (cond
4275 ((= eos eoh)
4276 ;; Nothing is hidden behind this heading
4277 (message "EMPTY ENTRY")
4278 (setq org-cycle-subtree-status nil)
4279 (save-excursion
4280 (goto-char eos)
4281 (outline-next-heading)
4282 (if (org-invisible-p) (org-flag-heading nil))))
4283 ((or (>= eol eos)
4284 (not (string-match "\\S-" (buffer-substring eol eos))))
4285 ;; Entire subtree is hidden in one line: open it
4286 (org-show-entry)
4287 (show-children)
4288 (message "CHILDREN")
4289 (save-excursion
4290 (goto-char eos)
4291 (outline-next-heading)
4292 (if (org-invisible-p) (org-flag-heading nil)))
4293 (setq org-cycle-subtree-status 'children)
4294 (run-hook-with-args 'org-cycle-hook 'children))
4295 ((and (eq last-command this-command)
4296 (eq org-cycle-subtree-status 'children))
4297 ;; We just showed the children, now show everything.
4298 (org-show-subtree)
4299 (message "SUBTREE")
4300 (setq org-cycle-subtree-status 'subtree)
4301 (run-hook-with-args 'org-cycle-hook 'subtree))
4303 ;; Default action: hide the subtree.
4304 (hide-subtree)
4305 (message "FOLDED")
4306 (setq org-cycle-subtree-status 'folded)
4307 (run-hook-with-args 'org-cycle-hook 'folded)))))
4309 ;; TAB emulation and template completion
4310 (buffer-read-only (org-back-to-heading))
4312 ((org-try-structure-completion))
4314 ((org-try-cdlatex-tab))
4316 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4317 (or (not (bolp))
4318 (not (looking-at outline-regexp))))
4319 (call-interactively (global-key-binding "\t")))
4321 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4322 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4323 (or (and (eq org-cycle-emulate-tab 'white)
4324 (= (match-end 0) (point-at-eol)))
4325 (and (eq org-cycle-emulate-tab 'whitestart)
4326 (>= (match-end 0) pos))))
4328 (eq org-cycle-emulate-tab t))
4329 (call-interactively (global-key-binding "\t")))
4331 (t (save-excursion
4332 (org-back-to-heading)
4333 (org-cycle))))))
4335 ;;;###autoload
4336 (defun org-global-cycle (&optional arg)
4337 "Cycle the global visibility. For details see `org-cycle'.
4338 With C-u prefix arg, switch to startup visibility.
4339 With a numeric prefix, show all headlines up to that level."
4340 (interactive "P")
4341 (let ((org-cycle-include-plain-lists
4342 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4343 (cond
4344 ((integerp arg)
4345 (show-all)
4346 (hide-sublevels arg)
4347 (setq org-cycle-global-status 'contents))
4348 ((equal arg '(4))
4349 (org-set-startup-visibility)
4350 (message "Startup visibility, plus VISIBILITY properties."))
4352 (org-cycle '(4))))))
4354 (defun org-set-startup-visibility ()
4355 "Set the visibility required by startup options and properties."
4356 (cond
4357 ((eq org-startup-folded t)
4358 (org-cycle '(4)))
4359 ((eq org-startup-folded 'content)
4360 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4361 (org-cycle '(4)) (org-cycle '(4)))))
4362 (org-set-visibility-according-to-property 'no-cleanup)
4363 (org-cycle-hide-archived-subtrees 'all)
4364 (org-cycle-hide-drawers 'all)
4365 (org-cycle-show-empty-lines 'all))
4367 (defun org-set-visibility-according-to-property (&optional no-cleanup)
4368 "Switch subtree visibilities according to :VISIBILITY: property."
4369 (interactive)
4370 (let (state)
4371 (save-excursion
4372 (goto-char (point-min))
4373 (while (re-search-forward
4374 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
4375 nil t)
4376 (setq state (match-string 1))
4377 (save-excursion
4378 (org-back-to-heading t)
4379 (hide-subtree)
4380 (org-reveal)
4381 (cond
4382 ((equal state '("fold" "folded"))
4383 (hide-subtree))
4384 ((equal state "children")
4385 (org-show-hidden-entry)
4386 (show-children))
4387 ((equal state "content")
4388 (save-excursion
4389 (save-restriction
4390 (org-narrow-to-subtree)
4391 (org-content))))
4392 ((member state '("all" "showall"))
4393 (show-subtree)))))
4394 (unless no-cleanup
4395 (org-cycle-hide-archived-subtrees 'all)
4396 (org-cycle-hide-drawers 'all)
4397 (org-cycle-show-empty-lines 'all)))))
4399 (defun org-overview ()
4400 "Switch to overview mode, showing only top-level headlines.
4401 Really, this shows all headlines with level equal or greater than the level
4402 of the first headline in the buffer. This is important, because if the
4403 first headline is not level one, then (hide-sublevels 1) gives confusing
4404 results."
4405 (interactive)
4406 (let ((level (save-excursion
4407 (goto-char (point-min))
4408 (if (re-search-forward (concat "^" outline-regexp) nil t)
4409 (progn
4410 (goto-char (match-beginning 0))
4411 (funcall outline-level))))))
4412 (and level (hide-sublevels level))))
4414 (defun org-content (&optional arg)
4415 "Show all headlines in the buffer, like a table of contents.
4416 With numerical argument N, show content up to level N."
4417 (interactive "P")
4418 (save-excursion
4419 ;; Visit all headings and show their offspring
4420 (and (integerp arg) (org-overview))
4421 (goto-char (point-max))
4422 (catch 'exit
4423 (while (and (progn (condition-case nil
4424 (outline-previous-visible-heading 1)
4425 (error (goto-char (point-min))))
4427 (looking-at outline-regexp))
4428 (if (integerp arg)
4429 (show-children (1- arg))
4430 (show-branches))
4431 (if (bobp) (throw 'exit nil))))))
4434 (defun org-optimize-window-after-visibility-change (state)
4435 "Adjust the window after a change in outline visibility.
4436 This function is the default value of the hook `org-cycle-hook'."
4437 (when (get-buffer-window (current-buffer))
4438 (cond
4439 ; ((eq state 'overview) (org-first-headline-recenter 1))
4440 ; ((eq state 'overview) (org-beginning-of-line))
4441 ((eq state 'content) nil)
4442 ((eq state 'all) nil)
4443 ((eq state 'folded) nil)
4444 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4445 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4447 (defun org-compact-display-after-subtree-move ()
4448 (let (beg end)
4449 (save-excursion
4450 (if (org-up-heading-safe)
4451 (progn
4452 (hide-subtree)
4453 (show-entry)
4454 (show-children)
4455 (org-cycle-show-empty-lines 'children)
4456 (org-cycle-hide-drawers 'children))
4457 (org-overview)))))
4459 (defun org-cycle-show-empty-lines (state)
4460 "Show empty lines above all visible headlines.
4461 The region to be covered depends on STATE when called through
4462 `org-cycle-hook'. Lisp program can use t for STATE to get the
4463 entire buffer covered. Note that an empty line is only shown if there
4464 are at least `org-cycle-separator-lines' empty lines before the headline."
4465 (when (> org-cycle-separator-lines 0)
4466 (save-excursion
4467 (let* ((n org-cycle-separator-lines)
4468 (re (cond
4469 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
4470 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
4471 (t (let ((ns (number-to-string (- n 2))))
4472 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
4473 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
4474 beg end)
4475 (cond
4476 ((memq state '(overview contents t))
4477 (setq beg (point-min) end (point-max)))
4478 ((memq state '(children folded))
4479 (setq beg (point) end (progn (org-end-of-subtree t t)
4480 (beginning-of-line 2)
4481 (point)))))
4482 (when beg
4483 (goto-char beg)
4484 (while (re-search-forward re end t)
4485 (if (not (get-char-property (match-end 1) 'invisible))
4486 (outline-flag-region
4487 (match-beginning 1) (match-end 1) nil)))))))
4488 ;; Never hide empty lines at the end of the file.
4489 (save-excursion
4490 (goto-char (point-max))
4491 (outline-previous-heading)
4492 (outline-end-of-heading)
4493 (if (and (looking-at "[ \t\n]+")
4494 (= (match-end 0) (point-max)))
4495 (outline-flag-region (point) (match-end 0) nil))))
4497 (defun org-show-empty-lines-in-parent ()
4498 "Move to the parent and re-show empty lines before visible headlines."
4499 (save-excursion
4500 (let ((context (if (org-up-heading-safe) 'children 'overview)))
4501 (org-cycle-show-empty-lines context))))
4503 (defun org-cycle-hide-drawers (state)
4504 "Re-hide all drawers after a visibility state change."
4505 (when (and (org-mode-p)
4506 (not (memq state '(overview folded))))
4507 (save-excursion
4508 (let* ((globalp (memq state '(contents all)))
4509 (beg (if globalp (point-min) (point)))
4510 (end (if globalp (point-max) (org-end-of-subtree t))))
4511 (goto-char beg)
4512 (while (re-search-forward org-drawer-regexp end t)
4513 (org-flag-drawer t))))))
4515 (defun org-flag-drawer (flag)
4516 (save-excursion
4517 (beginning-of-line 1)
4518 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
4519 (let ((b (match-end 0))
4520 (outline-regexp org-outline-regexp))
4521 (if (re-search-forward
4522 "^[ \t]*:END:"
4523 (save-excursion (outline-next-heading) (point)) t)
4524 (outline-flag-region b (point-at-eol) flag)
4525 (error ":END: line missing"))))))
4527 (defun org-subtree-end-visible-p ()
4528 "Is the end of the current subtree visible?"
4529 (pos-visible-in-window-p
4530 (save-excursion (org-end-of-subtree t) (point))))
4532 (defun org-first-headline-recenter (&optional N)
4533 "Move cursor to the first headline and recenter the headline.
4534 Optional argument N means, put the headline into the Nth line of the window."
4535 (goto-char (point-min))
4536 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4537 (beginning-of-line)
4538 (recenter (prefix-numeric-value N))))
4540 ;;; Org-goto
4542 (defvar org-goto-window-configuration nil)
4543 (defvar org-goto-marker nil)
4544 (defvar org-goto-map
4545 (let ((map (make-sparse-keymap)))
4546 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
4547 (while (setq cmd (pop cmds))
4548 (substitute-key-definition cmd cmd map global-map)))
4549 (suppress-keymap map)
4550 (org-defkey map "\C-m" 'org-goto-ret)
4551 (org-defkey map [(return)] 'org-goto-ret)
4552 (org-defkey map [(left)] 'org-goto-left)
4553 (org-defkey map [(right)] 'org-goto-right)
4554 (org-defkey map [(control ?g)] 'org-goto-quit)
4555 (org-defkey map "\C-i" 'org-cycle)
4556 (org-defkey map [(tab)] 'org-cycle)
4557 (org-defkey map [(down)] 'outline-next-visible-heading)
4558 (org-defkey map [(up)] 'outline-previous-visible-heading)
4559 (if org-goto-auto-isearch
4560 (if (fboundp 'define-key-after)
4561 (define-key-after map [t] 'org-goto-local-auto-isearch)
4562 nil)
4563 (org-defkey map "q" 'org-goto-quit)
4564 (org-defkey map "n" 'outline-next-visible-heading)
4565 (org-defkey map "p" 'outline-previous-visible-heading)
4566 (org-defkey map "f" 'outline-forward-same-level)
4567 (org-defkey map "b" 'outline-backward-same-level)
4568 (org-defkey map "u" 'outline-up-heading))
4569 (org-defkey map "/" 'org-occur)
4570 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4571 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4572 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
4573 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
4574 (org-defkey map "\C-c\C-u" 'outline-up-heading)
4575 map))
4577 (defconst org-goto-help
4578 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4579 RET=jump to location [Q]uit and return to previous location
4580 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4582 (defvar org-goto-start-pos) ; dynamically scoped parameter
4584 ;; FIXME: Docstring doe not mention both interfaces
4585 (defun org-goto (&optional alternative-interface)
4586 "Look up a different location in the current file, keeping current visibility.
4588 When you want look-up or go to a different location in a document, the
4589 fastest way is often to fold the entire buffer and then dive into the tree.
4590 This method has the disadvantage, that the previous location will be folded,
4591 which may not be what you want.
4593 This command works around this by showing a copy of the current buffer
4594 in an indirect buffer, in overview mode. You can dive into the tree in
4595 that copy, use org-occur and incremental search to find a location.
4596 When pressing RET or `Q', the command returns to the original buffer in
4597 which the visibility is still unchanged. After RET is will also jump to
4598 the location selected in the indirect buffer and expose the
4599 the headline hierarchy above."
4600 (interactive "P")
4601 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
4602 (org-refile-use-outline-path t)
4603 (interface
4604 (if (not alternative-interface)
4605 org-goto-interface
4606 (if (eq org-goto-interface 'outline)
4607 'outline-path-completion
4608 'outline)))
4609 (org-goto-start-pos (point))
4610 (selected-point
4611 (if (eq interface 'outline)
4612 (car (org-get-location (current-buffer) org-goto-help))
4613 (nth 3 (org-refile-get-location "Goto: ")))))
4614 (if selected-point
4615 (progn
4616 (org-mark-ring-push org-goto-start-pos)
4617 (goto-char selected-point)
4618 (if (or (org-invisible-p) (org-invisible-p2))
4619 (org-show-context 'org-goto)))
4620 (message "Quit"))))
4622 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
4623 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
4624 (defvar org-goto-local-auto-isearch-map) ; defined below
4626 (defun org-get-location (buf help)
4627 "Let the user select a location in the Org-mode buffer BUF.
4628 This function uses a recursive edit. It returns the selected position
4629 or nil."
4630 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
4631 (isearch-hide-immediately nil)
4632 (isearch-search-fun-function
4633 (lambda () 'org-goto-local-search-headings))
4634 (org-goto-selected-point org-goto-exit-command))
4635 (save-excursion
4636 (save-window-excursion
4637 (delete-other-windows)
4638 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
4639 (switch-to-buffer
4640 (condition-case nil
4641 (make-indirect-buffer (current-buffer) "*org-goto*")
4642 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
4643 (with-output-to-temp-buffer "*Help*"
4644 (princ help))
4645 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
4646 (setq buffer-read-only nil)
4647 (let ((org-startup-truncated t)
4648 (org-startup-folded nil)
4649 (org-startup-align-all-tables nil))
4650 (org-mode)
4651 (org-overview))
4652 (setq buffer-read-only t)
4653 (if (and (boundp 'org-goto-start-pos)
4654 (integer-or-marker-p org-goto-start-pos))
4655 (let ((org-show-hierarchy-above t)
4656 (org-show-siblings t)
4657 (org-show-following-heading t))
4658 (goto-char org-goto-start-pos)
4659 (and (org-invisible-p) (org-show-context)))
4660 (goto-char (point-min)))
4661 (org-beginning-of-line)
4662 (message "Select location and press RET")
4663 (use-local-map org-goto-map)
4664 (recursive-edit)
4666 (kill-buffer "*org-goto*")
4667 (cons org-goto-selected-point org-goto-exit-command)))
4669 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
4670 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
4671 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
4672 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
4674 (defun org-goto-local-search-headings (string bound noerror)
4675 "Search and make sure that any matches are in headlines."
4676 (catch 'return
4677 (while (if isearch-forward
4678 (search-forward string bound noerror)
4679 (search-backward string bound noerror))
4680 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
4681 (and (member :headline context)
4682 (not (member :tags context))))
4683 (throw 'return (point))))))
4685 (defun org-goto-local-auto-isearch ()
4686 "Start isearch."
4687 (interactive)
4688 (goto-char (point-min))
4689 (let ((keys (this-command-keys)))
4690 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
4691 (isearch-mode t)
4692 (isearch-process-search-char (string-to-char keys)))))
4694 (defun org-goto-ret (&optional arg)
4695 "Finish `org-goto' by going to the new location."
4696 (interactive "P")
4697 (setq org-goto-selected-point (point)
4698 org-goto-exit-command 'return)
4699 (throw 'exit nil))
4701 (defun org-goto-left ()
4702 "Finish `org-goto' by going to the new location."
4703 (interactive)
4704 (if (org-on-heading-p)
4705 (progn
4706 (beginning-of-line 1)
4707 (setq org-goto-selected-point (point)
4708 org-goto-exit-command 'left)
4709 (throw 'exit nil))
4710 (error "Not on a heading")))
4712 (defun org-goto-right ()
4713 "Finish `org-goto' by going to the new location."
4714 (interactive)
4715 (if (org-on-heading-p)
4716 (progn
4717 (setq org-goto-selected-point (point)
4718 org-goto-exit-command 'right)
4719 (throw 'exit nil))
4720 (error "Not on a heading")))
4722 (defun org-goto-quit ()
4723 "Finish `org-goto' without cursor motion."
4724 (interactive)
4725 (setq org-goto-selected-point nil)
4726 (setq org-goto-exit-command 'quit)
4727 (throw 'exit nil))
4729 ;;; Indirect buffer display of subtrees
4731 (defvar org-indirect-dedicated-frame nil
4732 "This is the frame being used for indirect tree display.")
4733 (defvar org-last-indirect-buffer nil)
4735 (defun org-tree-to-indirect-buffer (&optional arg)
4736 "Create indirect buffer and narrow it to current subtree.
4737 With numerical prefix ARG, go up to this level and then take that tree.
4738 If ARG is negative, go up that many levels.
4739 If `org-indirect-buffer-display' is not `new-frame', the command removes the
4740 indirect buffer previously made with this command, to avoid proliferation of
4741 indirect buffers. However, when you call the command with a `C-u' prefix, or
4742 when `org-indirect-buffer-display' is `new-frame', the last buffer
4743 is kept so that you can work with several indirect buffers at the same time.
4744 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
4745 requests that a new frame be made for the new buffer, so that the dedicated
4746 frame is not changed."
4747 (interactive "P")
4748 (let ((cbuf (current-buffer))
4749 (cwin (selected-window))
4750 (pos (point))
4751 beg end level heading ibuf)
4752 (save-excursion
4753 (org-back-to-heading t)
4754 (when (numberp arg)
4755 (setq level (org-outline-level))
4756 (if (< arg 0) (setq arg (+ level arg)))
4757 (while (> (setq level (org-outline-level)) arg)
4758 (outline-up-heading 1 t)))
4759 (setq beg (point)
4760 heading (org-get-heading))
4761 (org-end-of-subtree t) (setq end (point)))
4762 (if (and (buffer-live-p org-last-indirect-buffer)
4763 (not (eq org-indirect-buffer-display 'new-frame))
4764 (not arg))
4765 (kill-buffer org-last-indirect-buffer))
4766 (setq ibuf (org-get-indirect-buffer cbuf)
4767 org-last-indirect-buffer ibuf)
4768 (cond
4769 ((or (eq org-indirect-buffer-display 'new-frame)
4770 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
4771 (select-frame (make-frame))
4772 (delete-other-windows)
4773 (switch-to-buffer ibuf)
4774 (org-set-frame-title heading))
4775 ((eq org-indirect-buffer-display 'dedicated-frame)
4776 (raise-frame
4777 (select-frame (or (and org-indirect-dedicated-frame
4778 (frame-live-p org-indirect-dedicated-frame)
4779 org-indirect-dedicated-frame)
4780 (setq org-indirect-dedicated-frame (make-frame)))))
4781 (delete-other-windows)
4782 (switch-to-buffer ibuf)
4783 (org-set-frame-title (concat "Indirect: " heading)))
4784 ((eq org-indirect-buffer-display 'current-window)
4785 (switch-to-buffer ibuf))
4786 ((eq org-indirect-buffer-display 'other-window)
4787 (pop-to-buffer ibuf))
4788 (t (error "Invalid value.")))
4789 (if (featurep 'xemacs)
4790 (save-excursion (org-mode) (turn-on-font-lock)))
4791 (narrow-to-region beg end)
4792 (show-all)
4793 (goto-char pos)
4794 (and (window-live-p cwin) (select-window cwin))))
4796 (defun org-get-indirect-buffer (&optional buffer)
4797 (setq buffer (or buffer (current-buffer)))
4798 (let ((n 1) (base (buffer-name buffer)) bname)
4799 (while (buffer-live-p
4800 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
4801 (setq n (1+ n)))
4802 (condition-case nil
4803 (make-indirect-buffer buffer bname 'clone)
4804 (error (make-indirect-buffer buffer bname)))))
4806 (defun org-set-frame-title (title)
4807 "Set the title of the current frame to the string TITLE."
4808 ;; FIXME: how to name a single frame in XEmacs???
4809 (unless (featurep 'xemacs)
4810 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
4812 ;;;; Structure editing
4814 ;;; Inserting headlines
4816 (defun org-insert-heading (&optional force-heading)
4817 "Insert a new heading or item with same depth at point.
4818 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
4819 If point is at the beginning of a headline, insert a sibling before the
4820 current headline. If point is not at the beginning, do not split the line,
4821 but create the new headline after the current line."
4822 (interactive "P")
4823 (if (= (buffer-size) 0)
4824 (insert "\n* ")
4825 (when (or force-heading (not (org-insert-item)))
4826 (let* ((head (save-excursion
4827 (condition-case nil
4828 (progn
4829 (org-back-to-heading)
4830 (match-string 0))
4831 (error "*"))))
4832 (blank (cdr (assq 'heading org-blank-before-new-entry)))
4833 pos hide-previous previous-pos)
4834 (cond
4835 ((and (org-on-heading-p) (bolp)
4836 (or (bobp)
4837 (save-excursion (backward-char 1) (not (org-invisible-p)))))
4838 ;; insert before the current line
4839 (open-line (if blank 2 1)))
4840 ((and (bolp)
4841 (or (bobp)
4842 (save-excursion
4843 (backward-char 1) (not (org-invisible-p)))))
4844 ;; insert right here
4845 nil)
4847 ;; somewhere in the line
4848 (save-excursion
4849 (setq previous-pos (point-at-bol))
4850 (end-of-line)
4851 (setq hide-previous (org-invisible-p)))
4852 (and org-insert-heading-respect-content (org-show-subtree))
4853 (let ((split
4854 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
4855 (save-excursion
4856 (let ((p (point)))
4857 (goto-char (point-at-bol))
4858 (and (looking-at org-complex-heading-regexp)
4859 (> p (match-beginning 4)))))))
4860 tags pos)
4861 (cond
4862 (org-insert-heading-respect-content
4863 (org-end-of-subtree nil t)
4864 (or (bolp) (newline))
4865 (open-line 1))
4866 ((org-on-heading-p)
4867 (when hide-previous
4868 (show-children)
4869 (org-show-entry))
4870 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4871 (setq tags (and (match-end 2) (match-string 2)))
4872 (and (match-end 1)
4873 (delete-region (match-beginning 1) (match-end 1)))
4874 (setq pos (point-at-bol))
4875 (or split (end-of-line 1))
4876 (delete-horizontal-space)
4877 (newline (if blank 2 1))
4878 (when tags
4879 (save-excursion
4880 (goto-char pos)
4881 (end-of-line 1)
4882 (insert " " tags)
4883 (org-set-tags nil 'align))))
4885 (or split (end-of-line 1))
4886 (newline (if blank 2 1)))))))
4887 (insert head) (just-one-space)
4888 (setq pos (point))
4889 (end-of-line 1)
4890 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
4891 (when (and org-insert-heading-respect-content hide-previous)
4892 (save-excursion
4893 (goto-char previous-pos)
4894 (hide-subtree)))
4895 (run-hooks 'org-insert-heading-hook)))))
4897 (defun org-get-heading (&optional no-tags)
4898 "Return the heading of the current entry, without the stars."
4899 (save-excursion
4900 (org-back-to-heading t)
4901 (if (looking-at
4902 (if no-tags
4903 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
4904 "\\*+[ \t]+\\([^\r\n]*\\)"))
4905 (match-string 1) "")))
4907 (defun org-insert-heading-after-current ()
4908 "Insert a new heading with same level as current, after current subtree."
4909 (interactive)
4910 (org-back-to-heading)
4911 (org-insert-heading)
4912 (org-move-subtree-down)
4913 (end-of-line 1))
4915 (defun org-insert-heading-respect-content ()
4916 (interactive)
4917 (let ((org-insert-heading-respect-content t))
4918 (org-insert-heading t)))
4920 (defun org-insert-todo-heading-respect-content (&optional force-state)
4921 (interactive "P")
4922 (let ((org-insert-heading-respect-content t))
4923 (org-insert-todo-heading force-state t)))
4925 (defun org-insert-todo-heading (arg &optional force-heading)
4926 "Insert a new heading with the same level and TODO state as current heading.
4927 If the heading has no TODO state, or if the state is DONE, use the first
4928 state (TODO by default). Also with prefix arg, force first state."
4929 (interactive "P")
4930 (when (or force-heading (not (org-insert-item 'checkbox)))
4931 (org-insert-heading force-heading)
4932 (save-excursion
4933 (org-back-to-heading)
4934 (outline-previous-heading)
4935 (looking-at org-todo-line-regexp))
4936 (if (or arg
4937 (not (match-beginning 2))
4938 (member (match-string 2) org-done-keywords))
4939 (insert (car org-todo-keywords-1) " ")
4940 (insert (match-string 2) " "))
4941 (when org-provide-todo-statistics
4942 (org-update-parent-todo-statistics))))
4944 (defun org-insert-subheading (arg)
4945 "Insert a new subheading and demote it.
4946 Works for outline headings and for plain lists alike."
4947 (interactive "P")
4948 (org-insert-heading arg)
4949 (cond
4950 ((org-on-heading-p) (org-do-demote))
4951 ((org-at-item-p) (org-indent-item 1))))
4953 (defun org-insert-todo-subheading (arg)
4954 "Insert a new subheading with TODO keyword or checkbox and demote it.
4955 Works for outline headings and for plain lists alike."
4956 (interactive "P")
4957 (org-insert-todo-heading arg)
4958 (cond
4959 ((org-on-heading-p) (org-do-demote))
4960 ((org-at-item-p) (org-indent-item 1))))
4962 ;;; Promotion and Demotion
4964 (defun org-promote-subtree ()
4965 "Promote the entire subtree.
4966 See also `org-promote'."
4967 (interactive)
4968 (save-excursion
4969 (org-map-tree 'org-promote))
4970 (org-fix-position-after-promote))
4972 (defun org-demote-subtree ()
4973 "Demote the entire subtree. See `org-demote'.
4974 See also `org-promote'."
4975 (interactive)
4976 (save-excursion
4977 (org-map-tree 'org-demote))
4978 (org-fix-position-after-promote))
4981 (defun org-do-promote ()
4982 "Promote the current heading higher up the tree.
4983 If the region is active in `transient-mark-mode', promote all headings
4984 in the region."
4985 (interactive)
4986 (save-excursion
4987 (if (org-region-active-p)
4988 (org-map-region 'org-promote (region-beginning) (region-end))
4989 (org-promote)))
4990 (org-fix-position-after-promote))
4992 (defun org-do-demote ()
4993 "Demote the current heading lower down the tree.
4994 If the region is active in `transient-mark-mode', demote all headings
4995 in the region."
4996 (interactive)
4997 (save-excursion
4998 (if (org-region-active-p)
4999 (org-map-region 'org-demote (region-beginning) (region-end))
5000 (org-demote)))
5001 (org-fix-position-after-promote))
5003 (defun org-fix-position-after-promote ()
5004 "Make sure that after pro/demotion cursor position is right."
5005 (let ((pos (point)))
5006 (when (save-excursion
5007 (beginning-of-line 1)
5008 (looking-at org-todo-line-regexp)
5009 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
5010 (cond ((eobp) (insert " "))
5011 ((eolp) (insert " "))
5012 ((equal (char-after) ?\ ) (forward-char 1))))))
5014 (defun org-reduced-level (l)
5015 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
5017 (defun org-get-valid-level (level &optional change)
5018 "Rectify a level change under the influence of `org-odd-levels-only'
5019 LEVEL is a current level, CHANGE is by how much the level should be
5020 modified. Even if CHANGE is nil, LEVEL may be returned modified because
5021 even level numbers will become the next higher odd number."
5022 (if org-odd-levels-only
5023 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
5024 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
5025 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
5026 (max 1 (+ level change))))
5028 (if (boundp 'define-obsolete-function-alias)
5029 (if (or (featurep 'xemacs) (< emacs-major-version 23))
5030 (define-obsolete-function-alias 'org-get-legal-level
5031 'org-get-valid-level)
5032 (define-obsolete-function-alias 'org-get-legal-level
5033 'org-get-valid-level "23.1")))
5035 (defun org-promote ()
5036 "Promote the current heading higher up the tree.
5037 If the region is active in `transient-mark-mode', promote all headings
5038 in the region."
5039 (org-back-to-heading t)
5040 (let* ((level (save-match-data (funcall outline-level)))
5041 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
5042 (diff (abs (- level (length up-head) -1))))
5043 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
5044 (replace-match up-head nil t)
5045 ;; Fixup tag positioning
5046 (and org-auto-align-tags (org-set-tags nil t))
5047 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
5049 (defun org-demote ()
5050 "Demote the current heading lower down the tree.
5051 If the region is active in `transient-mark-mode', demote all headings
5052 in the region."
5053 (org-back-to-heading t)
5054 (let* ((level (save-match-data (funcall outline-level)))
5055 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
5056 (diff (abs (- level (length down-head) -1))))
5057 (replace-match down-head nil t)
5058 ;; Fixup tag positioning
5059 (and org-auto-align-tags (org-set-tags nil t))
5060 (if org-adapt-indentation (org-fixup-indentation diff))))
5062 (defun org-map-tree (fun)
5063 "Call FUN for every heading underneath the current one."
5064 (org-back-to-heading)
5065 (let ((level (funcall outline-level)))
5066 (save-excursion
5067 (funcall fun)
5068 (while (and (progn
5069 (outline-next-heading)
5070 (> (funcall outline-level) level))
5071 (not (eobp)))
5072 (funcall fun)))))
5074 (defun org-map-region (fun beg end)
5075 "Call FUN for every heading between BEG and END."
5076 (let ((org-ignore-region t))
5077 (save-excursion
5078 (setq end (copy-marker end))
5079 (goto-char beg)
5080 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
5081 (< (point) end))
5082 (funcall fun))
5083 (while (and (progn
5084 (outline-next-heading)
5085 (< (point) end))
5086 (not (eobp)))
5087 (funcall fun)))))
5089 (defun org-fixup-indentation (diff)
5090 "Change the indentation in the current entry by DIFF
5091 However, if any line in the current entry has no indentation, or if it
5092 would end up with no indentation after the change, nothing at all is done."
5093 (save-excursion
5094 (let ((end (save-excursion (outline-next-heading)
5095 (point-marker)))
5096 (prohibit (if (> diff 0)
5097 "^\\S-"
5098 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
5099 col)
5100 (unless (save-excursion (end-of-line 1)
5101 (re-search-forward prohibit end t))
5102 (while (and (< (point) end)
5103 (re-search-forward "^[ \t]+" end t))
5104 (goto-char (match-end 0))
5105 (setq col (current-column))
5106 (if (< diff 0) (replace-match ""))
5107 (org-indent-to-column (+ diff col))))
5108 (move-marker end nil))))
5110 (defun org-convert-to-odd-levels ()
5111 "Convert an org-mode file with all levels allowed to one with odd levels.
5112 This will leave level 1 alone, convert level 2 to level 3, level 3 to
5113 level 5 etc."
5114 (interactive)
5115 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
5116 (let ((org-odd-levels-only nil) n)
5117 (save-excursion
5118 (goto-char (point-min))
5119 (while (re-search-forward "^\\*\\*+ " nil t)
5120 (setq n (- (length (match-string 0)) 2))
5121 (while (>= (setq n (1- n)) 0)
5122 (org-demote))
5123 (end-of-line 1))))))
5126 (defun org-convert-to-oddeven-levels ()
5127 "Convert an org-mode file with only odd levels to one with odd and even levels.
5128 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
5129 section with an even level, conversion would destroy the structure of the file. An error
5130 is signaled in this case."
5131 (interactive)
5132 (goto-char (point-min))
5133 ;; First check if there are no even levels
5134 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
5135 (org-show-context t)
5136 (error "Not all levels are odd in this file. Conversion not possible."))
5137 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
5138 (let ((org-odd-levels-only nil) n)
5139 (save-excursion
5140 (goto-char (point-min))
5141 (while (re-search-forward "^\\*\\*+ " nil t)
5142 (setq n (/ (1- (length (match-string 0))) 2))
5143 (while (>= (setq n (1- n)) 0)
5144 (org-promote))
5145 (end-of-line 1))))))
5147 (defun org-tr-level (n)
5148 "Make N odd if required."
5149 (if org-odd-levels-only (1+ (/ n 2)) n))
5151 ;;; Vertical tree motion, cutting and pasting of subtrees
5153 (defun org-move-subtree-up (&optional arg)
5154 "Move the current subtree up past ARG headlines of the same level."
5155 (interactive "p")
5156 (org-move-subtree-down (- (prefix-numeric-value arg))))
5158 (defun org-move-subtree-down (&optional arg)
5159 "Move the current subtree down past ARG headlines of the same level."
5160 (interactive "p")
5161 (setq arg (prefix-numeric-value arg))
5162 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
5163 'outline-get-last-sibling))
5164 (ins-point (make-marker))
5165 (cnt (abs arg))
5166 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
5167 ;; Select the tree
5168 (org-back-to-heading)
5169 (setq beg0 (point))
5170 (save-excursion
5171 (setq ne-beg (org-back-over-empty-lines))
5172 (setq beg (point)))
5173 (save-match-data
5174 (save-excursion (outline-end-of-heading)
5175 (setq folded (org-invisible-p)))
5176 (outline-end-of-subtree))
5177 (outline-next-heading)
5178 (setq ne-end (org-back-over-empty-lines))
5179 (setq end (point))
5180 (goto-char beg0)
5181 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
5182 ;; include less whitespace
5183 (save-excursion
5184 (goto-char beg)
5185 (forward-line (- ne-beg ne-end))
5186 (setq beg (point))))
5187 ;; Find insertion point, with error handling
5188 (while (> cnt 0)
5189 (or (and (funcall movfunc) (looking-at outline-regexp))
5190 (progn (goto-char beg0)
5191 (error "Cannot move past superior level or buffer limit")))
5192 (setq cnt (1- cnt)))
5193 (if (> arg 0)
5194 ;; Moving forward - still need to move over subtree
5195 (progn (org-end-of-subtree t t)
5196 (save-excursion
5197 (org-back-over-empty-lines)
5198 (or (bolp) (newline)))))
5199 (setq ne-ins (org-back-over-empty-lines))
5200 (move-marker ins-point (point))
5201 (setq txt (buffer-substring beg end))
5202 (org-save-markers-in-region beg end)
5203 (delete-region beg end)
5204 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
5205 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
5206 (let ((bbb (point)))
5207 (insert-before-markers txt)
5208 (org-reinstall-markers-in-region bbb)
5209 (move-marker ins-point bbb))
5210 (or (bolp) (insert "\n"))
5211 (setq ins-end (point))
5212 (goto-char ins-point)
5213 (org-skip-whitespace)
5214 (when (and (< arg 0)
5215 (org-first-sibling-p)
5216 (> ne-ins ne-beg))
5217 ;; Move whitespace back to beginning
5218 (save-excursion
5219 (goto-char ins-end)
5220 (let ((kill-whole-line t))
5221 (kill-line (- ne-ins ne-beg)) (point)))
5222 (insert (make-string (- ne-ins ne-beg) ?\n)))
5223 (move-marker ins-point nil)
5224 (org-compact-display-after-subtree-move)
5225 (org-show-empty-lines-in-parent)
5226 (unless folded
5227 (org-show-entry)
5228 (show-children)
5229 (org-cycle-hide-drawers 'children))))
5231 (defvar org-subtree-clip ""
5232 "Clipboard for cut and paste of subtrees.
5233 This is actually only a copy of the kill, because we use the normal kill
5234 ring. We need it to check if the kill was created by `org-copy-subtree'.")
5236 (defvar org-subtree-clip-folded nil
5237 "Was the last copied subtree folded?
5238 This is used to fold the tree back after pasting.")
5240 (defun org-cut-subtree (&optional n)
5241 "Cut the current subtree into the clipboard.
5242 With prefix arg N, cut this many sequential subtrees.
5243 This is a short-hand for marking the subtree and then cutting it."
5244 (interactive "p")
5245 (org-copy-subtree n 'cut))
5247 (defun org-copy-subtree (&optional n cut force-store-markers)
5248 "Cut the current subtree into the clipboard.
5249 With prefix arg N, cut this many sequential subtrees.
5250 This is a short-hand for marking the subtree and then copying it.
5251 If CUT is non-nil, actually cut the subtree.
5252 If FORCE-STORE-MARKERS is non-nil, store the relative locations
5253 of some markers in the region, even if CUT is non-nil. This is
5254 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
5255 (interactive "p")
5256 (let (beg end folded (beg0 (point)))
5257 (if (interactive-p)
5258 (org-back-to-heading nil) ; take what looks like a subtree
5259 (org-back-to-heading t)) ; take what is really there
5260 (org-back-over-empty-lines)
5261 (setq beg (point))
5262 (skip-chars-forward " \t\r\n")
5263 (save-match-data
5264 (save-excursion (outline-end-of-heading)
5265 (setq folded (org-invisible-p)))
5266 (condition-case nil
5267 (outline-forward-same-level (1- n))
5268 (error nil))
5269 (org-end-of-subtree t t))
5270 (org-back-over-empty-lines)
5271 (setq end (point))
5272 (goto-char beg0)
5273 (when (> end beg)
5274 (setq org-subtree-clip-folded folded)
5275 (when (or cut force-store-markers)
5276 (org-save-markers-in-region beg end))
5277 (if cut (kill-region beg end) (copy-region-as-kill beg end))
5278 (setq org-subtree-clip (current-kill 0))
5279 (message "%s: Subtree(s) with %d characters"
5280 (if cut "Cut" "Copied")
5281 (length org-subtree-clip)))))
5283 (defun org-paste-subtree (&optional level tree for-yank)
5284 "Paste the clipboard as a subtree, with modification of headline level.
5285 The entire subtree is promoted or demoted in order to match a new headline
5286 level.
5288 If the cursor is at the beginning of a headline, the same level as
5289 that headline is used to paste the tree
5291 If not, the new level is derived from the *visible* headings
5292 before and after the insertion point, and taken to be the inferior headline
5293 level of the two. So if the previous visible heading is level 3 and the
5294 next is level 4 (or vice versa), level 4 will be used for insertion.
5295 This makes sure that the subtree remains an independent subtree and does
5296 not swallow low level entries.
5298 You can also force a different level, either by using a numeric prefix
5299 argument, or by inserting the heading marker by hand. For example, if the
5300 cursor is after \"*****\", then the tree will be shifted to level 5.
5302 If optional TREE is given, use this text instead of the kill ring.
5304 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
5305 move back over whitespace before inserting, and move point to the end of
5306 the inserted text when done."
5307 (interactive "P")
5308 (unless (org-kill-is-subtree-p tree)
5309 (error "%s"
5310 (substitute-command-keys
5311 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
5312 (let* ((visp (not (org-invisible-p)))
5313 (txt (or tree (and kill-ring (current-kill 0))))
5314 (^re (concat "^\\(" outline-regexp "\\)"))
5315 (re (concat "\\(" outline-regexp "\\)"))
5316 (^re_ (concat "\\(\\*+\\)[ \t]*"))
5318 (old-level (if (string-match ^re txt)
5319 (- (match-end 0) (match-beginning 0) 1)
5320 -1))
5321 (force-level (cond (level (prefix-numeric-value level))
5322 ((and (looking-at "[ \t]*$")
5323 (string-match
5324 ^re_ (buffer-substring
5325 (point-at-bol) (point))))
5326 (- (match-end 1) (match-beginning 1)))
5327 ((and (bolp)
5328 (looking-at org-outline-regexp))
5329 (- (match-end 0) (point) 1))
5330 (t nil)))
5331 (previous-level (save-excursion
5332 (condition-case nil
5333 (progn
5334 (outline-previous-visible-heading 1)
5335 (if (looking-at re)
5336 (- (match-end 0) (match-beginning 0) 1)
5338 (error 1))))
5339 (next-level (save-excursion
5340 (condition-case nil
5341 (progn
5342 (or (looking-at outline-regexp)
5343 (outline-next-visible-heading 1))
5344 (if (looking-at re)
5345 (- (match-end 0) (match-beginning 0) 1)
5347 (error 1))))
5348 (new-level (or force-level (max previous-level next-level)))
5349 (shift (if (or (= old-level -1)
5350 (= new-level -1)
5351 (= old-level new-level))
5353 (- new-level old-level)))
5354 (delta (if (> shift 0) -1 1))
5355 (func (if (> shift 0) 'org-demote 'org-promote))
5356 (org-odd-levels-only nil)
5357 beg end newend)
5358 ;; Remove the forced level indicator
5359 (if force-level
5360 (delete-region (point-at-bol) (point)))
5361 ;; Paste
5362 (beginning-of-line 1)
5363 (unless for-yank (org-back-over-empty-lines))
5364 (setq beg (point))
5365 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
5366 (insert-before-markers txt)
5367 (unless (string-match "\n\\'" txt) (insert "\n"))
5368 (setq newend (point))
5369 (org-reinstall-markers-in-region beg)
5370 (setq end (point))
5371 (goto-char beg)
5372 (skip-chars-forward " \t\n\r")
5373 (setq beg (point))
5374 (if (and (org-invisible-p) visp)
5375 (save-excursion (outline-show-heading)))
5376 ;; Shift if necessary
5377 (unless (= shift 0)
5378 (save-restriction
5379 (narrow-to-region beg end)
5380 (while (not (= shift 0))
5381 (org-map-region func (point-min) (point-max))
5382 (setq shift (+ delta shift)))
5383 (goto-char (point-min))
5384 (setq newend (point-max))))
5385 (when (or (interactive-p) for-yank)
5386 (message "Clipboard pasted as level %d subtree" new-level))
5387 (if (and (not for-yank) ; in this case, org-yank will decide about folding
5388 kill-ring
5389 (eq org-subtree-clip (current-kill 0))
5390 org-subtree-clip-folded)
5391 ;; The tree was folded before it was killed/copied
5392 (hide-subtree))
5393 (and for-yank (goto-char newend))))
5395 (defun org-kill-is-subtree-p (&optional txt)
5396 "Check if the current kill is an outline subtree, or a set of trees.
5397 Returns nil if kill does not start with a headline, or if the first
5398 headline level is not the largest headline level in the tree.
5399 So this will actually accept several entries of equal levels as well,
5400 which is OK for `org-paste-subtree'.
5401 If optional TXT is given, check this string instead of the current kill."
5402 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
5403 (start-level (and kill
5404 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
5405 org-outline-regexp "\\)")
5406 kill)
5407 (- (match-end 2) (match-beginning 2) 1)))
5408 (re (concat "^" org-outline-regexp))
5409 (start (1+ (or (match-beginning 2) -1))))
5410 (if (not start-level)
5411 (progn
5412 nil) ;; does not even start with a heading
5413 (catch 'exit
5414 (while (setq start (string-match re kill (1+ start)))
5415 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
5416 (throw 'exit nil)))
5417 t))))
5419 (defvar org-markers-to-move nil
5420 "Markers that should be moved with a cut-and-paste operation.
5421 Those markers are stored together with their positions relative to
5422 the start of the region.")
5424 (defun org-save-markers-in-region (beg end)
5425 "Check markers in region.
5426 If these markers are between BEG and END, record their position relative
5427 to BEG, so that after moving the block of text, we can put the markers back
5428 into place.
5429 This function gets called just before an entry or tree gets cut from the
5430 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
5431 called immediately, to move the markers with the entries."
5432 (setq org-markers-to-move nil)
5433 (when (featurep 'org-clock)
5434 (org-clock-save-markers-for-cut-and-paste beg end))
5435 (when (featurep 'org-agenda)
5436 (org-agenda-save-markers-for-cut-and-paste beg end)))
5438 (defun org-check-and-save-marker (marker beg end)
5439 "Check if MARKER is between BEG and END.
5440 If yes, remember the marker and the distance to BEG."
5441 (when (and (marker-buffer marker)
5442 (equal (marker-buffer marker) (current-buffer)))
5443 (if (and (>= marker beg) (< marker end))
5444 (push (cons marker (- marker beg)) org-markers-to-move))))
5446 (defun org-reinstall-markers-in-region (beg)
5447 "Move all remembered markers to their position relative to BEG."
5448 (mapc (lambda (x)
5449 (move-marker (car x) (+ beg (cdr x))))
5450 org-markers-to-move)
5451 (setq org-markers-to-move nil))
5453 (defun org-narrow-to-subtree ()
5454 "Narrow buffer to the current subtree."
5455 (interactive)
5456 (save-excursion
5457 (save-match-data
5458 (narrow-to-region
5459 (progn (org-back-to-heading) (point))
5460 (progn (org-end-of-subtree t) (point))))))
5463 ;;; Outline Sorting
5465 (defun org-sort (with-case)
5466 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
5467 Optional argument WITH-CASE means sort case-sensitively."
5468 (interactive "P")
5469 (if (org-at-table-p)
5470 (org-call-with-arg 'org-table-sort-lines with-case)
5471 (org-call-with-arg 'org-sort-entries-or-items with-case)))
5473 (defun org-sort-remove-invisible (s)
5474 (remove-text-properties 0 (length s) org-rm-props s)
5475 (while (string-match org-bracket-link-regexp s)
5476 (setq s (replace-match (if (match-end 2)
5477 (match-string 3 s)
5478 (match-string 1 s)) t t s)))
5481 (defvar org-priority-regexp) ; defined later in the file
5483 (defun org-sort-entries-or-items
5484 (&optional with-case sorting-type getkey-func compare-func property)
5485 "Sort entries on a certain level of an outline tree.
5486 If there is an active region, the entries in the region are sorted.
5487 Else, if the cursor is before the first entry, sort the top-level items.
5488 Else, the children of the entry at point are sorted.
5490 Sorting can be alphabetically, numerically, and by date/time as given by
5491 the first time stamp in the entry. The command prompts for the sorting
5492 type unless it has been given to the function through the SORTING-TYPE
5493 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
5494 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
5495 called with point at the beginning of the record. It must return either
5496 a string or a number that should serve as the sorting key for that record.
5498 Comparing entries ignores case by default. However, with an optional argument
5499 WITH-CASE, the sorting considers case as well."
5500 (interactive "P")
5501 (let ((case-func (if with-case 'identity 'downcase))
5502 start beg end stars re re2
5503 txt what tmp plain-list-p)
5504 ;; Find beginning and end of region to sort
5505 (cond
5506 ((org-region-active-p)
5507 ;; we will sort the region
5508 (setq end (region-end)
5509 what "region")
5510 (goto-char (region-beginning))
5511 (if (not (org-on-heading-p)) (outline-next-heading))
5512 (setq start (point)))
5513 ((org-at-item-p)
5514 ;; we will sort this plain list
5515 (org-beginning-of-item-list) (setq start (point))
5516 (org-end-of-item-list) (setq end (point))
5517 (goto-char start)
5518 (setq plain-list-p t
5519 what "plain list"))
5520 ((or (org-on-heading-p)
5521 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
5522 ;; we will sort the children of the current headline
5523 (org-back-to-heading)
5524 (setq start (point)
5525 end (progn (org-end-of-subtree t t)
5526 (org-back-over-empty-lines)
5527 (point))
5528 what "children")
5529 (goto-char start)
5530 (show-subtree)
5531 (outline-next-heading))
5533 ;; we will sort the top-level entries in this file
5534 (goto-char (point-min))
5535 (or (org-on-heading-p) (outline-next-heading))
5536 (setq start (point) end (point-max) what "top-level")
5537 (goto-char start)
5538 (show-all)))
5540 (setq beg (point))
5541 (if (>= beg end) (error "Nothing to sort"))
5543 (unless plain-list-p
5544 (looking-at "\\(\\*+\\)")
5545 (setq stars (match-string 1)
5546 re (concat "^" (regexp-quote stars) " +")
5547 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
5548 txt (buffer-substring beg end))
5549 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
5550 (if (and (not (equal stars "*")) (string-match re2 txt))
5551 (error "Region to sort contains a level above the first entry")))
5553 (unless sorting-type
5554 (message
5555 (if plain-list-p
5556 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
5557 "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:")
5558 what)
5559 (setq sorting-type (read-char-exclusive))
5561 (and (= (downcase sorting-type) ?f)
5562 (setq getkey-func
5563 (org-ido-completing-read "Sort using function: "
5564 obarray 'fboundp t nil nil))
5565 (setq getkey-func (intern getkey-func)))
5567 (and (= (downcase sorting-type) ?r)
5568 (setq property
5569 (org-ido-completing-read "Property: "
5570 (mapcar 'list (org-buffer-property-keys t))
5571 nil t))))
5573 (message "Sorting entries...")
5575 (save-restriction
5576 (narrow-to-region start end)
5578 (let ((dcst (downcase sorting-type))
5579 (now (current-time)))
5580 (sort-subr
5581 (/= dcst sorting-type)
5582 ;; This function moves to the beginning character of the "record" to
5583 ;; be sorted.
5584 (if plain-list-p
5585 (lambda nil
5586 (if (org-at-item-p) t (goto-char (point-max))))
5587 (lambda nil
5588 (if (re-search-forward re nil t)
5589 (goto-char (match-beginning 0))
5590 (goto-char (point-max)))))
5591 ;; This function moves to the last character of the "record" being
5592 ;; sorted.
5593 (if plain-list-p
5594 'org-end-of-item
5595 (lambda nil
5596 (save-match-data
5597 (condition-case nil
5598 (outline-forward-same-level 1)
5599 (error
5600 (goto-char (point-max)))))))
5602 ;; This function returns the value that gets sorted against.
5603 (if plain-list-p
5604 (lambda nil
5605 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
5606 (cond
5607 ((= dcst ?n)
5608 (string-to-number (buffer-substring (match-end 0)
5609 (point-at-eol))))
5610 ((= dcst ?a)
5611 (buffer-substring (match-end 0) (point-at-eol)))
5612 ((= dcst ?t)
5613 (if (re-search-forward org-ts-regexp
5614 (point-at-eol) t)
5615 (org-time-string-to-time (match-string 0))
5616 now))
5617 ((= dcst ?f)
5618 (if getkey-func
5619 (progn
5620 (setq tmp (funcall getkey-func))
5621 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5622 tmp)
5623 (error "Invalid key function `%s'" getkey-func)))
5624 (t (error "Invalid sorting type `%c'" sorting-type)))))
5625 (lambda nil
5626 (cond
5627 ((= dcst ?n)
5628 (if (looking-at org-complex-heading-regexp)
5629 (string-to-number (match-string 4))
5630 nil))
5631 ((= dcst ?a)
5632 (if (looking-at org-complex-heading-regexp)
5633 (funcall case-func (match-string 4))
5634 nil))
5635 ((= dcst ?t)
5636 (if (re-search-forward org-ts-regexp
5637 (save-excursion
5638 (forward-line 2)
5639 (point)) t)
5640 (org-time-string-to-time (match-string 0))
5641 now))
5642 ((= dcst ?p)
5643 (if (re-search-forward org-priority-regexp (point-at-eol) t)
5644 (string-to-char (match-string 2))
5645 org-default-priority))
5646 ((= dcst ?r)
5647 (or (org-entry-get nil property) ""))
5648 ((= dcst ?o)
5649 (if (looking-at org-complex-heading-regexp)
5650 (- 9999 (length (member (match-string 2)
5651 org-todo-keywords-1)))))
5652 ((= dcst ?f)
5653 (if getkey-func
5654 (progn
5655 (setq tmp (funcall getkey-func))
5656 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5657 tmp)
5658 (error "Invalid key function `%s'" getkey-func)))
5659 (t (error "Invalid sorting type `%c'" sorting-type)))))
5661 (cond
5662 ((= dcst ?a) 'string<)
5663 ((= dcst ?t) 'time-less-p)
5664 ((= dcst ?f) compare-func)
5665 (t nil)))))
5666 (message "Sorting entries...done")))
5668 (defun org-do-sort (table what &optional with-case sorting-type)
5669 "Sort TABLE of WHAT according to SORTING-TYPE.
5670 The user will be prompted for the SORTING-TYPE if the call to this
5671 function does not specify it. WHAT is only for the prompt, to indicate
5672 what is being sorted. The sorting key will be extracted from
5673 the car of the elements of the table.
5674 If WITH-CASE is non-nil, the sorting will be case-sensitive."
5675 (unless sorting-type
5676 (message
5677 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
5678 what)
5679 (setq sorting-type (read-char-exclusive)))
5680 (let ((dcst (downcase sorting-type))
5681 extractfun comparefun)
5682 ;; Define the appropriate functions
5683 (cond
5684 ((= dcst ?n)
5685 (setq extractfun 'string-to-number
5686 comparefun (if (= dcst sorting-type) '< '>)))
5687 ((= dcst ?a)
5688 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
5689 (lambda(x) (downcase (org-sort-remove-invisible x))))
5690 comparefun (if (= dcst sorting-type)
5691 'string<
5692 (lambda (a b) (and (not (string< a b))
5693 (not (string= a b)))))))
5694 ((= dcst ?t)
5695 (setq extractfun
5696 (lambda (x)
5697 (if (string-match org-ts-regexp x)
5698 (time-to-seconds
5699 (org-time-string-to-time (match-string 0 x)))
5701 comparefun (if (= dcst sorting-type) '< '>)))
5702 (t (error "Invalid sorting type `%c'" sorting-type)))
5704 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5705 table)
5706 (lambda (a b) (funcall comparefun (car a) (car b))))))
5708 ;;; Editing source examples
5710 (defvar org-exit-edit-mode-map (make-sparse-keymap))
5711 (define-key org-exit-edit-mode-map "\C-c'" 'org-edit-src-exit)
5712 (defvar org-edit-src-force-single-line nil)
5713 (defvar org-edit-src-from-org-mode nil)
5714 (defvar org-edit-src-picture nil)
5716 (define-minor-mode org-exit-edit-mode
5717 "Minor mode installing a single key binding, \"C-c '\" to exit special edit.")
5719 (defun org-edit-src-code ()
5720 "Edit the source code example at point.
5721 An indirect buffer is created, and that buffer is then narrowed to the
5722 example at point and switched to the correct language mode. When done,
5723 exit by killing the buffer with \\[org-edit-src-exit]."
5724 (interactive)
5725 (let ((line (org-current-line))
5726 (case-fold-search t)
5727 (msg (substitute-command-keys
5728 "Edit, then exit with C-c ' (C-c and single quote)"))
5729 (info (org-edit-src-find-region-and-lang))
5730 (org-mode-p (eq major-mode 'org-mode))
5731 beg end lang lang-f single)
5732 (if (not info)
5734 (setq beg (nth 0 info)
5735 end (nth 1 info)
5736 lang (nth 2 info)
5737 single (nth 3 info)
5738 lang-f (intern (concat lang "-mode")))
5739 (unless (functionp lang-f)
5740 (error "No such language mode: %s" lang-f))
5741 (goto-line line)
5742 (if (get-buffer "*Org Edit Src Example*")
5743 (kill-buffer "*Org Edit Src Example*"))
5744 (switch-to-buffer (make-indirect-buffer (current-buffer)
5745 "*Org Edit Src Example*"))
5746 (narrow-to-region beg end)
5747 (remove-text-properties beg end '(display nil invisible nil
5748 intangible nil))
5749 (let ((org-inhibit-startup t))
5750 (funcall lang-f))
5751 (set (make-local-variable 'org-edit-src-force-single-line) single)
5752 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5753 (when org-mode-p
5754 (goto-char (point-min))
5755 (while (re-search-forward "^," nil t)
5756 (replace-match "")))
5757 (goto-line line)
5758 (org-exit-edit-mode)
5759 (org-set-local 'header-line-format msg)
5760 (message "%s" msg)
5761 t)))
5763 (defun org-edit-fixed-width-region ()
5764 "Edit the fixed-width ascii drawing at point.
5765 This must be a region where each line starts with a colon followed by
5766 a space character.
5767 An indirect buffer is created, and that buffer is then narrowed to the
5768 example at point and switched to artist-mode. When done,
5769 exit by killing the buffer with \\[org-edit-src-exit]."
5770 (interactive)
5771 (let ((line (org-current-line))
5772 (case-fold-search t)
5773 (msg (substitute-command-keys
5774 "Edit, then exit with C-c ' (C-c and single quote)"))
5775 (org-mode-p (eq major-mode 'org-mode))
5776 beg end lang lang-f)
5777 (beginning-of-line 1)
5778 (if (looking-at "[ \t]*[^:\n \t]")
5780 (if (looking-at "[ \t]*\\(\n\\|\\'\\)")
5781 (setq beg (point) end beg)
5782 (save-excursion
5783 (if (re-search-backward "^[ \t]*[^:]" nil 'move)
5784 (setq beg (point-at-bol 2))
5785 (setq beg (point))))
5786 (save-excursion
5787 (if (re-search-forward "^[ \t]*[^:]" nil 'move)
5788 (setq end (1- (match-beginning 0)))
5789 (setq end (point))))
5790 (goto-line line))
5791 (if (get-buffer "*Org Edit Picture*")
5792 (kill-buffer "*Org Edit Picture*"))
5793 (switch-to-buffer (make-indirect-buffer (current-buffer)
5794 "*Org Edit Picture*"))
5795 (narrow-to-region beg end)
5796 (remove-text-properties beg end '(display nil invisible nil
5797 intangible nil))
5798 (when (fboundp 'font-lock-unfontify-region)
5799 (font-lock-unfontify-region (point-min) (point-max)))
5800 (cond
5801 ((eq org-edit-fixed-width-region-mode 'artist-mode)
5802 (fundamental-mode)
5803 (artist-mode 1))
5804 (t (funcall org-edit-fixed-width-region-mode)))
5805 (set (make-local-variable 'org-edit-src-force-single-line) nil)
5806 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5807 (set (make-local-variable 'org-edit-src-picture) t)
5808 (goto-char (point-min))
5809 (while (re-search-forward "^[ \t]*: ?" nil t)
5810 (replace-match ""))
5811 (goto-line line)
5812 (org-exit-edit-mode)
5813 (org-set-local 'header-line-format msg)
5814 (message "%s" msg)
5815 t)))
5818 (defun org-edit-src-find-region-and-lang ()
5819 "Find the region and language for a local edit.
5820 Return a list with beginning and end of the region, a string representing
5821 the language, a switch telling of the content should be in a single line."
5822 (let ((re-list
5823 (append
5824 org-edit-src-region-extra
5826 ("<src\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</src>" lang)
5827 ("<literal\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</literal>" style)
5828 ("<example>[ \t]*\n?" "\n?[ \t]*</example>" "fundamental")
5829 ("<lisp>[ \t]*\n?" "\n?[ \t]*</lisp>" "emacs-lisp")
5830 ("<perl>[ \t]*\n?" "\n?[ \t]*</perl>" "perl")
5831 ("<python>[ \t]*\n?" "\n?[ \t]*</python>" "python")
5832 ("<ruby>[ \t]*\n?" "\n?[ \t]*</ruby>" "ruby")
5833 ("^#\\+begin_src\\( \\([^ \t\n]+\\)\\)?.*\n" "\n#\\+end_src" 2)
5834 ("^#\\+begin_example.*\n" "\n#\\+end_example" "fundamental")
5835 ("^#\\+html:" "\n" "html" single-line)
5836 ("^#\\+begin_html.*\n" "\n#\\+end_html" "html")
5837 ("^#\\+begin_latex.*\n" "\n#\\+end_latex" "latex")
5838 ("^#\\+latex:" "\n" "latex" single-line)
5839 ("^#\\+begin_ascii.*\n" "\n#\\+end_ascii" "fundamental")
5840 ("^#\\+ascii:" "\n" "ascii" single-line)
5842 (pos (point))
5843 re re1 re2 single beg end lang)
5844 (catch 'exit
5845 (while (setq entry (pop re-list))
5846 (setq re1 (car entry) re2 (nth 1 entry) lang (nth 2 entry)
5847 single (nth 3 entry))
5848 (save-excursion
5849 (if (or (looking-at re1)
5850 (re-search-backward re1 nil t))
5851 (progn
5852 (setq beg (match-end 0) lang (org-edit-src-get-lang lang))
5853 (if (and (re-search-forward re2 nil t)
5854 (>= (match-end 0) pos))
5855 (throw 'exit (list beg (match-beginning 0) lang single))))
5856 (if (or (looking-at re2)
5857 (re-search-forward re2 nil t))
5858 (progn
5859 (setq end (match-beginning 0))
5860 (if (and (re-search-backward re1 nil t)
5861 (<= (match-beginning 0) pos))
5862 (throw 'exit
5863 (list (match-end 0) end
5864 (org-edit-src-get-lang lang) single)))))))))))
5866 (defun org-edit-src-get-lang (lang)
5867 "Extract the src language."
5868 (let ((m (match-string 0)))
5869 (cond
5870 ((stringp lang) lang)
5871 ((integerp lang) (match-string lang))
5872 ((and (eq lang 'lang)
5873 (string-match "\\<lang=\"\\([^ \t\n\"]+\\)\"" m))
5874 (match-string 1 m))
5875 ((and (eq lang 'style)
5876 (string-match "\\<style=\"\\([^ \t\n\"]+\\)\"" m))
5877 (match-string 1 m))
5878 (t "fundamental"))))
5880 (defun org-edit-src-exit ()
5881 "Exit special edit and protect problematic lines."
5882 (interactive)
5883 (unless (buffer-base-buffer (current-buffer))
5884 (error "This is not an indirect buffer, something is wrong..."))
5885 (unless (> (point-min) 1)
5886 (error "This buffer is not narrowed, something is wrong..."))
5887 (goto-char (point-min))
5888 (if (looking-at "[ \t\n]*\n") (replace-match ""))
5889 (if (re-search-forward "\n[ \t\n]*\\'" nil t) (replace-match ""))
5890 (when (org-bound-and-true-p org-edit-src-force-single-line)
5891 (goto-char (point-min))
5892 (while (re-search-forward "\n" nil t)
5893 (replace-match " "))
5894 (goto-char (point-min))
5895 (if (looking-at "\\s-*") (replace-match " "))
5896 (if (re-search-forward "\\s-+\\'" nil t)
5897 (replace-match "")))
5898 (when (org-bound-and-true-p org-edit-src-from-org-mode)
5899 (goto-char (point-min))
5900 (while (re-search-forward (if (org-mode-p) "^\\(.\\)" "^\\([*#]\\)") nil t)
5901 (replace-match ",\\1"))
5902 (when font-lock-mode
5903 (font-lock-unfontify-region (point-min) (point-max)))
5904 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
5905 (when (org-bound-and-true-p org-edit-src-picture)
5906 (untabify (point-min) (point-max))
5907 (goto-char (point-min))
5908 (while (re-search-forward "^" nil t)
5909 (replace-match ": "))
5910 (when font-lock-mode
5911 (font-lock-unfontify-region (point-min) (point-max)))
5912 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
5913 (kill-buffer (current-buffer))
5914 (and (org-mode-p) (org-restart-font-lock)))
5917 ;;; The orgstruct minor mode
5919 ;; Define a minor mode which can be used in other modes in order to
5920 ;; integrate the org-mode structure editing commands.
5922 ;; This is really a hack, because the org-mode structure commands use
5923 ;; keys which normally belong to the major mode. Here is how it
5924 ;; works: The minor mode defines all the keys necessary to operate the
5925 ;; structure commands, but wraps the commands into a function which
5926 ;; tests if the cursor is currently at a headline or a plain list
5927 ;; item. If that is the case, the structure command is used,
5928 ;; temporarily setting many Org-mode variables like regular
5929 ;; expressions for filling etc. However, when any of those keys is
5930 ;; used at a different location, function uses `key-binding' to look
5931 ;; up if the key has an associated command in another currently active
5932 ;; keymap (minor modes, major mode, global), and executes that
5933 ;; command. There might be problems if any of the keys is otherwise
5934 ;; used as a prefix key.
5936 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
5937 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
5938 ;; addresses this by checking explicitly for both bindings.
5940 (defvar orgstruct-mode-map (make-sparse-keymap)
5941 "Keymap for the minor `orgstruct-mode'.")
5943 (defvar org-local-vars nil
5944 "List of local variables, for use by `orgstruct-mode'")
5946 ;;;###autoload
5947 (define-minor-mode orgstruct-mode
5948 "Toggle the minor more `orgstruct-mode'.
5949 This mode is for using Org-mode structure commands in other modes.
5950 The following key behave as if Org-mode was active, if the cursor
5951 is on a headline, or on a plain list item (both in the definition
5952 of Org-mode).
5954 M-up Move entry/item up
5955 M-down Move entry/item down
5956 M-left Promote
5957 M-right Demote
5958 M-S-up Move entry/item up
5959 M-S-down Move entry/item down
5960 M-S-left Promote subtree
5961 M-S-right Demote subtree
5962 M-q Fill paragraph and items like in Org-mode
5963 C-c ^ Sort entries
5964 C-c - Cycle list bullet
5965 TAB Cycle item visibility
5966 M-RET Insert new heading/item
5967 S-M-RET Insert new TODO heading / Checkbox item
5968 C-c C-c Set tags / toggle checkbox"
5969 nil " OrgStruct" nil
5970 (org-load-modules-maybe)
5971 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
5973 ;;;###autoload
5974 (defun turn-on-orgstruct ()
5975 "Unconditionally turn on `orgstruct-mode'."
5976 (orgstruct-mode 1))
5978 ;;;###autoload
5979 (defun turn-on-orgstruct++ ()
5980 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
5981 In addition to setting orgstruct-mode, this also exports all indentation and
5982 autofilling variables from org-mode into the buffer. Note that turning
5983 off orgstruct-mode will *not* remove these additional settings."
5984 (orgstruct-mode 1)
5985 (let (var val)
5986 (mapc
5987 (lambda (x)
5988 (when (string-match
5989 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
5990 (symbol-name (car x)))
5991 (setq var (car x) val (nth 1 x))
5992 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
5993 org-local-vars)))
5995 (defun orgstruct-error ()
5996 "Error when there is no default binding for a structure key."
5997 (interactive)
5998 (error "This key has no function outside structure elements"))
6000 (defun orgstruct-setup ()
6001 "Setup orgstruct keymaps."
6002 (let ((nfunc 0)
6003 (bindings
6004 (list
6005 '([(meta up)] org-metaup)
6006 '([(meta down)] org-metadown)
6007 '([(meta left)] org-metaleft)
6008 '([(meta right)] org-metaright)
6009 '([(meta shift up)] org-shiftmetaup)
6010 '([(meta shift down)] org-shiftmetadown)
6011 '([(meta shift left)] org-shiftmetaleft)
6012 '([(meta shift right)] org-shiftmetaright)
6013 '([(shift up)] org-shiftup)
6014 '([(shift down)] org-shiftdown)
6015 '([(shift left)] org-shiftleft)
6016 '([(shift right)] org-shiftright)
6017 '("\C-c\C-c" org-ctrl-c-ctrl-c)
6018 '("\M-q" fill-paragraph)
6019 '("\C-c^" org-sort)
6020 '("\C-c-" org-cycle-list-bullet)))
6021 elt key fun cmd)
6022 (while (setq elt (pop bindings))
6023 (setq nfunc (1+ nfunc))
6024 (setq key (org-key (car elt))
6025 fun (nth 1 elt)
6026 cmd (orgstruct-make-binding fun nfunc key))
6027 (org-defkey orgstruct-mode-map key cmd))
6029 ;; Special treatment needed for TAB and RET
6030 (org-defkey orgstruct-mode-map [(tab)]
6031 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
6032 (org-defkey orgstruct-mode-map "\C-i"
6033 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
6035 (org-defkey orgstruct-mode-map "\M-\C-m"
6036 (orgstruct-make-binding 'org-insert-heading 105
6037 "\M-\C-m" [(meta return)]))
6038 (org-defkey orgstruct-mode-map [(meta return)]
6039 (orgstruct-make-binding 'org-insert-heading 106
6040 [(meta return)] "\M-\C-m"))
6042 (org-defkey orgstruct-mode-map [(shift meta return)]
6043 (orgstruct-make-binding 'org-insert-todo-heading 107
6044 [(meta return)] "\M-\C-m"))
6046 (unless org-local-vars
6047 (setq org-local-vars (org-get-local-variables)))
6051 (defun orgstruct-make-binding (fun n &rest keys)
6052 "Create a function for binding in the structure minor mode.
6053 FUN is the command to call inside a table. N is used to create a unique
6054 command name. KEYS are keys that should be checked in for a command
6055 to execute outside of tables."
6056 (eval
6057 (list 'defun
6058 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6059 '(arg)
6060 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6061 "Outside of structure, run the binding of `"
6062 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6063 "'.")
6064 '(interactive "p")
6065 (list 'if
6066 '(org-context-p 'headline 'item)
6067 (list 'org-run-like-in-org-mode (list 'quote fun))
6068 (list 'let '(orgstruct-mode)
6069 (list 'call-interactively
6070 (append '(or)
6071 (mapcar (lambda (k)
6072 (list 'key-binding k))
6073 keys)
6074 '('orgstruct-error))))))))
6076 (defun org-context-p (&rest contexts)
6077 "Check if local context is any of CONTEXTS.
6078 Possible values in the list of contexts are `table', `headline', and `item'."
6079 (let ((pos (point)))
6080 (goto-char (point-at-bol))
6081 (prog1 (or (and (memq 'table contexts)
6082 (looking-at "[ \t]*|"))
6083 (and (memq 'headline contexts)
6084 ;;????????? (looking-at "\\*+"))
6085 (looking-at outline-regexp))
6086 (and (memq 'item contexts)
6087 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
6088 (goto-char pos))))
6090 (defun org-get-local-variables ()
6091 "Return a list of all local variables in an org-mode buffer."
6092 (let (varlist)
6093 (with-current-buffer (get-buffer-create "*Org tmp*")
6094 (erase-buffer)
6095 (org-mode)
6096 (setq varlist (buffer-local-variables)))
6097 (kill-buffer "*Org tmp*")
6098 (delq nil
6099 (mapcar
6100 (lambda (x)
6101 (setq x
6102 (if (symbolp x)
6103 (list x)
6104 (list (car x) (list 'quote (cdr x)))))
6105 (if (string-match
6106 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6107 (symbol-name (car x)))
6108 x nil))
6109 varlist))))
6111 ;;;###autoload
6112 (defun org-run-like-in-org-mode (cmd)
6113 (org-load-modules-maybe)
6114 (unless org-local-vars
6115 (setq org-local-vars (org-get-local-variables)))
6116 (eval (list 'let org-local-vars
6117 (list 'call-interactively (list 'quote cmd)))))
6119 ;;;; Archiving
6121 (defun org-get-category (&optional pos)
6122 "Get the category applying to position POS."
6123 (get-text-property (or pos (point)) 'org-category))
6125 (defun org-refresh-category-properties ()
6126 "Refresh category text properties in the buffer."
6127 (let ((def-cat (cond
6128 ((null org-category)
6129 (if buffer-file-name
6130 (file-name-sans-extension
6131 (file-name-nondirectory buffer-file-name))
6132 "???"))
6133 ((symbolp org-category) (symbol-name org-category))
6134 (t org-category)))
6135 beg end cat pos optionp)
6136 (org-unmodified
6137 (save-excursion
6138 (save-restriction
6139 (widen)
6140 (goto-char (point-min))
6141 (put-text-property (point) (point-max) 'org-category def-cat)
6142 (while (re-search-forward
6143 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6144 (setq pos (match-end 0)
6145 optionp (equal (char-after (match-beginning 0)) ?#)
6146 cat (org-trim (match-string 2)))
6147 (if optionp
6148 (setq beg (point-at-bol) end (point-max))
6149 (org-back-to-heading t)
6150 (setq beg (point) end (org-end-of-subtree t t)))
6151 (put-text-property beg end 'org-category cat)
6152 (goto-char pos)))))))
6155 ;;;; Link Stuff
6157 ;;; Link abbreviations
6159 (defun org-link-expand-abbrev (link)
6160 "Apply replacements as defined in `org-link-abbrev-alist."
6161 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6162 (let* ((key (match-string 1 link))
6163 (as (or (assoc key org-link-abbrev-alist-local)
6164 (assoc key org-link-abbrev-alist)))
6165 (tag (and (match-end 2) (match-string 3 link)))
6166 rpl)
6167 (if (not as)
6168 link
6169 (setq rpl (cdr as))
6170 (cond
6171 ((symbolp rpl) (funcall rpl tag))
6172 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
6173 ((string-match "%h" rpl)
6174 (replace-match (url-hexify-string (or tag "")) t t rpl))
6175 (t (concat rpl tag)))))
6176 link))
6178 ;;; Storing and inserting links
6180 (defvar org-insert-link-history nil
6181 "Minibuffer history for links inserted with `org-insert-link'.")
6183 (defvar org-stored-links nil
6184 "Contains the links stored with `org-store-link'.")
6186 (defvar org-store-link-plist nil
6187 "Plist with info about the most recently link created with `org-store-link'.")
6189 (defvar org-link-protocols nil
6190 "Link protocols added to Org-mode using `org-add-link-type'.")
6192 (defvar org-store-link-functions nil
6193 "List of functions that are called to create and store a link.
6194 Each function will be called in turn until one returns a non-nil
6195 value. Each function should check if it is responsible for creating
6196 this link (for example by looking at the major mode).
6197 If not, it must exit and return nil.
6198 If yes, it should return a non-nil value after a calling
6199 `org-store-link-props' with a list of properties and values.
6200 Special properties are:
6202 :type The link prefix. like \"http\". This must be given.
6203 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6204 This is obligatory as well.
6205 :description Optional default description for the second pair
6206 of brackets in an Org-mode link. The user can still change
6207 this when inserting this link into an Org-mode buffer.
6209 In addition to these, any additional properties can be specified
6210 and then used in remember templates.")
6212 (defun org-add-link-type (type &optional follow export)
6213 "Add TYPE to the list of `org-link-types'.
6214 Re-compute all regular expressions depending on `org-link-types'
6216 FOLLOW and EXPORT are two functions.
6218 FOLLOW should take the link path as the single argument and do whatever
6219 is necessary to follow the link, for example find a file or display
6220 a mail message.
6222 EXPORT should format the link path for export to one of the export formats.
6223 It should be a function accepting three arguments:
6225 path the path of the link, the text after the prefix (like \"http:\")
6226 desc the description of the link, if any, nil if there was no description
6227 format the export format, a symbol like `html' or `latex'.
6229 The function may use the FORMAT information to return different values
6230 depending on the format. The return value will be put literally into
6231 the exported file.
6232 Org-mode has a built-in default for exporting links. If you are happy with
6233 this default, there is no need to define an export function for the link
6234 type. For a simple example of an export function, see `org-bbdb.el'."
6235 (add-to-list 'org-link-types type t)
6236 (org-make-link-regexps)
6237 (if (assoc type org-link-protocols)
6238 (setcdr (assoc type org-link-protocols) (list follow export))
6239 (push (list type follow export) org-link-protocols)))
6241 ;;;###autoload
6242 (defun org-store-link (arg)
6243 "\\<org-mode-map>Store an org-link to the current location.
6244 This link is added to `org-stored-links' and can later be inserted
6245 into an org-buffer with \\[org-insert-link].
6247 For some link types, a prefix arg is interpreted:
6248 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
6249 For file links, arg negates `org-context-in-file-links'."
6250 (interactive "P")
6251 (org-load-modules-maybe)
6252 (setq org-store-link-plist nil) ; reset
6253 (let (link cpltxt desc description search txt)
6254 (cond
6256 ((run-hook-with-args-until-success 'org-store-link-functions)
6257 (setq link (plist-get org-store-link-plist :link)
6258 desc (or (plist-get org-store-link-plist :description) link)))
6260 ((equal (buffer-name) "*Org Edit Src Example*")
6261 (let (label gc)
6262 (while (or (not label)
6263 (save-excursion
6264 (save-restriction
6265 (widen)
6266 (goto-char (point-min))
6267 (re-search-forward (concat "((" label "))") nil t))))
6268 (when label (message "Label exists already") (sit-for 2))
6269 (setq label (read-string "Code line label: " label)))
6270 (end-of-line 1)
6271 (setq link (format "((%s))" label))
6272 (setq gc (- 79 (length link)))
6273 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
6274 (insert link)
6275 (setq desc nil)))
6277 ((eq major-mode 'calendar-mode)
6278 (let ((cd (calendar-cursor-to-date)))
6279 (setq link
6280 (format-time-string
6281 (car org-time-stamp-formats)
6282 (apply 'encode-time
6283 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6284 nil nil nil))))
6285 (org-store-link-props :type "calendar" :date cd)))
6287 ((eq major-mode 'w3-mode)
6288 (setq cpltxt (url-view-url t)
6289 link (org-make-link cpltxt))
6290 (org-store-link-props :type "w3" :url (url-view-url t)))
6292 ((eq major-mode 'w3m-mode)
6293 (setq cpltxt (or w3m-current-title w3m-current-url)
6294 link (org-make-link w3m-current-url))
6295 (org-store-link-props :type "w3m" :url (url-view-url t)))
6297 ((setq search (run-hook-with-args-until-success
6298 'org-create-file-search-functions))
6299 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6300 "::" search))
6301 (setq cpltxt (or description link)))
6303 ((eq major-mode 'image-mode)
6304 (setq cpltxt (concat "file:"
6305 (abbreviate-file-name buffer-file-name))
6306 link (org-make-link cpltxt))
6307 (org-store-link-props :type "image" :file buffer-file-name))
6309 ((eq major-mode 'dired-mode)
6310 ;; link to the file in the current line
6311 (setq cpltxt (concat "file:"
6312 (abbreviate-file-name
6313 (expand-file-name
6314 (dired-get-filename nil t))))
6315 link (org-make-link cpltxt)))
6317 ((and buffer-file-name (org-mode-p))
6318 (cond
6319 ((org-in-regexp "<<\\(.*?\\)>>")
6320 (setq cpltxt
6321 (concat "file:"
6322 (abbreviate-file-name buffer-file-name)
6323 "::" (match-string 1))
6324 link (org-make-link cpltxt)))
6325 ((and (featurep 'org-id)
6326 (or (eq org-link-to-org-use-id t)
6327 (and (eq org-link-to-org-use-id 'create-if-interactive)
6328 (interactive-p))
6329 (and org-link-to-org-use-id
6330 (condition-case nil
6331 (org-entry-get nil "ID")
6332 (error nil)))))
6333 ;; We can make a link using the ID.
6334 (setq link (condition-case nil
6335 (prog1 (org-id-store-link)
6336 (setq desc (plist-get org-store-link-plist
6337 :description)))
6338 (error
6339 ;; probably before first headline, link to file only
6340 (concat "file:"
6341 (abbreviate-file-name buffer-file-name))))))
6343 ;; Just link to current headline
6344 (setq cpltxt (concat "file:"
6345 (abbreviate-file-name buffer-file-name)))
6346 ;; Add a context search string
6347 (when (org-xor org-context-in-file-links arg)
6348 (setq txt (cond
6349 ((org-on-heading-p) nil)
6350 ((org-region-active-p)
6351 (buffer-substring (region-beginning) (region-end)))
6352 (t nil)))
6353 (when (or (null txt) (string-match "\\S-" txt))
6354 (setq cpltxt
6355 (concat cpltxt "::"
6356 (condition-case nil
6357 (org-make-org-heading-search-string txt)
6358 (error "")))
6359 desc "NONE")))
6360 (if (string-match "::\\'" cpltxt)
6361 (setq cpltxt (substring cpltxt 0 -2)))
6362 (setq link (org-make-link cpltxt)))))
6364 ((buffer-file-name (buffer-base-buffer))
6365 ;; Just link to this file here.
6366 (setq cpltxt (concat "file:"
6367 (abbreviate-file-name
6368 (buffer-file-name (buffer-base-buffer)))))
6369 ;; Add a context string
6370 (when (org-xor org-context-in-file-links arg)
6371 (setq txt (if (org-region-active-p)
6372 (buffer-substring (region-beginning) (region-end))
6373 (buffer-substring (point-at-bol) (point-at-eol))))
6374 ;; Only use search option if there is some text.
6375 (when (string-match "\\S-" txt)
6376 (setq cpltxt
6377 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6378 desc "NONE")))
6379 (setq link (org-make-link cpltxt)))
6381 ((interactive-p)
6382 (error "Cannot link to a buffer which is not visiting a file"))
6384 (t (setq link nil)))
6386 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6387 (setq link (or link cpltxt)
6388 desc (or desc cpltxt))
6389 (if (equal desc "NONE") (setq desc nil))
6391 (if (and (interactive-p) link)
6392 (progn
6393 (setq org-stored-links
6394 (cons (list link desc) org-stored-links))
6395 (message "Stored: %s" (or desc link)))
6396 (and link (org-make-link-string link desc)))))
6398 (defun org-store-link-props (&rest plist)
6399 "Store link properties, extract names and addresses."
6400 (let (x adr)
6401 (when (setq x (plist-get plist :from))
6402 (setq adr (mail-extract-address-components x))
6403 (setq plist (plist-put plist :fromname (car adr)))
6404 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
6405 (when (setq x (plist-get plist :to))
6406 (setq adr (mail-extract-address-components x))
6407 (setq plist (plist-put plist :toname (car adr)))
6408 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
6409 (let ((from (plist-get plist :from))
6410 (to (plist-get plist :to)))
6411 (when (and from to org-from-is-user-regexp)
6412 (setq plist
6413 (plist-put plist :fromto
6414 (if (string-match org-from-is-user-regexp from)
6415 (concat "to %t")
6416 (concat "from %f"))))))
6417 (setq org-store-link-plist plist))
6419 (defun org-add-link-props (&rest plist)
6420 "Add these properties to the link property list."
6421 (let (key value)
6422 (while plist
6423 (setq key (pop plist) value (pop plist))
6424 (setq org-store-link-plist
6425 (plist-put org-store-link-plist key value)))))
6427 (defun org-email-link-description (&optional fmt)
6428 "Return the description part of an email link.
6429 This takes information from `org-store-link-plist' and formats it
6430 according to FMT (default from `org-email-link-description-format')."
6431 (setq fmt (or fmt org-email-link-description-format))
6432 (let* ((p org-store-link-plist)
6433 (to (plist-get p :toaddress))
6434 (from (plist-get p :fromaddress))
6435 (table
6436 (list
6437 (cons "%c" (plist-get p :fromto))
6438 (cons "%F" (plist-get p :from))
6439 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
6440 (cons "%T" (plist-get p :to))
6441 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
6442 (cons "%s" (plist-get p :subject))
6443 (cons "%m" (plist-get p :message-id)))))
6444 (when (string-match "%c" fmt)
6445 ;; Check if the user wrote this message
6446 (if (and org-from-is-user-regexp from to
6447 (save-match-data (string-match org-from-is-user-regexp from)))
6448 (setq fmt (replace-match "to %t" t t fmt))
6449 (setq fmt (replace-match "from %f" t t fmt))))
6450 (org-replace-escapes fmt table)))
6452 (defun org-make-org-heading-search-string (&optional string heading)
6453 "Make search string for STRING or current headline."
6454 (interactive)
6455 (let ((s (or string (org-get-heading))))
6456 (unless (and string (not heading))
6457 ;; We are using a headline, clean up garbage in there.
6458 (if (string-match org-todo-regexp s)
6459 (setq s (replace-match "" t t s)))
6460 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
6461 (setq s (replace-match "" t t s)))
6462 (setq s (org-trim s))
6463 (if (string-match (concat "^\\(" org-quote-string "\\|"
6464 org-comment-string "\\)") s)
6465 (setq s (replace-match "" t t s)))
6466 (while (string-match org-ts-regexp s)
6467 (setq s (replace-match "" t t s))))
6468 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
6469 (setq s (replace-match " " t t s)))
6470 (or string (setq s (concat "*" s))) ; Add * for headlines
6471 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
6473 (defun org-make-link (&rest strings)
6474 "Concatenate STRINGS."
6475 (apply 'concat strings))
6477 (defun org-make-link-string (link &optional description)
6478 "Make a link with brackets, consisting of LINK and DESCRIPTION."
6479 (unless (string-match "\\S-" link)
6480 (error "Empty link"))
6481 (when (stringp description)
6482 ;; Remove brackets from the description, they are fatal.
6483 (while (string-match "\\[" description)
6484 (setq description (replace-match "{" t t description)))
6485 (while (string-match "\\]" description)
6486 (setq description (replace-match "}" t t description))))
6487 (when (equal (org-link-escape link) description)
6488 ;; No description needed, it is identical
6489 (setq description nil))
6490 (when (and (not description)
6491 (not (equal link (org-link-escape link))))
6492 (setq description (org-extract-attributes link)))
6493 (concat "[[" (org-link-escape link) "]"
6494 (if description (concat "[" description "]") "")
6495 "]"))
6497 (defconst org-link-escape-chars
6498 '((?\ . "%20")
6499 (?\[ . "%5B")
6500 (?\] . "%5D")
6501 (?\340 . "%E0") ; `a
6502 (?\342 . "%E2") ; ^a
6503 (?\347 . "%E7") ; ,c
6504 (?\350 . "%E8") ; `e
6505 (?\351 . "%E9") ; 'e
6506 (?\352 . "%EA") ; ^e
6507 (?\356 . "%EE") ; ^i
6508 (?\364 . "%F4") ; ^o
6509 (?\371 . "%F9") ; `u
6510 (?\373 . "%FB") ; ^u
6511 (?\; . "%3B")
6512 (?? . "%3F")
6513 (?= . "%3D")
6514 (?+ . "%2B")
6516 "Association list of escapes for some characters problematic in links.
6517 This is the list that is used for internal purposes.")
6519 (defconst org-link-escape-chars-browser
6520 '((?\ . "%20")) ; 32 for the SPC char
6521 "Association list of escapes for some characters problematic in links.
6522 This is the list that is used before handing over to the browser.")
6524 (defun org-link-escape (text &optional table)
6525 "Escape characters in TEXT that are problematic for links."
6526 (setq table (or table org-link-escape-chars))
6527 (when text
6528 (let ((re (mapconcat (lambda (x) (regexp-quote
6529 (char-to-string (car x))))
6530 table "\\|")))
6531 (while (string-match re text)
6532 (setq text
6533 (replace-match
6534 (cdr (assoc (string-to-char (match-string 0 text))
6535 table))
6536 t t text)))
6537 text)))
6539 (defun org-link-unescape (text &optional table)
6540 "Reverse the action of `org-link-escape'."
6541 (setq table (or table org-link-escape-chars))
6542 (when text
6543 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
6544 table "\\|")))
6545 (while (string-match re text)
6546 (setq text
6547 (replace-match
6548 (char-to-string (car (rassoc (match-string 0 text) table)))
6549 t t text)))
6550 text)))
6552 (defun org-xor (a b)
6553 "Exclusive or."
6554 (if a (not b) b))
6556 (defun org-get-header (header)
6557 "Find a header field in the current buffer."
6558 (save-excursion
6559 (goto-char (point-min))
6560 (let ((case-fold-search t) s)
6561 (cond
6562 ((eq header 'from)
6563 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
6564 (setq s (match-string 1)))
6565 (while (string-match "\"" s)
6566 (setq s (replace-match "" t t s)))
6567 (if (string-match "[<(].*" s)
6568 (setq s (replace-match "" t t s))))
6569 ((eq header 'message-id)
6570 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
6571 (setq s (match-string 1))))
6572 ((eq header 'subject)
6573 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
6574 (setq s (match-string 1)))))
6575 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
6576 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
6577 s)))
6580 (defun org-fixup-message-id-for-http (s)
6581 "Replace special characters in a message id, so it can be used in an http query."
6582 (while (string-match "<" s)
6583 (setq s (replace-match "%3C" t t s)))
6584 (while (string-match ">" s)
6585 (setq s (replace-match "%3E" t t s)))
6586 (while (string-match "@" s)
6587 (setq s (replace-match "%40" t t s)))
6590 ;;;###autoload
6591 (defun org-insert-link-global ()
6592 "Insert a link like Org-mode does.
6593 This command can be called in any mode to insert a link in Org-mode syntax."
6594 (interactive)
6595 (org-load-modules-maybe)
6596 (org-run-like-in-org-mode 'org-insert-link))
6598 (defun org-insert-link (&optional complete-file link-location)
6599 "Insert a link. At the prompt, enter the link.
6601 Completion can be used to insert any of the link protocol prefixes like
6602 http or ftp in use.
6604 The history can be used to select a link previously stored with
6605 `org-store-link'. When the empty string is entered (i.e. if you just
6606 press RET at the prompt), the link defaults to the most recently
6607 stored link. As SPC triggers completion in the minibuffer, you need to
6608 use M-SPC or C-q SPC to force the insertion of a space character.
6610 You will also be prompted for a description, and if one is given, it will
6611 be displayed in the buffer instead of the link.
6613 If there is already a link at point, this command will allow you to edit link
6614 and description parts.
6616 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
6617 be selected using completion. The path to the file will be relative to the
6618 current directory if the file is in the current directory or a subdirectory.
6619 Otherwise, the link will be the absolute path as completed in the minibuffer
6620 \(i.e. normally ~/path/to/file). You can configure this behavior using the
6621 option `org-link-file-path-type'.
6623 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
6624 the current directory or below.
6626 With three \\[universal-argument] prefixes, negate the meaning of
6627 `org-keep-stored-link-after-insertion'.
6629 If `org-make-link-description-function' is non-nil, this function will be
6630 called with the link target, and the result will be the default
6631 link description.
6633 If the LINK-LOCATION parameter is non-nil, this value will be
6634 used as the link location instead of reading one interactively."
6635 (interactive "P")
6636 (let* ((wcf (current-window-configuration))
6637 (region (if (org-region-active-p)
6638 (buffer-substring (region-beginning) (region-end))))
6639 (remove (and region (list (region-beginning) (region-end))))
6640 (desc region)
6641 tmphist ; byte-compile incorrectly complains about this
6642 (link link-location)
6643 entry file)
6644 (cond
6645 (link-location) ; specified by arg, just use it.
6646 ((org-in-regexp org-bracket-link-regexp 1)
6647 ;; We do have a link at point, and we are going to edit it.
6648 (setq remove (list (match-beginning 0) (match-end 0)))
6649 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
6650 (setq link (read-string "Link: "
6651 (org-link-unescape
6652 (org-match-string-no-properties 1)))))
6653 ((or (org-in-regexp org-angle-link-re)
6654 (org-in-regexp org-plain-link-re))
6655 ;; Convert to bracket link
6656 (setq remove (list (match-beginning 0) (match-end 0))
6657 link (read-string "Link: "
6658 (org-remove-angle-brackets (match-string 0)))))
6659 ((member complete-file '((4) (16)))
6660 ;; Completing read for file names.
6661 (setq file (read-file-name "File: "))
6662 (let ((pwd (file-name-as-directory (expand-file-name ".")))
6663 (pwd1 (file-name-as-directory (abbreviate-file-name
6664 (expand-file-name ".")))))
6665 (cond
6666 ((equal complete-file '(16))
6667 (setq link (org-make-link
6668 "file:"
6669 (abbreviate-file-name (expand-file-name file)))))
6670 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
6671 (setq link (org-make-link "file:" (match-string 1 file))))
6672 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
6673 (expand-file-name file))
6674 (setq link (org-make-link
6675 "file:" (match-string 1 (expand-file-name file)))))
6676 (t (setq link (org-make-link "file:" file))))))
6678 ;; Read link, with completion for stored links.
6679 (with-output-to-temp-buffer "*Org Links*"
6680 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
6681 (when org-stored-links
6682 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
6683 (princ (mapconcat
6684 (lambda (x)
6685 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
6686 (reverse org-stored-links) "\n"))))
6687 (let ((cw (selected-window)))
6688 (select-window (get-buffer-window "*Org Links*"))
6689 (setq truncate-lines t)
6690 (org-fit-window-to-buffer)
6691 (select-window cw))
6692 ;; Fake a link history, containing the stored links.
6693 (setq tmphist (append (mapcar 'car org-stored-links)
6694 org-insert-link-history))
6695 (unwind-protect
6696 (setq link
6697 (let ((org-completion-use-ido nil))
6698 (org-completing-read
6699 "Link: "
6700 (append
6701 (mapcar (lambda (x) (list (concat (car x) ":")))
6702 (append org-link-abbrev-alist-local org-link-abbrev-alist))
6703 (mapcar (lambda (x) (list (concat x ":")))
6704 org-link-types))
6705 nil nil nil
6706 'tmphist
6707 (or (car (car org-stored-links))))))
6708 (set-window-configuration wcf)
6709 (kill-buffer "*Org Links*"))
6710 (setq entry (assoc link org-stored-links))
6711 (or entry (push link org-insert-link-history))
6712 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
6713 (not org-keep-stored-link-after-insertion))
6714 (setq org-stored-links (delq (assoc link org-stored-links)
6715 org-stored-links)))
6716 (setq desc (or desc (nth 1 entry)))))
6718 (if (string-match org-plain-link-re link)
6719 ;; URL-like link, normalize the use of angular brackets.
6720 (setq link (org-make-link (org-remove-angle-brackets link))))
6722 ;; Check if we are linking to the current file with a search option
6723 ;; If yes, simplify the link by using only the search option.
6724 (when (and buffer-file-name
6725 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
6726 (let* ((path (match-string 1 link))
6727 (case-fold-search nil)
6728 (search (match-string 2 link)))
6729 (save-match-data
6730 (if (equal (file-truename buffer-file-name) (file-truename path))
6731 ;; We are linking to this same file, with a search option
6732 (setq link search)))))
6734 ;; Check if we can/should use a relative path. If yes, simplify the link
6735 (when (string-match "^file:\\(.*\\)" link)
6736 (let* ((path (match-string 1 link))
6737 (origpath path)
6738 (case-fold-search nil))
6739 (cond
6740 ((or (eq org-link-file-path-type 'absolute)
6741 (equal complete-file '(16)))
6742 (setq path (abbreviate-file-name (expand-file-name path))))
6743 ((eq org-link-file-path-type 'noabbrev)
6744 (setq path (expand-file-name path)))
6745 ((eq org-link-file-path-type 'relative)
6746 (setq path (file-relative-name path)))
6748 (save-match-data
6749 (if (string-match (concat "^" (regexp-quote
6750 (file-name-as-directory
6751 (expand-file-name "."))))
6752 (expand-file-name path))
6753 ;; We are linking a file with relative path name.
6754 (setq path (substring (expand-file-name path)
6755 (match-end 0)))
6756 (setq path (abbreviate-file-name (expand-file-name path)))))))
6757 (setq link (concat "file:" path))
6758 (if (equal desc origpath)
6759 (setq desc path))))
6761 (if org-make-link-description-function
6762 (setq desc (funcall org-make-link-description-function link desc)))
6764 (setq desc (read-string "Description: " desc))
6765 (unless (string-match "\\S-" desc) (setq desc nil))
6766 (if remove (apply 'delete-region remove))
6767 (insert (org-make-link-string link desc))))
6769 (defun org-completing-read (&rest args)
6770 "Completing-read with SPACE being a normal character."
6771 (let ((minibuffer-local-completion-map
6772 (copy-keymap minibuffer-local-completion-map)))
6773 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
6774 (apply 'org-ido-completing-read args)))
6776 (defun org-ido-completing-read (&rest args)
6777 "Completing-read using `ido-mode' speedups if available"
6778 (if (and org-completion-use-ido
6779 (fboundp 'ido-completing-read)
6780 (boundp 'ido-mode) ido-mode
6781 (listp (second args)))
6782 (apply 'ido-completing-read (concat (car args)) (cdr args))
6783 (apply 'completing-read args)))
6785 (defun org-extract-attributes (s)
6786 "Extract the attributes cookie from a string and set as text property."
6787 (let (a attr (start 0) key value)
6788 (save-match-data
6789 (when (string-match "{{\\([^}]+\\)}}$" s)
6790 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
6791 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
6792 (setq key (match-string 1 a) value (match-string 2 a)
6793 start (match-end 0)
6794 attr (plist-put attr (intern key) value))))
6795 (org-add-props s nil 'org-attr attr))
6798 (defun org-attributes-to-string (plist)
6799 "Format a property list into an HTML attribute list."
6800 (let ((s "") key value)
6801 (while plist
6802 (setq key (pop plist) value (pop plist))
6803 (and value
6804 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
6807 ;;; Opening/following a link
6809 (defvar org-link-search-failed nil)
6811 (defun org-next-link ()
6812 "Move forward to the next link.
6813 If the link is in hidden text, expose it."
6814 (interactive)
6815 (when (and org-link-search-failed (eq this-command last-command))
6816 (goto-char (point-min))
6817 (message "Link search wrapped back to beginning of buffer"))
6818 (setq org-link-search-failed nil)
6819 (let* ((pos (point))
6820 (ct (org-context))
6821 (a (assoc :link ct)))
6822 (if a (goto-char (nth 2 a)))
6823 (if (re-search-forward org-any-link-re nil t)
6824 (progn
6825 (goto-char (match-beginning 0))
6826 (if (org-invisible-p) (org-show-context)))
6827 (goto-char pos)
6828 (setq org-link-search-failed t)
6829 (error "No further link found"))))
6831 (defun org-previous-link ()
6832 "Move backward to the previous link.
6833 If the link is in hidden text, expose it."
6834 (interactive)
6835 (when (and org-link-search-failed (eq this-command last-command))
6836 (goto-char (point-max))
6837 (message "Link search wrapped back to end of buffer"))
6838 (setq org-link-search-failed nil)
6839 (let* ((pos (point))
6840 (ct (org-context))
6841 (a (assoc :link ct)))
6842 (if a (goto-char (nth 1 a)))
6843 (if (re-search-backward org-any-link-re nil t)
6844 (progn
6845 (goto-char (match-beginning 0))
6846 (if (org-invisible-p) (org-show-context)))
6847 (goto-char pos)
6848 (setq org-link-search-failed t)
6849 (error "No further link found"))))
6851 (defun org-translate-link (s)
6852 "Translate a link string if a translation function has been defined."
6853 (if (and org-link-translation-function
6854 (fboundp org-link-translation-function)
6855 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
6856 (progn
6857 (setq s (funcall org-link-translation-function
6858 (match-string 1) (match-string 2)))
6859 (concat (car s) ":" (cdr s)))
6862 (defun org-translate-link-from-planner (type path)
6863 "Translate a link from Emacs Planner syntax so that Org can follow it.
6864 This is still an experimental function, your mileage may vary."
6865 (cond
6866 ((member type '("http" "https" "news" "ftp"))
6867 ;; standard Internet links are the same.
6868 nil)
6869 ((and (equal type "irc") (string-match "^//" path))
6870 ;; Planner has two / at the beginning of an irc link, we have 1.
6871 ;; We should have zero, actually....
6872 (setq path (substring path 1)))
6873 ((and (equal type "lisp") (string-match "^/" path))
6874 ;; Planner has a slash, we do not.
6875 (setq type "elisp" path (substring path 1)))
6876 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
6877 ;; A typical message link. Planner has the id after the fina slash,
6878 ;; we separate it with a hash mark
6879 (setq path (concat (match-string 1 path) "#"
6880 (org-remove-angle-brackets (match-string 2 path)))))
6882 (cons type path))
6884 (defun org-find-file-at-mouse (ev)
6885 "Open file link or URL at mouse."
6886 (interactive "e")
6887 (mouse-set-point ev)
6888 (org-open-at-point 'in-emacs))
6890 (defun org-open-at-mouse (ev)
6891 "Open file link or URL at mouse."
6892 (interactive "e")
6893 (mouse-set-point ev)
6894 (if (eq major-mode 'org-agenda-mode)
6895 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
6896 (org-open-at-point))
6898 (defvar org-window-config-before-follow-link nil
6899 "The window configuration before following a link.
6900 This is saved in case the need arises to restore it.")
6902 (defvar org-open-link-marker (make-marker)
6903 "Marker pointing to the location where `org-open-at-point; was called.")
6905 ;;;###autoload
6906 (defun org-open-at-point-global ()
6907 "Follow a link like Org-mode does.
6908 This command can be called in any mode to follow a link that has
6909 Org-mode syntax."
6910 (interactive)
6911 (org-run-like-in-org-mode 'org-open-at-point))
6913 ;;;###autoload
6914 (defun org-open-link-from-string (s &optional arg)
6915 "Open a link in the string S, as if it was in Org-mode."
6916 (interactive "sLink: \nP")
6917 (with-temp-buffer
6918 (let ((org-inhibit-startup t))
6919 (org-mode)
6920 (insert s)
6921 (goto-char (point-min))
6922 (org-open-at-point arg))))
6924 (defun org-open-at-point (&optional in-emacs)
6925 "Open link at or after point.
6926 If there is no link at point, this function will search forward up to
6927 the end of the current subtree.
6928 Normally, files will be opened by an appropriate application. If the
6929 optional argument IN-EMACS is non-nil, Emacs will visit the file.
6930 With a double prefix argument, try to open outside of Emacs, in the
6931 application the system uses for this file type."
6932 (interactive "P")
6933 (org-load-modules-maybe)
6934 (move-marker org-open-link-marker (point))
6935 (setq org-window-config-before-follow-link (current-window-configuration))
6936 (org-remove-occur-highlights nil nil t)
6937 (cond
6938 ((org-at-timestamp-p t) (org-follow-timestamp-link))
6939 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
6940 (org-footnote-action))
6942 (let (type path link line search (pos (point)))
6943 (catch 'match
6944 (save-excursion
6945 (skip-chars-forward "^]\n\r")
6946 (when (org-in-regexp org-bracket-link-regexp)
6947 (setq link (org-extract-attributes
6948 (org-link-unescape (org-match-string-no-properties 1))))
6949 (while (string-match " *\n *" link)
6950 (setq link (replace-match " " t t link)))
6951 (setq link (org-link-expand-abbrev link))
6952 (cond
6953 ((or (file-name-absolute-p link)
6954 (string-match "^\\.\\.?/" link))
6955 (setq type "file" path link))
6956 ((string-match org-link-re-with-space3 link)
6957 (setq type (match-string 1 link) path (match-string 2 link)))
6958 (t (setq type "thisfile" path link)))
6959 (throw 'match t)))
6961 (when (get-text-property (point) 'org-linked-text)
6962 (setq type "thisfile"
6963 pos (if (get-text-property (1+ (point)) 'org-linked-text)
6964 (1+ (point)) (point))
6965 path (buffer-substring
6966 (previous-single-property-change pos 'org-linked-text)
6967 (next-single-property-change pos 'org-linked-text)))
6968 (throw 'match t))
6970 (save-excursion
6971 (when (or (org-in-regexp org-angle-link-re)
6972 (org-in-regexp org-plain-link-re))
6973 (setq type (match-string 1) path (match-string 2))
6974 (throw 'match t)))
6975 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
6976 (setq type "tree-match"
6977 path (match-string 1))
6978 (throw 'match t))
6979 (save-excursion
6980 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
6981 (setq type "tags"
6982 path (match-string 1))
6983 (while (string-match ":" path)
6984 (setq path (replace-match "+" t t path)))
6985 (throw 'match t))))
6986 (unless path
6987 (error "No link found"))
6988 ;; Remove any trailing spaces in path
6989 (if (string-match " +\\'" path)
6990 (setq path (replace-match "" t t path)))
6991 (if (and org-link-translation-function
6992 (fboundp org-link-translation-function))
6993 ;; Check if we need to translate the link
6994 (let ((tmp (funcall org-link-translation-function type path)))
6995 (setq type (car tmp) path (cdr tmp))))
6997 (cond
6999 ((assoc type org-link-protocols)
7000 (funcall (nth 1 (assoc type org-link-protocols)) path))
7002 ((equal type "mailto")
7003 (let ((cmd (car org-link-mailto-program))
7004 (args (cdr org-link-mailto-program)) args1
7005 (address path) (subject "") a)
7006 (if (string-match "\\(.*\\)::\\(.*\\)" path)
7007 (setq address (match-string 1 path)
7008 subject (org-link-escape (match-string 2 path))))
7009 (while args
7010 (cond
7011 ((not (stringp (car args))) (push (pop args) args1))
7012 (t (setq a (pop args))
7013 (if (string-match "%a" a)
7014 (setq a (replace-match address t t a)))
7015 (if (string-match "%s" a)
7016 (setq a (replace-match subject t t a)))
7017 (push a args1))))
7018 (apply cmd (nreverse args1))))
7020 ((member type '("http" "https" "ftp" "news"))
7021 (browse-url (concat type ":" (org-link-escape
7022 path org-link-escape-chars-browser))))
7024 ((member type '("message"))
7025 (browse-url (concat type ":" path)))
7027 ((string= type "tags")
7028 (org-tags-view in-emacs path))
7029 ((string= type "thisfile")
7030 (if in-emacs
7031 (switch-to-buffer-other-window
7032 (org-get-buffer-for-internal-link (current-buffer)))
7033 (org-mark-ring-push))
7034 (let ((cmd `(org-link-search
7035 ,path
7036 ,(cond ((equal in-emacs '(4)) 'occur)
7037 ((equal in-emacs '(16)) 'org-occur)
7038 (t nil))
7039 ,pos)))
7040 (condition-case nil (eval cmd)
7041 (error (progn (widen) (eval cmd))))))
7043 ((string= type "tree-match")
7044 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
7046 ((string= type "file")
7047 (if (string-match "::\\([0-9]+\\)\\'" path)
7048 (setq line (string-to-number (match-string 1 path))
7049 path (substring path 0 (match-beginning 0)))
7050 (if (string-match "::\\(.+\\)\\'" path)
7051 (setq search (match-string 1 path)
7052 path (substring path 0 (match-beginning 0)))))
7053 (if (string-match "[*?{]" (file-name-nondirectory path))
7054 (dired path)
7055 (org-open-file path in-emacs line search)))
7057 ((string= type "news")
7058 (require 'org-gnus)
7059 (org-gnus-follow-link path))
7061 ((string= type "shell")
7062 (let ((cmd path))
7063 (if (or (not org-confirm-shell-link-function)
7064 (funcall org-confirm-shell-link-function
7065 (format "Execute \"%s\" in shell? "
7066 (org-add-props cmd nil
7067 'face 'org-warning))))
7068 (progn
7069 (message "Executing %s" cmd)
7070 (shell-command cmd))
7071 (error "Abort"))))
7073 ((string= type "elisp")
7074 (let ((cmd path))
7075 (if (or (not org-confirm-elisp-link-function)
7076 (funcall org-confirm-elisp-link-function
7077 (format "Execute \"%s\" as elisp? "
7078 (org-add-props cmd nil
7079 'face 'org-warning))))
7080 (message "%s => %s" cmd
7081 (if (equal (string-to-char cmd) ?\()
7082 (eval (read cmd))
7083 (call-interactively (read cmd))))
7084 (error "Abort"))))
7087 (browse-url-at-point))))))
7088 (move-marker org-open-link-marker nil)
7089 (run-hook-with-args 'org-follow-link-hook))
7091 ;;;; Time estimates
7093 (defun org-get-effort (&optional pom)
7094 "Get the effort estimate for the current entry."
7095 (org-entry-get pom org-effort-property))
7097 ;;; File search
7099 (defvar org-create-file-search-functions nil
7100 "List of functions to construct the right search string for a file link.
7101 These functions are called in turn with point at the location to
7102 which the link should point.
7104 A function in the hook should first test if it would like to
7105 handle this file type, for example by checking the major-mode or
7106 the file extension. If it decides not to handle this file, it
7107 should just return nil to give other functions a chance. If it
7108 does handle the file, it must return the search string to be used
7109 when following the link. The search string will be part of the
7110 file link, given after a double colon, and `org-open-at-point'
7111 will automatically search for it. If special measures must be
7112 taken to make the search successful, another function should be
7113 added to the companion hook `org-execute-file-search-functions',
7114 which see.
7116 A function in this hook may also use `setq' to set the variable
7117 `description' to provide a suggestion for the descriptive text to
7118 be used for this link when it gets inserted into an Org-mode
7119 buffer with \\[org-insert-link].")
7121 (defvar org-execute-file-search-functions nil
7122 "List of functions to execute a file search triggered by a link.
7124 Functions added to this hook must accept a single argument, the
7125 search string that was part of the file link, the part after the
7126 double colon. The function must first check if it would like to
7127 handle this search, for example by checking the major-mode or the
7128 file extension. If it decides not to handle this search, it
7129 should just return nil to give other functions a chance. If it
7130 does handle the search, it must return a non-nil value to keep
7131 other functions from trying.
7133 Each function can access the current prefix argument through the
7134 variable `current-prefix-argument'. Note that a single prefix is
7135 used to force opening a link in Emacs, so it may be good to only
7136 use a numeric or double prefix to guide the search function.
7138 In case this is needed, a function in this hook can also restore
7139 the window configuration before `org-open-at-point' was called using:
7141 (set-window-configuration org-window-config-before-follow-link)")
7143 (defun org-link-search (s &optional type avoid-pos)
7144 "Search for a link search option.
7145 If S is surrounded by forward slashes, it is interpreted as a
7146 regular expression. In org-mode files, this will create an `org-occur'
7147 sparse tree. In ordinary files, `occur' will be used to list matches.
7148 If the current buffer is in `dired-mode', grep will be used to search
7149 in all files. If AVOID-POS is given, ignore matches near that position."
7150 (let ((case-fold-search t)
7151 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
7152 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
7153 (append '(("") (" ") ("\t") ("\n"))
7154 org-emphasis-alist)
7155 "\\|") "\\)"))
7156 (pos (point))
7157 (pre nil) (post nil)
7158 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
7159 (cond
7160 ;; First check if there are any special
7161 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
7162 ;; Now try the builtin stuff
7163 ((save-excursion
7164 (goto-char (point-min))
7165 (and
7166 (re-search-forward
7167 (concat "<<" (regexp-quote s0) ">>") nil t)
7168 (setq type 'dedicated
7169 pos (match-beginning 0))))
7170 ;; There is an exact target for this
7171 (goto-char pos))
7172 ((and (string-match "^((.*))$" s0)
7173 (save-excursion
7174 (goto-char (point-min))
7175 (and
7176 (re-search-forward (concat "[^[]" (regexp-quote s0)) nil t)
7177 (setq type 'dedicated
7178 pos (1+ (match-beginning 0))))))
7179 ;; There is a coderef target for this
7180 (goto-char pos))
7181 ((string-match "^/\\(.*\\)/$" s)
7182 ;; A regular expression
7183 (cond
7184 ((org-mode-p)
7185 (org-occur (match-string 1 s)))
7186 ;;((eq major-mode 'dired-mode)
7187 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
7188 (t (org-do-occur (match-string 1 s)))))
7190 ;; A normal search strings
7191 (when (equal (string-to-char s) ?*)
7192 ;; Anchor on headlines, post may include tags.
7193 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
7194 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
7195 s (substring s 1)))
7196 (remove-text-properties
7197 0 (length s)
7198 '(face nil mouse-face nil keymap nil fontified nil) s)
7199 ;; Make a series of regular expressions to find a match
7200 (setq words (org-split-string s "[ \n\r\t]+")
7202 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
7203 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
7204 "\\)" markers)
7205 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
7206 re2a (concat "[ \t\r\n]" re2a_)
7207 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
7208 re4 (concat "[^a-zA-Z_]" re4_)
7210 re1 (concat pre re2 post)
7211 re3 (concat pre (if pre re4_ re4) post)
7212 re5 (concat pre ".*" re4)
7213 re2 (concat pre re2)
7214 re2a (concat pre (if pre re2a_ re2a))
7215 re4 (concat pre (if pre re4_ re4))
7216 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7217 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7218 re5 "\\)"
7220 (cond
7221 ((eq type 'org-occur) (org-occur reall))
7222 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7223 (t (goto-char (point-min))
7224 (setq type 'fuzzy)
7225 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
7226 (org-search-not-self 1 re1 nil t)
7227 (org-search-not-self 1 re2 nil t)
7228 (org-search-not-self 1 re2a nil t)
7229 (org-search-not-self 1 re3 nil t)
7230 (org-search-not-self 1 re4 nil t)
7231 (org-search-not-self 1 re5 nil t)
7233 (goto-char (match-beginning 1))
7234 (goto-char pos)
7235 (error "No match")))))
7237 ;; Normal string-search
7238 (goto-char (point-min))
7239 (if (search-forward s nil t)
7240 (goto-char (match-beginning 0))
7241 (error "No match"))))
7242 (and (org-mode-p) (org-show-context 'link-search))
7243 type))
7245 (defun org-search-not-self (group &rest args)
7246 "Execute `re-search-forward', but only accept matches that do not
7247 enclose the position of `org-open-link-marker'."
7248 (let ((m org-open-link-marker))
7249 (catch 'exit
7250 (while (apply 're-search-forward args)
7251 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
7252 (goto-char (match-end group))
7253 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
7254 (> (match-beginning 0) (marker-position m))
7255 (< (match-end 0) (marker-position m)))
7256 (save-match-data
7257 (or (not (org-in-regexp
7258 org-bracket-link-analytic-regexp 1))
7259 (not (match-end 4)) ; no description
7260 (and (<= (match-beginning 4) (point))
7261 (>= (match-end 4) (point))))))
7262 (throw 'exit (point))))))))
7264 (defun org-get-buffer-for-internal-link (buffer)
7265 "Return a buffer to be used for displaying the link target of internal links."
7266 (cond
7267 ((not org-display-internal-link-with-indirect-buffer)
7268 buffer)
7269 ((string-match "(Clone)$" (buffer-name buffer))
7270 (message "Buffer is already a clone, not making another one")
7271 ;; we also do not modify visibility in this case
7272 buffer)
7273 (t ; make a new indirect buffer for displaying the link
7274 (let* ((bn (buffer-name buffer))
7275 (ibn (concat bn "(Clone)"))
7276 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
7277 (with-current-buffer ib (org-overview))
7278 ib))))
7280 (defun org-do-occur (regexp &optional cleanup)
7281 "Call the Emacs command `occur'.
7282 If CLEANUP is non-nil, remove the printout of the regular expression
7283 in the *Occur* buffer. This is useful if the regex is long and not useful
7284 to read."
7285 (occur regexp)
7286 (when cleanup
7287 (let ((cwin (selected-window)) win beg end)
7288 (when (setq win (get-buffer-window "*Occur*"))
7289 (select-window win))
7290 (goto-char (point-min))
7291 (when (re-search-forward "match[a-z]+" nil t)
7292 (setq beg (match-end 0))
7293 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7294 (setq end (1- (match-beginning 0)))))
7295 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
7296 (goto-char (point-min))
7297 (select-window cwin))))
7299 ;;; The mark ring for links jumps
7301 (defvar org-mark-ring nil
7302 "Mark ring for positions before jumps in Org-mode.")
7303 (defvar org-mark-ring-last-goto nil
7304 "Last position in the mark ring used to go back.")
7305 ;; Fill and close the ring
7306 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7307 (loop for i from 1 to org-mark-ring-length do
7308 (push (make-marker) org-mark-ring))
7309 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7310 org-mark-ring)
7312 (defun org-mark-ring-push (&optional pos buffer)
7313 "Put the current position or POS into the mark ring and rotate it."
7314 (interactive)
7315 (setq pos (or pos (point)))
7316 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7317 (move-marker (car org-mark-ring)
7318 (or pos (point))
7319 (or buffer (current-buffer)))
7320 (message "%s"
7321 (substitute-command-keys
7322 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7324 (defun org-mark-ring-goto (&optional n)
7325 "Jump to the previous position in the mark ring.
7326 With prefix arg N, jump back that many stored positions. When
7327 called several times in succession, walk through the entire ring.
7328 Org-mode commands jumping to a different position in the current file,
7329 or to another Org-mode file, automatically push the old position
7330 onto the ring."
7331 (interactive "p")
7332 (let (p m)
7333 (if (eq last-command this-command)
7334 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7335 (setq p org-mark-ring))
7336 (setq org-mark-ring-last-goto p)
7337 (setq m (car p))
7338 (switch-to-buffer (marker-buffer m))
7339 (goto-char m)
7340 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
7342 (defun org-remove-angle-brackets (s)
7343 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7344 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7346 (defun org-add-angle-brackets (s)
7347 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7348 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7350 (defun org-remove-double-quotes (s)
7351 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
7352 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
7355 ;;; Following specific links
7357 (defun org-follow-timestamp-link ()
7358 (cond
7359 ((org-at-date-range-p t)
7360 (let ((org-agenda-start-on-weekday)
7361 (t1 (match-string 1))
7362 (t2 (match-string 2)))
7363 (setq t1 (time-to-days (org-time-string-to-time t1))
7364 t2 (time-to-days (org-time-string-to-time t2)))
7365 (org-agenda-list nil t1 (1+ (- t2 t1)))))
7366 ((org-at-timestamp-p t)
7367 (org-agenda-list nil (time-to-days (org-time-string-to-time
7368 (substring (match-string 1) 0 10)))
7370 (t (error "This should not happen"))))
7373 ;;; Following file links
7374 (defvar org-wait nil)
7375 (defun org-open-file (path &optional in-emacs line search)
7376 "Open the file at PATH.
7377 First, this expands any special file name abbreviations. Then the
7378 configuration variable `org-file-apps' is checked if it contains an
7379 entry for this file type, and if yes, the corresponding command is launched.
7381 If no application is found, Emacs simply visits the file.
7383 With optional prefix argument IN-EMACS, Emacs will visit the file.
7384 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
7385 and o use an external application to visit the file.
7387 Optional LINE specifies a line to go to, optional SEARCH a string to
7388 search for. If LINE or SEARCH is given, the file will always be
7389 opened in Emacs.
7390 If the file does not exist, an error is thrown."
7391 (setq in-emacs (or in-emacs line search))
7392 (let* ((file (if (equal path "")
7393 buffer-file-name
7394 (substitute-in-file-name (expand-file-name path))))
7395 (apps (append org-file-apps (org-default-apps)))
7396 (remp (and (assq 'remote apps) (org-file-remote-p file)))
7397 (dirp (if remp nil (file-directory-p file)))
7398 (file (if (and dirp org-open-directory-means-index-dot-org)
7399 (concat (file-name-as-directory file) "index.org")
7400 file))
7401 (a-m-a-p (assq 'auto-mode apps))
7402 (dfile (downcase file))
7403 (old-buffer (current-buffer))
7404 (old-pos (point))
7405 (old-mode major-mode)
7406 ext cmd)
7407 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7408 (setq ext (match-string 1 dfile))
7409 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7410 (setq ext (match-string 1 dfile))))
7411 (cond
7412 ((equal in-emacs '(16))
7413 (setq cmd (cdr (assoc 'system apps))))
7414 (in-emacs (setq cmd 'emacs))
7416 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
7417 (and dirp (cdr (assoc 'directory apps)))
7418 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
7419 'string-match)
7420 (cdr (assoc ext apps))
7421 (cdr (assoc t apps))))))
7422 (when (eq cmd 'system)
7423 (setq cmd (cdr (assoc 'system apps))))
7424 (when (eq cmd 'default)
7425 (setq cmd (cdr (assoc t apps))))
7426 (when (eq cmd 'mailcap)
7427 (require 'mailcap)
7428 (mailcap-parse-mailcaps)
7429 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7430 (command (mailcap-mime-info mime-type)))
7431 (if (stringp command)
7432 (setq cmd command)
7433 (setq cmd 'emacs))))
7434 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
7435 (not (file-exists-p file))
7436 (not org-open-non-existing-files))
7437 (error "No such file: %s" file))
7438 (cond
7439 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7440 ;; Remove quotes around the file name - we'll use shell-quote-argument.
7441 (while (string-match "['\"]%s['\"]" cmd)
7442 (setq cmd (replace-match "%s" t t cmd)))
7443 (while (string-match "%s" cmd)
7444 (setq cmd (replace-match
7445 (save-match-data
7446 (shell-quote-argument
7447 (convert-standard-filename file)))
7448 t t cmd)))
7449 (save-window-excursion
7450 (start-process-shell-command cmd nil cmd)
7451 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
7453 ((or (stringp cmd)
7454 (eq cmd 'emacs))
7455 (funcall (cdr (assq 'file org-link-frame-setup)) file)
7456 (widen)
7457 (if line (goto-line line)
7458 (if search (org-link-search search))))
7459 ((consp cmd)
7460 (let ((file (convert-standard-filename file)))
7461 (eval cmd)))
7462 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7463 (and (org-mode-p) (eq old-mode 'org-mode)
7464 (or (not (equal old-buffer (current-buffer)))
7465 (not (equal old-pos (point))))
7466 (org-mark-ring-push old-pos old-buffer))))
7468 (defun org-default-apps ()
7469 "Return the default applications for this operating system."
7470 (cond
7471 ((eq system-type 'darwin)
7472 org-file-apps-defaults-macosx)
7473 ((eq system-type 'windows-nt)
7474 org-file-apps-defaults-windowsnt)
7475 (t org-file-apps-defaults-gnu)))
7477 (defun org-apps-regexp-alist (list &optional add-auto-mode)
7478 "Convert extensions to regular expressions in the cars of LIST.
7479 Also, weed out any non-string entries, because the return value is used
7480 only for regexp matching.
7481 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
7482 point to the symbol `emacs', indicating that the file should
7483 be opened in Emacs."
7484 (append
7485 (delq nil
7486 (mapcar (lambda (x)
7487 (if (not (stringp (car x)))
7489 (if (string-match "\\W" (car x))
7491 (cons (concat "\\." (car x) "\\'") (cdr x)))))
7492 list))
7493 (if add-auto-mode
7494 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
7496 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
7497 (defun org-file-remote-p (file)
7498 "Test whether FILE specifies a location on a remote system.
7499 Return non-nil if the location is indeed remote.
7501 For example, the filename \"/user@host:/foo\" specifies a location
7502 on the system \"/user@host:\"."
7503 (cond ((fboundp 'file-remote-p)
7504 (file-remote-p file))
7505 ((fboundp 'tramp-handle-file-remote-p)
7506 (tramp-handle-file-remote-p file))
7507 ((and (boundp 'ange-ftp-name-format)
7508 (string-match (car ange-ftp-name-format) file))
7510 (t nil)))
7513 ;;;; Refiling
7515 (defun org-get-org-file ()
7516 "Read a filename, with default directory `org-directory'."
7517 (let ((default (or org-default-notes-file remember-data-file)))
7518 (read-file-name (format "File name [%s]: " default)
7519 (file-name-as-directory org-directory)
7520 default)))
7522 (defun org-notes-order-reversed-p ()
7523 "Check if the current file should receive notes in reversed order."
7524 (cond
7525 ((not org-reverse-note-order) nil)
7526 ((eq t org-reverse-note-order) t)
7527 ((not (listp org-reverse-note-order)) nil)
7528 (t (catch 'exit
7529 (let ((all org-reverse-note-order)
7530 entry)
7531 (while (setq entry (pop all))
7532 (if (string-match (car entry) buffer-file-name)
7533 (throw 'exit (cdr entry))))
7534 nil)))))
7536 (defvar org-refile-target-table nil
7537 "The list of refile targets, created by `org-refile'.")
7539 (defvar org-agenda-new-buffers nil
7540 "Buffers created to visit agenda files.")
7542 (defun org-get-refile-targets (&optional default-buffer)
7543 "Produce a table with refile targets."
7544 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
7545 targets txt re files f desc descre fast-path-p level)
7546 (message "Getting targets...")
7547 (with-current-buffer (or default-buffer (current-buffer))
7548 (while (setq entry (pop entries))
7549 (setq files (car entry) desc (cdr entry))
7550 (setq fast-path-p nil)
7551 (cond
7552 ((null files) (setq files (list (current-buffer))))
7553 ((eq files 'org-agenda-files)
7554 (setq files (org-agenda-files 'unrestricted)))
7555 ((and (symbolp files) (fboundp files))
7556 (setq files (funcall files)))
7557 ((and (symbolp files) (boundp files))
7558 (setq files (symbol-value files))))
7559 (if (stringp files) (setq files (list files)))
7560 (cond
7561 ((eq (car desc) :tag)
7562 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
7563 ((eq (car desc) :todo)
7564 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
7565 ((eq (car desc) :regexp)
7566 (setq descre (cdr desc)))
7567 ((eq (car desc) :level)
7568 (setq descre (concat "^\\*\\{" (number-to-string
7569 (if org-odd-levels-only
7570 (1- (* 2 (cdr desc)))
7571 (cdr desc)))
7572 "\\}[ \t]")))
7573 ((eq (car desc) :maxlevel)
7574 (setq fast-path-p t)
7575 (setq descre (concat "^\\*\\{1," (number-to-string
7576 (if org-odd-levels-only
7577 (1- (* 2 (cdr desc)))
7578 (cdr desc)))
7579 "\\}[ \t]")))
7580 (t (error "Bad refiling target description %s" desc)))
7581 (while (setq f (pop files))
7582 (save-excursion
7583 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
7584 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
7585 (setq f (expand-file-name f))
7586 (save-excursion
7587 (save-restriction
7588 (widen)
7589 (goto-char (point-min))
7590 (while (re-search-forward descre nil t)
7591 (goto-char (point-at-bol))
7592 (when (looking-at org-complex-heading-regexp)
7593 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
7594 txt (org-link-display-format (match-string 4))
7595 re (concat "^" (regexp-quote
7596 (buffer-substring (match-beginning 1)
7597 (match-end 4)))))
7598 (if (match-end 5) (setq re (concat re "[ \t]+"
7599 (regexp-quote
7600 (match-string 5)))))
7601 (setq re (concat re "[ \t]*$"))
7602 (when org-refile-use-outline-path
7603 (setq txt (mapconcat 'org-protect-slash
7604 (append
7605 (if (eq org-refile-use-outline-path 'file)
7606 (list (file-name-nondirectory
7607 (buffer-file-name (buffer-base-buffer))))
7608 (if (eq org-refile-use-outline-path 'full-file-path)
7609 (list (buffer-file-name (buffer-base-buffer)))))
7610 (org-get-outline-path fast-path-p level txt)
7611 (list txt))
7612 "/")))
7613 (push (list txt f re (point)) targets))
7614 (goto-char (point-at-eol))))))))
7615 (message "Getting targets...done")
7616 (nreverse targets))))
7618 (defun org-protect-slash (s)
7619 (while (string-match "/" s)
7620 (setq s (replace-match "\\" t t s)))
7623 (defvar org-olpa (make-vector 20 nil))
7625 (defun org-get-outline-path (&optional fastp level heading)
7626 "Return the outline path to the current entry, as a list."
7627 (if fastp
7628 (progn
7629 (if (> level 19)
7630 (error "Outline path failure, more than 19 levels."))
7631 (loop for i from level upto 19 do
7632 (aset org-olpa i nil))
7633 (prog1
7634 (delq nil (append org-olpa nil))
7635 (aset org-olpa level heading)))
7636 (let (rtn)
7637 (save-excursion
7638 (while (org-up-heading-safe)
7639 (when (looking-at org-complex-heading-regexp)
7640 (push (org-match-string-no-properties 4) rtn)))
7641 rtn))))
7643 (defvar org-refile-history nil
7644 "History for refiling operations.")
7646 (defun org-refile (&optional goto default-buffer)
7647 "Move the entry at point to another heading.
7648 The list of target headings is compiled using the information in
7649 `org-refile-targets', which see. This list is created before each use
7650 and will therefore always be up-to-date.
7652 At the target location, the entry is filed as a subitem of the target heading.
7653 Depending on `org-reverse-note-order', the new subitem will either be the
7654 first or the last subitem.
7656 If there is an active region, all entries in that region will be moved.
7657 However, the region must fulfil the requirement that the first heading
7658 is the first one sets the top-level of the moved text - at most siblings
7659 below it are allowed.
7661 With prefix arg GOTO, the command will only visit the target location,
7662 not actually move anything.
7663 With a double prefix `C-u C-u', go to the location where the last refiling
7664 operation has put the subtree."
7665 (interactive "P")
7666 (let* ((cbuf (current-buffer))
7667 (regionp (org-region-active-p))
7668 (region-start (and regionp (region-beginning)))
7669 (region-end (and regionp (region-end)))
7670 (region-length (and regionp (- region-end region-start)))
7671 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7672 pos it nbuf file re level reversed)
7673 (when regionp (goto-char region-start)
7674 (unless (org-kill-is-subtree-p
7675 (buffer-substring region-start region-end))
7676 (error "The region is not a (sequence of) subtree(s)")))
7677 (if (equal goto '(16))
7678 (org-refile-goto-last-stored)
7679 (when (setq it (org-refile-get-location
7680 (if goto "Goto: " "Refile to: ") default-buffer))
7681 (setq file (nth 1 it)
7682 re (nth 2 it)
7683 pos (nth 3 it))
7684 (if (and (equal (buffer-file-name) file)
7685 (if regionp
7686 (and (>= pos region-start)
7687 (<= pos region-end))
7688 (and (>= pos (point))
7689 (< pos (save-excursion
7690 (org-end-of-subtree t t))))))
7691 (error "Cannot refile to position inside the tree or region"))
7693 (setq nbuf (or (find-buffer-visiting file)
7694 (find-file-noselect file)))
7695 (if goto
7696 (progn
7697 (switch-to-buffer nbuf)
7698 (goto-char pos)
7699 (org-show-context 'org-goto))
7700 (if regionp
7701 (progn
7702 (kill-new (buffer-substring region-start region-end))
7703 (org-save-markers-in-region region-start region-end))
7704 (org-copy-subtree 1 nil t))
7705 (save-excursion
7706 (set-buffer (setq nbuf (or (find-buffer-visiting file)
7707 (find-file-noselect file))))
7708 (setq reversed (org-notes-order-reversed-p))
7709 (save-excursion
7710 (save-restriction
7711 (widen)
7712 (goto-char pos)
7713 (looking-at outline-regexp)
7714 (setq level (org-get-valid-level (funcall outline-level) 1))
7715 (goto-char
7716 (if reversed
7717 (or (outline-next-heading) (point-max))
7718 (or (save-excursion (outline-get-next-sibling))
7719 (org-end-of-subtree t t)
7720 (point-max))))
7721 (if (not (bolp)) (newline))
7722 (bookmark-set "org-refile-last-stored")
7723 (org-paste-subtree level))))
7724 (if regionp
7725 (delete-region (point) (+ (point) region-length))
7726 (org-cut-subtree))
7727 (setq org-markers-to-move nil)
7728 (message "Refiled to \"%s\"" (car it)))))))
7730 (defun org-refile-goto-last-stored ()
7731 "Go to the location where the last refile was stored."
7732 (interactive)
7733 (bookmark-jump "org-refile-last-stored")
7734 (message "This is the location of the last refile"))
7736 (defun org-refile-get-location (&optional prompt default-buffer)
7737 "Prompt the user for a refile location, using PROMPT."
7738 (let ((org-refile-targets org-refile-targets)
7739 (org-refile-use-outline-path org-refile-use-outline-path))
7740 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
7741 (unless org-refile-target-table
7742 (error "No refile targets"))
7743 (let* ((cbuf (current-buffer))
7744 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
7745 (cfunc (if (and org-refile-use-outline-path
7746 org-outline-path-complete-in-steps)
7747 'org-olpath-completing-read
7748 'org-ido-completing-read))
7749 (extra (if org-refile-use-outline-path "/" ""))
7750 (filename (and cfn (expand-file-name cfn)))
7751 (tbl (mapcar
7752 (lambda (x)
7753 (if (not (equal filename (nth 1 x)))
7754 (cons (concat (car x) extra " ("
7755 (file-name-nondirectory (nth 1 x)) ")")
7756 (cdr x))
7757 (cons (concat (car x) extra) (cdr x))))
7758 org-refile-target-table))
7759 (completion-ignore-case t))
7760 (assoc (funcall cfunc prompt tbl nil t nil 'org-refile-history)
7761 tbl)))
7763 (defun org-olpath-completing-read (prompt collection &rest args)
7764 "Read an outline path like a file name."
7765 (let ((thetable collection))
7766 (apply
7767 'org-ido-completing-read prompt
7768 (lambda (string predicate &optional flag)
7769 (let (rtn r s f (l (length string)))
7770 (cond
7771 ((eq flag nil)
7772 ;; try completion
7773 (try-completion string thetable))
7774 ((eq flag t)
7775 ;; all-completions
7776 (setq rtn (all-completions string thetable predicate))
7777 (mapcar
7778 (lambda (x)
7779 (setq r (substring x l))
7780 (if (string-match " ([^)]*)$" x)
7781 (setq f (match-string 0 x))
7782 (setq f ""))
7783 (if (string-match "/" r)
7784 (concat string (substring r 0 (match-end 0)) f)
7786 rtn))
7787 ((eq flag 'lambda)
7788 ;; exact match?
7789 (assoc string thetable)))
7791 args)))
7793 ;;;; Dynamic blocks
7795 (defun org-find-dblock (name)
7796 "Find the first dynamic block with name NAME in the buffer.
7797 If not found, stay at current position and return nil."
7798 (let (pos)
7799 (save-excursion
7800 (goto-char (point-min))
7801 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
7802 nil t)
7803 (match-beginning 0))))
7804 (if pos (goto-char pos))
7805 pos))
7807 (defconst org-dblock-start-re
7808 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
7809 "Matches the startline of a dynamic block, with parameters.")
7811 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
7812 "Matches the end of a dynamic block.")
7814 (defun org-create-dblock (plist)
7815 "Create a dynamic block section, with parameters taken from PLIST.
7816 PLIST must contain a :name entry which is used as name of the block."
7817 (unless (bolp) (newline))
7818 (let ((name (plist-get plist :name)))
7819 (insert "#+BEGIN: " name)
7820 (while plist
7821 (if (eq (car plist) :name)
7822 (setq plist (cddr plist))
7823 (insert " " (prin1-to-string (pop plist)))))
7824 (insert "\n\n#+END:\n")
7825 (beginning-of-line -2)))
7827 (defun org-prepare-dblock ()
7828 "Prepare dynamic block for refresh.
7829 This empties the block, puts the cursor at the insert position and returns
7830 the property list including an extra property :name with the block name."
7831 (unless (looking-at org-dblock-start-re)
7832 (error "Not at a dynamic block"))
7833 (let* ((begdel (1+ (match-end 0)))
7834 (name (org-no-properties (match-string 1)))
7835 (params (append (list :name name)
7836 (read (concat "(" (match-string 3) ")")))))
7837 (unless (re-search-forward org-dblock-end-re nil t)
7838 (error "Dynamic block not terminated"))
7839 (setq params
7840 (append params
7841 (list :content (buffer-substring
7842 begdel (match-beginning 0)))))
7843 (delete-region begdel (match-beginning 0))
7844 (goto-char begdel)
7845 (open-line 1)
7846 params))
7848 (defun org-map-dblocks (&optional command)
7849 "Apply COMMAND to all dynamic blocks in the current buffer.
7850 If COMMAND is not given, use `org-update-dblock'."
7851 (let ((cmd (or command 'org-update-dblock))
7852 pos)
7853 (save-excursion
7854 (goto-char (point-min))
7855 (while (re-search-forward org-dblock-start-re nil t)
7856 (goto-char (setq pos (match-beginning 0)))
7857 (condition-case nil
7858 (funcall cmd)
7859 (error (message "Error during update of dynamic block")))
7860 (goto-char pos)
7861 (unless (re-search-forward org-dblock-end-re nil t)
7862 (error "Dynamic block not terminated"))))))
7864 (defun org-dblock-update (&optional arg)
7865 "User command for updating dynamic blocks.
7866 Update the dynamic block at point. With prefix ARG, update all dynamic
7867 blocks in the buffer."
7868 (interactive "P")
7869 (if arg
7870 (org-update-all-dblocks)
7871 (or (looking-at org-dblock-start-re)
7872 (org-beginning-of-dblock))
7873 (org-update-dblock)))
7875 (defun org-update-dblock ()
7876 "Update the dynamic block at point
7877 This means to empty the block, parse for parameters and then call
7878 the correct writing function."
7879 (save-window-excursion
7880 (let* ((pos (point))
7881 (line (org-current-line))
7882 (params (org-prepare-dblock))
7883 (name (plist-get params :name))
7884 (cmd (intern (concat "org-dblock-write:" name))))
7885 (message "Updating dynamic block `%s' at line %d..." name line)
7886 (funcall cmd params)
7887 (message "Updating dynamic block `%s' at line %d...done" name line)
7888 (goto-char pos))))
7890 (defun org-beginning-of-dblock ()
7891 "Find the beginning of the dynamic block at point.
7892 Error if there is no such block at point."
7893 (let ((pos (point))
7894 beg)
7895 (end-of-line 1)
7896 (if (and (re-search-backward org-dblock-start-re nil t)
7897 (setq beg (match-beginning 0))
7898 (re-search-forward org-dblock-end-re nil t)
7899 (> (match-end 0) pos))
7900 (goto-char beg)
7901 (goto-char pos)
7902 (error "Not in a dynamic block"))))
7904 (defun org-update-all-dblocks ()
7905 "Update all dynamic blocks in the buffer.
7906 This function can be used in a hook."
7907 (when (org-mode-p)
7908 (org-map-dblocks 'org-update-dblock)))
7911 ;;;; Completion
7913 (defconst org-additional-option-like-keywords
7914 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
7915 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
7916 "BEGIN_EXAMPLE" "END_EXAMPLE"
7917 "BEGIN_QUOTE" "END_QUOTE"
7918 "BEGIN_VERSE" "END_VERSE"
7919 "BEGIN_SRC" "END_SRC"
7920 "CAPTION" "LABEL" "ATTR_HTML" "ATTR_LaTeX"))
7922 (defcustom org-structure-template-alist
7924 ("s" "#+begin_src ?\n\n#+end_src"
7925 "<src lang=\"?\">\n\n</src>")
7926 ("e" "#+begin_example\n?\n#+end_example"
7927 "<example>\n?\n</example>")
7928 ("q" "#+begin_quote\n?\n#+end_quote"
7929 "<quote>\n?\n</quote>")
7930 ("v" "#+begin_verse\n?\n#+end_verse"
7931 "<verse>\n?\n/verse>")
7932 ("l" "#+begin_latex\n?\n#+end_latex"
7933 "<literal style=\"latex\">\n?\n</literal>")
7934 ("L" "#+latex: "
7935 "<literal style=\"latex\">?</literal>")
7936 ("h" "#+begin_html\n?\n#+end_html"
7937 "<literal style=\"html\">\n?\n</literal>")
7938 ("H" "#+html: "
7939 "<literal style=\"html\">?</literal>")
7940 ("a" "#+begin_ascii\n?\n#+end_ascii")
7941 ("A" "#+ascii: ")
7942 ("i" "#+include %file ?"
7943 "<include file=%file markup=\"?\">")
7945 "Structure completion elements.
7946 This is a list of abbreviation keys and values. The value gets inserted
7947 it you type @samp{.} followed by the key and then the completion key,
7948 usually `M-TAB'. %file will be replaced by a file name after prompting
7949 for the file using completion.
7950 There are two templates for each key, the first uses the original Org syntax,
7951 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
7952 the default when the /org-mtags.el/ module has been loaded. See also the
7953 variable `org-mtags-prefer-muse-templates'.
7954 This is an experimental feature, it is undecided if it is going to stay in."
7955 :group 'org-completion
7956 :type '(repeat
7957 (string :tag "Key")
7958 (string :tag "Template")
7959 (string :tag "Muse Template")))
7961 (defun org-try-structure-completion ()
7962 "Try to complete a structure template before point.
7963 This looks for strings like \"<e\" on an otherwise empty line and
7964 expands them."
7965 (let ((l (buffer-substring (point-at-bol) (point)))
7967 (when (and (looking-at "[ \t]*$")
7968 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
7969 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
7970 (org-complete-expand-structure-template (+ -1 (point-at-bol)
7971 (match-beginning 1)) a)
7972 t)))
7974 (defun org-complete-expand-structure-template (start cell)
7975 "Expand a structure template."
7976 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
7977 (rpl (nth (if musep 2 1) cell)))
7978 (delete-region start (point))
7979 (when (string-match "\\`#\\+" rpl)
7980 (cond
7981 ((bolp))
7982 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
7983 (delete-region (point-at-bol) (point)))
7984 (t (newline))))
7985 (setq start (point))
7986 (if (string-match "%file" rpl)
7987 (setq rpl (replace-match
7988 (concat
7989 "\""
7990 (save-match-data
7991 (abbreviate-file-name (read-file-name "Include file: ")))
7992 "\"")
7993 t t rpl)))
7994 (insert rpl)
7995 (if (re-search-backward "\\?" start t) (delete-char 1))))
7998 (defun org-complete (&optional arg)
7999 "Perform completion on word at point.
8000 At the beginning of a headline, this completes TODO keywords as given in
8001 `org-todo-keywords'.
8002 If the current word is preceded by a backslash, completes the TeX symbols
8003 that are supported for HTML support.
8004 If the current word is preceded by \"#+\", completes special words for
8005 setting file options.
8006 In the line after \"#+STARTUP:, complete valid keywords.\"
8007 At all other locations, this simply calls the value of
8008 `org-completion-fallback-command'."
8009 (interactive "P")
8010 (org-without-partial-completion
8011 (catch 'exit
8012 (let* ((a nil)
8013 (end (point))
8014 (beg1 (save-excursion
8015 (skip-chars-backward (org-re "[:alnum:]_@"))
8016 (point)))
8017 (beg (save-excursion
8018 (skip-chars-backward "a-zA-Z0-9_:$")
8019 (point)))
8020 (confirm (lambda (x) (stringp (car x))))
8021 (searchhead (equal (char-before beg) ?*))
8022 (struct
8023 (when (and (member (char-before beg1) '(?. ?<))
8024 (setq a (assoc (buffer-substring beg1 (point))
8025 org-structure-template-alist)))
8026 (org-complete-expand-structure-template (1- beg1) a)
8027 (throw 'exit t)))
8028 (tag (and (equal (char-before beg1) ?:)
8029 (equal (char-after (point-at-bol)) ?*)))
8030 (prop (and (equal (char-before beg1) ?:)
8031 (not (equal (char-after (point-at-bol)) ?*))))
8032 (texp (equal (char-before beg) ?\\))
8033 (link (equal (char-before beg) ?\[))
8034 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
8035 beg)
8036 "#+"))
8037 (startup (string-match "^#\\+STARTUP:.*"
8038 (buffer-substring (point-at-bol) (point))))
8039 (completion-ignore-case opt)
8040 (type nil)
8041 (tbl nil)
8042 (table (cond
8043 (opt
8044 (setq type :opt)
8045 (require 'org-exp)
8046 (append
8047 (mapcar
8048 (lambda (x)
8049 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
8050 (cons (match-string 2 x) (match-string 1 x)))
8051 (org-split-string (org-get-current-options) "\n"))
8052 (mapcar 'list org-additional-option-like-keywords)))
8053 (startup
8054 (setq type :startup)
8055 org-startup-options)
8056 (link (append org-link-abbrev-alist-local
8057 org-link-abbrev-alist))
8058 (texp
8059 (setq type :tex)
8060 org-html-entities)
8061 ((string-match "\\`\\*+[ \t]+\\'"
8062 (buffer-substring (point-at-bol) beg))
8063 (setq type :todo)
8064 (mapcar 'list org-todo-keywords-1))
8065 (searchhead
8066 (setq type :searchhead)
8067 (save-excursion
8068 (goto-char (point-min))
8069 (while (re-search-forward org-todo-line-regexp nil t)
8070 (push (list
8071 (org-make-org-heading-search-string
8072 (match-string 3) t))
8073 tbl)))
8074 tbl)
8075 (tag (setq type :tag beg beg1)
8076 (or org-tag-alist (org-get-buffer-tags)))
8077 (prop (setq type :prop beg beg1)
8078 (mapcar 'list (org-buffer-property-keys nil t t)))
8079 (t (progn
8080 (call-interactively org-completion-fallback-command)
8081 (throw 'exit nil)))))
8082 (pattern (buffer-substring-no-properties beg end))
8083 (completion (try-completion pattern table confirm)))
8084 (cond ((eq completion t)
8085 (if (not (assoc (upcase pattern) table))
8086 (message "Already complete")
8087 (if (and (equal type :opt)
8088 (not (member (car (assoc (upcase pattern) table))
8089 org-additional-option-like-keywords)))
8090 (insert (substring (cdr (assoc (upcase pattern) table))
8091 (length pattern)))
8092 (if (memq type '(:tag :prop)) (insert ":")))))
8093 ((null completion)
8094 (message "Can't find completion for \"%s\"" pattern)
8095 (ding))
8096 ((not (string= pattern completion))
8097 (delete-region beg end)
8098 (if (string-match " +$" completion)
8099 (setq completion (replace-match "" t t completion)))
8100 (insert completion)
8101 (if (get-buffer-window "*Completions*")
8102 (delete-window (get-buffer-window "*Completions*")))
8103 (if (assoc completion table)
8104 (if (eq type :todo) (insert " ")
8105 (if (memq type '(:tag :prop)) (insert ":"))))
8106 (if (and (equal type :opt) (assoc completion table))
8107 (message "%s" (substitute-command-keys
8108 "Press \\[org-complete] again to insert example settings"))))
8110 (message "Making completion list...")
8111 (let ((list (sort (all-completions pattern table confirm)
8112 'string<)))
8113 (with-output-to-temp-buffer "*Completions*"
8114 (condition-case nil
8115 ;; Protection needed for XEmacs and emacs 21
8116 (display-completion-list list pattern)
8117 (error (display-completion-list list)))))
8118 (message "Making completion list...%s" "done")))))))
8120 ;;;; TODO, DEADLINE, Comments
8122 (defun org-toggle-comment ()
8123 "Change the COMMENT state of an entry."
8124 (interactive)
8125 (save-excursion
8126 (org-back-to-heading)
8127 (let (case-fold-search)
8128 (if (looking-at (concat outline-regexp
8129 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
8130 (replace-match "" t t nil 1)
8131 (if (looking-at outline-regexp)
8132 (progn
8133 (goto-char (match-end 0))
8134 (insert org-comment-string " ")))))))
8136 (defvar org-last-todo-state-is-todo nil
8137 "This is non-nil when the last TODO state change led to a TODO state.
8138 If the last change removed the TODO tag or switched to DONE, then
8139 this is nil.")
8141 (defvar org-setting-tags nil) ; dynamically skipped
8143 (defun org-parse-local-options (string var)
8144 "Parse STRING for startup setting relevant for variable VAR."
8145 (let ((rtn (symbol-value var))
8146 e opts)
8147 (save-match-data
8148 (if (or (not string) (not (string-match "\\S-" string)))
8150 (setq opts (delq nil (mapcar (lambda (x)
8151 (setq e (assoc x org-startup-options))
8152 (if (eq (nth 1 e) var) e nil))
8153 (org-split-string string "[ \t]+"))))
8154 (if (not opts)
8156 (setq rtn nil)
8157 (while (setq e (pop opts))
8158 (if (not (nth 3 e))
8159 (setq rtn (nth 2 e))
8160 (if (not (listp rtn)) (setq rtn nil))
8161 (push (nth 2 e) rtn)))
8162 rtn)))))
8164 (defvar org-blocker-hook nil
8165 "Hook for functions that are allowed to block a state change.
8167 Each function gets as its single argument a property list, see
8168 `org-trigger-hook' for more information about this list.
8170 If any of the functions in this hook returns nil, the state change
8171 is blocked.")
8173 (defvar org-trigger-hook nil
8174 "Hook for functions that are triggered by a state change.
8176 Each function gets as its single argument a property list with at least
8177 the following elements:
8179 (:type type-of-change :position pos-at-entry-start
8180 :from old-state :to new-state)
8182 Depending on the type, more properties may be present.
8184 This mechanism is currently implemented for:
8186 TODO state changes
8187 ------------------
8188 :type todo-state-change
8189 :from previous state (keyword as a string), or nil
8190 :to new state (keyword as a string), or nil")
8192 (defvar org-agenda-headline-snapshot-before-repeat)
8193 (defun org-todo (&optional arg)
8194 "Change the TODO state of an item.
8195 The state of an item is given by a keyword at the start of the heading,
8196 like
8197 *** TODO Write paper
8198 *** DONE Call mom
8200 The different keywords are specified in the variable `org-todo-keywords'.
8201 By default the available states are \"TODO\" and \"DONE\".
8202 So for this example: when the item starts with TODO, it is changed to DONE.
8203 When it starts with DONE, the DONE is removed. And when neither TODO nor
8204 DONE are present, add TODO at the beginning of the heading.
8206 With C-u prefix arg, use completion to determine the new state.
8207 With numeric prefix arg, switch to that state.
8209 For calling through lisp, arg is also interpreted in the following way:
8210 'none -> empty state
8211 \"\"(empty string) -> switch to empty state
8212 'done -> switch to DONE
8213 'nextset -> switch to the next set of keywords
8214 'previousset -> switch to the previous set of keywords
8215 \"WAITING\" -> switch to the specified keyword, but only if it
8216 really is a member of `org-todo-keywords'."
8217 (interactive "P")
8218 (save-excursion
8219 (catch 'exit
8220 (org-back-to-heading)
8221 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
8222 (or (looking-at (concat " +" org-todo-regexp " *"))
8223 (looking-at " *"))
8224 (let* ((match-data (match-data))
8225 (startpos (point-at-bol))
8226 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
8227 (org-log-done org-log-done)
8228 (org-log-repeat org-log-repeat)
8229 (org-todo-log-states org-todo-log-states)
8230 (this (match-string 1))
8231 (hl-pos (match-beginning 0))
8232 (head (org-get-todo-sequence-head this))
8233 (ass (assoc head org-todo-kwd-alist))
8234 (interpret (nth 1 ass))
8235 (done-word (nth 3 ass))
8236 (final-done-word (nth 4 ass))
8237 (last-state (or this ""))
8238 (completion-ignore-case t)
8239 (member (member this org-todo-keywords-1))
8240 (tail (cdr member))
8241 (state (cond
8242 ((and org-todo-key-trigger
8243 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
8244 (and (not arg) org-use-fast-todo-selection
8245 (not (eq org-use-fast-todo-selection 'prefix)))))
8246 ;; Use fast selection
8247 (org-fast-todo-selection))
8248 ((and (equal arg '(4))
8249 (or (not org-use-fast-todo-selection)
8250 (not org-todo-key-trigger)))
8251 ;; Read a state with completion
8252 (org-ido-completing-read "State: " (mapcar (lambda(x) (list x))
8253 org-todo-keywords-1)
8254 nil t))
8255 ((eq arg 'right)
8256 (if this
8257 (if tail (car tail) nil)
8258 (car org-todo-keywords-1)))
8259 ((eq arg 'left)
8260 (if (equal member org-todo-keywords-1)
8262 (if this
8263 (nth (- (length org-todo-keywords-1) (length tail) 2)
8264 org-todo-keywords-1)
8265 (org-last org-todo-keywords-1))))
8266 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
8267 (setq arg nil))) ; hack to fall back to cycling
8268 (arg
8269 ;; user or caller requests a specific state
8270 (cond
8271 ((equal arg "") nil)
8272 ((eq arg 'none) nil)
8273 ((eq arg 'done) (or done-word (car org-done-keywords)))
8274 ((eq arg 'nextset)
8275 (or (car (cdr (member head org-todo-heads)))
8276 (car org-todo-heads)))
8277 ((eq arg 'previousset)
8278 (let ((org-todo-heads (reverse org-todo-heads)))
8279 (or (car (cdr (member head org-todo-heads)))
8280 (car org-todo-heads))))
8281 ((car (member arg org-todo-keywords-1)))
8282 ((nth (1- (prefix-numeric-value arg))
8283 org-todo-keywords-1))))
8284 ((null member) (or head (car org-todo-keywords-1)))
8285 ((equal this final-done-word) nil) ;; -> make empty
8286 ((null tail) nil) ;; -> first entry
8287 ((eq interpret 'sequence)
8288 (car tail))
8289 ((memq interpret '(type priority))
8290 (if (eq this-command last-command)
8291 (car tail)
8292 (if (> (length tail) 0)
8293 (or done-word (car org-done-keywords))
8294 nil)))
8295 (t nil)))
8296 (next (if state (concat " " state " ") " "))
8297 (change-plist (list :type 'todo-state-change :from this :to state
8298 :position startpos))
8299 dolog now-done-p)
8300 (when org-blocker-hook
8301 (unless (save-excursion
8302 (save-match-data
8303 (run-hook-with-args-until-failure
8304 'org-blocker-hook change-plist)))
8305 (if (interactive-p)
8306 (error "TODO state change from %s to %s blocked" this state)
8307 ;; fail silently
8308 (message "TODO state change from %s to %s blocked" this state)
8309 (throw 'exit nil))))
8310 (store-match-data match-data)
8311 (replace-match next t t)
8312 (unless (pos-visible-in-window-p hl-pos)
8313 (message "TODO state changed to %s" (org-trim next)))
8314 (unless head
8315 (setq head (org-get-todo-sequence-head state)
8316 ass (assoc head org-todo-kwd-alist)
8317 interpret (nth 1 ass)
8318 done-word (nth 3 ass)
8319 final-done-word (nth 4 ass)))
8320 (when (memq arg '(nextset previousset))
8321 (message "Keyword-Set %d/%d: %s"
8322 (- (length org-todo-sets) -1
8323 (length (memq (assoc state org-todo-sets) org-todo-sets)))
8324 (length org-todo-sets)
8325 (mapconcat 'identity (assoc state org-todo-sets) " ")))
8326 (setq org-last-todo-state-is-todo
8327 (not (member state org-done-keywords)))
8328 (setq now-done-p (and (member state org-done-keywords)
8329 (not (member this org-done-keywords))))
8330 (and logging (org-local-logging logging))
8331 (when (and (or org-todo-log-states org-log-done)
8332 (not (memq arg '(nextset previousset))))
8333 ;; we need to look at recording a time and note
8334 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
8335 (nth 2 (assoc this org-todo-log-states))))
8336 (when (and state
8337 (member state org-not-done-keywords)
8338 (not (member this org-not-done-keywords)))
8339 ;; This is now a todo state and was not one before
8340 ;; If there was a CLOSED time stamp, get rid of it.
8341 (org-add-planning-info nil nil 'closed))
8342 (when (and now-done-p org-log-done)
8343 ;; It is now done, and it was not done before
8344 (org-add-planning-info 'closed (org-current-time))
8345 (if (and (not dolog) (eq 'note org-log-done))
8346 (org-add-log-setup 'done state 'findpos 'note)))
8347 (when (and state dolog)
8348 ;; This is a non-nil state, and we need to log it
8349 (org-add-log-setup 'state state 'findpos dolog)))
8350 ;; Fixup tag positioning
8351 (org-todo-trigger-tag-changes state)
8352 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
8353 (when org-provide-todo-statistics
8354 (org-update-parent-todo-statistics))
8355 (run-hooks 'org-after-todo-state-change-hook)
8356 (if (and arg (not (member state org-done-keywords)))
8357 (setq head (org-get-todo-sequence-head state)))
8358 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
8359 ;; Do we need to trigger a repeat?
8360 (when now-done-p
8361 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
8362 ;; This is for the agenda, take a snapshot of the headline.
8363 (save-match-data
8364 (setq org-agenda-headline-snapshot-before-repeat
8365 (org-get-heading))))
8366 (org-auto-repeat-maybe state))
8367 ;; Fixup cursor location if close to the keyword
8368 (if (and (outline-on-heading-p)
8369 (not (bolp))
8370 (save-excursion (beginning-of-line 1)
8371 (looking-at org-todo-line-regexp))
8372 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
8373 (progn
8374 (goto-char (or (match-end 2) (match-end 1)))
8375 (just-one-space)))
8376 (when org-trigger-hook
8377 (save-excursion
8378 (run-hook-with-args 'org-trigger-hook change-plist)))))))
8380 (defun org-update-parent-todo-statistics ()
8381 "Update any statistics cookie in the parent of the current headline."
8382 (interactive)
8383 (let ((box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
8384 level (cnt-all 0) (cnt-done 0) is-percent kwd)
8385 (catch 'exit
8386 (save-excursion
8387 (setq level (org-up-heading-safe))
8388 (unless (and level
8389 (re-search-forward box-re (point-at-eol) t))
8390 (throw 'exit nil))
8391 (setq is-percent (match-end 2))
8392 (save-match-data
8393 (unless (outline-next-heading) (throw 'exit nil))
8394 (while (looking-at org-todo-line-regexp)
8395 (setq kwd (match-string 2))
8396 (and kwd (setq cnt-all (1+ cnt-all)))
8397 (and (member kwd org-done-keywords)
8398 (setq cnt-done (1+ cnt-done)))
8399 (condition-case nil
8400 (org-forward-same-level 1)
8401 (error (end-of-line 1)))))
8402 (replace-match
8403 (if is-percent
8404 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
8405 (format "[%d/%d]" cnt-done cnt-all)))
8406 (run-hook-with-args 'org-after-todo-statistics-hook
8407 cnt-done (- cnt-all cnt-done))))))
8409 (defvar org-after-todo-statistics-hook nil
8410 "Hook that is called after a TODO statistics cookie has been updated.
8411 Each function is called with two arguments: the number of not-done entries
8412 and the number of done entries.
8414 For example, the following function, when added to this hook, will switch
8415 an entry to DONE when all children are done, and back to TODO when new
8416 entries are set to a TODO status. Note that this hook is only called
8417 when there is a statistics cookie in the headline!
8419 (defun org-summary-todo (n-done n-not-done)
8420 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
8421 (let (org-log-done org-log-states) ; turn off logging
8422 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
8425 (defun org-todo-trigger-tag-changes (state)
8426 "Apply the changes defined in `org-todo-state-tags-triggers'."
8427 (let ((l org-todo-state-tags-triggers)
8428 changes)
8429 (when (or (not state) (equal state ""))
8430 (setq changes (append changes (cdr (assoc "" l)))))
8431 (when (and (stringp state) (> (length state) 0))
8432 (setq changes (append changes (cdr (assoc state l)))))
8433 (when (member state org-not-done-keywords)
8434 (setq changes (append changes (cdr (assoc 'todo l)))))
8435 (when (member state org-done-keywords)
8436 (setq changes (append changes (cdr (assoc 'done l)))))
8437 (dolist (c changes)
8438 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
8440 (defun org-local-logging (value)
8441 "Get logging settings from a property VALUE."
8442 (let* (words w a)
8443 ;; directly set the variables, they are already local.
8444 (setq org-log-done nil
8445 org-log-repeat nil
8446 org-todo-log-states nil)
8447 (setq words (org-split-string value))
8448 (while (setq w (pop words))
8449 (cond
8450 ((setq a (assoc w org-startup-options))
8451 (and (member (nth 1 a) '(org-log-done org-log-repeat))
8452 (set (nth 1 a) (nth 2 a))))
8453 ((setq a (org-extract-log-state-settings w))
8454 (and (member (car a) org-todo-keywords-1)
8455 (push a org-todo-log-states)))))))
8457 (defun org-get-todo-sequence-head (kwd)
8458 "Return the head of the TODO sequence to which KWD belongs.
8459 If KWD is not set, check if there is a text property remembering the
8460 right sequence."
8461 (let (p)
8462 (cond
8463 ((not kwd)
8464 (or (get-text-property (point-at-bol) 'org-todo-head)
8465 (progn
8466 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
8467 nil (point-at-eol)))
8468 (get-text-property p 'org-todo-head))))
8469 ((not (member kwd org-todo-keywords-1))
8470 (car org-todo-keywords-1))
8471 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
8473 (defun org-fast-todo-selection ()
8474 "Fast TODO keyword selection with single keys.
8475 Returns the new TODO keyword, or nil if no state change should occur."
8476 (let* ((fulltable org-todo-key-alist)
8477 (done-keywords org-done-keywords) ;; needed for the faces.
8478 (maxlen (apply 'max (mapcar
8479 (lambda (x)
8480 (if (stringp (car x)) (string-width (car x)) 0))
8481 fulltable)))
8482 (expert nil)
8483 (fwidth (+ maxlen 3 1 3))
8484 (ncol (/ (- (window-width) 4) fwidth))
8485 tg cnt e c tbl
8486 groups ingroup)
8487 (save-window-excursion
8488 (if expert
8489 (set-buffer (get-buffer-create " *Org todo*"))
8490 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
8491 (erase-buffer)
8492 (org-set-local 'org-done-keywords done-keywords)
8493 (setq tbl fulltable cnt 0)
8494 (while (setq e (pop tbl))
8495 (cond
8496 ((equal e '(:startgroup))
8497 (push '() groups) (setq ingroup t)
8498 (when (not (= cnt 0))
8499 (setq cnt 0)
8500 (insert "\n"))
8501 (insert "{ "))
8502 ((equal e '(:endgroup))
8503 (setq ingroup nil cnt 0)
8504 (insert "}\n"))
8506 (setq tg (car e) c (cdr e))
8507 (if ingroup (push tg (car groups)))
8508 (setq tg (org-add-props tg nil 'face
8509 (org-get-todo-face tg)))
8510 (if (and (= cnt 0) (not ingroup)) (insert " "))
8511 (insert "[" c "] " tg (make-string
8512 (- fwidth 4 (length tg)) ?\ ))
8513 (when (= (setq cnt (1+ cnt)) ncol)
8514 (insert "\n")
8515 (if ingroup (insert " "))
8516 (setq cnt 0)))))
8517 (insert "\n")
8518 (goto-char (point-min))
8519 (if (not expert) (org-fit-window-to-buffer))
8520 (message "[a-z..]:Set [SPC]:clear")
8521 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
8522 (cond
8523 ((or (= c ?\C-g)
8524 (and (= c ?q) (not (rassoc c fulltable))))
8525 (setq quit-flag t))
8526 ((= c ?\ ) nil)
8527 ((setq e (rassoc c fulltable) tg (car e))
8529 (t (setq quit-flag t))))))
8531 (defun org-entry-is-todo-p ()
8532 (member (org-get-todo-state) org-not-done-keywords))
8534 (defun org-entry-is-done-p ()
8535 (member (org-get-todo-state) org-done-keywords))
8537 (defun org-get-todo-state ()
8538 (save-excursion
8539 (org-back-to-heading t)
8540 (and (looking-at org-todo-line-regexp)
8541 (match-end 2)
8542 (match-string 2))))
8544 (defun org-at-date-range-p (&optional inactive-ok)
8545 "Is the cursor inside a date range?"
8546 (interactive)
8547 (save-excursion
8548 (catch 'exit
8549 (let ((pos (point)))
8550 (skip-chars-backward "^[<\r\n")
8551 (skip-chars-backward "<[")
8552 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8553 (>= (match-end 0) pos)
8554 (throw 'exit t))
8555 (skip-chars-backward "^<[\r\n")
8556 (skip-chars-backward "<[")
8557 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8558 (>= (match-end 0) pos)
8559 (throw 'exit t)))
8560 nil)))
8562 (defun org-get-repeat ()
8563 "Check if there is a deadline/schedule with repeater in this entry."
8564 (save-match-data
8565 (save-excursion
8566 (org-back-to-heading t)
8567 (if (re-search-forward
8568 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
8569 (match-string 1)))))
8571 (defvar org-last-changed-timestamp)
8572 (defvar org-last-inserted-timestamp)
8573 (defvar org-log-post-message)
8574 (defvar org-log-note-purpose)
8575 (defvar org-log-note-how)
8576 (defvar org-log-note-extra)
8577 (defun org-auto-repeat-maybe (done-word)
8578 "Check if the current headline contains a repeated deadline/schedule.
8579 If yes, set TODO state back to what it was and change the base date
8580 of repeating deadline/scheduled time stamps to new date.
8581 This function is run automatically after each state change to a DONE state."
8582 ;; last-state is dynamically scoped into this function
8583 (let* ((repeat (org-get-repeat))
8584 (aa (assoc last-state org-todo-kwd-alist))
8585 (interpret (nth 1 aa))
8586 (head (nth 2 aa))
8587 (whata '(("d" . day) ("m" . month) ("y" . year)))
8588 (msg "Entry repeats: ")
8589 (org-log-done nil)
8590 (org-todo-log-states nil)
8591 (nshiftmax 10) (nshift 0)
8592 re type n what ts mb0 time)
8593 (when repeat
8594 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
8595 (org-todo (if (eq interpret 'type) last-state head))
8596 (when org-log-repeat
8597 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
8598 (memq 'org-add-log-note post-command-hook))
8599 ;; OK, we are already setup for some record
8600 (if (eq org-log-repeat 'note)
8601 ;; make sure we take a note, not only a time stamp
8602 (setq org-log-note-how 'note))
8603 ;; Set up for taking a record
8604 (org-add-log-setup 'state (or done-word (car org-done-keywords))
8605 'findpos org-log-repeat)))
8606 (org-back-to-heading t)
8607 (org-add-planning-info nil nil 'closed)
8608 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
8609 org-deadline-time-regexp "\\)\\|\\("
8610 org-ts-regexp "\\)"))
8611 (while (re-search-forward
8612 re (save-excursion (outline-next-heading) (point)) t)
8613 (setq type (if (match-end 1) org-scheduled-string
8614 (if (match-end 3) org-deadline-string "Plain:"))
8615 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0)))
8616 mb0 (match-beginning 0))
8617 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
8618 (setq n (string-to-number (match-string 2 ts))
8619 what (match-string 3 ts))
8620 (if (equal what "w") (setq n (* n 7) what "d"))
8621 ;; Preparation, see if we need to modify the start date for the change
8622 (when (match-end 1)
8623 (setq time (save-match-data (org-time-string-to-time ts)))
8624 (cond
8625 ((equal (match-string 1 ts) ".")
8626 ;; Shift starting date to today
8627 (org-timestamp-change
8628 (- (time-to-days (current-time)) (time-to-days time))
8629 'day))
8630 ((equal (match-string 1 ts) "+")
8631 (while (or (= nshift 0)
8632 (<= (time-to-days time) (time-to-days (current-time))))
8633 (when (= (incf nshift) nshiftmax)
8634 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
8635 (error "Abort")))
8636 (org-timestamp-change n (cdr (assoc what whata)))
8637 (org-at-timestamp-p t)
8638 (setq ts (match-string 1))
8639 (setq time (save-match-data (org-time-string-to-time ts))))
8640 (org-timestamp-change (- n) (cdr (assoc what whata)))
8641 ;; rematch, so that we have everything in place for the real shift
8642 (org-at-timestamp-p t)
8643 (setq ts (match-string 1))
8644 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
8645 (org-timestamp-change n (cdr (assoc what whata)))
8646 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
8647 (setq org-log-post-message msg)
8648 (message "%s" msg))))
8650 (defun org-show-todo-tree (arg)
8651 "Make a compact tree which shows all headlines marked with TODO.
8652 The tree will show the lines where the regexp matches, and all higher
8653 headlines above the match.
8654 With a \\[universal-argument] prefix, also show the DONE entries.
8655 With a numeric prefix N, construct a sparse tree for the Nth element
8656 of `org-todo-keywords-1'."
8657 (interactive "P")
8658 (let ((case-fold-search nil)
8659 (kwd-re
8660 (cond ((null arg) org-not-done-regexp)
8661 ((equal arg '(4))
8662 (let ((kwd (org-ido-completing-read "Keyword (or KWD1|KWD2|...): "
8663 (mapcar 'list org-todo-keywords-1))))
8664 (concat "\\("
8665 (mapconcat 'identity (org-split-string kwd "|") "\\|")
8666 "\\)\\>")))
8667 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
8668 (regexp-quote (nth (1- (prefix-numeric-value arg))
8669 org-todo-keywords-1)))
8670 (t (error "Invalid prefix argument: %s" arg)))))
8671 (message "%d TODO entries found"
8672 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
8674 (defun org-deadline (&optional remove time)
8675 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
8676 With argument REMOVE, remove any deadline from the item.
8677 When TIME is set, it should be an internal time specification, and the
8678 scheduling will use the corresponding date."
8679 (interactive "P")
8680 (if remove
8681 (progn
8682 (org-remove-timestamp-with-keyword org-deadline-string)
8683 (message "Item no longer has a deadline."))
8684 (if (org-get-repeat)
8685 (error "Cannot change deadline on task with repeater, please do that by hand")
8686 (org-add-planning-info 'deadline time 'closed)
8687 (message "Deadline on %s" org-last-inserted-timestamp))))
8689 (defun org-schedule (&optional remove time)
8690 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
8691 With argument REMOVE, remove any scheduling date from the item.
8692 When TIME is set, it should be an internal time specification, and the
8693 scheduling will use the corresponding date."
8694 (interactive "P")
8695 (if remove
8696 (progn
8697 (org-remove-timestamp-with-keyword org-scheduled-string)
8698 (message "Item is no longer scheduled."))
8699 (if (org-get-repeat)
8700 (error "Cannot reschedule task with repeater, please do that by hand")
8701 (org-add-planning-info 'scheduled time 'closed)
8702 (message "Scheduled to %s" org-last-inserted-timestamp))))
8704 (defun org-remove-timestamp-with-keyword (keyword)
8705 "Remove all time stamps with KEYWORD in the current entry."
8706 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
8707 beg)
8708 (save-excursion
8709 (org-back-to-heading t)
8710 (setq beg (point))
8711 (org-end-of-subtree t t)
8712 (while (re-search-backward re beg t)
8713 (replace-match "")
8714 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
8715 (equal (char-before) ?\ ))
8716 (backward-delete-char 1)
8717 (if (string-match "^[ \t]*$" (buffer-substring
8718 (point-at-bol) (point-at-eol)))
8719 (delete-region (point-at-bol)
8720 (min (point-max) (1+ (point-at-eol))))))))))
8722 (defun org-add-planning-info (what &optional time &rest remove)
8723 "Insert new timestamp with keyword in the line directly after the headline.
8724 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
8725 If non is given, the user is prompted for a date.
8726 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
8727 be removed."
8728 (interactive)
8729 (let (org-time-was-given org-end-time-was-given ts
8730 end default-time default-input)
8732 (when (and (not time) (memq what '(scheduled deadline)))
8733 ;; Try to get a default date/time from existing timestamp
8734 (save-excursion
8735 (org-back-to-heading t)
8736 (setq end (save-excursion (outline-next-heading) (point)))
8737 (when (re-search-forward (if (eq what 'scheduled)
8738 org-scheduled-time-regexp
8739 org-deadline-time-regexp)
8740 end t)
8741 (setq ts (match-string 1)
8742 default-time
8743 (apply 'encode-time (org-parse-time-string ts))
8744 default-input (and ts (org-get-compact-tod ts))))))
8745 (when what
8746 ;; If necessary, get the time from the user
8747 (setq time (or time (org-read-date nil 'to-time nil nil
8748 default-time default-input))))
8750 (when (and org-insert-labeled-timestamps-at-point
8751 (member what '(scheduled deadline)))
8752 (insert
8753 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
8754 (org-insert-time-stamp time org-time-was-given
8755 nil nil nil (list org-end-time-was-given))
8756 (setq what nil))
8757 (save-excursion
8758 (save-restriction
8759 (let (col list elt ts buffer-invisibility-spec)
8760 (org-back-to-heading t)
8761 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
8762 (goto-char (match-end 1))
8763 (setq col (current-column))
8764 (goto-char (match-end 0))
8765 (if (eobp) (insert "\n") (forward-char 1))
8766 (if (and (not (looking-at outline-regexp))
8767 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
8768 "[^\r\n]*"))
8769 (not (equal (match-string 1) org-clock-string)))
8770 (narrow-to-region (match-beginning 0) (match-end 0))
8771 (insert-before-markers "\n")
8772 (backward-char 1)
8773 (narrow-to-region (point) (point))
8774 (and org-adapt-indentation (org-indent-to-column col)))
8775 ;; Check if we have to remove something.
8776 (setq list (cons what remove))
8777 (while list
8778 (setq elt (pop list))
8779 (goto-char (point-min))
8780 (when (or (and (eq elt 'scheduled)
8781 (re-search-forward org-scheduled-time-regexp nil t))
8782 (and (eq elt 'deadline)
8783 (re-search-forward org-deadline-time-regexp nil t))
8784 (and (eq elt 'closed)
8785 (re-search-forward org-closed-time-regexp nil t)))
8786 (replace-match "")
8787 (if (looking-at "--+<[^>]+>") (replace-match ""))
8788 (if (looking-at " +") (replace-match ""))))
8789 (goto-char (point-max))
8790 (when what
8791 (insert
8792 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
8793 (cond ((eq what 'scheduled) org-scheduled-string)
8794 ((eq what 'deadline) org-deadline-string)
8795 ((eq what 'closed) org-closed-string))
8796 " ")
8797 (setq ts (org-insert-time-stamp
8798 time
8799 (or org-time-was-given
8800 (and (eq what 'closed) org-log-done-with-time))
8801 (eq what 'closed)
8802 nil nil (list org-end-time-was-given)))
8803 (end-of-line 1))
8804 (goto-char (point-min))
8805 (widen)
8806 (if (and (looking-at "[ \t]+\n")
8807 (equal (char-before) ?\n))
8808 (delete-region (1- (point)) (point-at-eol)))
8809 ts)))))
8811 (defvar org-log-note-marker (make-marker))
8812 (defvar org-log-note-purpose nil)
8813 (defvar org-log-note-state nil)
8814 (defvar org-log-note-how nil)
8815 (defvar org-log-note-extra nil)
8816 (defvar org-log-note-window-configuration nil)
8817 (defvar org-log-note-return-to (make-marker))
8818 (defvar org-log-post-message nil
8819 "Message to be displayed after a log note has been stored.
8820 The auto-repeater uses this.")
8822 (defun org-add-note ()
8823 "Add a note to the current entry.
8824 This is done in the same way as adding a state change note."
8825 (interactive)
8826 (org-add-log-setup 'note nil 'findpos nil))
8828 (defvar org-property-end-re)
8829 (defun org-add-log-setup (&optional purpose state findpos how &optional extra)
8830 "Set up the post command hook to take a note.
8831 If this is about to TODO state change, the new state is expected in STATE.
8832 When FINDPOS is non-nil, find the correct position for the note in
8833 the current entry. If not, assume that it can be inserted at point.
8834 HOW is an indicator what kind of note should be created.
8835 EXTRA is additional text that will be inserted into the notes buffer."
8836 (save-restriction
8837 (save-excursion
8838 (when findpos
8839 (org-back-to-heading t)
8840 (narrow-to-region (point) (save-excursion
8841 (outline-next-heading) (point)))
8842 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
8843 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
8844 "[^\r\n]*\\)?"))
8845 (goto-char (match-end 0))
8846 (when (and org-log-state-notes-insert-after-drawers
8847 (save-excursion
8848 (forward-line) (looking-at org-drawer-regexp)))
8849 (progn (forward-line)
8850 (while (looking-at org-drawer-regexp)
8851 (goto-char (match-end 0))
8852 (re-search-forward org-property-end-re (point-max) t)
8853 (forward-line))
8854 (forward-line -1)))
8855 (unless org-log-states-order-reversed
8856 (and (= (char-after) ?\n) (forward-char 1))
8857 (org-skip-over-state-notes)
8858 (skip-chars-backward " \t\n\r")))
8859 (move-marker org-log-note-marker (point))
8860 (setq org-log-note-purpose purpose
8861 org-log-note-state state
8862 org-log-note-how how
8863 org-log-note-extra extra)
8864 (add-hook 'post-command-hook 'org-add-log-note 'append))))
8866 (defun org-skip-over-state-notes ()
8867 "Skip past the list of State notes in an entry."
8868 (if (looking-at "\n[ \t]*- State") (forward-char 1))
8869 (while (looking-at "[ \t]*- State")
8870 (condition-case nil
8871 (org-next-item)
8872 (error (org-end-of-item)))))
8874 (defun org-add-log-note (&optional purpose)
8875 "Pop up a window for taking a note, and add this note later at point."
8876 (remove-hook 'post-command-hook 'org-add-log-note)
8877 (setq org-log-note-window-configuration (current-window-configuration))
8878 (delete-other-windows)
8879 (move-marker org-log-note-return-to (point))
8880 (switch-to-buffer (marker-buffer org-log-note-marker))
8881 (goto-char org-log-note-marker)
8882 (org-switch-to-buffer-other-window "*Org Note*")
8883 (erase-buffer)
8884 (if (memq org-log-note-how '(time state))
8885 (let (current-prefix-arg) (org-store-log-note))
8886 (let ((org-inhibit-startup t)) (org-mode))
8887 (insert (format "# Insert note for %s.
8888 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
8889 (cond
8890 ((eq org-log-note-purpose 'clock-out) "stopped clock")
8891 ((eq org-log-note-purpose 'done) "closed todo item")
8892 ((eq org-log-note-purpose 'state)
8893 (format "state change to \"%s\"" org-log-note-state))
8894 ((eq org-log-note-purpose 'note)
8895 "this entry")
8896 (t (error "This should not happen")))))
8897 (if org-log-note-extra (insert org-log-note-extra))
8898 (org-set-local 'org-finish-function 'org-store-log-note)))
8900 (defvar org-note-abort nil) ; dynamically scoped
8901 (defun org-store-log-note ()
8902 "Finish taking a log note, and insert it to where it belongs."
8903 (let ((txt (buffer-string))
8904 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
8905 lines ind)
8906 (kill-buffer (current-buffer))
8907 (while (string-match "\\`#.*\n[ \t\n]*" txt)
8908 (setq txt (replace-match "" t t txt)))
8909 (if (string-match "\\s-+\\'" txt)
8910 (setq txt (replace-match "" t t txt)))
8911 (setq lines (org-split-string txt "\n"))
8912 (when (and note (string-match "\\S-" note))
8913 (setq note
8914 (org-replace-escapes
8915 note
8916 (list (cons "%u" (user-login-name))
8917 (cons "%U" user-full-name)
8918 (cons "%t" (format-time-string
8919 (org-time-stamp-format 'long 'inactive)
8920 (current-time)))
8921 (cons "%s" (if org-log-note-state
8922 (concat "\"" org-log-note-state "\"")
8923 "")))))
8924 (if lines (setq note (concat note " \\\\")))
8925 (push note lines))
8926 (when (or current-prefix-arg org-note-abort) (setq lines nil))
8927 (when lines
8928 (save-excursion
8929 (set-buffer (marker-buffer org-log-note-marker))
8930 (save-excursion
8931 (goto-char org-log-note-marker)
8932 (move-marker org-log-note-marker nil)
8933 (end-of-line 1)
8934 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
8935 (indent-relative nil)
8936 (insert "- " (pop lines))
8937 (org-indent-line-function)
8938 (beginning-of-line 1)
8939 (looking-at "[ \t]*")
8940 (setq ind (concat (match-string 0) " "))
8941 (end-of-line 1)
8942 (while lines (insert "\n" ind (pop lines)))))))
8943 (set-window-configuration org-log-note-window-configuration)
8944 (with-current-buffer (marker-buffer org-log-note-return-to)
8945 (goto-char org-log-note-return-to))
8946 (move-marker org-log-note-return-to nil)
8947 (and org-log-post-message (message "%s" org-log-post-message)))
8949 (defun org-sparse-tree (&optional arg)
8950 "Create a sparse tree, prompt for the details.
8951 This command can create sparse trees. You first need to select the type
8952 of match used to create the tree:
8954 t Show entries with a specific TODO keyword.
8955 T Show entries selected by a tags match.
8956 p Enter a property name and its value (both with completion on existing
8957 names/values) and show entries with that property.
8958 r Show entries matching a regular expression
8959 d Show deadlines due within `org-deadline-warning-days'."
8960 (interactive "P")
8961 (let (ans kwd value)
8962 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
8963 (setq ans (read-char-exclusive))
8964 (cond
8965 ((equal ans ?d)
8966 (call-interactively 'org-check-deadlines))
8967 ((equal ans ?b)
8968 (call-interactively 'org-check-before-date))
8969 ((equal ans ?t)
8970 (org-show-todo-tree '(4)))
8971 ((equal ans ?T)
8972 (call-interactively 'org-tags-sparse-tree))
8973 ((member ans '(?p ?P))
8974 (setq kwd (org-ido-completing-read "Property: "
8975 (mapcar 'list (org-buffer-property-keys))))
8976 (setq value (org-ido-completing-read "Value: "
8977 (mapcar 'list (org-property-values kwd))))
8978 (unless (string-match "\\`{.*}\\'" value)
8979 (setq value (concat "\"" value "\"")))
8980 (org-tags-sparse-tree arg (concat kwd "=" value)))
8981 ((member ans '(?r ?R ?/))
8982 (call-interactively 'org-occur))
8983 (t (error "No such sparse tree command \"%c\"" ans)))))
8985 (defvar org-occur-highlights nil
8986 "List of overlays used for occur matches.")
8987 (make-variable-buffer-local 'org-occur-highlights)
8988 (defvar org-occur-parameters nil
8989 "Parameters of the active org-occur calls.
8990 This is a list, each call to org-occur pushes as cons cell,
8991 containing the regular expression and the callback, onto the list.
8992 The list can contain several entries if `org-occur' has been called
8993 several time with the KEEP-PREVIOUS argument. Otherwise, this list
8994 will only contain one set of parameters. When the highlights are
8995 removed (for example with `C-c C-c', or with the next edit (depending
8996 on `org-remove-highlights-with-change'), this variable is emptied
8997 as well.")
8998 (make-variable-buffer-local 'org-occur-parameters)
9000 (defun org-occur (regexp &optional keep-previous callback)
9001 "Make a compact tree which shows all matches of REGEXP.
9002 The tree will show the lines where the regexp matches, and all higher
9003 headlines above the match. It will also show the heading after the match,
9004 to make sure editing the matching entry is easy.
9005 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
9006 call to `org-occur' will be kept, to allow stacking of calls to this
9007 command.
9008 If CALLBACK is non-nil, it is a function which is called to confirm
9009 that the match should indeed be shown."
9010 (interactive "sRegexp: \nP")
9011 (unless keep-previous
9012 (org-remove-occur-highlights nil nil t))
9013 (push (cons regexp callback) org-occur-parameters)
9014 (let ((cnt 0))
9015 (save-excursion
9016 (goto-char (point-min))
9017 (if (or (not keep-previous) ; do not want to keep
9018 (not org-occur-highlights)) ; no previous matches
9019 ;; hide everything
9020 (org-overview))
9021 (while (re-search-forward regexp nil t)
9022 (when (or (not callback)
9023 (save-match-data (funcall callback)))
9024 (setq cnt (1+ cnt))
9025 (when org-highlight-sparse-tree-matches
9026 (org-highlight-new-match (match-beginning 0) (match-end 0)))
9027 (org-show-context 'occur-tree))))
9028 (when org-remove-highlights-with-change
9029 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
9030 nil 'local))
9031 (unless org-sparse-tree-open-archived-trees
9032 (org-hide-archived-subtrees (point-min) (point-max)))
9033 (run-hooks 'org-occur-hook)
9034 (if (interactive-p)
9035 (message "%d match(es) for regexp %s" cnt regexp))
9036 cnt))
9038 (defun org-show-context (&optional key)
9039 "Make sure point and context and visible.
9040 How much context is shown depends upon the variables
9041 `org-show-hierarchy-above', `org-show-following-heading'. and
9042 `org-show-siblings'."
9043 (let ((heading-p (org-on-heading-p t))
9044 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
9045 (following-p (org-get-alist-option org-show-following-heading key))
9046 (entry-p (org-get-alist-option org-show-entry-below key))
9047 (siblings-p (org-get-alist-option org-show-siblings key)))
9048 (catch 'exit
9049 ;; Show heading or entry text
9050 (if (and heading-p (not entry-p))
9051 (org-flag-heading nil) ; only show the heading
9052 (and (or entry-p (org-invisible-p) (org-invisible-p2))
9053 (org-show-hidden-entry))) ; show entire entry
9054 (when following-p
9055 ;; Show next sibling, or heading below text
9056 (save-excursion
9057 (and (if heading-p (org-goto-sibling) (outline-next-heading))
9058 (org-flag-heading nil))))
9059 (when siblings-p (org-show-siblings))
9060 (when hierarchy-p
9061 ;; show all higher headings, possibly with siblings
9062 (save-excursion
9063 (while (and (condition-case nil
9064 (progn (org-up-heading-all 1) t)
9065 (error nil))
9066 (not (bobp)))
9067 (org-flag-heading nil)
9068 (when siblings-p (org-show-siblings))))))))
9070 (defun org-reveal (&optional siblings)
9071 "Show current entry, hierarchy above it, and the following headline.
9072 This can be used to show a consistent set of context around locations
9073 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
9074 not t for the search context.
9076 With optional argument SIBLINGS, on each level of the hierarchy all
9077 siblings are shown. This repairs the tree structure to what it would
9078 look like when opened with hierarchical calls to `org-cycle'."
9079 (interactive "P")
9080 (let ((org-show-hierarchy-above t)
9081 (org-show-following-heading t)
9082 (org-show-siblings (if siblings t org-show-siblings)))
9083 (org-show-context nil)))
9085 (defun org-highlight-new-match (beg end)
9086 "Highlight from BEG to END and mark the highlight is an occur headline."
9087 (let ((ov (org-make-overlay beg end)))
9088 (org-overlay-put ov 'face 'secondary-selection)
9089 (push ov org-occur-highlights)))
9091 (defun org-remove-occur-highlights (&optional beg end noremove)
9092 "Remove the occur highlights from the buffer.
9093 BEG and END are ignored. If NOREMOVE is nil, remove this function
9094 from the `before-change-functions' in the current buffer."
9095 (interactive)
9096 (unless org-inhibit-highlight-removal
9097 (mapc 'org-delete-overlay org-occur-highlights)
9098 (setq org-occur-highlights nil)
9099 (setq org-occur-parameters nil)
9100 (unless noremove
9101 (remove-hook 'before-change-functions
9102 'org-remove-occur-highlights 'local))))
9104 ;;;; Priorities
9106 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
9107 "Regular expression matching the priority indicator.")
9109 (defvar org-remove-priority-next-time nil)
9111 (defun org-priority-up ()
9112 "Increase the priority of the current item."
9113 (interactive)
9114 (org-priority 'up))
9116 (defun org-priority-down ()
9117 "Decrease the priority of the current item."
9118 (interactive)
9119 (org-priority 'down))
9121 (defun org-priority (&optional action)
9122 "Change the priority of an item by ARG.
9123 ACTION can be `set', `up', `down', or a character."
9124 (interactive)
9125 (setq action (or action 'set))
9126 (let (current new news have remove)
9127 (save-excursion
9128 (org-back-to-heading)
9129 (if (looking-at org-priority-regexp)
9130 (setq current (string-to-char (match-string 2))
9131 have t)
9132 (setq current org-default-priority))
9133 (cond
9134 ((or (eq action 'set)
9135 (if (featurep 'xemacs) (characterp action) (integerp action)))
9136 (if (not (eq action 'set))
9137 (setq new action)
9138 (message "Priority %c-%c, SPC to remove: "
9139 org-highest-priority org-lowest-priority)
9140 (setq new (read-char-exclusive)))
9141 (if (and (= (upcase org-highest-priority) org-highest-priority)
9142 (= (upcase org-lowest-priority) org-lowest-priority))
9143 (setq new (upcase new)))
9144 (cond ((equal new ?\ ) (setq remove t))
9145 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
9146 (error "Priority must be between `%c' and `%c'"
9147 org-highest-priority org-lowest-priority))))
9148 ((eq action 'up)
9149 (if (and (not have) (eq last-command this-command))
9150 (setq new org-lowest-priority)
9151 (setq new (if (and org-priority-start-cycle-with-default (not have))
9152 org-default-priority (1- current)))))
9153 ((eq action 'down)
9154 (if (and (not have) (eq last-command this-command))
9155 (setq new org-highest-priority)
9156 (setq new (if (and org-priority-start-cycle-with-default (not have))
9157 org-default-priority (1+ current)))))
9158 (t (error "Invalid action")))
9159 (if (or (< (upcase new) org-highest-priority)
9160 (> (upcase new) org-lowest-priority))
9161 (setq remove t))
9162 (setq news (format "%c" new))
9163 (if have
9164 (if remove
9165 (replace-match "" t t nil 1)
9166 (replace-match news t t nil 2))
9167 (if remove
9168 (error "No priority cookie found in line")
9169 (looking-at org-todo-line-regexp)
9170 (if (match-end 2)
9171 (progn
9172 (goto-char (match-end 2))
9173 (insert " [#" news "]"))
9174 (goto-char (match-beginning 3))
9175 (insert "[#" news "] ")))))
9176 (org-preserve-lc (org-set-tags nil 'align))
9177 (if remove
9178 (message "Priority removed")
9179 (message "Priority of current item set to %s" news))))
9182 (defun org-get-priority (s)
9183 "Find priority cookie and return priority."
9184 (save-match-data
9185 (if (not (string-match org-priority-regexp s))
9186 (* 1000 (- org-lowest-priority org-default-priority))
9187 (* 1000 (- org-lowest-priority
9188 (string-to-char (match-string 2 s)))))))
9190 ;;;; Tags
9192 (defvar org-agenda-archives-mode)
9193 (defun org-scan-tags (action matcher &optional todo-only)
9194 "Scan headline tags with inheritance and produce output ACTION.
9196 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
9197 or `agenda' to produce an entry list for an agenda view. It can also be
9198 a Lisp form or a function that should be called at each matched headline, in
9199 this case the return value is a list of all return values from these calls.
9201 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
9202 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
9203 only lines with a TODO keyword are included in the output."
9204 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
9205 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
9206 (org-re
9207 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
9208 (props (list 'face 'default
9209 'done-face 'org-done
9210 'undone-face 'default
9211 'mouse-face 'highlight
9212 'org-not-done-regexp org-not-done-regexp
9213 'org-todo-regexp org-todo-regexp
9214 'keymap org-agenda-keymap
9215 'help-echo
9216 (format "mouse-2 or RET jump to org file %s"
9217 (abbreviate-file-name
9218 (or (buffer-file-name (buffer-base-buffer))
9219 (buffer-name (buffer-base-buffer)))))))
9220 (case-fold-search nil)
9221 lspos tags tags-list
9222 (tags-alist (list (cons 0 (mapcar 'downcase org-file-tags))))
9223 (llast 0) rtn rtn1 level category i txt
9224 todo marker entry priority)
9225 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
9226 (setq action (list 'lambda nil action)))
9227 (save-excursion
9228 (goto-char (point-min))
9229 (when (eq action 'sparse-tree)
9230 (org-overview)
9231 (org-remove-occur-highlights))
9232 (while (re-search-forward re nil t)
9233 (catch :skip
9234 (setq todo (if (match-end 1) (match-string 2))
9235 tags (if (match-end 4) (match-string 4)))
9236 (goto-char (setq lspos (1+ (match-beginning 0))))
9237 (setq level (org-reduced-level (funcall outline-level))
9238 category (org-get-category))
9239 (setq i llast llast level)
9240 ;; remove tag lists from same and sublevels
9241 (while (>= i level)
9242 (when (setq entry (assoc i tags-alist))
9243 (setq tags-alist (delete entry tags-alist)))
9244 (setq i (1- i)))
9245 ;; add the next tags
9246 (when tags
9247 (setq tags (mapcar 'downcase (org-split-string tags ":"))
9248 tags-alist
9249 (cons (cons level tags) tags-alist)))
9250 ;; compile tags for current headline
9251 (setq tags-list
9252 (if org-use-tag-inheritance
9253 (apply 'append (mapcar 'cdr (reverse tags-alist)))
9254 tags))
9255 (when org-use-tag-inheritance
9256 (setcdr (car tags-alist)
9257 (mapcar (lambda (x)
9258 (setq x (copy-sequence x))
9259 (org-add-prop-inherited x))
9260 (cdar tags-alist))))
9261 (when (and tags org-use-tag-inheritance
9262 (not (eq t org-use-tag-inheritance)))
9263 ;; selective inheritance, remove uninherited ones
9264 (setcdr (car tags-alist)
9265 (org-remove-uniherited-tags (cdar tags-alist))))
9266 (when (and (or (not todo-only) (member todo org-not-done-keywords))
9267 (let ((case-fold-search t)) (eval matcher))
9269 (not (member org-archive-tag tags-list))
9270 ;; we have an archive tag, should we use this anyway?
9271 (or (not org-agenda-skip-archived-trees)
9272 (and (eq action 'agenda) org-agenda-archives-mode))))
9273 (unless (eq action 'sparse-tree) (org-agenda-skip))
9275 ;; select this headline
9277 (cond
9278 ((eq action 'sparse-tree)
9279 (and org-highlight-sparse-tree-matches
9280 (org-get-heading) (match-end 0)
9281 (org-highlight-new-match
9282 (match-beginning 0) (match-beginning 1)))
9283 (org-show-context 'tags-tree))
9284 ((eq action 'agenda)
9285 (setq txt (org-format-agenda-item
9287 (concat
9288 (if org-tags-match-list-sublevels
9289 (make-string (1- level) ?.) "")
9290 (org-get-heading))
9291 category (org-get-tags-at))
9292 priority (org-get-priority txt))
9293 (goto-char lspos)
9294 (setq marker (org-agenda-new-marker))
9295 (org-add-props txt props
9296 'org-marker marker 'org-hd-marker marker 'org-category category
9297 'priority priority 'type "tagsmatch")
9298 (push txt rtn))
9299 ((functionp action)
9300 (save-excursion
9301 (setq rtn1 (funcall action))
9302 (push rtn1 rtn))
9303 (goto-char (point-at-eol)))
9304 (t (error "Invalid action")))
9306 ;; if we are to skip sublevels, jump to end of subtree
9307 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
9308 (when (and (eq action 'sparse-tree)
9309 (not org-sparse-tree-open-archived-trees))
9310 (org-hide-archived-subtrees (point-min) (point-max)))
9311 (nreverse rtn)))
9313 (defun org-remove-uniherited-tags (tags)
9314 "Remove all tags that are not inherited from the list TAGS."
9315 (cond
9316 ((eq org-use-tag-inheritance t)
9317 (if org-tags-exclude-from-inheritance
9318 (org-delete-all org-tags-exclude-from-inheritance tags)
9319 tags))
9320 ((not org-use-tag-inheritance) nil)
9321 ((stringp org-use-tag-inheritance)
9322 (delq nil (mapcar
9323 (lambda (x)
9324 (if (and (string-match org-use-tag-inheritance x)
9325 (not (member x org-tags-exclude-from-inheritance)))
9326 x nil))
9327 tags)))
9328 ((listp org-use-tag-inheritance)
9329 (delq nil (mapcar
9330 (lambda (x)
9331 (if (member x org-use-tag-inheritance) x nil))
9332 tags)))))
9334 (defvar todo-only) ;; dynamically scoped
9336 (defun org-tags-sparse-tree (&optional todo-only match)
9337 "Create a sparse tree according to tags string MATCH.
9338 MATCH can contain positive and negative selection of tags, like
9339 \"+WORK+URGENT-WITHBOSS\".
9340 If optional argument TODO-ONLY is non-nil, only select lines that are
9341 also TODO lines."
9342 (interactive "P")
9343 (org-prepare-agenda-buffers (list (current-buffer)))
9344 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
9346 (defvar org-cached-props nil)
9347 (defun org-cached-entry-get (pom property)
9348 (if (or (eq t org-use-property-inheritance)
9349 (and (stringp org-use-property-inheritance)
9350 (string-match org-use-property-inheritance property))
9351 (and (listp org-use-property-inheritance)
9352 (member property org-use-property-inheritance)))
9353 ;; Caching is not possible, check it directly
9354 (org-entry-get pom property 'inherit)
9355 ;; Get all properties, so that we can do complicated checks easily
9356 (cdr (assoc property (or org-cached-props
9357 (setq org-cached-props
9358 (org-entry-properties pom)))))))
9360 (defun org-global-tags-completion-table (&optional files)
9361 "Return the list of all tags in all agenda buffer/files."
9362 (save-excursion
9363 (org-uniquify
9364 (delq nil
9365 (apply 'append
9366 (mapcar
9367 (lambda (file)
9368 (set-buffer (find-file-noselect file))
9369 (append (org-get-buffer-tags)
9370 (mapcar (lambda (x) (if (stringp (car-safe x))
9371 (list (car-safe x)) nil))
9372 org-tag-alist)))
9373 (if (and files (car files))
9374 files
9375 (org-agenda-files))))))))
9377 (defun org-make-tags-matcher (match)
9378 "Create the TAGS//TODO matcher form for the selection string MATCH."
9379 ;; todo-only is scoped dynamically into this function, and the function
9380 ;; may change it if the matcher asks for it.
9381 (unless match
9382 ;; Get a new match request, with completion
9383 (let ((org-last-tags-completion-table
9384 (org-global-tags-completion-table)))
9385 (setq match (org-ido-completing-read
9386 "Match: " 'org-tags-completion-function nil nil nil
9387 'org-tags-history))))
9389 ;; Parse the string and create a lisp form
9390 (let ((match0 match)
9391 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
9392 minus tag mm
9393 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
9394 orterms term orlist re-p str-p level-p level-op time-p
9395 prop-p pn pv po cat-p gv rest)
9396 (if (string-match "/+" match)
9397 ;; match contains also a todo-matching request
9398 (progn
9399 (setq tagsmatch (substring match 0 (match-beginning 0))
9400 todomatch (substring match (match-end 0)))
9401 (if (string-match "^!" todomatch)
9402 (setq todo-only t todomatch (substring todomatch 1)))
9403 (if (string-match "^\\s-*$" todomatch)
9404 (setq todomatch nil)))
9405 ;; only matching tags
9406 (setq tagsmatch match todomatch nil))
9408 ;; Make the tags matcher
9409 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
9410 (setq tagsmatcher t)
9411 (setq orterms (org-split-string tagsmatch "|") orlist nil)
9412 (while (setq term (pop orterms))
9413 (while (and (equal (substring term -1) "\\") orterms)
9414 (setq term (concat term "|" (pop orterms)))) ; repair bad split
9415 (while (string-match re term)
9416 (setq rest (substring term (match-end 0))
9417 minus (and (match-end 1)
9418 (equal (match-string 1 term) "-"))
9419 tag (match-string 2 term)
9420 re-p (equal (string-to-char tag) ?{)
9421 level-p (match-end 4)
9422 prop-p (match-end 5)
9423 mm (cond
9424 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
9425 (level-p
9426 (setq level-op (org-op-to-function (match-string 3 term)))
9427 `(,level-op level ,(string-to-number
9428 (match-string 4 term))))
9429 (prop-p
9430 (setq pn (match-string 5 term)
9431 po (match-string 6 term)
9432 pv (match-string 7 term)
9433 cat-p (equal pn "CATEGORY")
9434 re-p (equal (string-to-char pv) ?{)
9435 str-p (equal (string-to-char pv) ?\")
9436 time-p (save-match-data
9437 (string-match "^\"[[<].*[]>]\"$" pv))
9438 pv (if (or re-p str-p) (substring pv 1 -1) pv))
9439 (if time-p (setq pv (org-matcher-time pv)))
9440 (setq po (org-op-to-function po (if time-p 'time str-p)))
9441 (cond
9442 ((equal pn "CATEGORY")
9443 (setq gv '(get-text-property (point) 'org-category)))
9444 ((equal pn "TODO")
9445 (setq gv 'todo))
9447 (setq gv `(org-cached-entry-get nil ,pn))))
9448 (if re-p
9449 (if (eq po 'org<>)
9450 `(not (string-match ,pv (or ,gv "")))
9451 `(string-match ,pv (or ,gv "")))
9452 (if str-p
9453 `(,po (or ,gv "") ,pv)
9454 `(,po (string-to-number (or ,gv ""))
9455 ,(string-to-number pv) ))))
9456 (t `(member ,(downcase tag) tags-list)))
9457 mm (if minus (list 'not mm) mm)
9458 term rest)
9459 (push mm tagsmatcher))
9460 (push (if (> (length tagsmatcher) 1)
9461 (cons 'and tagsmatcher)
9462 (car tagsmatcher))
9463 orlist)
9464 (setq tagsmatcher nil))
9465 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
9466 (setq tagsmatcher
9467 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
9468 ;; Make the todo matcher
9469 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
9470 (setq todomatcher t)
9471 (setq orterms (org-split-string todomatch "|") orlist nil)
9472 (while (setq term (pop orterms))
9473 (while (string-match re term)
9474 (setq minus (and (match-end 1)
9475 (equal (match-string 1 term) "-"))
9476 kwd (match-string 2 term)
9477 re-p (equal (string-to-char kwd) ?{)
9478 term (substring term (match-end 0))
9479 mm (if re-p
9480 `(string-match ,(substring kwd 1 -1) todo)
9481 (list 'equal 'todo kwd))
9482 mm (if minus (list 'not mm) mm))
9483 (push mm todomatcher))
9484 (push (if (> (length todomatcher) 1)
9485 (cons 'and todomatcher)
9486 (car todomatcher))
9487 orlist)
9488 (setq todomatcher nil))
9489 (setq todomatcher (if (> (length orlist) 1)
9490 (cons 'or orlist) (car orlist))))
9492 ;; Return the string and lisp forms of the matcher
9493 (setq matcher (if todomatcher
9494 (list 'and tagsmatcher todomatcher)
9495 tagsmatcher))
9496 (cons match0 matcher)))
9498 (defun org-op-to-function (op &optional stringp)
9499 "Turn an operator into the appropriate function."
9500 (setq op
9501 (cond
9502 ((equal op "<" ) '(< string< org-time<))
9503 ((equal op ">" ) '(> org-string> org-time>))
9504 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
9505 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
9506 ((member op '("=" "==")) '(= string= org-time=))
9507 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
9508 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
9510 (defun org<> (a b) (not (= a b)))
9511 (defun org-string<= (a b) (or (string= a b) (string< a b)))
9512 (defun org-string>= (a b) (not (string< a b)))
9513 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
9514 (defun org-string<> (a b) (not (string= a b)))
9515 (defun org-time= (a b) (= (org-2ft a) (org-2ft b)))
9516 (defun org-time< (a b) (< (org-2ft a) (org-2ft b)))
9517 (defun org-time<= (a b) (<= (org-2ft a) (org-2ft b)))
9518 (defun org-time> (a b) (> (org-2ft a) (org-2ft b)))
9519 (defun org-time>= (a b) (>= (org-2ft a) (org-2ft b)))
9520 (defun org-time<> (a b) (org<> (org-2ft a) (org-2ft b)))
9521 (defun org-2ft (s)
9522 "Convert S to a floating point time.
9523 If S is already a number, just return it. If it is a string, parse
9524 it as a time string and apply `float-time' to it. f S is nil, just return 0."
9525 (cond
9526 ((numberp s) s)
9527 ((stringp s)
9528 (condition-case nil
9529 (float-time (apply 'encode-time (org-parse-time-string s)))
9530 (error 0.)))
9531 (t 0.)))
9533 (defun org-time-today ()
9534 "Time in seconds today at 0:00.
9535 Returns the float number of seconds since the beginning of the
9536 epoch to the beginning of today (00:00)."
9537 (float-time (apply 'encode-time
9538 (append '(0 0 0) (nthcdr 3 (decode-time))))))
9540 (defun org-matcher-time (s)
9541 "Interpret a time comparison value."
9542 (save-match-data
9543 (cond
9544 ((string= s "<now>") (float-time))
9545 ((string= s "<today>") (org-time-today))
9546 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
9547 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
9548 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
9549 (+ (org-time-today)
9550 (* (string-to-number (match-string 1 s))
9551 (cdr (assoc (match-string 2 s)
9552 '(("d" . 86400.0) ("w" . 604800.0)
9553 ("m" . 2678400.0) ("y" . 31557600.0)))))))
9554 (t (org-2ft s)))))
9556 (defun org-match-any-p (re list)
9557 "Does re match any element of list?"
9558 (setq list (mapcar (lambda (x) (string-match re x)) list))
9559 (delq nil list))
9561 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
9562 (defvar org-tags-overlay (org-make-overlay 1 1))
9563 (org-detach-overlay org-tags-overlay)
9565 (defun org-get-local-tags-at (&optional pos)
9566 "Get a list of tags defined in the current headline."
9567 (org-get-tags-at pos 'local))
9569 (defun org-get-local-tags ()
9570 "Get a list of tags defined in the current headline."
9571 (org-get-tags-at nil 'local))
9573 (defun org-get-tags-at (&optional pos local)
9574 "Get a list of all headline tags applicable at POS.
9575 POS defaults to point. If tags are inherited, the list contains
9576 the targets in the same sequence as the headlines appear, i.e.
9577 the tags of the current headline come last.
9578 When LOCAL is non-nil, only return tags from the current headline,
9579 ignore inherited ones."
9580 (interactive)
9581 (let (tags ltags lastpos parent)
9582 (save-excursion
9583 (save-restriction
9584 (widen)
9585 (goto-char (or pos (point)))
9586 (save-match-data
9587 (catch 'done
9588 (condition-case nil
9589 (progn
9590 (org-back-to-heading t)
9591 (while (not (equal lastpos (point)))
9592 (setq lastpos (point))
9593 (when (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
9594 (setq ltags (org-split-string
9595 (org-match-string-no-properties 1) ":"))
9596 (when parent
9597 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
9598 (setq tags (append
9599 (if parent
9600 (org-remove-uniherited-tags ltags)
9601 ltags)
9602 tags)))
9603 (or org-use-tag-inheritance (throw 'done t))
9604 (if local (throw 'done t))
9605 (org-up-heading-all 1)
9606 (setq parent t)))
9607 (error nil)))))
9608 (append (org-remove-uniherited-tags org-file-tags) tags))))
9610 (defun org-add-prop-inherited (s)
9611 (add-text-properties 0 (length s) '(inherited t) s)
9614 (defun org-toggle-tag (tag &optional onoff)
9615 "Toggle the tag TAG for the current line.
9616 If ONOFF is `on' or `off', don't toggle but set to this state."
9617 (let (res current)
9618 (save-excursion
9619 (org-back-to-heading t)
9620 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
9621 (point-at-eol) t)
9622 (progn
9623 (setq current (match-string 1))
9624 (replace-match ""))
9625 (setq current ""))
9626 (setq current (nreverse (org-split-string current ":")))
9627 (cond
9628 ((eq onoff 'on)
9629 (setq res t)
9630 (or (member tag current) (push tag current)))
9631 ((eq onoff 'off)
9632 (or (not (member tag current)) (setq current (delete tag current))))
9633 (t (if (member tag current)
9634 (setq current (delete tag current))
9635 (setq res t)
9636 (push tag current))))
9637 (end-of-line 1)
9638 (if current
9639 (progn
9640 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
9641 (org-set-tags nil t))
9642 (delete-horizontal-space))
9643 (run-hooks 'org-after-tags-change-hook))
9644 res))
9646 (defun org-align-tags-here (to-col)
9647 ;; Assumes that this is a headline
9648 (let ((pos (point)) (col (current-column)) ncol tags-l p)
9649 (beginning-of-line 1)
9650 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9651 (< pos (match-beginning 2)))
9652 (progn
9653 (setq tags-l (- (match-end 2) (match-beginning 2)))
9654 (goto-char (match-beginning 1))
9655 (insert " ")
9656 (delete-region (point) (1+ (match-beginning 2)))
9657 (setq ncol (max (1+ (current-column))
9658 (1+ col)
9659 (if (> to-col 0)
9660 to-col
9661 (- (abs to-col) tags-l))))
9662 (setq p (point))
9663 (insert (make-string (- ncol (current-column)) ?\ ))
9664 (setq ncol (current-column))
9665 (when indent-tabs-mode (tabify p (point-at-eol)))
9666 (org-move-to-column (min ncol col) t))
9667 (goto-char pos))))
9669 (defun org-set-tags-command (&optional arg just-align)
9670 "Call the set-tags command for the current entry."
9671 (interactive "P")
9672 (if (org-on-heading-p)
9673 (org-set-tags arg just-align)
9674 (save-excursion
9675 (org-back-to-heading t)
9676 (org-set-tags arg just-align))))
9678 (defun org-set-tags (&optional arg just-align)
9679 "Set the tags for the current headline.
9680 With prefix ARG, realign all tags in headings in the current buffer."
9681 (interactive "P")
9682 (let* ((re (concat "^" outline-regexp))
9683 (current (org-get-tags-string))
9684 (col (current-column))
9685 (org-setting-tags t)
9686 table current-tags inherited-tags ; computed below when needed
9687 tags p0 c0 c1 rpl)
9688 (if arg
9689 (save-excursion
9690 (goto-char (point-min))
9691 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
9692 (while (re-search-forward re nil t)
9693 (org-set-tags nil t)
9694 (end-of-line 1)))
9695 (message "All tags realigned to column %d" org-tags-column))
9696 (if just-align
9697 (setq tags current)
9698 ;; Get a new set of tags from the user
9699 (save-excursion
9700 (setq table (or org-tag-alist (org-get-buffer-tags))
9701 org-last-tags-completion-table table
9702 current-tags (org-split-string current ":")
9703 inherited-tags (nreverse
9704 (nthcdr (length current-tags)
9705 (nreverse (org-get-tags-at))))
9706 tags
9707 (if (or (eq t org-use-fast-tag-selection)
9708 (and org-use-fast-tag-selection
9709 (delq nil (mapcar 'cdr table))))
9710 (org-fast-tag-selection
9711 current-tags inherited-tags table
9712 (if org-fast-tag-selection-include-todo org-todo-key-alist))
9713 (let ((org-add-colon-after-tag-completion t))
9714 (org-trim
9715 (org-without-partial-completion
9716 (org-ido-completing-read "Tags: " 'org-tags-completion-function
9717 nil nil current 'org-tags-history)))))))
9718 (while (string-match "[-+&]+" tags)
9719 ;; No boolean logic, just a list
9720 (setq tags (replace-match ":" t t tags))))
9722 (if (string-match "\\`[\t ]*\\'" tags)
9723 (setq tags "")
9724 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
9725 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
9727 ;; Insert new tags at the correct column
9728 (beginning-of-line 1)
9729 (cond
9730 ((and (equal current "") (equal tags "")))
9731 ((re-search-forward
9732 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
9733 (point-at-eol) t)
9734 (if (equal tags "")
9735 (setq rpl "")
9736 (goto-char (match-beginning 0))
9737 (setq c0 (current-column) p0 (point)
9738 c1 (max (1+ c0) (if (> org-tags-column 0)
9739 org-tags-column
9740 (- (- org-tags-column) (length tags))))
9741 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
9742 (replace-match rpl t t)
9743 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
9744 tags)
9745 (t (error "Tags alignment failed")))
9746 (org-move-to-column col)
9747 (unless just-align
9748 (run-hooks 'org-after-tags-change-hook)))))
9750 (defun org-change-tag-in-region (beg end tag off)
9751 "Add or remove TAG for each entry in the region.
9752 This works in the agenda, and also in an org-mode buffer."
9753 (interactive
9754 (list (region-beginning) (region-end)
9755 (let ((org-last-tags-completion-table
9756 (if (org-mode-p)
9757 (org-get-buffer-tags)
9758 (org-global-tags-completion-table))))
9759 (org-ido-completing-read
9760 "Tag: " 'org-tags-completion-function nil nil nil
9761 'org-tags-history))
9762 (progn
9763 (message "[s]et or [r]emove? ")
9764 (equal (read-char-exclusive) ?r))))
9765 (if (fboundp 'deactivate-mark) (deactivate-mark))
9766 (let ((agendap (equal major-mode 'org-agenda-mode))
9767 l1 l2 m buf pos newhead (cnt 0))
9768 (goto-char end)
9769 (setq l2 (1- (org-current-line)))
9770 (goto-char beg)
9771 (setq l1 (org-current-line))
9772 (loop for l from l1 to l2 do
9773 (goto-line l)
9774 (setq m (get-text-property (point) 'org-hd-marker))
9775 (when (or (and (org-mode-p) (org-on-heading-p))
9776 (and agendap m))
9777 (setq buf (if agendap (marker-buffer m) (current-buffer))
9778 pos (if agendap m (point)))
9779 (with-current-buffer buf
9780 (save-excursion
9781 (save-restriction
9782 (goto-char pos)
9783 (setq cnt (1+ cnt))
9784 (org-toggle-tag tag (if off 'off 'on))
9785 (setq newhead (org-get-heading)))))
9786 (and agendap (org-agenda-change-all-lines newhead m))))
9787 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
9789 (defun org-tags-completion-function (string predicate &optional flag)
9790 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
9791 (confirm (lambda (x) (stringp (car x)))))
9792 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
9793 (setq s1 (match-string 1 string)
9794 s2 (match-string 2 string))
9795 (setq s1 "" s2 string))
9796 (cond
9797 ((eq flag nil)
9798 ;; try completion
9799 (setq rtn (try-completion s2 ctable confirm))
9800 (if (stringp rtn)
9801 (setq rtn
9802 (concat s1 s2 (substring rtn (length s2))
9803 (if (and org-add-colon-after-tag-completion
9804 (assoc rtn ctable))
9805 ":" ""))))
9806 rtn)
9807 ((eq flag t)
9808 ;; all-completions
9809 (all-completions s2 ctable confirm)
9811 ((eq flag 'lambda)
9812 ;; exact match?
9813 (assoc s2 ctable)))
9816 (defun org-fast-tag-insert (kwd tags face &optional end)
9817 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
9818 (insert (format "%-12s" (concat kwd ":"))
9819 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
9820 (or end "")))
9822 (defun org-fast-tag-show-exit (flag)
9823 (save-excursion
9824 (goto-line 3)
9825 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
9826 (replace-match ""))
9827 (when flag
9828 (end-of-line 1)
9829 (org-move-to-column (- (window-width) 19) t)
9830 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
9832 (defun org-set-current-tags-overlay (current prefix)
9833 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
9834 (if (featurep 'xemacs)
9835 (org-overlay-display org-tags-overlay (concat prefix s)
9836 'secondary-selection)
9837 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
9838 (org-overlay-display org-tags-overlay (concat prefix s)))))
9840 (defun org-fast-tag-selection (current inherited table &optional todo-table)
9841 "Fast tag selection with single keys.
9842 CURRENT is the current list of tags in the headline, INHERITED is the
9843 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
9844 possibly with grouping information. TODO-TABLE is a similar table with
9845 TODO keywords, should these have keys assigned to them.
9846 If the keys are nil, a-z are automatically assigned.
9847 Returns the new tags string, or nil to not change the current settings."
9848 (let* ((fulltable (append table todo-table))
9849 (maxlen (apply 'max (mapcar
9850 (lambda (x)
9851 (if (stringp (car x)) (string-width (car x)) 0))
9852 fulltable)))
9853 (buf (current-buffer))
9854 (expert (eq org-fast-tag-selection-single-key 'expert))
9855 (buffer-tags nil)
9856 (fwidth (+ maxlen 3 1 3))
9857 (ncol (/ (- (window-width) 4) fwidth))
9858 (i-face 'org-done)
9859 (c-face 'org-todo)
9860 tg cnt e c char c1 c2 ntable tbl rtn
9861 ov-start ov-end ov-prefix
9862 (exit-after-next org-fast-tag-selection-single-key)
9863 (done-keywords org-done-keywords)
9864 groups ingroup)
9865 (save-excursion
9866 (beginning-of-line 1)
9867 (if (looking-at
9868 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9869 (setq ov-start (match-beginning 1)
9870 ov-end (match-end 1)
9871 ov-prefix "")
9872 (setq ov-start (1- (point-at-eol))
9873 ov-end (1+ ov-start))
9874 (skip-chars-forward "^\n\r")
9875 (setq ov-prefix
9876 (concat
9877 (buffer-substring (1- (point)) (point))
9878 (if (> (current-column) org-tags-column)
9880 (make-string (- org-tags-column (current-column)) ?\ ))))))
9881 (org-move-overlay org-tags-overlay ov-start ov-end)
9882 (save-window-excursion
9883 (if expert
9884 (set-buffer (get-buffer-create " *Org tags*"))
9885 (delete-other-windows)
9886 (split-window-vertically)
9887 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
9888 (erase-buffer)
9889 (org-set-local 'org-done-keywords done-keywords)
9890 (org-fast-tag-insert "Inherited" inherited i-face "\n")
9891 (org-fast-tag-insert "Current" current c-face "\n\n")
9892 (org-fast-tag-show-exit exit-after-next)
9893 (org-set-current-tags-overlay current ov-prefix)
9894 (setq tbl fulltable char ?a cnt 0)
9895 (while (setq e (pop tbl))
9896 (cond
9897 ((equal e '(:startgroup))
9898 (push '() groups) (setq ingroup t)
9899 (when (not (= cnt 0))
9900 (setq cnt 0)
9901 (insert "\n"))
9902 (insert "{ "))
9903 ((equal e '(:endgroup))
9904 (setq ingroup nil cnt 0)
9905 (insert "}\n"))
9907 (setq tg (car e) c2 nil)
9908 (if (cdr e)
9909 (setq c (cdr e))
9910 ;; automatically assign a character.
9911 (setq c1 (string-to-char
9912 (downcase (substring
9913 tg (if (= (string-to-char tg) ?@) 1 0)))))
9914 (if (or (rassoc c1 ntable) (rassoc c1 table))
9915 (while (or (rassoc char ntable) (rassoc char table))
9916 (setq char (1+ char)))
9917 (setq c2 c1))
9918 (setq c (or c2 char)))
9919 (if ingroup (push tg (car groups)))
9920 (setq tg (org-add-props tg nil 'face
9921 (cond
9922 ((not (assoc tg table))
9923 (org-get-todo-face tg))
9924 ((member tg current) c-face)
9925 ((member tg inherited) i-face)
9926 (t nil))))
9927 (if (and (= cnt 0) (not ingroup)) (insert " "))
9928 (insert "[" c "] " tg (make-string
9929 (- fwidth 4 (length tg)) ?\ ))
9930 (push (cons tg c) ntable)
9931 (when (= (setq cnt (1+ cnt)) ncol)
9932 (insert "\n")
9933 (if ingroup (insert " "))
9934 (setq cnt 0)))))
9935 (setq ntable (nreverse ntable))
9936 (insert "\n")
9937 (goto-char (point-min))
9938 (if (not expert) (org-fit-window-to-buffer))
9939 (setq rtn
9940 (catch 'exit
9941 (while t
9942 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
9943 (if groups " [!] no groups" " [!]groups")
9944 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
9945 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9946 (cond
9947 ((= c ?\r) (throw 'exit t))
9948 ((= c ?!)
9949 (setq groups (not groups))
9950 (goto-char (point-min))
9951 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
9952 ((= c ?\C-c)
9953 (if (not expert)
9954 (org-fast-tag-show-exit
9955 (setq exit-after-next (not exit-after-next)))
9956 (setq expert nil)
9957 (delete-other-windows)
9958 (split-window-vertically)
9959 (org-switch-to-buffer-other-window " *Org tags*")
9960 (org-fit-window-to-buffer)))
9961 ((or (= c ?\C-g)
9962 (and (= c ?q) (not (rassoc c ntable))))
9963 (org-detach-overlay org-tags-overlay)
9964 (setq quit-flag t))
9965 ((= c ?\ )
9966 (setq current nil)
9967 (if exit-after-next (setq exit-after-next 'now)))
9968 ((= c ?\t)
9969 (condition-case nil
9970 (setq tg (org-ido-completing-read
9971 "Tag: "
9972 (or buffer-tags
9973 (with-current-buffer buf
9974 (org-get-buffer-tags)))))
9975 (quit (setq tg "")))
9976 (when (string-match "\\S-" tg)
9977 (add-to-list 'buffer-tags (list tg))
9978 (if (member tg current)
9979 (setq current (delete tg current))
9980 (push tg current)))
9981 (if exit-after-next (setq exit-after-next 'now)))
9982 ((setq e (rassoc c todo-table) tg (car e))
9983 (with-current-buffer buf
9984 (save-excursion (org-todo tg)))
9985 (if exit-after-next (setq exit-after-next 'now)))
9986 ((setq e (rassoc c ntable) tg (car e))
9987 (if (member tg current)
9988 (setq current (delete tg current))
9989 (loop for g in groups do
9990 (if (member tg g)
9991 (mapc (lambda (x)
9992 (setq current (delete x current)))
9993 g)))
9994 (push tg current))
9995 (if exit-after-next (setq exit-after-next 'now))))
9997 ;; Create a sorted list
9998 (setq current
9999 (sort current
10000 (lambda (a b)
10001 (assoc b (cdr (memq (assoc a ntable) ntable))))))
10002 (if (eq exit-after-next 'now) (throw 'exit t))
10003 (goto-char (point-min))
10004 (beginning-of-line 2)
10005 (delete-region (point) (point-at-eol))
10006 (org-fast-tag-insert "Current" current c-face)
10007 (org-set-current-tags-overlay current ov-prefix)
10008 (while (re-search-forward
10009 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
10010 (setq tg (match-string 1))
10011 (add-text-properties
10012 (match-beginning 1) (match-end 1)
10013 (list 'face
10014 (cond
10015 ((member tg current) c-face)
10016 ((member tg inherited) i-face)
10017 (t (get-text-property (match-beginning 1) 'face))))))
10018 (goto-char (point-min)))))
10019 (org-detach-overlay org-tags-overlay)
10020 (if rtn
10021 (mapconcat 'identity current ":")
10022 nil))))
10024 (defun org-get-tags-string ()
10025 "Get the TAGS string in the current headline."
10026 (unless (org-on-heading-p t)
10027 (error "Not on a heading"))
10028 (save-excursion
10029 (beginning-of-line 1)
10030 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10031 (org-match-string-no-properties 1)
10032 "")))
10034 (defun org-get-tags ()
10035 "Get the list of tags specified in the current headline."
10036 (org-split-string (org-get-tags-string) ":"))
10038 (defun org-get-buffer-tags ()
10039 "Get a table of all tags used in the buffer, for completion."
10040 (let (tags)
10041 (save-excursion
10042 (goto-char (point-min))
10043 (while (re-search-forward
10044 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
10045 (when (equal (char-after (point-at-bol 0)) ?*)
10046 (mapc (lambda (x) (add-to-list 'tags x))
10047 (org-split-string (org-match-string-no-properties 1) ":")))))
10048 (mapcar 'list tags)))
10050 ;;;; The mapping API
10052 ;;;###autoload
10053 (defun org-map-entries (func &optional match scope &rest skip)
10054 "Call FUNC at each headline selected by MATCH in SCOPE.
10056 FUNC is a function or a lisp form. The function will be called without
10057 arguments, with the cursor positioned at the beginning of the headline.
10058 The return values of all calls to the function will be collected and
10059 returned as a list.
10061 MATCH is a tags/property/todo match as it is used in the agenda tags view.
10062 Only headlines that are matched by this query will be considered during
10063 the iteration. When MATCH is nil or t, all headlines will be
10064 visited by the iteration.
10066 SCOPE determines the scope of this command. It can be any of:
10068 nil The current buffer, respecting the restriction if any
10069 tree The subtree started with the entry at point
10070 file The current buffer, without restriction
10071 file-with-archives
10072 The current buffer, and any archives associated with it
10073 agenda All agenda files
10074 agenda-with-archives
10075 All agenda files with any archive files associated with them
10076 \(file1 file2 ...)
10077 If this is a list, all files in the list will be scanned
10079 The remaining args are treated as settings for the skipping facilities of
10080 the scanner. The following items can be given here:
10082 archive skip trees with the archive tag.
10083 comment skip trees with the COMMENT keyword
10084 function or Emacs Lisp form:
10085 will be used as value for `org-agenda-skip-function', so whenever
10086 the the function returns t, FUNC will not be called for that
10087 entry and search will continue from the point where the
10088 function leaves it."
10089 (let* ((org-agenda-archives-mode nil) ; just to make sure
10090 (org-agenda-skip-archived-trees (memq 'archive skip))
10091 (org-agenda-skip-comment-trees (memq 'comment skip))
10092 (org-agenda-skip-function
10093 (car (org-delete-all '(comment archive) skip)))
10094 (org-tags-match-list-sublevels t)
10095 matcher pos file res
10096 org-todo-keywords-for-agenda
10097 org-done-keywords-for-agenda
10098 org-todo-keyword-alist-for-agenda
10099 org-tag-alist-for-agenda)
10101 (cond
10102 ((eq match t) (setq matcher t))
10103 ((eq match nil) (setq matcher t))
10104 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
10106 (when (eq scope 'tree)
10107 (org-back-to-heading t)
10108 (org-narrow-to-subtree)
10109 (setq scope nil))
10111 (if (not scope)
10112 (progn
10113 (org-prepare-agenda-buffers
10114 (list (buffer-file-name (current-buffer))))
10115 (org-scan-tags func matcher))
10116 ;; Get the right scope
10117 (setq pos (point))
10118 (cond
10119 ((and scope (listp scope) (symbolp (car scope)))
10120 (setq scope (eval scope)))
10121 ((eq scope 'agenda)
10122 (setq scope (org-agenda-files t)))
10123 ((eq scope 'agenda-with-archives)
10124 (setq scope (org-agenda-files t))
10125 (setq scope (org-add-archive-files scope)))
10126 ((eq scope 'file)
10127 (setq scope (list (buffer-file-name))))
10128 ((eq scope 'file-with-archives)
10129 (setq scope (org-add-archive-files (list (buffer-file-name))))))
10130 (org-prepare-agenda-buffers scope)
10131 (while (setq file (pop scope))
10132 (with-current-buffer (org-find-base-buffer-visiting file)
10133 (save-excursion
10134 (save-restriction
10135 (widen)
10136 (goto-char (point-min))
10137 (setq res (append res (org-scan-tags func matcher)))))))
10138 res)))
10140 ;;;; Properties
10142 ;;; Setting and retrieving properties
10144 (defconst org-special-properties
10145 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
10146 "TIMESTAMP" "TIMESTAMP_IA")
10147 "The special properties valid in Org-mode.
10149 These are properties that are not defined in the property drawer,
10150 but in some other way.")
10152 (defconst org-default-properties
10153 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
10154 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
10155 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
10156 "EXPORT_FILE_NAME" "EXPORT_TITLE")
10157 "Some properties that are used by Org-mode for various purposes.
10158 Being in this list makes sure that they are offered for completion.")
10160 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
10161 "Regular expression matching the first line of a property drawer.")
10163 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
10164 "Regular expression matching the first line of a property drawer.")
10166 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
10167 "Regular expression matching the first line of a property drawer.")
10169 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
10170 "Regular expression matching the first line of a property drawer.")
10172 (defconst org-property-drawer-re
10173 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
10174 org-property-end-re "\\)\n?")
10175 "Matches an entire property drawer.")
10177 (defconst org-clock-drawer-re
10178 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
10179 org-property-end-re "\\)\n?")
10180 "Matches an entire clock drawer.")
10182 (defun org-property-action ()
10183 "Do an action on properties."
10184 (interactive)
10185 (let (c)
10186 (org-at-property-p)
10187 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
10188 (setq c (read-char-exclusive))
10189 (cond
10190 ((equal c ?s)
10191 (call-interactively 'org-set-property))
10192 ((equal c ?d)
10193 (call-interactively 'org-delete-property))
10194 ((equal c ?D)
10195 (call-interactively 'org-delete-property-globally))
10196 ((equal c ?c)
10197 (call-interactively 'org-compute-property-at-point))
10198 (t (error "No such property action %c" c)))))
10200 (defun org-at-property-p ()
10201 "Is the cursor in a property line?"
10202 ;; FIXME: Does not check if we are actually in the drawer.
10203 ;; FIXME: also returns true on any drawers.....
10204 ;; This is used by C-c C-c for property action.
10205 (save-excursion
10206 (beginning-of-line 1)
10207 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
10209 (defun org-get-property-block (&optional beg end force)
10210 "Return the (beg . end) range of the body of the property drawer.
10211 BEG and END can be beginning and end of subtree, if not given
10212 they will be found.
10213 If the drawer does not exist and FORCE is non-nil, create the drawer."
10214 (catch 'exit
10215 (save-excursion
10216 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
10217 (end (or end (progn (outline-next-heading) (point)))))
10218 (goto-char beg)
10219 (if (re-search-forward org-property-start-re end t)
10220 (setq beg (1+ (match-end 0)))
10221 (if force
10222 (save-excursion
10223 (org-insert-property-drawer)
10224 (setq end (progn (outline-next-heading) (point))))
10225 (throw 'exit nil))
10226 (goto-char beg)
10227 (if (re-search-forward org-property-start-re end t)
10228 (setq beg (1+ (match-end 0)))))
10229 (if (re-search-forward org-property-end-re end t)
10230 (setq end (match-beginning 0))
10231 (or force (throw 'exit nil))
10232 (goto-char beg)
10233 (setq end beg)
10234 (org-indent-line-function)
10235 (insert ":END:\n"))
10236 (cons beg end)))))
10238 (defun org-entry-properties (&optional pom which)
10239 "Get all properties of the entry at point-or-marker POM.
10240 This includes the TODO keyword, the tags, time strings for deadline,
10241 scheduled, and clocking, and any additional properties defined in the
10242 entry. The return value is an alist, keys may occur multiple times
10243 if the property key was used several times.
10244 POM may also be nil, in which case the current entry is used.
10245 If WHICH is nil or `all', get all properties. If WHICH is
10246 `special' or `standard', only get that subclass."
10247 (setq which (or which 'all))
10248 (org-with-point-at pom
10249 (let ((clockstr (substring org-clock-string 0 -1))
10250 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
10251 beg end range props sum-props key value string clocksum)
10252 (save-excursion
10253 (when (condition-case nil (org-back-to-heading t) (error nil))
10254 (setq beg (point))
10255 (setq sum-props (get-text-property (point) 'org-summaries))
10256 (setq clocksum (get-text-property (point) :org-clock-minutes))
10257 (outline-next-heading)
10258 (setq end (point))
10259 (when (memq which '(all special))
10260 ;; Get the special properties, like TODO and tags
10261 (goto-char beg)
10262 (when (and (looking-at org-todo-line-regexp) (match-end 2))
10263 (push (cons "TODO" (org-match-string-no-properties 2)) props))
10264 (when (looking-at org-priority-regexp)
10265 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
10266 (when (and (setq value (org-get-tags-string))
10267 (string-match "\\S-" value))
10268 (push (cons "TAGS" value) props))
10269 (when (setq value (org-get-tags-at))
10270 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
10271 props))
10272 (while (re-search-forward org-maybe-keyword-time-regexp end t)
10273 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
10274 string (if (equal key clockstr)
10275 (org-no-properties
10276 (org-trim
10277 (buffer-substring
10278 (match-beginning 3) (goto-char (point-at-eol)))))
10279 (substring (org-match-string-no-properties 3) 1 -1)))
10280 (unless key
10281 (if (= (char-after (match-beginning 3)) ?\[)
10282 (setq key "TIMESTAMP_IA")
10283 (setq key "TIMESTAMP")))
10284 (when (or (equal key clockstr) (not (assoc key props)))
10285 (push (cons key string) props)))
10289 (when (memq which '(all standard))
10290 ;; Get the standard properties, like :PORP: ...
10291 (setq range (org-get-property-block beg end))
10292 (when range
10293 (goto-char (car range))
10294 (while (re-search-forward
10295 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
10296 (cdr range) t)
10297 (setq key (org-match-string-no-properties 1)
10298 value (org-trim (or (org-match-string-no-properties 2) "")))
10299 (unless (member key excluded)
10300 (push (cons key (or value "")) props)))))
10301 (if clocksum
10302 (push (cons "CLOCKSUM"
10303 (org-columns-number-to-string (/ (float clocksum) 60.)
10304 'add_times))
10305 props))
10306 (unless (assoc "CATEGORY" props)
10307 (setq value (or (org-get-category)
10308 (progn (org-refresh-category-properties)
10309 (org-get-category))))
10310 (push (cons "CATEGORY" value) props))
10311 (append sum-props (nreverse props)))))))
10313 (defun org-entry-get (pom property &optional inherit)
10314 "Get value of PROPERTY for entry at point-or-marker POM.
10315 If INHERIT is non-nil and the entry does not have the property,
10316 then also check higher levels of the hierarchy.
10317 If INHERIT is the symbol `selective', use inheritance only if the setting
10318 in `org-use-property-inheritance' selects PROPERTY for inheritance.
10319 If the property is present but empty, the return value is the empty string.
10320 If the property is not present at all, nil is returned."
10321 (org-with-point-at pom
10322 (if (and inherit (if (eq inherit 'selective)
10323 (org-property-inherit-p property)
10325 (org-entry-get-with-inheritance property)
10326 (if (member property org-special-properties)
10327 ;; We need a special property. Use brute force, get all properties.
10328 (cdr (assoc property (org-entry-properties nil 'special)))
10329 (let ((range (org-get-property-block)))
10330 (if (and range
10331 (goto-char (car range))
10332 (re-search-forward
10333 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
10334 (cdr range) t))
10335 ;; Found the property, return it.
10336 (if (match-end 1)
10337 (org-match-string-no-properties 1)
10338 "")))))))
10340 (defun org-property-or-variable-value (var &optional inherit)
10341 "Check if there is a property fixing the value of VAR.
10342 If yes, return this value. If not, return the current value of the variable."
10343 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
10344 (if (and prop (stringp prop) (string-match "\\S-" prop))
10345 (read prop)
10346 (symbol-value var))))
10348 (defun org-entry-delete (pom property)
10349 "Delete the property PROPERTY from entry at point-or-marker POM."
10350 (org-with-point-at pom
10351 (if (member property org-special-properties)
10352 nil ; cannot delete these properties.
10353 (let ((range (org-get-property-block)))
10354 (if (and range
10355 (goto-char (car range))
10356 (re-search-forward
10357 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
10358 (cdr range) t))
10359 (progn
10360 (delete-region (match-beginning 0) (1+ (point-at-eol)))
10362 nil)))))
10364 ;; Multi-values properties are properties that contain multiple values
10365 ;; These values are assumed to be single words, separated by whitespace.
10366 (defun org-entry-add-to-multivalued-property (pom property value)
10367 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
10368 (let* ((old (org-entry-get pom property))
10369 (values (and old (org-split-string old "[ \t]"))))
10370 (setq value (org-entry-protect-space value))
10371 (unless (member value values)
10372 (setq values (cons value values))
10373 (org-entry-put pom property
10374 (mapconcat 'identity values " ")))))
10376 (defun org-entry-remove-from-multivalued-property (pom property value)
10377 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
10378 (let* ((old (org-entry-get pom property))
10379 (values (and old (org-split-string old "[ \t]"))))
10380 (setq value (org-entry-protect-space value))
10381 (when (member value values)
10382 (setq values (delete value values))
10383 (org-entry-put pom property
10384 (mapconcat 'identity values " ")))))
10386 (defun org-entry-member-in-multivalued-property (pom property value)
10387 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
10388 (let* ((old (org-entry-get pom property))
10389 (values (and old (org-split-string old "[ \t]"))))
10390 (setq value (org-entry-protect-space value))
10391 (member value values)))
10393 (defun org-entry-get-multivalued-property (pom property)
10394 "Return a list of values in a multivalued property."
10395 (let* ((value (org-entry-get pom property))
10396 (values (and value (org-split-string value "[ \t]"))))
10397 (mapcar 'org-entry-restore-space values)))
10399 (defun org-entry-put-multivalued-property (pom property &rest values)
10400 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
10401 VALUES should be a list of strings. Spaces will be protected."
10402 (org-entry-put pom property
10403 (mapconcat 'org-entry-protect-space values " "))
10404 (let* ((value (org-entry-get pom property))
10405 (values (and value (org-split-string value "[ \t]"))))
10406 (mapcar 'org-entry-restore-space values)))
10408 (defun org-entry-protect-space (s)
10409 "Protect spaces and newline in string S."
10410 (while (string-match " " s)
10411 (setq s (replace-match "%20" t t s)))
10412 (while (string-match "\n" s)
10413 (setq s (replace-match "%0A" t t s)))
10416 (defun org-entry-restore-space (s)
10417 "Restore spaces and newline in string S."
10418 (while (string-match "%20" s)
10419 (setq s (replace-match " " t t s)))
10420 (while (string-match "%0A" s)
10421 (setq s (replace-match "\n" t t s)))
10424 (defvar org-entry-property-inherited-from (make-marker)
10425 "Marker pointing to the entry from where a property was inherited.
10426 Each call to `org-entry-get-with-inheritance' will set this marker to the
10427 location of the entry where the inheritance search matched. If there was
10428 no match, the marker will point nowhere.
10429 Note that also `org-entry-get' calls this function, if the INHERIT flag
10430 is set.")
10432 (defun org-entry-get-with-inheritance (property)
10433 "Get entry property, and search higher levels if not present."
10434 (move-marker org-entry-property-inherited-from nil)
10435 (let (tmp)
10436 (save-excursion
10437 (save-restriction
10438 (widen)
10439 (catch 'ex
10440 (while t
10441 (when (setq tmp (org-entry-get nil property))
10442 (org-back-to-heading t)
10443 (move-marker org-entry-property-inherited-from (point))
10444 (throw 'ex tmp))
10445 (or (org-up-heading-safe) (throw 'ex nil)))))
10446 (or tmp
10447 (cdr (assoc property org-file-properties))
10448 (cdr (assoc property org-global-properties))
10449 (cdr (assoc property org-global-properties-fixed))))))
10451 (defun org-entry-put (pom property value)
10452 "Set PROPERTY to VALUE for entry at point-or-marker POM."
10453 (org-with-point-at pom
10454 (org-back-to-heading t)
10455 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
10456 range)
10457 (cond
10458 ((equal property "TODO")
10459 (when (and (stringp value) (string-match "\\S-" value)
10460 (not (member value org-todo-keywords-1)))
10461 (error "\"%s\" is not a valid TODO state" value))
10462 (if (or (not value)
10463 (not (string-match "\\S-" value)))
10464 (setq value 'none))
10465 (org-todo value)
10466 (org-set-tags nil 'align))
10467 ((equal property "PRIORITY")
10468 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
10469 (string-to-char value) ?\ ))
10470 (org-set-tags nil 'align))
10471 ((equal property "SCHEDULED")
10472 (if (re-search-forward org-scheduled-time-regexp end t)
10473 (cond
10474 ((eq value 'earlier) (org-timestamp-change -1 'day))
10475 ((eq value 'later) (org-timestamp-change 1 'day))
10476 (t (call-interactively 'org-schedule)))
10477 (call-interactively 'org-schedule)))
10478 ((equal property "DEADLINE")
10479 (if (re-search-forward org-deadline-time-regexp end t)
10480 (cond
10481 ((eq value 'earlier) (org-timestamp-change -1 'day))
10482 ((eq value 'later) (org-timestamp-change 1 'day))
10483 (t (call-interactively 'org-deadline)))
10484 (call-interactively 'org-deadline)))
10485 ((member property org-special-properties)
10486 (error "The %s property can not yet be set with `org-entry-put'"
10487 property))
10488 (t ; a non-special property
10489 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
10490 (setq range (org-get-property-block beg end 'force))
10491 (goto-char (car range))
10492 (if (re-search-forward
10493 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
10494 (progn
10495 (delete-region (match-beginning 1) (match-end 1))
10496 (goto-char (match-beginning 1)))
10497 (goto-char (cdr range))
10498 (insert "\n")
10499 (backward-char 1)
10500 (org-indent-line-function)
10501 (insert ":" property ":"))
10502 (and value (insert " " value))
10503 (org-indent-line-function)))))))
10505 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
10506 "Get all property keys in the current buffer.
10507 With INCLUDE-SPECIALS, also list the special properties that reflect things
10508 like tags and TODO state.
10509 With INCLUDE-DEFAULTS, also include properties that has special meaning
10510 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
10511 With INCLUDE-COLUMNS, also include property names given in COLUMN
10512 formats in the current buffer."
10513 (let (rtn range cfmt cols s p)
10514 (save-excursion
10515 (save-restriction
10516 (widen)
10517 (goto-char (point-min))
10518 (while (re-search-forward org-property-start-re nil t)
10519 (setq range (org-get-property-block))
10520 (goto-char (car range))
10521 (while (re-search-forward
10522 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
10523 (cdr range) t)
10524 (add-to-list 'rtn (org-match-string-no-properties 1)))
10525 (outline-next-heading))))
10527 (when include-specials
10528 (setq rtn (append org-special-properties rtn)))
10530 (when include-defaults
10531 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
10533 (when include-columns
10534 (save-excursion
10535 (save-restriction
10536 (widen)
10537 (goto-char (point-min))
10538 (while (re-search-forward
10539 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
10540 nil t)
10541 (setq cfmt (match-string 2) s 0)
10542 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
10543 cfmt s)
10544 (setq s (match-end 0)
10545 p (match-string 1 cfmt))
10546 (unless (or (equal p "ITEM")
10547 (member p org-special-properties))
10548 (add-to-list 'rtn (match-string 1 cfmt))))))))
10550 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
10552 (defun org-property-values (key)
10553 "Return a list of all values of property KEY."
10554 (save-excursion
10555 (save-restriction
10556 (widen)
10557 (goto-char (point-min))
10558 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
10559 values)
10560 (while (re-search-forward re nil t)
10561 (add-to-list 'values (org-trim (match-string 1))))
10562 (delete "" values)))))
10564 (defun org-insert-property-drawer ()
10565 "Insert a property drawer into the current entry."
10566 (interactive)
10567 (org-back-to-heading t)
10568 (looking-at outline-regexp)
10569 (let ((indent (- (match-end 0)(match-beginning 0)))
10570 (beg (point))
10571 (re (concat "^[ \t]*" org-keyword-time-regexp))
10572 end hiddenp)
10573 (outline-next-heading)
10574 (setq end (point))
10575 (goto-char beg)
10576 (while (re-search-forward re end t))
10577 (setq hiddenp (org-invisible-p))
10578 (end-of-line 1)
10579 (and (equal (char-after) ?\n) (forward-char 1))
10580 (while (looking-at "^[ \t]*\\(:CLOCK:\\|CLOCK\\|:END:\\)")
10581 (beginning-of-line 2))
10582 (org-skip-over-state-notes)
10583 (skip-chars-backward " \t\n\r")
10584 (if (eq (char-before) ?*) (forward-char 1))
10585 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
10586 (beginning-of-line 0)
10587 (org-indent-to-column indent)
10588 (beginning-of-line 2)
10589 (org-indent-to-column indent)
10590 (beginning-of-line 0)
10591 (if hiddenp
10592 (save-excursion
10593 (org-back-to-heading t)
10594 (hide-entry))
10595 (org-flag-drawer t))))
10597 (defun org-set-property (property value)
10598 "In the current entry, set PROPERTY to VALUE.
10599 When called interactively, this will prompt for a property name, offering
10600 completion on existing and default properties. And then it will prompt
10601 for a value, offering completion either on allowed values (via an inherited
10602 xxx_ALL property) or on existing values in other instances of this property
10603 in the current file."
10604 (interactive
10605 (let* ((completion-ignore-case t)
10606 (keys (org-buffer-property-keys nil t t))
10607 (prop0 (org-ido-completing-read "Property: " (mapcar 'list keys)))
10608 (prop (if (member prop0 keys)
10609 prop0
10610 (or (cdr (assoc (downcase prop0)
10611 (mapcar (lambda (x) (cons (downcase x) x))
10612 keys)))
10613 prop0)))
10614 (cur (org-entry-get nil prop))
10615 (allowed (org-property-get-allowed-values nil prop 'table))
10616 (existing (mapcar 'list (org-property-values prop)))
10617 (val (if allowed
10618 (org-completing-read "Value: " allowed nil 'req-match)
10619 (org-completing-read
10620 (concat "Value" (if (and cur (string-match "\\S-" cur))
10621 (concat "[" cur "]") "")
10622 ": ")
10623 existing nil nil "" nil cur))))
10624 (list prop (if (equal val "") cur val))))
10625 (unless (equal (org-entry-get nil property) value)
10626 (org-entry-put nil property value)))
10628 (defun org-delete-property (property)
10629 "In the current entry, delete PROPERTY."
10630 (interactive
10631 (let* ((completion-ignore-case t)
10632 (prop (org-ido-completing-read
10633 "Property: " (org-entry-properties nil 'standard))))
10634 (list prop)))
10635 (message "Property %s %s" property
10636 (if (org-entry-delete nil property)
10637 "deleted"
10638 "was not present in the entry")))
10640 (defun org-delete-property-globally (property)
10641 "Remove PROPERTY globally, from all entries."
10642 (interactive
10643 (let* ((completion-ignore-case t)
10644 (prop (org-ido-completing-read
10645 "Globally remove property: "
10646 (mapcar 'list (org-buffer-property-keys)))))
10647 (list prop)))
10648 (save-excursion
10649 (save-restriction
10650 (widen)
10651 (goto-char (point-min))
10652 (let ((cnt 0))
10653 (while (re-search-forward
10654 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
10655 nil t)
10656 (setq cnt (1+ cnt))
10657 (replace-match ""))
10658 (message "Property \"%s\" removed from %d entries" property cnt)))))
10660 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
10662 (defun org-compute-property-at-point ()
10663 "Compute the property at point.
10664 This looks for an enclosing column format, extracts the operator and
10665 then applies it to the property in the column format's scope."
10666 (interactive)
10667 (unless (org-at-property-p)
10668 (error "Not at a property"))
10669 (let ((prop (org-match-string-no-properties 2)))
10670 (org-columns-get-format-and-top-level)
10671 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
10672 (error "No operator defined for property %s" prop))
10673 (org-columns-compute prop)))
10675 (defun org-property-get-allowed-values (pom property &optional table)
10676 "Get allowed values for the property PROPERTY.
10677 When TABLE is non-nil, return an alist that can directly be used for
10678 completion."
10679 (let (vals)
10680 (cond
10681 ((equal property "TODO")
10682 (setq vals (org-with-point-at pom
10683 (append org-todo-keywords-1 '("")))))
10684 ((equal property "PRIORITY")
10685 (let ((n org-lowest-priority))
10686 (while (>= n org-highest-priority)
10687 (push (char-to-string n) vals)
10688 (setq n (1- n)))))
10689 ((member property org-special-properties))
10691 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
10693 (when (and vals (string-match "\\S-" vals))
10694 (setq vals (car (read-from-string (concat "(" vals ")"))))
10695 (setq vals (mapcar (lambda (x)
10696 (cond ((stringp x) x)
10697 ((numberp x) (number-to-string x))
10698 ((symbolp x) (symbol-name x))
10699 (t "???")))
10700 vals)))))
10701 (if table (mapcar 'list vals) vals)))
10703 (defun org-property-previous-allowed-value (&optional previous)
10704 "Switch to the next allowed value for this property."
10705 (interactive)
10706 (org-property-next-allowed-value t))
10708 (defun org-property-next-allowed-value (&optional previous)
10709 "Switch to the next allowed value for this property."
10710 (interactive)
10711 (unless (org-at-property-p)
10712 (error "Not at a property"))
10713 (let* ((key (match-string 2))
10714 (value (match-string 3))
10715 (allowed (or (org-property-get-allowed-values (point) key)
10716 (and (member value '("[ ]" "[-]" "[X]"))
10717 '("[ ]" "[X]"))))
10718 nval)
10719 (unless allowed
10720 (error "Allowed values for this property have not been defined"))
10721 (if previous (setq allowed (reverse allowed)))
10722 (if (member value allowed)
10723 (setq nval (car (cdr (member value allowed)))))
10724 (setq nval (or nval (car allowed)))
10725 (if (equal nval value)
10726 (error "Only one allowed value for this property"))
10727 (org-at-property-p)
10728 (replace-match (concat " :" key ": " nval) t t)
10729 (org-indent-line-function)
10730 (beginning-of-line 1)
10731 (skip-chars-forward " \t")))
10733 (defun org-find-entry-with-id (ident)
10734 "Locate the entry that contains the ID property with exact value IDENT.
10735 IDENT can be a string, a symbol or a number, this function will search for
10736 the string representation of it.
10737 Return the position where this entry starts, or nil if there is no such entry."
10738 (interactive "sID: ")
10739 (let ((id (cond
10740 ((stringp ident) ident)
10741 ((symbol-name ident) (symbol-name ident))
10742 ((numberp ident) (number-to-string ident))
10743 (t (error "IDENT %s must be a string, symbol or number" ident))))
10744 (case-fold-search nil))
10745 (save-excursion
10746 (save-restriction
10747 (widen)
10748 (goto-char (point-min))
10749 (when (re-search-forward
10750 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
10751 nil t)
10752 (org-back-to-heading)
10753 (point))))))
10755 ;;;; Timestamps
10757 (defvar org-last-changed-timestamp nil)
10758 (defvar org-last-inserted-timestamp nil
10759 "The last time stamp inserted with `org-insert-time-stamp'.")
10760 (defvar org-time-was-given) ; dynamically scoped parameter
10761 (defvar org-end-time-was-given) ; dynamically scoped parameter
10762 (defvar org-ts-what) ; dynamically scoped parameter
10764 (defun org-time-stamp (arg &optional inactive)
10765 "Prompt for a date/time and insert a time stamp.
10766 If the user specifies a time like HH:MM, or if this command is called
10767 with a prefix argument, the time stamp will contain date and time.
10768 Otherwise, only the date will be included. All parts of a date not
10769 specified by the user will be filled in from the current date/time.
10770 So if you press just return without typing anything, the time stamp
10771 will represent the current date/time. If there is already a timestamp
10772 at the cursor, it will be modified."
10773 (interactive "P")
10774 (let* ((ts nil)
10775 (default-time
10776 ;; Default time is either today, or, when entering a range,
10777 ;; the range start.
10778 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
10779 (save-excursion
10780 (re-search-backward
10781 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
10782 (- (point) 20) t)))
10783 (apply 'encode-time (org-parse-time-string (match-string 1)))
10784 (current-time)))
10785 (default-input (and ts (org-get-compact-tod ts)))
10786 org-time-was-given org-end-time-was-given time)
10787 (cond
10788 ((and (org-at-timestamp-p t)
10789 (memq last-command '(org-time-stamp org-time-stamp-inactive))
10790 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
10791 (insert "--")
10792 (setq time (let ((this-command this-command))
10793 (org-read-date arg 'totime nil nil
10794 default-time default-input)))
10795 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
10796 ((org-at-timestamp-p t)
10797 (setq time (let ((this-command this-command))
10798 (org-read-date arg 'totime nil nil default-time default-input)))
10799 (when (org-at-timestamp-p t) ; just to get the match data
10800 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
10801 (replace-match "")
10802 (setq org-last-changed-timestamp
10803 (org-insert-time-stamp
10804 time (or org-time-was-given arg)
10805 inactive nil nil (list org-end-time-was-given))))
10806 (message "Timestamp updated"))
10808 (setq time (let ((this-command this-command))
10809 (org-read-date arg 'totime nil nil default-time default-input)))
10810 (org-insert-time-stamp time (or org-time-was-given arg) inactive
10811 nil nil (list org-end-time-was-given))))))
10813 ;; FIXME: can we use this for something else, like computing time differences?
10814 (defun org-get-compact-tod (s)
10815 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
10816 (let* ((t1 (match-string 1 s))
10817 (h1 (string-to-number (match-string 2 s)))
10818 (m1 (string-to-number (match-string 3 s)))
10819 (t2 (and (match-end 4) (match-string 5 s)))
10820 (h2 (and t2 (string-to-number (match-string 6 s))))
10821 (m2 (and t2 (string-to-number (match-string 7 s))))
10822 dh dm)
10823 (if (not t2)
10825 (setq dh (- h2 h1) dm (- m2 m1))
10826 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
10827 (concat t1 "+" (number-to-string dh)
10828 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
10830 (defun org-time-stamp-inactive (&optional arg)
10831 "Insert an inactive time stamp.
10832 An inactive time stamp is enclosed in square brackets instead of angle
10833 brackets. It is inactive in the sense that it does not trigger agenda entries,
10834 does not link to the calendar and cannot be changed with the S-cursor keys.
10835 So these are more for recording a certain time/date."
10836 (interactive "P")
10837 (org-time-stamp arg 'inactive))
10839 (defvar org-date-ovl (org-make-overlay 1 1))
10840 (org-overlay-put org-date-ovl 'face 'org-warning)
10841 (org-detach-overlay org-date-ovl)
10843 (defvar org-ans1) ; dynamically scoped parameter
10844 (defvar org-ans2) ; dynamically scoped parameter
10846 (defvar org-plain-time-of-day-regexp) ; defined below
10848 (defvar org-overriding-default-time nil) ; dynamically scoped
10849 (defvar org-read-date-overlay nil)
10850 (defvar org-dcst nil) ; dynamically scoped
10852 (defun org-read-date (&optional with-time to-time from-string prompt
10853 default-time default-input)
10854 "Read a date, possibly a time, and make things smooth for the user.
10855 The prompt will suggest to enter an ISO date, but you can also enter anything
10856 which will at least partially be understood by `parse-time-string'.
10857 Unrecognized parts of the date will default to the current day, month, year,
10858 hour and minute. If this command is called to replace a timestamp at point,
10859 of to enter the second timestamp of a range, the default time is taken from the
10860 existing stamp. For example,
10861 3-2-5 --> 2003-02-05
10862 feb 15 --> currentyear-02-15
10863 sep 12 9 --> 2009-09-12
10864 12:45 --> today 12:45
10865 22 sept 0:34 --> currentyear-09-22 0:34
10866 12 --> currentyear-currentmonth-12
10867 Fri --> nearest Friday (today or later)
10868 etc.
10870 Furthermore you can specify a relative date by giving, as the *first* thing
10871 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
10872 change in days weeks, months, years.
10873 With a single plus or minus, the date is relative to today. With a double
10874 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
10875 +4d --> four days from today
10876 +4 --> same as above
10877 +2w --> two weeks from today
10878 ++5 --> five days from default date
10880 The function understands only English month and weekday abbreviations,
10881 but this can be configured with the variables `parse-time-months' and
10882 `parse-time-weekdays'.
10884 While prompting, a calendar is popped up - you can also select the
10885 date with the mouse (button 1). The calendar shows a period of three
10886 months. To scroll it to other months, use the keys `>' and `<'.
10887 If you don't like the calendar, turn it off with
10888 \(setq org-read-date-popup-calendar nil)
10890 With optional argument TO-TIME, the date will immediately be converted
10891 to an internal time.
10892 With an optional argument WITH-TIME, the prompt will suggest to also
10893 insert a time. Note that when WITH-TIME is not set, you can still
10894 enter a time, and this function will inform the calling routine about
10895 this change. The calling routine may then choose to change the format
10896 used to insert the time stamp into the buffer to include the time.
10897 With optional argument FROM-STRING, read from this string instead from
10898 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
10899 the time/date that is used for everything that is not specified by the
10900 user."
10901 (require 'parse-time)
10902 (let* ((org-time-stamp-rounding-minutes
10903 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
10904 (org-dcst org-display-custom-times)
10905 (ct (org-current-time))
10906 (def (or org-overriding-default-time default-time ct))
10907 (defdecode (decode-time def))
10908 (dummy (progn
10909 (when (< (nth 2 defdecode) org-extend-today-until)
10910 (setcar (nthcdr 2 defdecode) -1)
10911 (setcar (nthcdr 1 defdecode) 59)
10912 (setq def (apply 'encode-time defdecode)
10913 defdecode (decode-time def)))))
10914 (calendar-move-hook nil)
10915 (calendar-view-diary-initially-flag nil)
10916 (view-diary-entries-initially nil)
10917 (calendar-view-holidays-initially-flag nil)
10918 (view-calendar-holidays-initially nil)
10919 (timestr (format-time-string
10920 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
10921 (prompt (concat (if prompt (concat prompt " ") "")
10922 (format "Date+time [%s]: " timestr)))
10923 ans (org-ans0 "") org-ans1 org-ans2 final)
10925 (cond
10926 (from-string (setq ans from-string))
10927 (org-read-date-popup-calendar
10928 (save-excursion
10929 (save-window-excursion
10930 (calendar)
10931 (calendar-forward-day (- (time-to-days def)
10932 (calendar-absolute-from-gregorian
10933 (calendar-current-date))))
10934 (org-eval-in-calendar nil t)
10935 (let* ((old-map (current-local-map))
10936 (map (copy-keymap calendar-mode-map))
10937 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
10938 (org-defkey map (kbd "RET") 'org-calendar-select)
10939 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
10940 'org-calendar-select-mouse)
10941 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
10942 'org-calendar-select-mouse)
10943 (org-defkey minibuffer-local-map [(meta shift left)]
10944 (lambda () (interactive)
10945 (org-eval-in-calendar '(calendar-backward-month 1))))
10946 (org-defkey minibuffer-local-map [(meta shift right)]
10947 (lambda () (interactive)
10948 (org-eval-in-calendar '(calendar-forward-month 1))))
10949 (org-defkey minibuffer-local-map [(meta shift up)]
10950 (lambda () (interactive)
10951 (org-eval-in-calendar '(calendar-backward-year 1))))
10952 (org-defkey minibuffer-local-map [(meta shift down)]
10953 (lambda () (interactive)
10954 (org-eval-in-calendar '(calendar-forward-year 1))))
10955 (org-defkey minibuffer-local-map [(shift up)]
10956 (lambda () (interactive)
10957 (org-eval-in-calendar '(calendar-backward-week 1))))
10958 (org-defkey minibuffer-local-map [(shift down)]
10959 (lambda () (interactive)
10960 (org-eval-in-calendar '(calendar-forward-week 1))))
10961 (org-defkey minibuffer-local-map [(shift left)]
10962 (lambda () (interactive)
10963 (org-eval-in-calendar '(calendar-backward-day 1))))
10964 (org-defkey minibuffer-local-map [(shift right)]
10965 (lambda () (interactive)
10966 (org-eval-in-calendar '(calendar-forward-day 1))))
10967 (org-defkey minibuffer-local-map ">"
10968 (lambda () (interactive)
10969 (org-eval-in-calendar '(scroll-calendar-left 1))))
10970 (org-defkey minibuffer-local-map "<"
10971 (lambda () (interactive)
10972 (org-eval-in-calendar '(scroll-calendar-right 1))))
10973 (unwind-protect
10974 (progn
10975 (use-local-map map)
10976 (add-hook 'post-command-hook 'org-read-date-display)
10977 (setq org-ans0 (read-string prompt default-input nil nil))
10978 ;; org-ans0: from prompt
10979 ;; org-ans1: from mouse click
10980 ;; org-ans2: from calendar motion
10981 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
10982 (remove-hook 'post-command-hook 'org-read-date-display)
10983 (use-local-map old-map)
10984 (when org-read-date-overlay
10985 (org-delete-overlay org-read-date-overlay)
10986 (setq org-read-date-overlay nil)))))))
10988 (t ; Naked prompt only
10989 (unwind-protect
10990 (setq ans (read-string prompt default-input nil timestr))
10991 (when org-read-date-overlay
10992 (org-delete-overlay org-read-date-overlay)
10993 (setq org-read-date-overlay nil)))))
10995 (setq final (org-read-date-analyze ans def defdecode))
10997 (if to-time
10998 (apply 'encode-time final)
10999 (if (and (boundp 'org-time-was-given) org-time-was-given)
11000 (format "%04d-%02d-%02d %02d:%02d"
11001 (nth 5 final) (nth 4 final) (nth 3 final)
11002 (nth 2 final) (nth 1 final))
11003 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
11004 (defvar def)
11005 (defvar defdecode)
11006 (defvar with-time)
11007 (defun org-read-date-display ()
11008 "Display the current date prompt interpretation in the minibuffer."
11009 (when org-read-date-display-live
11010 (when org-read-date-overlay
11011 (org-delete-overlay org-read-date-overlay))
11012 (let ((p (point)))
11013 (end-of-line 1)
11014 (while (not (equal (buffer-substring
11015 (max (point-min) (- (point) 4)) (point))
11016 " "))
11017 (insert " "))
11018 (goto-char p))
11019 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
11020 " " (or org-ans1 org-ans2)))
11021 (org-end-time-was-given nil)
11022 (f (org-read-date-analyze ans def defdecode))
11023 (fmts (if org-dcst
11024 org-time-stamp-custom-formats
11025 org-time-stamp-formats))
11026 (fmt (if (or with-time
11027 (and (boundp 'org-time-was-given) org-time-was-given))
11028 (cdr fmts)
11029 (car fmts)))
11030 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
11031 (when (and org-end-time-was-given
11032 (string-match org-plain-time-of-day-regexp txt))
11033 (setq txt (concat (substring txt 0 (match-end 0)) "-"
11034 org-end-time-was-given
11035 (substring txt (match-end 0)))))
11036 (setq org-read-date-overlay
11037 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
11038 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
11040 (defun org-read-date-analyze (ans def defdecode)
11041 "Analyse the combined answer of the date prompt."
11042 ;; FIXME: cleanup and comment
11043 (let (delta deltan deltaw deltadef year month day
11044 hour minute second wday pm h2 m2 tl wday1
11045 iso-year iso-weekday iso-week iso-year iso-date)
11047 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
11048 (setq ans "+0"))
11050 (when (setq delta (org-read-date-get-relative ans (current-time) def))
11051 (setq ans (replace-match "" t t ans)
11052 deltan (car delta)
11053 deltaw (nth 1 delta)
11054 deltadef (nth 2 delta)))
11056 ;; Check if there is an iso week date in there
11057 ;; If yes, sore the info and postpone interpreting it until the rest
11058 ;; of the parsing is done
11059 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
11060 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
11061 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
11062 iso-week (string-to-number (match-string 2 ans)))
11063 (setq ans (replace-match "" t t ans)))
11065 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
11066 (when (string-match
11067 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
11068 (setq year (if (match-end 2)
11069 (string-to-number (match-string 2 ans))
11070 (string-to-number (format-time-string "%Y")))
11071 month (string-to-number (match-string 3 ans))
11072 day (string-to-number (match-string 4 ans)))
11073 (if (< year 100) (setq year (+ 2000 year)))
11074 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
11075 t nil ans)))
11076 ;; Help matching am/pm times, because `parse-time-string' does not do that.
11077 ;; If there is a time with am/pm, and *no* time without it, we convert
11078 ;; so that matching will be successful.
11079 (loop for i from 1 to 2 do ; twice, for end time as well
11080 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
11081 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
11082 (setq hour (string-to-number (match-string 1 ans))
11083 minute (if (match-end 3)
11084 (string-to-number (match-string 3 ans))
11086 pm (equal ?p
11087 (string-to-char (downcase (match-string 4 ans)))))
11088 (if (and (= hour 12) (not pm))
11089 (setq hour 0)
11090 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
11091 (setq ans (replace-match (format "%02d:%02d" hour minute)
11092 t t ans))))
11094 ;; Check if a time range is given as a duration
11095 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
11096 (setq hour (string-to-number (match-string 1 ans))
11097 h2 (+ hour (string-to-number (match-string 3 ans)))
11098 minute (string-to-number (match-string 2 ans))
11099 m2 (+ minute (if (match-end 5) (string-to-number
11100 (match-string 5 ans))0)))
11101 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
11102 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
11103 t t ans)))
11105 ;; Check if there is a time range
11106 (when (boundp 'org-end-time-was-given)
11107 (setq org-time-was-given nil)
11108 (when (and (string-match org-plain-time-of-day-regexp ans)
11109 (match-end 8))
11110 (setq org-end-time-was-given (match-string 8 ans))
11111 (setq ans (concat (substring ans 0 (match-beginning 7))
11112 (substring ans (match-end 7))))))
11114 (setq tl (parse-time-string ans)
11115 day (or (nth 3 tl) (nth 3 defdecode))
11116 month (or (nth 4 tl)
11117 (if (and org-read-date-prefer-future
11118 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
11119 (1+ (nth 4 defdecode))
11120 (nth 4 defdecode)))
11121 year (or (nth 5 tl)
11122 (if (and org-read-date-prefer-future
11123 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
11124 (1+ (nth 5 defdecode))
11125 (nth 5 defdecode)))
11126 hour (or (nth 2 tl) (nth 2 defdecode))
11127 minute (or (nth 1 tl) (nth 1 defdecode))
11128 second (or (nth 0 tl) 0)
11129 wday (nth 6 tl))
11131 ;; Special date definitions below
11132 (cond
11133 (iso-week
11134 ;; There was an iso week
11135 (setq year (or iso-year year)
11136 day (or iso-weekday wday 1)
11137 wday nil ; to make sure that the trigger below does not match
11138 iso-date (calendar-gregorian-from-absolute
11139 (calendar-absolute-from-iso
11140 (list iso-week day year))))
11141 ; FIXME: Should we also push ISO weeks into the future?
11142 ; (when (and org-read-date-prefer-future
11143 ; (not iso-year)
11144 ; (< (calendar-absolute-from-gregorian iso-date)
11145 ; (time-to-days (current-time))))
11146 ; (setq year (1+ year)
11147 ; iso-date (calendar-gregorian-from-absolute
11148 ; (calendar-absolute-from-iso
11149 ; (list iso-week day year)))))
11150 (setq month (car iso-date)
11151 year (nth 2 iso-date)
11152 day (nth 1 iso-date)))
11153 (deltan
11154 (unless deltadef
11155 (let ((now (decode-time (current-time))))
11156 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
11157 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
11158 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
11159 ((equal deltaw "m") (setq month (+ month deltan)))
11160 ((equal deltaw "y") (setq year (+ year deltan)))))
11161 ((and wday (not (nth 3 tl)))
11162 ;; Weekday was given, but no day, so pick that day in the week
11163 ;; on or after the derived date.
11164 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
11165 (unless (equal wday wday1)
11166 (setq day (+ day (% (- wday wday1 -7) 7))))))
11167 (if (and (boundp 'org-time-was-given)
11168 (nth 2 tl))
11169 (setq org-time-was-given t))
11170 (if (< year 100) (setq year (+ 2000 year)))
11171 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
11172 (list second minute hour day month year)))
11174 (defvar parse-time-weekdays)
11176 (defun org-read-date-get-relative (s today default)
11177 "Check string S for special relative date string.
11178 TODAY and DEFAULT are internal times, for today and for a default.
11179 Return shift list (N what def-flag)
11180 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
11181 N is the number of WHATs to shift.
11182 DEF-FLAG is t when a double ++ or -- indicates shift relative to
11183 the DEFAULT date rather than TODAY."
11184 (when (and
11185 (string-match
11186 (concat
11187 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
11188 "\\([0-9]+\\)?"
11189 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
11190 "\\([ \t]\\|$\\)") s)
11191 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
11192 (let* ((dir (if (> (match-end 1) (match-beginning 1))
11193 (string-to-char (substring (match-string 1 s) -1))
11194 ?+))
11195 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
11196 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
11197 (what (if (match-end 3) (match-string 3 s) "d"))
11198 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
11199 (date (if rel default today))
11200 (wday (nth 6 (decode-time date)))
11201 delta)
11202 (if wday1
11203 (progn
11204 (setq delta (mod (+ 7 (- wday1 wday)) 7))
11205 (if (= dir ?-) (setq delta (- delta 7)))
11206 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
11207 (list delta "d" rel))
11208 (list (* n (if (= dir ?-) -1 1)) what rel)))))
11210 (defun org-eval-in-calendar (form &optional keepdate)
11211 "Eval FORM in the calendar window and return to current window.
11212 Also, store the cursor date in variable org-ans2."
11213 (let ((sw (selected-window)))
11214 (select-window (get-buffer-window "*Calendar*"))
11215 (eval form)
11216 (when (and (not keepdate) (calendar-cursor-to-date))
11217 (let* ((date (calendar-cursor-to-date))
11218 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11219 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
11220 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
11221 (select-window sw)))
11223 (defun org-calendar-select ()
11224 "Return to `org-read-date' with the date currently selected.
11225 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11226 (interactive)
11227 (when (calendar-cursor-to-date)
11228 (let* ((date (calendar-cursor-to-date))
11229 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11230 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11231 (if (active-minibuffer-window) (exit-minibuffer))))
11233 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
11234 "Insert a date stamp for the date given by the internal TIME.
11235 WITH-HM means, use the stamp format that includes the time of the day.
11236 INACTIVE means use square brackets instead of angular ones, so that the
11237 stamp will not contribute to the agenda.
11238 PRE and POST are optional strings to be inserted before and after the
11239 stamp.
11240 The command returns the inserted time stamp."
11241 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
11242 stamp)
11243 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
11244 (insert-before-markers (or pre ""))
11245 (insert-before-markers (setq stamp (format-time-string fmt time)))
11246 (when (listp extra)
11247 (setq extra (car extra))
11248 (if (and (stringp extra)
11249 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
11250 (setq extra (format "-%02d:%02d"
11251 (string-to-number (match-string 1 extra))
11252 (string-to-number (match-string 2 extra))))
11253 (setq extra nil)))
11254 (when extra
11255 (backward-char 1)
11256 (insert-before-markers extra)
11257 (forward-char 1))
11258 (insert-before-markers (or post ""))
11259 (setq org-last-inserted-timestamp stamp)))
11261 (defun org-toggle-time-stamp-overlays ()
11262 "Toggle the use of custom time stamp formats."
11263 (interactive)
11264 (setq org-display-custom-times (not org-display-custom-times))
11265 (unless org-display-custom-times
11266 (let ((p (point-min)) (bmp (buffer-modified-p)))
11267 (while (setq p (next-single-property-change p 'display))
11268 (if (and (get-text-property p 'display)
11269 (eq (get-text-property p 'face) 'org-date))
11270 (remove-text-properties
11271 p (setq p (next-single-property-change p 'display))
11272 '(display t))))
11273 (set-buffer-modified-p bmp)))
11274 (if (featurep 'xemacs)
11275 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
11276 (org-restart-font-lock)
11277 (setq org-table-may-need-update t)
11278 (if org-display-custom-times
11279 (message "Time stamps are overlayed with custom format")
11280 (message "Time stamp overlays removed")))
11282 (defun org-display-custom-time (beg end)
11283 "Overlay modified time stamp format over timestamp between BEG and END."
11284 (let* ((ts (buffer-substring beg end))
11285 t1 w1 with-hm tf time str w2 (off 0))
11286 (save-match-data
11287 (setq t1 (org-parse-time-string ts t))
11288 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
11289 (setq off (- (match-end 0) (match-beginning 0)))))
11290 (setq end (- end off))
11291 (setq w1 (- end beg)
11292 with-hm (and (nth 1 t1) (nth 2 t1))
11293 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
11294 time (org-fix-decoded-time t1)
11295 str (org-add-props
11296 (format-time-string
11297 (substring tf 1 -1) (apply 'encode-time time))
11298 nil 'mouse-face 'highlight)
11299 w2 (length str))
11300 (if (not (= w2 w1))
11301 (add-text-properties (1+ beg) (+ 2 beg)
11302 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
11303 (if (featurep 'xemacs)
11304 (progn
11305 (put-text-property beg end 'invisible t)
11306 (put-text-property beg end 'end-glyph (make-glyph str)))
11307 (put-text-property beg end 'display str))))
11309 (defun org-translate-time (string)
11310 "Translate all timestamps in STRING to custom format.
11311 But do this only if the variable `org-display-custom-times' is set."
11312 (when org-display-custom-times
11313 (save-match-data
11314 (let* ((start 0)
11315 (re org-ts-regexp-both)
11316 t1 with-hm inactive tf time str beg end)
11317 (while (setq start (string-match re string start))
11318 (setq beg (match-beginning 0)
11319 end (match-end 0)
11320 t1 (save-match-data
11321 (org-parse-time-string (substring string beg end) t))
11322 with-hm (and (nth 1 t1) (nth 2 t1))
11323 inactive (equal (substring string beg (1+ beg)) "[")
11324 tf (funcall (if with-hm 'cdr 'car)
11325 org-time-stamp-custom-formats)
11326 time (org-fix-decoded-time t1)
11327 str (format-time-string
11328 (concat
11329 (if inactive "[" "<") (substring tf 1 -1)
11330 (if inactive "]" ">"))
11331 (apply 'encode-time time))
11332 string (replace-match str t t string)
11333 start (+ start (length str)))))))
11334 string)
11336 (defun org-fix-decoded-time (time)
11337 "Set 0 instead of nil for the first 6 elements of time.
11338 Don't touch the rest."
11339 (let ((n 0))
11340 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
11342 (defun org-days-to-time (timestamp-string)
11343 "Difference between TIMESTAMP-STRING and now in days."
11344 (- (time-to-days (org-time-string-to-time timestamp-string))
11345 (time-to-days (current-time))))
11347 (defun org-deadline-close (timestamp-string &optional ndays)
11348 "Is the time in TIMESTAMP-STRING close to the current date?"
11349 (setq ndays (or ndays (org-get-wdays timestamp-string)))
11350 (and (< (org-days-to-time timestamp-string) ndays)
11351 (not (org-entry-is-done-p))))
11353 (defun org-get-wdays (ts)
11354 "Get the deadline lead time appropriate for timestring TS."
11355 (cond
11356 ((<= org-deadline-warning-days 0)
11357 ;; 0 or negative, enforce this value no matter what
11358 (- org-deadline-warning-days))
11359 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
11360 ;; lead time is specified.
11361 (floor (* (string-to-number (match-string 1 ts))
11362 (cdr (assoc (match-string 2 ts)
11363 '(("d" . 1) ("w" . 7)
11364 ("m" . 30.4) ("y" . 365.25)))))))
11365 ;; go for the default.
11366 (t org-deadline-warning-days)))
11368 (defun org-calendar-select-mouse (ev)
11369 "Return to `org-read-date' with the date currently selected.
11370 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11371 (interactive "e")
11372 (mouse-set-point ev)
11373 (when (calendar-cursor-to-date)
11374 (let* ((date (calendar-cursor-to-date))
11375 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11376 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11377 (if (active-minibuffer-window) (exit-minibuffer))))
11379 (defun org-check-deadlines (ndays)
11380 "Check if there are any deadlines due or past due.
11381 A deadline is considered due if it happens within `org-deadline-warning-days'
11382 days from today's date. If the deadline appears in an entry marked DONE,
11383 it is not shown. The prefix arg NDAYS can be used to test that many
11384 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
11385 (interactive "P")
11386 (let* ((org-warn-days
11387 (cond
11388 ((equal ndays '(4)) 100000)
11389 (ndays (prefix-numeric-value ndays))
11390 (t (abs org-deadline-warning-days))))
11391 (case-fold-search nil)
11392 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
11393 (callback
11394 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
11396 (message "%d deadlines past-due or due within %d days"
11397 (org-occur regexp nil callback)
11398 org-warn-days)))
11400 (defun org-check-before-date (date)
11401 "Check if there are deadlines or scheduled entries before DATE."
11402 (interactive (list (org-read-date)))
11403 (let ((case-fold-search nil)
11404 (regexp (concat "\\<\\(" org-deadline-string
11405 "\\|" org-scheduled-string
11406 "\\) *<\\([^>]+\\)>"))
11407 (callback
11408 (lambda () (time-less-p
11409 (org-time-string-to-time (match-string 2))
11410 (org-time-string-to-time date)))))
11411 (message "%d entries before %s"
11412 (org-occur regexp nil callback) date)))
11414 (defun org-evaluate-time-range (&optional to-buffer)
11415 "Evaluate a time range by computing the difference between start and end.
11416 Normally the result is just printed in the echo area, but with prefix arg
11417 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
11418 If the time range is actually in a table, the result is inserted into the
11419 next column.
11420 For time difference computation, a year is assumed to be exactly 365
11421 days in order to avoid rounding problems."
11422 (interactive "P")
11424 (org-clock-update-time-maybe)
11425 (save-excursion
11426 (unless (org-at-date-range-p t)
11427 (goto-char (point-at-bol))
11428 (re-search-forward org-tr-regexp-both (point-at-eol) t))
11429 (if (not (org-at-date-range-p t))
11430 (error "Not at a time-stamp range, and none found in current line")))
11431 (let* ((ts1 (match-string 1))
11432 (ts2 (match-string 2))
11433 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
11434 (match-end (match-end 0))
11435 (time1 (org-time-string-to-time ts1))
11436 (time2 (org-time-string-to-time ts2))
11437 (t1 (time-to-seconds time1))
11438 (t2 (time-to-seconds time2))
11439 (diff (abs (- t2 t1)))
11440 (negative (< (- t2 t1) 0))
11441 ;; (ys (floor (* 365 24 60 60)))
11442 (ds (* 24 60 60))
11443 (hs (* 60 60))
11444 (fy "%dy %dd %02d:%02d")
11445 (fy1 "%dy %dd")
11446 (fd "%dd %02d:%02d")
11447 (fd1 "%dd")
11448 (fh "%02d:%02d")
11449 y d h m align)
11450 (if havetime
11451 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11453 d (floor (/ diff ds)) diff (mod diff ds)
11454 h (floor (/ diff hs)) diff (mod diff hs)
11455 m (floor (/ diff 60)))
11456 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11458 d (floor (+ (/ diff ds) 0.5))
11459 h 0 m 0))
11460 (if (not to-buffer)
11461 (message "%s" (org-make-tdiff-string y d h m))
11462 (if (org-at-table-p)
11463 (progn
11464 (goto-char match-end)
11465 (setq align t)
11466 (and (looking-at " *|") (goto-char (match-end 0))))
11467 (goto-char match-end))
11468 (if (looking-at
11469 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
11470 (replace-match ""))
11471 (if negative (insert " -"))
11472 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
11473 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
11474 (insert " " (format fh h m))))
11475 (if align (org-table-align))
11476 (message "Time difference inserted")))))
11478 (defun org-make-tdiff-string (y d h m)
11479 (let ((fmt "")
11480 (l nil))
11481 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
11482 l (push y l)))
11483 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
11484 l (push d l)))
11485 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
11486 l (push h l)))
11487 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
11488 l (push m l)))
11489 (apply 'format fmt (nreverse l))))
11491 (defun org-time-string-to-time (s)
11492 (apply 'encode-time (org-parse-time-string s)))
11494 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
11495 "Convert a time stamp to an absolute day number.
11496 If there is a specifyer for a cyclic time stamp, get the closest date to
11497 DAYNR.
11498 PREFER and SHOW-ALL are passed through to `org-closest-date'."
11499 (cond
11500 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
11501 (if (org-diary-sexp-entry (match-string 1 s) "" date)
11502 daynr
11503 (+ daynr 1000)))
11504 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
11505 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
11506 (time-to-days (current-time))) (match-string 0 s)
11507 prefer show-all))
11508 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
11510 (defun org-days-to-iso-week (days)
11511 "Return the iso week number."
11512 (require 'cal-iso)
11513 (car (calendar-iso-from-absolute days)))
11515 (defun org-small-year-to-year (year)
11516 "Convert 2-digit years into 4-digit years.
11517 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
11518 The year 2000 cannot be abbreviated. Any year larger than 99
11519 is returned unchanged."
11520 (if (< year 38)
11521 (setq year (+ 2000 year))
11522 (if (< year 100)
11523 (setq year (+ 1900 year))))
11524 year)
11526 (defun org-time-from-absolute (d)
11527 "Return the time corresponding to date D.
11528 D may be an absolute day number, or a calendar-type list (month day year)."
11529 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
11530 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
11532 (defun org-calendar-holiday ()
11533 "List of holidays, for Diary display in Org-mode."
11534 (require 'holidays)
11535 (let ((hl (funcall
11536 (if (fboundp 'calendar-check-holidays)
11537 'calendar-check-holidays 'check-calendar-holidays) date)))
11538 (if hl (mapconcat 'identity hl "; "))))
11540 (defun org-diary-sexp-entry (sexp entry date)
11541 "Process a SEXP diary ENTRY for DATE."
11542 (require 'diary-lib)
11543 (let ((result (if calendar-debug-sexp
11544 (let ((stack-trace-on-error t))
11545 (eval (car (read-from-string sexp))))
11546 (condition-case nil
11547 (eval (car (read-from-string sexp)))
11548 (error
11549 (beep)
11550 (message "Bad sexp at line %d in %s: %s"
11551 (org-current-line)
11552 (buffer-file-name) sexp)
11553 (sleep-for 2))))))
11554 (cond ((stringp result) result)
11555 ((and (consp result)
11556 (stringp (cdr result))) (cdr result))
11557 (result entry)
11558 (t nil))))
11560 (defun org-diary-to-ical-string (frombuf)
11561 "Get iCalendar entries from diary entries in buffer FROMBUF.
11562 This uses the icalendar.el library."
11563 (let* ((tmpdir (if (featurep 'xemacs)
11564 (temp-directory)
11565 temporary-file-directory))
11566 (tmpfile (make-temp-name
11567 (expand-file-name "orgics" tmpdir)))
11568 buf rtn b e)
11569 (save-excursion
11570 (set-buffer frombuf)
11571 (icalendar-export-region (point-min) (point-max) tmpfile)
11572 (setq buf (find-buffer-visiting tmpfile))
11573 (set-buffer buf)
11574 (goto-char (point-min))
11575 (if (re-search-forward "^BEGIN:VEVENT" nil t)
11576 (setq b (match-beginning 0)))
11577 (goto-char (point-max))
11578 (if (re-search-backward "^END:VEVENT" nil t)
11579 (setq e (match-end 0)))
11580 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
11581 (kill-buffer buf)
11582 (delete-file tmpfile)
11583 rtn))
11585 (defun org-closest-date (start current change prefer show-all)
11586 "Find the date closest to CURRENT that is consistent with START and CHANGE.
11587 When PREFER is `past' return a date that is either CURRENT or past.
11588 When PREFER is `future', return a date that is either CURRENT or future.
11589 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
11590 ;; Make the proper lists from the dates
11591 (catch 'exit
11592 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
11593 dn dw sday cday n1 n2
11594 d m y y1 y2 date1 date2 nmonths nm ny m2)
11596 (setq start (org-date-to-gregorian start)
11597 current (org-date-to-gregorian
11598 (if show-all
11599 current
11600 (time-to-days (current-time))))
11601 sday (calendar-absolute-from-gregorian start)
11602 cday (calendar-absolute-from-gregorian current))
11604 (if (<= cday sday) (throw 'exit sday))
11606 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
11607 (setq dn (string-to-number (match-string 1 change))
11608 dw (cdr (assoc (match-string 2 change) a1)))
11609 (error "Invalid change specifyer: %s" change))
11610 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
11611 (cond
11612 ((eq dw 'day)
11613 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
11614 n2 (+ n1 dn)))
11615 ((eq dw 'year)
11616 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
11617 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
11618 (setq date1 (list m d y1)
11619 n1 (calendar-absolute-from-gregorian date1)
11620 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
11621 n2 (calendar-absolute-from-gregorian date2)))
11622 ((eq dw 'month)
11623 ;; approx number of month between the two dates
11624 (setq nmonths (floor (/ (- cday sday) 30.436875)))
11625 ;; How often does dn fit in there?
11626 (setq d (nth 1 start) m (car start) y (nth 2 start)
11627 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
11628 m (+ m nm)
11629 ny (floor (/ m 12))
11630 y (+ y ny)
11631 m (- m (* ny 12)))
11632 (while (> m 12) (setq m (- m 12) y (1+ y)))
11633 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
11634 (setq m2 (+ m dn) y2 y)
11635 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11636 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
11637 (while (<= n2 cday)
11638 (setq n1 n2 m m2 y y2)
11639 (setq m2 (+ m dn) y2 y)
11640 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11641 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
11642 (if show-all
11643 (cond
11644 ((eq prefer 'past) n1)
11645 ((eq prefer 'future) (if (= cday n1) n1 n2))
11646 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
11647 (cond
11648 ((eq prefer 'past) n1)
11649 ((eq prefer 'future) (if (= cday n1) n1 n2))
11650 (t (if (= cday n1) n1 n2)))))))
11652 (defun org-date-to-gregorian (date)
11653 "Turn any specification of DATE into a gregorian date for the calendar."
11654 (cond ((integerp date) (calendar-gregorian-from-absolute date))
11655 ((and (listp date) (= (length date) 3)) date)
11656 ((stringp date)
11657 (setq date (org-parse-time-string date))
11658 (list (nth 4 date) (nth 3 date) (nth 5 date)))
11659 ((listp date)
11660 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
11662 (defun org-parse-time-string (s &optional nodefault)
11663 "Parse the standard Org-mode time string.
11664 This should be a lot faster than the normal `parse-time-string'.
11665 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
11666 hour and minute fields will be nil if not given."
11667 (if (string-match org-ts-regexp0 s)
11668 (list 0
11669 (if (or (match-beginning 8) (not nodefault))
11670 (string-to-number (or (match-string 8 s) "0")))
11671 (if (or (match-beginning 7) (not nodefault))
11672 (string-to-number (or (match-string 7 s) "0")))
11673 (string-to-number (match-string 4 s))
11674 (string-to-number (match-string 3 s))
11675 (string-to-number (match-string 2 s))
11676 nil nil nil)
11677 (make-list 9 0)))
11679 (defun org-timestamp-up (&optional arg)
11680 "Increase the date item at the cursor by one.
11681 If the cursor is on the year, change the year. If it is on the month or
11682 the day, change that.
11683 With prefix ARG, change by that many units."
11684 (interactive "p")
11685 (org-timestamp-change (prefix-numeric-value arg)))
11687 (defun org-timestamp-down (&optional arg)
11688 "Decrease the date item at the cursor by one.
11689 If the cursor is on the year, change the year. If it is on the month or
11690 the day, change that.
11691 With prefix ARG, change by that many units."
11692 (interactive "p")
11693 (org-timestamp-change (- (prefix-numeric-value arg))))
11695 (defun org-timestamp-up-day (&optional arg)
11696 "Increase the date in the time stamp by one day.
11697 With prefix ARG, change that many days."
11698 (interactive "p")
11699 (if (and (not (org-at-timestamp-p t))
11700 (org-on-heading-p))
11701 (org-todo 'up)
11702 (org-timestamp-change (prefix-numeric-value arg) 'day)))
11704 (defun org-timestamp-down-day (&optional arg)
11705 "Decrease the date in the time stamp by one day.
11706 With prefix ARG, change that many days."
11707 (interactive "p")
11708 (if (and (not (org-at-timestamp-p t))
11709 (org-on-heading-p))
11710 (org-todo 'down)
11711 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
11713 (defun org-at-timestamp-p (&optional inactive-ok)
11714 "Determine if the cursor is in or at a timestamp."
11715 (interactive)
11716 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
11717 (pos (point))
11718 (ans (or (looking-at tsr)
11719 (save-excursion
11720 (skip-chars-backward "^[<\n\r\t")
11721 (if (> (point) (point-min)) (backward-char 1))
11722 (and (looking-at tsr)
11723 (> (- (match-end 0) pos) -1))))))
11724 (and ans
11725 (boundp 'org-ts-what)
11726 (setq org-ts-what
11727 (cond
11728 ((= pos (match-beginning 0)) 'bracket)
11729 ((= pos (1- (match-end 0))) 'bracket)
11730 ((org-pos-in-match-range pos 2) 'year)
11731 ((org-pos-in-match-range pos 3) 'month)
11732 ((org-pos-in-match-range pos 7) 'hour)
11733 ((org-pos-in-match-range pos 8) 'minute)
11734 ((or (org-pos-in-match-range pos 4)
11735 (org-pos-in-match-range pos 5)) 'day)
11736 ((and (> pos (or (match-end 8) (match-end 5)))
11737 (< pos (match-end 0)))
11738 (- pos (or (match-end 8) (match-end 5))))
11739 (t 'day))))
11740 ans))
11742 (defun org-toggle-timestamp-type ()
11743 "Toggle the type (<active> or [inactive]) of a time stamp."
11744 (interactive)
11745 (when (org-at-timestamp-p t)
11746 (let ((beg (match-beginning 0)) (end (match-end 0))
11747 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
11748 (save-excursion
11749 (goto-char beg)
11750 (while (re-search-forward "[][<>]" end t)
11751 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
11752 t t)))
11753 (message "Timestamp is now %sactive"
11754 (if (equal (char-after beg) ?<) "" "in")))))
11756 (defun org-timestamp-change (n &optional what)
11757 "Change the date in the time stamp at point.
11758 The date will be changed by N times WHAT. WHAT can be `day', `month',
11759 `year', `minute', `second'. If WHAT is not given, the cursor position
11760 in the timestamp determines what will be changed."
11761 (let ((pos (point))
11762 with-hm inactive
11763 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
11764 org-ts-what
11765 extra rem
11766 ts time time0)
11767 (if (not (org-at-timestamp-p t))
11768 (error "Not at a timestamp"))
11769 (if (and (not what) (eq org-ts-what 'bracket))
11770 (org-toggle-timestamp-type)
11771 (if (and (not what) (not (eq org-ts-what 'day))
11772 org-display-custom-times
11773 (get-text-property (point) 'display)
11774 (not (get-text-property (1- (point)) 'display)))
11775 (setq org-ts-what 'day))
11776 (setq org-ts-what (or what org-ts-what)
11777 inactive (= (char-after (match-beginning 0)) ?\[)
11778 ts (match-string 0))
11779 (replace-match "")
11780 (if (string-match
11781 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
11783 (setq extra (match-string 1 ts)))
11784 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
11785 (setq with-hm t))
11786 (setq time0 (org-parse-time-string ts))
11787 (when (and (eq org-ts-what 'minute)
11788 (eq current-prefix-arg nil))
11789 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
11790 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
11791 (setcar (cdr time0) (+ (nth 1 time0)
11792 (if (> n 0) (- rem) (- dm rem))))))
11793 (setq time
11794 (encode-time (or (car time0) 0)
11795 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
11796 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
11797 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
11798 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
11799 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
11800 (nthcdr 6 time0)))
11801 (when (integerp org-ts-what)
11802 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
11803 (if (eq what 'calendar)
11804 (let ((cal-date (org-get-date-from-calendar)))
11805 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
11806 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
11807 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
11808 (setcar time0 (or (car time0) 0))
11809 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
11810 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
11811 (setq time (apply 'encode-time time0))))
11812 (setq org-last-changed-timestamp
11813 (org-insert-time-stamp time with-hm inactive nil nil extra))
11814 (org-clock-update-time-maybe)
11815 (goto-char pos)
11816 ;; Try to recenter the calendar window, if any
11817 (if (and org-calendar-follow-timestamp-change
11818 (get-buffer-window "*Calendar*" t)
11819 (memq org-ts-what '(day month year)))
11820 (org-recenter-calendar (time-to-days time))))))
11822 (defun org-modify-ts-extra (s pos n dm)
11823 "Change the different parts of the lead-time and repeat fields in timestamp."
11824 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
11825 ng h m new rem)
11826 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
11827 (cond
11828 ((or (org-pos-in-match-range pos 2)
11829 (org-pos-in-match-range pos 3))
11830 (setq m (string-to-number (match-string 3 s))
11831 h (string-to-number (match-string 2 s)))
11832 (if (org-pos-in-match-range pos 2)
11833 (setq h (+ h n))
11834 (setq n (* dm (org-no-warnings (signum n))))
11835 (when (not (= 0 (setq rem (% m dm))))
11836 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
11837 (setq m (+ m n)))
11838 (if (< m 0) (setq m (+ m 60) h (1- h)))
11839 (if (> m 59) (setq m (- m 60) h (1+ h)))
11840 (setq h (min 24 (max 0 h)))
11841 (setq ng 1 new (format "-%02d:%02d" h m)))
11842 ((org-pos-in-match-range pos 6)
11843 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
11844 ((org-pos-in-match-range pos 5)
11845 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
11847 ((org-pos-in-match-range pos 9)
11848 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
11849 ((org-pos-in-match-range pos 8)
11850 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
11852 (when ng
11853 (setq s (concat
11854 (substring s 0 (match-beginning ng))
11856 (substring s (match-end ng))))))
11859 (defun org-recenter-calendar (date)
11860 "If the calendar is visible, recenter it to DATE."
11861 (let* ((win (selected-window))
11862 (cwin (get-buffer-window "*Calendar*" t))
11863 (calendar-move-hook nil))
11864 (when cwin
11865 (select-window cwin)
11866 (calendar-goto-date (if (listp date) date
11867 (calendar-gregorian-from-absolute date)))
11868 (select-window win))))
11870 (defun org-goto-calendar (&optional arg)
11871 "Go to the Emacs calendar at the current date.
11872 If there is a time stamp in the current line, go to that date.
11873 A prefix ARG can be used to force the current date."
11874 (interactive "P")
11875 (let ((tsr org-ts-regexp) diff
11876 (calendar-move-hook nil)
11877 (calendar-view-holidays-initially-flag nil)
11878 (view-calendar-holidays-initially nil)
11879 (calendar-view-diary-initially-flag nil)
11880 (view-diary-entries-initially nil))
11881 (if (or (org-at-timestamp-p)
11882 (save-excursion
11883 (beginning-of-line 1)
11884 (looking-at (concat ".*" tsr))))
11885 (let ((d1 (time-to-days (current-time)))
11886 (d2 (time-to-days
11887 (org-time-string-to-time (match-string 1)))))
11888 (setq diff (- d2 d1))))
11889 (calendar)
11890 (calendar-goto-today)
11891 (if (and diff (not arg)) (calendar-forward-day diff))))
11893 (defun org-get-date-from-calendar ()
11894 "Return a list (month day year) of date at point in calendar."
11895 (with-current-buffer "*Calendar*"
11896 (save-match-data
11897 (calendar-cursor-to-date))))
11899 (defun org-date-from-calendar ()
11900 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
11901 If there is already a time stamp at the cursor position, update it."
11902 (interactive)
11903 (if (org-at-timestamp-p t)
11904 (org-timestamp-change 0 'calendar)
11905 (let ((cal-date (org-get-date-from-calendar)))
11906 (org-insert-time-stamp
11907 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
11909 (defun org-minutes-to-hh:mm-string (m)
11910 "Compute H:MM from a number of minutes."
11911 (let ((h (/ m 60)))
11912 (setq m (- m (* 60 h)))
11913 (format org-time-clocksum-format h m)))
11915 (defun org-hh:mm-string-to-minutes (s)
11916 "Convert a string H:MM to a number of minutes."
11917 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
11918 (+ (* (string-to-number (match-string 1 s)) 60)
11919 (string-to-number (match-string 2 s)))
11922 ;;;; Agenda files
11924 ;;;###autoload
11925 (defun org-iswitchb (&optional arg)
11926 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
11927 With a prefix argument, restrict available to files.
11928 With two prefix arguments, restrict available buffers to agenda files.
11930 Due to some yet unresolved reason, the global function
11931 `iswitchb-mode' needs to be active for this function to work."
11932 (interactive "P")
11933 (require 'iswitchb)
11934 (let ((enabled iswitchb-mode) blist)
11935 (or enabled (iswitchb-mode 1))
11936 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
11937 ((equal arg '(16)) (org-buffer-list 'agenda))
11938 (t (org-buffer-list))))
11939 (unwind-protect
11940 (let ((iswitchb-make-buflist-hook
11941 (lambda ()
11942 (setq iswitchb-temp-buflist
11943 (mapcar 'buffer-name blist)))))
11944 (switch-to-buffer
11945 (iswitchb-read-buffer
11946 "Switch-to: " nil t))
11947 (or enabled (iswitchb-mode -1))))))
11949 ;;;###autoload
11950 (defun org-ido-switchb (&optional arg)
11951 "Use `org-ido-completing-read' to prompt for an Org buffer to switch to.
11952 With a prefix argument, restrict available to files.
11953 With two prefix arguments, restrict available buffers to agenda files."
11954 (interactive "P")
11955 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
11956 ((equal arg '(16)) (org-buffer-list 'agenda))
11957 (t (org-buffer-list)))))
11958 (switch-to-buffer
11959 (org-ido-completing-read "Org buffer: "
11960 (mapcar 'buffer-name blist)
11961 nil t))))
11963 (defun org-buffer-list (&optional predicate exclude-tmp)
11964 "Return a list of Org buffers.
11965 PREDICATE can be `export', `files' or `agenda'.
11967 export restrict the list to Export buffers.
11968 files restrict the list to buffers visiting Org files.
11969 agenda restrict the list to buffers visiting agenda files.
11971 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
11972 (let* ((bfn nil)
11973 (agenda-files (and (eq predicate 'agenda)
11974 (mapcar 'file-truename (org-agenda-files t))))
11975 (filter
11976 (cond
11977 ((eq predicate 'files)
11978 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
11979 ((eq predicate 'export)
11980 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
11981 ((eq predicate 'agenda)
11982 (lambda (b)
11983 (with-current-buffer b
11984 (and (eq major-mode 'org-mode)
11985 (setq bfn (buffer-file-name b))
11986 (member (file-truename bfn) agenda-files)))))
11987 (t (lambda (b) (with-current-buffer b
11988 (or (eq major-mode 'org-mode)
11989 (string-match "\*Org .*Export"
11990 (buffer-name b)))))))))
11991 (delq nil
11992 (mapcar
11993 (lambda(b)
11994 (if (and (funcall filter b)
11995 (or (not exclude-tmp)
11996 (not (string-match "tmp" (buffer-name b)))))
11998 nil))
11999 (buffer-list)))))
12001 (defun org-agenda-files (&optional unrestricted archives)
12002 "Get the list of agenda files.
12003 Optional UNRESTRICTED means return the full list even if a restriction
12004 is currently in place.
12005 When ARCHIVES is t, include all archive files hat are really being
12006 used by the agenda files. If ARCHIVE is `ifmode', do this only if
12007 `org-agenda-archives-mode' is t."
12008 (let ((files
12009 (cond
12010 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
12011 ((stringp org-agenda-files) (org-read-agenda-file-list))
12012 ((listp org-agenda-files) org-agenda-files)
12013 (t (error "Invalid value of `org-agenda-files'")))))
12014 (setq files (apply 'append
12015 (mapcar (lambda (f)
12016 (if (file-directory-p f)
12017 (directory-files
12018 f t org-agenda-file-regexp)
12019 (list f)))
12020 files)))
12021 (when org-agenda-skip-unavailable-files
12022 (setq files (delq nil
12023 (mapcar (function
12024 (lambda (file)
12025 (and (file-readable-p file) file)))
12026 files))))
12027 (when (or (eq archives t)
12028 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
12029 (setq files (org-add-archive-files files)))
12030 files))
12032 (defun org-edit-agenda-file-list ()
12033 "Edit the list of agenda files.
12034 Depending on setup, this either uses customize to edit the variable
12035 `org-agenda-files', or it visits the file that is holding the list. In the
12036 latter case, the buffer is set up in a way that saving it automatically kills
12037 the buffer and restores the previous window configuration."
12038 (interactive)
12039 (if (stringp org-agenda-files)
12040 (let ((cw (current-window-configuration)))
12041 (find-file org-agenda-files)
12042 (org-set-local 'org-window-configuration cw)
12043 (org-add-hook 'after-save-hook
12044 (lambda ()
12045 (set-window-configuration
12046 (prog1 org-window-configuration
12047 (kill-buffer (current-buffer))))
12048 (org-install-agenda-files-menu)
12049 (message "New agenda file list installed"))
12050 nil 'local)
12051 (message "%s" (substitute-command-keys
12052 "Edit list and finish with \\[save-buffer]")))
12053 (customize-variable 'org-agenda-files)))
12055 (defun org-store-new-agenda-file-list (list)
12056 "Set new value for the agenda file list and save it correctly."
12057 (if (stringp org-agenda-files)
12058 (let ((f org-agenda-files) b)
12059 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
12060 (with-temp-file f
12061 (insert (mapconcat 'identity list "\n") "\n")))
12062 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
12063 (setq org-agenda-files list)
12064 (customize-save-variable 'org-agenda-files org-agenda-files))))
12066 (defun org-read-agenda-file-list ()
12067 "Read the list of agenda files from a file."
12068 (when (file-directory-p org-agenda-files)
12069 (error "`org-agenda-files' cannot be a single directory"))
12070 (when (stringp org-agenda-files)
12071 (with-temp-buffer
12072 (insert-file-contents org-agenda-files)
12073 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
12076 ;;;###autoload
12077 (defun org-cycle-agenda-files ()
12078 "Cycle through the files in `org-agenda-files'.
12079 If the current buffer visits an agenda file, find the next one in the list.
12080 If the current buffer does not, find the first agenda file."
12081 (interactive)
12082 (let* ((fs (org-agenda-files t))
12083 (files (append fs (list (car fs))))
12084 (tcf (if buffer-file-name (file-truename buffer-file-name)))
12085 file)
12086 (unless files (error "No agenda files"))
12087 (catch 'exit
12088 (while (setq file (pop files))
12089 (if (equal (file-truename file) tcf)
12090 (when (car files)
12091 (find-file (car files))
12092 (throw 'exit t))))
12093 (find-file (car fs)))
12094 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
12096 (defun org-agenda-file-to-front (&optional to-end)
12097 "Move/add the current file to the top of the agenda file list.
12098 If the file is not present in the list, it is added to the front. If it is
12099 present, it is moved there. With optional argument TO-END, add/move to the
12100 end of the list."
12101 (interactive "P")
12102 (let ((org-agenda-skip-unavailable-files nil)
12103 (file-alist (mapcar (lambda (x)
12104 (cons (file-truename x) x))
12105 (org-agenda-files t)))
12106 (ctf (file-truename buffer-file-name))
12107 x had)
12108 (setq x (assoc ctf file-alist) had x)
12110 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
12111 (if to-end
12112 (setq file-alist (append (delq x file-alist) (list x)))
12113 (setq file-alist (cons x (delq x file-alist))))
12114 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
12115 (org-install-agenda-files-menu)
12116 (message "File %s to %s of agenda file list"
12117 (if had "moved" "added") (if to-end "end" "front"))))
12119 (defun org-remove-file (&optional file)
12120 "Remove current file from the list of files in variable `org-agenda-files'.
12121 These are the files which are being checked for agenda entries.
12122 Optional argument FILE means, use this file instead of the current."
12123 (interactive)
12124 (let* ((org-agenda-skip-unavailable-files nil)
12125 (file (or file buffer-file-name))
12126 (true-file (file-truename file))
12127 (afile (abbreviate-file-name file))
12128 (files (delq nil (mapcar
12129 (lambda (x)
12130 (if (equal true-file
12131 (file-truename x))
12132 nil x))
12133 (org-agenda-files t)))))
12134 (if (not (= (length files) (length (org-agenda-files t))))
12135 (progn
12136 (org-store-new-agenda-file-list files)
12137 (org-install-agenda-files-menu)
12138 (message "Removed file: %s" afile))
12139 (message "File was not in list: %s (not removed)" afile))))
12141 (defun org-file-menu-entry (file)
12142 (vector file (list 'find-file file) t))
12144 (defun org-check-agenda-file (file)
12145 "Make sure FILE exists. If not, ask user what to do."
12146 (when (not (file-exists-p file))
12147 (message "non-existent file %s. [R]emove from list or [A]bort?"
12148 (abbreviate-file-name file))
12149 (let ((r (downcase (read-char-exclusive))))
12150 (cond
12151 ((equal r ?r)
12152 (org-remove-file file)
12153 (throw 'nextfile t))
12154 (t (error "Abort"))))))
12156 (defun org-get-agenda-file-buffer (file)
12157 "Get a buffer visiting FILE. If the buffer needs to be created, add
12158 it to the list of buffers which might be released later."
12159 (let ((buf (org-find-base-buffer-visiting file)))
12160 (if buf
12161 buf ; just return it
12162 ;; Make a new buffer and remember it
12163 (setq buf (find-file-noselect file))
12164 (if buf (push buf org-agenda-new-buffers))
12165 buf)))
12167 (defun org-release-buffers (blist)
12168 "Release all buffers in list, asking the user for confirmation when needed.
12169 When a buffer is unmodified, it is just killed. When modified, it is saved
12170 \(if the user agrees) and then killed."
12171 (let (buf file)
12172 (while (setq buf (pop blist))
12173 (setq file (buffer-file-name buf))
12174 (when (and (buffer-modified-p buf)
12175 file
12176 (y-or-n-p (format "Save file %s? " file)))
12177 (with-current-buffer buf (save-buffer)))
12178 (kill-buffer buf))))
12180 (defun org-prepare-agenda-buffers (files)
12181 "Create buffers for all agenda files, protect archived trees and comments."
12182 (interactive)
12183 (let ((pa '(:org-archived t))
12184 (pc '(:org-comment t))
12185 (pall '(:org-archived t :org-comment t))
12186 (inhibit-read-only t)
12187 (rea (concat ":" org-archive-tag ":"))
12188 bmp file re)
12189 (save-excursion
12190 (save-restriction
12191 (while (setq file (pop files))
12192 (if (bufferp file)
12193 (set-buffer file)
12194 (org-check-agenda-file file)
12195 (set-buffer (org-get-agenda-file-buffer file)))
12196 (widen)
12197 (setq bmp (buffer-modified-p))
12198 (org-refresh-category-properties)
12199 (setq org-todo-keywords-for-agenda
12200 (append org-todo-keywords-for-agenda org-todo-keywords-1))
12201 (setq org-done-keywords-for-agenda
12202 (append org-done-keywords-for-agenda org-done-keywords))
12203 (setq org-todo-keyword-alist-for-agenda
12204 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
12205 (setq org-tag-alist-for-agenda
12206 (append org-tag-alist-for-agenda org-tag-alist))
12208 (save-excursion
12209 (remove-text-properties (point-min) (point-max) pall)
12210 (when org-agenda-skip-archived-trees
12211 (goto-char (point-min))
12212 (while (re-search-forward rea nil t)
12213 (if (org-on-heading-p t)
12214 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
12215 (goto-char (point-min))
12216 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
12217 (while (re-search-forward re nil t)
12218 (add-text-properties
12219 (match-beginning 0) (org-end-of-subtree t) pc)))
12220 (set-buffer-modified-p bmp))))
12221 (setq org-todo-keyword-alist-for-agenda
12222 (org-uniquify org-todo-keyword-alist-for-agenda)
12223 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
12225 ;;;; Embedded LaTeX
12227 (defvar org-cdlatex-mode-map (make-sparse-keymap)
12228 "Keymap for the minor `org-cdlatex-mode'.")
12230 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
12231 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
12232 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
12233 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
12234 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
12236 (defvar org-cdlatex-texmathp-advice-is-done nil
12237 "Flag remembering if we have applied the advice to texmathp already.")
12239 (define-minor-mode org-cdlatex-mode
12240 "Toggle the minor `org-cdlatex-mode'.
12241 This mode supports entering LaTeX environment and math in LaTeX fragments
12242 in Org-mode.
12243 \\{org-cdlatex-mode-map}"
12244 nil " OCDL" nil
12245 (when org-cdlatex-mode (require 'cdlatex))
12246 (unless org-cdlatex-texmathp-advice-is-done
12247 (setq org-cdlatex-texmathp-advice-is-done t)
12248 (defadvice texmathp (around org-math-always-on activate)
12249 "Always return t in org-mode buffers.
12250 This is because we want to insert math symbols without dollars even outside
12251 the LaTeX math segments. If Orgmode thinks that point is actually inside
12252 an embedded LaTeX fragment, let texmathp do its job.
12253 \\[org-cdlatex-mode-map]"
12254 (interactive)
12255 (let (p)
12256 (cond
12257 ((not (org-mode-p)) ad-do-it)
12258 ((eq this-command 'cdlatex-math-symbol)
12259 (setq ad-return-value t
12260 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
12262 (let ((p (org-inside-LaTeX-fragment-p)))
12263 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
12264 (setq ad-return-value t
12265 texmathp-why '("Org-mode embedded math" . 0))
12266 (if p ad-do-it)))))))))
12268 (defun turn-on-org-cdlatex ()
12269 "Unconditionally turn on `org-cdlatex-mode'."
12270 (org-cdlatex-mode 1))
12272 (defun org-inside-LaTeX-fragment-p ()
12273 "Test if point is inside a LaTeX fragment.
12274 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
12275 sequence appearing also before point.
12276 Even though the matchers for math are configurable, this function assumes
12277 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
12278 delimiters are skipped when they have been removed by customization.
12279 The return value is nil, or a cons cell with the delimiter and
12280 and the position of this delimiter.
12282 This function does a reasonably good job, but can locally be fooled by
12283 for example currency specifications. For example it will assume being in
12284 inline math after \"$22.34\". The LaTeX fragment formatter will only format
12285 fragments that are properly closed, but during editing, we have to live
12286 with the uncertainty caused by missing closing delimiters. This function
12287 looks only before point, not after."
12288 (catch 'exit
12289 (let ((pos (point))
12290 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
12291 (lim (progn
12292 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
12293 (point)))
12294 dd-on str (start 0) m re)
12295 (goto-char pos)
12296 (when dodollar
12297 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
12298 re (nth 1 (assoc "$" org-latex-regexps)))
12299 (while (string-match re str start)
12300 (cond
12301 ((= (match-end 0) (length str))
12302 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
12303 ((= (match-end 0) (- (length str) 5))
12304 (throw 'exit nil))
12305 (t (setq start (match-end 0))))))
12306 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
12307 (goto-char pos)
12308 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
12309 (and (match-beginning 2) (throw 'exit nil))
12310 ;; count $$
12311 (while (re-search-backward "\\$\\$" lim t)
12312 (setq dd-on (not dd-on)))
12313 (goto-char pos)
12314 (if dd-on (cons "$$" m))))))
12317 (defun org-try-cdlatex-tab ()
12318 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
12319 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
12320 - inside a LaTeX fragment, or
12321 - after the first word in a line, where an abbreviation expansion could
12322 insert a LaTeX environment."
12323 (when org-cdlatex-mode
12324 (cond
12325 ((save-excursion
12326 (skip-chars-backward "a-zA-Z0-9*")
12327 (skip-chars-backward " \t")
12328 (bolp))
12329 (cdlatex-tab) t)
12330 ((org-inside-LaTeX-fragment-p)
12331 (cdlatex-tab) t)
12332 (t nil))))
12334 (defun org-cdlatex-underscore-caret (&optional arg)
12335 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
12336 Revert to the normal definition outside of these fragments."
12337 (interactive "P")
12338 (if (org-inside-LaTeX-fragment-p)
12339 (call-interactively 'cdlatex-sub-superscript)
12340 (let (org-cdlatex-mode)
12341 (call-interactively (key-binding (vector last-input-event))))))
12343 (defun org-cdlatex-math-modify (&optional arg)
12344 "Execute `cdlatex-math-modify' in LaTeX fragments.
12345 Revert to the normal definition outside of these fragments."
12346 (interactive "P")
12347 (if (org-inside-LaTeX-fragment-p)
12348 (call-interactively 'cdlatex-math-modify)
12349 (let (org-cdlatex-mode)
12350 (call-interactively (key-binding (vector last-input-event))))))
12352 (defvar org-latex-fragment-image-overlays nil
12353 "List of overlays carrying the images of latex fragments.")
12354 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
12356 (defun org-remove-latex-fragment-image-overlays ()
12357 "Remove all overlays with LaTeX fragment images in current buffer."
12358 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
12359 (setq org-latex-fragment-image-overlays nil))
12361 (defun org-preview-latex-fragment (&optional subtree)
12362 "Preview the LaTeX fragment at point, or all locally or globally.
12363 If the cursor is in a LaTeX fragment, create the image and overlay
12364 it over the source code. If there is no fragment at point, display
12365 all fragments in the current text, from one headline to the next. With
12366 prefix SUBTREE, display all fragments in the current subtree. With a
12367 double prefix `C-u C-u', or when the cursor is before the first headline,
12368 display all fragments in the buffer.
12369 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
12370 (interactive "P")
12371 (org-remove-latex-fragment-image-overlays)
12372 (save-excursion
12373 (save-restriction
12374 (let (beg end at msg)
12375 (cond
12376 ((or (equal subtree '(16))
12377 (not (save-excursion
12378 (re-search-backward (concat "^" outline-regexp) nil t))))
12379 (setq beg (point-min) end (point-max)
12380 msg "Creating images for buffer...%s"))
12381 ((equal subtree '(4))
12382 (org-back-to-heading)
12383 (setq beg (point) end (org-end-of-subtree t)
12384 msg "Creating images for subtree...%s"))
12386 (if (setq at (org-inside-LaTeX-fragment-p))
12387 (goto-char (max (point-min) (- (cdr at) 2)))
12388 (org-back-to-heading))
12389 (setq beg (point) end (progn (outline-next-heading) (point))
12390 msg (if at "Creating image...%s"
12391 "Creating images for entry...%s"))))
12392 (message msg "")
12393 (narrow-to-region beg end)
12394 (goto-char beg)
12395 (org-format-latex
12396 (concat "ltxpng/" (file-name-sans-extension
12397 (file-name-nondirectory
12398 buffer-file-name)))
12399 default-directory 'overlays msg at 'forbuffer)
12400 (message msg "done. Use `C-c C-c' to remove images.")))))
12402 (defvar org-latex-regexps
12403 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
12404 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
12405 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
12406 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
12407 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
12408 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
12409 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
12410 "Regular expressions for matching embedded LaTeX.")
12412 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
12413 "Replace LaTeX fragments with links to an image, and produce images."
12414 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
12415 (let* ((prefixnodir (file-name-nondirectory prefix))
12416 (absprefix (expand-file-name prefix dir))
12417 (todir (file-name-directory absprefix))
12418 (opt org-format-latex-options)
12419 (matchers (plist-get opt :matchers))
12420 (re-list org-latex-regexps)
12421 (cnt 0) txt link beg end re e checkdir
12422 m n block linkfile movefile ov)
12423 ;; Check if there are old images files with this prefix, and remove them
12424 (when (file-directory-p todir)
12425 (mapc 'delete-file
12426 (directory-files
12427 todir 'full
12428 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
12429 ;; Check the different regular expressions
12430 (while (setq e (pop re-list))
12431 (setq m (car e) re (nth 1 e) n (nth 2 e)
12432 block (if (nth 3 e) "\n\n" ""))
12433 (when (member m matchers)
12434 (goto-char (point-min))
12435 (while (re-search-forward re nil t)
12436 (when (or (not at) (equal (cdr at) (match-beginning n)))
12437 (setq txt (match-string n)
12438 beg (match-beginning n) end (match-end n)
12439 cnt (1+ cnt)
12440 linkfile (format "%s_%04d.png" prefix cnt)
12441 movefile (format "%s_%04d.png" absprefix cnt)
12442 link (concat block "[[file:" linkfile "]]" block))
12443 (if msg (message msg cnt))
12444 (goto-char beg)
12445 (unless checkdir ; make sure the directory exists
12446 (setq checkdir t)
12447 (or (file-directory-p todir) (make-directory todir)))
12448 (org-create-formula-image
12449 txt movefile opt forbuffer)
12450 (if overlays
12451 (progn
12452 (setq ov (org-make-overlay beg end))
12453 (if (featurep 'xemacs)
12454 (progn
12455 (org-overlay-put ov 'invisible t)
12456 (org-overlay-put
12457 ov 'end-glyph
12458 (make-glyph (vector 'png :file movefile))))
12459 (org-overlay-put
12460 ov 'display
12461 (list 'image :type 'png :file movefile :ascent 'center)))
12462 (push ov org-latex-fragment-image-overlays)
12463 (goto-char end))
12464 (delete-region beg end)
12465 (insert link))))))))
12467 ;; This function borrows from Ganesh Swami's latex2png.el
12468 (defun org-create-formula-image (string tofile options buffer)
12469 (let* ((tmpdir (if (featurep 'xemacs)
12470 (temp-directory)
12471 temporary-file-directory))
12472 (texfilebase (make-temp-name
12473 (expand-file-name "orgtex" tmpdir)))
12474 (texfile (concat texfilebase ".tex"))
12475 (dvifile (concat texfilebase ".dvi"))
12476 (pngfile (concat texfilebase ".png"))
12477 (fnh (if (featurep 'xemacs)
12478 (font-height (get-face-font 'default))
12479 (face-attribute 'default :height nil)))
12480 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
12481 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
12482 (fg (or (plist-get options (if buffer :foreground :html-foreground))
12483 "Black"))
12484 (bg (or (plist-get options (if buffer :background :html-background))
12485 "Transparent")))
12486 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
12487 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
12488 (with-temp-file texfile
12489 (insert org-format-latex-header
12490 "\n\\begin{document}\n" string "\n\\end{document}\n"))
12491 (let ((dir default-directory))
12492 (condition-case nil
12493 (progn
12494 (cd tmpdir)
12495 (call-process "latex" nil nil nil texfile))
12496 (error nil))
12497 (cd dir))
12498 (if (not (file-exists-p dvifile))
12499 (progn (message "Failed to create dvi file from %s" texfile) nil)
12500 (condition-case nil
12501 (call-process "dvipng" nil nil nil
12502 "-E" "-fg" fg "-bg" bg
12503 "-D" dpi
12504 ;;"-x" scale "-y" scale
12505 "-T" "tight"
12506 "-o" pngfile
12507 dvifile)
12508 (error nil))
12509 (if (not (file-exists-p pngfile))
12510 (progn (message "Failed to create png file from %s" texfile) nil)
12511 ;; Use the requested file name and clean up
12512 (copy-file pngfile tofile 'replace)
12513 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
12514 (delete-file (concat texfilebase e)))
12515 pngfile))))
12517 (defun org-dvipng-color (attr)
12518 "Return an rgb color specification for dvipng."
12519 (apply 'format "rgb %s %s %s"
12520 (mapcar 'org-normalize-color
12521 (color-values (face-attribute 'default attr nil)))))
12523 (defun org-normalize-color (value)
12524 "Return string to be used as color value for an RGB component."
12525 (format "%g" (/ value 65535.0)))
12527 ;;;; Key bindings
12529 ;; Make `C-c C-x' a prefix key
12530 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
12532 ;; TAB key with modifiers
12533 (org-defkey org-mode-map "\C-i" 'org-cycle)
12534 (org-defkey org-mode-map [(tab)] 'org-cycle)
12535 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
12536 (org-defkey org-mode-map [(meta tab)] 'org-complete)
12537 (org-defkey org-mode-map "\M-\t" 'org-complete)
12538 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
12539 ;; The following line is necessary under Suse GNU/Linux
12540 (unless (featurep 'xemacs)
12541 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
12542 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
12543 (define-key org-mode-map [backtab] 'org-shifttab)
12545 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
12546 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
12547 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
12549 ;; Cursor keys with modifiers
12550 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
12551 (org-defkey org-mode-map [(meta right)] 'org-metaright)
12552 (org-defkey org-mode-map [(meta up)] 'org-metaup)
12553 (org-defkey org-mode-map [(meta down)] 'org-metadown)
12555 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
12556 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
12557 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
12558 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
12560 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
12561 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
12562 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
12563 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
12565 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
12566 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
12568 ;;; Extra keys for tty access.
12569 ;; We only set them when really needed because otherwise the
12570 ;; menus don't show the simple keys
12572 (when (or org-use-extra-keys
12573 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
12574 (not window-system))
12575 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
12576 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
12577 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
12578 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
12579 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
12580 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
12581 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
12582 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
12583 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
12584 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
12585 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
12586 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
12587 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
12588 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
12589 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
12590 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
12591 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
12592 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
12593 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
12594 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
12595 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
12596 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
12598 ;; All the other keys
12600 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
12601 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
12602 (if (boundp 'narrow-map)
12603 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
12604 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
12605 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
12606 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
12607 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
12608 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
12609 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
12610 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
12611 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
12612 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
12613 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
12614 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
12615 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
12616 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
12617 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
12618 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
12619 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
12620 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
12621 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
12622 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
12623 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
12624 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
12625 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
12626 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
12627 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
12628 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
12629 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
12630 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
12631 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
12632 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
12633 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
12634 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
12635 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
12636 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
12637 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
12638 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
12639 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
12640 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
12641 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
12642 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
12643 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
12644 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
12645 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
12646 (org-defkey org-mode-map "\C-c^" 'org-sort)
12647 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
12648 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
12649 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
12650 (org-defkey org-mode-map "\C-m" 'org-return)
12651 (org-defkey org-mode-map "\C-j" 'org-return-indent)
12652 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
12653 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
12654 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
12655 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
12656 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
12657 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
12658 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
12659 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
12660 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
12661 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
12662 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
12663 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
12664 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
12665 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
12666 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
12667 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
12669 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
12670 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
12671 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
12672 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
12674 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
12675 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
12676 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
12677 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
12678 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
12679 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
12680 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
12681 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
12682 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
12683 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
12684 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
12685 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
12687 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
12688 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
12689 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
12691 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
12693 (when (featurep 'xemacs)
12694 (org-defkey org-mode-map 'button3 'popup-mode-menu))
12696 (defvar org-table-auto-blank-field) ; defined in org-table.el
12697 (defun org-self-insert-command (N)
12698 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
12699 If the cursor is in a table looking at whitespace, the whitespace is
12700 overwritten, and the table is not marked as requiring realignment."
12701 (interactive "p")
12702 (if (and (org-table-p)
12703 (progn
12704 ;; check if we blank the field, and if that triggers align
12705 (and (featurep 'org-table) org-table-auto-blank-field
12706 (member last-command
12707 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
12708 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
12709 ;; got extra space, this field does not determine column width
12710 (let (org-table-may-need-update) (org-table-blank-field))
12711 ;; no extra space, this field may determine column width
12712 (org-table-blank-field)))
12714 (eq N 1)
12715 (looking-at "[^|\n]* |"))
12716 (let (org-table-may-need-update)
12717 (goto-char (1- (match-end 0)))
12718 (delete-backward-char 1)
12719 (goto-char (match-beginning 0))
12720 (self-insert-command N))
12721 (setq org-table-may-need-update t)
12722 (self-insert-command N)
12723 (org-fix-tags-on-the-fly)))
12725 (defun org-fix-tags-on-the-fly ()
12726 (when (and (equal (char-after (point-at-bol)) ?*)
12727 (org-on-heading-p))
12728 (org-align-tags-here org-tags-column)))
12730 (defun org-delete-backward-char (N)
12731 "Like `delete-backward-char', insert whitespace at field end in tables.
12732 When deleting backwards, in tables this function will insert whitespace in
12733 front of the next \"|\" separator, to keep the table aligned. The table will
12734 still be marked for re-alignment if the field did fill the entire column,
12735 because, in this case the deletion might narrow the column."
12736 (interactive "p")
12737 (if (and (org-table-p)
12738 (eq N 1)
12739 (string-match "|" (buffer-substring (point-at-bol) (point)))
12740 (looking-at ".*?|"))
12741 (let ((pos (point))
12742 (noalign (looking-at "[^|\n\r]* |"))
12743 (c org-table-may-need-update))
12744 (backward-delete-char N)
12745 (skip-chars-forward "^|")
12746 (insert " ")
12747 (goto-char (1- pos))
12748 ;; noalign: if there were two spaces at the end, this field
12749 ;; does not determine the width of the column.
12750 (if noalign (setq org-table-may-need-update c)))
12751 (backward-delete-char N)
12752 (org-fix-tags-on-the-fly)))
12754 (defun org-delete-char (N)
12755 "Like `delete-char', but insert whitespace at field end in tables.
12756 When deleting characters, in tables this function will insert whitespace in
12757 front of the next \"|\" separator, to keep the table aligned. The table will
12758 still be marked for re-alignment if the field did fill the entire column,
12759 because, in this case the deletion might narrow the column."
12760 (interactive "p")
12761 (if (and (org-table-p)
12762 (not (bolp))
12763 (not (= (char-after) ?|))
12764 (eq N 1))
12765 (if (looking-at ".*?|")
12766 (let ((pos (point))
12767 (noalign (looking-at "[^|\n\r]* |"))
12768 (c org-table-may-need-update))
12769 (replace-match (concat
12770 (substring (match-string 0) 1 -1)
12771 " |"))
12772 (goto-char pos)
12773 ;; noalign: if there were two spaces at the end, this field
12774 ;; does not determine the width of the column.
12775 (if noalign (setq org-table-may-need-update c)))
12776 (delete-char N))
12777 (delete-char N)
12778 (org-fix-tags-on-the-fly)))
12780 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
12781 (put 'org-self-insert-command 'delete-selection t)
12782 (put 'orgtbl-self-insert-command 'delete-selection t)
12783 (put 'org-delete-char 'delete-selection 'supersede)
12784 (put 'org-delete-backward-char 'delete-selection 'supersede)
12786 ;; Make `flyspell-mode' delay after some commands
12787 (put 'org-self-insert-command 'flyspell-delayed t)
12788 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
12789 (put 'org-delete-char 'flyspell-delayed t)
12790 (put 'org-delete-backward-char 'flyspell-delayed t)
12792 ;; Make pabbrev-mode expand after org-mode commands
12793 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
12794 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
12796 ;; How to do this: Measure non-white length of current string
12797 ;; If equal to column width, we should realign.
12799 (defun org-remap (map &rest commands)
12800 "In MAP, remap the functions given in COMMANDS.
12801 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
12802 (let (new old)
12803 (while commands
12804 (setq old (pop commands) new (pop commands))
12805 (if (fboundp 'command-remapping)
12806 (org-defkey map (vector 'remap old) new)
12807 (substitute-key-definition old new map global-map)))))
12809 (when (eq org-enable-table-editor 'optimized)
12810 ;; If the user wants maximum table support, we need to hijack
12811 ;; some standard editing functions
12812 (org-remap org-mode-map
12813 'self-insert-command 'org-self-insert-command
12814 'delete-char 'org-delete-char
12815 'delete-backward-char 'org-delete-backward-char)
12816 (org-defkey org-mode-map "|" 'org-force-self-insert))
12818 (defun org-shiftcursor-error ()
12819 "Throw an error because Shift-Cursor command was applied in wrong context."
12820 (error "This command is active in special context like tables, headlines or timestamps"))
12822 (defun org-shifttab (&optional arg)
12823 "Global visibility cycling or move to previous table field.
12824 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
12825 on context.
12826 See the individual commands for more information."
12827 (interactive "P")
12828 (cond
12829 ((org-at-table-p) (call-interactively 'org-table-previous-field))
12830 ((integerp arg)
12831 (message "Content view to level: %d" arg)
12832 (org-content (prefix-numeric-value arg))
12833 (setq org-cycle-global-status 'overview))
12834 (t (call-interactively 'org-global-cycle))))
12836 (defun org-shiftmetaleft ()
12837 "Promote subtree or delete table column.
12838 Calls `org-promote-subtree', `org-outdent-item',
12839 or `org-table-delete-column', depending on context.
12840 See the individual commands for more information."
12841 (interactive)
12842 (cond
12843 ((org-at-table-p) (call-interactively 'org-table-delete-column))
12844 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
12845 ((org-at-item-p) (call-interactively 'org-outdent-item))
12846 (t (org-shiftcursor-error))))
12848 (defun org-shiftmetaright ()
12849 "Demote subtree or insert table column.
12850 Calls `org-demote-subtree', `org-indent-item',
12851 or `org-table-insert-column', depending on context.
12852 See the individual commands for more information."
12853 (interactive)
12854 (cond
12855 ((org-at-table-p) (call-interactively 'org-table-insert-column))
12856 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
12857 ((org-at-item-p) (call-interactively 'org-indent-item))
12858 (t (org-shiftcursor-error))))
12860 (defun org-shiftmetaup (&optional arg)
12861 "Move subtree up or kill table row.
12862 Calls `org-move-subtree-up' or `org-table-kill-row' or
12863 `org-move-item-up' depending on context. See the individual commands
12864 for more information."
12865 (interactive "P")
12866 (cond
12867 ((org-at-table-p) (call-interactively 'org-table-kill-row))
12868 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12869 ((org-at-item-p) (call-interactively 'org-move-item-up))
12870 (t (org-shiftcursor-error))))
12871 (defun org-shiftmetadown (&optional arg)
12872 "Move subtree down or insert table row.
12873 Calls `org-move-subtree-down' or `org-table-insert-row' or
12874 `org-move-item-down', depending on context. See the individual
12875 commands for more information."
12876 (interactive "P")
12877 (cond
12878 ((org-at-table-p) (call-interactively 'org-table-insert-row))
12879 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12880 ((org-at-item-p) (call-interactively 'org-move-item-down))
12881 (t (org-shiftcursor-error))))
12883 (defun org-metaleft (&optional arg)
12884 "Promote heading or move table column to left.
12885 Calls `org-do-promote' or `org-table-move-column', depending on context.
12886 With no specific context, calls the Emacs default `backward-word'.
12887 See the individual commands for more information."
12888 (interactive "P")
12889 (cond
12890 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
12891 ((or (org-on-heading-p) (org-region-active-p))
12892 (call-interactively 'org-do-promote))
12893 ((org-at-item-p) (call-interactively 'org-outdent-item))
12894 (t (call-interactively 'backward-word))))
12896 (defun org-metaright (&optional arg)
12897 "Demote subtree or move table column to right.
12898 Calls `org-do-demote' or `org-table-move-column', depending on context.
12899 With no specific context, calls the Emacs default `forward-word'.
12900 See the individual commands for more information."
12901 (interactive "P")
12902 (cond
12903 ((org-at-table-p) (call-interactively 'org-table-move-column))
12904 ((or (org-on-heading-p) (org-region-active-p))
12905 (call-interactively 'org-do-demote))
12906 ((org-at-item-p) (call-interactively 'org-indent-item))
12907 (t (call-interactively 'forward-word))))
12909 (defun org-metaup (&optional arg)
12910 "Move subtree up or move table row up.
12911 Calls `org-move-subtree-up' or `org-table-move-row' or
12912 `org-move-item-up', depending on context. See the individual commands
12913 for more information."
12914 (interactive "P")
12915 (cond
12916 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
12917 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12918 ((org-at-item-p) (call-interactively 'org-move-item-up))
12919 (t (transpose-lines 1) (beginning-of-line -1))))
12921 (defun org-metadown (&optional arg)
12922 "Move subtree down or move table row down.
12923 Calls `org-move-subtree-down' or `org-table-move-row' or
12924 `org-move-item-down', depending on context. See the individual
12925 commands for more information."
12926 (interactive "P")
12927 (cond
12928 ((org-at-table-p) (call-interactively 'org-table-move-row))
12929 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12930 ((org-at-item-p) (call-interactively 'org-move-item-down))
12931 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
12933 (defun org-shiftup (&optional arg)
12934 "Increase item in timestamp or increase priority of current headline.
12935 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
12936 depending on context. See the individual commands for more information."
12937 (interactive "P")
12938 (cond
12939 ((org-at-timestamp-p t)
12940 (call-interactively (if org-edit-timestamp-down-means-later
12941 'org-timestamp-down 'org-timestamp-up)))
12942 ((org-on-heading-p) (call-interactively 'org-priority-up))
12943 ((org-at-item-p) (call-interactively 'org-previous-item))
12944 ((org-clocktable-try-shift 'up arg))
12945 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
12947 (defun org-shiftdown (&optional arg)
12948 "Decrease item in timestamp or decrease priority of current headline.
12949 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
12950 depending on context. See the individual commands for more information."
12951 (interactive "P")
12952 (cond
12953 ((org-at-timestamp-p t)
12954 (call-interactively (if org-edit-timestamp-down-means-later
12955 'org-timestamp-up 'org-timestamp-down)))
12956 ((org-on-heading-p) (call-interactively 'org-priority-down))
12957 ((org-clocktable-try-shift 'down arg))
12958 (t (call-interactively 'org-next-item))))
12960 (defun org-shiftright (&optional arg)
12961 "Cycle the thing at point or in the current line, depending on context.
12962 Depending on context, this does one of the following:
12964 - switch a timestamp at point one day into the future
12965 - on a headline, switch to the next TODO keyword.
12966 - on an item, switch entire list to the next bullet type
12967 - on a property line, switch to the next allowed value
12968 - on a clocktable definition line, move time block into the future"
12969 (interactive "P")
12970 (cond
12971 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
12972 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
12973 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
12974 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
12975 ((org-clocktable-try-shift 'right arg))
12976 (t (org-shiftcursor-error))))
12978 (defun org-shiftleft (&optional arg)
12979 "Cycle the thing at point or in the current line, depending on context.
12980 Depending on context, this does one of the following:
12982 - switch a timestamp at point one day into the past
12983 - on a headline, switch to the previous TODO keyword.
12984 - on an item, switch entire list to the previous bullet type
12985 - on a property line, switch to the previous allowed value
12986 - on a clocktable definition line, move time block into the past"
12987 (interactive "P")
12988 (cond
12989 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
12990 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
12991 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
12992 ((org-at-property-p)
12993 (call-interactively 'org-property-previous-allowed-value))
12994 ((org-clocktable-try-shift 'left arg))
12995 (t (org-shiftcursor-error))))
12997 (defun org-shiftcontrolright ()
12998 "Switch to next TODO set."
12999 (interactive)
13000 (cond
13001 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
13002 (t (org-shiftcursor-error))))
13004 (defun org-shiftcontrolleft ()
13005 "Switch to previous TODO set."
13006 (interactive)
13007 (cond
13008 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
13009 (t (org-shiftcursor-error))))
13011 (defun org-ctrl-c-ret ()
13012 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
13013 (interactive)
13014 (cond
13015 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
13016 (t (call-interactively 'org-insert-heading))))
13018 (defun org-copy-special ()
13019 "Copy region in table or copy current subtree.
13020 Calls `org-table-copy' or `org-copy-subtree', depending on context.
13021 See the individual commands for more information."
13022 (interactive)
13023 (call-interactively
13024 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
13026 (defun org-cut-special ()
13027 "Cut region in table or cut current subtree.
13028 Calls `org-table-copy' or `org-cut-subtree', depending on context.
13029 See the individual commands for more information."
13030 (interactive)
13031 (call-interactively
13032 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
13034 (defun org-paste-special (arg)
13035 "Paste rectangular region into table, or past subtree relative to level.
13036 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
13037 See the individual commands for more information."
13038 (interactive "P")
13039 (if (org-at-table-p)
13040 (org-table-paste-rectangle)
13041 (org-paste-subtree arg)))
13043 (defun org-edit-special ()
13044 "Call a special editor for the stuff at point.
13045 When at a table, call the formula editor with `org-table-edit-formulas'.
13046 When at the first line of an src example, call `org-edit-src-code'.
13047 When in an #+include line, visit the include file. Otherwise call
13048 `ffap' to visit the file at point."
13049 (interactive)
13050 (cond
13051 ((org-at-table-p)
13052 (call-interactively 'org-table-edit-formulas))
13053 ((save-excursion
13054 (beginning-of-line 1)
13055 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
13056 (find-file (org-trim (match-string 1))))
13057 ((org-edit-src-code))
13058 ((org-edit-fixed-width-region))
13059 (t (call-interactively 'ffap))))
13061 (defun org-ctrl-c-ctrl-c (&optional arg)
13062 "Set tags in headline, or update according to changed information at point.
13064 This command does many different things, depending on context:
13066 - If the cursor is in a headline, prompt for tags and insert them
13067 into the current line, aligned to `org-tags-column'. When called
13068 with prefix arg, realign all tags in the current buffer.
13070 - If the cursor is in one of the special #+KEYWORD lines, this
13071 triggers scanning the buffer for these lines and updating the
13072 information.
13074 - If the cursor is inside a table, realign the table. This command
13075 works even if the automatic table editor has been turned off.
13077 - If the cursor is on a #+TBLFM line, re-apply the formulas to
13078 the entire table.
13080 - If the cursor is at a footnote reference or definition, jump to
13081 the corresponding definition or references, respectively.
13083 - If the cursor is a the beginning of a dynamic block, update it.
13085 - If the cursor is inside a table created by the table.el package,
13086 activate that table.
13088 - If the current buffer is a remember buffer, close note and file
13089 it. A prefix argument of 1 files to the default location
13090 without further interaction. A prefix argument of 2 files to
13091 the currently clocking task.
13093 - If the cursor is on a <<<target>>>, update radio targets and corresponding
13094 links in this buffer.
13096 - If the cursor is on a numbered item in a plain list, renumber the
13097 ordered list.
13099 - If the cursor is on a checkbox, toggle it."
13100 (interactive "P")
13101 (let ((org-enable-table-editor t))
13102 (cond
13103 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
13104 org-occur-highlights
13105 org-latex-fragment-image-overlays)
13106 (and (boundp 'org-clock-overlays) (org-remove-clock-overlays))
13107 (org-remove-occur-highlights)
13108 (org-remove-latex-fragment-image-overlays)
13109 (message "Temporary highlights/overlays removed from current buffer"))
13110 ((and (local-variable-p 'org-finish-function (current-buffer))
13111 (fboundp org-finish-function))
13112 (funcall org-finish-function))
13113 ((org-at-property-p)
13114 (call-interactively 'org-property-action))
13115 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
13116 ((org-on-heading-p) (call-interactively 'org-set-tags))
13117 ((org-at-table.el-p)
13118 (require 'table)
13119 (beginning-of-line 1)
13120 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
13121 (call-interactively 'table-recognize-table))
13122 ((org-at-table-p)
13123 (org-table-maybe-eval-formula)
13124 (if arg
13125 (call-interactively 'org-table-recalculate)
13126 (org-table-maybe-recalculate-line))
13127 (call-interactively 'org-table-align))
13128 ((or (org-footnote-at-reference-p)
13129 (org-footnote-at-definition-p))
13130 (call-interactively 'org-footnote-action))
13131 ((org-at-item-checkbox-p)
13132 (call-interactively 'org-toggle-checkbox))
13133 ((org-at-item-p)
13134 (call-interactively 'org-maybe-renumber-ordered-list))
13135 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
13136 ;; Dynamic block
13137 (beginning-of-line 1)
13138 (save-excursion (org-update-dblock)))
13139 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
13140 (cond
13141 ((equal (match-string 1) "TBLFM")
13142 ;; Recalculate the table before this line
13143 (save-excursion
13144 (beginning-of-line 1)
13145 (skip-chars-backward " \r\n\t")
13146 (if (org-at-table-p)
13147 (org-call-with-arg 'org-table-recalculate t))))
13149 ; (org-set-regexps-and-options)
13150 ; (org-restart-font-lock)
13151 (let ((org-inhibit-startup t)) (org-mode-restart))
13152 (message "Local setup has been refreshed"))))
13153 (t (error "C-c C-c can do nothing useful at this location.")))))
13155 (defun org-mode-restart ()
13156 "Restart Org-mode, to scan again for special lines.
13157 Also updates the keyword regular expressions."
13158 (interactive)
13159 (org-mode)
13160 (message "Org-mode restarted"))
13162 (defun org-kill-note-or-show-branches ()
13163 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
13164 (interactive)
13165 (if (not org-finish-function)
13166 (call-interactively 'show-branches)
13167 (let ((org-note-abort t))
13168 (funcall org-finish-function))))
13170 (defun org-return (&optional indent)
13171 "Goto next table row or insert a newline.
13172 Calls `org-table-next-row' or `newline', depending on context.
13173 See the individual commands for more information."
13174 (interactive)
13175 (cond
13176 ((bobp) (if indent (newline-and-indent) (newline)))
13177 ((and (org-at-heading-p)
13178 (looking-at
13179 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
13180 (org-show-entry)
13181 (end-of-line 1)
13182 (newline))
13183 ((org-at-table-p)
13184 (org-table-justify-field-maybe)
13185 (call-interactively 'org-table-next-row))
13186 (t (if indent (newline-and-indent) (newline)))))
13188 (defun org-return-indent ()
13189 "Goto next table row or insert a newline and indent.
13190 Calls `org-table-next-row' or `newline-and-indent', depending on
13191 context. See the individual commands for more information."
13192 (interactive)
13193 (org-return t))
13195 (defun org-ctrl-c-star ()
13196 "Compute table, or change heading status of lines.
13197 Calls `org-table-recalculate' or `org-toggle-region-headings',
13198 depending on context. This will also turn a plain list item or a normal
13199 line into a subheading."
13200 (interactive)
13201 (cond
13202 ((org-at-table-p)
13203 (call-interactively 'org-table-recalculate))
13204 ((org-region-active-p)
13205 ;; Convert all lines in region to list items
13206 (call-interactively 'org-toggle-region-headings))
13207 ((org-on-heading-p)
13208 (org-toggle-region-headings (point-at-bol)
13209 (min (1+ (point-at-eol)) (point-max))))
13210 ((org-at-item-p)
13211 ;; Convert to heading
13212 (let ((level (save-match-data
13213 (save-excursion
13214 (condition-case nil
13215 (progn
13216 (org-back-to-heading t)
13217 (funcall outline-level))
13218 (error 0))))))
13219 (replace-match
13220 (concat (make-string (org-get-valid-level level 1) ?*) " ") t t)))
13221 (t (org-toggle-region-headings (point-at-bol)
13222 (min (1+ (point-at-eol)) (point-max))))))
13224 (defun org-ctrl-c-minus ()
13225 "Insert separator line in table or modify bullet status of line.
13226 Also turns a plain line or a region of lines into list items.
13227 Calls `org-table-insert-hline', `org-toggle-region-items', or
13228 `org-cycle-list-bullet', depending on context."
13229 (interactive)
13230 (cond
13231 ((org-at-table-p)
13232 (call-interactively 'org-table-insert-hline))
13233 ((org-on-heading-p)
13234 ;; Convert to item
13235 (save-excursion
13236 (beginning-of-line 1)
13237 (if (looking-at "\\*+ ")
13238 (replace-match
13239 (concat (make-string
13240 (- (match-end 0) (point) (if org-odd-levels-only 2 1)) ?\ )
13241 "- ")))))
13242 ((org-region-active-p)
13243 ;; Convert all lines in region to list items
13244 (call-interactively 'org-toggle-region-items))
13245 ((org-in-item-p)
13246 (call-interactively 'org-cycle-list-bullet))
13247 (t (org-toggle-region-items (point-at-bol)
13248 (min (1+ (point-at-eol)) (point-max))))))
13250 (defun org-toggle-region-items (beg end)
13251 "Convert all lines in region to list items.
13252 If the first line is already an item, convert all list items in the region
13253 to normal lines."
13254 (interactive "r")
13255 (let (l2 l)
13256 (save-excursion
13257 (goto-char end)
13258 (setq l2 (org-current-line))
13259 (goto-char beg)
13260 (beginning-of-line 1)
13261 (setq l (1- (org-current-line)))
13262 (if (org-at-item-p)
13263 ;; We already have items, de-itemize
13264 (while (< (setq l (1+ l)) l2)
13265 (when (org-at-item-p)
13266 (goto-char (match-beginning 2))
13267 (delete-region (match-beginning 2) (match-end 2))
13268 (and (looking-at "[ \t]+") (replace-match "")))
13269 (beginning-of-line 2))
13270 (while (< (setq l (1+ l)) l2)
13271 (unless (org-at-item-p)
13272 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
13273 (replace-match "\\1- \\2")))
13274 (beginning-of-line 2))))))
13276 (defun org-toggle-region-headings (beg end)
13277 "Convert all lines in region to list items.
13278 If the first line is already an item, convert all list items in the region
13279 to normal lines."
13280 (interactive "r")
13281 (let (l2 l)
13282 (save-excursion
13283 (goto-char end)
13284 (setq l2 (org-current-line))
13285 (goto-char beg)
13286 (beginning-of-line 1)
13287 (setq l (1- (org-current-line)))
13288 (if (org-on-heading-p)
13289 ;; We already have headlines, de-star them
13290 (while (< (setq l (1+ l)) l2)
13291 (when (org-on-heading-p t)
13292 (and (looking-at outline-regexp) (replace-match "")))
13293 (beginning-of-line 2))
13294 (let* ((stars (save-excursion
13295 (re-search-backward org-complex-heading-regexp nil t)
13296 (or (match-string 1) "*")))
13297 (add-stars (if org-odd-levels-only "**" "*"))
13298 (rpl (concat stars add-stars " \\2")))
13299 (while (< (setq l (1+ l)) l2)
13300 (unless (org-on-heading-p)
13301 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
13302 (replace-match rpl)))
13303 (beginning-of-line 2)))))))
13305 (defun org-meta-return (&optional arg)
13306 "Insert a new heading or wrap a region in a table.
13307 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
13308 See the individual commands for more information."
13309 (interactive "P")
13310 (cond
13311 ((org-at-table-p)
13312 (call-interactively 'org-table-wrap-region))
13313 (t (call-interactively 'org-insert-heading))))
13315 ;;; Menu entries
13317 ;; Define the Org-mode menus
13318 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
13319 '("Tbl"
13320 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
13321 ["Next Field" org-cycle (org-at-table-p)]
13322 ["Previous Field" org-shifttab (org-at-table-p)]
13323 ["Next Row" org-return (org-at-table-p)]
13324 "--"
13325 ["Blank Field" org-table-blank-field (org-at-table-p)]
13326 ["Edit Field" org-table-edit-field (org-at-table-p)]
13327 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
13328 "--"
13329 ("Column"
13330 ["Move Column Left" org-metaleft (org-at-table-p)]
13331 ["Move Column Right" org-metaright (org-at-table-p)]
13332 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
13333 ["Insert Column" org-shiftmetaright (org-at-table-p)])
13334 ("Row"
13335 ["Move Row Up" org-metaup (org-at-table-p)]
13336 ["Move Row Down" org-metadown (org-at-table-p)]
13337 ["Delete Row" org-shiftmetaup (org-at-table-p)]
13338 ["Insert Row" org-shiftmetadown (org-at-table-p)]
13339 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
13340 "--"
13341 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
13342 ("Rectangle"
13343 ["Copy Rectangle" org-copy-special (org-at-table-p)]
13344 ["Cut Rectangle" org-cut-special (org-at-table-p)]
13345 ["Paste Rectangle" org-paste-special (org-at-table-p)]
13346 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
13347 "--"
13348 ("Calculate"
13349 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
13350 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
13351 ["Edit Formulas" org-edit-special (org-at-table-p)]
13352 "--"
13353 ["Recalculate line" org-table-recalculate (org-at-table-p)]
13354 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
13355 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
13356 "--"
13357 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
13358 "--"
13359 ["Sum Column/Rectangle" org-table-sum
13360 (or (org-at-table-p) (org-region-active-p))]
13361 ["Which Column?" org-table-current-column (org-at-table-p)])
13362 ["Debug Formulas"
13363 org-table-toggle-formula-debugger
13364 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
13365 ["Show Col/Row Numbers"
13366 org-table-toggle-coordinate-overlays
13367 :style toggle
13368 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
13369 "--"
13370 ["Create" org-table-create (and (not (org-at-table-p))
13371 org-enable-table-editor)]
13372 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
13373 ["Import from File" org-table-import (not (org-at-table-p))]
13374 ["Export to File" org-table-export (org-at-table-p)]
13375 "--"
13376 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
13378 (easy-menu-define org-org-menu org-mode-map "Org menu"
13379 '("Org"
13380 ("Show/Hide"
13381 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
13382 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
13383 ["Sparse Tree..." org-sparse-tree t]
13384 ["Reveal Context" org-reveal t]
13385 ["Show All" show-all t]
13386 "--"
13387 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
13388 "--"
13389 ["New Heading" org-insert-heading t]
13390 ("Navigate Headings"
13391 ["Up" outline-up-heading t]
13392 ["Next" outline-next-visible-heading t]
13393 ["Previous" outline-previous-visible-heading t]
13394 ["Next Same Level" outline-forward-same-level t]
13395 ["Previous Same Level" outline-backward-same-level t]
13396 "--"
13397 ["Jump" org-goto t])
13398 ("Edit Structure"
13399 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
13400 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
13401 "--"
13402 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
13403 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
13404 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
13405 "--"
13406 ["Promote Heading" org-metaleft (not (org-at-table-p))]
13407 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
13408 ["Demote Heading" org-metaright (not (org-at-table-p))]
13409 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
13410 "--"
13411 ["Sort Region/Children" org-sort (not (org-at-table-p))]
13412 "--"
13413 ["Convert to odd levels" org-convert-to-odd-levels t]
13414 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
13415 ("Editing"
13416 ["Emphasis..." org-emphasize t]
13417 ["Edit Source Example" org-edit-special t]
13418 "--"
13419 ["Footnote new/jump" org-footnote-action t]
13420 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
13421 ("Archive"
13422 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
13423 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
13424 ; :active t :keys "C-u C-c C-x C-a"]
13425 ["Sparse trees open ARCHIVE trees"
13426 (setq org-sparse-tree-open-archived-trees
13427 (not org-sparse-tree-open-archived-trees))
13428 :style toggle :selected org-sparse-tree-open-archived-trees]
13429 ["Cycling opens ARCHIVE trees"
13430 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
13431 :style toggle :selected org-cycle-open-archived-trees]
13432 "--"
13433 ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
13434 ["Move Subtree to Archive" org-advertized-archive-subtree t]
13435 ; ["Check and Move Children" (org-archive-subtree '(4))
13436 ; :active t :keys "C-u C-c C-x C-s"]
13438 "--"
13439 ("TODO Lists"
13440 ["TODO/DONE/-" org-todo t]
13441 ("Select keyword"
13442 ["Next keyword" org-shiftright (org-on-heading-p)]
13443 ["Previous keyword" org-shiftleft (org-on-heading-p)]
13444 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
13445 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
13446 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
13447 ["Show TODO Tree" org-show-todo-tree t]
13448 ["Global TODO list" org-todo-list t]
13449 "--"
13450 ["Set Priority" org-priority t]
13451 ["Priority Up" org-shiftup t]
13452 ["Priority Down" org-shiftdown t])
13453 ("TAGS and Properties"
13454 ["Set Tags" org-set-tags-command t]
13455 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
13456 "--"
13457 ["Set property" org-set-property t]
13458 ["Column view of properties" org-columns t]
13459 ["Insert Column View DBlock" org-insert-columns-dblock t])
13460 ("Dates and Scheduling"
13461 ["Timestamp" org-time-stamp t]
13462 ["Timestamp (inactive)" org-time-stamp-inactive t]
13463 ("Change Date"
13464 ["1 Day Later" org-shiftright t]
13465 ["1 Day Earlier" org-shiftleft t]
13466 ["1 ... Later" org-shiftup t]
13467 ["1 ... Earlier" org-shiftdown t])
13468 ["Compute Time Range" org-evaluate-time-range t]
13469 ["Schedule Item" org-schedule t]
13470 ["Deadline" org-deadline t]
13471 "--"
13472 ["Custom time format" org-toggle-time-stamp-overlays
13473 :style radio :selected org-display-custom-times]
13474 "--"
13475 ["Goto Calendar" org-goto-calendar t]
13476 ["Date from Calendar" org-date-from-calendar t]
13477 "--"
13478 ["Start/restart timer" org-timer-start t]
13479 ["Insert timer string" org-timer t]
13480 ["Insert timer item" org-timer-item t])
13481 ("Logging work"
13482 ["Clock in" org-clock-in t]
13483 ["Clock out" org-clock-out t]
13484 ["Clock cancel" org-clock-cancel t]
13485 ["Goto running clock" org-clock-goto t]
13486 ["Display times" org-clock-display t]
13487 ["Create clock table" org-clock-report t]
13488 "--"
13489 ["Record DONE time"
13490 (progn (setq org-log-done (not org-log-done))
13491 (message "Switching to %s will %s record a timestamp"
13492 (car org-done-keywords)
13493 (if org-log-done "automatically" "not")))
13494 :style toggle :selected org-log-done])
13495 "--"
13496 ["Agenda Command..." org-agenda t]
13497 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
13498 ("File List for Agenda")
13499 ("Special views current file"
13500 ["TODO Tree" org-show-todo-tree t]
13501 ["Check Deadlines" org-check-deadlines t]
13502 ["Timeline" org-timeline t]
13503 ["Tags Tree" org-tags-sparse-tree t])
13504 "--"
13505 ("Hyperlinks"
13506 ["Store Link (Global)" org-store-link t]
13507 ["Insert Link" org-insert-link t]
13508 ["Follow Link" org-open-at-point t]
13509 "--"
13510 ["Next link" org-next-link t]
13511 ["Previous link" org-previous-link t]
13512 "--"
13513 ["Descriptive Links"
13514 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
13515 :style radio
13516 :selected (member '(org-link) buffer-invisibility-spec)]
13517 ["Literal Links"
13518 (progn
13519 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
13520 :style radio
13521 :selected (not (member '(org-link) buffer-invisibility-spec))])
13522 "--"
13523 ["Export/Publish..." org-export t]
13524 ("LaTeX"
13525 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
13526 :selected org-cdlatex-mode]
13527 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
13528 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
13529 ["Modify math symbol" org-cdlatex-math-modify
13530 (org-inside-LaTeX-fragment-p)]
13531 ["Export LaTeX fragments as images"
13532 (if (featurep 'org-exp)
13533 (setq org-export-with-LaTeX-fragments
13534 (not org-export-with-LaTeX-fragments))
13535 (require 'org-exp))
13536 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
13537 org-export-with-LaTeX-fragments)])
13538 "--"
13539 ("Documentation"
13540 ["Show Version" org-version t]
13541 ["Info Documentation" org-info t])
13542 ("Customize"
13543 ["Browse Org Group" org-customize t]
13544 "--"
13545 ["Expand This Menu" org-create-customize-menu
13546 (fboundp 'customize-menu-create)])
13547 "--"
13548 ["Refresh setup" org-mode-restart t]
13551 (defun org-info (&optional node)
13552 "Read documentation for Org-mode in the info system.
13553 With optional NODE, go directly to that node."
13554 (interactive)
13555 (info (format "(org)%s" (or node ""))))
13557 (defun org-install-agenda-files-menu ()
13558 (let ((bl (buffer-list)))
13559 (save-excursion
13560 (while bl
13561 (set-buffer (pop bl))
13562 (if (org-mode-p) (setq bl nil)))
13563 (when (org-mode-p)
13564 (easy-menu-change
13565 '("Org") "File List for Agenda"
13566 (append
13567 (list
13568 ["Edit File List" (org-edit-agenda-file-list) t]
13569 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
13570 ["Remove Current File from List" org-remove-file t]
13571 ["Cycle through agenda files" org-cycle-agenda-files t]
13572 ["Occur in all agenda files" org-occur-in-agenda-files t]
13573 "--")
13574 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
13576 ;;;; Documentation
13578 ;;;###autoload
13579 (defun org-require-autoloaded-modules ()
13580 (interactive)
13581 (mapc 'require
13582 '(org-agenda org-archive org-clock org-colview
13583 org-exp org-id org-export-latex org-publish
13584 org-remember org-table)))
13586 ;;;###autoload
13587 (defun org-customize ()
13588 "Call the customize function with org as argument."
13589 (interactive)
13590 (org-load-modules-maybe)
13591 (org-require-autoloaded-modules)
13592 (customize-browse 'org))
13594 (defun org-create-customize-menu ()
13595 "Create a full customization menu for Org-mode, insert it into the menu."
13596 (interactive)
13597 (org-load-modules-maybe)
13598 (org-require-autoloaded-modules)
13599 (if (fboundp 'customize-menu-create)
13600 (progn
13601 (easy-menu-change
13602 '("Org") "Customize"
13603 `(["Browse Org group" org-customize t]
13604 "--"
13605 ,(customize-menu-create 'org)
13606 ["Set" Custom-set t]
13607 ["Save" Custom-save t]
13608 ["Reset to Current" Custom-reset-current t]
13609 ["Reset to Saved" Custom-reset-saved t]
13610 ["Reset to Standard Settings" Custom-reset-standard t]))
13611 (message "\"Org\"-menu now contains full customization menu"))
13612 (error "Cannot expand menu (outdated version of cus-edit.el)")))
13614 ;;;; Miscellaneous stuff
13616 ;;; Generally useful functions
13618 (defun org-find-text-property-in-string (prop s)
13619 "Return the first non-nil value of property PROP in string S."
13620 (or (get-text-property 0 prop s)
13621 (get-text-property (or (next-single-property-change 0 prop s) 0)
13622 prop s)))
13624 (defun org-display-warning (message) ;; Copied from Emacs-Muse
13625 "Display the given MESSAGE as a warning."
13626 (if (fboundp 'display-warning)
13627 (display-warning 'org message
13628 (if (featurep 'xemacs)
13629 'warning
13630 :warning))
13631 (let ((buf (get-buffer-create "*Org warnings*")))
13632 (with-current-buffer buf
13633 (goto-char (point-max))
13634 (insert "Warning (Org): " message)
13635 (unless (bolp)
13636 (newline)))
13637 (display-buffer buf)
13638 (sit-for 0))))
13640 (defun org-goto-marker-or-bmk (marker &optional bookmark)
13641 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
13642 (if (and marker (marker-buffer marker)
13643 (buffer-live-p (marker-buffer marker)))
13644 (progn
13645 (switch-to-buffer (marker-buffer marker))
13646 (if (or (> marker (point-max)) (< marker (point-min)))
13647 (widen))
13648 (goto-char marker))
13649 (if bookmark
13650 (bookmark-jump bookmark)
13651 (error "Cannot find location"))))
13653 (defun org-quote-csv-field (s)
13654 "Quote field for inclusion in CSV material."
13655 (if (string-match "[\",]" s)
13656 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
13659 (defun org-plist-delete (plist property)
13660 "Delete PROPERTY from PLIST.
13661 This is in contrast to merely setting it to 0."
13662 (let (p)
13663 (while plist
13664 (if (not (eq property (car plist)))
13665 (setq p (plist-put p (car plist) (nth 1 plist))))
13666 (setq plist (cddr plist)))
13669 (defun org-force-self-insert (N)
13670 "Needed to enforce self-insert under remapping."
13671 (interactive "p")
13672 (self-insert-command N))
13674 (defun org-string-width (s)
13675 "Compute width of string, ignoring invisible characters.
13676 This ignores character with invisibility property `org-link', and also
13677 characters with property `org-cwidth', because these will become invisible
13678 upon the next fontification round."
13679 (let (b l)
13680 (when (or (eq t buffer-invisibility-spec)
13681 (assq 'org-link buffer-invisibility-spec))
13682 (while (setq b (text-property-any 0 (length s)
13683 'invisible 'org-link s))
13684 (setq s (concat (substring s 0 b)
13685 (substring s (or (next-single-property-change
13686 b 'invisible s) (length s)))))))
13687 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
13688 (setq s (concat (substring s 0 b)
13689 (substring s (or (next-single-property-change
13690 b 'org-cwidth s) (length s))))))
13691 (setq l (string-width s) b -1)
13692 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
13693 (setq l (- l (get-text-property b 'org-dwidth-n s))))
13696 (defun org-get-indentation (&optional line)
13697 "Get the indentation of the current line, interpreting tabs.
13698 When LINE is given, assume it represents a line and compute its indentation."
13699 (if line
13700 (if (string-match "^ *" (org-remove-tabs line))
13701 (match-end 0))
13702 (save-excursion
13703 (beginning-of-line 1)
13704 (skip-chars-forward " \t")
13705 (current-column))))
13707 (defun org-remove-tabs (s &optional width)
13708 "Replace tabulators in S with spaces.
13709 Assumes that s is a single line, starting in column 0."
13710 (setq width (or width tab-width))
13711 (while (string-match "\t" s)
13712 (setq s (replace-match
13713 (make-string
13714 (- (* width (/ (+ (match-beginning 0) width) width))
13715 (match-beginning 0)) ?\ )
13716 t t s)))
13719 (defun org-fix-indentation (line ind)
13720 "Fix indentation in LINE.
13721 IND is a cons cell with target and minimum indentation.
13722 If the current indentation in LINE is smaller than the minimum,
13723 leave it alone. If it is larger than ind, set it to the target."
13724 (let* ((l (org-remove-tabs line))
13725 (i (org-get-indentation l))
13726 (i1 (car ind)) (i2 (cdr ind)))
13727 (if (>= i i2) (setq l (substring line i2)))
13728 (if (> i1 0)
13729 (concat (make-string i1 ?\ ) l)
13730 l)))
13732 (defun org-base-buffer (buffer)
13733 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
13734 (if (not buffer)
13735 buffer
13736 (or (buffer-base-buffer buffer)
13737 buffer)))
13739 (defun org-trim (s)
13740 "Remove whitespace at beginning and end of string."
13741 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
13742 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
13745 (defun org-wrap (string &optional width lines)
13746 "Wrap string to either a number of lines, or a width in characters.
13747 If WIDTH is non-nil, the string is wrapped to that width, however many lines
13748 that costs. If there is a word longer than WIDTH, the text is actually
13749 wrapped to the length of that word.
13750 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
13751 many lines, whatever width that takes.
13752 The return value is a list of lines, without newlines at the end."
13753 (let* ((words (org-split-string string "[ \t\n]+"))
13754 (maxword (apply 'max (mapcar 'org-string-width words)))
13755 w ll)
13756 (cond (width
13757 (org-do-wrap words (max maxword width)))
13758 (lines
13759 (setq w maxword)
13760 (setq ll (org-do-wrap words maxword))
13761 (if (<= (length ll) lines)
13763 (setq ll words)
13764 (while (> (length ll) lines)
13765 (setq w (1+ w))
13766 (setq ll (org-do-wrap words w)))
13767 ll))
13768 (t (error "Cannot wrap this")))))
13770 (defun org-do-wrap (words width)
13771 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
13772 (let (lines line)
13773 (while words
13774 (setq line (pop words))
13775 (while (and words (< (+ (length line) (length (car words))) width))
13776 (setq line (concat line " " (pop words))))
13777 (setq lines (push line lines)))
13778 (nreverse lines)))
13780 (defun org-split-string (string &optional separators)
13781 "Splits STRING into substrings at SEPARATORS.
13782 No empty strings are returned if there are matches at the beginning
13783 and end of string."
13784 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
13785 (start 0)
13786 notfirst
13787 (list nil))
13788 (while (and (string-match rexp string
13789 (if (and notfirst
13790 (= start (match-beginning 0))
13791 (< start (length string)))
13792 (1+ start) start))
13793 (< (match-beginning 0) (length string)))
13794 (setq notfirst t)
13795 (or (eq (match-beginning 0) 0)
13796 (and (eq (match-beginning 0) (match-end 0))
13797 (eq (match-beginning 0) start))
13798 (setq list
13799 (cons (substring string start (match-beginning 0))
13800 list)))
13801 (setq start (match-end 0)))
13802 (or (eq start (length string))
13803 (setq list
13804 (cons (substring string start)
13805 list)))
13806 (nreverse list)))
13808 (defun org-context ()
13809 "Return a list of contexts of the current cursor position.
13810 If several contexts apply, all are returned.
13811 Each context entry is a list with a symbol naming the context, and
13812 two positions indicating start and end of the context. Possible
13813 contexts are:
13815 :headline anywhere in a headline
13816 :headline-stars on the leading stars in a headline
13817 :todo-keyword on a TODO keyword (including DONE) in a headline
13818 :tags on the TAGS in a headline
13819 :priority on the priority cookie in a headline
13820 :item on the first line of a plain list item
13821 :item-bullet on the bullet/number of a plain list item
13822 :checkbox on the checkbox in a plain list item
13823 :table in an org-mode table
13824 :table-special on a special filed in a table
13825 :table-table in a table.el table
13826 :link on a hyperlink
13827 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
13828 :target on a <<target>>
13829 :radio-target on a <<<radio-target>>>
13830 :latex-fragment on a LaTeX fragment
13831 :latex-preview on a LaTeX fragment with overlayed preview image
13833 This function expects the position to be visible because it uses font-lock
13834 faces as a help to recognize the following contexts: :table-special, :link,
13835 and :keyword."
13836 (let* ((f (get-text-property (point) 'face))
13837 (faces (if (listp f) f (list f)))
13838 (p (point)) clist o)
13839 ;; First the large context
13840 (cond
13841 ((org-on-heading-p t)
13842 (push (list :headline (point-at-bol) (point-at-eol)) clist)
13843 (when (progn
13844 (beginning-of-line 1)
13845 (looking-at org-todo-line-tags-regexp))
13846 (push (org-point-in-group p 1 :headline-stars) clist)
13847 (push (org-point-in-group p 2 :todo-keyword) clist)
13848 (push (org-point-in-group p 4 :tags) clist))
13849 (goto-char p)
13850 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
13851 (if (looking-at "\\[#[A-Z0-9]\\]")
13852 (push (org-point-in-group p 0 :priority) clist)))
13854 ((org-at-item-p)
13855 (push (org-point-in-group p 2 :item-bullet) clist)
13856 (push (list :item (point-at-bol)
13857 (save-excursion (org-end-of-item) (point)))
13858 clist)
13859 (and (org-at-item-checkbox-p)
13860 (push (org-point-in-group p 0 :checkbox) clist)))
13862 ((org-at-table-p)
13863 (push (list :table (org-table-begin) (org-table-end)) clist)
13864 (if (memq 'org-formula faces)
13865 (push (list :table-special
13866 (previous-single-property-change p 'face)
13867 (next-single-property-change p 'face)) clist)))
13868 ((org-at-table-p 'any)
13869 (push (list :table-table) clist)))
13870 (goto-char p)
13872 ;; Now the small context
13873 (cond
13874 ((org-at-timestamp-p)
13875 (push (org-point-in-group p 0 :timestamp) clist))
13876 ((memq 'org-link faces)
13877 (push (list :link
13878 (previous-single-property-change p 'face)
13879 (next-single-property-change p 'face)) clist))
13880 ((memq 'org-special-keyword faces)
13881 (push (list :keyword
13882 (previous-single-property-change p 'face)
13883 (next-single-property-change p 'face)) clist))
13884 ((org-on-target-p)
13885 (push (org-point-in-group p 0 :target) clist)
13886 (goto-char (1- (match-beginning 0)))
13887 (if (looking-at org-radio-target-regexp)
13888 (push (org-point-in-group p 0 :radio-target) clist))
13889 (goto-char p))
13890 ((setq o (car (delq nil
13891 (mapcar
13892 (lambda (x)
13893 (if (memq x org-latex-fragment-image-overlays) x))
13894 (org-overlays-at (point))))))
13895 (push (list :latex-fragment
13896 (org-overlay-start o) (org-overlay-end o)) clist)
13897 (push (list :latex-preview
13898 (org-overlay-start o) (org-overlay-end o)) clist))
13899 ((org-inside-LaTeX-fragment-p)
13900 ;; FIXME: positions wrong.
13901 (push (list :latex-fragment (point) (point)) clist)))
13903 (setq clist (nreverse (delq nil clist)))
13904 clist))
13906 ;; FIXME: Compare with at-regexp-p Do we need both?
13907 (defun org-in-regexp (re &optional nlines visually)
13908 "Check if point is inside a match of regexp.
13909 Normally only the current line is checked, but you can include NLINES extra
13910 lines both before and after point into the search.
13911 If VISUALLY is set, require that the cursor is not after the match but
13912 really on, so that the block visually is on the match."
13913 (catch 'exit
13914 (let ((pos (point))
13915 (eol (point-at-eol (+ 1 (or nlines 0))))
13916 (inc (if visually 1 0)))
13917 (save-excursion
13918 (beginning-of-line (- 1 (or nlines 0)))
13919 (while (re-search-forward re eol t)
13920 (if (and (<= (match-beginning 0) pos)
13921 (>= (+ inc (match-end 0)) pos))
13922 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
13924 (defun org-at-regexp-p (regexp)
13925 "Is point inside a match of REGEXP in the current line?"
13926 (catch 'exit
13927 (save-excursion
13928 (let ((pos (point)) (end (point-at-eol)))
13929 (beginning-of-line 1)
13930 (while (re-search-forward regexp end t)
13931 (if (and (<= (match-beginning 0) pos)
13932 (>= (match-end 0) pos))
13933 (throw 'exit t)))
13934 nil))))
13936 (defun org-occur-in-agenda-files (regexp &optional nlines)
13937 "Call `multi-occur' with buffers for all agenda files."
13938 (interactive "sOrg-files matching: \np")
13939 (let* ((files (org-agenda-files))
13940 (tnames (mapcar 'file-truename files))
13941 (extra org-agenda-text-search-extra-files)
13943 (when (eq (car extra) 'agenda-archives)
13944 (setq extra (cdr extra))
13945 (setq files (org-add-archive-files files)))
13946 (while (setq f (pop extra))
13947 (unless (member (file-truename f) tnames)
13948 (add-to-list 'files f 'append)
13949 (add-to-list 'tnames (file-truename f) 'append)))
13950 (multi-occur
13951 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
13952 regexp)))
13954 (if (boundp 'occur-mode-find-occurrence-hook)
13955 ;; Emacs 23
13956 (add-hook 'occur-mode-find-occurrence-hook
13957 (lambda ()
13958 (when (org-mode-p)
13959 (org-reveal))))
13960 ;; Emacs 22
13961 (defadvice occur-mode-goto-occurrence
13962 (after org-occur-reveal activate)
13963 (and (org-mode-p) (org-reveal)))
13964 (defadvice occur-mode-goto-occurrence-other-window
13965 (after org-occur-reveal activate)
13966 (and (org-mode-p) (org-reveal)))
13967 (defadvice occur-mode-display-occurrence
13968 (after org-occur-reveal activate)
13969 (when (org-mode-p)
13970 (let ((pos (occur-mode-find-occurrence)))
13971 (with-current-buffer (marker-buffer pos)
13972 (save-excursion
13973 (goto-char pos)
13974 (org-reveal)))))))
13976 (defun org-uniquify (list)
13977 "Remove duplicate elements from LIST."
13978 (let (res)
13979 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
13980 res))
13982 (defun org-delete-all (elts list)
13983 "Remove all elements in ELTS from LIST."
13984 (while elts
13985 (setq list (delete (pop elts) list)))
13986 list)
13988 (defun org-back-over-empty-lines ()
13989 "Move backwards over whitespace, to the beginning of the first empty line.
13990 Returns the number of empty lines passed."
13991 (let ((pos (point)))
13992 (skip-chars-backward " \t\n\r")
13993 (beginning-of-line 2)
13994 (goto-char (min (point) pos))
13995 (count-lines (point) pos)))
13997 (defun org-skip-whitespace ()
13998 (skip-chars-forward " \t\n\r"))
14000 (defun org-point-in-group (point group &optional context)
14001 "Check if POINT is in match-group GROUP.
14002 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
14003 match. If the match group does ot exist or point is not inside it,
14004 return nil."
14005 (and (match-beginning group)
14006 (>= point (match-beginning group))
14007 (<= point (match-end group))
14008 (if context
14009 (list context (match-beginning group) (match-end group))
14010 t)))
14012 (defun org-switch-to-buffer-other-window (&rest args)
14013 "Switch to buffer in a second window on the current frame.
14014 In particular, do not allow pop-up frames."
14015 (let (pop-up-frames special-display-buffer-names special-display-regexps
14016 special-display-function)
14017 (apply 'switch-to-buffer-other-window args)))
14019 (defun org-combine-plists (&rest plists)
14020 "Create a single property list from all plists in PLISTS.
14021 The process starts by copying the first list, and then setting properties
14022 from the other lists. Settings in the last list are the most significant
14023 ones and overrule settings in the other lists."
14024 (let ((rtn (copy-sequence (pop plists)))
14025 p v ls)
14026 (while plists
14027 (setq ls (pop plists))
14028 (while ls
14029 (setq p (pop ls) v (pop ls))
14030 (setq rtn (plist-put rtn p v))))
14031 rtn))
14033 (defun org-move-line-down (arg)
14034 "Move the current line down. With prefix argument, move it past ARG lines."
14035 (interactive "p")
14036 (let ((col (current-column))
14037 beg end pos)
14038 (beginning-of-line 1) (setq beg (point))
14039 (beginning-of-line 2) (setq end (point))
14040 (beginning-of-line (+ 1 arg))
14041 (setq pos (move-marker (make-marker) (point)))
14042 (insert (delete-and-extract-region beg end))
14043 (goto-char pos)
14044 (org-move-to-column col)))
14046 (defun org-move-line-up (arg)
14047 "Move the current line up. With prefix argument, move it past ARG lines."
14048 (interactive "p")
14049 (let ((col (current-column))
14050 beg end pos)
14051 (beginning-of-line 1) (setq beg (point))
14052 (beginning-of-line 2) (setq end (point))
14053 (beginning-of-line (- arg))
14054 (setq pos (move-marker (make-marker) (point)))
14055 (insert (delete-and-extract-region beg end))
14056 (goto-char pos)
14057 (org-move-to-column col)))
14059 (defun org-replace-escapes (string table)
14060 "Replace %-escapes in STRING with values in TABLE.
14061 TABLE is an association list with keys like \"%a\" and string values.
14062 The sequences in STRING may contain normal field width and padding information,
14063 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
14064 so values can contain further %-escapes if they are define later in TABLE."
14065 (let ((case-fold-search nil)
14066 e re rpl)
14067 (while (setq e (pop table))
14068 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
14069 (while (string-match re string)
14070 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
14071 (cdr e)))
14072 (setq string (replace-match rpl t t string))))
14073 string))
14076 (defun org-sublist (list start end)
14077 "Return a section of LIST, from START to END.
14078 Counting starts at 1."
14079 (let (rtn (c start))
14080 (setq list (nthcdr (1- start) list))
14081 (while (and list (<= c end))
14082 (push (pop list) rtn)
14083 (setq c (1+ c)))
14084 (nreverse rtn)))
14086 (defun org-find-base-buffer-visiting (file)
14087 "Like `find-buffer-visiting' but alway return the base buffer and
14088 not an indirect buffer."
14089 (let ((buf (find-buffer-visiting file)))
14090 (if buf
14091 (or (buffer-base-buffer buf) buf)
14092 nil)))
14094 (defun org-image-file-name-regexp ()
14095 "Return regexp matching the file names of images."
14096 (if (fboundp 'image-file-name-regexp)
14097 (image-file-name-regexp)
14098 (let ((image-file-name-extensions
14099 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
14100 "xbm" "xpm" "pbm" "pgm" "ppm")))
14101 (concat "\\."
14102 (regexp-opt (nconc (mapcar 'upcase
14103 image-file-name-extensions)
14104 image-file-name-extensions)
14106 "\\'"))))
14108 (defun org-file-image-p (file)
14109 "Return non-nil if FILE is an image."
14110 (save-match-data
14111 (string-match (org-image-file-name-regexp) file)))
14113 (defun org-get-cursor-date ()
14114 "Return the date at cursor in as a time.
14115 This works in the calendar and in the agenda, anywhere else it just
14116 returns the current time."
14117 (let (date day defd)
14118 (cond
14119 ((eq major-mode 'calendar-mode)
14120 (setq date (calendar-cursor-to-date)
14121 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14122 ((eq major-mode 'org-agenda-mode)
14123 (setq day (get-text-property (point) 'day))
14124 (if day
14125 (setq date (calendar-gregorian-from-absolute day)
14126 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
14127 (nth 2 date))))))
14128 (or defd (current-time))))
14130 (defvar org-agenda-action-marker (make-marker)
14131 "Marker pointing to the entry for the next agenda action.")
14133 (defun org-mark-entry-for-agenda-action ()
14134 "Mark the current entry as target of an agenda action.
14135 Agenda actions are actions executed from the agenda with the key `k',
14136 which make use of the date at the cursor."
14137 (interactive)
14138 (move-marker org-agenda-action-marker
14139 (save-excursion (org-back-to-heading t) (point))
14140 (current-buffer))
14141 (message
14142 "Entry marked for action; press `k' at desired date in agenda or calendar"))
14144 ;;; Paragraph filling stuff.
14145 ;; We want this to be just right, so use the full arsenal.
14147 (defun org-indent-line-function ()
14148 "Indent line like previous, but further if previous was headline or item."
14149 (interactive)
14150 (let* ((pos (point))
14151 (itemp (org-at-item-p))
14152 column bpos bcol tpos tcol bullet btype bullet-type)
14153 ;; Find the previous relevant line
14154 (beginning-of-line 1)
14155 (cond
14156 ((looking-at "#") (setq column 0))
14157 ((looking-at "\\*+ ") (setq column 0))
14159 (beginning-of-line 0)
14160 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
14161 (beginning-of-line 0))
14162 (cond
14163 ((looking-at "\\*+[ \t]+")
14164 (if (not org-adapt-indentation)
14165 (setq column 0)
14166 (goto-char (match-end 0))
14167 (setq column (current-column))))
14168 ((org-in-item-p)
14169 (org-beginning-of-item)
14170 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
14171 (setq bpos (match-beginning 1) tpos (match-end 0)
14172 bcol (progn (goto-char bpos) (current-column))
14173 tcol (progn (goto-char tpos) (current-column))
14174 bullet (match-string 1)
14175 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
14176 (if (> tcol (+ bcol org-description-max-indent))
14177 (setq tcol (+ bcol 5)))
14178 (if (not itemp)
14179 (setq column tcol)
14180 (goto-char pos)
14181 (beginning-of-line 1)
14182 (if (looking-at "\\S-")
14183 (progn
14184 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
14185 (setq bullet (match-string 1)
14186 btype (if (string-match "[0-9]" bullet) "n" bullet))
14187 (setq column (if (equal btype bullet-type) bcol tcol)))
14188 (setq column (org-get-indentation)))))
14189 (t (setq column (org-get-indentation))))))
14190 (goto-char pos)
14191 (if (<= (current-column) (current-indentation))
14192 (org-indent-line-to column)
14193 (save-excursion (org-indent-line-to column)))
14194 (setq column (current-column))
14195 (beginning-of-line 1)
14196 (if (looking-at
14197 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
14198 (replace-match (concat "\\1" (format org-property-format
14199 (match-string 2) (match-string 3)))
14200 t nil))
14201 (org-move-to-column column)))
14203 (defun org-set-autofill-regexps ()
14204 (interactive)
14205 ;; In the paragraph separator we include headlines, because filling
14206 ;; text in a line directly attached to a headline would otherwise
14207 ;; fill the headline as well.
14208 (org-set-local 'comment-start-skip "^#+[ \t]*")
14209 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
14210 ;; The paragraph starter includes hand-formatted lists.
14211 (org-set-local 'paragraph-start
14212 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
14213 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
14214 ;; But only if the user has not turned off tables or fixed-width regions
14215 (org-set-local
14216 'auto-fill-inhibit-regexp
14217 (concat "\\*+ \\|#\\+"
14218 "\\|[ \t]*" org-keyword-time-regexp
14219 (if (or org-enable-table-editor org-enable-fixed-width-editor)
14220 (concat
14221 "\\|[ \t]*["
14222 (if org-enable-table-editor "|" "")
14223 (if org-enable-fixed-width-editor ":" "")
14224 "]"))))
14225 ;; We use our own fill-paragraph function, to make sure that tables
14226 ;; and fixed-width regions are not wrapped. That function will pass
14227 ;; through to `fill-paragraph' when appropriate.
14228 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
14229 ; Adaptive filling: To get full control, first make sure that
14230 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
14231 (org-set-local 'adaptive-fill-regexp "\000")
14232 (org-set-local 'adaptive-fill-function
14233 'org-adaptive-fill-function)
14234 (org-set-local
14235 'align-mode-rules-list
14236 '((org-in-buffer-settings
14237 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
14238 (modes . '(org-mode))))))
14240 (defun org-fill-paragraph (&optional justify)
14241 "Re-align a table, pass through to fill-paragraph if no table."
14242 (let ((table-p (org-at-table-p))
14243 (table.el-p (org-at-table.el-p)))
14244 (cond ((and (equal (char-after (point-at-bol)) ?*)
14245 (save-excursion (goto-char (point-at-bol))
14246 (looking-at outline-regexp)))
14247 t) ; skip headlines
14248 (table.el-p t) ; skip table.el tables
14249 (table-p (org-table-align) t) ; align org-mode tables
14250 (t nil)))) ; call paragraph-fill
14252 ;; For reference, this is the default value of adaptive-fill-regexp
14253 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
14255 (defun org-adaptive-fill-function ()
14256 "Return a fill prefix for org-mode files.
14257 In particular, this makes sure hanging paragraphs for hand-formatted lists
14258 work correctly."
14259 (cond ((looking-at "#[ \t]+")
14260 (match-string 0))
14261 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
14262 (save-excursion
14263 (if (> (match-end 1) (+ (match-beginning 1)
14264 org-description-max-indent))
14265 (goto-char (+ (match-beginning 1) 5))
14266 (goto-char (match-end 0)))
14267 (make-string (current-column) ?\ )))
14268 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
14269 (save-excursion
14270 (goto-char (match-end 0))
14271 (make-string (current-column) ?\ )))
14272 (t nil)))
14274 ;;; Other stuff.
14276 (defun org-toggle-fixed-width-section (arg)
14277 "Toggle the fixed-width export.
14278 If there is no active region, the QUOTE keyword at the current headline is
14279 inserted or removed. When present, it causes the text between this headline
14280 and the next to be exported as fixed-width text, and unmodified.
14281 If there is an active region, this command adds or removes a colon as the
14282 first character of this line. If the first character of a line is a colon,
14283 this line is also exported in fixed-width font."
14284 (interactive "P")
14285 (let* ((cc 0)
14286 (regionp (org-region-active-p))
14287 (beg (if regionp (region-beginning) (point)))
14288 (end (if regionp (region-end)))
14289 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
14290 (case-fold-search nil)
14291 (re "[ \t]*\\(:\\)")
14292 off)
14293 (if regionp
14294 (save-excursion
14295 (goto-char beg)
14296 (setq cc (current-column))
14297 (beginning-of-line 1)
14298 (setq off (looking-at re))
14299 (while (> nlines 0)
14300 (setq nlines (1- nlines))
14301 (beginning-of-line 1)
14302 (cond
14303 (arg
14304 (org-move-to-column cc t)
14305 (insert ":\n")
14306 (forward-line -1))
14307 ((and off (looking-at re))
14308 (replace-match "" t t nil 1))
14309 ((not off) (org-move-to-column cc t) (insert ":")))
14310 (forward-line 1)))
14311 (save-excursion
14312 (org-back-to-heading)
14313 (if (looking-at (concat outline-regexp
14314 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
14315 (replace-match "" t t nil 1)
14316 (if (looking-at outline-regexp)
14317 (progn
14318 (goto-char (match-end 0))
14319 (insert org-quote-string " "))))))))
14321 ;;;; Functions extending outline functionality
14323 (defun org-beginning-of-line (&optional arg)
14324 "Go to the beginning of the current line. If that is invisible, continue
14325 to a visible line beginning. This makes the function of C-a more intuitive.
14326 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
14327 first attempt, and only move to after the tags when the cursor is already
14328 beyond the end of the headline."
14329 (interactive "P")
14330 (let ((pos (point)) refpos)
14331 (beginning-of-line 1)
14332 (if (bobp)
14334 (backward-char 1)
14335 (if (org-invisible-p)
14336 (while (and (not (bobp)) (org-invisible-p))
14337 (backward-char 1)
14338 (beginning-of-line 1))
14339 (forward-char 1)))
14340 (when org-special-ctrl-a/e
14341 (cond
14342 ((and (looking-at org-complex-heading-regexp)
14343 (= (char-after (match-end 1)) ?\ ))
14344 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
14345 (point-at-eol)))
14346 (goto-char
14347 (if (eq org-special-ctrl-a/e t)
14348 (cond ((> pos refpos) refpos)
14349 ((= pos (point)) refpos)
14350 (t (point)))
14351 (cond ((> pos (point)) (point))
14352 ((not (eq last-command this-command)) (point))
14353 (t refpos)))))
14354 ((org-at-item-p)
14355 (goto-char
14356 (if (eq org-special-ctrl-a/e t)
14357 (cond ((> pos (match-end 4)) (match-end 4))
14358 ((= pos (point)) (match-end 4))
14359 (t (point)))
14360 (cond ((> pos (point)) (point))
14361 ((not (eq last-command this-command)) (point))
14362 (t (match-end 4))))))))
14363 (org-no-warnings
14364 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
14366 (defun org-end-of-line (&optional arg)
14367 "Go to the end of the line.
14368 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
14369 first attempt, and only move to after the tags when the cursor is already
14370 beyond the end of the headline."
14371 (interactive "P")
14372 (if (or (not org-special-ctrl-a/e)
14373 (not (org-on-heading-p)))
14374 (end-of-line arg)
14375 (let ((pos (point)))
14376 (beginning-of-line 1)
14377 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
14378 (if (eq org-special-ctrl-a/e t)
14379 (if (or (< pos (match-beginning 1))
14380 (= pos (match-end 0)))
14381 (goto-char (match-beginning 1))
14382 (goto-char (match-end 0)))
14383 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
14384 (goto-char (match-end 0))
14385 (goto-char (match-beginning 1))))
14386 (end-of-line arg))))
14387 (org-no-warnings
14388 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
14391 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
14392 (define-key org-mode-map "\C-e" 'org-end-of-line)
14394 (defun org-kill-line (&optional arg)
14395 "Kill line, to tags or end of line."
14396 (interactive "P")
14397 (cond
14398 ((or (not org-special-ctrl-k)
14399 (bolp)
14400 (not (org-on-heading-p)))
14401 (call-interactively 'kill-line))
14402 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
14403 (kill-region (point) (match-beginning 1))
14404 (org-set-tags nil t))
14405 (t (kill-region (point) (point-at-eol)))))
14407 (define-key org-mode-map "\C-k" 'org-kill-line)
14409 (defun org-yank (&optional arg)
14410 "Yank. If the kill is a subtree, treat it specially.
14411 This command will look at the current kill and check if is a single
14412 subtree, or a series of subtrees[1]. If it passes the test, and if the
14413 cursor is at the beginning of a line or after the stars of a currently
14414 empty headline, then the yank is handled specially. How exactly depends
14415 on the value of the following variables, both set by default.
14417 org-yank-folded-subtrees
14418 When set, the subtree(s) will be folded after insertion, but only
14419 if doing so would now swallow text after the yanked text.
14421 org-yank-adjusted-subtrees
14422 When set, the subtree will be promoted or demoted in order to
14423 fit into the local outline tree structure, which means that the level
14424 will be adjusted so that it becomes the smaller one of the two
14425 *visible* surrounding headings.
14427 Any prefix to this command will cause `yank' to be called directly with
14428 no special treatment. In particular, a simple `C-u' prefix will just
14429 plainly yank the text as it is.
14431 \[1] Basically, the test checks if the first non-white line is a heading
14432 and if there are no other headings with fewer stars."
14433 (interactive "P")
14434 (setq this-command 'yank)
14435 (if arg
14436 (call-interactively 'yank)
14437 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
14438 (and (org-kill-is-subtree-p)
14439 (or (bolp)
14440 (and (looking-at "[ \t]*$")
14441 (string-match
14442 "\\`\\*+\\'"
14443 (buffer-substring (point-at-bol) (point)))))))
14444 swallowp)
14445 (cond
14446 ((and subtreep org-yank-folded-subtrees)
14447 (let ((beg (point))
14448 end)
14449 (if (and subtreep org-yank-adjusted-subtrees)
14450 (org-paste-subtree nil nil 'for-yank)
14451 (call-interactively 'yank))
14452 (setq end (point))
14453 (goto-char beg)
14454 (when (and (bolp) subtreep
14455 (not (setq swallowp
14456 (org-yank-folding-would-swallow-text beg end))))
14457 (or (looking-at outline-regexp)
14458 (re-search-forward (concat "^" outline-regexp) end t))
14459 (while (and (< (point) end) (looking-at outline-regexp))
14460 (hide-subtree)
14461 (org-cycle-show-empty-lines 'folded)
14462 (condition-case nil
14463 (outline-forward-same-level 1)
14464 (error (goto-char end)))))
14465 (when swallowp
14466 (message
14467 "Yanked text not folded because that would swallow text"))
14468 (goto-char end)
14469 (skip-chars-forward " \t\n\r")
14470 (beginning-of-line 1)
14471 (push-mark beg 'nomsg)))
14472 ((and subtreep org-yank-adjusted-subtrees)
14473 (let ((beg (point-at-bol)))
14474 (org-paste-subtree nil nil 'for-yank)
14475 (push-mark beg 'nomsg)))
14477 (call-interactively 'yank))))))
14479 (defun org-yank-folding-would-swallow-text (beg end)
14480 "Would hide-subtree at BEG swallow any text after END?"
14481 (let (level)
14482 (save-excursion
14483 (goto-char beg)
14484 (when (or (looking-at outline-regexp)
14485 (re-search-forward (concat "^" outline-regexp) end t))
14486 (setq level (org-outline-level)))
14487 (goto-char end)
14488 (skip-chars-forward " \t\r\n\v\f")
14489 (if (or (eobp)
14490 (and (bolp) (looking-at org-outline-regexp)
14491 (<= (org-outline-level) level)))
14492 nil ; Nothing would be swallowed
14493 t)))) ; something would swallow
14495 (define-key org-mode-map "\C-y" 'org-yank)
14497 (defun org-invisible-p ()
14498 "Check if point is at a character currently not visible."
14499 ;; Early versions of noutline don't have `outline-invisible-p'.
14500 (if (fboundp 'outline-invisible-p)
14501 (outline-invisible-p)
14502 (get-char-property (point) 'invisible)))
14504 (defun org-invisible-p2 ()
14505 "Check if point is at a character currently not visible."
14506 (save-excursion
14507 (if (and (eolp) (not (bobp))) (backward-char 1))
14508 ;; Early versions of noutline don't have `outline-invisible-p'.
14509 (if (fboundp 'outline-invisible-p)
14510 (outline-invisible-p)
14511 (get-char-property (point) 'invisible))))
14513 (defun org-back-to-heading (&optional invisible-ok)
14514 "Call `outline-back-to-heading', but provide a better error message."
14515 (condition-case nil
14516 (outline-back-to-heading invisible-ok)
14517 (error (error "Before first headline at position %d in buffer %s"
14518 (point) (current-buffer)))))
14520 (defun org-before-first-heading-p ()
14521 "Before first heading?"
14522 (save-excursion
14523 (null (re-search-backward "^\\*+ " nil t))))
14525 (defalias 'org-on-heading-p 'outline-on-heading-p)
14526 (defalias 'org-at-heading-p 'outline-on-heading-p)
14527 (defun org-at-heading-or-item-p ()
14528 (or (org-on-heading-p) (org-at-item-p)))
14530 (defun org-on-target-p ()
14531 (or (org-in-regexp org-radio-target-regexp)
14532 (org-in-regexp org-target-regexp)))
14534 (defun org-up-heading-all (arg)
14535 "Move to the heading line of which the present line is a subheading.
14536 This function considers both visible and invisible heading lines.
14537 With argument, move up ARG levels."
14538 (if (fboundp 'outline-up-heading-all)
14539 (outline-up-heading-all arg) ; emacs 21 version of outline.el
14540 (outline-up-heading arg t))) ; emacs 22 version of outline.el
14542 (defun org-up-heading-safe ()
14543 "Move to the heading line of which the present line is a subheading.
14544 This version will not throw an error. It will return the level of the
14545 headline found, or nil if no higher level is found."
14546 (let (start-level re)
14547 (org-back-to-heading t)
14548 (setq start-level (funcall outline-level))
14549 (if (equal start-level 1)
14551 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
14552 (if (re-search-backward re nil t)
14553 (funcall outline-level)))))
14555 (defun org-first-sibling-p ()
14556 "Is this heading the first child of its parents?"
14557 (interactive)
14558 (let ((re (concat "^" outline-regexp))
14559 level l)
14560 (unless (org-at-heading-p t)
14561 (error "Not at a heading"))
14562 (setq level (funcall outline-level))
14563 (save-excursion
14564 (if (not (re-search-backward re nil t))
14566 (setq l (funcall outline-level))
14567 (< l level)))))
14569 (defun org-goto-sibling (&optional previous)
14570 "Goto the next sibling, even if it is invisible.
14571 When PREVIOUS is set, go to the previous sibling instead. Returns t
14572 when a sibling was found. When none is found, return nil and don't
14573 move point."
14574 (let ((fun (if previous 're-search-backward 're-search-forward))
14575 (pos (point))
14576 (re (concat "^" outline-regexp))
14577 level l)
14578 (when (condition-case nil (org-back-to-heading t) (error nil))
14579 (setq level (funcall outline-level))
14580 (catch 'exit
14581 (or previous (forward-char 1))
14582 (while (funcall fun re nil t)
14583 (setq l (funcall outline-level))
14584 (when (< l level) (goto-char pos) (throw 'exit nil))
14585 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
14586 (goto-char pos)
14587 nil))))
14589 (defun org-show-siblings ()
14590 "Show all siblings of the current headline."
14591 (save-excursion
14592 (while (org-goto-sibling) (org-flag-heading nil)))
14593 (save-excursion
14594 (while (org-goto-sibling 'previous)
14595 (org-flag-heading nil))))
14597 (defun org-show-hidden-entry ()
14598 "Show an entry where even the heading is hidden."
14599 (save-excursion
14600 (org-show-entry)))
14602 (defun org-flag-heading (flag &optional entry)
14603 "Flag the current heading. FLAG non-nil means make invisible.
14604 When ENTRY is non-nil, show the entire entry."
14605 (save-excursion
14606 (org-back-to-heading t)
14607 ;; Check if we should show the entire entry
14608 (if entry
14609 (progn
14610 (org-show-entry)
14611 (save-excursion
14612 (and (outline-next-heading)
14613 (org-flag-heading nil))))
14614 (outline-flag-region (max (point-min) (1- (point)))
14615 (save-excursion (outline-end-of-heading) (point))
14616 flag))))
14618 (defun org-forward-same-level (arg)
14619 "Move forward to the ARG'th subheading at same level as this one.
14620 Stop at the first and last subheadings of a superior heading.
14621 This is like outline-forward-same-level, but invisible headings are ok."
14622 (interactive "p")
14623 (org-back-to-heading t)
14624 (while (> arg 0)
14625 (let ((point-to-move-to (save-excursion
14626 (org-get-next-sibling))))
14627 (if point-to-move-to
14628 (progn
14629 (goto-char point-to-move-to)
14630 (setq arg (1- arg)))
14631 (progn
14632 (setq arg 0)
14633 (error "No following same-level heading"))))))
14635 (defun org-get-next-sibling ()
14636 "Move to next heading of the same level, and return point.
14637 If there is no such heading, return nil.
14638 This is like outline-next-sibling, but invisible headings are ok."
14639 (let ((level (funcall outline-level)))
14640 (outline-next-heading)
14641 (while (and (not (eobp)) (> (funcall outline-level) level))
14642 (outline-next-heading))
14643 (if (or (eobp) (< (funcall outline-level) level))
14645 (point))))
14647 (defun org-end-of-subtree (&optional invisible-OK to-heading)
14648 ;; This is an exact copy of the original function, but it uses
14649 ;; `org-back-to-heading', to make it work also in invisible
14650 ;; trees. And is uses an invisible-OK argument.
14651 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
14652 (org-back-to-heading invisible-OK)
14653 (let ((first t)
14654 (level (funcall outline-level)))
14655 (while (and (not (eobp))
14656 (or first (> (funcall outline-level) level)))
14657 (setq first nil)
14658 (outline-next-heading))
14659 (unless to-heading
14660 (if (memq (preceding-char) '(?\n ?\^M))
14661 (progn
14662 ;; Go to end of line before heading
14663 (forward-char -1)
14664 (if (memq (preceding-char) '(?\n ?\^M))
14665 ;; leave blank line before heading
14666 (forward-char -1))))))
14667 (point))
14669 (defun org-show-subtree ()
14670 "Show everything after this heading at deeper levels."
14671 (outline-flag-region
14672 (point)
14673 (save-excursion
14674 (outline-end-of-subtree) (outline-next-heading) (point))
14675 nil))
14677 (defun org-show-entry ()
14678 "Show the body directly following this heading.
14679 Show the heading too, if it is currently invisible."
14680 (interactive)
14681 (save-excursion
14682 (condition-case nil
14683 (progn
14684 (org-back-to-heading t)
14685 (outline-flag-region
14686 (max (point-min) (1- (point)))
14687 (save-excursion
14688 (re-search-forward
14689 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
14690 (or (match-beginning 1) (point-max)))
14691 nil))
14692 (error nil))))
14694 (defun org-make-options-regexp (kwds)
14695 "Make a regular expression for keyword lines."
14696 (concat
14698 "#?[ \t]*\\+\\("
14699 (mapconcat 'regexp-quote kwds "\\|")
14700 "\\):[ \t]*"
14701 "\\(.+\\)"))
14703 ;; Make isearch reveal the necessary context
14704 (defun org-isearch-end ()
14705 "Reveal context after isearch exits."
14706 (when isearch-success ; only if search was successful
14707 (if (featurep 'xemacs)
14708 ;; Under XEmacs, the hook is run in the correct place,
14709 ;; we directly show the context.
14710 (org-show-context 'isearch)
14711 ;; In Emacs the hook runs *before* restoring the overlays.
14712 ;; So we have to use a one-time post-command-hook to do this.
14713 ;; (Emacs 22 has a special variable, see function `org-mode')
14714 (unless (and (boundp 'isearch-mode-end-hook-quit)
14715 isearch-mode-end-hook-quit)
14716 ;; Only when the isearch was not quitted.
14717 (org-add-hook 'post-command-hook 'org-isearch-post-command
14718 'append 'local)))))
14720 (defun org-isearch-post-command ()
14721 "Remove self from hook, and show context."
14722 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
14723 (org-show-context 'isearch))
14726 ;;;; Integration with and fixes for other packages
14728 ;;; Imenu support
14730 (defvar org-imenu-markers nil
14731 "All markers currently used by Imenu.")
14732 (make-variable-buffer-local 'org-imenu-markers)
14734 (defun org-imenu-new-marker (&optional pos)
14735 "Return a new marker for use by Imenu, and remember the marker."
14736 (let ((m (make-marker)))
14737 (move-marker m (or pos (point)))
14738 (push m org-imenu-markers)
14741 (defun org-imenu-get-tree ()
14742 "Produce the index for Imenu."
14743 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
14744 (setq org-imenu-markers nil)
14745 (let* ((n org-imenu-depth)
14746 (re (concat "^" outline-regexp))
14747 (subs (make-vector (1+ n) nil))
14748 (last-level 0)
14749 m tree level head)
14750 (save-excursion
14751 (save-restriction
14752 (widen)
14753 (goto-char (point-max))
14754 (while (re-search-backward re nil t)
14755 (setq level (org-reduced-level (funcall outline-level)))
14756 (when (<= level n)
14757 (looking-at org-complex-heading-regexp)
14758 (setq head (org-link-display-format
14759 (org-match-string-no-properties 4))
14760 m (org-imenu-new-marker))
14761 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
14762 (if (>= level last-level)
14763 (push (cons head m) (aref subs level))
14764 (push (cons head (aref subs (1+ level))) (aref subs level))
14765 (loop for i from (1+ level) to n do (aset subs i nil)))
14766 (setq last-level level)))))
14767 (aref subs 1)))
14769 (eval-after-load "imenu"
14770 '(progn
14771 (add-hook 'imenu-after-jump-hook
14772 (lambda ()
14773 (if (eq major-mode 'org-mode)
14774 (org-show-context 'org-goto))))))
14776 (defun org-link-display-format (link)
14777 "Replace a link with either the description, or the link target
14778 if no description is present"
14779 (save-match-data
14780 (if (string-match org-bracket-link-analytic-regexp link)
14781 (replace-match (or (match-string 5 link)
14782 (concat (match-string 1 link)
14783 (match-string 3 link)))
14784 nil nil link)
14785 link)))
14787 ;; Speedbar support
14789 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
14790 "Overlay marking the agenda restriction line in speedbar.")
14791 (org-overlay-put org-speedbar-restriction-lock-overlay
14792 'face 'org-agenda-restriction-lock)
14793 (org-overlay-put org-speedbar-restriction-lock-overlay
14794 'help-echo "Agendas are currently limited to this item.")
14795 (org-detach-overlay org-speedbar-restriction-lock-overlay)
14797 (defun org-speedbar-set-agenda-restriction ()
14798 "Restrict future agenda commands to the location at point in speedbar.
14799 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
14800 (interactive)
14801 (require 'org-agenda)
14802 (let (p m tp np dir txt w)
14803 (cond
14804 ((setq p (text-property-any (point-at-bol) (point-at-eol)
14805 'org-imenu t))
14806 (setq m (get-text-property p 'org-imenu-marker))
14807 (save-excursion
14808 (save-restriction
14809 (set-buffer (marker-buffer m))
14810 (goto-char m)
14811 (org-agenda-set-restriction-lock 'subtree))))
14812 ((setq p (text-property-any (point-at-bol) (point-at-eol)
14813 'speedbar-function 'speedbar-find-file))
14814 (setq tp (previous-single-property-change
14815 (1+ p) 'speedbar-function)
14816 np (next-single-property-change
14817 tp 'speedbar-function)
14818 dir (speedbar-line-directory)
14819 txt (buffer-substring-no-properties (or tp (point-min))
14820 (or np (point-max))))
14821 (save-excursion
14822 (save-restriction
14823 (set-buffer (find-file-noselect
14824 (let ((default-directory dir))
14825 (expand-file-name txt))))
14826 (unless (org-mode-p)
14827 (error "Cannot restrict to non-Org-mode file"))
14828 (org-agenda-set-restriction-lock 'file))))
14829 (t (error "Don't know how to restrict Org-mode's agenda")))
14830 (org-move-overlay org-speedbar-restriction-lock-overlay
14831 (point-at-bol) (point-at-eol))
14832 (setq current-prefix-arg nil)
14833 (org-agenda-maybe-redo)))
14835 (eval-after-load "speedbar"
14836 '(progn
14837 (speedbar-add-supported-extension ".org")
14838 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
14839 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
14840 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
14841 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
14842 (add-hook 'speedbar-visiting-tag-hook
14843 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
14846 ;;; Fixes and Hacks for problems with other packages
14848 ;; Make flyspell not check words in links, to not mess up our keymap
14849 (defun org-mode-flyspell-verify ()
14850 "Don't let flyspell put overlays at active buttons."
14851 (not (get-text-property (point) 'keymap)))
14853 ;; Make `bookmark-jump' show the jump location if it was hidden.
14854 (eval-after-load "bookmark"
14855 '(if (boundp 'bookmark-after-jump-hook)
14856 ;; We can use the hook
14857 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
14858 ;; Hook not available, use advice
14859 (defadvice bookmark-jump (after org-make-visible activate)
14860 "Make the position visible."
14861 (org-bookmark-jump-unhide))))
14863 ;; Make sure saveplace show the location if it was hidden
14864 (eval-after-load "saveplace"
14865 '(defadvice save-place-find-file-hook (after org-make-visible activate)
14866 "Make the position visible."
14867 (org-bookmark-jump-unhide)))
14869 (defun org-bookmark-jump-unhide ()
14870 "Unhide the current position, to show the bookmark location."
14871 (and (org-mode-p)
14872 (or (org-invisible-p)
14873 (save-excursion (goto-char (max (point-min) (1- (point))))
14874 (org-invisible-p)))
14875 (org-show-context 'bookmark-jump)))
14877 ;; Make session.el ignore our circular variable
14878 (eval-after-load "session"
14879 '(add-to-list 'session-globals-exclude 'org-mark-ring))
14881 ;;;; Experimental code
14883 (defun org-closed-in-range ()
14884 "Sparse tree of items closed in a certain time range.
14885 Still experimental, may disappear in the future."
14886 (interactive)
14887 ;; Get the time interval from the user.
14888 (let* ((time1 (time-to-seconds
14889 (org-read-date nil 'to-time nil "Starting date: ")))
14890 (time2 (time-to-seconds
14891 (org-read-date nil 'to-time nil "End date:")))
14892 ;; callback function
14893 (callback (lambda ()
14894 (let ((time
14895 (time-to-seconds
14896 (apply 'encode-time
14897 (org-parse-time-string
14898 (match-string 1))))))
14899 ;; check if time in interval
14900 (and (>= time time1) (<= time time2))))))
14901 ;; make tree, check each match with the callback
14902 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
14905 ;;;; Finish up
14907 (provide 'org)
14909 (run-hooks 'org-load-hook)
14911 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
14913 ;;; org.el ends here