Captions and attributes for images and tables during export
[org-mode/org-tableheadings.git] / lisp / org.el
blob9406b2bb4842867390241b1dbc4adf1a2e0c4230
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.14
9 ;;
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
24 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
26 ;;; Commentary:
28 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
29 ;; project planning with a fast and effective plain-text system.
31 ;; Org-mode develops organizational tasks around NOTES files that contain
32 ;; information about projects as plain text. Org-mode is implemented on
33 ;; top of outline-mode, which makes it possible to keep the content of
34 ;; large files well structured. Visibility cycling and structure editing
35 ;; help to work with the tree. Tables are easily created with a built-in
36 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
37 ;; and scheduling. It dynamically compiles entries into an agenda that
38 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
39 ;; Plain text URL-like links connect to websites, emails, Usenet
40 ;; messages, BBDB entries, and any files related to the projects. For
41 ;; printing and sharing of notes, an Org-mode file can be exported as a
42 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
43 ;; iCalendar file. It can also serve as a publishing tool for a set of
44 ;; linked webpages.
46 ;; Installation and Activation
47 ;; ---------------------------
48 ;; See the corresponding sections in the manual at
50 ;; http://orgmode.org/org.html#Installation
52 ;; Documentation
53 ;; -------------
54 ;; The documentation of Org-mode can be found in the TeXInfo file. The
55 ;; distribution also contains a PDF version of it. At the homepage of
56 ;; Org-mode, you can read the same text online as HTML. There is also an
57 ;; excellent reference card made by Philip Rooke. This card can be found
58 ;; in the etc/ directory of Emacs 22.
60 ;; A list of recent changes can be found at
61 ;; http://orgmode.org/Changes.html
63 ;;; Code:
65 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
66 (defvar org-table-formula-constants-local nil
67 "Local version of `org-table-formula-constants'.")
68 (make-variable-buffer-local 'org-table-formula-constants-local)
70 ;;;; Require other packages
72 (eval-when-compile
73 (require 'cl)
74 (require 'gnus-sum)
75 (require 'calendar))
76 ;; For XEmacs, noutline is not yet provided by outline.el, so arrange for
77 ;; the file noutline.el being loaded.
78 (if (featurep 'xemacs) (condition-case nil (require 'noutline)))
79 ;; We require noutline, which might be provided in outline.el
80 (require 'outline) (require 'noutline)
81 ;; Other stuff we need.
82 (require 'time-date)
83 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
84 (require 'easymenu)
86 (require 'org-macs)
87 (require 'org-compat)
88 (require 'org-faces)
89 (require 'org-list)
91 ;;;; Customization variables
93 ;;; Version
95 (defconst org-version "6.14"
96 "The version number of the file org.el.")
98 (defun org-version (&optional here)
99 "Show the org-mode version in the echo area.
100 With prefix arg HERE, insert it at point."
101 (interactive "P")
102 (let ((version (format "Org-mode version %s" org-version)))
103 (message version)
104 (if here
105 (insert version))))
107 ;;; Compatibility constants
109 ;;; The custom variables
111 (defgroup org nil
112 "Outline-based notes management and organizer."
113 :tag "Org"
114 :group 'outlines
115 :group 'hypermedia
116 :group 'calendar)
118 (defcustom org-load-hook nil
119 "Hook that is run after org.el has been loaded."
120 :group 'org
121 :type 'hook)
123 (defvar org-modules) ; defined below
124 (defvar org-modules-loaded nil
125 "Have the modules been loaded already?")
127 (defun org-load-modules-maybe (&optional force)
128 "Load all extensions listed in `org-modules'."
129 (when (or force (not org-modules-loaded))
130 (mapc (lambda (ext)
131 (condition-case nil (require ext)
132 (error (message "Problems while trying to load feature `%s'" ext))))
133 org-modules)
134 (setq org-modules-loaded t)))
136 (defun org-set-modules (var value)
137 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
138 (set var value)
139 (when (featurep 'org)
140 (org-load-modules-maybe 'force)))
142 (when (org-bound-and-true-p org-modules)
143 (let ((a (member 'org-infojs org-modules)))
144 (and a (setcar a 'org-jsinfo))))
146 (defcustom org-modules '(org-bbdb org-bibtex org-gnus org-info org-jsinfo org-irc org-mew org-mhe org-rmail org-vm org-w3m org-wl)
147 "Modules that should always be loaded together with org.el.
148 If a description starts with <C>, the file is not part of Emacs
149 and loading it will require that you have downloaded and properly installed
150 the org-mode distribution.
152 You can also use this system to load external packages (i.e. neither Org
153 core modules, not modules from the CONTRIB directory). Just add symbols
154 to the end of the list. If the package is called org-xyz.el, then you need
155 to add the symbol `xyz', and the package must have a call to
157 (provide 'org-xyz)"
158 :group 'org
159 :set 'org-set-modules
160 :type
161 '(set :greedy t
162 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
163 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
164 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
165 (const :tag " id: Global id's for identifying entries" org-id)
166 (const :tag " info: Links to Info nodes" org-info)
167 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
168 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
169 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
170 (const :tag " mew Links to Mew folders/messages" org-mew)
171 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
172 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
173 (const :tag " vm: Links to VM folders/messages" org-vm)
174 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
175 (const :tag " w3m: Special cut/past from w3m to Org." org-w3m)
176 (const :tag " mouse: Additional mouse support" org-mouse)
178 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
179 (const :tag "C annotation-helper: Call Remeber directly from Browser" org-annotation-helper)
180 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
181 (const :tag "C browser-url: Store link, directly from Browser" org-browser-url)
182 (const :tag "C depend: TODO dependencies for Org-mode" org-depend)
183 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
184 (const :tag "C eval: Include command output as text" org-eval)
185 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
186 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
187 (const :tag "C exp-blocks: Pre-process blocks for export" org-exp-blocks)
188 (const :tag "C interactive-query: Interactive modification of tags query" org-interactive-query)
189 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
190 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
191 (const :tag "C mtags: Support for muse-like tags" org-mtags)
192 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
193 (const :tag "C registry: A registry for Org links" org-registry)
194 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
195 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
196 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
197 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
198 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
201 (defgroup org-startup nil
202 "Options concerning startup of Org-mode."
203 :tag "Org Startup"
204 :group 'org)
206 (defcustom org-startup-folded t
207 "Non-nil means, entering Org-mode will switch to OVERVIEW.
208 This can also be configured on a per-file basis by adding one of
209 the following lines anywhere in the buffer:
211 #+STARTUP: fold
212 #+STARTUP: nofold
213 #+STARTUP: content"
214 :group 'org-startup
215 :type '(choice
216 (const :tag "nofold: show all" nil)
217 (const :tag "fold: overview" t)
218 (const :tag "content: all headlines" content)))
220 (defcustom org-startup-truncated t
221 "Non-nil means, entering Org-mode will set `truncate-lines'.
222 This is useful since some lines containing links can be very long and
223 uninteresting. Also tables look terrible when wrapped."
224 :group 'org-startup
225 :type 'boolean)
227 (defcustom org-startup-align-all-tables nil
228 "Non-nil means, align all tables when visiting a file.
229 This is useful when the column width in tables is forced with <N> cookies
230 in table fields. Such tables will look correct only after the first re-align.
231 This can also be configured on a per-file basis by adding one of
232 the following lines anywhere in the buffer:
233 #+STARTUP: align
234 #+STARTUP: noalign"
235 :group 'org-startup
236 :type 'boolean)
238 (defcustom org-insert-mode-line-in-empty-file nil
239 "Non-nil means insert the first line setting Org-mode in empty files.
240 When the function `org-mode' is called interactively in an empty file, this
241 normally means that the file name does not automatically trigger Org-mode.
242 To ensure that the file will always be in Org-mode in the future, a
243 line enforcing Org-mode will be inserted into the buffer, if this option
244 has been set."
245 :group 'org-startup
246 :type 'boolean)
248 (defcustom org-replace-disputed-keys nil
249 "Non-nil means use alternative key bindings for some keys.
250 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
251 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
252 If you want to use Org-mode together with one of these other modes,
253 or more generally if you would like to move some Org-mode commands to
254 other keys, set this variable and configure the keys with the variable
255 `org-disputed-keys'.
257 This option is only relevant at load-time of Org-mode, and must be set
258 *before* org.el is loaded. Changing it requires a restart of Emacs to
259 become effective."
260 :group 'org-startup
261 :type 'boolean)
263 (defcustom org-use-extra-keys nil
264 "Non-nil means use extra key sequence definitions for certain
265 commands. This happens automatically if you run XEmacs or if
266 window-system is nil. This variable lets you do the same
267 manually. You must set it before loading org.
269 Example: on Carbon Emacs 22 running graphically, with an external
270 keyboard on a Powerbook, the default way of setting M-left might
271 not work for either Alt or ESC. Setting this variable will make
272 it work for ESC."
273 :group 'org-startup
274 :type 'boolean)
276 (if (fboundp 'defvaralias)
277 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
279 (defcustom org-disputed-keys
280 '(([(shift up)] . [(meta p)])
281 ([(shift down)] . [(meta n)])
282 ([(shift left)] . [(meta -)])
283 ([(shift right)] . [(meta +)])
284 ([(control shift right)] . [(meta shift +)])
285 ([(control shift left)] . [(meta shift -)]))
286 "Keys for which Org-mode and other modes compete.
287 This is an alist, cars are the default keys, second element specifies
288 the alternative to use when `org-replace-disputed-keys' is t.
290 Keys can be specified in any syntax supported by `define-key'.
291 The value of this option takes effect only at Org-mode's startup,
292 therefore you'll have to restart Emacs to apply it after changing."
293 :group 'org-startup
294 :type 'alist)
296 (defun org-key (key)
297 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
298 Or return the original if not disputed."
299 (if org-replace-disputed-keys
300 (let* ((nkey (key-description key))
301 (x (org-find-if (lambda (x)
302 (equal (key-description (car x)) nkey))
303 org-disputed-keys)))
304 (if x (cdr x) key))
305 key))
307 (defun org-find-if (predicate seq)
308 (catch 'exit
309 (while seq
310 (if (funcall predicate (car seq))
311 (throw 'exit (car seq))
312 (pop seq)))))
314 (defun org-defkey (keymap key def)
315 "Define a key, possibly translated, as returned by `org-key'."
316 (define-key keymap (org-key key) def))
318 (defcustom org-ellipsis nil
319 "The ellipsis to use in the Org-mode outline.
320 When nil, just use the standard three dots. When a string, use that instead,
321 When a face, use the standart 3 dots, but with the specified face.
322 The change affects only Org-mode (which will then use its own display table).
323 Changing this requires executing `M-x org-mode' in a buffer to become
324 effective."
325 :group 'org-startup
326 :type '(choice (const :tag "Default" nil)
327 (face :tag "Face" :value org-warning)
328 (string :tag "String" :value "...#")))
330 (defvar org-display-table nil
331 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
333 (defgroup org-keywords nil
334 "Keywords in Org-mode."
335 :tag "Org Keywords"
336 :group 'org)
338 (defcustom org-deadline-string "DEADLINE:"
339 "String to mark deadline entries.
340 A deadline is this string, followed by a time stamp. Should be a word,
341 terminated by a colon. You can insert a schedule keyword and
342 a timestamp with \\[org-deadline].
343 Changes become only effective after restarting Emacs."
344 :group 'org-keywords
345 :type 'string)
347 (defcustom org-scheduled-string "SCHEDULED:"
348 "String to mark scheduled TODO entries.
349 A schedule is this string, followed by a time stamp. Should be a word,
350 terminated by a colon. You can insert a schedule keyword and
351 a timestamp with \\[org-schedule].
352 Changes become only effective after restarting Emacs."
353 :group 'org-keywords
354 :type 'string)
356 (defcustom org-closed-string "CLOSED:"
357 "String used as the prefix for timestamps logging closing a TODO entry."
358 :group 'org-keywords
359 :type 'string)
361 (defcustom org-clock-string "CLOCK:"
362 "String used as prefix for timestamps clocking work hours on an item."
363 :group 'org-keywords
364 :type 'string)
366 (defcustom org-comment-string "COMMENT"
367 "Entries starting with this keyword will never be exported.
368 An entry can be toggled between COMMENT and normal with
369 \\[org-toggle-comment].
370 Changes become only effective after restarting Emacs."
371 :group 'org-keywords
372 :type 'string)
374 (defcustom org-quote-string "QUOTE"
375 "Entries starting with this keyword will be exported in fixed-width font.
376 Quoting applies only to the text in the entry following the headline, and does
377 not extend beyond the next headline, even if that is lower level.
378 An entry can be toggled between QUOTE and normal with
379 \\[org-toggle-fixed-width-section]."
380 :group 'org-keywords
381 :type 'string)
383 (defconst org-repeat-re
384 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\([.+]?\\+[0-9]+[dwmy]\\)"
385 "Regular expression for specifying repeated events.
386 After a match, group 1 contains the repeat expression.")
388 (defgroup org-structure nil
389 "Options concerning the general structure of Org-mode files."
390 :tag "Org Structure"
391 :group 'org)
393 (defgroup org-reveal-location nil
394 "Options about how to make context of a location visible."
395 :tag "Org Reveal Location"
396 :group 'org-structure)
398 (defconst org-context-choice
399 '(choice
400 (const :tag "Always" t)
401 (const :tag "Never" nil)
402 (repeat :greedy t :tag "Individual contexts"
403 (cons
404 (choice :tag "Context"
405 (const agenda)
406 (const org-goto)
407 (const occur-tree)
408 (const tags-tree)
409 (const link-search)
410 (const mark-goto)
411 (const bookmark-jump)
412 (const isearch)
413 (const default))
414 (boolean))))
415 "Contexts for the reveal options.")
417 (defcustom org-show-hierarchy-above '((default . t))
418 "Non-nil means, show full hierarchy when revealing a location.
419 Org-mode often shows locations in an org-mode file which might have
420 been invisible before. When this is set, the hierarchy of headings
421 above the exposed location is shown.
422 Turning this off for example for sparse trees makes them very compact.
423 Instead of t, this can also be an alist specifying this option for different
424 contexts. Valid contexts are
425 agenda when exposing an entry from the agenda
426 org-goto when using the command `org-goto' on key C-c C-j
427 occur-tree when using the command `org-occur' on key C-c /
428 tags-tree when constructing a sparse tree based on tags matches
429 link-search when exposing search matches associated with a link
430 mark-goto when exposing the jump goal of a mark
431 bookmark-jump when exposing a bookmark location
432 isearch when exiting from an incremental search
433 default default for all contexts not set explicitly"
434 :group 'org-reveal-location
435 :type org-context-choice)
437 (defcustom org-show-following-heading '((default . nil))
438 "Non-nil means, show following heading when revealing a location.
439 Org-mode often shows locations in an org-mode file which might have
440 been invisible before. When this is set, the heading following the
441 match is shown.
442 Turning this off for example for sparse trees makes them very compact,
443 but makes it harder to edit the location of the match. In such a case,
444 use the command \\[org-reveal] to show more context.
445 Instead of t, this can also be an alist specifying this option for different
446 contexts. See `org-show-hierarchy-above' for valid contexts."
447 :group 'org-reveal-location
448 :type org-context-choice)
450 (defcustom org-show-siblings '((default . nil) (isearch t))
451 "Non-nil means, show all sibling heading when revealing a location.
452 Org-mode often shows locations in an org-mode file which might have
453 been invisible before. When this is set, the sibling of the current entry
454 heading are all made visible. If `org-show-hierarchy-above' is t,
455 the same happens on each level of the hierarchy above the current entry.
457 By default this is on for the isearch context, off for all other contexts.
458 Turning this off for example for sparse trees makes them very compact,
459 but makes it harder to edit the location of the match. In such a case,
460 use the command \\[org-reveal] to show more context.
461 Instead of t, this can also be an alist specifying this option for different
462 contexts. See `org-show-hierarchy-above' for valid contexts."
463 :group 'org-reveal-location
464 :type org-context-choice)
466 (defcustom org-show-entry-below '((default . nil))
467 "Non-nil means, show the entry below a headline when revealing a location.
468 Org-mode often shows locations in an org-mode file which might have
469 been invisible before. When this is set, the text below the headline that is
470 exposed is also shown.
472 By default this is off for all contexts.
473 Instead of t, this can also be an alist specifying this option for different
474 contexts. See `org-show-hierarchy-above' for valid contexts."
475 :group 'org-reveal-location
476 :type org-context-choice)
478 (defcustom org-indirect-buffer-display 'other-window
479 "How should indirect tree buffers be displayed?
480 This applies to indirect buffers created with the commands
481 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
482 Valid values are:
483 current-window Display in the current window
484 other-window Just display in another window.
485 dedicated-frame Create one new frame, and re-use it each time.
486 new-frame Make a new frame each time. Note that in this case
487 previously-made indirect buffers are kept, and you need to
488 kill these buffers yourself."
489 :group 'org-structure
490 :group 'org-agenda-windows
491 :type '(choice
492 (const :tag "In current window" current-window)
493 (const :tag "In current frame, other window" other-window)
494 (const :tag "Each time a new frame" new-frame)
495 (const :tag "One dedicated frame" dedicated-frame)))
497 (defgroup org-cycle nil
498 "Options concerning visibility cycling in Org-mode."
499 :tag "Org Cycle"
500 :group 'org-structure)
502 (defcustom org-drawers '("PROPERTIES" "CLOCK")
503 "Names of drawers. Drawers are not opened by cycling on the headline above.
504 Drawers only open with a TAB on the drawer line itself. A drawer looks like
505 this:
506 :DRAWERNAME:
507 .....
508 :END:
509 The drawer \"PROPERTIES\" is special for capturing properties through
510 the property API.
512 Drawers can be defined on the per-file basis with a line like:
514 #+DRAWERS: HIDDEN STATE PROPERTIES"
515 :group 'org-structure
516 :type '(repeat (string :tag "Drawer Name")))
518 (defcustom org-cycle-global-at-bob nil
519 "Cycle globally if cursor is at beginning of buffer and not at a headline.
520 This makes it possible to do global cycling without having to use S-TAB or
521 C-u TAB. For this special case to work, the first line of the buffer
522 must not be a headline - it may be empty ot some other text. When used in
523 this way, `org-cycle-hook' is disables temporarily, to make sure the
524 cursor stays at the beginning of the buffer.
525 When this option is nil, don't do anything special at the beginning
526 of the buffer."
527 :group 'org-cycle
528 :type 'boolean)
530 (defcustom org-cycle-emulate-tab t
531 "Where should `org-cycle' emulate TAB.
532 nil Never
533 white Only in completely white lines
534 whitestart Only at the beginning of lines, before the first non-white char
535 t Everywhere except in headlines
536 exc-hl-bol Everywhere except at the start of a headline
537 If TAB is used in a place where it does not emulate TAB, the current subtree
538 visibility is cycled."
539 :group 'org-cycle
540 :type '(choice (const :tag "Never" nil)
541 (const :tag "Only in completely white lines" white)
542 (const :tag "Before first char in a line" whitestart)
543 (const :tag "Everywhere except in headlines" t)
544 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
547 (defcustom org-cycle-separator-lines 2
548 "Number of empty lines needed to keep an empty line between collapsed trees.
549 If you leave an empty line between the end of a subtree and the following
550 headline, this empty line is hidden when the subtree is folded.
551 Org-mode will leave (exactly) one empty line visible if the number of
552 empty lines is equal or larger to the number given in this variable.
553 So the default 2 means, at least 2 empty lines after the end of a subtree
554 are needed to produce free space between a collapsed subtree and the
555 following headline.
557 Special case: when 0, never leave empty lines in collapsed view."
558 :group 'org-cycle
559 :type 'integer)
560 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
562 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
563 org-cycle-hide-drawers
564 org-cycle-show-empty-lines
565 org-optimize-window-after-visibility-change)
566 "Hook that is run after `org-cycle' has changed the buffer visibility.
567 The function(s) in this hook must accept a single argument which indicates
568 the new state that was set by the most recent `org-cycle' command. The
569 argument is a symbol. After a global state change, it can have the values
570 `overview', `content', or `all'. After a local state change, it can have
571 the values `folded', `children', or `subtree'."
572 :group 'org-cycle
573 :type 'hook)
575 (defgroup org-edit-structure nil
576 "Options concerning structure editing in Org-mode."
577 :tag "Org Edit Structure"
578 :group 'org-structure)
580 (defcustom org-odd-levels-only nil
581 "Non-nil means, skip even levels and only use odd levels for the outline.
582 This has the effect that two stars are being added/taken away in
583 promotion/demotion commands. It also influences how levels are
584 handled by the exporters.
585 Changing it requires restart of `font-lock-mode' to become effective
586 for fontification also in regions already fontified.
587 You may also set this on a per-file basis by adding one of the following
588 lines to the buffer:
590 #+STARTUP: odd
591 #+STARTUP: oddeven"
592 :group 'org-edit-structure
593 :group 'org-font-lock
594 :type 'boolean)
596 (defcustom org-adapt-indentation t
597 "Non-nil means, adapt indentation when promoting and demoting.
598 When this is set and the *entire* text in an entry is indented, the
599 indentation is increased by one space in a demotion command, and
600 decreased by one in a promotion command. If any line in the entry
601 body starts at column 0, indentation is not changed at all."
602 :group 'org-edit-structure
603 :type 'boolean)
605 (defcustom org-special-ctrl-a/e nil
606 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
607 When t, `C-a' will bring back the cursor to the beginning of the
608 headline text, i.e. after the stars and after a possible TODO keyword.
609 In an item, this will be the position after the bullet.
610 When the cursor is already at that position, another `C-a' will bring
611 it to the beginning of the line.
612 `C-e' will jump to the end of the headline, ignoring the presence of tags
613 in the headline. A second `C-e' will then jump to the true end of the
614 line, after any tags.
615 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
616 and only a directly following, identical keypress will bring the cursor
617 to the special positions."
618 :group 'org-edit-structure
619 :type '(choice
620 (const :tag "off" nil)
621 (const :tag "after bullet first" t)
622 (const :tag "border first" reversed)))
624 (if (fboundp 'defvaralias)
625 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
627 (defcustom org-special-ctrl-k nil
628 "Non-nil means `C-k' will behave specially in headlines.
629 When nil, `C-k' will call the default `kill-line' command.
630 When t, the following will happen while the cursor is in the headline:
632 - When the cursor is at the beginning of a headline, kill the entire
633 line and possible the folded subtree below the line.
634 - When in the middle of the headline text, kill the headline up to the tags.
635 - When after the headline text, kill the tags."
636 :group 'org-edit-structure
637 :type 'boolean)
639 (defcustom org-yank-folded-subtrees t
640 "Non-nil means, when yanking subtrees, fold them.
641 If the kill is a single subtree, or a sequence of subtrees, i.e. if
642 it starts with a heading and all other headings in it are either children
643 or siblings, then fold all the subtrees. However, do this only if no
644 text after the yank would be swallowed into a folded tree by this action."
645 :group 'org-edit-structure
646 :type 'boolean)
648 (defcustom org-yank-adjusted-subtrees t
649 "Non-nil means, when yanking subtrees, adjust the level.
650 With this setting, `org-paste-subtree' is used to insert the subtree, see
651 this function for details."
652 :group 'org-edit-structure
653 :type 'boolean)
655 (defcustom org-M-RET-may-split-line '((default . t))
656 "Non-nil means, M-RET will split the line at the cursor position.
657 When nil, it will go to the end of the line before making a
658 new line.
659 You may also set this option in a different way for different
660 contexts. Valid contexts are:
662 headline when creating a new headline
663 item when creating a new item
664 table in a table field
665 default the value to be used for all contexts not explicitly
666 customized"
667 :group 'org-structure
668 :group 'org-table
669 :type '(choice
670 (const :tag "Always" t)
671 (const :tag "Never" nil)
672 (repeat :greedy t :tag "Individual contexts"
673 (cons
674 (choice :tag "Context"
675 (const headline)
676 (const item)
677 (const table)
678 (const default))
679 (boolean)))))
682 (defcustom org-insert-heading-respect-content nil
683 "Non-nil means, insert new headings after the current subtree.
684 When nil, the new heading is created directly after the current line.
685 The commands \\[org-insert-heading-respect-content] and
686 \\[org-insert-todo-heading-respect-content] turn this variable on
687 for the duration of the command."
688 :group 'org-structure
689 :type 'boolean)
691 (defcustom org-blank-before-new-entry '((heading . nil)
692 (plain-list-item . nil))
693 "Should `org-insert-heading' leave a blank line before new heading/item?
694 The value is an alist, with `heading' and `plain-list-item' as car,
695 and a boolean flag as cdr."
696 :group 'org-edit-structure
697 :type '(list
698 (cons (const heading) (boolean))
699 (cons (const plain-list-item) (boolean))))
701 (defcustom org-insert-heading-hook nil
702 "Hook being run after inserting a new heading."
703 :group 'org-edit-structure
704 :type 'hook)
706 (defcustom org-enable-fixed-width-editor t
707 "Non-nil means, lines starting with \":\" are treated as fixed-width.
708 This currently only means, they are never auto-wrapped.
709 When nil, such lines will be treated like ordinary lines.
710 See also the QUOTE keyword."
711 :group 'org-edit-structure
712 :type 'boolean)
714 (defcustom org-edit-src-region-extra nil
715 "Additional regexps to identify regions for editing with `org-edit-src-code'.
716 For examples see the function `org-edit-src-find-region-and-lang'.
717 The regular expression identifying the begin marker should end with a newline,
718 and the regexp marking the end line should start with a newline, to make sure
719 there are kept outside the narrowed region."
720 :group 'org-edit-structure
721 :type '(repeat
722 (list
723 (regexp :tag "begin regexp")
724 (regexp :tag "end regexp")
725 (choice :tag "language"
726 (string :tag "specify")
727 (integer :tag "from match group")
728 (const :tag "from `lang' element")
729 (const :tag "from `style' element")))))
731 (defcustom org-edit-fixed-width-region-mode 'artist-mode
732 "The mode that should be used to edit fixed-width regions.
733 These are the regions where each line starts with a colon."
734 :group 'org-edit-structure
735 :type '(choice
736 (const artist-mode)
737 (const picture-mode)
738 (const fundamental-mode)
739 (function :tag "Other (specify)")))
741 (defcustom org-goto-auto-isearch t
742 "Non-nil means, typing characters in org-goto starts incremental search."
743 :group 'org-edit-structure
744 :type 'boolean)
746 (defgroup org-sparse-trees nil
747 "Options concerning sparse trees in Org-mode."
748 :tag "Org Sparse Trees"
749 :group 'org-structure)
751 (defcustom org-highlight-sparse-tree-matches t
752 "Non-nil means, highlight all matches that define a sparse tree.
753 The highlights will automatically disappear the next time the buffer is
754 changed by an edit command."
755 :group 'org-sparse-trees
756 :type 'boolean)
758 (defcustom org-remove-highlights-with-change t
759 "Non-nil means, any change to the buffer will remove temporary highlights.
760 Such highlights are created by `org-occur' and `org-clock-display'.
761 When nil, `C-c C-c needs to be used to get rid of the highlights.
762 The highlights created by `org-preview-latex-fragment' always need
763 `C-c C-c' to be removed."
764 :group 'org-sparse-trees
765 :group 'org-time
766 :type 'boolean)
769 (defcustom org-occur-hook '(org-first-headline-recenter)
770 "Hook that is run after `org-occur' has constructed a sparse tree.
771 This can be used to recenter the window to show as much of the structure
772 as possible."
773 :group 'org-sparse-trees
774 :type 'hook)
776 (defgroup org-imenu-and-speedbar nil
777 "Options concerning imenu and speedbar in Org-mode."
778 :tag "Org Imenu and Speedbar"
779 :group 'org-structure)
781 (defcustom org-imenu-depth 2
782 "The maximum level for Imenu access to Org-mode headlines.
783 This also applied for speedbar access."
784 :group 'org-imenu-and-speedbar
785 :type 'number)
787 (defgroup org-table nil
788 "Options concerning tables in Org-mode."
789 :tag "Org Table"
790 :group 'org)
792 (defcustom org-enable-table-editor 'optimized
793 "Non-nil means, lines starting with \"|\" are handled by the table editor.
794 When nil, such lines will be treated like ordinary lines.
796 When equal to the symbol `optimized', the table editor will be optimized to
797 do the following:
798 - Automatic overwrite mode in front of whitespace in table fields.
799 This makes the structure of the table stay in tact as long as the edited
800 field does not exceed the column width.
801 - Minimize the number of realigns. Normally, the table is aligned each time
802 TAB or RET are pressed to move to another field. With optimization this
803 happens only if changes to a field might have changed the column width.
804 Optimization requires replacing the functions `self-insert-command',
805 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
806 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
807 very good at guessing when a re-align will be necessary, but you can always
808 force one with \\[org-ctrl-c-ctrl-c].
810 If you would like to use the optimized version in Org-mode, but the
811 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
813 This variable can be used to turn on and off the table editor during a session,
814 but in order to toggle optimization, a restart is required.
816 See also the variable `org-table-auto-blank-field'."
817 :group 'org-table
818 :type '(choice
819 (const :tag "off" nil)
820 (const :tag "on" t)
821 (const :tag "on, optimized" optimized)))
823 (defcustom org-table-tab-recognizes-table.el t
824 "Non-nil means, TAB will automatically notice a table.el table.
825 When it sees such a table, it moves point into it and - if necessary -
826 calls `table-recognize-table'."
827 :group 'org-table-editing
828 :type 'boolean)
830 (defgroup org-link nil
831 "Options concerning links in Org-mode."
832 :tag "Org Link"
833 :group 'org)
835 (defvar org-link-abbrev-alist-local nil
836 "Buffer-local version of `org-link-abbrev-alist', which see.
837 The value of this is taken from the #+LINK lines.")
838 (make-variable-buffer-local 'org-link-abbrev-alist-local)
840 (defcustom org-link-abbrev-alist nil
841 "Alist of link abbreviations.
842 The car of each element is a string, to be replaced at the start of a link.
843 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
844 links in Org-mode buffers can have an optional tag after a double colon, e.g.
846 [[linkkey:tag][description]]
848 If REPLACE is a string, the tag will simply be appended to create the link.
849 If the string contains \"%s\", the tag will be inserted there. Alternatively,
850 the placeholder \"%h\" will cause a url-encoded version of the tag to
851 be inserted at that point (see the function `url-hexify-string').
853 REPLACE may also be a function that will be called with the tag as the
854 only argument to create the link, which should be returned as a string.
856 See the manual for examples."
857 :group 'org-link
858 :type '(repeat
859 (cons
860 (string :tag "Protocol")
861 (choice
862 (string :tag "Format")
863 (function)))))
865 (defcustom org-descriptive-links t
866 "Non-nil means, hide link part and only show description of bracket links.
867 Bracket links are like [[link][descritpion]]. This variable sets the initial
868 state in new org-mode buffers. The setting can then be toggled on a
869 per-buffer basis from the Org->Hyperlinks menu."
870 :group 'org-link
871 :type 'boolean)
873 (defcustom org-link-file-path-type 'adaptive
874 "How the path name in file links should be stored.
875 Valid values are:
877 relative Relative to the current directory, i.e. the directory of the file
878 into which the link is being inserted.
879 absolute Absolute path, if possible with ~ for home directory.
880 noabbrev Absolute path, no abbreviation of home directory.
881 adaptive Use relative path for files in the current directory and sub-
882 directories of it. For other files, use an absolute path."
883 :group 'org-link
884 :type '(choice
885 (const relative)
886 (const absolute)
887 (const noabbrev)
888 (const adaptive)))
890 (defcustom org-activate-links '(bracket angle plain radio tag date)
891 "Types of links that should be activated in Org-mode files.
892 This is a list of symbols, each leading to the activation of a certain link
893 type. In principle, it does not hurt to turn on most link types - there may
894 be a small gain when turning off unused link types. The types are:
896 bracket The recommended [[link][description]] or [[link]] links with hiding.
897 angular Links in angular brackes that may contain whitespace like
898 <bbdb:Carsten Dominik>.
899 plain Plain links in normal text, no whitespace, like http://google.com.
900 radio Text that is matched by a radio target, see manual for details.
901 tag Tag settings in a headline (link to tag search).
902 date Time stamps (link to calendar).
904 Changing this variable requires a restart of Emacs to become effective."
905 :group 'org-link
906 :type '(set (const :tag "Double bracket links (new style)" bracket)
907 (const :tag "Angular bracket links (old style)" angular)
908 (const :tag "Plain text links" plain)
909 (const :tag "Radio target matches" radio)
910 (const :tag "Tags" tag)
911 (const :tag "Timestamps" date)))
913 (defcustom org-make-link-description-function nil
914 "Function to use to generate link descriptions from links. If
915 nil the link location will be used. This function must take two
916 parameters; the first is the link and the second the description
917 org-insert-link has generated, and should return the description
918 to use."
919 :group 'org-link
920 :type 'function)
922 (defgroup org-link-store nil
923 "Options concerning storing links in Org-mode."
924 :tag "Org Store Link"
925 :group 'org-link)
927 (defcustom org-email-link-description-format "Email %c: %.30s"
928 "Format of the description part of a link to an email or usenet message.
929 The following %-excapes will be replaced by corresponding information:
931 %F full \"From\" field
932 %f name, taken from \"From\" field, address if no name
933 %T full \"To\" field
934 %t first name in \"To\" field, address if no name
935 %c correspondent. Unually \"from NAME\", but if you sent it yourself, it
936 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
937 %s subject
938 %m message-id.
940 You may use normal field width specification between the % and the letter.
941 This is for example useful to limit the length of the subject.
943 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
944 :group 'org-link-store
945 :type 'string)
947 (defcustom org-from-is-user-regexp
948 (let (r1 r2)
949 (when (and user-mail-address (not (string= user-mail-address "")))
950 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
951 (when (and user-full-name (not (string= user-full-name "")))
952 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
953 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
954 "Regexp mached against the \"From:\" header of an email or usenet message.
955 It should match if the message is from the user him/herself."
956 :group 'org-link-store
957 :type 'regexp)
959 (defcustom org-context-in-file-links t
960 "Non-nil means, file links from `org-store-link' contain context.
961 A search string will be added to the file name with :: as separator and
962 used to find the context when the link is activated by the command
963 `org-open-at-point'.
964 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
965 negates this setting for the duration of the command."
966 :group 'org-link-store
967 :type 'boolean)
969 (defcustom org-keep-stored-link-after-insertion nil
970 "Non-nil means, keep link in list for entire session.
972 The command `org-store-link' adds a link pointing to the current
973 location to an internal list. These links accumulate during a session.
974 The command `org-insert-link' can be used to insert links into any
975 Org-mode file (offering completion for all stored links). When this
976 option is nil, every link which has been inserted once using \\[org-insert-link]
977 will be removed from the list, to make completing the unused links
978 more efficient."
979 :group 'org-link-store
980 :type 'boolean)
982 (defgroup org-link-follow nil
983 "Options concerning following links in Org-mode."
984 :tag "Org Follow Link"
985 :group 'org-link)
987 (defcustom org-link-translation-function nil
988 "Function to translate links with different syntax to Org syntax.
989 This can be used to translate links created for example by the Planner
990 or emacs-wiki packages to Org syntax.
991 The function must accept two parameters, a TYPE containing the link
992 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
993 which is everything after the link protocol. It should return a cons
994 with possibly modifed values of type and path.
995 Org contains a function for this, so if you set this variable to
996 `org-translate-link-from-planner', you should be able follow many
997 links created by planner."
998 :group 'org-link-follow
999 :type 'function)
1001 (defcustom org-follow-link-hook nil
1002 "Hook that is run after a link has been followed."
1003 :group 'org-link-follow
1004 :type 'hook)
1006 (defcustom org-tab-follows-link nil
1007 "Non-nil means, on links TAB will follow the link.
1008 Needs to be set before org.el is loaded."
1009 :group 'org-link-follow
1010 :type 'boolean)
1012 (defcustom org-return-follows-link nil
1013 "Non-nil means, on links RET will follow the link.
1014 Needs to be set before org.el is loaded."
1015 :group 'org-link-follow
1016 :type 'boolean)
1018 (defcustom org-mouse-1-follows-link
1019 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1020 "Non-nil means, mouse-1 on a link will follow the link.
1021 A longer mouse click will still set point. Does not work on XEmacs.
1022 Needs to be set before org.el is loaded."
1023 :group 'org-link-follow
1024 :type 'boolean)
1026 (defcustom org-mark-ring-length 4
1027 "Number of different positions to be recorded in the ring
1028 Changing this requires a restart of Emacs to work correctly."
1029 :group 'org-link-follow
1030 :type 'interger)
1032 (defcustom org-link-frame-setup
1033 '((vm . vm-visit-folder-other-frame)
1034 (gnus . gnus-other-frame)
1035 (file . find-file-other-window))
1036 "Setup the frame configuration for following links.
1037 When following a link with Emacs, it may often be useful to display
1038 this link in another window or frame. This variable can be used to
1039 set this up for the different types of links.
1040 For VM, use any of
1041 `vm-visit-folder'
1042 `vm-visit-folder-other-frame'
1043 For Gnus, use any of
1044 `gnus'
1045 `gnus-other-frame'
1046 `org-gnus-no-new-news'
1047 For FILE, use any of
1048 `find-file'
1049 `find-file-other-window'
1050 `find-file-other-frame'
1051 For the calendar, use the variable `calendar-setup'.
1052 For BBDB, it is currently only possible to display the matches in
1053 another window."
1054 :group 'org-link-follow
1055 :type '(list
1056 (cons (const vm)
1057 (choice
1058 (const vm-visit-folder)
1059 (const vm-visit-folder-other-window)
1060 (const vm-visit-folder-other-frame)))
1061 (cons (const gnus)
1062 (choice
1063 (const gnus)
1064 (const gnus-other-frame)
1065 (const org-gnus-no-new-news)))
1066 (cons (const file)
1067 (choice
1068 (const find-file)
1069 (const find-file-other-window)
1070 (const find-file-other-frame)))))
1072 (defcustom org-display-internal-link-with-indirect-buffer nil
1073 "Non-nil means, use indirect buffer to display infile links.
1074 Activating internal links (from one location in a file to another location
1075 in the same file) normally just jumps to the location. When the link is
1076 activated with a C-u prefix (or with mouse-3), the link is displayed in
1077 another window. When this option is set, the other window actually displays
1078 an indirect buffer clone of the current buffer, to avoid any visibility
1079 changes to the current buffer."
1080 :group 'org-link-follow
1081 :type 'boolean)
1083 (defcustom org-open-non-existing-files nil
1084 "Non-nil means, `org-open-file' will open non-existing files.
1085 When nil, an error will be generated."
1086 :group 'org-link-follow
1087 :type 'boolean)
1089 (defcustom org-open-directory-means-index-dot-org nil
1090 "Non-nil means, a link to a directory really means to index.org.
1091 When nil, following a directory link will run dired or open a finder/explorer
1092 window on that directory."
1093 :group 'org-link-follow
1094 :type 'boolean)
1096 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1097 "Function and arguments to call for following mailto links.
1098 This is a list with the first element being a lisp function, and the
1099 remaining elements being arguments to the function. In string arguments,
1100 %a will be replaced by the address, and %s will be replaced by the subject
1101 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1102 :group 'org-link-follow
1103 :type '(choice
1104 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1105 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1106 (const :tag "message-mail" (message-mail "%a" "%s"))
1107 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1109 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1110 "Non-nil means, ask for confirmation before executing shell links.
1111 Shell links can be dangerous: just think about a link
1113 [[shell:rm -rf ~/*][Google Search]]
1115 This link would show up in your Org-mode document as \"Google Search\",
1116 but really it would remove your entire home directory.
1117 Therefore we advise against setting this variable to nil.
1118 Just change it to `y-or-n-p' of you want to confirm with a
1119 single keystroke rather than having to type \"yes\"."
1120 :group 'org-link-follow
1121 :type '(choice
1122 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1123 (const :tag "with y-or-n (faster)" y-or-n-p)
1124 (const :tag "no confirmation (dangerous)" nil)))
1126 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1127 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1128 Elisp links can be dangerous: just think about a link
1130 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1132 This link would show up in your Org-mode document as \"Google Search\",
1133 but really it would remove your entire home directory.
1134 Therefore we advise against setting this variable to nil.
1135 Just change it to `y-or-n-p' of you want to confirm with a
1136 single keystroke rather than having to type \"yes\"."
1137 :group 'org-link-follow
1138 :type '(choice
1139 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1140 (const :tag "with y-or-n (faster)" y-or-n-p)
1141 (const :tag "no confirmation (dangerous)" nil)))
1143 (defconst org-file-apps-defaults-gnu
1144 '((remote . emacs)
1145 (system . mailcap)
1146 (t . mailcap))
1147 "Default file applications on a UNIX or GNU/Linux system.
1148 See `org-file-apps'.")
1150 (defconst org-file-apps-defaults-macosx
1151 '((remote . emacs)
1152 (t . "open %s")
1153 (system . "open %s")
1154 ("ps.gz" . "gv %s")
1155 ("eps.gz" . "gv %s")
1156 ("dvi" . "xdvi %s")
1157 ("fig" . "xfig %s"))
1158 "Default file applications on a MacOS X system.
1159 The system \"open\" is known as a default, but we use X11 applications
1160 for some files for which the OS does not have a good default.
1161 See `org-file-apps'.")
1163 (defconst org-file-apps-defaults-windowsnt
1164 (list
1165 '(remote . emacs)
1166 (cons t
1167 (list (if (featurep 'xemacs)
1168 'mswindows-shell-execute
1169 'w32-shell-execute)
1170 "open" 'file))
1171 (cons 'system
1172 (list (if (featurep 'xemacs)
1173 'mswindows-shell-execute
1174 'w32-shell-execute)
1175 "open" 'file)))
1176 "Default file applications on a Windows NT system.
1177 The system \"open\" is used for most files.
1178 See `org-file-apps'.")
1180 (defcustom org-file-apps
1182 (auto-mode . emacs)
1183 ("\\.x?html?\\'" . default)
1184 ("\\.pdf\\'" . default)
1186 "External applications for opening `file:path' items in a document.
1187 Org-mode uses system defaults for different file types, but
1188 you can use this variable to set the application for a given file
1189 extension. The entries in this list are cons cells where the car identifies
1190 files and the cdr the corresponding command. Possible values for the
1191 file identifier are
1192 \"regex\" Regular expression matched against the file name. For backward
1193 compatibility, this can also be a string with only alphanumeric
1194 characters, which is then interpreted as an extension.
1195 `directory' Matches a directory
1196 `remote' Matches a remote file, accessible through tramp or efs.
1197 Remote files most likely should be visited through Emacs
1198 because external applications cannot handle such paths.
1199 `auto-mode' Matches files that are mached by any entry in `auto-mode-alist',
1200 so all files Emacs knows how to handle. Using this with
1201 command `emacs' will open most files in Emacs. Beware that this
1202 will also open html files insite Emacs, unless you add
1203 (\"html\" . default) to the list as well.
1204 t Default for files not matched by any of the other options.
1205 `system' The system command to open files, like `open' on Windows
1206 and Mac OS X, and mailcap under GNU/Linux. This is the command
1207 that will be selected if you call `C-c C-o' with a double
1208 `C-u C-u' prefix.
1210 Possible values for the command are:
1211 `emacs' The file will be visited by the current Emacs process.
1212 `default' Use the default application for this file type, which is the
1213 association for t in the list, most likely in the system-specific
1214 part.
1215 This can be used to overrule an unwanted seting in the
1216 system-specific variable.
1217 `system' Use the system command for opening files, like \"open\".
1218 This command is specified by the entry whose car is `system'.
1219 Most likely, the system-specific version of this variable
1220 does define this command, but you can overrule/replace it
1221 here.
1222 string A command to be executed by a shell; %s will be replaced
1223 by the path to the file.
1224 sexp A Lisp form which will be evaluated. The file path will
1225 be available in the Lisp variable `file'.
1226 For more examples, see the system specific constants
1227 `org-file-apps-defaults-macosx'
1228 `org-file-apps-defaults-windowsnt'
1229 `org-file-apps-defaults-gnu'."
1230 :group 'org-link-follow
1231 :type '(repeat
1232 (cons (choice :value ""
1233 (string :tag "Extension")
1234 (const :tag "System command to open files" system)
1235 (const :tag "Default for unrecognized files" t)
1236 (const :tag "Remote file" remote)
1237 (const :tag "Links to a directory" directory)
1238 (const :tag "Any files that have Emacs modes"
1239 auto-mode))
1240 (choice :value ""
1241 (const :tag "Visit with Emacs" emacs)
1242 (const :tag "Use default" default)
1243 (const :tag "Use the system command" system)
1244 (string :tag "Command")
1245 (sexp :tag "Lisp form")))))
1247 (defgroup org-refile nil
1248 "Options concerning refiling entries in Org-mode."
1249 :tag "Org Refile"
1250 :group 'org)
1252 (defcustom org-directory "~/org"
1253 "Directory with org files.
1254 This directory will be used as default to prompt for org files.
1255 Used by the hooks for remember.el."
1256 :group 'org-refile
1257 :group 'org-remember
1258 :type 'directory)
1260 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1261 "Default target for storing notes.
1262 Used by the hooks for remember.el. This can be a string, or nil to mean
1263 the value of `remember-data-file'.
1264 You can set this on a per-template basis with the variable
1265 `org-remember-templates'."
1266 :group 'org-refile
1267 :group 'org-remember
1268 :type '(choice
1269 (const :tag "Default from remember-data-file" nil)
1270 file))
1272 (defcustom org-goto-interface 'outline
1273 "The default interface to be used for `org-goto'.
1274 Allowed vaues are:
1275 outline The interface shows an outline of the relevant file
1276 and the correct heading is found by moving through
1277 the outline or by searching with incremental search.
1278 outline-path-completion Headlines in the current buffer are offered via
1279 completion. This is the interface also used by
1280 the refile command."
1281 :group 'org-refile
1282 :type '(choice
1283 (const :tag "Outline" outline)
1284 (const :tag "Outline-path-completion" outline-path-completion)))
1286 (defcustom org-reverse-note-order nil
1287 "Non-nil means, store new notes at the beginning of a file or entry.
1288 When nil, new notes will be filed to the end of a file or entry.
1289 This can also be a list with cons cells of regular expressions that
1290 are matched against file names, and values."
1291 :group 'org-remember
1292 :group 'org-refile
1293 :type '(choice
1294 (const :tag "Reverse always" t)
1295 (const :tag "Reverse never" nil)
1296 (repeat :tag "By file name regexp"
1297 (cons regexp boolean))))
1299 (defcustom org-refile-targets nil
1300 "Targets for refiling entries with \\[org-refile].
1301 This is list of cons cells. Each cell contains:
1302 - a specification of the files to be considered, either a list of files,
1303 or a symbol whose function or variable value will be used to retrieve
1304 a file name or a list of file names. Nil means, refile to a different
1305 heading in the current buffer.
1306 - A specification of how to find candidate refile targets. This may be
1307 any of
1308 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1309 This tag has to be present in all target headlines, inheritance will
1310 not be considered.
1311 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1312 todo keyword.
1313 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1314 headlines that are refiling targets.
1315 - a cons cell (:level . N). Any headline of level N is considered a target.
1316 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1318 When this variable is nil, all top-level headlines in the current buffer
1319 are used, equivalent to the value `((nil . (:level . 1))'."
1320 :group 'org-refile
1321 :type '(repeat
1322 (cons
1323 (choice :value org-agenda-files
1324 (const :tag "All agenda files" org-agenda-files)
1325 (const :tag "Current buffer" nil)
1326 (function) (variable) (file))
1327 (choice :tag "Identify target headline by"
1328 (cons :tag "Specific tag" (const :value :tag) (string))
1329 (cons :tag "TODO keyword" (const :value :todo) (string))
1330 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1331 (cons :tag "Level number" (const :value :level) (integer))
1332 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1334 (defcustom org-refile-use-outline-path nil
1335 "Non-nil means, provide refile targets as paths.
1336 So a level 3 headline will be available as level1/level2/level3.
1337 When the value is `file', also include the file name (without directory)
1338 into the path. When `full-file-path', include the full file path."
1339 :group 'org-refile
1340 :type '(choice
1341 (const :tag "Not" nil)
1342 (const :tag "Yes" t)
1343 (const :tag "Start with file name" file)
1344 (const :tag "Start with full file path" full-file-path)))
1346 (defcustom org-outline-path-complete-in-steps t
1347 "Non-nil means, complete the outline path in hierarchical steps.
1348 When Org-mode uses the refile interface to select an outline path
1349 \(see variable `org-refile-use-outline-path'), the completion of
1350 the path can be done is a single go, or if can be done in steps down
1351 the headline hierarchy. Going in steps is probably the best if you
1352 do not use a special completion package like `ido' or `icicles'.
1353 However, when using these packages, going in one step can be very
1354 fast, while still showing the whole path to the entry."
1355 :group 'org-refile
1356 :type 'boolean)
1358 (defgroup org-todo nil
1359 "Options concerning TODO items in Org-mode."
1360 :tag "Org TODO"
1361 :group 'org)
1363 (defgroup org-progress nil
1364 "Options concerning Progress logging in Org-mode."
1365 :tag "Org Progress"
1366 :group 'org-time)
1368 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1369 "List of TODO entry keyword sequences and their interpretation.
1370 \\<org-mode-map>This is a list of sequences.
1372 Each sequence starts with a symbol, either `sequence' or `type',
1373 indicating if the keywords should be interpreted as a sequence of
1374 action steps, or as different types of TODO items. The first
1375 keywords are states requiring action - these states will select a headline
1376 for inclusion into the global TODO list Org-mode produces. If one of
1377 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1378 signify that no further action is necessary. If \"|\" is not found,
1379 the last keyword is treated as the only DONE state of the sequence.
1381 The command \\[org-todo] cycles an entry through these states, and one
1382 additional state where no keyword is present. For details about this
1383 cycling, see the manual.
1385 TODO keywords and interpretation can also be set on a per-file basis with
1386 the special #+SEQ_TODO and #+TYP_TODO lines.
1388 Each keyword can optionally specify a character for fast state selection
1389 \(in combination with the variable `org-use-fast-todo-selection')
1390 and specifiers for state change logging, using the same syntax
1391 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1392 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1393 indicates to record a time stamp each time this state is selected.
1395 Each keyword may also specify if a timestamp or a note should be
1396 recorded when entering or leaving the state, by adding additional
1397 characters in the parenthesis after the keyword. This looks like this:
1398 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1399 record only the time of the state change. With X and Y being either
1400 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1401 Y when leaving the state if and only if the *target* state does not
1402 define X. You may omit any of the fast-selection key or X or /Y,
1403 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1405 For backward compatibility, this variable may also be just a list
1406 of keywords - in this case the interptetation (sequence or type) will be
1407 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1408 :group 'org-todo
1409 :group 'org-keywords
1410 :type '(choice
1411 (repeat :tag "Old syntax, just keywords"
1412 (string :tag "Keyword"))
1413 (repeat :tag "New syntax"
1414 (cons
1415 (choice
1416 :tag "Interpretation"
1417 (const :tag "Sequence (cycling hits every state)" sequence)
1418 (const :tag "Type (cycling directly to DONE)" type))
1419 (repeat
1420 (string :tag "Keyword"))))))
1422 (defvar org-todo-keywords-1 nil
1423 "All TODO and DONE keywords active in a buffer.")
1424 (make-variable-buffer-local 'org-todo-keywords-1)
1425 (defvar org-todo-keywords-for-agenda nil)
1426 (defvar org-done-keywords-for-agenda nil)
1427 (defvar org-todo-keyword-alist-for-agenda nil)
1428 (defvar org-tag-alist-for-agenda nil)
1429 (defvar org-agenda-contributing-files nil)
1430 (defvar org-not-done-keywords nil)
1431 (make-variable-buffer-local 'org-not-done-keywords)
1432 (defvar org-done-keywords nil)
1433 (make-variable-buffer-local 'org-done-keywords)
1434 (defvar org-todo-heads nil)
1435 (make-variable-buffer-local 'org-todo-heads)
1436 (defvar org-todo-sets nil)
1437 (make-variable-buffer-local 'org-todo-sets)
1438 (defvar org-todo-log-states nil)
1439 (make-variable-buffer-local 'org-todo-log-states)
1440 (defvar org-todo-kwd-alist nil)
1441 (make-variable-buffer-local 'org-todo-kwd-alist)
1442 (defvar org-todo-key-alist nil)
1443 (make-variable-buffer-local 'org-todo-key-alist)
1444 (defvar org-todo-key-trigger nil)
1445 (make-variable-buffer-local 'org-todo-key-trigger)
1447 (defcustom org-todo-interpretation 'sequence
1448 "Controls how TODO keywords are interpreted.
1449 This variable is in principle obsolete and is only used for
1450 backward compatibility, if the interpretation of todo keywords is
1451 not given already in `org-todo-keywords'. See that variable for
1452 more information."
1453 :group 'org-todo
1454 :group 'org-keywords
1455 :type '(choice (const sequence)
1456 (const type)))
1458 (defcustom org-use-fast-todo-selection 'prefix
1459 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1460 This variable describes if and under what circumstances the cycling
1461 mechanism for TODO keywords will be replaced by a single-key, direct
1462 selection scheme.
1464 When nil, fast selection is never used.
1466 When the symbol `prefix', it will be used when `org-todo' is called with
1467 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1468 in an agenda buffer.
1470 When t, fast selection is used by default. In this case, the prefix
1471 argument forces cycling instead.
1473 In all cases, the special interface is only used if access keys have actually
1474 been assigned by the user, i.e. if keywords in the configuration are followed
1475 by a letter in parenthesis, like TODO(t)."
1476 :group 'org-todo
1477 :type '(choice
1478 (const :tag "Never" nil)
1479 (const :tag "By default" t)
1480 (const :tag "Only with C-u C-c C-t" prefix)))
1482 (defcustom org-provide-todo-statistics t
1483 "Non-nil means, update todo statistics after insert and toggle.
1484 When this is set, todo statistics is updated in the parent of the current
1485 entry each time a todo state is changed."
1486 :group 'org-todo
1487 :type 'boolean)
1489 (defcustom org-after-todo-state-change-hook nil
1490 "Hook which is run after the state of a TODO item was changed.
1491 The new state (a string with a TODO keyword, or nil) is available in the
1492 Lisp variable `state'."
1493 :group 'org-todo
1494 :type 'hook)
1496 (defcustom org-todo-state-tags-triggers nil
1497 "Tag changes that should be triggered by TODO state changes.
1498 This is a list. Each entry is
1500 (state-change (tag . flag) .......)
1502 State-change can be a string with a state, and empty string to indicate the
1503 state that has no TODO keyword, or it can be one of the symbols `todo'
1504 or `done', meaning any not-done or done state, respectively."
1505 :group 'org-todo
1506 :group 'org-tags
1507 :type '(repeat
1508 (cons (choice :tag "When changing to"
1509 (const :tag "Not-done state" todo)
1510 (const :tag "Done state" done)
1511 (string :tag "State"))
1512 (repeat
1513 (cons :tag "Tag action"
1514 (string :tag "Tag")
1515 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1517 (defcustom org-log-done nil
1518 "Non-nil means, record a CLOSED timestamp when moving an entry to DONE.
1519 When equal to the list (done), also prompt for a closing note.
1520 This can also be configured on a per-file basis by adding one of
1521 the following lines anywhere in the buffer:
1523 #+STARTUP: logdone
1524 #+STARTUP: lognotedone
1525 #+STARTUP: nologdone"
1526 :group 'org-todo
1527 :group 'org-progress
1528 :type '(choice
1529 (const :tag "No logging" nil)
1530 (const :tag "Record CLOSED timestamp" time)
1531 (const :tag "Record CLOSED timestamp with closing note." note)))
1533 ;; Normalize old uses of org-log-done.
1534 (cond
1535 ((eq org-log-done t) (setq org-log-done 'time))
1536 ((and (listp org-log-done) (memq 'done org-log-done))
1537 (setq org-log-done 'note)))
1539 (defcustom org-log-note-clock-out nil
1540 "Non-nil means, record a note when clocking out of an item.
1541 This can also be configured on a per-file basis by adding one of
1542 the following lines anywhere in the buffer:
1544 #+STARTUP: lognoteclock-out
1545 #+STARTUP: nolognoteclock-out"
1546 :group 'org-todo
1547 :group 'org-progress
1548 :type 'boolean)
1550 (defcustom org-log-done-with-time t
1551 "Non-nil means, the CLOSED time stamp will contain date and time.
1552 When nil, only the date will be recorded."
1553 :group 'org-progress
1554 :type 'boolean)
1556 (defcustom org-log-note-headings
1557 '((done . "CLOSING NOTE %t")
1558 (state . "State %-12s %t")
1559 (note . "Note taken on %t")
1560 (clock-out . ""))
1561 "Headings for notes added to entries.
1562 The value is an alist, with the car being a symbol indicating the note
1563 context, and the cdr is the heading to be used. The heading may also be the
1564 empty string.
1565 %t in the heading will be replaced by a time stamp.
1566 %s will be replaced by the new TODO state, in double quotes.
1567 %u will be replaced by the user name.
1568 %U will be replaced by the full user name."
1569 :group 'org-todo
1570 :group 'org-progress
1571 :type '(list :greedy t
1572 (cons (const :tag "Heading when closing an item" done) string)
1573 (cons (const :tag
1574 "Heading when changing todo state (todo sequence only)"
1575 state) string)
1576 (cons (const :tag "Heading when just taking a note" note) string)
1577 (cons (const :tag "Heading when clocking out" clock-out) string)))
1579 (unless (assq 'note org-log-note-headings)
1580 (push '(note . "%t") org-log-note-headings))
1582 (defcustom org-log-state-notes-insert-after-drawers nil
1583 "Non-nil means, insert state change notes after any drawers in entry.
1584 Only the drawers that *immediately* follow the headline and the
1585 deadline/scheduled line are skipped.
1586 When nil, insert notes right after the heading and perhaps the line
1587 with deadline/scheduling if present."
1588 :group 'org-todo
1589 :group 'org-progress
1590 :type 'boolean)
1592 (defcustom org-log-states-order-reversed t
1593 "Non-nil means, the latest state change note will be directly after heading.
1594 When nil, the notes will be orderer according to time."
1595 :group 'org-todo
1596 :group 'org-progress
1597 :type 'boolean)
1599 (defcustom org-log-repeat 'time
1600 "Non-nil means, record moving through the DONE state when triggering repeat.
1601 An auto-repeating tasks is immediately switched back to TODO when marked
1602 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1603 the TODO keyword definition, or recording a closing note by setting
1604 `org-log-done', there will be no record of the task moving through DONE.
1605 This variable forces taking a note anyway. Possible values are:
1607 nil Don't force a record
1608 time Record a time stamp
1609 note Record a note
1611 This option can also be set with on a per-file-basis with
1613 #+STARTUP: logrepeat
1614 #+STARTUP: lognoterepeat
1615 #+STARTUP: nologrepeat
1617 You can have local logging settings for a subtree by setting the LOGGING
1618 property to one or more of these keywords."
1619 :group 'org-todo
1620 :group 'org-progress
1621 :type '(choice
1622 (const :tag "Don't force a record" nil)
1623 (const :tag "Force recording the DONE state" time)
1624 (const :tag "Force recording a note with the DONE state" note)))
1627 (defgroup org-priorities nil
1628 "Priorities in Org-mode."
1629 :tag "Org Priorities"
1630 :group 'org-todo)
1632 (defcustom org-highest-priority ?A
1633 "The highest priority of TODO items. A character like ?A, ?B etc.
1634 Must have a smaller ASCII number than `org-lowest-priority'."
1635 :group 'org-priorities
1636 :type 'character)
1638 (defcustom org-lowest-priority ?C
1639 "The lowest priority of TODO items. A character like ?A, ?B etc.
1640 Must have a larger ASCII number than `org-highest-priority'."
1641 :group 'org-priorities
1642 :type 'character)
1644 (defcustom org-default-priority ?B
1645 "The default priority of TODO items.
1646 This is the priority an item get if no explicit priority is given."
1647 :group 'org-priorities
1648 :type 'character)
1650 (defcustom org-priority-start-cycle-with-default t
1651 "Non-nil means, start with default priority when starting to cycle.
1652 When this is nil, the first step in the cycle will be (depending on the
1653 command used) one higher or lower that the default priority."
1654 :group 'org-priorities
1655 :type 'boolean)
1657 (defgroup org-time nil
1658 "Options concerning time stamps and deadlines in Org-mode."
1659 :tag "Org Time"
1660 :group 'org)
1662 (defcustom org-insert-labeled-timestamps-at-point nil
1663 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1664 When nil, these labeled time stamps are forces into the second line of an
1665 entry, just after the headline. When scheduling from the global TODO list,
1666 the time stamp will always be forced into the second line."
1667 :group 'org-time
1668 :type 'boolean)
1670 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1671 "Formats for `format-time-string' which are used for time stamps.
1672 It is not recommended to change this constant.")
1674 (defcustom org-time-stamp-rounding-minutes '(0 5)
1675 "Number of minutes to round time stamps to.
1676 These are two values, the first applies when first creating a time stamp.
1677 The second applies when changing it with the commands `S-up' and `S-down'.
1678 When changing the time stamp, this means that it will change in steps
1679 of N minutes, as given by the second value.
1681 When a setting is 0 or 1, insert the time unmodified. Useful rounding
1682 numbers should be factors of 60, so for example 5, 10, 15.
1684 When this is larger than 1, you can still force an exact time-stamp by using
1685 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
1686 and by using a prefix arg to `S-up/down' to specify the exact number
1687 of minutes to shift."
1688 :group 'org-time
1689 :get '(lambda (var) ; Make sure all entries have 5 elements
1690 (if (integerp (default-value var))
1691 (list (default-value var) 5)
1692 (default-value var)))
1693 :type '(list
1694 (integer :tag "when inserting times")
1695 (integer :tag "when modifying times")))
1697 ;; Normalize old customizations of this variable.
1698 (when (integerp org-time-stamp-rounding-minutes)
1699 (setq org-time-stamp-rounding-minutes
1700 (list org-time-stamp-rounding-minutes
1701 org-time-stamp-rounding-minutes)))
1703 (defcustom org-display-custom-times nil
1704 "Non-nil means, overlay custom formats over all time stamps.
1705 The formats are defined through the variable `org-time-stamp-custom-formats'.
1706 To turn this on on a per-file basis, insert anywhere in the file:
1707 #+STARTUP: customtime"
1708 :group 'org-time
1709 :set 'set-default
1710 :type 'sexp)
1711 (make-variable-buffer-local 'org-display-custom-times)
1713 (defcustom org-time-stamp-custom-formats
1714 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1715 "Custom formats for time stamps. See `format-time-string' for the syntax.
1716 These are overlayed over the default ISO format if the variable
1717 `org-display-custom-times' is set. Time like %H:%M should be at the
1718 end of the second format."
1719 :group 'org-time
1720 :type 'sexp)
1722 (defun org-time-stamp-format (&optional long inactive)
1723 "Get the right format for a time string."
1724 (let ((f (if long (cdr org-time-stamp-formats)
1725 (car org-time-stamp-formats))))
1726 (if inactive
1727 (concat "[" (substring f 1 -1) "]")
1728 f)))
1730 (defcustom org-time-clocksum-format "%d:%02d"
1731 "The format string used when creating CLOCKSUM lines, or when
1732 org-mode generates a time duration."
1733 :group 'org-time
1734 :type 'string)
1736 (defcustom org-deadline-warning-days 14
1737 "No. of days before expiration during which a deadline becomes active.
1738 This variable governs the display in sparse trees and in the agenda.
1739 When 0 or negative, it means use this number (the absolute value of it)
1740 even if a deadline has a different individual lead time specified."
1741 :group 'org-time
1742 :group 'org-agenda-daily/weekly
1743 :type 'number)
1745 (defcustom org-read-date-prefer-future t
1746 "Non-nil means, assume future for incomplete date input from user.
1747 This affects the following situations:
1748 1. The user gives a day, but no month.
1749 For example, if today is the 15th, and you enter \"3\", Org-mode will
1750 read this as the third of *next* month. However, if you enter \"17\",
1751 it will be considered as *this* month.
1752 2. The user gives a month but not a year.
1753 For example, if it is april and you enter \"feb 2\", this will be read
1754 as feb 2, *next* year. \"May 5\", however, will be this year.
1756 Currently this does not work for ISO week specifications.
1758 When this option is nil, the current month and year will always be used
1759 as defaults."
1760 :group 'org-time
1761 :type 'boolean)
1763 (defcustom org-read-date-display-live t
1764 "Non-nil means, display current interpretation of date prompt live.
1765 This display will be in an overlay, in the minibuffer."
1766 :group 'org-time
1767 :type 'boolean)
1769 (defcustom org-read-date-popup-calendar t
1770 "Non-nil means, pop up a calendar when prompting for a date.
1771 In the calendar, the date can be selected with mouse-1. However, the
1772 minibuffer will also be active, and you can simply enter the date as well.
1773 When nil, only the minibuffer will be available."
1774 :group 'org-time
1775 :type 'boolean)
1776 (if (fboundp 'defvaralias)
1777 (defvaralias 'org-popup-calendar-for-date-prompt
1778 'org-read-date-popup-calendar))
1780 (defcustom org-extend-today-until 0
1781 "The hour when your day really ends. Must be an integer.
1782 This has influence for the following applications:
1783 - When switching the agenda to \"today\". It it is still earlier than
1784 the time given here, the day recognized as TODAY is actually yesterday.
1785 - When a date is read from the user and it is still before the time given
1786 here, the current date and time will be assumed to be yesterday, 23:59.
1787 Also, timestamps inserted in remember templates follow this rule.
1789 IMPORTANT: This is a feature whose implementation is and likely will
1790 remain incomplete. Really, it is only here because past midnight seems to
1791 be the favorite working time of John Wiegley :-)"
1792 :group 'org-time
1793 :type 'number)
1795 (defcustom org-edit-timestamp-down-means-later nil
1796 "Non-nil means, S-down will increase the time in a time stamp.
1797 When nil, S-up will increase."
1798 :group 'org-time
1799 :type 'boolean)
1801 (defcustom org-calendar-follow-timestamp-change t
1802 "Non-nil means, make the calendar window follow timestamp changes.
1803 When a timestamp is modified and the calendar window is visible, it will be
1804 moved to the new date."
1805 :group 'org-time
1806 :type 'boolean)
1808 (defgroup org-tags nil
1809 "Options concerning tags in Org-mode."
1810 :tag "Org Tags"
1811 :group 'org)
1813 (defcustom org-tag-alist nil
1814 "List of tags allowed in Org-mode files.
1815 When this list is nil, Org-mode will base TAG input on what is already in the
1816 buffer.
1817 The value of this variable is an alist, the car of each entry must be a
1818 keyword as a string, the cdr may be a character that is used to select
1819 that tag through the fast-tag-selection interface.
1820 See the manual for details."
1821 :group 'org-tags
1822 :type '(repeat
1823 (choice
1824 (cons (string :tag "Tag name")
1825 (character :tag "Access char"))
1826 (const :tag "Start radio group" (:startgroup))
1827 (const :tag "End radio group" (:endgroup)))))
1829 (defvar org-file-tags nil
1830 "List of tags that can be inherited by all entries in the file.
1831 The tags will be inherited if the variable `org-use-tag-inheritance'
1832 says they should be.
1833 This variable is populated from #+TAG lines.")
1835 (defcustom org-use-fast-tag-selection 'auto
1836 "Non-nil means, use fast tag selection scheme.
1837 This is a special interface to select and deselect tags with single keys.
1838 When nil, fast selection is never used.
1839 When the symbol `auto', fast selection is used if and only if selection
1840 characters for tags have been configured, either through the variable
1841 `org-tag-alist' or through a #+TAGS line in the buffer.
1842 When t, fast selection is always used and selection keys are assigned
1843 automatically if necessary."
1844 :group 'org-tags
1845 :type '(choice
1846 (const :tag "Always" t)
1847 (const :tag "Never" nil)
1848 (const :tag "When selection characters are configured" 'auto)))
1850 (defcustom org-fast-tag-selection-single-key nil
1851 "Non-nil means, fast tag selection exits after first change.
1852 When nil, you have to press RET to exit it.
1853 During fast tag selection, you can toggle this flag with `C-c'.
1854 This variable can also have the value `expert'. In this case, the window
1855 displaying the tags menu is not even shown, until you press C-c again."
1856 :group 'org-tags
1857 :type '(choice
1858 (const :tag "No" nil)
1859 (const :tag "Yes" t)
1860 (const :tag "Expert" expert)))
1862 (defvar org-fast-tag-selection-include-todo nil
1863 "Non-nil means, fast tags selection interface will also offer TODO states.
1864 This is an undocumented feature, you should not rely on it.")
1866 (defcustom org-tags-column (if (featurep 'xemacs) -79 -80)
1867 "The column to which tags should be indented in a headline.
1868 If this number is positive, it specifies the column. If it is negative,
1869 it means that the tags should be flushright to that column. For example,
1870 -80 works well for a normal 80 character screen."
1871 :group 'org-tags
1872 :type 'integer)
1874 (defcustom org-auto-align-tags t
1875 "Non-nil means, realign tags after pro/demotion of TODO state change.
1876 These operations change the length of a headline and therefore shift
1877 the tags around. With this options turned on, after each such operation
1878 the tags are again aligned to `org-tags-column'."
1879 :group 'org-tags
1880 :type 'boolean)
1882 (defcustom org-use-tag-inheritance t
1883 "Non-nil means, tags in levels apply also for sublevels.
1884 When nil, only the tags directly given in a specific line apply there.
1885 This may also be a list of tags that should be inherited, or a regexp that
1886 matches tags that should be inherited. Additional control is possible
1887 with the variable `org-tags-exclude-from-inheritance' which gives an
1888 explicit list of tags to be excluded from inheritance., even if the value of
1889 `org-use-tag-inheritance' would select it for inheritance.
1891 If this option is t, a match early-on in a tree can lead to a large
1892 number of matches in the subtree when constructing the agenda or creating
1893 a sparse tree. If you only want to see the first match in a tree during
1894 a search, check out the variable `org-tags-match-list-sublevels'."
1895 :group 'org-tags
1896 :type '(choice
1897 (const :tag "Not" nil)
1898 (const :tag "Always" t)
1899 (repeat :tag "Specific tags" (string :tag "Tag"))
1900 (regexp :tag "Tags matched by regexp")))
1902 (defcustom org-tags-exclude-from-inheritance nil
1903 "List of tags that should never be inherited.
1904 This is a way to exclude a few tags from inheritance. For way to do
1905 the opposite, to actively allow inheritance for selected tags,
1906 see the variable `org-use-tag-inheritance'."
1907 :group 'org-tags
1908 :type '(repeat (string :tag "Tag")))
1910 (defun org-tag-inherit-p (tag)
1911 "Check if TAG is one that should be inherited."
1912 (cond
1913 ((member tag org-tags-exclude-from-inheritance) nil)
1914 ((eq org-use-tag-inheritance t) t)
1915 ((not org-use-tag-inheritance) nil)
1916 ((stringp org-use-tag-inheritance)
1917 (string-match org-use-tag-inheritance tag))
1918 ((listp org-use-tag-inheritance)
1919 (member tag org-use-tag-inheritance))
1920 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
1922 (defcustom org-tags-match-list-sublevels t
1923 "Non-nil means list also sublevels of headlines matching tag search.
1924 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1925 the sublevels of a headline matching a tag search often also match
1926 the same search. Listing all of them can create very long lists.
1927 Setting this variable to nil causes subtrees of a match to be skipped.
1928 This option is off by default, because inheritance in on. If you turn
1929 inheritance off, you very likely want to turn this option on.
1931 As a special case, if the tag search is restricted to TODO items, the
1932 value of this variable is ignored and sublevels are always checked, to
1933 make sure all corresponding TODO items find their way into the list.
1935 This variable is semi-obsolete and probably should always be true. It
1936 is better to limit inheritance to certain tags using the variables
1937 `org-use-tag-inheritanc'e and `org-tags-exclude-from-inheritance'."
1938 :group 'org-tags
1939 :type 'boolean)
1941 (defvar org-tags-history nil
1942 "History of minibuffer reads for tags.")
1943 (defvar org-last-tags-completion-table nil
1944 "The last used completion table for tags.")
1945 (defvar org-after-tags-change-hook nil
1946 "Hook that is run after the tags in a line have changed.")
1948 (defgroup org-properties nil
1949 "Options concerning properties in Org-mode."
1950 :tag "Org Properties"
1951 :group 'org)
1953 (defcustom org-property-format "%-10s %s"
1954 "How property key/value pairs should be formatted by `indent-line'.
1955 When `indent-line' hits a property definition, it will format the line
1956 according to this format, mainly to make sure that the values are
1957 lined-up with respect to each other."
1958 :group 'org-properties
1959 :type 'string)
1961 (defcustom org-use-property-inheritance nil
1962 "Non-nil means, properties apply also for sublevels.
1964 This setting is chiefly used during property searches. Turning it on can
1965 cause significant overhead when doing a search, which is why it is not
1966 on by default.
1968 When nil, only the properties directly given in the current entry count.
1969 When t, every property is inherited. The value may also be a list of
1970 properties that should have inheritance, or a regular expression matching
1971 properties that should be inherited.
1973 However, note that some special properties use inheritance under special
1974 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
1975 and the properties ending in \"_ALL\" when they are used as descriptor
1976 for valid values of a property.
1978 Note for programmers:
1979 When querying an entry with `org-entry-get', you can control if inheritance
1980 should be used. By default, `org-entry-get' looks only at the local
1981 properties. You can request inheritance by setting the inherit argument
1982 to t (to force inheritance) or to `selective' (to respect the setting
1983 in this variable)."
1984 :group 'org-properties
1985 :type '(choice
1986 (const :tag "Not" nil)
1987 (const :tag "Always" t)
1988 (repeat :tag "Specific properties" (string :tag "Property"))
1989 (regexp :tag "Properties matched by regexp")))
1991 (defun org-property-inherit-p (property)
1992 "Check if PROPERTY is one that should be inherited."
1993 (cond
1994 ((eq org-use-property-inheritance t) t)
1995 ((not org-use-property-inheritance) nil)
1996 ((stringp org-use-property-inheritance)
1997 (string-match org-use-property-inheritance property))
1998 ((listp org-use-property-inheritance)
1999 (member property org-use-property-inheritance))
2000 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2002 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2003 "The default column format, if no other format has been defined.
2004 This variable can be set on the per-file basis by inserting a line
2006 #+COLUMNS: %25ITEM ....."
2007 :group 'org-properties
2008 :type 'string)
2010 (defcustom org-columns-ellipses ".."
2011 "The ellipses to be used when a field in column view is truncated.
2012 When this is the empty string, as many characters as possible are shown,
2013 but then there will be no visual indication that the field has been truncated.
2014 When this is a string of length N, the last N characters of a truncated
2015 field are replaced by this string. If the column is narrower than the
2016 ellipses string, only part of the ellipses string will be shown."
2017 :group 'org-properties
2018 :type 'string)
2020 (defcustom org-columns-modify-value-for-display-function nil
2021 "Function that modifies values for display in column view.
2022 For example, it can be used to cut out a certain part from a time stamp.
2023 The function must take 2 arguments:
2025 column-title The tite of the column (*not* the property name)
2026 value The value that should be modified.
2028 The function should return the value that should be displayed,
2029 or nil if the normal value should be used."
2030 :group 'org-properties
2031 :type 'function)
2033 (defcustom org-effort-property "Effort"
2034 "The property that is being used to keep track of effort estimates.
2035 Effort estimates given in this property need to have the format H:MM."
2036 :group 'org-properties
2037 :group 'org-progress
2038 :type '(string :tag "Property"))
2040 (defconst org-global-properties-fixed
2041 '(("VISIBILITY_ALL" . "folded children content all"))
2042 "List of property/value pairs that can be inherited by any entry.
2043 These are fixed values, for the preset properties.")
2046 (defcustom org-global-properties nil
2047 "List of property/value pairs that can be inherited by any entry.
2048 You can set buffer-local values for the same purpose in the variable
2049 `org-file-properties' this by adding lines like
2051 #+PROPERTY: NAME VALUE"
2052 :group 'org-properties
2053 :type '(repeat
2054 (cons (string :tag "Property")
2055 (string :tag "Value"))))
2057 (defvar org-file-properties nil
2058 "List of property/value pairs that can be inherited by any entry.
2059 Valid for the current buffer.
2060 This variable is populated from #+PROPERTY lines.")
2061 (make-variable-buffer-local 'org-file-properties)
2063 (defgroup org-agenda nil
2064 "Options concerning agenda views in Org-mode."
2065 :tag "Org Agenda"
2066 :group 'org)
2068 (defvar org-category nil
2069 "Variable used by org files to set a category for agenda display.
2070 Such files should use a file variable to set it, for example
2072 # -*- mode: org; org-category: \"ELisp\"
2074 or contain a special line
2076 #+CATEGORY: ELisp
2078 If the file does not specify a category, then file's base name
2079 is used instead.")
2080 (make-variable-buffer-local 'org-category)
2081 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2083 (defcustom org-agenda-files nil
2084 "The files to be used for agenda display.
2085 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2086 \\[org-remove-file]. You can also use customize to edit the list.
2088 If an entry is a directory, all files in that directory that are matched by
2089 `org-agenda-file-regexp' will be part of the file list.
2091 If the value of the variable is not a list but a single file name, then
2092 the list of agenda files is actually stored and maintained in that file, one
2093 agenda file per line."
2094 :group 'org-agenda
2095 :type '(choice
2096 (repeat :tag "List of files and directories" file)
2097 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2099 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2100 "Regular expression to match files for `org-agenda-files'.
2101 If any element in the list in that variable contains a directory instead
2102 of a normal file, all files in that directory that are matched by this
2103 regular expression will be included."
2104 :group 'org-agenda
2105 :type 'regexp)
2107 (defcustom org-agenda-text-search-extra-files nil
2108 "List of extra files to be searched by text search commands.
2109 These files will be search in addition to the agenda files by the
2110 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2111 Note that these files will only be searched for text search commands,
2112 not for the other agenda views like todo lists, tag searches or the weekly
2113 agenda. This variable is intended to list notes and possibly archive files
2114 that should also be searched by these two commands.
2115 In fact, if the first element in the list is the symbol `agenda-archives',
2116 than all archive files of all agenda files will be added to the search
2117 scope."
2118 :group 'org-agenda
2119 :type '(set :greedy t
2120 (const :tag "Agenda Archives" agenda-archives)
2121 (repeat :inline t (file))))
2123 (if (fboundp 'defvaralias)
2124 (defvaralias 'org-agenda-multi-occur-extra-files
2125 'org-agenda-text-search-extra-files))
2127 (defcustom org-agenda-skip-unavailable-files nil
2128 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2129 A nil value means to remove them, after a query, from the list."
2130 :group 'org-agenda
2131 :type 'boolean)
2133 (defcustom org-calendar-to-agenda-key [?c]
2134 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2135 The command `org-calendar-goto-agenda' will be bound to this key. The
2136 default is the character `c' because then `c' can be used to switch back and
2137 forth between agenda and calendar."
2138 :group 'org-agenda
2139 :type 'sexp)
2141 (defcustom org-calendar-agenda-action-key [?k]
2142 "The key to be installed in `calendar-mode-map' for agenda-action.
2143 The command `org-agenda-action' will be bound to this key. The
2144 default is the character `k' because we use the same key in the agenda."
2145 :group 'org-agenda
2146 :type 'sexp)
2148 (eval-after-load "calendar"
2149 '(progn
2150 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2151 'org-calendar-goto-agenda)
2152 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2153 'org-agenda-action)))
2155 (defgroup org-latex nil
2156 "Options for embedding LaTeX code into Org-mode."
2157 :tag "Org LaTeX"
2158 :group 'org)
2160 (defcustom org-format-latex-options
2161 '(:foreground default :background default :scale 1.0
2162 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2163 :matchers ("begin" "$" "$$" "\\(" "\\["))
2164 "Options for creating images from LaTeX fragments.
2165 This is a property list with the following properties:
2166 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2167 `default' means use the foreground of the default face.
2168 :background the background color, or \"Transparent\".
2169 `default' means use the background of the default face.
2170 :scale a scaling factor for the size of the images.
2171 :html-foreground, :html-background, :html-scale
2172 the same numbers for HTML export.
2173 :matchers a list indicating which matchers should be used to
2174 find LaTeX fragments. Valid members of this list are:
2175 \"begin\" find environments
2176 \"$\" find math expressions surrounded by $...$
2177 \"$$\" find math expressions surrounded by $$....$$
2178 \"\\(\" find math expressions surrounded by \\(...\\)
2179 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2180 :group 'org-latex
2181 :type 'plist)
2183 (defcustom org-format-latex-header "\\documentclass{article}
2184 \\usepackage{fullpage} % do not remove
2185 \\usepackage{amssymb}
2186 \\usepackage[usenames]{color}
2187 \\usepackage{amsmath}
2188 \\usepackage{latexsym}
2189 \\usepackage[mathscr]{eucal}
2190 \\pagestyle{empty} % do not remove"
2191 "The document header used for processing LaTeX fragments."
2192 :group 'org-latex
2193 :type 'string)
2196 (defgroup org-font-lock nil
2197 "Font-lock settings for highlighting in Org-mode."
2198 :tag "Org Font Lock"
2199 :group 'org)
2201 (defcustom org-level-color-stars-only nil
2202 "Non-nil means fontify only the stars in each headline.
2203 When nil, the entire headline is fontified.
2204 Changing it requires restart of `font-lock-mode' to become effective
2205 also in regions already fontified."
2206 :group 'org-font-lock
2207 :type 'boolean)
2209 (defcustom org-hide-leading-stars nil
2210 "Non-nil means, hide the first N-1 stars in a headline.
2211 This works by using the face `org-hide' for these stars. This
2212 face is white for a light background, and black for a dark
2213 background. You may have to customize the face `org-hide' to
2214 make this work.
2215 Changing it requires restart of `font-lock-mode' to become effective
2216 also in regions already fontified.
2217 You may also set this on a per-file basis by adding one of the following
2218 lines to the buffer:
2220 #+STARTUP: hidestars
2221 #+STARTUP: showstars"
2222 :group 'org-font-lock
2223 :type 'boolean)
2225 (defcustom org-fontify-done-headline nil
2226 "Non-nil means, change the face of a headline if it is marked DONE.
2227 Normally, only the TODO/DONE keyword indicates the state of a headline.
2228 When this is non-nil, the headline after the keyword is set to the
2229 `org-headline-done' as an additional indication."
2230 :group 'org-font-lock
2231 :type 'boolean)
2233 (defcustom org-fontify-emphasized-text t
2234 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2235 Changing this variable requires a restart of Emacs to take effect."
2236 :group 'org-font-lock
2237 :type 'boolean)
2239 (defcustom org-highlight-latex-fragments-and-specials nil
2240 "Non-nil means, fontify what is treated specially by the exporters."
2241 :group 'org-font-lock
2242 :type 'boolean)
2244 (defcustom org-hide-emphasis-markers nil
2245 "Non-nil mean font-lock should hide the emphasis marker characters."
2246 :group 'org-font-lock
2247 :type 'boolean)
2249 (defvar org-emph-re nil
2250 "Regular expression for matching emphasis.")
2251 (defvar org-verbatim-re nil
2252 "Regular expression for matching verbatim text.")
2253 (defvar org-emphasis-regexp-components) ; defined just below
2254 (defvar org-emphasis-alist) ; defined just below
2255 (defun org-set-emph-re (var val)
2256 "Set variable and compute the emphasis regular expression."
2257 (set var val)
2258 (when (and (boundp 'org-emphasis-alist)
2259 (boundp 'org-emphasis-regexp-components)
2260 org-emphasis-alist org-emphasis-regexp-components)
2261 (let* ((e org-emphasis-regexp-components)
2262 (pre (car e))
2263 (post (nth 1 e))
2264 (border (nth 2 e))
2265 (body (nth 3 e))
2266 (nl (nth 4 e))
2267 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
2268 (body1 (concat body "*?"))
2269 (markers (mapconcat 'car org-emphasis-alist ""))
2270 (vmarkers (mapconcat
2271 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2272 org-emphasis-alist "")))
2273 ;; make sure special characters appear at the right position in the class
2274 (if (string-match "\\^" markers)
2275 (setq markers (concat (replace-match "" t t markers) "^")))
2276 (if (string-match "-" markers)
2277 (setq markers (concat (replace-match "" t t markers) "-")))
2278 (if (string-match "\\^" vmarkers)
2279 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2280 (if (string-match "-" vmarkers)
2281 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2282 (if (> nl 0)
2283 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2284 (int-to-string nl) "\\}")))
2285 ;; Make the regexp
2286 (setq org-emph-re
2287 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
2288 "\\("
2289 "\\([" markers "]\\)"
2290 "\\("
2291 "[^" border "]\\|"
2292 "[^" border (if (and nil stacked) markers) "]"
2293 body1
2294 "[^" border (if (and nil stacked) markers) "]"
2295 "\\)"
2296 "\\3\\)"
2297 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
2298 (setq org-verbatim-re
2299 (concat "\\([" pre "]\\|^\\)"
2300 "\\("
2301 "\\([" vmarkers "]\\)"
2302 "\\("
2303 "[^" border "]\\|"
2304 "[^" border "]"
2305 body1
2306 "[^" border "]"
2307 "\\)"
2308 "\\3\\)"
2309 "\\([" post "]\\|$\\)")))))
2311 (defcustom org-emphasis-regexp-components
2312 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
2313 "Components used to build the regular expression for emphasis.
2314 This is a list with 6 entries. Terminology: In an emphasis string
2315 like \" *strong word* \", we call the initial space PREMATCH, the final
2316 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2317 and \"trong wor\" is the body. The different components in this variable
2318 specify what is allowed/forbidden in each part:
2320 pre Chars allowed as prematch. Beginning of line will be allowed too.
2321 post Chars allowed as postmatch. End of line will be allowed too.
2322 border The chars *forbidden* as border characters.
2323 body-regexp A regexp like \".\" to match a body character. Don't use
2324 non-shy groups here, and don't allow newline here.
2325 newline The maximum number of newlines allowed in an emphasis exp.
2327 Use customize to modify this, or restart Emacs after changing it."
2328 :group 'org-font-lock
2329 :set 'org-set-emph-re
2330 :type '(list
2331 (sexp :tag "Allowed chars in pre ")
2332 (sexp :tag "Allowed chars in post ")
2333 (sexp :tag "Forbidden chars in border ")
2334 (sexp :tag "Regexp for body ")
2335 (integer :tag "number of newlines allowed")
2336 (option (boolean :tag "Please ignore this button"))))
2338 (defcustom org-emphasis-alist
2339 `(("*" bold "<b>" "</b>")
2340 ("/" italic "<i>" "</i>")
2341 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
2342 ("=" org-code "<code>" "</code>" verbatim)
2343 ("~" org-verbatim "<code>" "</code>" verbatim)
2344 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2345 "<del>" "</del>")
2347 "Special syntax for emphasized text.
2348 Text starting and ending with a special character will be emphasized, for
2349 example *bold*, _underlined_ and /italic/. This variable sets the marker
2350 characters, the face to be used by font-lock for highlighting in Org-mode
2351 Emacs buffers, and the HTML tags to be used for this.
2352 Use customize to modify this, or restart Emacs after changing it."
2353 :group 'org-font-lock
2354 :set 'org-set-emph-re
2355 :type '(repeat
2356 (list
2357 (string :tag "Marker character")
2358 (choice
2359 (face :tag "Font-lock-face")
2360 (plist :tag "Face property list"))
2361 (string :tag "HTML start tag")
2362 (string :tag "HTML end tag")
2363 (option (const verbatim)))))
2365 ;;; Miscellaneous options
2367 (defgroup org-completion nil
2368 "Completion in Org-mode."
2369 :tag "Org Completion"
2370 :group 'org)
2372 (defcustom org-completion-use-ido nil
2373 "Non-nil means, use ido completion wherever possible."
2374 :group 'org-completion
2375 :type 'boolean)
2377 (defcustom org-completion-fallback-command 'hippie-expand
2378 "The expansion command called by \\[org-complete] in normal context.
2379 Normal means, no org-mode-specific context."
2380 :group 'org-completion
2381 :type 'function)
2383 ;;; Functions and variables from ther packages
2384 ;; Declared here to avoid compiler warnings
2386 ;; XEmacs only
2387 (defvar outline-mode-menu-heading)
2388 (defvar outline-mode-menu-show)
2389 (defvar outline-mode-menu-hide)
2390 (defvar zmacs-regions) ; XEmacs regions
2392 ;; Emacs only
2393 (defvar mark-active)
2395 ;; Various packages
2396 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2397 (declare-function calendar-forward-day "cal-move" (arg))
2398 (declare-function calendar-goto-date "cal-move" (date))
2399 (declare-function calendar-goto-today "cal-move" ())
2400 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2401 (defvar calc-embedded-close-formula)
2402 (defvar calc-embedded-open-formula)
2403 (declare-function cdlatex-tab "ext:cdlatex" ())
2404 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2405 (defvar font-lock-unfontify-region-function)
2406 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2407 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2408 (defvar iswitchb-temp-buflist)
2409 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2410 (declare-function org-agenda-skip "org-agenda" ())
2411 (declare-function org-format-agenda-item "org-agenda"
2412 (extra txt &optional category tags dotime noprefix remove-re))
2413 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2414 (declare-function org-agenda-change-all-lines "org-agenda"
2415 (newhead hdmarker &optional fixface just-this))
2416 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2417 (declare-function org-agenda-maybe-redo "org-agenda" ())
2418 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2419 (beg end))
2420 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
2421 (declare-function parse-time-string "parse-time" (string))
2422 (declare-function remember "remember" (&optional initial))
2423 (declare-function remember-buffer-desc "remember" ())
2424 (declare-function remember-finalize "remember" ())
2425 (defvar remember-save-after-remembering)
2426 (defvar remember-data-file)
2427 (defvar remember-register)
2428 (defvar remember-buffer)
2429 (defvar remember-handler-functions)
2430 (defvar remember-annotation-functions)
2431 (defvar texmathp-why)
2432 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2433 (declare-function table--at-cell-p "table" (position &optional object at-column))
2435 (defvar w3m-current-url)
2436 (defvar w3m-current-title)
2438 (defvar org-latex-regexps)
2440 ;;; Autoload and prepare some org modules
2442 ;; Some table stuff that needs to be defined here, because it is used
2443 ;; by the functions setting up org-mode or checking for table context.
2445 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2446 "Detects an org-type or table-type table.")
2447 (defconst org-table-line-regexp "^[ \t]*|"
2448 "Detects an org-type table line.")
2449 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2450 "Detects an org-type table line.")
2451 (defconst org-table-hline-regexp "^[ \t]*|-"
2452 "Detects an org-type table hline.")
2453 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2454 "Detects a table-type table hline.")
2455 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2456 "Searching from within a table (any type) this finds the first line
2457 outside the table.")
2459 ;; Autoload the functions in org-table.el that are needed by functions here.
2461 (eval-and-compile
2462 (org-autoload "org-table"
2463 '(org-table-align org-table-begin org-table-blank-field
2464 org-table-convert org-table-convert-region org-table-copy-down
2465 org-table-copy-region org-table-create
2466 org-table-create-or-convert-from-region
2467 org-table-create-with-table.el org-table-current-dline
2468 org-table-cut-region org-table-delete-column org-table-edit-field
2469 org-table-edit-formulas org-table-end org-table-eval-formula
2470 org-table-export org-table-field-info
2471 org-table-get-stored-formulas org-table-goto-column
2472 org-table-hline-and-move org-table-import org-table-insert-column
2473 org-table-insert-hline org-table-insert-row org-table-iterate
2474 org-table-justify-field-maybe org-table-kill-row
2475 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2476 org-table-move-column org-table-move-column-left
2477 org-table-move-column-right org-table-move-row
2478 org-table-move-row-down org-table-move-row-up
2479 org-table-next-field org-table-next-row org-table-paste-rectangle
2480 org-table-previous-field org-table-recalculate
2481 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2482 org-table-toggle-coordinate-overlays
2483 org-table-toggle-formula-debugger org-table-wrap-region
2484 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
2486 (defun org-at-table-p (&optional table-type)
2487 "Return t if the cursor is inside an org-type table.
2488 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2489 (if org-enable-table-editor
2490 (save-excursion
2491 (beginning-of-line 1)
2492 (looking-at (if table-type org-table-any-line-regexp
2493 org-table-line-regexp)))
2494 nil))
2495 (defsubst org-table-p () (org-at-table-p))
2497 (defun org-at-table.el-p ()
2498 "Return t if and only if we are at a table.el table."
2499 (and (org-at-table-p 'any)
2500 (save-excursion
2501 (goto-char (org-table-begin 'any))
2502 (looking-at org-table1-hline-regexp))))
2503 (defun org-table-recognize-table.el ()
2504 "If there is a table.el table nearby, recognize it and move into it."
2505 (if org-table-tab-recognizes-table.el
2506 (if (org-at-table.el-p)
2507 (progn
2508 (beginning-of-line 1)
2509 (if (looking-at org-table-dataline-regexp)
2511 (if (looking-at org-table1-hline-regexp)
2512 (progn
2513 (beginning-of-line 2)
2514 (if (looking-at org-table-any-border-regexp)
2515 (beginning-of-line -1)))))
2516 (if (re-search-forward "|" (org-table-end t) t)
2517 (progn
2518 (require 'table)
2519 (if (table--at-cell-p (point))
2521 (message "recognizing table.el table...")
2522 (table-recognize-table)
2523 (message "recognizing table.el table...done")))
2524 (error "This should not happen..."))
2526 nil)
2527 nil))
2529 (defun org-at-table-hline-p ()
2530 "Return t if the cursor is inside a hline in a table."
2531 (if org-enable-table-editor
2532 (save-excursion
2533 (beginning-of-line 1)
2534 (looking-at org-table-hline-regexp))
2535 nil))
2537 (defvar org-table-clean-did-remove-column nil)
2539 (defun org-table-map-tables (function)
2540 "Apply FUNCTION to the start of all tables in the buffer."
2541 (save-excursion
2542 (save-restriction
2543 (widen)
2544 (goto-char (point-min))
2545 (while (re-search-forward org-table-any-line-regexp nil t)
2546 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2547 (beginning-of-line 1)
2548 (if (looking-at org-table-line-regexp)
2549 (save-excursion (funcall function)))
2550 (re-search-forward org-table-any-border-regexp nil 1))))
2551 (message "Mapping tables: done"))
2553 ;; Declare and autoload functions from org-exp.el
2555 (declare-function org-default-export-plist "org-exp")
2556 (declare-function org-infile-export-plist "org-exp")
2557 (declare-function org-get-current-options "org-exp")
2558 (eval-and-compile
2559 (org-autoload "org-exp"
2560 '(org-export org-export-as-ascii org-export-visible
2561 org-insert-export-options-template org-export-as-html-and-open
2562 org-export-as-html-batch org-export-as-html-to-buffer
2563 org-replace-region-by-html org-export-region-as-html
2564 org-export-as-html org-export-icalendar-this-file
2565 org-export-icalendar-all-agenda-files
2566 org-table-clean-before-export
2567 org-export-icalendar-combine-agenda-files org-export-as-xoxo)))
2569 ;; Declare and autoload functions from org-agenda.el
2571 (eval-and-compile
2572 (org-autoload "org-agenda"
2573 '(org-agenda org-agenda-list org-search-view
2574 org-todo-list org-tags-view org-agenda-list-stuck-projects
2575 org-diary org-agenda-to-appt)))
2577 ;; Autoload org-remember
2579 (eval-and-compile
2580 (org-autoload "org-remember"
2581 '(org-remember-insinuate org-remember-annotation
2582 org-remember-apply-template org-remember org-remember-handler)))
2584 ;; Autoload org-clock.el
2587 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
2588 (beg end))
2589 (declare-function org-update-mode-line "org-clock" ())
2590 (defvar org-clock-start-time)
2591 (defvar org-clock-marker (make-marker)
2592 "Marker recording the last clock-in.")
2594 (eval-and-compile
2595 (org-autoload
2596 "org-clock"
2597 '(org-clock-in org-clock-out org-clock-cancel
2598 org-clock-goto org-clock-sum org-clock-display
2599 org-remove-clock-overlays org-clock-report
2600 org-clocktable-shift org-dblock-write:clocktable
2601 org-get-clocktable)))
2603 (defun org-clock-update-time-maybe ()
2604 "If this is a CLOCK line, update it and return t.
2605 Otherwise, return nil."
2606 (interactive)
2607 (save-excursion
2608 (beginning-of-line 1)
2609 (skip-chars-forward " \t")
2610 (when (looking-at org-clock-string)
2611 (let ((re (concat "[ \t]*" org-clock-string
2612 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
2613 "\\([ \t]*=>.*\\)?\\)?"))
2614 ts te h m s neg)
2615 (cond
2616 ((not (looking-at re))
2617 nil)
2618 ((not (match-end 2))
2619 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2620 (> org-clock-marker (point))
2621 (<= org-clock-marker (point-at-eol)))
2622 ;; The clock is running here
2623 (setq org-clock-start-time
2624 (apply 'encode-time
2625 (org-parse-time-string (match-string 1))))
2626 (org-update-mode-line)))
2628 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
2629 (end-of-line 1)
2630 (setq ts (match-string 1)
2631 te (match-string 3))
2632 (setq s (- (time-to-seconds
2633 (apply 'encode-time (org-parse-time-string te)))
2634 (time-to-seconds
2635 (apply 'encode-time (org-parse-time-string ts))))
2636 neg (< s 0)
2637 s (abs s)
2638 h (floor (/ s 3600))
2639 s (- s (* 3600 h))
2640 m (floor (/ s 60))
2641 s (- s (* 60 s)))
2642 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
2643 t))))))
2645 (defun org-check-running-clock ()
2646 "Check if the current buffer contains the running clock.
2647 If yes, offer to stop it and to save the buffer with the changes."
2648 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2649 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
2650 (buffer-name))))
2651 (org-clock-out)
2652 (when (y-or-n-p "Save changed buffer?")
2653 (save-buffer))))
2655 (defun org-clocktable-try-shift (dir n)
2656 "Check if this line starts a clock table, if yes, shift the time block."
2657 (when (org-match-line "#\\+BEGIN: clocktable\\>")
2658 (org-clocktable-shift dir n)))
2660 ;; Autoload org-timer.el
2662 ;(declare-function org-timer "org-timer")
2664 (eval-and-compile
2665 (org-autoload
2666 "org-timer"
2667 '(org-timer-start org-timer org-timer-item
2668 org-timer-change-times-in-region)))
2671 ;; Autoload archiving code
2672 ;; The stuff that is needed for cycling and tags has to be defined here.
2674 (defgroup org-archive nil
2675 "Options concerning archiving in Org-mode."
2676 :tag "Org Archive"
2677 :group 'org-structure)
2679 (defcustom org-archive-location "%s_archive::"
2680 "The location where subtrees should be archived.
2682 The value of this variable is a string, consisting of two parts,
2683 separated by a double-colon. The first part is a filename and
2684 the second part is a headline.
2686 When the filename is omitted, archiving happens in the same file.
2687 %s in the filename will be replaced by the current file
2688 name (without the directory part). Archiving to a different file
2689 is useful to keep archived entries from contributing to the
2690 Org-mode Agenda.
2692 The archived entries will be filed as subtrees of the specified
2693 headline. When the headline is omitted, the subtrees are simply
2694 filed away at the end of the file, as top-level entries.
2696 Here are a few examples:
2697 \"%s_archive::\"
2698 If the current file is Projects.org, archive in file
2699 Projects.org_archive, as top-level trees. This is the default.
2701 \"::* Archived Tasks\"
2702 Archive in the current file, under the top-level headline
2703 \"* Archived Tasks\".
2705 \"~/org/archive.org::\"
2706 Archive in file ~/org/archive.org (absolute path), as top-level trees.
2708 \"basement::** Finished Tasks\"
2709 Archive in file ./basement (relative path), as level 3 trees
2710 below the level 2 heading \"** Finished Tasks\".
2712 You may set this option on a per-file basis by adding to the buffer a
2713 line like
2715 #+ARCHIVE: basement::** Finished Tasks
2717 You may also define it locally for a subtree by setting an ARCHIVE property
2718 in the entry. If such a property is found in an entry, or anywhere up
2719 the hierarchy, it will be used."
2720 :group 'org-archive
2721 :type 'string)
2723 (defcustom org-archive-tag "ARCHIVE"
2724 "The tag that marks a subtree as archived.
2725 An archived subtree does not open during visibility cycling, and does
2726 not contribute to the agenda listings.
2727 After changing this, font-lock must be restarted in the relevant buffers to
2728 get the proper fontification."
2729 :group 'org-archive
2730 :group 'org-keywords
2731 :type 'string)
2733 (defcustom org-agenda-skip-archived-trees t
2734 "Non-nil means, the agenda will skip any items located in archived trees.
2735 An archived tree is a tree marked with the tag ARCHIVE. The use of this
2736 variable is no longer recommended, you should leave it at the value t.
2737 Instead, use the key `v' to cycle the archives-mode in the agenda."
2738 :group 'org-archive
2739 :group 'org-agenda-skip
2740 :type 'boolean)
2742 (defcustom org-cycle-open-archived-trees nil
2743 "Non-nil means, `org-cycle' will open archived trees.
2744 An archived tree is a tree marked with the tag ARCHIVE.
2745 When nil, archived trees will stay folded. You can still open them with
2746 normal outline commands like `show-all', but not with the cycling commands."
2747 :group 'org-archive
2748 :group 'org-cycle
2749 :type 'boolean)
2751 (defcustom org-sparse-tree-open-archived-trees nil
2752 "Non-nil means sparse tree construction shows matches in archived trees.
2753 When nil, matches in these trees are highlighted, but the trees are kept in
2754 collapsed state."
2755 :group 'org-archive
2756 :group 'org-sparse-trees
2757 :type 'boolean)
2759 (defun org-cycle-hide-archived-subtrees (state)
2760 "Re-hide all archived subtrees after a visibility state change."
2761 (when (and (not org-cycle-open-archived-trees)
2762 (not (memq state '(overview folded))))
2763 (save-excursion
2764 (let* ((globalp (memq state '(contents all)))
2765 (beg (if globalp (point-min) (point)))
2766 (end (if globalp (point-max) (org-end-of-subtree t))))
2767 (org-hide-archived-subtrees beg end)
2768 (goto-char beg)
2769 (if (looking-at (concat ".*:" org-archive-tag ":"))
2770 (message "%s" (substitute-command-keys
2771 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
2773 (defun org-force-cycle-archived ()
2774 "Cycle subtree even if it is archived."
2775 (interactive)
2776 (setq this-command 'org-cycle)
2777 (let ((org-cycle-open-archived-trees t))
2778 (call-interactively 'org-cycle)))
2780 (defun org-hide-archived-subtrees (beg end)
2781 "Re-hide all archived subtrees after a visibility state change."
2782 (save-excursion
2783 (let* ((re (concat ":" org-archive-tag ":")))
2784 (goto-char beg)
2785 (while (re-search-forward re end t)
2786 (and (org-on-heading-p) (hide-subtree))
2787 (org-end-of-subtree t)))))
2789 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
2791 (eval-and-compile
2792 (org-autoload "org-archive"
2793 '(org-add-archive-files org-archive-subtree
2794 org-archive-to-archive-sibling org-toggle-archive-tag)))
2796 ;; Autoload Column View Code
2798 (declare-function org-columns-number-to-string "org-colview")
2799 (declare-function org-columns-get-format-and-top-level "org-colview")
2800 (declare-function org-columns-compute "org-colview")
2802 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
2803 '(org-columns-number-to-string org-columns-get-format-and-top-level
2804 org-columns-compute org-agenda-columns org-columns-remove-overlays
2805 org-columns org-insert-columns-dblock org-dblock-write:columnview))
2807 ;; Autoload ID code
2809 (org-autoload "org-id"
2810 '(org-id-get-create org-id-new org-id-copy org-id-get
2811 org-id-get-with-outline-path-completion
2812 org-id-get-with-outline-drilling
2813 org-id-goto org-id-find))
2815 ;;; Variables for pre-computed regular expressions, all buffer local
2817 (defvar org-drawer-regexp nil
2818 "Matches first line of a hidden block.")
2819 (make-variable-buffer-local 'org-drawer-regexp)
2820 (defvar org-todo-regexp nil
2821 "Matches any of the TODO state keywords.")
2822 (make-variable-buffer-local 'org-todo-regexp)
2823 (defvar org-not-done-regexp nil
2824 "Matches any of the TODO state keywords except the last one.")
2825 (make-variable-buffer-local 'org-not-done-regexp)
2826 (defvar org-todo-line-regexp nil
2827 "Matches a headline and puts TODO state into group 2 if present.")
2828 (make-variable-buffer-local 'org-todo-line-regexp)
2829 (defvar org-complex-heading-regexp nil
2830 "Matches a headline and puts everything into groups:
2831 group 1: the stars
2832 group 2: The todo keyword, maybe
2833 group 3: Priority cookie
2834 group 4: True headline
2835 group 5: Tags")
2836 (make-variable-buffer-local 'org-complex-heading-regexp)
2837 (defvar org-todo-line-tags-regexp nil
2838 "Matches a headline and puts TODO state into group 2 if present.
2839 Also put tags into group 4 if tags are present.")
2840 (make-variable-buffer-local 'org-todo-line-tags-regexp)
2841 (defvar org-nl-done-regexp nil
2842 "Matches newline followed by a headline with the DONE keyword.")
2843 (make-variable-buffer-local 'org-nl-done-regexp)
2844 (defvar org-looking-at-done-regexp nil
2845 "Matches the DONE keyword a point.")
2846 (make-variable-buffer-local 'org-looking-at-done-regexp)
2847 (defvar org-ds-keyword-length 12
2848 "Maximum length of the Deadline and SCHEDULED keywords.")
2849 (make-variable-buffer-local 'org-ds-keyword-length)
2850 (defvar org-deadline-regexp nil
2851 "Matches the DEADLINE keyword.")
2852 (make-variable-buffer-local 'org-deadline-regexp)
2853 (defvar org-deadline-time-regexp nil
2854 "Matches the DEADLINE keyword together with a time stamp.")
2855 (make-variable-buffer-local 'org-deadline-time-regexp)
2856 (defvar org-deadline-line-regexp nil
2857 "Matches the DEADLINE keyword and the rest of the line.")
2858 (make-variable-buffer-local 'org-deadline-line-regexp)
2859 (defvar org-scheduled-regexp nil
2860 "Matches the SCHEDULED keyword.")
2861 (make-variable-buffer-local 'org-scheduled-regexp)
2862 (defvar org-scheduled-time-regexp nil
2863 "Matches the SCHEDULED keyword together with a time stamp.")
2864 (make-variable-buffer-local 'org-scheduled-time-regexp)
2865 (defvar org-closed-time-regexp nil
2866 "Matches the CLOSED keyword together with a time stamp.")
2867 (make-variable-buffer-local 'org-closed-time-regexp)
2869 (defvar org-keyword-time-regexp nil
2870 "Matches any of the 4 keywords, together with the time stamp.")
2871 (make-variable-buffer-local 'org-keyword-time-regexp)
2872 (defvar org-keyword-time-not-clock-regexp nil
2873 "Matches any of the 3 keywords, together with the time stamp.")
2874 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
2875 (defvar org-maybe-keyword-time-regexp nil
2876 "Matches a timestamp, possibly preceeded by a keyword.")
2877 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
2878 (defvar org-planning-or-clock-line-re nil
2879 "Matches a line with planning or clock info.")
2880 (make-variable-buffer-local 'org-planning-or-clock-line-re)
2882 (defconst org-plain-time-of-day-regexp
2883 (concat
2884 "\\(\\<[012]?[0-9]"
2885 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2886 "\\(--?"
2887 "\\(\\<[012]?[0-9]"
2888 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2889 "\\)?")
2890 "Regular expression to match a plain time or time range.
2891 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2892 groups carry important information:
2893 0 the full match
2894 1 the first time, range or not
2895 8 the second time, if it is a range.")
2897 (defconst org-plain-time-extension-regexp
2898 (concat
2899 "\\(\\<[012]?[0-9]"
2900 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2901 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
2902 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
2903 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2904 groups carry important information:
2905 0 the full match
2906 7 hours of duration
2907 9 minutes of duration")
2909 (defconst org-stamp-time-of-day-regexp
2910 (concat
2911 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
2912 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
2913 "\\(--?"
2914 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
2915 "Regular expression to match a timestamp time or time range.
2916 After a match, the following groups carry important information:
2917 0 the full match
2918 1 date plus weekday, for backreferencing to make sure both times on same day
2919 2 the first time, range or not
2920 4 the second time, if it is a range.")
2922 (defconst org-startup-options
2923 '(("fold" org-startup-folded t)
2924 ("overview" org-startup-folded t)
2925 ("nofold" org-startup-folded nil)
2926 ("showall" org-startup-folded nil)
2927 ("content" org-startup-folded content)
2928 ("hidestars" org-hide-leading-stars t)
2929 ("showstars" org-hide-leading-stars nil)
2930 ("odd" org-odd-levels-only t)
2931 ("oddeven" org-odd-levels-only nil)
2932 ("align" org-startup-align-all-tables t)
2933 ("noalign" org-startup-align-all-tables nil)
2934 ("customtime" org-display-custom-times t)
2935 ("logdone" org-log-done time)
2936 ("lognotedone" org-log-done note)
2937 ("nologdone" org-log-done nil)
2938 ("lognoteclock-out" org-log-note-clock-out t)
2939 ("nolognoteclock-out" org-log-note-clock-out nil)
2940 ("logrepeat" org-log-repeat state)
2941 ("lognoterepeat" org-log-repeat note)
2942 ("nologrepeat" org-log-repeat nil)
2943 ("constcgs" constants-unit-system cgs)
2944 ("constSI" constants-unit-system SI))
2945 "Variable associated with STARTUP options for org-mode.
2946 Each element is a list of three items: The startup options as written
2947 in the #+STARTUP line, the corresponding variable, and the value to
2948 set this variable to if the option is found. An optional forth element PUSH
2949 means to push this value onto the list in the variable.")
2951 (defun org-set-regexps-and-options ()
2952 "Precompute regular expressions for current buffer."
2953 (when (org-mode-p)
2954 (org-set-local 'org-todo-kwd-alist nil)
2955 (org-set-local 'org-todo-key-alist nil)
2956 (org-set-local 'org-todo-key-trigger nil)
2957 (org-set-local 'org-todo-keywords-1 nil)
2958 (org-set-local 'org-done-keywords nil)
2959 (org-set-local 'org-todo-heads nil)
2960 (org-set-local 'org-todo-sets nil)
2961 (org-set-local 'org-todo-log-states nil)
2962 (org-set-local 'org-file-properties nil)
2963 (org-set-local 'org-file-tags nil)
2964 (let ((re (org-make-options-regexp
2965 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
2966 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
2967 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")))
2968 (splitre "[ \t]+")
2969 kwds kws0 kwsa key log value cat arch tags const links hw dws
2970 tail sep kws1 prio props ftags drawers
2971 ext-setup-or-nil setup-contents (start 0))
2972 (save-excursion
2973 (save-restriction
2974 (widen)
2975 (goto-char (point-min))
2976 (while (or (and ext-setup-or-nil
2977 (string-match re ext-setup-or-nil start)
2978 (setq start (match-end 0)))
2979 (and (setq ext-setup-or-nil nil start 0)
2980 (re-search-forward re nil t)))
2981 (setq key (upcase (match-string 1 ext-setup-or-nil))
2982 value (org-match-string-no-properties 2 ext-setup-or-nil))
2983 (cond
2984 ((equal key "CATEGORY")
2985 (if (string-match "[ \t]+$" value)
2986 (setq value (replace-match "" t t value)))
2987 (setq cat value))
2988 ((member key '("SEQ_TODO" "TODO"))
2989 (push (cons 'sequence (org-split-string value splitre)) kwds))
2990 ((equal key "TYP_TODO")
2991 (push (cons 'type (org-split-string value splitre)) kwds))
2992 ((equal key "TAGS")
2993 (setq tags (append tags (org-split-string value splitre))))
2994 ((equal key "COLUMNS")
2995 (org-set-local 'org-columns-default-format value))
2996 ((equal key "LINK")
2997 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
2998 (push (cons (match-string 1 value)
2999 (org-trim (match-string 2 value)))
3000 links)))
3001 ((equal key "PRIORITIES")
3002 (setq prio (org-split-string value " +")))
3003 ((equal key "PROPERTY")
3004 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3005 (push (cons (match-string 1 value) (match-string 2 value))
3006 props)))
3007 ((equal key "FILETAGS")
3008 (when (string-match "\\S-" value)
3009 (setq ftags
3010 (append
3011 ftags
3012 (apply 'append
3013 (mapcar (lambda (x) (org-split-string x ":"))
3014 (org-split-string value)))))))
3015 ((equal key "DRAWERS")
3016 (setq drawers (org-split-string value splitre)))
3017 ((equal key "CONSTANTS")
3018 (setq const (append const (org-split-string value splitre))))
3019 ((equal key "STARTUP")
3020 (let ((opts (org-split-string value splitre))
3021 l var val)
3022 (while (setq l (pop opts))
3023 (when (setq l (assoc l org-startup-options))
3024 (setq var (nth 1 l) val (nth 2 l))
3025 (if (not (nth 3 l))
3026 (set (make-local-variable var) val)
3027 (if (not (listp (symbol-value var)))
3028 (set (make-local-variable var) nil))
3029 (set (make-local-variable var) (symbol-value var))
3030 (add-to-list var val))))))
3031 ((equal key "ARCHIVE")
3032 (string-match " *$" value)
3033 (setq arch (replace-match "" t t value))
3034 (remove-text-properties 0 (length arch)
3035 '(face t fontified t) arch))
3036 ((equal key "SETUPFILE")
3037 (setq setup-contents (org-file-contents
3038 (expand-file-name
3039 (org-remove-double-quotes value))
3040 'noerror))
3041 (if (not ext-setup-or-nil)
3042 (setq ext-setup-or-nil setup-contents start 0)
3043 (setq ext-setup-or-nil
3044 (concat (substring ext-setup-or-nil 0 start)
3045 "\n" setup-contents "\n"
3046 (substring ext-setup-or-nil start)))))
3047 ))))
3048 (when cat
3049 (org-set-local 'org-category (intern cat))
3050 (push (cons "CATEGORY" cat) props))
3051 (when prio
3052 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3053 (setq prio (mapcar 'string-to-char prio))
3054 (org-set-local 'org-highest-priority (nth 0 prio))
3055 (org-set-local 'org-lowest-priority (nth 1 prio))
3056 (org-set-local 'org-default-priority (nth 2 prio)))
3057 (and props (org-set-local 'org-file-properties (nreverse props)))
3058 (and ftags (org-set-local 'org-file-tags ftags))
3059 (and drawers (org-set-local 'org-drawers drawers))
3060 (and arch (org-set-local 'org-archive-location arch))
3061 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3062 ;; Process the TODO keywords
3063 (unless kwds
3064 ;; Use the global values as if they had been given locally.
3065 (setq kwds (default-value 'org-todo-keywords))
3066 (if (stringp (car kwds))
3067 (setq kwds (list (cons org-todo-interpretation
3068 (default-value 'org-todo-keywords)))))
3069 (setq kwds (reverse kwds)))
3070 (setq kwds (nreverse kwds))
3071 (let (inter kws kw)
3072 (while (setq kws (pop kwds))
3073 (setq inter (pop kws) sep (member "|" kws)
3074 kws0 (delete "|" (copy-sequence kws))
3075 kwsa nil
3076 kws1 (mapcar
3077 (lambda (x)
3078 ;; 1 2
3079 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3080 (progn
3081 (setq kw (match-string 1 x)
3082 key (and (match-end 2) (match-string 2 x))
3083 log (org-extract-log-state-settings x))
3084 (push (cons kw (and key (string-to-char key))) kwsa)
3085 (and log (push log org-todo-log-states))
3087 (error "Invalid TODO keyword %s" x)))
3088 kws0)
3089 kwsa (if kwsa (append '((:startgroup))
3090 (nreverse kwsa)
3091 '((:endgroup))))
3092 hw (car kws1)
3093 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3094 tail (list inter hw (car dws) (org-last dws)))
3095 (add-to-list 'org-todo-heads hw 'append)
3096 (push kws1 org-todo-sets)
3097 (setq org-done-keywords (append org-done-keywords dws nil))
3098 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3099 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3100 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3101 (setq org-todo-sets (nreverse org-todo-sets)
3102 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3103 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3104 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3105 ;; Process the constants
3106 (when const
3107 (let (e cst)
3108 (while (setq e (pop const))
3109 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3110 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3111 (setq org-table-formula-constants-local cst)))
3113 ;; Process the tags.
3114 (when tags
3115 (let (e tgs)
3116 (while (setq e (pop tags))
3117 (cond
3118 ((equal e "{") (push '(:startgroup) tgs))
3119 ((equal e "}") (push '(:endgroup) tgs))
3120 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3121 (push (cons (match-string 1 e)
3122 (string-to-char (match-string 2 e)))
3123 tgs))
3124 (t (push (list e) tgs))))
3125 (org-set-local 'org-tag-alist nil)
3126 (while (setq e (pop tgs))
3127 (or (and (stringp (car e))
3128 (assoc (car e) org-tag-alist))
3129 (push e org-tag-alist)))))
3131 ;; Compute the regular expressions and other local variables
3132 (if (not org-done-keywords)
3133 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
3134 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3135 (length org-scheduled-string)
3136 (length org-clock-string)
3137 (length org-closed-string)))
3138 org-drawer-regexp
3139 (concat "^[ \t]*:\\("
3140 (mapconcat 'regexp-quote org-drawers "\\|")
3141 "\\):[ \t]*$")
3142 org-not-done-keywords
3143 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3144 org-todo-regexp
3145 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3146 "\\|") "\\)\\>")
3147 org-not-done-regexp
3148 (concat "\\<\\("
3149 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3150 "\\)\\>")
3151 org-todo-line-regexp
3152 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3153 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3154 "\\)\\>\\)?[ \t]*\\(.*\\)")
3155 org-complex-heading-regexp
3156 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
3157 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3158 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3159 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3160 org-nl-done-regexp
3161 (concat "\n\\*+[ \t]+"
3162 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3163 "\\)" "\\>")
3164 org-todo-line-tags-regexp
3165 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3166 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3167 (org-re
3168 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3169 org-looking-at-done-regexp
3170 (concat "^" "\\(?:"
3171 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3172 "\\>")
3173 org-deadline-regexp (concat "\\<" org-deadline-string)
3174 org-deadline-time-regexp
3175 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3176 org-deadline-line-regexp
3177 (concat "\\<\\(" org-deadline-string "\\).*")
3178 org-scheduled-regexp
3179 (concat "\\<" org-scheduled-string)
3180 org-scheduled-time-regexp
3181 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3182 org-closed-time-regexp
3183 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3184 org-keyword-time-regexp
3185 (concat "\\<\\(" org-scheduled-string
3186 "\\|" org-deadline-string
3187 "\\|" org-closed-string
3188 "\\|" org-clock-string "\\)"
3189 " *[[<]\\([^]>]+\\)[]>]")
3190 org-keyword-time-not-clock-regexp
3191 (concat "\\<\\(" org-scheduled-string
3192 "\\|" org-deadline-string
3193 "\\|" org-closed-string
3194 "\\)"
3195 " *[[<]\\([^]>]+\\)[]>]")
3196 org-maybe-keyword-time-regexp
3197 (concat "\\(\\<\\(" org-scheduled-string
3198 "\\|" org-deadline-string
3199 "\\|" org-closed-string
3200 "\\|" org-clock-string "\\)\\)?"
3201 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3202 org-planning-or-clock-line-re
3203 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3204 "\\|" org-deadline-string
3205 "\\|" org-closed-string "\\|" org-clock-string
3206 "\\)\\>\\)")
3208 (org-compute-latex-and-specials-regexp)
3209 (org-set-font-lock-defaults))))
3211 (defun org-file-contents (file &optional noerror)
3212 "Return the contents of FILE, as a string."
3213 (if (or (not file)
3214 (not (file-readable-p file)))
3215 (if noerror
3216 (progn
3217 (message "Cannot read file %s" file)
3218 (ding) (sit-for 2)
3220 (error "Cannot read file %s" file))
3221 (with-temp-buffer
3222 (insert-file-contents file)
3223 (buffer-string))))
3225 (defun org-extract-log-state-settings (x)
3226 "Extract the log state setting from a TODO keyword string.
3227 This will extract info from a string like \"WAIT(w@/!)\"."
3228 (let (kw key log1 log2)
3229 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3230 (setq kw (match-string 1 x)
3231 key (and (match-end 2) (match-string 2 x))
3232 log1 (and (match-end 3) (match-string 3 x))
3233 log2 (and (match-end 4) (match-string 4 x)))
3234 (and (or log1 log2)
3235 (list kw
3236 (and log1 (if (equal log1 "!") 'time 'note))
3237 (and log2 (if (equal log2 "!") 'time 'note)))))))
3239 (defun org-remove-keyword-keys (list)
3240 "Remove a pair of parenthesis at the end of each string in LIST."
3241 (mapcar (lambda (x)
3242 (if (string-match "(.*)$" x)
3243 (substring x 0 (match-beginning 0))
3245 list))
3247 ;; FIXME: this could be done much better, using second characters etc.
3248 (defun org-assign-fast-keys (alist)
3249 "Assign fast keys to a keyword-key alist.
3250 Respect keys that are already there."
3251 (let (new e k c c1 c2 (char ?a))
3252 (while (setq e (pop alist))
3253 (cond
3254 ((equal e '(:startgroup)) (push e new))
3255 ((equal e '(:endgroup)) (push e new))
3257 (setq k (car e) c2 nil)
3258 (if (cdr e)
3259 (setq c (cdr e))
3260 ;; automatically assign a character.
3261 (setq c1 (string-to-char
3262 (downcase (substring
3263 k (if (= (string-to-char k) ?@) 1 0)))))
3264 (if (or (rassoc c1 new) (rassoc c1 alist))
3265 (while (or (rassoc char new) (rassoc char alist))
3266 (setq char (1+ char)))
3267 (setq c2 c1))
3268 (setq c (or c2 char)))
3269 (push (cons k c) new))))
3270 (nreverse new)))
3272 ;;; Some variables used in various places
3274 (defvar org-window-configuration nil
3275 "Used in various places to store a window configuration.")
3276 (defvar org-finish-function nil
3277 "Function to be called when `C-c C-c' is used.
3278 This is for getting out of special buffers like remember.")
3281 ;; FIXME: Occasionally check by commenting these, to make sure
3282 ;; no other functions uses these, forgetting to let-bind them.
3283 (defvar entry)
3284 (defvar state)
3285 (defvar last-state)
3286 (defvar date)
3287 (defvar description)
3289 ;; Defined somewhere in this file, but used before definition.
3290 (defvar org-html-entities)
3291 (defvar org-struct-menu)
3292 (defvar org-org-menu)
3293 (defvar org-tbl-menu)
3294 (defvar org-agenda-keymap)
3296 ;;;; Define the Org-mode
3298 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3299 (error "Conflict with outdated version of allout.el. Load org.el before allout.el, or ugrade to newer allout, for example by switching to Emacs 22."))
3302 ;; We use a before-change function to check if a table might need
3303 ;; an update.
3304 (defvar org-table-may-need-update t
3305 "Indicates that a table might need an update.
3306 This variable is set by `org-before-change-function'.
3307 `org-table-align' sets it back to nil.")
3308 (defun org-before-change-function (beg end)
3309 "Every change indicates that a table might need an update."
3310 (setq org-table-may-need-update t))
3311 (defvar org-mode-map)
3312 (defvar org-mode-hook nil)
3313 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3314 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3315 (defvar org-table-buffer-is-an nil)
3316 (defconst org-outline-regexp "\\*+ ")
3318 ;;;###autoload
3319 (define-derived-mode org-mode outline-mode "Org"
3320 "Outline-based notes management and organizer, alias
3321 \"Carsten's outline-mode for keeping track of everything.\"
3323 Org-mode develops organizational tasks around a NOTES file which
3324 contains information about projects as plain text. Org-mode is
3325 implemented on top of outline-mode, which is ideal to keep the content
3326 of large files well structured. It supports ToDo items, deadlines and
3327 time stamps, which magically appear in the diary listing of the Emacs
3328 calendar. Tables are easily created with a built-in table editor.
3329 Plain text URL-like links connect to websites, emails (VM), Usenet
3330 messages (Gnus), BBDB entries, and any files related to the project.
3331 For printing and sharing of notes, an Org-mode file (or a part of it)
3332 can be exported as a structured ASCII or HTML file.
3334 The following commands are available:
3336 \\{org-mode-map}"
3338 ;; Get rid of Outline menus, they are not needed
3339 ;; Need to do this here because define-derived-mode sets up
3340 ;; the keymap so late. Still, it is a waste to call this each time
3341 ;; we switch another buffer into org-mode.
3342 (if (featurep 'xemacs)
3343 (when (boundp 'outline-mode-menu-heading)
3344 ;; Assume this is Greg's port, it used easymenu
3345 (easy-menu-remove outline-mode-menu-heading)
3346 (easy-menu-remove outline-mode-menu-show)
3347 (easy-menu-remove outline-mode-menu-hide))
3348 (define-key org-mode-map [menu-bar headings] 'undefined)
3349 (define-key org-mode-map [menu-bar hide] 'undefined)
3350 (define-key org-mode-map [menu-bar show] 'undefined))
3352 (org-load-modules-maybe)
3353 (easy-menu-add org-org-menu)
3354 (easy-menu-add org-tbl-menu)
3355 (org-install-agenda-files-menu)
3356 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3357 (org-add-to-invisibility-spec '(org-cwidth))
3358 (when (featurep 'xemacs)
3359 (org-set-local 'line-move-ignore-invisible t))
3360 (org-set-local 'outline-regexp org-outline-regexp)
3361 (org-set-local 'outline-level 'org-outline-level)
3362 (when (and org-ellipsis
3363 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3364 (fboundp 'make-glyph-code))
3365 (unless org-display-table
3366 (setq org-display-table (make-display-table)))
3367 (set-display-table-slot
3368 org-display-table 4
3369 (vconcat (mapcar
3370 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3371 org-ellipsis)))
3372 (if (stringp org-ellipsis) org-ellipsis "..."))))
3373 (setq buffer-display-table org-display-table))
3374 (org-set-regexps-and-options)
3375 ;; Calc embedded
3376 (org-set-local 'calc-embedded-open-mode "# ")
3377 (modify-syntax-entry ?# "<")
3378 (modify-syntax-entry ?@ "w")
3379 (if org-startup-truncated (setq truncate-lines t))
3380 (org-set-local 'font-lock-unfontify-region-function
3381 'org-unfontify-region)
3382 ;; Activate before-change-function
3383 (org-set-local 'org-table-may-need-update t)
3384 (org-add-hook 'before-change-functions 'org-before-change-function nil
3385 'local)
3386 ;; Check for running clock before killing a buffer
3387 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3388 ;; Paragraphs and auto-filling
3389 (org-set-autofill-regexps)
3390 (setq indent-line-function 'org-indent-line-function)
3391 (org-update-radio-target-regexp)
3393 ;; Comment characters
3394 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3395 (org-set-local 'comment-padding " ")
3397 ;; Align options lines
3398 (org-set-local
3399 'align-mode-rules-list
3400 '((org-in-buffer-settings
3401 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3402 (modes . '(org-mode)))))
3404 ;; Imenu
3405 (org-set-local 'imenu-create-index-function
3406 'org-imenu-get-tree)
3408 ;; Make isearch reveal context
3409 (if (or (featurep 'xemacs)
3410 (not (boundp 'outline-isearch-open-invisible-function)))
3411 ;; Emacs 21 and XEmacs make use of the hook
3412 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3413 ;; Emacs 22 deals with this through a special variable
3414 (org-set-local 'outline-isearch-open-invisible-function
3415 (lambda (&rest ignore) (org-show-context 'isearch))))
3417 ;; If empty file that did not turn on org-mode automatically, make it to.
3418 (if (and org-insert-mode-line-in-empty-file
3419 (interactive-p)
3420 (= (point-min) (point-max)))
3421 (insert "# -*- mode: org -*-\n\n"))
3423 (unless org-inhibit-startup
3424 (when org-startup-align-all-tables
3425 (let ((bmp (buffer-modified-p)))
3426 (org-table-map-tables 'org-table-align)
3427 (set-buffer-modified-p bmp)))
3428 (org-set-startup-visibility)))
3430 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3432 (defun org-current-time ()
3433 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3434 (if (> (car org-time-stamp-rounding-minutes) 1)
3435 (let ((r (car org-time-stamp-rounding-minutes))
3436 (time (decode-time)))
3437 (apply 'encode-time
3438 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3439 (nthcdr 2 time))))
3440 (current-time)))
3442 ;;;; Font-Lock stuff, including the activators
3444 (defvar org-mouse-map (make-sparse-keymap))
3445 (org-defkey org-mouse-map
3446 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3447 (org-defkey org-mouse-map
3448 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3449 (when org-mouse-1-follows-link
3450 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3451 (when org-tab-follows-link
3452 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3453 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3454 (when org-return-follows-link
3455 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
3456 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
3458 (require 'font-lock)
3460 (defconst org-non-link-chars "]\t\n\r<>")
3461 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3462 "shell" "elisp"))
3463 (defvar org-link-types-re nil
3464 "Matches a link that has a url-like prefix like \"http:\"")
3465 (defvar org-link-re-with-space nil
3466 "Matches a link with spaces, optional angular brackets around it.")
3467 (defvar org-link-re-with-space2 nil
3468 "Matches a link with spaces, optional angular brackets around it.")
3469 (defvar org-link-re-with-space3 nil
3470 "Matches a link with spaces, only for internal part in bracket links.")
3471 (defvar org-angle-link-re nil
3472 "Matches link with angular brackets, spaces are allowed.")
3473 (defvar org-plain-link-re nil
3474 "Matches plain link, without spaces.")
3475 (defvar org-bracket-link-regexp nil
3476 "Matches a link in double brackets.")
3477 (defvar org-bracket-link-analytic-regexp nil
3478 "Regular expression used to analyze links.
3479 Here is what the match groups contain after a match:
3480 1: http:
3481 2: http
3482 3: path
3483 4: [desc]
3484 5: desc")
3485 (defvar org-any-link-re nil
3486 "Regular expression matching any link.")
3488 (defun org-make-link-regexps ()
3489 "Update the link regular expressions.
3490 This should be called after the variable `org-link-types' has changed."
3491 (setq org-link-types-re
3492 (concat
3493 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3494 org-link-re-with-space
3495 (concat
3496 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3497 "\\([^" org-non-link-chars " ]"
3498 "[^" org-non-link-chars "]*"
3499 "[^" org-non-link-chars " ]\\)>?")
3500 org-link-re-with-space2
3501 (concat
3502 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3503 "\\([^" org-non-link-chars " ]"
3504 "[^\t\n\r]*"
3505 "[^" org-non-link-chars " ]\\)>?")
3506 org-link-re-with-space3
3507 (concat
3508 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3509 "\\([^" org-non-link-chars " ]"
3510 "[^\t\n\r]*\\)")
3511 org-angle-link-re
3512 (concat
3513 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3514 "\\([^" org-non-link-chars " ]"
3515 "[^" org-non-link-chars "]*"
3516 "\\)>")
3517 org-plain-link-re
3518 (concat
3519 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3520 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3521 org-bracket-link-regexp
3522 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3523 org-bracket-link-analytic-regexp
3524 (concat
3525 "\\[\\["
3526 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3527 "\\([^]]+\\)"
3528 "\\]"
3529 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3530 "\\]")
3531 org-any-link-re
3532 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3533 org-angle-link-re "\\)\\|\\("
3534 org-plain-link-re "\\)")))
3536 (org-make-link-regexps)
3538 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
3539 "Regular expression for fast time stamp matching.")
3540 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
3541 "Regular expression for fast time stamp matching.")
3542 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3543 "Regular expression matching time strings for analysis.
3544 This one does not require the space after the date, so it can be used
3545 on a string that terminates immediately after the date.")
3546 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3547 "Regular expression matching time strings for analysis.")
3548 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
3549 "Regular expression matching time stamps, with groups.")
3550 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
3551 "Regular expression matching time stamps (also [..]), with groups.")
3552 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3553 "Regular expression matching a time stamp range.")
3554 (defconst org-tr-regexp-both
3555 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3556 "Regular expression matching a time stamp range.")
3557 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3558 org-ts-regexp "\\)?")
3559 "Regular expression matching a time stamp or time stamp range.")
3560 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3561 org-ts-regexp-both "\\)?")
3562 "Regular expression matching a time stamp or time stamp range.
3563 The time stamps may be either active or inactive.")
3565 (defvar org-emph-face nil)
3567 (defun org-do-emphasis-faces (limit)
3568 "Run through the buffer and add overlays to links."
3569 (let (rtn)
3570 (while (and (not rtn) (re-search-forward org-emph-re limit t))
3571 (if (not (= (char-after (match-beginning 3))
3572 (char-after (match-beginning 4))))
3573 (progn
3574 (setq rtn t)
3575 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3576 'face
3577 (nth 1 (assoc (match-string 3)
3578 org-emphasis-alist)))
3579 (add-text-properties (match-beginning 2) (match-end 2)
3580 '(font-lock-multiline t))
3581 (when org-hide-emphasis-markers
3582 (add-text-properties (match-end 4) (match-beginning 5)
3583 '(invisible org-link))
3584 (add-text-properties (match-beginning 3) (match-end 3)
3585 '(invisible org-link)))))
3586 (backward-char 1))
3587 rtn))
3589 (defun org-emphasize (&optional char)
3590 "Insert or change an emphasis, i.e. a font like bold or italic.
3591 If there is an active region, change that region to a new emphasis.
3592 If there is no region, just insert the marker characters and position
3593 the cursor between them.
3594 CHAR should be either the marker character, or the first character of the
3595 HTML tag associated with that emphasis. If CHAR is a space, the means
3596 to remove the emphasis of the selected region.
3597 If char is not given (for example in an interactive call) it
3598 will be prompted for."
3599 (interactive)
3600 (let ((eal org-emphasis-alist) e det
3601 (erc org-emphasis-regexp-components)
3602 (prompt "")
3603 (string "") beg end move tag c s)
3604 (if (org-region-active-p)
3605 (setq beg (region-beginning) end (region-end)
3606 string (buffer-substring beg end))
3607 (setq move t))
3609 (while (setq e (pop eal))
3610 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
3611 c (aref tag 0))
3612 (push (cons c (string-to-char (car e))) det)
3613 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
3614 (substring tag 1)))))
3615 (setq det (nreverse det))
3616 (unless char
3617 (message "%s" (concat "Emphasis marker or tag:" prompt))
3618 (setq char (read-char-exclusive)))
3619 (setq char (or (cdr (assoc char det)) char))
3620 (if (equal char ?\ )
3621 (setq s "" move nil)
3622 (unless (assoc (char-to-string char) org-emphasis-alist)
3623 (error "No such emphasis marker: \"%c\"" char))
3624 (setq s (char-to-string char)))
3625 (while (and (> (length string) 1)
3626 (equal (substring string 0 1) (substring string -1))
3627 (assoc (substring string 0 1) org-emphasis-alist))
3628 (setq string (substring string 1 -1)))
3629 (setq string (concat s string s))
3630 (if beg (delete-region beg end))
3631 (unless (or (bolp)
3632 (string-match (concat "[" (nth 0 erc) "\n]")
3633 (char-to-string (char-before (point)))))
3634 (insert " "))
3635 (unless (string-match (concat "[" (nth 1 erc) "\n]")
3636 (char-to-string (char-after (point))))
3637 (insert " ") (backward-char 1))
3638 (insert string)
3639 (and move (backward-char 1))))
3641 (defconst org-nonsticky-props
3642 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
3645 (defun org-activate-plain-links (limit)
3646 "Run through the buffer and add overlays to links."
3647 (catch 'exit
3648 (let (f)
3649 (while (re-search-forward org-plain-link-re limit t)
3650 (setq f (get-text-property (match-beginning 0) 'face))
3651 (if (or (eq f 'org-tag)
3652 (and (listp f) (memq 'org-tag f)))
3654 (add-text-properties (match-beginning 0) (match-end 0)
3655 (list 'mouse-face 'highlight
3656 'rear-nonsticky org-nonsticky-props
3657 'keymap org-mouse-map
3659 (throw 'exit t))))))
3661 (defun org-activate-code (limit)
3662 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
3663 (progn
3664 (remove-text-properties (match-beginning 0) (match-end 0)
3665 '(display t invisible t intangible t))
3666 t)))
3668 (defun org-activate-angle-links (limit)
3669 "Run through the buffer and add overlays to links."
3670 (if (re-search-forward org-angle-link-re limit t)
3671 (progn
3672 (add-text-properties (match-beginning 0) (match-end 0)
3673 (list 'mouse-face 'highlight
3674 'rear-nonsticky org-nonsticky-props
3675 'keymap org-mouse-map
3677 t)))
3679 (defun org-activate-bracket-links (limit)
3680 "Run through the buffer and add overlays to bracketed links."
3681 (if (re-search-forward org-bracket-link-regexp limit t)
3682 (let* ((help (concat "LINK: "
3683 (org-match-string-no-properties 1)))
3684 ;; FIXME: above we should remove the escapes.
3685 ;; but that requires another match, protecting match data,
3686 ;; a lot of overhead for font-lock.
3687 (ip (org-maybe-intangible
3688 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
3689 'keymap org-mouse-map 'mouse-face 'highlight
3690 'font-lock-multiline t 'help-echo help)))
3691 (vp (list 'rear-nonsticky org-nonsticky-props
3692 'keymap org-mouse-map 'mouse-face 'highlight
3693 ' font-lock-multiline t 'help-echo help)))
3694 ;; We need to remove the invisible property here. Table narrowing
3695 ;; may have made some of this invisible.
3696 (remove-text-properties (match-beginning 0) (match-end 0)
3697 '(invisible nil))
3698 (if (match-end 3)
3699 (progn
3700 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3701 (add-text-properties (match-beginning 3) (match-end 3) vp)
3702 (add-text-properties (match-end 3) (match-end 0) ip))
3703 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3704 (add-text-properties (match-beginning 1) (match-end 1) vp)
3705 (add-text-properties (match-end 1) (match-end 0) ip))
3706 t)))
3708 (defun org-activate-dates (limit)
3709 "Run through the buffer and add overlays to dates."
3710 (if (re-search-forward org-tsr-regexp-both limit t)
3711 (progn
3712 (add-text-properties (match-beginning 0) (match-end 0)
3713 (list 'mouse-face 'highlight
3714 'rear-nonsticky org-nonsticky-props
3715 'keymap org-mouse-map))
3716 (when org-display-custom-times
3717 (if (match-end 3)
3718 (org-display-custom-time (match-beginning 3) (match-end 3)))
3719 (org-display-custom-time (match-beginning 1) (match-end 1)))
3720 t)))
3722 (defvar org-target-link-regexp nil
3723 "Regular expression matching radio targets in plain text.")
3724 (make-variable-buffer-local 'org-target-link-regexp)
3725 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3726 "Regular expression matching a link target.")
3727 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3728 "Regular expression matching a radio target.")
3729 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
3730 "Regular expression matching any target.")
3732 (defun org-activate-target-links (limit)
3733 "Run through the buffer and add overlays to target matches."
3734 (when org-target-link-regexp
3735 (let ((case-fold-search t))
3736 (if (re-search-forward org-target-link-regexp limit t)
3737 (progn
3738 (add-text-properties (match-beginning 0) (match-end 0)
3739 (list 'mouse-face 'highlight
3740 'rear-nonsticky org-nonsticky-props
3741 'keymap org-mouse-map
3742 'help-echo "Radio target link"
3743 'org-linked-text t))
3744 t)))))
3746 (defun org-update-radio-target-regexp ()
3747 "Find all radio targets in this file and update the regular expression."
3748 (interactive)
3749 (when (memq 'radio org-activate-links)
3750 (setq org-target-link-regexp
3751 (org-make-target-link-regexp (org-all-targets 'radio)))
3752 (org-restart-font-lock)))
3754 (defun org-hide-wide-columns (limit)
3755 (let (s e)
3756 (setq s (text-property-any (point) (or limit (point-max))
3757 'org-cwidth t))
3758 (when s
3759 (setq e (next-single-property-change s 'org-cwidth))
3760 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
3761 (goto-char e)
3762 t)))
3764 (defvar org-latex-and-specials-regexp nil
3765 "Regular expression for highlighting export special stuff.")
3766 (defvar org-match-substring-regexp)
3767 (defvar org-match-substring-with-braces-regexp)
3768 (defvar org-export-html-special-string-regexps)
3770 (defun org-compute-latex-and-specials-regexp ()
3771 "Compute regular expression for stuff treated specially by exporters."
3772 (if (not org-highlight-latex-fragments-and-specials)
3773 (org-set-local 'org-latex-and-specials-regexp nil)
3774 (require 'org-exp)
3775 (let*
3776 ((matchers (plist-get org-format-latex-options :matchers))
3777 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
3778 org-latex-regexps)))
3779 (options (org-combine-plists (org-default-export-plist)
3780 (org-infile-export-plist)))
3781 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
3782 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
3783 (org-export-with-TeX-macros (plist-get options :TeX-macros))
3784 (org-export-html-expand (plist-get options :expand-quoted-html))
3785 (org-export-with-special-strings (plist-get options :special-strings))
3786 (re-sub
3787 (cond
3788 ((equal org-export-with-sub-superscripts '{})
3789 (list org-match-substring-with-braces-regexp))
3790 (org-export-with-sub-superscripts
3791 (list org-match-substring-regexp))
3792 (t nil)))
3793 (re-latex
3794 (if org-export-with-LaTeX-fragments
3795 (mapcar (lambda (x) (nth 1 x)) latexs)))
3796 (re-macros
3797 (if org-export-with-TeX-macros
3798 (list (concat "\\\\"
3799 (regexp-opt
3800 (append (mapcar 'car org-html-entities)
3801 (if (boundp 'org-latex-entities)
3802 org-latex-entities nil))
3803 'words))) ; FIXME
3805 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
3806 (re-special (if org-export-with-special-strings
3807 (mapcar (lambda (x) (car x))
3808 org-export-html-special-string-regexps)))
3809 (re-rest
3810 (delq nil
3811 (list
3812 (if org-export-html-expand "@<[^>\n]+>")
3813 ))))
3814 (org-set-local
3815 'org-latex-and-specials-regexp
3816 (mapconcat 'identity (append re-latex re-sub re-macros re-special
3817 re-rest) "\\|")))))
3819 (defun org-do-latex-and-special-faces (limit)
3820 "Run through the buffer and add overlays to links."
3821 (when org-latex-and-specials-regexp
3822 (let (rtn d)
3823 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
3824 limit t))
3825 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
3826 'face))
3827 '(org-code org-verbatim underline)))
3828 (progn
3829 (setq rtn t
3830 d (cond ((member (char-after (1+ (match-beginning 0)))
3831 '(?_ ?^)) 1)
3832 (t 0)))
3833 (font-lock-prepend-text-property
3834 (+ d (match-beginning 0)) (match-end 0)
3835 'face 'org-latex-and-export-specials)
3836 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
3837 '(font-lock-multiline t)))))
3838 rtn)))
3840 (defun org-restart-font-lock ()
3841 "Restart font-lock-mode, to force refontification."
3842 (when (and (boundp 'font-lock-mode) font-lock-mode)
3843 (font-lock-mode -1)
3844 (font-lock-mode 1)))
3846 (defun org-all-targets (&optional radio)
3847 "Return a list of all targets in this file.
3848 With optional argument RADIO, only find radio targets."
3849 (let ((re (if radio org-radio-target-regexp org-target-regexp))
3850 rtn)
3851 (save-excursion
3852 (goto-char (point-min))
3853 (while (re-search-forward re nil t)
3854 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
3855 rtn)))
3857 (defun org-make-target-link-regexp (targets)
3858 "Make regular expression matching all strings in TARGETS.
3859 The regular expression finds the targets also if there is a line break
3860 between words."
3861 (and targets
3862 (concat
3863 "\\<\\("
3864 (mapconcat
3865 (lambda (x)
3866 (while (string-match " +" x)
3867 (setq x (replace-match "\\s-+" t t x)))
3869 targets
3870 "\\|")
3871 "\\)\\>")))
3873 (defun org-activate-tags (limit)
3874 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
3875 (progn
3876 (add-text-properties (match-beginning 1) (match-end 1)
3877 (list 'mouse-face 'highlight
3878 'rear-nonsticky org-nonsticky-props
3879 'keymap org-mouse-map))
3880 t)))
3882 (defun org-outline-level ()
3883 (save-excursion
3884 (looking-at outline-regexp)
3885 (if (match-beginning 1)
3886 (+ (org-get-string-indentation (match-string 1)) 1000)
3887 (1- (- (match-end 0) (match-beginning 0))))))
3889 (defvar org-font-lock-keywords nil)
3891 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
3892 "Regular expression matching a property line.")
3894 (defvar org-font-lock-hook nil
3895 "Functions to be called for special font lock stuff.")
3897 (defun org-font-lock-hook (limit)
3898 (run-hook-with-args 'org-font-lock-hook limit))
3900 (defun org-set-font-lock-defaults ()
3901 (let* ((em org-fontify-emphasized-text)
3902 (lk org-activate-links)
3903 (org-font-lock-extra-keywords
3904 (list
3905 ;; Call the hook
3906 '(org-font-lock-hook)
3907 ;; Headlines
3908 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
3909 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
3910 ;; Table lines
3911 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
3912 (1 'org-table t))
3913 ;; Table internals
3914 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
3915 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
3916 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
3917 ;; Drawers
3918 (list org-drawer-regexp '(0 'org-special-keyword t))
3919 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
3920 ;; Properties
3921 (list org-property-re
3922 '(1 'org-special-keyword t)
3923 '(3 'org-property-value t))
3924 (if org-format-transports-properties-p
3925 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
3926 ;; Links
3927 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
3928 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
3929 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
3930 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
3931 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
3932 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
3933 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
3934 '(org-hide-wide-columns (0 nil append))
3935 ;; TODO lines
3936 (list (concat "^\\*+[ \t]+" org-todo-regexp)
3937 '(1 (org-get-todo-face 1) t))
3938 ;; DONE
3939 (if org-fontify-done-headline
3940 (list (concat "^[*]+ +\\<\\("
3941 (mapconcat 'regexp-quote org-done-keywords "\\|")
3942 "\\)\\(.*\\)")
3943 '(2 'org-headline-done t))
3944 nil)
3945 ;; Priorities
3946 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
3947 ;; Tags
3948 '(org-font-lock-add-tag-faces)
3949 ;; Special keywords
3950 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
3951 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
3952 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
3953 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
3954 ;; Emphasis
3955 (if em
3956 (if (featurep 'xemacs)
3957 '(org-do-emphasis-faces (0 nil append))
3958 '(org-do-emphasis-faces)))
3959 ;; Checkboxes
3960 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
3961 2 'bold prepend)
3962 (if org-provide-checkbox-statistics
3963 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
3964 (0 (org-get-checkbox-statistics-face) t)))
3965 ;; Description list items
3966 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
3967 2 'bold prepend)
3968 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
3969 '(1 'org-archived prepend))
3970 ;; Specials
3971 '(org-do-latex-and-special-faces)
3972 ;; Code
3973 '(org-activate-code (1 'org-code t))
3974 ;; COMMENT
3975 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
3976 "\\|" org-quote-string "\\)\\>")
3977 '(1 'org-special-keyword t))
3978 '("^#.*" (0 'font-lock-comment-face t))
3980 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
3981 ;; Now set the full font-lock-keywords
3982 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
3983 (org-set-local 'font-lock-defaults
3984 '(org-font-lock-keywords t nil nil backward-paragraph))
3985 (kill-local-variable 'font-lock-keywords) nil))
3987 (defvar org-m nil)
3988 (defvar org-l nil)
3989 (defvar org-f nil)
3990 (defun org-get-level-face (n)
3991 "Get the right face for match N in font-lock matching of healdines."
3992 (setq org-l (- (match-end 2) (match-beginning 1) 1))
3993 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
3994 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
3995 (cond
3996 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
3997 ((eq n 2) org-f)
3998 (t (if org-level-color-stars-only nil org-f))))
4000 (defun org-get-todo-face (kwd)
4001 "Get the right face for a TODO keyword KWD.
4002 If KWD is a number, get the corresponding match group."
4003 (if (numberp kwd) (setq kwd (match-string kwd)))
4004 (or (cdr (assoc kwd org-todo-keyword-faces))
4005 (and (member kwd org-done-keywords) 'org-done)
4006 'org-todo))
4008 (defun org-font-lock-add-tag-faces (limit)
4009 "Add the special tag faces."
4010 (when (and org-tag-faces org-tags-special-faces-re)
4011 (while (re-search-forward org-tags-special-faces-re limit t)
4012 (add-text-properties (match-beginning 1) (match-end 1)
4013 (list 'face (org-get-tag-face 1)
4014 'font-lock-fontified t))
4015 (backward-char 1))))
4017 (defun org-get-tag-face (kwd)
4018 "Get the right face for a TODO keyword KWD.
4019 If KWD is a number, get the corresponding match group."
4020 (if (numberp kwd) (setq kwd (match-string kwd)))
4021 (or (cdr (assoc kwd org-tag-faces))
4022 'org-tag))
4024 (defun org-unfontify-region (beg end &optional maybe_loudly)
4025 "Remove fontification and activation overlays from links."
4026 (font-lock-default-unfontify-region beg end)
4027 (let* ((buffer-undo-list t)
4028 (inhibit-read-only t) (inhibit-point-motion-hooks t)
4029 (inhibit-modification-hooks t)
4030 deactivate-mark buffer-file-name buffer-file-truename)
4031 (remove-text-properties beg end
4032 '(mouse-face t keymap t org-linked-text t
4033 invisible t intangible t))))
4035 ;;;; Visibility cycling, including org-goto and indirect buffer
4037 ;;; Cycling
4039 (defvar org-cycle-global-status nil)
4040 (make-variable-buffer-local 'org-cycle-global-status)
4041 (defvar org-cycle-subtree-status nil)
4042 (make-variable-buffer-local 'org-cycle-subtree-status)
4044 ;;;###autoload
4045 (defun org-cycle (&optional arg)
4046 "Visibility cycling for Org-mode.
4048 - When this function is called with a prefix argument, rotate the entire
4049 buffer through 3 states (global cycling)
4050 1. OVERVIEW: Show only top-level headlines.
4051 2. CONTENTS: Show all headlines of all levels, but no body text.
4052 3. SHOW ALL: Show everything.
4053 When called with two C-u C-u prefixes, switch to the startup visibility,
4054 determined by the variable `org-startup-folded', and by any VISIBILITY
4055 properties in the buffer.
4056 When called with three C-u C-u C-u prefixed, show the entire buffer,
4057 including drawers.
4059 - When point is at the beginning of a headline, rotate the subtree started
4060 by this line through 3 different states (local cycling)
4061 1. FOLDED: Only the main headline is shown.
4062 2. CHILDREN: The main headline and the direct children are shown.
4063 From this state, you can move to one of the children
4064 and zoom in further.
4065 3. SUBTREE: Show the entire subtree, including body text.
4067 - When there is a numeric prefix, go up to a heading with level ARG, do
4068 a `show-subtree' and return to the previous cursor position. If ARG
4069 is negative, go up that many levels.
4071 - When point is not at the beginning of a headline, execute the global
4072 binding for TAB, which is re-indenting the line. See the option
4073 `org-cycle-emulate-tab' for details.
4075 - Special case: if point is at the beginning of the buffer and there is
4076 no headline in line 1, this function will act as if called with prefix arg.
4077 But only if also the variable `org-cycle-global-at-bob' is t."
4078 (interactive "P")
4079 (org-load-modules-maybe)
4080 (let* ((outline-regexp
4081 (if (and (org-mode-p) org-cycle-include-plain-lists)
4082 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
4083 outline-regexp))
4084 (bob-special (and org-cycle-global-at-bob (bobp)
4085 (not (looking-at outline-regexp))))
4086 (org-cycle-hook
4087 (if bob-special
4088 (delq 'org-optimize-window-after-visibility-change
4089 (copy-sequence org-cycle-hook))
4090 org-cycle-hook))
4091 (pos (point)))
4093 (if (or bob-special (equal arg '(4)))
4094 ;; special case: use global cycling
4095 (setq arg t))
4097 (cond
4099 ((equal arg '(16))
4100 (org-set-startup-visibility)
4101 (message "Startup visibility, plus VISIBILITY properties"))
4103 ((equal arg '(64))
4104 (show-all)
4105 (message "Entire buffer visible, including drawers"))
4107 ((org-at-table-p 'any)
4108 ;; Enter the table or move to the next field in the table
4109 (or (org-table-recognize-table.el)
4110 (progn
4111 (if arg (org-table-edit-field t)
4112 (org-table-justify-field-maybe)
4113 (call-interactively 'org-table-next-field)))))
4115 ((eq arg t) ;; Global cycling
4117 (cond
4118 ((and (eq last-command this-command)
4119 (eq org-cycle-global-status 'overview))
4120 ;; We just created the overview - now do table of contents
4121 ;; This can be slow in very large buffers, so indicate action
4122 (message "CONTENTS...")
4123 (org-content)
4124 (message "CONTENTS...done")
4125 (setq org-cycle-global-status 'contents)
4126 (run-hook-with-args 'org-cycle-hook 'contents))
4128 ((and (eq last-command this-command)
4129 (eq org-cycle-global-status 'contents))
4130 ;; We just showed the table of contents - now show everything
4131 (show-all)
4132 (message "SHOW ALL")
4133 (setq org-cycle-global-status 'all)
4134 (run-hook-with-args 'org-cycle-hook 'all))
4137 ;; Default action: go to overview
4138 (org-overview)
4139 (message "OVERVIEW")
4140 (setq org-cycle-global-status 'overview)
4141 (run-hook-with-args 'org-cycle-hook 'overview))))
4143 ((and org-drawers org-drawer-regexp
4144 (save-excursion
4145 (beginning-of-line 1)
4146 (looking-at org-drawer-regexp)))
4147 ;; Toggle block visibility
4148 (org-flag-drawer
4149 (not (get-char-property (match-end 0) 'invisible))))
4151 ((integerp arg)
4152 ;; Show-subtree, ARG levels up from here.
4153 (save-excursion
4154 (org-back-to-heading)
4155 (outline-up-heading (if (< arg 0) (- arg)
4156 (- (funcall outline-level) arg)))
4157 (org-show-subtree)))
4159 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4160 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4161 ;; At a heading: rotate between three different views
4162 (org-back-to-heading)
4163 (let ((goal-column 0) eoh eol eos)
4164 ;; First, some boundaries
4165 (save-excursion
4166 (org-back-to-heading)
4167 (save-excursion
4168 (beginning-of-line 2)
4169 (while (and (not (eobp)) ;; this is like `next-line'
4170 (get-char-property (1- (point)) 'invisible))
4171 (beginning-of-line 2)) (setq eol (point)))
4172 (outline-end-of-heading) (setq eoh (point))
4173 (org-end-of-subtree t)
4174 (unless (eobp)
4175 (skip-chars-forward " \t\n")
4176 (beginning-of-line 1) ; in case this is an item
4178 (setq eos (1- (point))))
4179 ;; Find out what to do next and set `this-command'
4180 (cond
4181 ((= eos eoh)
4182 ;; Nothing is hidden behind this heading
4183 (message "EMPTY ENTRY")
4184 (setq org-cycle-subtree-status nil)
4185 (save-excursion
4186 (goto-char eos)
4187 (outline-next-heading)
4188 (if (org-invisible-p) (org-flag-heading nil))))
4189 ((or (>= eol eos)
4190 (not (string-match "\\S-" (buffer-substring eol eos))))
4191 ;; Entire subtree is hidden in one line: open it
4192 (org-show-entry)
4193 (show-children)
4194 (message "CHILDREN")
4195 (save-excursion
4196 (goto-char eos)
4197 (outline-next-heading)
4198 (if (org-invisible-p) (org-flag-heading nil)))
4199 (setq org-cycle-subtree-status 'children)
4200 (run-hook-with-args 'org-cycle-hook 'children))
4201 ((and (eq last-command this-command)
4202 (eq org-cycle-subtree-status 'children))
4203 ;; We just showed the children, now show everything.
4204 (org-show-subtree)
4205 (message "SUBTREE")
4206 (setq org-cycle-subtree-status 'subtree)
4207 (run-hook-with-args 'org-cycle-hook 'subtree))
4209 ;; Default action: hide the subtree.
4210 (hide-subtree)
4211 (message "FOLDED")
4212 (setq org-cycle-subtree-status 'folded)
4213 (run-hook-with-args 'org-cycle-hook 'folded)))))
4215 ;; TAB emulation and template completion
4216 (buffer-read-only (org-back-to-heading))
4218 ((org-try-structure-completion))
4220 ((org-try-cdlatex-tab))
4222 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4223 (or (not (bolp))
4224 (not (looking-at outline-regexp))))
4225 (call-interactively (global-key-binding "\t")))
4227 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4228 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4229 (or (and (eq org-cycle-emulate-tab 'white)
4230 (= (match-end 0) (point-at-eol)))
4231 (and (eq org-cycle-emulate-tab 'whitestart)
4232 (>= (match-end 0) pos))))
4234 (eq org-cycle-emulate-tab t))
4235 (call-interactively (global-key-binding "\t")))
4237 (t (save-excursion
4238 (org-back-to-heading)
4239 (org-cycle))))))
4241 ;;;###autoload
4242 (defun org-global-cycle (&optional arg)
4243 "Cycle the global visibility. For details see `org-cycle'.
4244 With C-u prefix arg, switch to startup visibility.
4245 With a numeric prefix, show all headlines up to that level."
4246 (interactive "P")
4247 (let ((org-cycle-include-plain-lists
4248 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4249 (cond
4250 ((integerp arg)
4251 (show-all)
4252 (hide-sublevels arg)
4253 (setq org-cycle-global-status 'contents))
4254 ((equal arg '(4))
4255 (org-set-startup-visibility)
4256 (message "Startup visibility, plus VISIBILITY properties."))
4258 (org-cycle '(4))))))
4260 (defun org-set-startup-visibility ()
4261 "Set the visibility required by startup options and properties."
4262 (cond
4263 ((eq org-startup-folded t)
4264 (org-cycle '(4)))
4265 ((eq org-startup-folded 'content)
4266 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4267 (org-cycle '(4)) (org-cycle '(4)))))
4268 (org-set-visibility-according-to-property 'no-cleanup)
4269 (org-cycle-hide-archived-subtrees 'all)
4270 (org-cycle-hide-drawers 'all)
4271 (org-cycle-show-empty-lines 'all))
4273 (defun org-set-visibility-according-to-property (&optional no-cleanup)
4274 "Switch subtree visibilities according to :VISIBILITY: property."
4275 (interactive)
4276 (let (state)
4277 (save-excursion
4278 (goto-char (point-min))
4279 (while (re-search-forward
4280 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
4281 nil t)
4282 (setq state (match-string 1))
4283 (save-excursion
4284 (org-back-to-heading t)
4285 (hide-subtree)
4286 (org-reveal)
4287 (cond
4288 ((equal state '("fold" "folded"))
4289 (hide-subtree))
4290 ((equal state "children")
4291 (org-show-hidden-entry)
4292 (show-children))
4293 ((equal state "content")
4294 (save-excursion
4295 (save-restriction
4296 (org-narrow-to-subtree)
4297 (org-content))))
4298 ((member state '("all" "showall"))
4299 (show-subtree)))))
4300 (unless no-cleanup
4301 (org-cycle-hide-archived-subtrees 'all)
4302 (org-cycle-hide-drawers 'all)
4303 (org-cycle-show-empty-lines 'all)))))
4305 (defun org-overview ()
4306 "Switch to overview mode, shoing only top-level headlines.
4307 Really, this shows all headlines with level equal or greater than the level
4308 of the first headline in the buffer. This is important, because if the
4309 first headline is not level one, then (hide-sublevels 1) gives confusing
4310 results."
4311 (interactive)
4312 (let ((level (save-excursion
4313 (goto-char (point-min))
4314 (if (re-search-forward (concat "^" outline-regexp) nil t)
4315 (progn
4316 (goto-char (match-beginning 0))
4317 (funcall outline-level))))))
4318 (and level (hide-sublevels level))))
4320 (defun org-content (&optional arg)
4321 "Show all headlines in the buffer, like a table of contents.
4322 With numerical argument N, show content up to level N."
4323 (interactive "P")
4324 (save-excursion
4325 ;; Visit all headings and show their offspring
4326 (and (integerp arg) (org-overview))
4327 (goto-char (point-max))
4328 (catch 'exit
4329 (while (and (progn (condition-case nil
4330 (outline-previous-visible-heading 1)
4331 (error (goto-char (point-min))))
4333 (looking-at outline-regexp))
4334 (if (integerp arg)
4335 (show-children (1- arg))
4336 (show-branches))
4337 (if (bobp) (throw 'exit nil))))))
4340 (defun org-optimize-window-after-visibility-change (state)
4341 "Adjust the window after a change in outline visibility.
4342 This function is the default value of the hook `org-cycle-hook'."
4343 (when (get-buffer-window (current-buffer))
4344 (cond
4345 ; ((eq state 'overview) (org-first-headline-recenter 1))
4346 ; ((eq state 'overview) (org-beginning-of-line))
4347 ((eq state 'content) nil)
4348 ((eq state 'all) nil)
4349 ((eq state 'folded) nil)
4350 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4351 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4353 (defun org-compact-display-after-subtree-move ()
4354 (let (beg end)
4355 (save-excursion
4356 (if (org-up-heading-safe)
4357 (progn
4358 (hide-subtree)
4359 (show-entry)
4360 (show-children)
4361 (org-cycle-show-empty-lines 'children)
4362 (org-cycle-hide-drawers 'children))
4363 (org-overview)))))
4365 (defun org-cycle-show-empty-lines (state)
4366 "Show empty lines above all visible headlines.
4367 The region to be covered depends on STATE when called through
4368 `org-cycle-hook'. Lisp program can use t for STATE to get the
4369 entire buffer covered. Note that an empty line is only shown if there
4370 are at least `org-cycle-separator-lines' empty lines before the headeline."
4371 (when (> org-cycle-separator-lines 0)
4372 (save-excursion
4373 (let* ((n org-cycle-separator-lines)
4374 (re (cond
4375 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
4376 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
4377 (t (let ((ns (number-to-string (- n 2))))
4378 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
4379 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
4380 beg end)
4381 (cond
4382 ((memq state '(overview contents t))
4383 (setq beg (point-min) end (point-max)))
4384 ((memq state '(children folded))
4385 (setq beg (point) end (progn (org-end-of-subtree t t)
4386 (beginning-of-line 2)
4387 (point)))))
4388 (when beg
4389 (goto-char beg)
4390 (while (re-search-forward re end t)
4391 (if (not (get-char-property (match-end 1) 'invisible))
4392 (outline-flag-region
4393 (match-beginning 1) (match-end 1) nil)))))))
4394 ;; Never hide empty lines at the end of the file.
4395 (save-excursion
4396 (goto-char (point-max))
4397 (outline-previous-heading)
4398 (outline-end-of-heading)
4399 (if (and (looking-at "[ \t\n]+")
4400 (= (match-end 0) (point-max)))
4401 (outline-flag-region (point) (match-end 0) nil))))
4403 (defun org-show-empty-lines-in-parent ()
4404 "Move to the parent and re-show empty lines before visible headlines."
4405 (save-excursion
4406 (let ((context (if (org-up-heading-safe) 'children 'overview)))
4407 (org-cycle-show-empty-lines context))))
4409 (defun org-cycle-hide-drawers (state)
4410 "Re-hide all drawers after a visibility state change."
4411 (when (and (org-mode-p)
4412 (not (memq state '(overview folded))))
4413 (save-excursion
4414 (let* ((globalp (memq state '(contents all)))
4415 (beg (if globalp (point-min) (point)))
4416 (end (if globalp (point-max) (org-end-of-subtree t))))
4417 (goto-char beg)
4418 (while (re-search-forward org-drawer-regexp end t)
4419 (org-flag-drawer t))))))
4421 (defun org-flag-drawer (flag)
4422 (save-excursion
4423 (beginning-of-line 1)
4424 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
4425 (let ((b (match-end 0))
4426 (outline-regexp org-outline-regexp))
4427 (if (re-search-forward
4428 "^[ \t]*:END:"
4429 (save-excursion (outline-next-heading) (point)) t)
4430 (outline-flag-region b (point-at-eol) flag)
4431 (error ":END: line missing"))))))
4433 (defun org-subtree-end-visible-p ()
4434 "Is the end of the current subtree visible?"
4435 (pos-visible-in-window-p
4436 (save-excursion (org-end-of-subtree t) (point))))
4438 (defun org-first-headline-recenter (&optional N)
4439 "Move cursor to the first headline and recenter the headline.
4440 Optional argument N means, put the headline into the Nth line of the window."
4441 (goto-char (point-min))
4442 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4443 (beginning-of-line)
4444 (recenter (prefix-numeric-value N))))
4446 ;;; Org-goto
4448 (defvar org-goto-window-configuration nil)
4449 (defvar org-goto-marker nil)
4450 (defvar org-goto-map
4451 (let ((map (make-sparse-keymap)))
4452 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
4453 (while (setq cmd (pop cmds))
4454 (substitute-key-definition cmd cmd map global-map)))
4455 (suppress-keymap map)
4456 (org-defkey map "\C-m" 'org-goto-ret)
4457 (org-defkey map [(return)] 'org-goto-ret)
4458 (org-defkey map [(left)] 'org-goto-left)
4459 (org-defkey map [(right)] 'org-goto-right)
4460 (org-defkey map [(control ?g)] 'org-goto-quit)
4461 (org-defkey map "\C-i" 'org-cycle)
4462 (org-defkey map [(tab)] 'org-cycle)
4463 (org-defkey map [(down)] 'outline-next-visible-heading)
4464 (org-defkey map [(up)] 'outline-previous-visible-heading)
4465 (if org-goto-auto-isearch
4466 (if (fboundp 'define-key-after)
4467 (define-key-after map [t] 'org-goto-local-auto-isearch)
4468 nil)
4469 (org-defkey map "q" 'org-goto-quit)
4470 (org-defkey map "n" 'outline-next-visible-heading)
4471 (org-defkey map "p" 'outline-previous-visible-heading)
4472 (org-defkey map "f" 'outline-forward-same-level)
4473 (org-defkey map "b" 'outline-backward-same-level)
4474 (org-defkey map "u" 'outline-up-heading))
4475 (org-defkey map "/" 'org-occur)
4476 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4477 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4478 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
4479 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
4480 (org-defkey map "\C-c\C-u" 'outline-up-heading)
4481 map))
4483 (defconst org-goto-help
4484 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4485 RET=jump to location [Q]uit and return to previous location
4486 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4488 (defvar org-goto-start-pos) ; dynamically scoped parameter
4490 ;; FIXME: Docstring doe not mention both interfaces
4491 (defun org-goto (&optional alternative-interface)
4492 "Look up a different location in the current file, keeping current visibility.
4494 When you want look-up or go to a different location in a document, the
4495 fastest way is often to fold the entire buffer and then dive into the tree.
4496 This method has the disadvantage, that the previous location will be folded,
4497 which may not be what you want.
4499 This command works around this by showing a copy of the current buffer
4500 in an indirect buffer, in overview mode. You can dive into the tree in
4501 that copy, use org-occur and incremental search to find a location.
4502 When pressing RET or `Q', the command returns to the original buffer in
4503 which the visibility is still unchanged. After RET is will also jump to
4504 the location selected in the indirect buffer and expose the
4505 the headline hierarchy above."
4506 (interactive "P")
4507 (let* ((org-refile-targets '((nil . (:maxlevel . 10))))
4508 (org-refile-use-outline-path t)
4509 (interface
4510 (if (not alternative-interface)
4511 org-goto-interface
4512 (if (eq org-goto-interface 'outline)
4513 'outline-path-completion
4514 'outline)))
4515 (org-goto-start-pos (point))
4516 (selected-point
4517 (if (eq interface 'outline)
4518 (car (org-get-location (current-buffer) org-goto-help))
4519 (nth 3 (org-refile-get-location "Goto: ")))))
4520 (if selected-point
4521 (progn
4522 (org-mark-ring-push org-goto-start-pos)
4523 (goto-char selected-point)
4524 (if (or (org-invisible-p) (org-invisible-p2))
4525 (org-show-context 'org-goto)))
4526 (message "Quit"))))
4528 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
4529 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
4530 (defvar org-goto-local-auto-isearch-map) ; defined below
4532 (defun org-get-location (buf help)
4533 "Let the user select a location in the Org-mode buffer BUF.
4534 This function uses a recursive edit. It returns the selected position
4535 or nil."
4536 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
4537 (isearch-hide-immediately nil)
4538 (isearch-search-fun-function
4539 (lambda () 'org-goto-local-search-headings))
4540 (org-goto-selected-point org-goto-exit-command))
4541 (save-excursion
4542 (save-window-excursion
4543 (delete-other-windows)
4544 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
4545 (switch-to-buffer
4546 (condition-case nil
4547 (make-indirect-buffer (current-buffer) "*org-goto*")
4548 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
4549 (with-output-to-temp-buffer "*Help*"
4550 (princ help))
4551 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
4552 (setq buffer-read-only nil)
4553 (let ((org-startup-truncated t)
4554 (org-startup-folded nil)
4555 (org-startup-align-all-tables nil))
4556 (org-mode)
4557 (org-overview))
4558 (setq buffer-read-only t)
4559 (if (and (boundp 'org-goto-start-pos)
4560 (integer-or-marker-p org-goto-start-pos))
4561 (let ((org-show-hierarchy-above t)
4562 (org-show-siblings t)
4563 (org-show-following-heading t))
4564 (goto-char org-goto-start-pos)
4565 (and (org-invisible-p) (org-show-context)))
4566 (goto-char (point-min)))
4567 (org-beginning-of-line)
4568 (message "Select location and press RET")
4569 (use-local-map org-goto-map)
4570 (recursive-edit)
4572 (kill-buffer "*org-goto*")
4573 (cons org-goto-selected-point org-goto-exit-command)))
4575 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
4576 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
4577 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
4578 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
4580 (defun org-goto-local-search-headings (string bound noerror)
4581 "Search and make sure that any matches are in headlines."
4582 (catch 'return
4583 (while (if isearch-forward
4584 (search-forward string bound noerror)
4585 (search-backward string bound noerror))
4586 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
4587 (and (member :headline context)
4588 (not (member :tags context))))
4589 (throw 'return (point))))))
4591 (defun org-goto-local-auto-isearch ()
4592 "Start isearch."
4593 (interactive)
4594 (goto-char (point-min))
4595 (let ((keys (this-command-keys)))
4596 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
4597 (isearch-mode t)
4598 (isearch-process-search-char (string-to-char keys)))))
4600 (defun org-goto-ret (&optional arg)
4601 "Finish `org-goto' by going to the new location."
4602 (interactive "P")
4603 (setq org-goto-selected-point (point)
4604 org-goto-exit-command 'return)
4605 (throw 'exit nil))
4607 (defun org-goto-left ()
4608 "Finish `org-goto' by going to the new location."
4609 (interactive)
4610 (if (org-on-heading-p)
4611 (progn
4612 (beginning-of-line 1)
4613 (setq org-goto-selected-point (point)
4614 org-goto-exit-command 'left)
4615 (throw 'exit nil))
4616 (error "Not on a heading")))
4618 (defun org-goto-right ()
4619 "Finish `org-goto' by going to the new location."
4620 (interactive)
4621 (if (org-on-heading-p)
4622 (progn
4623 (setq org-goto-selected-point (point)
4624 org-goto-exit-command 'right)
4625 (throw 'exit nil))
4626 (error "Not on a heading")))
4628 (defun org-goto-quit ()
4629 "Finish `org-goto' without cursor motion."
4630 (interactive)
4631 (setq org-goto-selected-point nil)
4632 (setq org-goto-exit-command 'quit)
4633 (throw 'exit nil))
4635 ;;; Indirect buffer display of subtrees
4637 (defvar org-indirect-dedicated-frame nil
4638 "This is the frame being used for indirect tree display.")
4639 (defvar org-last-indirect-buffer nil)
4641 (defun org-tree-to-indirect-buffer (&optional arg)
4642 "Create indirect buffer and narrow it to current subtree.
4643 With numerical prefix ARG, go up to this level and then take that tree.
4644 If ARG is negative, go up that many levels.
4645 If `org-indirect-buffer-display' is not `new-frame', the command removes the
4646 indirect buffer previously made with this command, to avoid proliferation of
4647 indirect buffers. However, when you call the command with a `C-u' prefix, or
4648 when `org-indirect-buffer-display' is `new-frame', the last buffer
4649 is kept so that you can work with several indirect buffers at the same time.
4650 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
4651 requests that a new frame be made for the new buffer, so that the dedicated
4652 frame is not changed."
4653 (interactive "P")
4654 (let ((cbuf (current-buffer))
4655 (cwin (selected-window))
4656 (pos (point))
4657 beg end level heading ibuf)
4658 (save-excursion
4659 (org-back-to-heading t)
4660 (when (numberp arg)
4661 (setq level (org-outline-level))
4662 (if (< arg 0) (setq arg (+ level arg)))
4663 (while (> (setq level (org-outline-level)) arg)
4664 (outline-up-heading 1 t)))
4665 (setq beg (point)
4666 heading (org-get-heading))
4667 (org-end-of-subtree t) (setq end (point)))
4668 (if (and (buffer-live-p org-last-indirect-buffer)
4669 (not (eq org-indirect-buffer-display 'new-frame))
4670 (not arg))
4671 (kill-buffer org-last-indirect-buffer))
4672 (setq ibuf (org-get-indirect-buffer cbuf)
4673 org-last-indirect-buffer ibuf)
4674 (cond
4675 ((or (eq org-indirect-buffer-display 'new-frame)
4676 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
4677 (select-frame (make-frame))
4678 (delete-other-windows)
4679 (switch-to-buffer ibuf)
4680 (org-set-frame-title heading))
4681 ((eq org-indirect-buffer-display 'dedicated-frame)
4682 (raise-frame
4683 (select-frame (or (and org-indirect-dedicated-frame
4684 (frame-live-p org-indirect-dedicated-frame)
4685 org-indirect-dedicated-frame)
4686 (setq org-indirect-dedicated-frame (make-frame)))))
4687 (delete-other-windows)
4688 (switch-to-buffer ibuf)
4689 (org-set-frame-title (concat "Indirect: " heading)))
4690 ((eq org-indirect-buffer-display 'current-window)
4691 (switch-to-buffer ibuf))
4692 ((eq org-indirect-buffer-display 'other-window)
4693 (pop-to-buffer ibuf))
4694 (t (error "Invalid value.")))
4695 (if (featurep 'xemacs)
4696 (save-excursion (org-mode) (turn-on-font-lock)))
4697 (narrow-to-region beg end)
4698 (show-all)
4699 (goto-char pos)
4700 (and (window-live-p cwin) (select-window cwin))))
4702 (defun org-get-indirect-buffer (&optional buffer)
4703 (setq buffer (or buffer (current-buffer)))
4704 (let ((n 1) (base (buffer-name buffer)) bname)
4705 (while (buffer-live-p
4706 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
4707 (setq n (1+ n)))
4708 (condition-case nil
4709 (make-indirect-buffer buffer bname 'clone)
4710 (error (make-indirect-buffer buffer bname)))))
4712 (defun org-set-frame-title (title)
4713 "Set the title of the current frame to the string TITLE."
4714 ;; FIXME: how to name a single frame in XEmacs???
4715 (unless (featurep 'xemacs)
4716 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
4718 ;;;; Structure editing
4720 ;;; Inserting headlines
4722 (defun org-insert-heading (&optional force-heading)
4723 "Insert a new heading or item with same depth at point.
4724 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
4725 If point is at the beginning of a headline, insert a sibling before the
4726 current headline. If point is not at the beginning, do not split the line,
4727 but create the new headline after the current line."
4728 (interactive "P")
4729 (if (= (buffer-size) 0)
4730 (insert "\n* ")
4731 (when (or force-heading (not (org-insert-item)))
4732 (let* ((head (save-excursion
4733 (condition-case nil
4734 (progn
4735 (org-back-to-heading)
4736 (match-string 0))
4737 (error "*"))))
4738 (blank (cdr (assq 'heading org-blank-before-new-entry)))
4739 pos hide-previous previous-pos)
4740 (cond
4741 ((and (org-on-heading-p) (bolp)
4742 (or (bobp)
4743 (save-excursion (backward-char 1) (not (org-invisible-p)))))
4744 ;; insert before the current line
4745 (open-line (if blank 2 1)))
4746 ((and (bolp)
4747 (or (bobp)
4748 (save-excursion
4749 (backward-char 1) (not (org-invisible-p)))))
4750 ;; insert right here
4751 nil)
4753 ;; somewhere in the line
4754 (save-excursion
4755 (setq previous-pos (point-at-bol))
4756 (end-of-line)
4757 (setq hide-previous (org-invisible-p)))
4758 (and org-insert-heading-respect-content (org-show-subtree))
4759 (let ((split
4760 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
4761 (save-excursion
4762 (let ((p (point)))
4763 (goto-char (point-at-bol))
4764 (and (looking-at org-complex-heading-regexp)
4765 (> p (match-beginning 4)))))))
4766 tags pos)
4767 (cond
4768 (org-insert-heading-respect-content
4769 (org-end-of-subtree nil t)
4770 (or (bolp) (newline))
4771 (open-line 1))
4772 ((org-on-heading-p)
4773 (when hide-previous
4774 (show-children)
4775 (org-show-entry))
4776 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4777 (setq tags (and (match-end 2) (match-string 2)))
4778 (and (match-end 1)
4779 (delete-region (match-beginning 1) (match-end 1)))
4780 (setq pos (point-at-bol))
4781 (or split (end-of-line 1))
4782 (delete-horizontal-space)
4783 (newline (if blank 2 1))
4784 (when tags
4785 (save-excursion
4786 (goto-char pos)
4787 (end-of-line 1)
4788 (insert " " tags)
4789 (org-set-tags nil 'align))))
4791 (or split (end-of-line 1))
4792 (newline (if blank 2 1)))))))
4793 (insert head) (just-one-space)
4794 (setq pos (point))
4795 (end-of-line 1)
4796 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
4797 (when (and org-insert-heading-respect-content hide-previous)
4798 (save-excursion
4799 (goto-char previous-pos)
4800 (hide-subtree)))
4801 (run-hooks 'org-insert-heading-hook)))))
4803 (defun org-get-heading (&optional no-tags)
4804 "Return the heading of the current entry, without the stars."
4805 (save-excursion
4806 (org-back-to-heading t)
4807 (if (looking-at
4808 (if no-tags
4809 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
4810 "\\*+[ \t]+\\([^\r\n]*\\)"))
4811 (match-string 1) "")))
4813 (defun org-insert-heading-after-current ()
4814 "Insert a new heading with same level as current, after current subtree."
4815 (interactive)
4816 (org-back-to-heading)
4817 (org-insert-heading)
4818 (org-move-subtree-down)
4819 (end-of-line 1))
4821 (defun org-insert-heading-respect-content ()
4822 (interactive)
4823 (let ((org-insert-heading-respect-content t))
4824 (org-insert-heading t)))
4826 (defun org-insert-todo-heading-respect-content (&optional force-state)
4827 (interactive "P")
4828 (let ((org-insert-heading-respect-content t))
4829 (org-insert-todo-heading force-state t)))
4831 (defun org-insert-todo-heading (arg &optional force-heading)
4832 "Insert a new heading with the same level and TODO state as current heading.
4833 If the heading has no TODO state, or if the state is DONE, use the first
4834 state (TODO by default). Also with prefix arg, force first state."
4835 (interactive "P")
4836 (when (or force-heading (not (org-insert-item 'checkbox)))
4837 (org-insert-heading force-heading)
4838 (save-excursion
4839 (org-back-to-heading)
4840 (outline-previous-heading)
4841 (looking-at org-todo-line-regexp))
4842 (if (or arg
4843 (not (match-beginning 2))
4844 (member (match-string 2) org-done-keywords))
4845 (insert (car org-todo-keywords-1) " ")
4846 (insert (match-string 2) " "))
4847 (when org-provide-todo-statistics
4848 (org-update-parent-todo-statistics))))
4850 (defun org-insert-subheading (arg)
4851 "Insert a new subheading and demote it.
4852 Works for outline headings and for plain lists alike."
4853 (interactive "P")
4854 (org-insert-heading arg)
4855 (cond
4856 ((org-on-heading-p) (org-do-demote))
4857 ((org-at-item-p) (org-indent-item 1))))
4859 (defun org-insert-todo-subheading (arg)
4860 "Insert a new subheading with TODO keyword or checkbox and demote it.
4861 Works for outline headings and for plain lists alike."
4862 (interactive "P")
4863 (org-insert-todo-heading arg)
4864 (cond
4865 ((org-on-heading-p) (org-do-demote))
4866 ((org-at-item-p) (org-indent-item 1))))
4868 ;;; Promotion and Demotion
4870 (defun org-promote-subtree ()
4871 "Promote the entire subtree.
4872 See also `org-promote'."
4873 (interactive)
4874 (save-excursion
4875 (org-map-tree 'org-promote))
4876 (org-fix-position-after-promote))
4878 (defun org-demote-subtree ()
4879 "Demote the entire subtree. See `org-demote'.
4880 See also `org-promote'."
4881 (interactive)
4882 (save-excursion
4883 (org-map-tree 'org-demote))
4884 (org-fix-position-after-promote))
4887 (defun org-do-promote ()
4888 "Promote the current heading higher up the tree.
4889 If the region is active in `transient-mark-mode', promote all headings
4890 in the region."
4891 (interactive)
4892 (save-excursion
4893 (if (org-region-active-p)
4894 (org-map-region 'org-promote (region-beginning) (region-end))
4895 (org-promote)))
4896 (org-fix-position-after-promote))
4898 (defun org-do-demote ()
4899 "Demote the current heading lower down the tree.
4900 If the region is active in `transient-mark-mode', demote all headings
4901 in the region."
4902 (interactive)
4903 (save-excursion
4904 (if (org-region-active-p)
4905 (org-map-region 'org-demote (region-beginning) (region-end))
4906 (org-demote)))
4907 (org-fix-position-after-promote))
4909 (defun org-fix-position-after-promote ()
4910 "Make sure that after pro/demotion cursor position is right."
4911 (let ((pos (point)))
4912 (when (save-excursion
4913 (beginning-of-line 1)
4914 (looking-at org-todo-line-regexp)
4915 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
4916 (cond ((eobp) (insert " "))
4917 ((eolp) (insert " "))
4918 ((equal (char-after) ?\ ) (forward-char 1))))))
4920 (defun org-reduced-level (l)
4921 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
4923 (defun org-get-valid-level (level &optional change)
4924 "Rectify a level change under the influence of `org-odd-levels-only'
4925 LEVEL is a current level, CHANGE is by how much the level should be
4926 modified. Even if CHANGE is nil, LEVEL may be returned modified because
4927 even level numbers will become the next higher odd number."
4928 (if org-odd-levels-only
4929 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
4930 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
4931 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
4932 (max 1 (+ level change))))
4934 (if (boundp 'define-obsolete-function-alias)
4935 (if (or (featurep 'xemacs) (< emacs-major-version 23))
4936 (define-obsolete-function-alias 'org-get-legal-level
4937 'org-get-valid-level)
4938 (define-obsolete-function-alias 'org-get-legal-level
4939 'org-get-valid-level "23.1")))
4941 (defun org-promote ()
4942 "Promote the current heading higher up the tree.
4943 If the region is active in `transient-mark-mode', promote all headings
4944 in the region."
4945 (org-back-to-heading t)
4946 (let* ((level (save-match-data (funcall outline-level)))
4947 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
4948 (diff (abs (- level (length up-head) -1))))
4949 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
4950 (replace-match up-head nil t)
4951 ;; Fixup tag positioning
4952 (and org-auto-align-tags (org-set-tags nil t))
4953 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
4955 (defun org-demote ()
4956 "Demote the current heading lower down the tree.
4957 If the region is active in `transient-mark-mode', demote all headings
4958 in the region."
4959 (org-back-to-heading t)
4960 (let* ((level (save-match-data (funcall outline-level)))
4961 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
4962 (diff (abs (- level (length down-head) -1))))
4963 (replace-match down-head nil t)
4964 ;; Fixup tag positioning
4965 (and org-auto-align-tags (org-set-tags nil t))
4966 (if org-adapt-indentation (org-fixup-indentation diff))))
4968 (defun org-map-tree (fun)
4969 "Call FUN for every heading underneath the current one."
4970 (org-back-to-heading)
4971 (let ((level (funcall outline-level)))
4972 (save-excursion
4973 (funcall fun)
4974 (while (and (progn
4975 (outline-next-heading)
4976 (> (funcall outline-level) level))
4977 (not (eobp)))
4978 (funcall fun)))))
4980 (defun org-map-region (fun beg end)
4981 "Call FUN for every heading between BEG and END."
4982 (let ((org-ignore-region t))
4983 (save-excursion
4984 (setq end (copy-marker end))
4985 (goto-char beg)
4986 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
4987 (< (point) end))
4988 (funcall fun))
4989 (while (and (progn
4990 (outline-next-heading)
4991 (< (point) end))
4992 (not (eobp)))
4993 (funcall fun)))))
4995 (defun org-fixup-indentation (diff)
4996 "Change the indentation in the current entry by DIFF
4997 However, if any line in the current entry has no indentation, or if it
4998 would end up with no indentation after the change, nothing at all is done."
4999 (save-excursion
5000 (let ((end (save-excursion (outline-next-heading)
5001 (point-marker)))
5002 (prohibit (if (> diff 0)
5003 "^\\S-"
5004 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
5005 col)
5006 (unless (save-excursion (end-of-line 1)
5007 (re-search-forward prohibit end t))
5008 (while (and (< (point) end)
5009 (re-search-forward "^[ \t]+" end t))
5010 (goto-char (match-end 0))
5011 (setq col (current-column))
5012 (if (< diff 0) (replace-match ""))
5013 (org-indent-to-column (+ diff col))))
5014 (move-marker end nil))))
5016 (defun org-convert-to-odd-levels ()
5017 "Convert an org-mode file with all levels allowed to one with odd levels.
5018 This will leave level 1 alone, convert level 2 to level 3, level 3 to
5019 level 5 etc."
5020 (interactive)
5021 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
5022 (let ((org-odd-levels-only nil) n)
5023 (save-excursion
5024 (goto-char (point-min))
5025 (while (re-search-forward "^\\*\\*+ " nil t)
5026 (setq n (- (length (match-string 0)) 2))
5027 (while (>= (setq n (1- n)) 0)
5028 (org-demote))
5029 (end-of-line 1))))))
5032 (defun org-convert-to-oddeven-levels ()
5033 "Convert an org-mode file with only odd levels to one with odd and even levels.
5034 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
5035 section with an even level, conversion would destroy the structure of the file. An error
5036 is signaled in this case."
5037 (interactive)
5038 (goto-char (point-min))
5039 ;; First check if there are no even levels
5040 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
5041 (org-show-context t)
5042 (error "Not all levels are odd in this file. Conversion not possible."))
5043 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
5044 (let ((org-odd-levels-only nil) n)
5045 (save-excursion
5046 (goto-char (point-min))
5047 (while (re-search-forward "^\\*\\*+ " nil t)
5048 (setq n (/ (1- (length (match-string 0))) 2))
5049 (while (>= (setq n (1- n)) 0)
5050 (org-promote))
5051 (end-of-line 1))))))
5053 (defun org-tr-level (n)
5054 "Make N odd if required."
5055 (if org-odd-levels-only (1+ (/ n 2)) n))
5057 ;;; Vertical tree motion, cutting and pasting of subtrees
5059 (defun org-move-subtree-up (&optional arg)
5060 "Move the current subtree up past ARG headlines of the same level."
5061 (interactive "p")
5062 (org-move-subtree-down (- (prefix-numeric-value arg))))
5064 (defun org-move-subtree-down (&optional arg)
5065 "Move the current subtree down past ARG headlines of the same level."
5066 (interactive "p")
5067 (setq arg (prefix-numeric-value arg))
5068 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
5069 'outline-get-last-sibling))
5070 (ins-point (make-marker))
5071 (cnt (abs arg))
5072 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
5073 ;; Select the tree
5074 (org-back-to-heading)
5075 (setq beg0 (point))
5076 (save-excursion
5077 (setq ne-beg (org-back-over-empty-lines))
5078 (setq beg (point)))
5079 (save-match-data
5080 (save-excursion (outline-end-of-heading)
5081 (setq folded (org-invisible-p)))
5082 (outline-end-of-subtree))
5083 (outline-next-heading)
5084 (setq ne-end (org-back-over-empty-lines))
5085 (setq end (point))
5086 (goto-char beg0)
5087 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
5088 ;; include less whitespace
5089 (save-excursion
5090 (goto-char beg)
5091 (forward-line (- ne-beg ne-end))
5092 (setq beg (point))))
5093 ;; Find insertion point, with error handling
5094 (while (> cnt 0)
5095 (or (and (funcall movfunc) (looking-at outline-regexp))
5096 (progn (goto-char beg0)
5097 (error "Cannot move past superior level or buffer limit")))
5098 (setq cnt (1- cnt)))
5099 (if (> arg 0)
5100 ;; Moving forward - still need to move over subtree
5101 (progn (org-end-of-subtree t t)
5102 (save-excursion
5103 (org-back-over-empty-lines)
5104 (or (bolp) (newline)))))
5105 (setq ne-ins (org-back-over-empty-lines))
5106 (move-marker ins-point (point))
5107 (setq txt (buffer-substring beg end))
5108 (org-save-markers-in-region beg end)
5109 (delete-region beg end)
5110 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
5111 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
5112 (let ((bbb (point)))
5113 (insert-before-markers txt)
5114 (org-reinstall-markers-in-region bbb)
5115 (move-marker ins-point bbb))
5116 (or (bolp) (insert "\n"))
5117 (setq ins-end (point))
5118 (goto-char ins-point)
5119 (org-skip-whitespace)
5120 (when (and (< arg 0)
5121 (org-first-sibling-p)
5122 (> ne-ins ne-beg))
5123 ;; Move whitespace back to beginning
5124 (save-excursion
5125 (goto-char ins-end)
5126 (let ((kill-whole-line t))
5127 (kill-line (- ne-ins ne-beg)) (point)))
5128 (insert (make-string (- ne-ins ne-beg) ?\n)))
5129 (move-marker ins-point nil)
5130 (org-compact-display-after-subtree-move)
5131 (org-show-empty-lines-in-parent)
5132 (unless folded
5133 (org-show-entry)
5134 (show-children)
5135 (org-cycle-hide-drawers 'children))))
5137 (defvar org-subtree-clip ""
5138 "Clipboard for cut and paste of subtrees.
5139 This is actually only a copy of the kill, because we use the normal kill
5140 ring. We need it to check if the kill was created by `org-copy-subtree'.")
5142 (defvar org-subtree-clip-folded nil
5143 "Was the last copied subtree folded?
5144 This is used to fold the tree back after pasting.")
5146 (defun org-cut-subtree (&optional n)
5147 "Cut the current subtree into the clipboard.
5148 With prefix arg N, cut this many sequential subtrees.
5149 This is a short-hand for marking the subtree and then cutting it."
5150 (interactive "p")
5151 (org-copy-subtree n 'cut))
5153 (defun org-copy-subtree (&optional n cut force-store-markers)
5154 "Cut the current subtree into the clipboard.
5155 With prefix arg N, cut this many sequential subtrees.
5156 This is a short-hand for marking the subtree and then copying it.
5157 If CUT is non-nil, actually cut the subtree.
5158 If FORCE-STORE-MARKERS is non-nil, store the relative locations
5159 of some markers in the region, even if CUT is non-nil. This is
5160 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
5161 (interactive "p")
5162 (let (beg end folded (beg0 (point)))
5163 (if (interactive-p)
5164 (org-back-to-heading nil) ; take what looks like a subtree
5165 (org-back-to-heading t)) ; take what is really there
5166 (org-back-over-empty-lines)
5167 (setq beg (point))
5168 (skip-chars-forward " \t\r\n")
5169 (save-match-data
5170 (save-excursion (outline-end-of-heading)
5171 (setq folded (org-invisible-p)))
5172 (condition-case nil
5173 (outline-forward-same-level (1- n))
5174 (error nil))
5175 (org-end-of-subtree t t))
5176 (org-back-over-empty-lines)
5177 (setq end (point))
5178 (goto-char beg0)
5179 (when (> end beg)
5180 (setq org-subtree-clip-folded folded)
5181 (when (or cut force-store-markers)
5182 (org-save-markers-in-region beg end))
5183 (if cut (kill-region beg end) (copy-region-as-kill beg end))
5184 (setq org-subtree-clip (current-kill 0))
5185 (message "%s: Subtree(s) with %d characters"
5186 (if cut "Cut" "Copied")
5187 (length org-subtree-clip)))))
5189 (defun org-paste-subtree (&optional level tree for-yank)
5190 "Paste the clipboard as a subtree, with modification of headline level.
5191 The entire subtree is promoted or demoted in order to match a new headline
5192 level.
5194 If the cursor is at the beginning of a headline, the same level as
5195 that headline is used to paste the tree
5197 If not, the new level is derived from the *visible* headings
5198 before and after the insertion point, and taken to be the inferior headline
5199 level of the two. So if the previous visible heading is level 3 and the
5200 next is level 4 (or vice versa), level 4 will be used for insertion.
5201 This makes sure that the subtree remains an independent subtree and does
5202 not swallow low level entries.
5204 You can also force a different level, either by using a numeric prefix
5205 argument, or by inserting the heading marker by hand. For example, if the
5206 cursor is after \"*****\", then the tree will be shifted to level 5.
5208 If optional TREE is given, use this text instead of the kill ring.
5210 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
5211 move back over whitespace before inserting, and move point to the end of
5212 the inserted text when done."
5213 (interactive "P")
5214 (unless (org-kill-is-subtree-p tree)
5215 (error "%s"
5216 (substitute-command-keys
5217 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
5218 (let* ((visp (not (org-invisible-p)))
5219 (txt (or tree (and kill-ring (current-kill 0))))
5220 (^re (concat "^\\(" outline-regexp "\\)"))
5221 (re (concat "\\(" outline-regexp "\\)"))
5222 (^re_ (concat "\\(\\*+\\)[ \t]*"))
5224 (old-level (if (string-match ^re txt)
5225 (- (match-end 0) (match-beginning 0) 1)
5226 -1))
5227 (force-level (cond (level (prefix-numeric-value level))
5228 ((and (looking-at "[ \t]*$")
5229 (string-match
5230 ^re_ (buffer-substring
5231 (point-at-bol) (point))))
5232 (- (match-end 1) (match-beginning 1)))
5233 ((and (bolp)
5234 (looking-at org-outline-regexp))
5235 (- (match-end 0) (point) 1))
5236 (t nil)))
5237 (previous-level (save-excursion
5238 (condition-case nil
5239 (progn
5240 (outline-previous-visible-heading 1)
5241 (if (looking-at re)
5242 (- (match-end 0) (match-beginning 0) 1)
5244 (error 1))))
5245 (next-level (save-excursion
5246 (condition-case nil
5247 (progn
5248 (or (looking-at outline-regexp)
5249 (outline-next-visible-heading 1))
5250 (if (looking-at re)
5251 (- (match-end 0) (match-beginning 0) 1)
5253 (error 1))))
5254 (new-level (or force-level (max previous-level next-level)))
5255 (shift (if (or (= old-level -1)
5256 (= new-level -1)
5257 (= old-level new-level))
5259 (- new-level old-level)))
5260 (delta (if (> shift 0) -1 1))
5261 (func (if (> shift 0) 'org-demote 'org-promote))
5262 (org-odd-levels-only nil)
5263 beg end newend)
5264 ;; Remove the forced level indicator
5265 (if force-level
5266 (delete-region (point-at-bol) (point)))
5267 ;; Paste
5268 (beginning-of-line 1)
5269 (unless for-yank (org-back-over-empty-lines))
5270 (setq beg (point))
5271 (insert-before-markers txt)
5272 (unless (string-match "\n\\'" txt) (insert "\n"))
5273 (setq newend (point))
5274 (org-reinstall-markers-in-region beg)
5275 (setq end (point))
5276 (goto-char beg)
5277 (skip-chars-forward " \t\n\r")
5278 (setq beg (point))
5279 (if (and (org-invisible-p) visp)
5280 (save-excursion (outline-show-heading)))
5281 ;; Shift if necessary
5282 (unless (= shift 0)
5283 (save-restriction
5284 (narrow-to-region beg end)
5285 (while (not (= shift 0))
5286 (org-map-region func (point-min) (point-max))
5287 (setq shift (+ delta shift)))
5288 (goto-char (point-min))
5289 (setq newend (point-max))))
5290 (when (or (interactive-p) for-yank)
5291 (message "Clipboard pasted as level %d subtree" new-level))
5292 (if (and (not for-yank) ; in this case, org-yank will decide about folding
5293 kill-ring
5294 (eq org-subtree-clip (current-kill 0))
5295 org-subtree-clip-folded)
5296 ;; The tree was folded before it was killed/copied
5297 (hide-subtree))
5298 (and for-yank (goto-char newend))))
5300 (defun org-kill-is-subtree-p (&optional txt)
5301 "Check if the current kill is an outline subtree, or a set of trees.
5302 Returns nil if kill does not start with a headline, or if the first
5303 headline level is not the largest headline level in the tree.
5304 So this will actually accept several entries of equal levels as well,
5305 which is OK for `org-paste-subtree'.
5306 If optional TXT is given, check this string instead of the current kill."
5307 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
5308 (start-level (and kill
5309 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
5310 org-outline-regexp "\\)")
5311 kill)
5312 (- (match-end 2) (match-beginning 2) 1)))
5313 (re (concat "^" org-outline-regexp))
5314 (start (1+ (or (match-beginning 2) -1))))
5315 (if (not start-level)
5316 (progn
5317 nil) ;; does not even start with a heading
5318 (catch 'exit
5319 (while (setq start (string-match re kill (1+ start)))
5320 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
5321 (throw 'exit nil)))
5322 t))))
5324 (defvar org-markers-to-move nil
5325 "Markers that should be moved with a cut-and-paste operation.
5326 Those markers are stored together with their positions relative to
5327 the start of the region.")
5329 (defun org-save-markers-in-region (beg end)
5330 "Check markers in region.
5331 If these markers are between BEG and END, record their position relative
5332 to BEG, so that after moving the block of text, we can put the markers back
5333 into place.
5334 This function gets called just before an entry or tree gets cut from the
5335 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
5336 called immediately, to move the markers with the entries."
5337 (setq org-markers-to-move nil)
5338 (when (featurep 'org-clock)
5339 (org-clock-save-markers-for-cut-and-paste beg end))
5340 (when (featurep 'org-agenda)
5341 (org-agenda-save-markers-for-cut-and-paste beg end)))
5343 (defun org-check-and-save-marker (marker beg end)
5344 "Check if MARKER is between BEG and END.
5345 If yes, remember the marker and the distance to BEG."
5346 (when (and (marker-buffer marker)
5347 (equal (marker-buffer marker) (current-buffer)))
5348 (if (and (>= marker beg) (< marker end))
5349 (push (cons marker (- marker beg)) org-markers-to-move))))
5351 (defun org-reinstall-markers-in-region (beg)
5352 "Move all remembered markers to their position relative to BEG."
5353 (mapc (lambda (x)
5354 (move-marker (car x) (+ beg (cdr x))))
5355 org-markers-to-move)
5356 (setq org-markers-to-move nil))
5358 (defun org-narrow-to-subtree ()
5359 "Narrow buffer to the current subtree."
5360 (interactive)
5361 (save-excursion
5362 (save-match-data
5363 (narrow-to-region
5364 (progn (org-back-to-heading) (point))
5365 (progn (org-end-of-subtree t) (point))))))
5368 ;;; Outline Sorting
5370 (defun org-sort (with-case)
5371 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
5372 Optional argument WITH-CASE means sort case-sensitively."
5373 (interactive "P")
5374 (if (org-at-table-p)
5375 (org-call-with-arg 'org-table-sort-lines with-case)
5376 (org-call-with-arg 'org-sort-entries-or-items with-case)))
5378 (defun org-sort-remove-invisible (s)
5379 (remove-text-properties 0 (length s) org-rm-props s)
5380 (while (string-match org-bracket-link-regexp s)
5381 (setq s (replace-match (if (match-end 2)
5382 (match-string 3 s)
5383 (match-string 1 s)) t t s)))
5386 (defvar org-priority-regexp) ; defined later in the file
5388 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
5389 "Sort entries on a certain level of an outline tree.
5390 If there is an active region, the entries in the region are sorted.
5391 Else, if the cursor is before the first entry, sort the top-level items.
5392 Else, the children of the entry at point are sorted.
5394 Sorting can be alphabetically, numerically, and by date/time as given by
5395 the first time stamp in the entry. The command prompts for the sorting
5396 type unless it has been given to the function through the SORTING-TYPE
5397 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
5398 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
5399 called with point at the beginning of the record. It must return either
5400 a string or a number that should serve as the sorting key for that record.
5402 Comparing entries ignores case by default. However, with an optional argument
5403 WITH-CASE, the sorting considers case as well."
5404 (interactive "P")
5405 (let ((case-func (if with-case 'identity 'downcase))
5406 start beg end stars re re2
5407 txt what tmp plain-list-p)
5408 ;; Find beginning and end of region to sort
5409 (cond
5410 ((org-region-active-p)
5411 ;; we will sort the region
5412 (setq end (region-end)
5413 what "region")
5414 (goto-char (region-beginning))
5415 (if (not (org-on-heading-p)) (outline-next-heading))
5416 (setq start (point)))
5417 ((org-at-item-p)
5418 ;; we will sort this plain list
5419 (org-beginning-of-item-list) (setq start (point))
5420 (org-end-of-item-list) (setq end (point))
5421 (goto-char start)
5422 (setq plain-list-p t
5423 what "plain list"))
5424 ((or (org-on-heading-p)
5425 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
5426 ;; we will sort the children of the current headline
5427 (org-back-to-heading)
5428 (setq start (point)
5429 end (progn (org-end-of-subtree t t)
5430 (org-back-over-empty-lines)
5431 (point))
5432 what "children")
5433 (goto-char start)
5434 (show-subtree)
5435 (outline-next-heading))
5437 ;; we will sort the top-level entries in this file
5438 (goto-char (point-min))
5439 (or (org-on-heading-p) (outline-next-heading))
5440 (setq start (point) end (point-max) what "top-level")
5441 (goto-char start)
5442 (show-all)))
5444 (setq beg (point))
5445 (if (>= beg end) (error "Nothing to sort"))
5447 (unless plain-list-p
5448 (looking-at "\\(\\*+\\)")
5449 (setq stars (match-string 1)
5450 re (concat "^" (regexp-quote stars) " +")
5451 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
5452 txt (buffer-substring beg end))
5453 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
5454 (if (and (not (equal stars "*")) (string-match re2 txt))
5455 (error "Region to sort contains a level above the first entry")))
5457 (unless sorting-type
5458 (message
5459 (if plain-list-p
5460 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
5461 "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:")
5462 what)
5463 (setq sorting-type (read-char-exclusive))
5465 (and (= (downcase sorting-type) ?f)
5466 (setq getkey-func
5467 (org-ido-completing-read "Sort using function: "
5468 obarray 'fboundp t nil nil))
5469 (setq getkey-func (intern getkey-func)))
5471 (and (= (downcase sorting-type) ?r)
5472 (setq property
5473 (org-ido-completing-read "Property: "
5474 (mapcar 'list (org-buffer-property-keys t))
5475 nil t))))
5477 (message "Sorting entries...")
5479 (save-restriction
5480 (narrow-to-region start end)
5482 (let ((dcst (downcase sorting-type))
5483 (now (current-time)))
5484 (sort-subr
5485 (/= dcst sorting-type)
5486 ;; This function moves to the beginning character of the "record" to
5487 ;; be sorted.
5488 (if plain-list-p
5489 (lambda nil
5490 (if (org-at-item-p) t (goto-char (point-max))))
5491 (lambda nil
5492 (if (re-search-forward re nil t)
5493 (goto-char (match-beginning 0))
5494 (goto-char (point-max)))))
5495 ;; This function moves to the last character of the "record" being
5496 ;; sorted.
5497 (if plain-list-p
5498 'org-end-of-item
5499 (lambda nil
5500 (save-match-data
5501 (condition-case nil
5502 (outline-forward-same-level 1)
5503 (error
5504 (goto-char (point-max)))))))
5506 ;; This function returns the value that gets sorted against.
5507 (if plain-list-p
5508 (lambda nil
5509 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
5510 (cond
5511 ((= dcst ?n)
5512 (string-to-number (buffer-substring (match-end 0)
5513 (point-at-eol))))
5514 ((= dcst ?a)
5515 (buffer-substring (match-end 0) (point-at-eol)))
5516 ((= dcst ?t)
5517 (if (re-search-forward org-ts-regexp
5518 (point-at-eol) t)
5519 (org-time-string-to-time (match-string 0))
5520 now))
5521 ((= dcst ?f)
5522 (if getkey-func
5523 (progn
5524 (setq tmp (funcall getkey-func))
5525 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5526 tmp)
5527 (error "Invalid key function `%s'" getkey-func)))
5528 (t (error "Invalid sorting type `%c'" sorting-type)))))
5529 (lambda nil
5530 (cond
5531 ((= dcst ?n)
5532 (if (looking-at org-complex-heading-regexp)
5533 (string-to-number (match-string 4))
5534 nil))
5535 ((= dcst ?a)
5536 (if (looking-at org-complex-heading-regexp)
5537 (funcall case-func (match-string 4))
5538 nil))
5539 ((= dcst ?t)
5540 (if (re-search-forward org-ts-regexp
5541 (save-excursion
5542 (forward-line 2)
5543 (point)) t)
5544 (org-time-string-to-time (match-string 0))
5545 now))
5546 ((= dcst ?p)
5547 (if (re-search-forward org-priority-regexp (point-at-eol) t)
5548 (string-to-char (match-string 2))
5549 org-default-priority))
5550 ((= dcst ?r)
5551 (or (org-entry-get nil property) ""))
5552 ((= dcst ?o)
5553 (if (looking-at org-complex-heading-regexp)
5554 (- 9999 (length (member (match-string 2)
5555 org-todo-keywords-1)))))
5556 ((= dcst ?f)
5557 (if getkey-func
5558 (progn
5559 (setq tmp (funcall getkey-func))
5560 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5561 tmp)
5562 (error "Invalid key function `%s'" getkey-func)))
5563 (t (error "Invalid sorting type `%c'" sorting-type)))))
5565 (cond
5566 ((= dcst ?a) 'string<)
5567 ((= dcst ?t) 'time-less-p)
5568 (t nil)))))
5569 (message "Sorting entries...done")))
5571 (defun org-do-sort (table what &optional with-case sorting-type)
5572 "Sort TABLE of WHAT according to SORTING-TYPE.
5573 The user will be prompted for the SORTING-TYPE if the call to this
5574 function does not specify it. WHAT is only for the prompt, to indicate
5575 what is being sorted. The sorting key will be extracted from
5576 the car of the elements of the table.
5577 If WITH-CASE is non-nil, the sorting will be case-sensitive."
5578 (unless sorting-type
5579 (message
5580 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
5581 what)
5582 (setq sorting-type (read-char-exclusive)))
5583 (let ((dcst (downcase sorting-type))
5584 extractfun comparefun)
5585 ;; Define the appropriate functions
5586 (cond
5587 ((= dcst ?n)
5588 (setq extractfun 'string-to-number
5589 comparefun (if (= dcst sorting-type) '< '>)))
5590 ((= dcst ?a)
5591 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
5592 (lambda(x) (downcase (org-sort-remove-invisible x))))
5593 comparefun (if (= dcst sorting-type)
5594 'string<
5595 (lambda (a b) (and (not (string< a b))
5596 (not (string= a b)))))))
5597 ((= dcst ?t)
5598 (setq extractfun
5599 (lambda (x)
5600 (if (string-match org-ts-regexp x)
5601 (time-to-seconds
5602 (org-time-string-to-time (match-string 0 x)))
5604 comparefun (if (= dcst sorting-type) '< '>)))
5605 (t (error "Invalid sorting type `%c'" sorting-type)))
5607 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5608 table)
5609 (lambda (a b) (funcall comparefun (car a) (car b))))))
5611 ;;; Editing source examples
5613 (defvar org-exit-edit-mode-map (make-sparse-keymap))
5614 (define-key org-exit-edit-mode-map "\C-c'" 'org-edit-src-exit)
5615 (defvar org-edit-src-force-single-line nil)
5616 (defvar org-edit-src-from-org-mode nil)
5617 (defvar org-edit-src-picture nil)
5619 (define-minor-mode org-exit-edit-mode
5620 "Minor mode installing a single key binding, \"C-c '\" to exit special edit.")
5622 (defun org-edit-src-code ()
5623 "Edit the source code example at point.
5624 An indirect buffer is created, and that buffer is then narrowed to the
5625 example at point and switched to the correct language mode. When done,
5626 exit by killing the buffer with \\[org-edit-src-exit]."
5627 (interactive)
5628 (let ((line (org-current-line))
5629 (case-fold-search t)
5630 (msg (substitute-command-keys
5631 "Edit, then exit with C-c ' (C-c and single quote)"))
5632 (info (org-edit-src-find-region-and-lang))
5633 (org-mode-p (eq major-mode 'org-mode))
5634 beg end lang lang-f single)
5635 (if (not info)
5637 (setq beg (nth 0 info)
5638 end (nth 1 info)
5639 lang (nth 2 info)
5640 single (nth 3 info)
5641 lang-f (intern (concat lang "-mode")))
5642 (unless (functionp lang-f)
5643 (error "No such language mode: %s" lang-f))
5644 (goto-line line)
5645 (if (get-buffer "*Org Edit Src Example*")
5646 (kill-buffer "*Org Edit Src Example*"))
5647 (switch-to-buffer (make-indirect-buffer (current-buffer)
5648 "*Org Edit Src Example*"))
5649 (narrow-to-region beg end)
5650 (remove-text-properties beg end '(display nil invisible nil
5651 intangible nil))
5652 (let ((org-inhibit-startup t))
5653 (funcall lang-f))
5654 (set (make-local-variable 'org-edit-src-force-single-line) single)
5655 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5656 (when org-mode-p
5657 (goto-char (point-min))
5658 (while (re-search-forward "^," nil t)
5659 (replace-match "")))
5660 (goto-line line)
5661 (org-exit-edit-mode)
5662 (org-set-local 'header-line-format msg)
5663 (message "%s" msg)
5664 t)))
5666 (defun org-edit-fixed-width-region ()
5667 "Edit the fixed-width ascii drawing at point.
5668 This must be a region where each line starts with ca colon followed by
5669 a space character.
5670 An indirect buffer is created, and that buffer is then narrowed to the
5671 example at point and switched to artist-mode. When done,
5672 exit by killing the buffer with \\[org-edit-src-exit]."
5673 (interactive)
5674 (let ((line (org-current-line))
5675 (case-fold-search t)
5676 (msg (substitute-command-keys
5677 "Edit, then exit with C-c ' (C-c and single quote)"))
5678 (org-mode-p (eq major-mode 'org-mode))
5679 beg end lang lang-f)
5680 (beginning-of-line 1)
5681 (if (looking-at "[ \t]*[^:\n \t]")
5683 (if (looking-at "[ \t]*\\(\n\\|\\'\\)")
5684 (setq beg (point) end beg)
5685 (save-excursion
5686 (if (re-search-backward "^[ \t]*[^:]" nil 'move)
5687 (setq beg (point-at-bol 2))
5688 (setq beg (point))))
5689 (save-excursion
5690 (if (re-search-forward "^[ \t]*[^:]" nil 'move)
5691 (setq end (1- (match-beginning 0)))
5692 (setq end (point))))
5693 (goto-line line))
5694 (if (get-buffer "*Org Edit Picture*")
5695 (kill-buffer "*Org Edit Picture*"))
5696 (switch-to-buffer (make-indirect-buffer (current-buffer)
5697 "*Org Edit Picture*"))
5698 (narrow-to-region beg end)
5699 (remove-text-properties beg end '(display nil invisible nil
5700 intangible nil))
5701 (when (fboundp 'font-lock-unfontify-region)
5702 (font-lock-unfontify-region (point-min) (point-max)))
5703 (cond
5704 ((eq org-edit-fixed-width-region-mode 'artist-mode)
5705 (fundamental-mode)
5706 (artist-mode 1))
5707 (t (funcall org-edit-fixed-width-region-mode)))
5708 (set (make-local-variable 'org-edit-src-force-single-line) nil)
5709 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5710 (set (make-local-variable 'org-edit-src-picture) t)
5711 (goto-char (point-min))
5712 (while (re-search-forward "^[ \t]*: ?" nil t)
5713 (replace-match ""))
5714 (goto-line line)
5715 (org-exit-edit-mode)
5716 (org-set-local 'header-line-format msg)
5717 (message "%s" msg)
5718 t)))
5721 (defun org-edit-src-find-region-and-lang ()
5722 "Find the region and language for a local edit.
5723 Return a list with beginning and end of the region, a string representing
5724 the language, a switch telling of the content should be in a single line."
5725 (let ((re-list
5726 (append
5727 org-edit-src-region-extra
5729 ("<src\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</src>" lang)
5730 ("<literal\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</literal>" style)
5731 ("<example>[ \t]*\n?" "\n?[ \t]*</example>" "fundamental")
5732 ("<lisp>[ \t]*\n?" "\n?[ \t]*</lisp>" "emacs-lisp")
5733 ("<perl>[ \t]*\n?" "\n?[ \t]*</perl>" "perl")
5734 ("<python>[ \t]*\n?" "\n?[ \t]*</python>" "python")
5735 ("<ruby>[ \t]*\n?" "\n?[ \t]*</ruby>" "ruby")
5736 ("^#\\+begin_src\\( \\([^ \t\n]+\\)\\)?.*\n" "\n#\\+end_src" 2)
5737 ("^#\\+begin_example.*\n" "\n#\\+end_example" "fundamental")
5738 ("^#\\+html:" "\n" "html" single-line)
5739 ("^#\\+begin_html.*\n" "\n#\\+end_html" "html")
5740 ("^#\\+begin_latex.*\n" "\n#\\+end_latex" "latex")
5741 ("^#\\+latex:" "\n" "latex" single-line)
5742 ("^#\\+begin_ascii.*\n" "\n#\\+end_ascii" "fundamental")
5743 ("^#\\+ascii:" "\n" "ascii" single-line)
5745 (pos (point))
5746 re re1 re2 single beg end lang)
5747 (catch 'exit
5748 (while (setq entry (pop re-list))
5749 (setq re1 (car entry) re2 (nth 1 entry) lang (nth 2 entry)
5750 single (nth 3 entry))
5751 (save-excursion
5752 (if (or (looking-at re1)
5753 (re-search-backward re1 nil t))
5754 (progn
5755 (setq beg (match-end 0) lang (org-edit-src-get-lang lang))
5756 (if (and (re-search-forward re2 nil t)
5757 (>= (match-end 0) pos))
5758 (throw 'exit (list beg (match-beginning 0) lang single))))
5759 (if (or (looking-at re2)
5760 (re-search-forward re2 nil t))
5761 (progn
5762 (setq end (match-beginning 0))
5763 (if (and (re-search-backward re1 nil t)
5764 (<= (match-beginning 0) pos))
5765 (throw 'exit
5766 (list (match-end 0) end
5767 (org-edit-src-get-lang lang) single)))))))))))
5769 (defun org-edit-src-get-lang (lang)
5770 "Extract the src language."
5771 (let ((m (match-string 0)))
5772 (cond
5773 ((stringp lang) lang)
5774 ((integerp lang) (match-string lang))
5775 ((and (eq lang 'lang)
5776 (string-match "\\<lang=\"\\([^ \t\n\"]+\\)\"" m))
5777 (match-string 1 m))
5778 ((and (eq lang 'style)
5779 (string-match "\\<style=\"\\([^ \t\n\"]+\\)\"" m))
5780 (match-string 1 m))
5781 (t "fundamental"))))
5783 (defun org-edit-src-exit ()
5784 "Exit special edit and protect problematic lines."
5785 (interactive)
5786 (unless (buffer-base-buffer (current-buffer))
5787 (error "This is not an indirect buffer, something is wrong..."))
5788 (unless (> (point-min) 1)
5789 (error "This buffer is not narrowed, something is wrong..."))
5790 (goto-char (point-min))
5791 (if (looking-at "[ \t\n]*\n") (replace-match ""))
5792 (if (re-search-forward "\n[ \t\n]*\\'" nil t) (replace-match ""))
5793 (when (org-bound-and-true-p org-edit-src-force-single-line)
5794 (goto-char (point-min))
5795 (while (re-search-forward "\n" nil t)
5796 (replace-match " "))
5797 (goto-char (point-min))
5798 (if (looking-at "\\s-*") (replace-match " "))
5799 (if (re-search-forward "\\s-+\\'" nil t)
5800 (replace-match "")))
5801 (when (org-bound-and-true-p org-edit-src-from-org-mode)
5802 (goto-char (point-min))
5803 (while (re-search-forward (if (org-mode-p) "^\\(.\\)" "^\\([*#]\\)") nil t)
5804 (replace-match ",\\1"))
5805 (when font-lock-mode
5806 (font-lock-unfontify-region (point-min) (point-max)))
5807 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
5808 (when (org-bound-and-true-p org-edit-src-picture)
5809 (untabify (point-min) (point-max))
5810 (goto-char (point-min))
5811 (while (re-search-forward "^" nil t)
5812 (replace-match ": "))
5813 (when font-lock-mode
5814 (font-lock-unfontify-region (point-min) (point-max)))
5815 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
5816 (kill-buffer (current-buffer))
5817 (and (org-mode-p) (org-restart-font-lock)))
5820 ;;; The orgstruct minor mode
5822 ;; Define a minor mode which can be used in other modes in order to
5823 ;; integrate the org-mode structure editing commands.
5825 ;; This is really a hack, because the org-mode structure commands use
5826 ;; keys which normally belong to the major mode. Here is how it
5827 ;; works: The minor mode defines all the keys necessary to operate the
5828 ;; structure commands, but wraps the commands into a function which
5829 ;; tests if the cursor is currently at a headline or a plain list
5830 ;; item. If that is the case, the structure command is used,
5831 ;; temporarily setting many Org-mode variables like regular
5832 ;; expressions for filling etc. However, when any of those keys is
5833 ;; used at a different location, function uses `key-binding' to look
5834 ;; up if the key has an associated command in another currently active
5835 ;; keymap (minor modes, major mode, global), and executes that
5836 ;; command. There might be problems if any of the keys is otherwise
5837 ;; used as a prefix key.
5839 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
5840 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
5841 ;; addresses this by checking explicitly for both bindings.
5843 (defvar orgstruct-mode-map (make-sparse-keymap)
5844 "Keymap for the minor `orgstruct-mode'.")
5846 (defvar org-local-vars nil
5847 "List of local variables, for use by `orgstruct-mode'")
5849 ;;;###autoload
5850 (define-minor-mode orgstruct-mode
5851 "Toggle the minor more `orgstruct-mode'.
5852 This mode is for using Org-mode structure commands in other modes.
5853 The following key behave as if Org-mode was active, if the cursor
5854 is on a headline, or on a plain list item (both in the definition
5855 of Org-mode).
5857 M-up Move entry/item up
5858 M-down Move entry/item down
5859 M-left Promote
5860 M-right Demote
5861 M-S-up Move entry/item up
5862 M-S-down Move entry/item down
5863 M-S-left Promote subtree
5864 M-S-right Demote subtree
5865 M-q Fill paragraph and items like in Org-mode
5866 C-c ^ Sort entries
5867 C-c - Cycle list bullet
5868 TAB Cycle item visibility
5869 M-RET Insert new heading/item
5870 S-M-RET Insert new TODO heading / Chekbox item
5871 C-c C-c Set tags / toggle checkbox"
5872 nil " OrgStruct" nil
5873 (org-load-modules-maybe)
5874 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
5876 ;;;###autoload
5877 (defun turn-on-orgstruct ()
5878 "Unconditionally turn on `orgstruct-mode'."
5879 (orgstruct-mode 1))
5881 ;;;###autoload
5882 (defun turn-on-orgstruct++ ()
5883 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
5884 In addition to setting orgstruct-mode, this also exports all indentation and
5885 autofilling variables from org-mode into the buffer. Note that turning
5886 off orgstruct-mode will *not* remove these additional settings."
5887 (orgstruct-mode 1)
5888 (let (var val)
5889 (mapc
5890 (lambda (x)
5891 (when (string-match
5892 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
5893 (symbol-name (car x)))
5894 (setq var (car x) val (nth 1 x))
5895 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
5896 org-local-vars)))
5898 (defun orgstruct-error ()
5899 "Error when there is no default binding for a structure key."
5900 (interactive)
5901 (error "This key has no function outside structure elements"))
5903 (defun orgstruct-setup ()
5904 "Setup orgstruct keymaps."
5905 (let ((nfunc 0)
5906 (bindings
5907 (list
5908 '([(meta up)] org-metaup)
5909 '([(meta down)] org-metadown)
5910 '([(meta left)] org-metaleft)
5911 '([(meta right)] org-metaright)
5912 '([(meta shift up)] org-shiftmetaup)
5913 '([(meta shift down)] org-shiftmetadown)
5914 '([(meta shift left)] org-shiftmetaleft)
5915 '([(meta shift right)] org-shiftmetaright)
5916 '([(shift up)] org-shiftup)
5917 '([(shift down)] org-shiftdown)
5918 '([(shift left)] org-shiftleft)
5919 '([(shift right)] org-shiftright)
5920 '("\C-c\C-c" org-ctrl-c-ctrl-c)
5921 '("\M-q" fill-paragraph)
5922 '("\C-c^" org-sort)
5923 '("\C-c-" org-cycle-list-bullet)))
5924 elt key fun cmd)
5925 (while (setq elt (pop bindings))
5926 (setq nfunc (1+ nfunc))
5927 (setq key (org-key (car elt))
5928 fun (nth 1 elt)
5929 cmd (orgstruct-make-binding fun nfunc key))
5930 (org-defkey orgstruct-mode-map key cmd))
5932 ;; Special treatment needed for TAB and RET
5933 (org-defkey orgstruct-mode-map [(tab)]
5934 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
5935 (org-defkey orgstruct-mode-map "\C-i"
5936 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
5938 (org-defkey orgstruct-mode-map "\M-\C-m"
5939 (orgstruct-make-binding 'org-insert-heading 105
5940 "\M-\C-m" [(meta return)]))
5941 (org-defkey orgstruct-mode-map [(meta return)]
5942 (orgstruct-make-binding 'org-insert-heading 106
5943 [(meta return)] "\M-\C-m"))
5945 (org-defkey orgstruct-mode-map [(shift meta return)]
5946 (orgstruct-make-binding 'org-insert-todo-heading 107
5947 [(meta return)] "\M-\C-m"))
5949 (unless org-local-vars
5950 (setq org-local-vars (org-get-local-variables)))
5954 (defun orgstruct-make-binding (fun n &rest keys)
5955 "Create a function for binding in the structure minor mode.
5956 FUN is the command to call inside a table. N is used to create a unique
5957 command name. KEYS are keys that should be checked in for a command
5958 to execute outside of tables."
5959 (eval
5960 (list 'defun
5961 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
5962 '(arg)
5963 (concat "In Structure, run `" (symbol-name fun) "'.\n"
5964 "Outside of structure, run the binding of `"
5965 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
5966 "'.")
5967 '(interactive "p")
5968 (list 'if
5969 '(org-context-p 'headline 'item)
5970 (list 'org-run-like-in-org-mode (list 'quote fun))
5971 (list 'let '(orgstruct-mode)
5972 (list 'call-interactively
5973 (append '(or)
5974 (mapcar (lambda (k)
5975 (list 'key-binding k))
5976 keys)
5977 '('orgstruct-error))))))))
5979 (defun org-context-p (&rest contexts)
5980 "Check if local context is any of CONTEXTS.
5981 Possible values in the list of contexts are `table', `headline', and `item'."
5982 (let ((pos (point)))
5983 (goto-char (point-at-bol))
5984 (prog1 (or (and (memq 'table contexts)
5985 (looking-at "[ \t]*|"))
5986 (and (memq 'headline contexts)
5987 ;;????????? (looking-at "\\*+"))
5988 (looking-at outline-regexp))
5989 (and (memq 'item contexts)
5990 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
5991 (goto-char pos))))
5993 (defun org-get-local-variables ()
5994 "Return a list of all local variables in an org-mode buffer."
5995 (let (varlist)
5996 (with-current-buffer (get-buffer-create "*Org tmp*")
5997 (erase-buffer)
5998 (org-mode)
5999 (setq varlist (buffer-local-variables)))
6000 (kill-buffer "*Org tmp*")
6001 (delq nil
6002 (mapcar
6003 (lambda (x)
6004 (setq x
6005 (if (symbolp x)
6006 (list x)
6007 (list (car x) (list 'quote (cdr x)))))
6008 (if (string-match
6009 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6010 (symbol-name (car x)))
6011 x nil))
6012 varlist))))
6014 ;;;###autoload
6015 (defun org-run-like-in-org-mode (cmd)
6016 (org-load-modules-maybe)
6017 (unless org-local-vars
6018 (setq org-local-vars (org-get-local-variables)))
6019 (eval (list 'let org-local-vars
6020 (list 'call-interactively (list 'quote cmd)))))
6022 ;;;; Archiving
6024 (defun org-get-category (&optional pos)
6025 "Get the category applying to position POS."
6026 (get-text-property (or pos (point)) 'org-category))
6028 (defun org-refresh-category-properties ()
6029 "Refresh category text properties in the buffer."
6030 (let ((def-cat (cond
6031 ((null org-category)
6032 (if buffer-file-name
6033 (file-name-sans-extension
6034 (file-name-nondirectory buffer-file-name))
6035 "???"))
6036 ((symbolp org-category) (symbol-name org-category))
6037 (t org-category)))
6038 beg end cat pos optionp)
6039 (org-unmodified
6040 (save-excursion
6041 (save-restriction
6042 (widen)
6043 (goto-char (point-min))
6044 (put-text-property (point) (point-max) 'org-category def-cat)
6045 (while (re-search-forward
6046 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6047 (setq pos (match-end 0)
6048 optionp (equal (char-after (match-beginning 0)) ?#)
6049 cat (org-trim (match-string 2)))
6050 (if optionp
6051 (setq beg (point-at-bol) end (point-max))
6052 (org-back-to-heading t)
6053 (setq beg (point) end (org-end-of-subtree t t)))
6054 (put-text-property beg end 'org-category cat)
6055 (goto-char pos)))))))
6058 ;;;; Link Stuff
6060 ;;; Link abbreviations
6062 (defun org-link-expand-abbrev (link)
6063 "Apply replacements as defined in `org-link-abbrev-alist."
6064 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6065 (let* ((key (match-string 1 link))
6066 (as (or (assoc key org-link-abbrev-alist-local)
6067 (assoc key org-link-abbrev-alist)))
6068 (tag (and (match-end 2) (match-string 3 link)))
6069 rpl)
6070 (if (not as)
6071 link
6072 (setq rpl (cdr as))
6073 (cond
6074 ((symbolp rpl) (funcall rpl tag))
6075 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
6076 ((string-match "%h" rpl)
6077 (replace-match (url-hexify-string (or tag "")) t t rpl))
6078 (t (concat rpl tag)))))
6079 link))
6081 ;;; Storing and inserting links
6083 (defvar org-insert-link-history nil
6084 "Minibuffer history for links inserted with `org-insert-link'.")
6086 (defvar org-stored-links nil
6087 "Contains the links stored with `org-store-link'.")
6089 (defvar org-store-link-plist nil
6090 "Plist with info about the most recently link created with `org-store-link'.")
6092 (defvar org-link-protocols nil
6093 "Link protocols added to Org-mode using `org-add-link-type'.")
6095 (defvar org-store-link-functions nil
6096 "List of functions that are called to create and store a link.
6097 Each function will be called in turn until one returns a non-nil
6098 value. Each function should check if it is responsible for creating
6099 this link (for example by looking at the major mode).
6100 If not, it must exit and return nil.
6101 If yes, it should return a non-nil value after a calling
6102 `org-store-link-props' with a list of properties and values.
6103 Special properties are:
6105 :type The link prefix. like \"http\". This must be given.
6106 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6107 This is obligatory as well.
6108 :description Optional default description for the second pair
6109 of brackets in an Org-mode link. The user can still change
6110 this when inserting this link into an Org-mode buffer.
6112 In addition to these, any additional properties can be specified
6113 and then used in remember templates.")
6115 (defun org-add-link-type (type &optional follow export)
6116 "Add TYPE to the list of `org-link-types'.
6117 Re-compute all regular expressions depending on `org-link-types'
6119 FOLLOW and EXPORT are two functions.
6121 FOLLOW should take the link path as the single argument and do whatever
6122 is necessary to follow the link, for example find a file or display
6123 a mail message.
6125 EXPORT should format the link path for export to one of the export formats.
6126 It should be a function accepting three arguments:
6128 path the path of the link, the text after the prefix (like \"http:\")
6129 desc the description of the link, if any, nil if there was no descripton
6130 format the export format, a symbol like `html' or `latex'.
6132 The function may use the FORMAT information to return different values
6133 depending on the format. The return value will be put literally into
6134 the exported file.
6135 Org-mode has a built-in default for exporting links. If you are happy with
6136 this default, there is no need to define an export function for the link
6137 type. For a simple example of an export function, see `org-bbdb.el'."
6138 (add-to-list 'org-link-types type t)
6139 (org-make-link-regexps)
6140 (if (assoc type org-link-protocols)
6141 (setcdr (assoc type org-link-protocols) (list follow export))
6142 (push (list type follow export) org-link-protocols)))
6145 ;;;###autoload
6146 (defun org-store-link (arg)
6147 "\\<org-mode-map>Store an org-link to the current location.
6148 This link is added to `org-stored-links' and can later be inserted
6149 into an org-buffer with \\[org-insert-link].
6151 For some link types, a prefix arg is interpreted:
6152 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
6153 For file links, arg negates `org-context-in-file-links'."
6154 (interactive "P")
6155 (org-load-modules-maybe)
6156 (setq org-store-link-plist nil) ; reset
6157 (let (link cpltxt desc description search txt)
6158 (cond
6160 ((run-hook-with-args-until-success 'org-store-link-functions)
6161 (setq link (plist-get org-store-link-plist :link)
6162 desc (or (plist-get org-store-link-plist :description) link)))
6164 ((eq major-mode 'calendar-mode)
6165 (let ((cd (calendar-cursor-to-date)))
6166 (setq link
6167 (format-time-string
6168 (car org-time-stamp-formats)
6169 (apply 'encode-time
6170 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6171 nil nil nil))))
6172 (org-store-link-props :type "calendar" :date cd)))
6174 ((eq major-mode 'w3-mode)
6175 (setq cpltxt (url-view-url t)
6176 link (org-make-link cpltxt))
6177 (org-store-link-props :type "w3" :url (url-view-url t)))
6179 ((eq major-mode 'w3m-mode)
6180 (setq cpltxt (or w3m-current-title w3m-current-url)
6181 link (org-make-link w3m-current-url))
6182 (org-store-link-props :type "w3m" :url (url-view-url t)))
6184 ((setq search (run-hook-with-args-until-success
6185 'org-create-file-search-functions))
6186 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6187 "::" search))
6188 (setq cpltxt (or description link)))
6190 ((eq major-mode 'image-mode)
6191 (setq cpltxt (concat "file:"
6192 (abbreviate-file-name buffer-file-name))
6193 link (org-make-link cpltxt))
6194 (org-store-link-props :type "image" :file buffer-file-name))
6196 ((eq major-mode 'dired-mode)
6197 ;; link to the file in the current line
6198 (setq cpltxt (concat "file:"
6199 (abbreviate-file-name
6200 (expand-file-name
6201 (dired-get-filename nil t))))
6202 link (org-make-link cpltxt)))
6204 ((and buffer-file-name (org-mode-p))
6205 ;; Just link to current headline
6206 (setq cpltxt (concat "file:"
6207 (abbreviate-file-name buffer-file-name)))
6208 ;; Add a context search string
6209 (when (org-xor org-context-in-file-links arg)
6210 ;; Check if we are on a target
6211 (if (org-in-regexp "<<\\(.*?\\)>>")
6212 (setq cpltxt (concat cpltxt "::" (match-string 1)))
6213 (setq txt (cond
6214 ((org-on-heading-p) nil)
6215 ((org-region-active-p)
6216 (buffer-substring (region-beginning) (region-end)))
6217 (t nil)))
6218 (when (or (null txt) (string-match "\\S-" txt))
6219 (setq cpltxt
6220 (concat cpltxt "::"
6221 (condition-case nil
6222 (org-make-org-heading-search-string txt)
6223 (error "")))
6224 desc "NONE"))))
6225 (if (string-match "::\\'" cpltxt)
6226 (setq cpltxt (substring cpltxt 0 -2)))
6227 (setq link (org-make-link cpltxt)))
6229 ((buffer-file-name (buffer-base-buffer))
6230 ;; Just link to this file here.
6231 (setq cpltxt (concat "file:"
6232 (abbreviate-file-name
6233 (buffer-file-name (buffer-base-buffer)))))
6234 ;; Add a context string
6235 (when (org-xor org-context-in-file-links arg)
6236 (setq txt (if (org-region-active-p)
6237 (buffer-substring (region-beginning) (region-end))
6238 (buffer-substring (point-at-bol) (point-at-eol))))
6239 ;; Only use search option if there is some text.
6240 (when (string-match "\\S-" txt)
6241 (setq cpltxt
6242 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6243 desc "NONE")))
6244 (setq link (org-make-link cpltxt)))
6246 ((interactive-p)
6247 (error "Cannot link to a buffer which is not visiting a file"))
6249 (t (setq link nil)))
6251 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6252 (setq link (or link cpltxt)
6253 desc (or desc cpltxt))
6254 (if (equal desc "NONE") (setq desc nil))
6256 (if (and (interactive-p) link)
6257 (progn
6258 (setq org-stored-links
6259 (cons (list link desc) org-stored-links))
6260 (message "Stored: %s" (or desc link)))
6261 (and link (org-make-link-string link desc)))))
6263 (defun org-store-link-props (&rest plist)
6264 "Store link properties, extract names and addresses."
6265 (let (x adr)
6266 (when (setq x (plist-get plist :from))
6267 (setq adr (mail-extract-address-components x))
6268 (setq plist (plist-put plist :fromname (car adr)))
6269 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
6270 (when (setq x (plist-get plist :to))
6271 (setq adr (mail-extract-address-components x))
6272 (setq plist (plist-put plist :toname (car adr)))
6273 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
6274 (let ((from (plist-get plist :from))
6275 (to (plist-get plist :to)))
6276 (when (and from to org-from-is-user-regexp)
6277 (setq plist
6278 (plist-put plist :fromto
6279 (if (string-match org-from-is-user-regexp from)
6280 (concat "to %t")
6281 (concat "from %f"))))))
6282 (setq org-store-link-plist plist))
6284 (defun org-add-link-props (&rest plist)
6285 "Add these properties to the link property list."
6286 (let (key value)
6287 (while plist
6288 (setq key (pop plist) value (pop plist))
6289 (setq org-store-link-plist
6290 (plist-put org-store-link-plist key value)))))
6292 (defun org-email-link-description (&optional fmt)
6293 "Return the description part of an email link.
6294 This takes information from `org-store-link-plist' and formats it
6295 according to FMT (default from `org-email-link-description-format')."
6296 (setq fmt (or fmt org-email-link-description-format))
6297 (let* ((p org-store-link-plist)
6298 (to (plist-get p :toaddress))
6299 (from (plist-get p :fromaddress))
6300 (table
6301 (list
6302 (cons "%c" (plist-get p :fromto))
6303 (cons "%F" (plist-get p :from))
6304 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
6305 (cons "%T" (plist-get p :to))
6306 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
6307 (cons "%s" (plist-get p :subject))
6308 (cons "%m" (plist-get p :message-id)))))
6309 (when (string-match "%c" fmt)
6310 ;; Check if the user wrote this message
6311 (if (and org-from-is-user-regexp from to
6312 (save-match-data (string-match org-from-is-user-regexp from)))
6313 (setq fmt (replace-match "to %t" t t fmt))
6314 (setq fmt (replace-match "from %f" t t fmt))))
6315 (org-replace-escapes fmt table)))
6317 (defun org-make-org-heading-search-string (&optional string heading)
6318 "Make search string for STRING or current headline."
6319 (interactive)
6320 (let ((s (or string (org-get-heading))))
6321 (unless (and string (not heading))
6322 ;; We are using a headline, clean up garbage in there.
6323 (if (string-match org-todo-regexp s)
6324 (setq s (replace-match "" t t s)))
6325 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
6326 (setq s (replace-match "" t t s)))
6327 (setq s (org-trim s))
6328 (if (string-match (concat "^\\(" org-quote-string "\\|"
6329 org-comment-string "\\)") s)
6330 (setq s (replace-match "" t t s)))
6331 (while (string-match org-ts-regexp s)
6332 (setq s (replace-match "" t t s))))
6333 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
6334 (setq s (replace-match " " t t s)))
6335 (or string (setq s (concat "*" s))) ; Add * for headlines
6336 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
6338 (defun org-make-link (&rest strings)
6339 "Concatenate STRINGS."
6340 (apply 'concat strings))
6342 (defun org-make-link-string (link &optional description)
6343 "Make a link with brackets, consisting of LINK and DESCRIPTION."
6344 (unless (string-match "\\S-" link)
6345 (error "Empty link"))
6346 (when (stringp description)
6347 ;; Remove brackets from the description, they are fatal.
6348 (while (string-match "\\[" description)
6349 (setq description (replace-match "{" t t description)))
6350 (while (string-match "\\]" description)
6351 (setq description (replace-match "}" t t description))))
6352 (when (equal (org-link-escape link) description)
6353 ;; No description needed, it is identical
6354 (setq description nil))
6355 (when (and (not description)
6356 (not (equal link (org-link-escape link))))
6357 (setq description (org-extract-attributes link)))
6358 (concat "[[" (org-link-escape link) "]"
6359 (if description (concat "[" description "]") "")
6360 "]"))
6362 (defconst org-link-escape-chars
6363 '((?\ . "%20")
6364 (?\[ . "%5B")
6365 (?\] . "%5D")
6366 (?\340 . "%E0") ; `a
6367 (?\342 . "%E2") ; ^a
6368 (?\347 . "%E7") ; ,c
6369 (?\350 . "%E8") ; `e
6370 (?\351 . "%E9") ; 'e
6371 (?\352 . "%EA") ; ^e
6372 (?\356 . "%EE") ; ^i
6373 (?\364 . "%F4") ; ^o
6374 (?\371 . "%F9") ; `u
6375 (?\373 . "%FB") ; ^u
6376 (?\; . "%3B")
6377 (?? . "%3F")
6378 (?= . "%3D")
6379 (?+ . "%2B")
6381 "Association list of escapes for some characters problematic in links.
6382 This is the list that is used for internal purposes.")
6384 (defconst org-link-escape-chars-browser
6385 '((?\ . "%20")) ; 32 for the SPC char
6386 "Association list of escapes for some characters problematic in links.
6387 This is the list that is used before handing over to the browser.")
6389 (defun org-link-escape (text &optional table)
6390 "Escape characters in TEXT that are problematic for links."
6391 (setq table (or table org-link-escape-chars))
6392 (when text
6393 (let ((re (mapconcat (lambda (x) (regexp-quote
6394 (char-to-string (car x))))
6395 table "\\|")))
6396 (while (string-match re text)
6397 (setq text
6398 (replace-match
6399 (cdr (assoc (string-to-char (match-string 0 text))
6400 table))
6401 t t text)))
6402 text)))
6404 (defun org-link-unescape (text &optional table)
6405 "Reverse the action of `org-link-escape'."
6406 (setq table (or table org-link-escape-chars))
6407 (when text
6408 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
6409 table "\\|")))
6410 (while (string-match re text)
6411 (setq text
6412 (replace-match
6413 (char-to-string (car (rassoc (match-string 0 text) table)))
6414 t t text)))
6415 text)))
6417 (defun org-xor (a b)
6418 "Exclusive or."
6419 (if a (not b) b))
6421 (defun org-get-header (header)
6422 "Find a header field in the current buffer."
6423 (save-excursion
6424 (goto-char (point-min))
6425 (let ((case-fold-search t) s)
6426 (cond
6427 ((eq header 'from)
6428 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
6429 (setq s (match-string 1)))
6430 (while (string-match "\"" s)
6431 (setq s (replace-match "" t t s)))
6432 (if (string-match "[<(].*" s)
6433 (setq s (replace-match "" t t s))))
6434 ((eq header 'message-id)
6435 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
6436 (setq s (match-string 1))))
6437 ((eq header 'subject)
6438 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
6439 (setq s (match-string 1)))))
6440 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
6441 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
6442 s)))
6445 (defun org-fixup-message-id-for-http (s)
6446 "Replace special characters in a message id, so it can be used in an http query."
6447 (while (string-match "<" s)
6448 (setq s (replace-match "%3C" t t s)))
6449 (while (string-match ">" s)
6450 (setq s (replace-match "%3E" t t s)))
6451 (while (string-match "@" s)
6452 (setq s (replace-match "%40" t t s)))
6455 ;;;###autoload
6456 (defun org-insert-link-global ()
6457 "Insert a link like Org-mode does.
6458 This command can be called in any mode to insert a link in Org-mode syntax."
6459 (interactive)
6460 (org-load-modules-maybe)
6461 (org-run-like-in-org-mode 'org-insert-link))
6463 (defun org-insert-link (&optional complete-file link-location)
6464 "Insert a link. At the prompt, enter the link.
6466 Completion can be used to insert any of the link protocol prefixes like
6467 http or ftp in use.
6469 The history can be used to select a link previously stored with
6470 `org-store-link'. When the empty string is entered (i.e. if you just
6471 press RET at the prompt), the link defaults to the most recently
6472 stored link. As SPC triggers completion in the minibuffer, you need to
6473 use M-SPC or C-q SPC to force the insertion of a space character.
6475 You will also be prompted for a description, and if one is given, it will
6476 be displayed in the buffer instead of the link.
6478 If there is already a link at point, this command will allow you to edit link
6479 and description parts.
6481 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
6482 be selected using completion. The path to the file will be relative to the
6483 current directory if the file is in the current directory or a subdirectory.
6484 Otherwise, the link will be the absolute path as completed in the minibuffer
6485 \(i.e. normally ~/path/to/file). You can configure this behavior using the
6486 option `org-link-file-path-type'.
6488 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
6489 the current directory or below.
6491 With three \\[universal-argument] prefixes, negate the meaning of
6492 `org-keep-stored-link-after-insertion'.
6494 If `org-make-link-description-function' is non-nil, this function will be
6495 called with the link target, and the result will be the default
6496 link description.
6498 If the LINK-LOCATION parameter is non-nil, this value will be
6499 used as the link location instead of reading one interactively."
6500 (interactive "P")
6501 (let* ((wcf (current-window-configuration))
6502 (region (if (org-region-active-p)
6503 (buffer-substring (region-beginning) (region-end))))
6504 (remove (and region (list (region-beginning) (region-end))))
6505 (desc region)
6506 tmphist ; byte-compile incorrectly complains about this
6507 (link link-location)
6508 entry file)
6509 (cond
6510 (link-location) ; specified by arg, just use it.
6511 ((org-in-regexp org-bracket-link-regexp 1)
6512 ;; We do have a link at point, and we are going to edit it.
6513 (setq remove (list (match-beginning 0) (match-end 0)))
6514 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
6515 (setq link (read-string "Link: "
6516 (org-link-unescape
6517 (org-match-string-no-properties 1)))))
6518 ((or (org-in-regexp org-angle-link-re)
6519 (org-in-regexp org-plain-link-re))
6520 ;; Convert to bracket link
6521 (setq remove (list (match-beginning 0) (match-end 0))
6522 link (read-string "Link: "
6523 (org-remove-angle-brackets (match-string 0)))))
6524 ((member complete-file '((4) (16)))
6525 ;; Completing read for file names.
6526 (setq file (read-file-name "File: "))
6527 (let ((pwd (file-name-as-directory (expand-file-name ".")))
6528 (pwd1 (file-name-as-directory (abbreviate-file-name
6529 (expand-file-name ".")))))
6530 (cond
6531 ((equal complete-file '(16))
6532 (setq link (org-make-link
6533 "file:"
6534 (abbreviate-file-name (expand-file-name file)))))
6535 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
6536 (setq link (org-make-link "file:" (match-string 1 file))))
6537 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
6538 (expand-file-name file))
6539 (setq link (org-make-link
6540 "file:" (match-string 1 (expand-file-name file)))))
6541 (t (setq link (org-make-link "file:" file))))))
6543 ;; Read link, with completion for stored links.
6544 (with-output-to-temp-buffer "*Org Links*"
6545 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
6546 (when org-stored-links
6547 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
6548 (princ (mapconcat
6549 (lambda (x)
6550 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
6551 (reverse org-stored-links) "\n"))))
6552 (let ((cw (selected-window)))
6553 (select-window (get-buffer-window "*Org Links*"))
6554 (org-fit-window-to-buffer)
6555 (setq truncate-lines t)
6556 (select-window cw))
6557 ;; Fake a link history, containing the stored links.
6558 (setq tmphist (append (mapcar 'car org-stored-links)
6559 org-insert-link-history))
6560 (unwind-protect
6561 (setq link (org-completing-read
6562 "Link: "
6563 (append
6564 (mapcar (lambda (x) (list (concat (car x) ":")))
6565 (append org-link-abbrev-alist-local org-link-abbrev-alist))
6566 (mapcar (lambda (x) (list (concat x ":")))
6567 org-link-types))
6568 nil nil nil
6569 'tmphist
6570 (or (car (car org-stored-links)))))
6571 (set-window-configuration wcf)
6572 (kill-buffer "*Org Links*"))
6573 (setq entry (assoc link org-stored-links))
6574 (or entry (push link org-insert-link-history))
6575 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
6576 (not org-keep-stored-link-after-insertion))
6577 (setq org-stored-links (delq (assoc link org-stored-links)
6578 org-stored-links)))
6579 (setq desc (or desc (nth 1 entry)))))
6581 (if (string-match org-plain-link-re link)
6582 ;; URL-like link, normalize the use of angular brackets.
6583 (setq link (org-make-link (org-remove-angle-brackets link))))
6585 ;; Check if we are linking to the current file with a search option
6586 ;; If yes, simplify the link by using only the search option.
6587 (when (and buffer-file-name
6588 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
6589 (let* ((path (match-string 1 link))
6590 (case-fold-search nil)
6591 (search (match-string 2 link)))
6592 (save-match-data
6593 (if (equal (file-truename buffer-file-name) (file-truename path))
6594 ;; We are linking to this same file, with a search option
6595 (setq link search)))))
6597 ;; Check if we can/should use a relative path. If yes, simplify the link
6598 (when (string-match "^file:\\(.*\\)" link)
6599 (let* ((path (match-string 1 link))
6600 (origpath path)
6601 (case-fold-search nil))
6602 (cond
6603 ((or (eq org-link-file-path-type 'absolute)
6604 (equal complete-file '(16)))
6605 (setq path (abbreviate-file-name (expand-file-name path))))
6606 ((eq org-link-file-path-type 'noabbrev)
6607 (setq path (expand-file-name path)))
6608 ((eq org-link-file-path-type 'relative)
6609 (setq path (file-relative-name path)))
6611 (save-match-data
6612 (if (string-match (concat "^" (regexp-quote
6613 (file-name-as-directory
6614 (expand-file-name "."))))
6615 (expand-file-name path))
6616 ;; We are linking a file with relative path name.
6617 (setq path (substring (expand-file-name path)
6618 (match-end 0)))
6619 (setq path (abbreviate-file-name (expand-file-name path)))))))
6620 (setq link (concat "file:" path))
6621 (if (equal desc origpath)
6622 (setq desc path))))
6624 (if org-make-link-description-function
6625 (setq desc (funcall org-make-link-description-function link desc)))
6627 (setq desc (read-string "Description: " desc))
6628 (unless (string-match "\\S-" desc) (setq desc nil))
6629 (if remove (apply 'delete-region remove))
6630 (insert (org-make-link-string link desc))))
6632 (defun org-completing-read (&rest args)
6633 "Completing-read with SPACE being a normal character."
6634 (let ((minibuffer-local-completion-map
6635 (copy-keymap minibuffer-local-completion-map)))
6636 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
6637 (apply 'org-ido-completing-read args)))
6639 (defun org-ido-completing-read (&rest args)
6640 "Completing-read using `ido-mode' speedups if available"
6641 (if (and org-completion-use-ido
6642 (fboundp 'ido-completing-read)
6643 (boundp 'ido-mode) ido-mode
6644 (listp (second args)))
6645 (apply 'ido-completing-read (concat (car args)) (cdr args))
6646 (apply 'completing-read args)))
6648 (defun org-extract-attributes (s)
6649 "Extract the attributes cookie from a string and set as text property."
6650 (let (a attr (start 0) key value)
6651 (save-match-data
6652 (when (string-match "{{\\([^}]+\\)}}$" s)
6653 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
6654 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
6655 (setq key (match-string 1 a) value (match-string 2 a)
6656 start (match-end 0)
6657 attr (plist-put attr (intern key) value))))
6658 (org-add-props s nil 'org-attr attr))
6661 (defun org-attributes-to-string (plist)
6662 "Format a property list into an HTML attribute list."
6663 (let ((s "") key value)
6664 (while plist
6665 (setq key (pop plist) value (pop plist))
6666 (and value
6667 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
6670 ;;; Opening/following a link
6672 (defvar org-link-search-failed nil)
6674 (defun org-next-link ()
6675 "Move forward to the next link.
6676 If the link is in hidden text, expose it."
6677 (interactive)
6678 (when (and org-link-search-failed (eq this-command last-command))
6679 (goto-char (point-min))
6680 (message "Link search wrapped back to beginning of buffer"))
6681 (setq org-link-search-failed nil)
6682 (let* ((pos (point))
6683 (ct (org-context))
6684 (a (assoc :link ct)))
6685 (if a (goto-char (nth 2 a)))
6686 (if (re-search-forward org-any-link-re nil t)
6687 (progn
6688 (goto-char (match-beginning 0))
6689 (if (org-invisible-p) (org-show-context)))
6690 (goto-char pos)
6691 (setq org-link-search-failed t)
6692 (error "No further link found"))))
6694 (defun org-previous-link ()
6695 "Move backward to the previous link.
6696 If the link is in hidden text, expose it."
6697 (interactive)
6698 (when (and org-link-search-failed (eq this-command last-command))
6699 (goto-char (point-max))
6700 (message "Link search wrapped back to end of buffer"))
6701 (setq org-link-search-failed nil)
6702 (let* ((pos (point))
6703 (ct (org-context))
6704 (a (assoc :link ct)))
6705 (if a (goto-char (nth 1 a)))
6706 (if (re-search-backward org-any-link-re nil t)
6707 (progn
6708 (goto-char (match-beginning 0))
6709 (if (org-invisible-p) (org-show-context)))
6710 (goto-char pos)
6711 (setq org-link-search-failed t)
6712 (error "No further link found"))))
6714 (defun org-translate-link (s)
6715 "Translate a link string if a translation function has been defined."
6716 (if (and org-link-translation-function
6717 (fboundp org-link-translation-function)
6718 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
6719 (progn
6720 (setq s (funcall org-link-translation-function
6721 (match-string 1) (match-string 2)))
6722 (concat (car s) ":" (cdr s)))
6725 (defun org-translate-link-from-planner (type path)
6726 "Translate a link from Emacs Planner syntax so that Org can follow it.
6727 This is still an experimental function, your mileage may vary."
6728 (cond
6729 ((member type '("http" "https" "news" "ftp"))
6730 ;; standard Internet links are the same.
6731 nil)
6732 ((and (equal type "irc") (string-match "^//" path))
6733 ;; Planner has two / at the beginning of an irc link, we have 1.
6734 ;; We should have zero, actually....
6735 (setq path (substring path 1)))
6736 ((and (equal type "lisp") (string-match "^/" path))
6737 ;; Planner has a slash, we do not.
6738 (setq type "elisp" path (substring path 1)))
6739 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
6740 ;; A typical message link. Planner has the id after the fina slash,
6741 ;; we separate it with a hash mark
6742 (setq path (concat (match-string 1 path) "#"
6743 (org-remove-angle-brackets (match-string 2 path)))))
6745 (cons type path))
6747 (defun org-find-file-at-mouse (ev)
6748 "Open file link or URL at mouse."
6749 (interactive "e")
6750 (mouse-set-point ev)
6751 (org-open-at-point 'in-emacs))
6753 (defun org-open-at-mouse (ev)
6754 "Open file link or URL at mouse."
6755 (interactive "e")
6756 (mouse-set-point ev)
6757 (if (eq major-mode 'org-agenda-mode)
6758 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
6759 (org-open-at-point))
6761 (defvar org-window-config-before-follow-link nil
6762 "The window configuration before following a link.
6763 This is saved in case the need arises to restore it.")
6765 (defvar org-open-link-marker (make-marker)
6766 "Marker pointing to the location where `org-open-at-point; was called.")
6768 ;;;###autoload
6769 (defun org-open-at-point-global ()
6770 "Follow a link like Org-mode does.
6771 This command can be called in any mode to follow a link that has
6772 Org-mode syntax."
6773 (interactive)
6774 (org-run-like-in-org-mode 'org-open-at-point))
6776 ;;;###autoload
6777 (defun org-open-link-from-string (s &optional arg)
6778 "Open a link in the string S, as if it was in Org-mode."
6779 (interactive "sLink: \nP")
6780 (with-temp-buffer
6781 (let ((org-inhibit-startup t))
6782 (org-mode)
6783 (insert s)
6784 (goto-char (point-min))
6785 (org-open-at-point arg))))
6787 (defun org-open-at-point (&optional in-emacs)
6788 "Open link at or after point.
6789 If there is no link at point, this function will search forward up to
6790 the end of the current subtree.
6791 Normally, files will be opened by an appropriate application. If the
6792 optional argument IN-EMACS is non-nil, Emacs will visit the file.
6793 With a double prefix argument, try to open outside of Emacs, in the
6794 application the system uses for this file type."
6795 (interactive "P")
6796 (org-load-modules-maybe)
6797 (move-marker org-open-link-marker (point))
6798 (setq org-window-config-before-follow-link (current-window-configuration))
6799 (org-remove-occur-highlights nil nil t)
6800 (if (org-at-timestamp-p t)
6801 (org-follow-timestamp-link)
6802 (let (type path link line search (pos (point)))
6803 (catch 'match
6804 (save-excursion
6805 (skip-chars-forward "^]\n\r")
6806 (when (org-in-regexp org-bracket-link-regexp)
6807 (setq link (org-extract-attributes
6808 (org-link-unescape (org-match-string-no-properties 1))))
6809 (while (string-match " *\n *" link)
6810 (setq link (replace-match " " t t link)))
6811 (setq link (org-link-expand-abbrev link))
6812 (cond
6813 ((or (file-name-absolute-p link)
6814 (string-match "^\\.\\.?/" link))
6815 (setq type "file" path link))
6816 ((string-match org-link-re-with-space3 link)
6817 (setq type (match-string 1 link) path (match-string 2 link)))
6818 (t (setq type "thisfile" path link)))
6819 (throw 'match t)))
6821 (when (get-text-property (point) 'org-linked-text)
6822 (setq type "thisfile"
6823 pos (if (get-text-property (1+ (point)) 'org-linked-text)
6824 (1+ (point)) (point))
6825 path (buffer-substring
6826 (previous-single-property-change pos 'org-linked-text)
6827 (next-single-property-change pos 'org-linked-text)))
6828 (throw 'match t))
6830 (save-excursion
6831 (when (or (org-in-regexp org-angle-link-re)
6832 (org-in-regexp org-plain-link-re))
6833 (setq type (match-string 1) path (match-string 2))
6834 (throw 'match t)))
6835 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
6836 (setq type "tree-match"
6837 path (match-string 1))
6838 (throw 'match t))
6839 (save-excursion
6840 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
6841 (setq type "tags"
6842 path (match-string 1))
6843 (while (string-match ":" path)
6844 (setq path (replace-match "+" t t path)))
6845 (throw 'match t))))
6846 (unless path
6847 (error "No link found"))
6848 ;; Remove any trailing spaces in path
6849 (if (string-match " +\\'" path)
6850 (setq path (replace-match "" t t path)))
6851 (if (and org-link-translation-function
6852 (fboundp org-link-translation-function))
6853 ;; Check if we need to translate the link
6854 (let ((tmp (funcall org-link-translation-function type path)))
6855 (setq type (car tmp) path (cdr tmp))))
6857 (cond
6859 ((assoc type org-link-protocols)
6860 (funcall (nth 1 (assoc type org-link-protocols)) path))
6862 ((equal type "mailto")
6863 (let ((cmd (car org-link-mailto-program))
6864 (args (cdr org-link-mailto-program)) args1
6865 (address path) (subject "") a)
6866 (if (string-match "\\(.*\\)::\\(.*\\)" path)
6867 (setq address (match-string 1 path)
6868 subject (org-link-escape (match-string 2 path))))
6869 (while args
6870 (cond
6871 ((not (stringp (car args))) (push (pop args) args1))
6872 (t (setq a (pop args))
6873 (if (string-match "%a" a)
6874 (setq a (replace-match address t t a)))
6875 (if (string-match "%s" a)
6876 (setq a (replace-match subject t t a)))
6877 (push a args1))))
6878 (apply cmd (nreverse args1))))
6880 ((member type '("http" "https" "ftp" "news"))
6881 (browse-url (concat type ":" (org-link-escape
6882 path org-link-escape-chars-browser))))
6884 ((member type '("message"))
6885 (browse-url (concat type ":" path)))
6887 ((string= type "tags")
6888 (org-tags-view in-emacs path))
6889 ((string= type "thisfile")
6890 (if in-emacs
6891 (switch-to-buffer-other-window
6892 (org-get-buffer-for-internal-link (current-buffer)))
6893 (org-mark-ring-push))
6894 (let ((cmd `(org-link-search
6895 ,path
6896 ,(cond ((equal in-emacs '(4)) 'occur)
6897 ((equal in-emacs '(16)) 'org-occur)
6898 (t nil))
6899 ,pos)))
6900 (condition-case nil (eval cmd)
6901 (error (progn (widen) (eval cmd))))))
6903 ((string= type "tree-match")
6904 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
6906 ((string= type "file")
6907 (if (string-match "::\\([0-9]+\\)\\'" path)
6908 (setq line (string-to-number (match-string 1 path))
6909 path (substring path 0 (match-beginning 0)))
6910 (if (string-match "::\\(.+\\)\\'" path)
6911 (setq search (match-string 1 path)
6912 path (substring path 0 (match-beginning 0)))))
6913 (if (string-match "[*?{]" (file-name-nondirectory path))
6914 (dired path)
6915 (org-open-file path in-emacs line search)))
6917 ((string= type "news")
6918 (require 'org-gnus)
6919 (org-gnus-follow-link path))
6921 ((string= type "shell")
6922 (let ((cmd path))
6923 (if (or (not org-confirm-shell-link-function)
6924 (funcall org-confirm-shell-link-function
6925 (format "Execute \"%s\" in shell? "
6926 (org-add-props cmd nil
6927 'face 'org-warning))))
6928 (progn
6929 (message "Executing %s" cmd)
6930 (shell-command cmd))
6931 (error "Abort"))))
6933 ((string= type "elisp")
6934 (let ((cmd path))
6935 (if (or (not org-confirm-elisp-link-function)
6936 (funcall org-confirm-elisp-link-function
6937 (format "Execute \"%s\" as elisp? "
6938 (org-add-props cmd nil
6939 'face 'org-warning))))
6940 (message "%s => %s" cmd
6941 (if (equal (string-to-char cmd) ?\()
6942 (eval (read cmd))
6943 (call-interactively (read cmd))))
6944 (error "Abort"))))
6947 (browse-url-at-point)))))
6948 (move-marker org-open-link-marker nil)
6949 (run-hook-with-args 'org-follow-link-hook))
6951 ;;;; Time estimates
6953 (defun org-get-effort (&optional pom)
6954 "Get the effort estimate for the current entry."
6955 (org-entry-get pom org-effort-property))
6957 ;;; File search
6959 (defvar org-create-file-search-functions nil
6960 "List of functions to construct the right search string for a file link.
6961 These functions are called in turn with point at the location to
6962 which the link should point.
6964 A function in the hook should first test if it would like to
6965 handle this file type, for example by checking the major-mode or
6966 the file extension. If it decides not to handle this file, it
6967 should just return nil to give other functions a chance. If it
6968 does handle the file, it must return the search string to be used
6969 when following the link. The search string will be part of the
6970 file link, given after a double colon, and `org-open-at-point'
6971 will automatically search for it. If special measures must be
6972 taken to make the search successful, another function should be
6973 added to the companion hook `org-execute-file-search-functions',
6974 which see.
6976 A function in this hook may also use `setq' to set the variable
6977 `description' to provide a suggestion for the descriptive text to
6978 be used for this link when it gets inserted into an Org-mode
6979 buffer with \\[org-insert-link].")
6981 (defvar org-execute-file-search-functions nil
6982 "List of functions to execute a file search triggered by a link.
6984 Functions added to this hook must accept a single argument, the
6985 search string that was part of the file link, the part after the
6986 double colon. The function must first check if it would like to
6987 handle this search, for example by checking the major-mode or the
6988 file extension. If it decides not to handle this search, it
6989 should just return nil to give other functions a chance. If it
6990 does handle the search, it must return a non-nil value to keep
6991 other functions from trying.
6993 Each function can access the current prefix argument through the
6994 variable `current-prefix-argument'. Note that a single prefix is
6995 used to force opening a link in Emacs, so it may be good to only
6996 use a numeric or double prefix to guide the search function.
6998 In case this is needed, a function in this hook can also restore
6999 the window configuration before `org-open-at-point' was called using:
7001 (set-window-configuration org-window-config-before-follow-link)")
7003 (defun org-link-search (s &optional type avoid-pos)
7004 "Search for a link search option.
7005 If S is surrounded by forward slashes, it is interpreted as a
7006 regular expression. In org-mode files, this will create an `org-occur'
7007 sparse tree. In ordinary files, `occur' will be used to list matches.
7008 If the current buffer is in `dired-mode', grep will be used to search
7009 in all files. If AVOID-POS is given, ignore matches near that position."
7010 (let ((case-fold-search t)
7011 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
7012 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
7013 (append '(("") (" ") ("\t") ("\n"))
7014 org-emphasis-alist)
7015 "\\|") "\\)"))
7016 (pos (point))
7017 (pre nil) (post nil)
7018 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
7019 (cond
7020 ;; First check if there are any special
7021 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
7022 ;; Now try the builtin stuff
7023 ((save-excursion
7024 (goto-char (point-min))
7025 (and
7026 (re-search-forward
7027 (concat "<<" (regexp-quote s0) ">>") nil t)
7028 (setq type 'dedicated
7029 pos (match-beginning 0))))
7030 ;; There is an exact target for this
7031 (goto-char pos))
7032 ((string-match "^/\\(.*\\)/$" s)
7033 ;; A regular expression
7034 (cond
7035 ((org-mode-p)
7036 (org-occur (match-string 1 s)))
7037 ;;((eq major-mode 'dired-mode)
7038 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
7039 (t (org-do-occur (match-string 1 s)))))
7041 ;; A normal search strings
7042 (when (equal (string-to-char s) ?*)
7043 ;; Anchor on headlines, post may include tags.
7044 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
7045 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
7046 s (substring s 1)))
7047 (remove-text-properties
7048 0 (length s)
7049 '(face nil mouse-face nil keymap nil fontified nil) s)
7050 ;; Make a series of regular expressions to find a match
7051 (setq words (org-split-string s "[ \n\r\t]+")
7053 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
7054 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
7055 "\\)" markers)
7056 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
7057 re2a (concat "[ \t\r\n]" re2a_)
7058 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
7059 re4 (concat "[^a-zA-Z_]" re4_)
7061 re1 (concat pre re2 post)
7062 re3 (concat pre (if pre re4_ re4) post)
7063 re5 (concat pre ".*" re4)
7064 re2 (concat pre re2)
7065 re2a (concat pre (if pre re2a_ re2a))
7066 re4 (concat pre (if pre re4_ re4))
7067 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7068 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7069 re5 "\\)"
7071 (cond
7072 ((eq type 'org-occur) (org-occur reall))
7073 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7074 (t (goto-char (point-min))
7075 (setq type 'fuzzy)
7076 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
7077 (org-search-not-self 1 re1 nil t)
7078 (org-search-not-self 1 re2 nil t)
7079 (org-search-not-self 1 re2a nil t)
7080 (org-search-not-self 1 re3 nil t)
7081 (org-search-not-self 1 re4 nil t)
7082 (org-search-not-self 1 re5 nil t)
7084 (goto-char (match-beginning 1))
7085 (goto-char pos)
7086 (error "No match")))))
7088 ;; Normal string-search
7089 (goto-char (point-min))
7090 (if (search-forward s nil t)
7091 (goto-char (match-beginning 0))
7092 (error "No match"))))
7093 (and (org-mode-p) (org-show-context 'link-search))
7094 type))
7096 (defun org-search-not-self (group &rest args)
7097 "Execute `re-search-forward', but only accept matches that do not
7098 enclose the position of `org-open-link-marker'."
7099 (let ((m org-open-link-marker))
7100 (catch 'exit
7101 (while (apply 're-search-forward args)
7102 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
7103 (goto-char (match-end group))
7104 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
7105 (> (match-beginning 0) (marker-position m))
7106 (< (match-end 0) (marker-position m)))
7107 (save-match-data
7108 (or (not (org-in-regexp
7109 org-bracket-link-analytic-regexp 1))
7110 (not (match-end 4)) ; no description
7111 (and (<= (match-beginning 4) (point))
7112 (>= (match-end 4) (point))))))
7113 (throw 'exit (point))))))))
7115 (defun org-get-buffer-for-internal-link (buffer)
7116 "Return a buffer to be used for displaying the link target of internal links."
7117 (cond
7118 ((not org-display-internal-link-with-indirect-buffer)
7119 buffer)
7120 ((string-match "(Clone)$" (buffer-name buffer))
7121 (message "Buffer is already a clone, not making another one")
7122 ;; we also do not modify visibility in this case
7123 buffer)
7124 (t ; make a new indirect buffer for displaying the link
7125 (let* ((bn (buffer-name buffer))
7126 (ibn (concat bn "(Clone)"))
7127 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
7128 (with-current-buffer ib (org-overview))
7129 ib))))
7131 (defun org-do-occur (regexp &optional cleanup)
7132 "Call the Emacs command `occur'.
7133 If CLEANUP is non-nil, remove the printout of the regular expression
7134 in the *Occur* buffer. This is useful if the regex is long and not useful
7135 to read."
7136 (occur regexp)
7137 (when cleanup
7138 (let ((cwin (selected-window)) win beg end)
7139 (when (setq win (get-buffer-window "*Occur*"))
7140 (select-window win))
7141 (goto-char (point-min))
7142 (when (re-search-forward "match[a-z]+" nil t)
7143 (setq beg (match-end 0))
7144 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7145 (setq end (1- (match-beginning 0)))))
7146 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
7147 (goto-char (point-min))
7148 (select-window cwin))))
7150 ;;; The mark ring for links jumps
7152 (defvar org-mark-ring nil
7153 "Mark ring for positions before jumps in Org-mode.")
7154 (defvar org-mark-ring-last-goto nil
7155 "Last position in the mark ring used to go back.")
7156 ;; Fill and close the ring
7157 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7158 (loop for i from 1 to org-mark-ring-length do
7159 (push (make-marker) org-mark-ring))
7160 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7161 org-mark-ring)
7163 (defun org-mark-ring-push (&optional pos buffer)
7164 "Put the current position or POS into the mark ring and rotate it."
7165 (interactive)
7166 (setq pos (or pos (point)))
7167 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7168 (move-marker (car org-mark-ring)
7169 (or pos (point))
7170 (or buffer (current-buffer)))
7171 (message "%s"
7172 (substitute-command-keys
7173 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7175 (defun org-mark-ring-goto (&optional n)
7176 "Jump to the previous position in the mark ring.
7177 With prefix arg N, jump back that many stored positions. When
7178 called several times in succession, walk through the entire ring.
7179 Org-mode commands jumping to a different position in the current file,
7180 or to another Org-mode file, automatically push the old position
7181 onto the ring."
7182 (interactive "p")
7183 (let (p m)
7184 (if (eq last-command this-command)
7185 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7186 (setq p org-mark-ring))
7187 (setq org-mark-ring-last-goto p)
7188 (setq m (car p))
7189 (switch-to-buffer (marker-buffer m))
7190 (goto-char m)
7191 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
7193 (defun org-remove-angle-brackets (s)
7194 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7195 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7197 (defun org-add-angle-brackets (s)
7198 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7199 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7201 (defun org-remove-double-quotes (s)
7202 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
7203 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
7206 ;;; Following specific links
7208 (defun org-follow-timestamp-link ()
7209 (cond
7210 ((org-at-date-range-p t)
7211 (let ((org-agenda-start-on-weekday)
7212 (t1 (match-string 1))
7213 (t2 (match-string 2)))
7214 (setq t1 (time-to-days (org-time-string-to-time t1))
7215 t2 (time-to-days (org-time-string-to-time t2)))
7216 (org-agenda-list nil t1 (1+ (- t2 t1)))))
7217 ((org-at-timestamp-p t)
7218 (org-agenda-list nil (time-to-days (org-time-string-to-time
7219 (substring (match-string 1) 0 10)))
7221 (t (error "This should not happen"))))
7224 ;;; Following file links
7225 (defvar org-wait nil)
7226 (defun org-open-file (path &optional in-emacs line search)
7227 "Open the file at PATH.
7228 First, this expands any special file name abbreviations. Then the
7229 configuration variable `org-file-apps' is checked if it contains an
7230 entry for this file type, and if yes, the corresponding command is launched.
7232 If no application is found, Emacs simply visits the file.
7234 With optional prefix argument IN-EMACS, Emacs will visit the file.
7235 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
7236 and o use an external application to visit the file.
7238 Optional LINE specifies a line to go to, optional SEARCH a string to
7239 search for. If LINE or SEARCH is given, the file will always be
7240 opened in Emacs.
7241 If the file does not exist, an error is thrown."
7242 (setq in-emacs (or in-emacs line search))
7243 (let* ((file (if (equal path "")
7244 buffer-file-name
7245 (substitute-in-file-name (expand-file-name path))))
7246 (apps (append org-file-apps (org-default-apps)))
7247 (remp (and (assq 'remote apps) (org-file-remote-p file)))
7248 (dirp (if remp nil (file-directory-p file)))
7249 (file (if (and dirp org-open-directory-means-index-dot-org)
7250 (concat (file-name-as-directory file) "index.org")
7251 file))
7252 (a-m-a-p (assq 'auto-mode apps))
7253 (dfile (downcase file))
7254 (old-buffer (current-buffer))
7255 (old-pos (point))
7256 (old-mode major-mode)
7257 ext cmd)
7258 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7259 (setq ext (match-string 1 dfile))
7260 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7261 (setq ext (match-string 1 dfile))))
7262 (cond
7263 ((equal in-emacs '(16))
7264 (setq cmd (cdr (assoc 'system apps))))
7265 (in-emacs (setq cmd 'emacs))
7267 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
7268 (and dirp (cdr (assoc 'directory apps)))
7269 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
7270 'string-match)
7271 (cdr (assoc ext apps))
7272 (cdr (assoc t apps))))))
7273 (when (eq cmd 'system)
7274 (setq cmd (cdr (assoc 'system apps))))
7275 (when (eq cmd 'default)
7276 (setq cmd (cdr (assoc t apps))))
7277 (when (eq cmd 'mailcap)
7278 (require 'mailcap)
7279 (mailcap-parse-mailcaps)
7280 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7281 (command (mailcap-mime-info mime-type)))
7282 (if (stringp command)
7283 (setq cmd command)
7284 (setq cmd 'emacs))))
7285 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
7286 (not (file-exists-p file))
7287 (not org-open-non-existing-files))
7288 (error "No such file: %s" file))
7289 (cond
7290 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7291 ;; Remove quotes around the file name - we'll use shell-quote-argument.
7292 (while (string-match "['\"]%s['\"]" cmd)
7293 (setq cmd (replace-match "%s" t t cmd)))
7294 (while (string-match "%s" cmd)
7295 (setq cmd (replace-match
7296 (save-match-data
7297 (shell-quote-argument
7298 (convert-standard-filename file)))
7299 t t cmd)))
7300 (save-window-excursion
7301 (start-process-shell-command cmd nil cmd)
7302 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
7304 ((or (stringp cmd)
7305 (eq cmd 'emacs))
7306 (funcall (cdr (assq 'file org-link-frame-setup)) file)
7307 (widen)
7308 (if line (goto-line line)
7309 (if search (org-link-search search))))
7310 ((consp cmd)
7311 (let ((file (convert-standard-filename file)))
7312 (eval cmd)))
7313 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7314 (and (org-mode-p) (eq old-mode 'org-mode)
7315 (or (not (equal old-buffer (current-buffer)))
7316 (not (equal old-pos (point))))
7317 (org-mark-ring-push old-pos old-buffer))))
7319 (defun org-default-apps ()
7320 "Return the default applications for this operating system."
7321 (cond
7322 ((eq system-type 'darwin)
7323 org-file-apps-defaults-macosx)
7324 ((eq system-type 'windows-nt)
7325 org-file-apps-defaults-windowsnt)
7326 (t org-file-apps-defaults-gnu)))
7328 (defun org-apps-regexp-alist (list &optional add-auto-mode)
7329 "Convert extensions to regular expressions in the cars of LIST.
7330 Also, weed out any non-string entries, because the return value is used
7331 only for regexp matching.
7332 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
7333 point to the symbol `emacs', indicating that the file should
7334 be opened in Emacs."
7335 (append
7336 (delq nil
7337 (mapcar (lambda (x)
7338 (if (not (stringp (car x)))
7340 (if (string-match "\\W" (car x))
7342 (cons (concat "\\." (car x) "\\'") (cdr x)))))
7343 list))
7344 (if add-auto-mode
7345 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
7347 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
7348 (defun org-file-remote-p (file)
7349 "Test whether FILE specifies a location on a remote system.
7350 Return non-nil if the location is indeed remote.
7352 For example, the filename \"/user@host:/foo\" specifies a location
7353 on the system \"/user@host:\"."
7354 (cond ((fboundp 'file-remote-p)
7355 (file-remote-p file))
7356 ((fboundp 'tramp-handle-file-remote-p)
7357 (tramp-handle-file-remote-p file))
7358 ((and (boundp 'ange-ftp-name-format)
7359 (string-match (car ange-ftp-name-format) file))
7361 (t nil)))
7364 ;;;; Refiling
7366 (defun org-get-org-file ()
7367 "Read a filename, with default directory `org-directory'."
7368 (let ((default (or org-default-notes-file remember-data-file)))
7369 (read-file-name (format "File name [%s]: " default)
7370 (file-name-as-directory org-directory)
7371 default)))
7373 (defun org-notes-order-reversed-p ()
7374 "Check if the current file should receive notes in reversed order."
7375 (cond
7376 ((not org-reverse-note-order) nil)
7377 ((eq t org-reverse-note-order) t)
7378 ((not (listp org-reverse-note-order)) nil)
7379 (t (catch 'exit
7380 (let ((all org-reverse-note-order)
7381 entry)
7382 (while (setq entry (pop all))
7383 (if (string-match (car entry) buffer-file-name)
7384 (throw 'exit (cdr entry))))
7385 nil)))))
7387 (defvar org-refile-target-table nil
7388 "The list of refile targets, created by `org-refile'.")
7390 (defvar org-agenda-new-buffers nil
7391 "Buffers created to visit agenda files.")
7393 (defun org-get-refile-targets (&optional default-buffer)
7394 "Produce a table with refile targets."
7395 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
7396 targets txt re files f desc descre)
7397 (with-current-buffer (or default-buffer (current-buffer))
7398 (while (setq entry (pop entries))
7399 (setq files (car entry) desc (cdr entry))
7400 (cond
7401 ((null files) (setq files (list (current-buffer))))
7402 ((eq files 'org-agenda-files)
7403 (setq files (org-agenda-files 'unrestricted)))
7404 ((and (symbolp files) (fboundp files))
7405 (setq files (funcall files)))
7406 ((and (symbolp files) (boundp files))
7407 (setq files (symbol-value files))))
7408 (if (stringp files) (setq files (list files)))
7409 (cond
7410 ((eq (car desc) :tag)
7411 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
7412 ((eq (car desc) :todo)
7413 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
7414 ((eq (car desc) :regexp)
7415 (setq descre (cdr desc)))
7416 ((eq (car desc) :level)
7417 (setq descre (concat "^\\*\\{" (number-to-string
7418 (if org-odd-levels-only
7419 (1- (* 2 (cdr desc)))
7420 (cdr desc)))
7421 "\\}[ \t]")))
7422 ((eq (car desc) :maxlevel)
7423 (setq descre (concat "^\\*\\{1," (number-to-string
7424 (if org-odd-levels-only
7425 (1- (* 2 (cdr desc)))
7426 (cdr desc)))
7427 "\\}[ \t]")))
7428 (t (error "Bad refiling target description %s" desc)))
7429 (while (setq f (pop files))
7430 (save-excursion
7431 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
7432 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
7433 (save-excursion
7434 (save-restriction
7435 (widen)
7436 (goto-char (point-min))
7437 (while (re-search-forward descre nil t)
7438 (goto-char (point-at-bol))
7439 (when (looking-at org-complex-heading-regexp)
7440 (setq txt (org-link-display-format (match-string 4))
7441 re (concat "^" (regexp-quote
7442 (buffer-substring (match-beginning 1)
7443 (match-end 4)))))
7444 (if (match-end 5) (setq re (concat re "[ \t]+"
7445 (regexp-quote
7446 (match-string 5)))))
7447 (setq re (concat re "[ \t]*$"))
7448 (when org-refile-use-outline-path
7449 (setq txt (mapconcat 'org-protect-slash
7450 (append
7451 (if (eq org-refile-use-outline-path 'file)
7452 (list (file-name-nondirectory
7453 (buffer-file-name (buffer-base-buffer))))
7454 (if (eq org-refile-use-outline-path 'full-file-path)
7455 (list (buffer-file-name (buffer-base-buffer)))))
7456 (org-get-outline-path)
7457 (list txt))
7458 "/")))
7459 (push (list txt f re (point)) targets))
7460 (goto-char (point-at-eol))))))))
7461 (nreverse targets))))
7463 (defun org-protect-slash (s)
7464 (while (string-match "/" s)
7465 (setq s (replace-match "\\" t t s)))
7468 (defun org-get-outline-path ()
7469 "Return the outline path to the current entry, as a list."
7470 (let (rtn)
7471 (save-excursion
7472 (while (org-up-heading-safe)
7473 (when (looking-at org-complex-heading-regexp)
7474 (push (org-match-string-no-properties 4) rtn)))
7475 rtn)))
7477 (defvar org-refile-history nil
7478 "History for refiling operations.")
7480 (defun org-refile (&optional goto default-buffer)
7481 "Move the entry at point to another heading.
7482 The list of target headings is compiled using the information in
7483 `org-refile-targets', which see. This list is created before each use
7484 and will therefore always be up-to-date.
7486 At the target location, the entry is filed as a subitem of the target heading.
7487 Depending on `org-reverse-note-order', the new subitem will either be the
7488 first or the last subitem.
7490 If there is an active region, all entries in that region will be moved.
7491 However, the region must fulfil the requirement that the first heading
7492 is the first one sets the top-level of the moved text - at most siblings
7493 below it are allowed.
7495 With prefix arg GOTO, the command will only visit the target location,
7496 not actually move anything.
7497 With a double prefix `C-u C-u', go to the location where the last refiling
7498 operation has put the subtree."
7499 (interactive "P")
7500 (let* ((cbuf (current-buffer))
7501 (regionp (org-region-active-p))
7502 (region-start (and regionp (region-beginning)))
7503 (region-end (and regionp (region-end)))
7504 (region-length (and regionp (- region-end region-start)))
7505 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7506 pos it nbuf file re level reversed)
7507 (when regionp (goto-char region-start)
7508 (unless (org-kill-is-subtree-p
7509 (buffer-substring region-start region-end))
7510 (error "The region is not a (sequence of) subtree(s)")))
7511 (if (equal goto '(16))
7512 (org-refile-goto-last-stored)
7513 (when (setq it (org-refile-get-location
7514 (if goto "Goto: " "Refile to: ") default-buffer))
7515 (setq file (nth 1 it)
7516 re (nth 2 it)
7517 pos (nth 3 it))
7518 (setq nbuf (or (find-buffer-visiting file)
7519 (find-file-noselect file)))
7520 (if goto
7521 (progn
7522 (switch-to-buffer nbuf)
7523 (goto-char pos)
7524 (org-show-context 'org-goto))
7525 (if regionp
7526 (progn
7527 (kill-new (buffer-substring region-start region-end))
7528 (org-save-markers-in-region region-start region-end))
7529 (org-copy-subtree 1 nil t))
7530 (save-excursion
7531 (set-buffer (setq nbuf (or (find-buffer-visiting file)
7532 (find-file-noselect file))))
7533 (setq reversed (org-notes-order-reversed-p))
7534 (save-excursion
7535 (save-restriction
7536 (widen)
7537 (goto-char pos)
7538 (looking-at outline-regexp)
7539 (setq level (org-get-valid-level (funcall outline-level) 1))
7540 (goto-char
7541 (if reversed
7542 (or (outline-next-heading) (point-max))
7543 (or (save-excursion (outline-get-next-sibling))
7544 (org-end-of-subtree t t)
7545 (point-max))))
7546 (if (not (bolp)) (newline))
7547 (bookmark-set "org-refile-last-stored")
7548 (org-paste-subtree level))))
7549 (if regionp
7550 (delete-region (point) (+ (point) region-length))
7551 (org-cut-subtree))
7552 (setq org-markers-to-move nil)
7553 (message "Refiled to \"%s\"" (car it)))))))
7555 (defun org-refile-goto-last-stored ()
7556 "Go to the location where the last refile was stored."
7557 (interactive)
7558 (bookmark-jump "org-refile-last-stored")
7559 (message "This is the location of the last refile"))
7561 (defun org-refile-get-location (&optional prompt default-buffer)
7562 "Prompt the user for a refile location, using PROMPT."
7563 (let ((org-refile-targets org-refile-targets)
7564 (org-refile-use-outline-path org-refile-use-outline-path))
7565 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
7566 (unless org-refile-target-table
7567 (error "No refile targets"))
7568 (let* ((cbuf (current-buffer))
7569 (cfunc (if (and org-refile-use-outline-path
7570 org-outline-path-complete-in-steps)
7571 'org-olpath-completing-read
7572 'org-ido-completing-read))
7573 (extra (if org-refile-use-outline-path "/" ""))
7574 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7575 (fname (and filename (file-truename filename)))
7576 (tbl (mapcar
7577 (lambda (x)
7578 (if (not (equal fname (file-truename (nth 1 x))))
7579 (cons (concat (car x) extra " ("
7580 (file-name-nondirectory (nth 1 x)) ")")
7581 (cdr x))
7582 (cons (concat (car x) extra) (cdr x))))
7583 org-refile-target-table))
7584 (completion-ignore-case t))
7585 (assoc (funcall cfunc prompt tbl nil t nil 'org-refile-history)
7586 tbl)))
7588 (defun org-olpath-completing-read (prompt collection &rest args)
7589 "Read an outline path like a file name."
7590 (let ((thetable collection))
7591 (apply
7592 'org-ido-completing-read prompt
7593 (lambda (string predicate &optional flag)
7594 (let (rtn r s f (l (length string)))
7595 (cond
7596 ((eq flag nil)
7597 ;; try completion
7598 (try-completion string thetable))
7599 ((eq flag t)
7600 ;; all-completions
7601 (setq rtn (all-completions string thetable predicate))
7602 (mapcar
7603 (lambda (x)
7604 (setq r (substring x l))
7605 (if (string-match " ([^)]*)$" x)
7606 (setq f (match-string 0 x))
7607 (setq f ""))
7608 (if (string-match "/" r)
7609 (concat string (substring r 0 (match-end 0)) f)
7611 rtn))
7612 ((eq flag 'lambda)
7613 ;; exact match?
7614 (assoc string thetable)))
7616 args)))
7618 ;;;; Dynamic blocks
7620 (defun org-find-dblock (name)
7621 "Find the first dynamic block with name NAME in the buffer.
7622 If not found, stay at current position and return nil."
7623 (let (pos)
7624 (save-excursion
7625 (goto-char (point-min))
7626 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
7627 nil t)
7628 (match-beginning 0))))
7629 (if pos (goto-char pos))
7630 pos))
7632 (defconst org-dblock-start-re
7633 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
7634 "Matches the startline of a dynamic block, with parameters.")
7636 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
7637 "Matches the end of a dyhamic block.")
7639 (defun org-create-dblock (plist)
7640 "Create a dynamic block section, with parameters taken from PLIST.
7641 PLIST must containe a :name entry which is used as name of the block."
7642 (unless (bolp) (newline))
7643 (let ((name (plist-get plist :name)))
7644 (insert "#+BEGIN: " name)
7645 (while plist
7646 (if (eq (car plist) :name)
7647 (setq plist (cddr plist))
7648 (insert " " (prin1-to-string (pop plist)))))
7649 (insert "\n\n#+END:\n")
7650 (beginning-of-line -2)))
7652 (defun org-prepare-dblock ()
7653 "Prepare dynamic block for refresh.
7654 This empties the block, puts the cursor at the insert position and returns
7655 the property list including an extra property :name with the block name."
7656 (unless (looking-at org-dblock-start-re)
7657 (error "Not at a dynamic block"))
7658 (let* ((begdel (1+ (match-end 0)))
7659 (name (org-no-properties (match-string 1)))
7660 (params (append (list :name name)
7661 (read (concat "(" (match-string 3) ")")))))
7662 (unless (re-search-forward org-dblock-end-re nil t)
7663 (error "Dynamic block not terminated"))
7664 (setq params
7665 (append params
7666 (list :content (buffer-substring
7667 begdel (match-beginning 0)))))
7668 (delete-region begdel (match-beginning 0))
7669 (goto-char begdel)
7670 (open-line 1)
7671 params))
7673 (defun org-map-dblocks (&optional command)
7674 "Apply COMMAND to all dynamic blocks in the current buffer.
7675 If COMMAND is not given, use `org-update-dblock'."
7676 (let ((cmd (or command 'org-update-dblock))
7677 pos)
7678 (save-excursion
7679 (goto-char (point-min))
7680 (while (re-search-forward org-dblock-start-re nil t)
7681 (goto-char (setq pos (match-beginning 0)))
7682 (condition-case nil
7683 (funcall cmd)
7684 (error (message "Error during update of dynamic block")))
7685 (goto-char pos)
7686 (unless (re-search-forward org-dblock-end-re nil t)
7687 (error "Dynamic block not terminated"))))))
7689 (defun org-dblock-update (&optional arg)
7690 "User command for updating dynamic blocks.
7691 Update the dynamic block at point. With prefix ARG, update all dynamic
7692 blocks in the buffer."
7693 (interactive "P")
7694 (if arg
7695 (org-update-all-dblocks)
7696 (or (looking-at org-dblock-start-re)
7697 (org-beginning-of-dblock))
7698 (org-update-dblock)))
7700 (defun org-update-dblock ()
7701 "Update the dynamic block at point
7702 This means to empty the block, parse for parameters and then call
7703 the correct writing function."
7704 (save-window-excursion
7705 (let* ((pos (point))
7706 (line (org-current-line))
7707 (params (org-prepare-dblock))
7708 (name (plist-get params :name))
7709 (cmd (intern (concat "org-dblock-write:" name))))
7710 (message "Updating dynamic block `%s' at line %d..." name line)
7711 (funcall cmd params)
7712 (message "Updating dynamic block `%s' at line %d...done" name line)
7713 (goto-char pos))))
7715 (defun org-beginning-of-dblock ()
7716 "Find the beginning of the dynamic block at point.
7717 Error if there is no scuh block at point."
7718 (let ((pos (point))
7719 beg)
7720 (end-of-line 1)
7721 (if (and (re-search-backward org-dblock-start-re nil t)
7722 (setq beg (match-beginning 0))
7723 (re-search-forward org-dblock-end-re nil t)
7724 (> (match-end 0) pos))
7725 (goto-char beg)
7726 (goto-char pos)
7727 (error "Not in a dynamic block"))))
7729 (defun org-update-all-dblocks ()
7730 "Update all dynamic blocks in the buffer.
7731 This function can be used in a hook."
7732 (when (org-mode-p)
7733 (org-map-dblocks 'org-update-dblock)))
7736 ;;;; Completion
7738 (defconst org-additional-option-like-keywords
7739 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
7740 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
7741 "BEGIN_EXAMPLE" "END_EXAMPLE"
7742 "BEGIN_QUOTE" "END_QUOTE"
7743 "BEGIN_VERSE" "END_VERSE"
7744 "BEGIN_SRC" "END_SRC"
7745 "CAPTION" "LABEL" "ATTR_HTML" "ATTR_LaTeX"))
7747 (defcustom org-structure-template-alist
7749 ("s" "#+begin_src ?\n\n#+end_src"
7750 "<src lang=\"?\">\n\n</src>")
7751 ("e" "#+begin_example\n?\n#+end_example"
7752 "<example>\n?\n</example>")
7753 ("q" "#+begin_quote\n?\n#+end_quote"
7754 "<quote>\n?\n</quote>")
7755 ("v" "#+begin_verse\n?\n#+end_verse"
7756 "<verse>\n?\n/verse>")
7757 ("l" "#+begin_latex\n?\n#+end_latex"
7758 "<literal style=\"latex\">\n?\n</literal>")
7759 ("L" "#+latex: "
7760 "<literal style=\"latex\">?</literal>")
7761 ("h" "#+begin_html\n?\n#+end_html"
7762 "<literal style=\"html\">\n?\n</literal>")
7763 ("H" "#+html: "
7764 "<literal style=\"html\">?</literal>")
7765 ("a" "#+begin_ascii\n?\n#+end_ascii")
7766 ("A" "#+ascii: ")
7767 ("i" "#+include %file ?"
7768 "<include file=%file markup=\"?\">")
7770 "Structure completion elements.
7771 This is a list of abbreviation keys and values. The value gets inserted
7772 it you type @samp{.} followed by the key and then the completion key,
7773 usually `M-TAB'. %file will be replaced by a file name after prompting
7774 for the file uning completion.
7775 There are two templates for each key, the first uses the original Org syntax,
7776 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
7777 the default when the /org-mtags.el/ module has been loaded. See also the
7778 variable `org-mtags-prefer-muse-templates'.
7779 This is an experimental feature, it is undecided if it is going to stay in."
7780 :group 'org-completion
7781 :type '(repeat
7782 (string :tag "Key")
7783 (string :tag "Template")
7784 (string :tag "Muse Template")))
7786 (defun org-try-structure-completion ()
7787 "Try to complete a structure template before point.
7788 This looks for strings like \"<e\" on an otherwise empty line and
7789 expands them."
7790 (let ((l (buffer-substring (point-at-bol) (point)))
7792 (when (and (looking-at "[ \t]*$")
7793 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
7794 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
7795 (org-complete-expand-structure-template (+ -1 (point-at-bol)
7796 (match-beginning 1)) a)
7797 t)))
7799 (defun org-complete-expand-structure-template (start cell)
7800 "Expand a structure template."
7801 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
7802 (rpl (nth (if musep 2 1) cell)))
7803 (delete-region start (point))
7804 (when (string-match "\\`#\\+" rpl)
7805 (cond
7806 ((bolp))
7807 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
7808 (delete-region (point-at-bol) (point)))
7809 (t (newline))))
7810 (setq start (point))
7811 (if (string-match "%file" rpl)
7812 (setq rpl (replace-match
7813 (concat
7814 "\""
7815 (save-match-data
7816 (abbreviate-file-name (read-file-name "Include file: ")))
7817 "\"")
7818 t t rpl)))
7819 (insert rpl)
7820 (if (re-search-backward "\\?" start t) (delete-char 1))))
7823 (defun org-complete (&optional arg)
7824 "Perform completion on word at point.
7825 At the beginning of a headline, this completes TODO keywords as given in
7826 `org-todo-keywords'.
7827 If the current word is preceded by a backslash, completes the TeX symbols
7828 that are supported for HTML support.
7829 If the current word is preceded by \"#+\", completes special words for
7830 setting file options.
7831 In the line after \"#+STARTUP:, complete valid keywords.\"
7832 At all other locations, this simply calls the value of
7833 `org-completion-fallback-command'."
7834 (interactive "P")
7835 (org-without-partial-completion
7836 (catch 'exit
7837 (let* ((a nil)
7838 (end (point))
7839 (beg1 (save-excursion
7840 (skip-chars-backward (org-re "[:alnum:]_@"))
7841 (point)))
7842 (beg (save-excursion
7843 (skip-chars-backward "a-zA-Z0-9_:$")
7844 (point)))
7845 (confirm (lambda (x) (stringp (car x))))
7846 (searchhead (equal (char-before beg) ?*))
7847 (struct
7848 (when (and (member (char-before beg1) '(?. ?<))
7849 (setq a (assoc (buffer-substring beg1 (point))
7850 org-structure-template-alist)))
7851 (org-complete-expand-structure-template (1- beg1) a)
7852 (throw 'exit t)))
7853 (tag (and (equal (char-before beg1) ?:)
7854 (equal (char-after (point-at-bol)) ?*)))
7855 (prop (and (equal (char-before beg1) ?:)
7856 (not (equal (char-after (point-at-bol)) ?*))))
7857 (texp (equal (char-before beg) ?\\))
7858 (link (equal (char-before beg) ?\[))
7859 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
7860 beg)
7861 "#+"))
7862 (startup (string-match "^#\\+STARTUP:.*"
7863 (buffer-substring (point-at-bol) (point))))
7864 (completion-ignore-case opt)
7865 (type nil)
7866 (tbl nil)
7867 (table (cond
7868 (opt
7869 (setq type :opt)
7870 (require 'org-exp)
7871 (append
7872 (mapcar
7873 (lambda (x)
7874 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
7875 (cons (match-string 2 x) (match-string 1 x)))
7876 (org-split-string (org-get-current-options) "\n"))
7877 (mapcar 'list org-additional-option-like-keywords)))
7878 (startup
7879 (setq type :startup)
7880 org-startup-options)
7881 (link (append org-link-abbrev-alist-local
7882 org-link-abbrev-alist))
7883 (texp
7884 (setq type :tex)
7885 org-html-entities)
7886 ((string-match "\\`\\*+[ \t]+\\'"
7887 (buffer-substring (point-at-bol) beg))
7888 (setq type :todo)
7889 (mapcar 'list org-todo-keywords-1))
7890 (searchhead
7891 (setq type :searchhead)
7892 (save-excursion
7893 (goto-char (point-min))
7894 (while (re-search-forward org-todo-line-regexp nil t)
7895 (push (list
7896 (org-make-org-heading-search-string
7897 (match-string 3) t))
7898 tbl)))
7899 tbl)
7900 (tag (setq type :tag beg beg1)
7901 (or org-tag-alist (org-get-buffer-tags)))
7902 (prop (setq type :prop beg beg1)
7903 (mapcar 'list (org-buffer-property-keys nil t t)))
7904 (t (progn
7905 (call-interactively org-completion-fallback-command)
7906 (throw 'exit nil)))))
7907 (pattern (buffer-substring-no-properties beg end))
7908 (completion (try-completion pattern table confirm)))
7909 (cond ((eq completion t)
7910 (if (not (assoc (upcase pattern) table))
7911 (message "Already complete")
7912 (if (and (equal type :opt)
7913 (not (member (car (assoc (upcase pattern) table))
7914 org-additional-option-like-keywords)))
7915 (insert (substring (cdr (assoc (upcase pattern) table))
7916 (length pattern)))
7917 (if (memq type '(:tag :prop)) (insert ":")))))
7918 ((null completion)
7919 (message "Can't find completion for \"%s\"" pattern)
7920 (ding))
7921 ((not (string= pattern completion))
7922 (delete-region beg end)
7923 (if (string-match " +$" completion)
7924 (setq completion (replace-match "" t t completion)))
7925 (insert completion)
7926 (if (get-buffer-window "*Completions*")
7927 (delete-window (get-buffer-window "*Completions*")))
7928 (if (assoc completion table)
7929 (if (eq type :todo) (insert " ")
7930 (if (memq type '(:tag :prop)) (insert ":"))))
7931 (if (and (equal type :opt) (assoc completion table))
7932 (message "%s" (substitute-command-keys
7933 "Press \\[org-complete] again to insert example settings"))))
7935 (message "Making completion list...")
7936 (let ((list (sort (all-completions pattern table confirm)
7937 'string<)))
7938 (with-output-to-temp-buffer "*Completions*"
7939 (condition-case nil
7940 ;; Protection needed for XEmacs and emacs 21
7941 (display-completion-list list pattern)
7942 (error (display-completion-list list)))))
7943 (message "Making completion list...%s" "done")))))))
7945 ;;;; TODO, DEADLINE, Comments
7947 (defun org-toggle-comment ()
7948 "Change the COMMENT state of an entry."
7949 (interactive)
7950 (save-excursion
7951 (org-back-to-heading)
7952 (let (case-fold-search)
7953 (if (looking-at (concat outline-regexp
7954 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
7955 (replace-match "" t t nil 1)
7956 (if (looking-at outline-regexp)
7957 (progn
7958 (goto-char (match-end 0))
7959 (insert org-comment-string " ")))))))
7961 (defvar org-last-todo-state-is-todo nil
7962 "This is non-nil when the last TODO state change led to a TODO state.
7963 If the last change removed the TODO tag or switched to DONE, then
7964 this is nil.")
7966 (defvar org-setting-tags nil) ; dynamically skiped
7968 (defun org-parse-local-options (string var)
7969 "Parse STRING for startup setting relevant for variable VAR."
7970 (let ((rtn (symbol-value var))
7971 e opts)
7972 (save-match-data
7973 (if (or (not string) (not (string-match "\\S-" string)))
7975 (setq opts (delq nil (mapcar (lambda (x)
7976 (setq e (assoc x org-startup-options))
7977 (if (eq (nth 1 e) var) e nil))
7978 (org-split-string string "[ \t]+"))))
7979 (if (not opts)
7981 (setq rtn nil)
7982 (while (setq e (pop opts))
7983 (if (not (nth 3 e))
7984 (setq rtn (nth 2 e))
7985 (if (not (listp rtn)) (setq rtn nil))
7986 (push (nth 2 e) rtn)))
7987 rtn)))))
7989 (defvar org-blocker-hook nil
7990 "Hook for functions that are allowed to block a state change.
7992 Each function gets as its single argument a property list, see
7993 `org-trigger-hook' for more information about this list.
7995 If any of the functions in this hook returns nil, the state change
7996 is blocked.")
7998 (defvar org-trigger-hook nil
7999 "Hook for functions that are triggered by a state change.
8001 Each function gets as its single argument a property list with at least
8002 the following elements:
8004 (:type type-of-change :position pos-at-entry-start
8005 :from old-state :to new-state)
8007 Depending on the type, more properties may be present.
8009 This mechanism is currently implemented for:
8011 TODO state changes
8012 ------------------
8013 :type todo-state-change
8014 :from previous state (keyword as a string), or nil
8015 :to new state (keyword as a string), or nil")
8017 (defvar org-agenda-headline-snapshot-before-repeat)
8018 (defun org-todo (&optional arg)
8019 "Change the TODO state of an item.
8020 The state of an item is given by a keyword at the start of the heading,
8021 like
8022 *** TODO Write paper
8023 *** DONE Call mom
8025 The different keywords are specified in the variable `org-todo-keywords'.
8026 By default the available states are \"TODO\" and \"DONE\".
8027 So for this example: when the item starts with TODO, it is changed to DONE.
8028 When it starts with DONE, the DONE is removed. And when neither TODO nor
8029 DONE are present, add TODO at the beginning of the heading.
8031 With C-u prefix arg, use completion to determine the new state.
8032 With numeric prefix arg, switch to that state.
8034 For calling through lisp, arg is also interpreted in the following way:
8035 'none -> empty state
8036 \"\"(empty string) -> switch to empty state
8037 'done -> switch to DONE
8038 'nextset -> switch to the next set of keywords
8039 'previousset -> switch to the previous set of keywords
8040 \"WAITING\" -> switch to the specified keyword, but only if it
8041 really is a member of `org-todo-keywords'."
8042 (interactive "P")
8043 (save-excursion
8044 (catch 'exit
8045 (org-back-to-heading)
8046 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
8047 (or (looking-at (concat " +" org-todo-regexp " *"))
8048 (looking-at " *"))
8049 (let* ((match-data (match-data))
8050 (startpos (point-at-bol))
8051 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
8052 (org-log-done org-log-done)
8053 (org-log-repeat org-log-repeat)
8054 (org-todo-log-states org-todo-log-states)
8055 (this (match-string 1))
8056 (hl-pos (match-beginning 0))
8057 (head (org-get-todo-sequence-head this))
8058 (ass (assoc head org-todo-kwd-alist))
8059 (interpret (nth 1 ass))
8060 (done-word (nth 3 ass))
8061 (final-done-word (nth 4 ass))
8062 (last-state (or this ""))
8063 (completion-ignore-case t)
8064 (member (member this org-todo-keywords-1))
8065 (tail (cdr member))
8066 (state (cond
8067 ((and org-todo-key-trigger
8068 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
8069 (and (not arg) org-use-fast-todo-selection
8070 (not (eq org-use-fast-todo-selection 'prefix)))))
8071 ;; Use fast selection
8072 (org-fast-todo-selection))
8073 ((and (equal arg '(4))
8074 (or (not org-use-fast-todo-selection)
8075 (not org-todo-key-trigger)))
8076 ;; Read a state with completion
8077 (org-ido-completing-read "State: " (mapcar (lambda(x) (list x))
8078 org-todo-keywords-1)
8079 nil t))
8080 ((eq arg 'right)
8081 (if this
8082 (if tail (car tail) nil)
8083 (car org-todo-keywords-1)))
8084 ((eq arg 'left)
8085 (if (equal member org-todo-keywords-1)
8087 (if this
8088 (nth (- (length org-todo-keywords-1) (length tail) 2)
8089 org-todo-keywords-1)
8090 (org-last org-todo-keywords-1))))
8091 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
8092 (setq arg nil))) ; hack to fall back to cycling
8093 (arg
8094 ;; user or caller requests a specific state
8095 (cond
8096 ((equal arg "") nil)
8097 ((eq arg 'none) nil)
8098 ((eq arg 'done) (or done-word (car org-done-keywords)))
8099 ((eq arg 'nextset)
8100 (or (car (cdr (member head org-todo-heads)))
8101 (car org-todo-heads)))
8102 ((eq arg 'previousset)
8103 (let ((org-todo-heads (reverse org-todo-heads)))
8104 (or (car (cdr (member head org-todo-heads)))
8105 (car org-todo-heads))))
8106 ((car (member arg org-todo-keywords-1)))
8107 ((nth (1- (prefix-numeric-value arg))
8108 org-todo-keywords-1))))
8109 ((null member) (or head (car org-todo-keywords-1)))
8110 ((equal this final-done-word) nil) ;; -> make empty
8111 ((null tail) nil) ;; -> first entry
8112 ((eq interpret 'sequence)
8113 (car tail))
8114 ((memq interpret '(type priority))
8115 (if (eq this-command last-command)
8116 (car tail)
8117 (if (> (length tail) 0)
8118 (or done-word (car org-done-keywords))
8119 nil)))
8120 (t nil)))
8121 (next (if state (concat " " state " ") " "))
8122 (change-plist (list :type 'todo-state-change :from this :to state
8123 :position startpos))
8124 dolog now-done-p)
8125 (when org-blocker-hook
8126 (unless (save-excursion
8127 (save-match-data
8128 (run-hook-with-args-until-failure
8129 'org-blocker-hook change-plist)))
8130 (if (interactive-p)
8131 (error "TODO state change from %s to %s blocked" this state)
8132 ;; fail silently
8133 (message "TODO state change from %s to %s blocked" this state)
8134 (throw 'exit nil))))
8135 (store-match-data match-data)
8136 (replace-match next t t)
8137 (unless (pos-visible-in-window-p hl-pos)
8138 (message "TODO state changed to %s" (org-trim next)))
8139 (unless head
8140 (setq head (org-get-todo-sequence-head state)
8141 ass (assoc head org-todo-kwd-alist)
8142 interpret (nth 1 ass)
8143 done-word (nth 3 ass)
8144 final-done-word (nth 4 ass)))
8145 (when (memq arg '(nextset previousset))
8146 (message "Keyword-Set %d/%d: %s"
8147 (- (length org-todo-sets) -1
8148 (length (memq (assoc state org-todo-sets) org-todo-sets)))
8149 (length org-todo-sets)
8150 (mapconcat 'identity (assoc state org-todo-sets) " ")))
8151 (setq org-last-todo-state-is-todo
8152 (not (member state org-done-keywords)))
8153 (setq now-done-p (and (member state org-done-keywords)
8154 (not (member this org-done-keywords))))
8155 (and logging (org-local-logging logging))
8156 (when (and (or org-todo-log-states org-log-done)
8157 (not (memq arg '(nextset previousset))))
8158 ;; we need to look at recording a time and note
8159 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
8160 (nth 2 (assoc this org-todo-log-states))))
8161 (when (and state
8162 (member state org-not-done-keywords)
8163 (not (member this org-not-done-keywords)))
8164 ;; This is now a todo state and was not one before
8165 ;; If there was a CLOSED time stamp, get rid of it.
8166 (org-add-planning-info nil nil 'closed))
8167 (when (and now-done-p org-log-done)
8168 ;; It is now done, and it was not done before
8169 (org-add-planning-info 'closed (org-current-time))
8170 (if (and (not dolog) (eq 'note org-log-done))
8171 (org-add-log-setup 'done state 'findpos 'note)))
8172 (when (and state dolog)
8173 ;; This is a non-nil state, and we need to log it
8174 (org-add-log-setup 'state state 'findpos dolog)))
8175 ;; Fixup tag positioning
8176 (org-todo-trigger-tag-changes state)
8177 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
8178 (when org-provide-todo-statistics
8179 (org-update-parent-todo-statistics))
8180 (run-hooks 'org-after-todo-state-change-hook)
8181 (if (and arg (not (member state org-done-keywords)))
8182 (setq head (org-get-todo-sequence-head state)))
8183 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
8184 ;; Do we need to trigger a repeat?
8185 (when now-done-p
8186 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
8187 ;; This is for the agenda, take a snapshot of the headline.
8188 (save-match-data
8189 (setq org-agenda-headline-snapshot-before-repeat
8190 (org-get-heading))))
8191 (org-auto-repeat-maybe state))
8192 ;; Fixup cursor location if close to the keyword
8193 (if (and (outline-on-heading-p)
8194 (not (bolp))
8195 (save-excursion (beginning-of-line 1)
8196 (looking-at org-todo-line-regexp))
8197 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
8198 (progn
8199 (goto-char (or (match-end 2) (match-end 1)))
8200 (just-one-space)))
8201 (when org-trigger-hook
8202 (save-excursion
8203 (run-hook-with-args 'org-trigger-hook change-plist)))))))
8205 (defun org-update-parent-todo-statistics ()
8206 "Update any statistics cookie in the parent of the current headline."
8207 (interactive)
8208 (let ((box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
8209 level (cnt-all 0) (cnt-done 0) is-percent kwd)
8210 (catch 'exit
8211 (save-excursion
8212 (setq level (org-up-heading-safe))
8213 (unless (and level
8214 (re-search-forward box-re (point-at-eol) t))
8215 (throw 'exit nil))
8216 (setq is-percent (match-end 2))
8217 (save-match-data
8218 (unless (outline-next-heading) (throw 'exit nil))
8219 (while (looking-at org-todo-line-regexp)
8220 (setq kwd (match-string 2))
8221 (and kwd (setq cnt-all (1+ cnt-all)))
8222 (and (member kwd org-done-keywords)
8223 (setq cnt-done (1+ cnt-done)))
8224 (condition-case nil
8225 (org-forward-same-level 1)
8226 (error (end-of-line 1)))))
8227 (replace-match
8228 (if is-percent
8229 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
8230 (format "[%d/%d]" cnt-done cnt-all)))
8231 (run-hook-with-args 'org-after-todo-statistics-hook
8232 cnt-done (- cnt-all cnt-done))))))
8234 (defvar org-after-todo-statistics-hook nil
8235 "Hook that is called after a TODO statistics cookie has been updated.
8236 Each function is called with two arguments: the number of not-done entries
8237 and the number of done entries.
8239 For example, the following function, when added to this hook, will switch
8240 an entry to DONE when all children are done, and back to TODO when new
8241 entries are set to a TODO status. Note that this hook is only called
8242 when there is a statistics cookie in the headline!
8244 (defun org-summary-todo (n-done n-not-done)
8245 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
8246 (let (org-log-done org-log-states) ; turn off logging
8247 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
8250 (defun org-todo-trigger-tag-changes (state)
8251 "Apply the changes defined in `org-todo-state-tags-triggers'."
8252 (let ((l org-todo-state-tags-triggers)
8253 changes)
8254 (when (or (not state) (equal state ""))
8255 (setq changes (append changes (cdr (assoc "" l)))))
8256 (when (and (stringp state) (> (length state) 0))
8257 (setq changes (append changes (cdr (assoc state l)))))
8258 (when (member state org-not-done-keywords)
8259 (setq changes (append changes (cdr (assoc 'todo l)))))
8260 (when (member state org-done-keywords)
8261 (setq changes (append changes (cdr (assoc 'done l)))))
8262 (dolist (c changes)
8263 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
8265 (defun org-local-logging (value)
8266 "Get logging settings from a property VALUE."
8267 (let* (words w a)
8268 ;; directly set the variables, they are already local.
8269 (setq org-log-done nil
8270 org-log-repeat nil
8271 org-todo-log-states nil)
8272 (setq words (org-split-string value))
8273 (while (setq w (pop words))
8274 (cond
8275 ((setq a (assoc w org-startup-options))
8276 (and (member (nth 1 a) '(org-log-done org-log-repeat))
8277 (set (nth 1 a) (nth 2 a))))
8278 ((setq a (org-extract-log-state-settings w))
8279 (and (member (car a) org-todo-keywords-1)
8280 (push a org-todo-log-states)))))))
8282 (defun org-get-todo-sequence-head (kwd)
8283 "Return the head of the TODO sequence to which KWD belongs.
8284 If KWD is not set, check if there is a text property remembering the
8285 right sequence."
8286 (let (p)
8287 (cond
8288 ((not kwd)
8289 (or (get-text-property (point-at-bol) 'org-todo-head)
8290 (progn
8291 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
8292 nil (point-at-eol)))
8293 (get-text-property p 'org-todo-head))))
8294 ((not (member kwd org-todo-keywords-1))
8295 (car org-todo-keywords-1))
8296 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
8298 (defun org-fast-todo-selection ()
8299 "Fast TODO keyword selection with single keys.
8300 Returns the new TODO keyword, or nil if no state change should occur."
8301 (let* ((fulltable org-todo-key-alist)
8302 (done-keywords org-done-keywords) ;; needed for the faces.
8303 (maxlen (apply 'max (mapcar
8304 (lambda (x)
8305 (if (stringp (car x)) (string-width (car x)) 0))
8306 fulltable)))
8307 (expert nil)
8308 (fwidth (+ maxlen 3 1 3))
8309 (ncol (/ (- (window-width) 4) fwidth))
8310 tg cnt e c tbl
8311 groups ingroup)
8312 (save-window-excursion
8313 (if expert
8314 (set-buffer (get-buffer-create " *Org todo*"))
8315 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
8316 (erase-buffer)
8317 (org-set-local 'org-done-keywords done-keywords)
8318 (setq tbl fulltable cnt 0)
8319 (while (setq e (pop tbl))
8320 (cond
8321 ((equal e '(:startgroup))
8322 (push '() groups) (setq ingroup t)
8323 (when (not (= cnt 0))
8324 (setq cnt 0)
8325 (insert "\n"))
8326 (insert "{ "))
8327 ((equal e '(:endgroup))
8328 (setq ingroup nil cnt 0)
8329 (insert "}\n"))
8331 (setq tg (car e) c (cdr e))
8332 (if ingroup (push tg (car groups)))
8333 (setq tg (org-add-props tg nil 'face
8334 (org-get-todo-face tg)))
8335 (if (and (= cnt 0) (not ingroup)) (insert " "))
8336 (insert "[" c "] " tg (make-string
8337 (- fwidth 4 (length tg)) ?\ ))
8338 (when (= (setq cnt (1+ cnt)) ncol)
8339 (insert "\n")
8340 (if ingroup (insert " "))
8341 (setq cnt 0)))))
8342 (insert "\n")
8343 (goto-char (point-min))
8344 (if (not expert) (org-fit-window-to-buffer))
8345 (message "[a-z..]:Set [SPC]:clear")
8346 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
8347 (cond
8348 ((or (= c ?\C-g)
8349 (and (= c ?q) (not (rassoc c fulltable))))
8350 (setq quit-flag t))
8351 ((= c ?\ ) nil)
8352 ((setq e (rassoc c fulltable) tg (car e))
8354 (t (setq quit-flag t))))))
8356 (defun org-entry-is-todo-p ()
8357 (member (org-get-todo-state) org-not-done-keywords))
8359 (defun org-entry-is-done-p ()
8360 (member (org-get-todo-state) org-done-keywords))
8362 (defun org-get-todo-state ()
8363 (save-excursion
8364 (org-back-to-heading t)
8365 (and (looking-at org-todo-line-regexp)
8366 (match-end 2)
8367 (match-string 2))))
8369 (defun org-at-date-range-p (&optional inactive-ok)
8370 "Is the cursor inside a date range?"
8371 (interactive)
8372 (save-excursion
8373 (catch 'exit
8374 (let ((pos (point)))
8375 (skip-chars-backward "^[<\r\n")
8376 (skip-chars-backward "<[")
8377 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8378 (>= (match-end 0) pos)
8379 (throw 'exit t))
8380 (skip-chars-backward "^<[\r\n")
8381 (skip-chars-backward "<[")
8382 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8383 (>= (match-end 0) pos)
8384 (throw 'exit t)))
8385 nil)))
8387 (defun org-get-repeat ()
8388 "Check if there is a deadline/schedule with repeater in this entry."
8389 (save-match-data
8390 (save-excursion
8391 (org-back-to-heading t)
8392 (if (re-search-forward
8393 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
8394 (match-string 1)))))
8396 (defvar org-last-changed-timestamp)
8397 (defvar org-last-inserted-timestamp)
8398 (defvar org-log-post-message)
8399 (defvar org-log-note-purpose)
8400 (defvar org-log-note-how)
8401 (defvar org-log-note-extra)
8402 (defun org-auto-repeat-maybe (done-word)
8403 "Check if the current headline contains a repeated deadline/schedule.
8404 If yes, set TODO state back to what it was and change the base date
8405 of repeating deadline/scheduled time stamps to new date.
8406 This function is run automatically after each state change to a DONE state."
8407 ;; last-state is dynamically scoped into this function
8408 (let* ((repeat (org-get-repeat))
8409 (aa (assoc last-state org-todo-kwd-alist))
8410 (interpret (nth 1 aa))
8411 (head (nth 2 aa))
8412 (whata '(("d" . day) ("m" . month) ("y" . year)))
8413 (msg "Entry repeats: ")
8414 (org-log-done nil)
8415 (org-todo-log-states nil)
8416 (nshiftmax 10) (nshift 0)
8417 re type n what ts mb0 time)
8418 (when repeat
8419 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
8420 (org-todo (if (eq interpret 'type) last-state head))
8421 (when org-log-repeat
8422 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
8423 (memq 'org-add-log-note post-command-hook))
8424 ;; OK, we are already setup for some record
8425 (if (eq org-log-repeat 'note)
8426 ;; make sure we take a note, not only a time stamp
8427 (setq org-log-note-how 'note))
8428 ;; Set up for taking a record
8429 (org-add-log-setup 'state (or done-word (car org-done-keywords))
8430 'findpos org-log-repeat)))
8431 (org-back-to-heading t)
8432 (org-add-planning-info nil nil 'closed)
8433 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
8434 org-deadline-time-regexp "\\)\\|\\("
8435 org-ts-regexp "\\)"))
8436 (while (re-search-forward
8437 re (save-excursion (outline-next-heading) (point)) t)
8438 (setq type (if (match-end 1) org-scheduled-string
8439 (if (match-end 3) org-deadline-string "Plain:"))
8440 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0)))
8441 mb0 (match-beginning 0))
8442 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
8443 (setq n (string-to-number (match-string 2 ts))
8444 what (match-string 3 ts))
8445 (if (equal what "w") (setq n (* n 7) what "d"))
8446 ;; Preparation, see if we need to modify the start date for the change
8447 (when (match-end 1)
8448 (setq time (save-match-data (org-time-string-to-time ts)))
8449 (cond
8450 ((equal (match-string 1 ts) ".")
8451 ;; Shift starting date to today
8452 (org-timestamp-change
8453 (- (time-to-days (current-time)) (time-to-days time))
8454 'day))
8455 ((equal (match-string 1 ts) "+")
8456 (while (or (= nshift 0)
8457 (<= (time-to-days time) (time-to-days (current-time))))
8458 (when (= (incf nshift) nshiftmax)
8459 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
8460 (error "Abort")))
8461 (org-timestamp-change n (cdr (assoc what whata)))
8462 (org-at-timestamp-p t)
8463 (setq ts (match-string 1))
8464 (setq time (save-match-data (org-time-string-to-time ts))))
8465 (org-timestamp-change (- n) (cdr (assoc what whata)))
8466 ;; rematch, so that we have everything in place for the real shift
8467 (org-at-timestamp-p t)
8468 (setq ts (match-string 1))
8469 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
8470 (org-timestamp-change n (cdr (assoc what whata)))
8471 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
8472 (setq org-log-post-message msg)
8473 (message "%s" msg))))
8475 (defun org-show-todo-tree (arg)
8476 "Make a compact tree which shows all headlines marked with TODO.
8477 The tree will show the lines where the regexp matches, and all higher
8478 headlines above the match.
8479 With a \\[universal-argument] prefix, also show the DONE entries.
8480 With a numeric prefix N, construct a sparse tree for the Nth element
8481 of `org-todo-keywords-1'."
8482 (interactive "P")
8483 (let ((case-fold-search nil)
8484 (kwd-re
8485 (cond ((null arg) org-not-done-regexp)
8486 ((equal arg '(4))
8487 (let ((kwd (org-ido-completing-read "Keyword (or KWD1|KWD2|...): "
8488 (mapcar 'list org-todo-keywords-1))))
8489 (concat "\\("
8490 (mapconcat 'identity (org-split-string kwd "|") "\\|")
8491 "\\)\\>")))
8492 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
8493 (regexp-quote (nth (1- (prefix-numeric-value arg))
8494 org-todo-keywords-1)))
8495 (t (error "Invalid prefix argument: %s" arg)))))
8496 (message "%d TODO entries found"
8497 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
8499 (defun org-deadline (&optional remove time)
8500 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
8501 With argument REMOVE, remove any deadline from the item.
8502 When TIME is set, it should be an internal time specification, and the
8503 scheduling will use the corresponding date."
8504 (interactive "P")
8505 (if remove
8506 (progn
8507 (org-remove-timestamp-with-keyword org-deadline-string)
8508 (message "Item no longer has a deadline."))
8509 (if (org-get-repeat)
8510 (error "Cannot change deadline on task with repeater, please do that by hand")
8511 (org-add-planning-info 'deadline time 'closed)
8512 (message "Deadline on %s" org-last-inserted-timestamp))))
8514 (defun org-schedule (&optional remove time)
8515 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
8516 With argument REMOVE, remove any scheduling date from the item.
8517 When TIME is set, it should be an internal time specification, and the
8518 scheduling will use the corresponding date."
8519 (interactive "P")
8520 (if remove
8521 (progn
8522 (org-remove-timestamp-with-keyword org-scheduled-string)
8523 (message "Item is no longer scheduled."))
8524 (if (org-get-repeat)
8525 (error "Cannot reschedule task with repeater, please do that by hand")
8526 (org-add-planning-info 'scheduled time 'closed)
8527 (message "Scheduled to %s" org-last-inserted-timestamp))))
8529 (defun org-remove-timestamp-with-keyword (keyword)
8530 "Remove all time stamps with KEYWORD in the current entry."
8531 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
8532 beg)
8533 (save-excursion
8534 (org-back-to-heading t)
8535 (setq beg (point))
8536 (org-end-of-subtree t t)
8537 (while (re-search-backward re beg t)
8538 (replace-match "")
8539 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
8540 (equal (char-before) ?\ ))
8541 (backward-delete-char 1)
8542 (if (string-match "^[ \t]*$" (buffer-substring
8543 (point-at-bol) (point-at-eol)))
8544 (delete-region (point-at-bol)
8545 (min (point-max) (1+ (point-at-eol))))))))))
8547 (defun org-add-planning-info (what &optional time &rest remove)
8548 "Insert new timestamp with keyword in the line directly after the headline.
8549 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
8550 If non is given, the user is prompted for a date.
8551 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
8552 be removed."
8553 (interactive)
8554 (let (org-time-was-given org-end-time-was-given ts
8555 end default-time default-input)
8557 (when (and (not time) (memq what '(scheduled deadline)))
8558 ;; Try to get a default date/time from existing timestamp
8559 (save-excursion
8560 (org-back-to-heading t)
8561 (setq end (save-excursion (outline-next-heading) (point)))
8562 (when (re-search-forward (if (eq what 'scheduled)
8563 org-scheduled-time-regexp
8564 org-deadline-time-regexp)
8565 end t)
8566 (setq ts (match-string 1)
8567 default-time
8568 (apply 'encode-time (org-parse-time-string ts))
8569 default-input (and ts (org-get-compact-tod ts))))))
8570 (when what
8571 ;; If necessary, get the time from the user
8572 (setq time (or time (org-read-date nil 'to-time nil nil
8573 default-time default-input))))
8575 (when (and org-insert-labeled-timestamps-at-point
8576 (member what '(scheduled deadline)))
8577 (insert
8578 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
8579 (org-insert-time-stamp time org-time-was-given
8580 nil nil nil (list org-end-time-was-given))
8581 (setq what nil))
8582 (save-excursion
8583 (save-restriction
8584 (let (col list elt ts buffer-invisibility-spec)
8585 (org-back-to-heading t)
8586 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
8587 (goto-char (match-end 1))
8588 (setq col (current-column))
8589 (goto-char (match-end 0))
8590 (if (eobp) (insert "\n") (forward-char 1))
8591 (if (and (not (looking-at outline-regexp))
8592 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
8593 "[^\r\n]*"))
8594 (not (equal (match-string 1) org-clock-string)))
8595 (narrow-to-region (match-beginning 0) (match-end 0))
8596 (insert-before-markers "\n")
8597 (backward-char 1)
8598 (narrow-to-region (point) (point))
8599 (and org-adapt-indentation (org-indent-to-column col)))
8600 ;; Check if we have to remove something.
8601 (setq list (cons what remove))
8602 (while list
8603 (setq elt (pop list))
8604 (goto-char (point-min))
8605 (when (or (and (eq elt 'scheduled)
8606 (re-search-forward org-scheduled-time-regexp nil t))
8607 (and (eq elt 'deadline)
8608 (re-search-forward org-deadline-time-regexp nil t))
8609 (and (eq elt 'closed)
8610 (re-search-forward org-closed-time-regexp nil t)))
8611 (replace-match "")
8612 (if (looking-at "--+<[^>]+>") (replace-match ""))
8613 (if (looking-at " +") (replace-match ""))))
8614 (goto-char (point-max))
8615 (when what
8616 (insert
8617 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
8618 (cond ((eq what 'scheduled) org-scheduled-string)
8619 ((eq what 'deadline) org-deadline-string)
8620 ((eq what 'closed) org-closed-string))
8621 " ")
8622 (setq ts (org-insert-time-stamp
8623 time
8624 (or org-time-was-given
8625 (and (eq what 'closed) org-log-done-with-time))
8626 (eq what 'closed)
8627 nil nil (list org-end-time-was-given)))
8628 (end-of-line 1))
8629 (goto-char (point-min))
8630 (widen)
8631 (if (and (looking-at "[ \t]+\n")
8632 (equal (char-before) ?\n))
8633 (delete-region (1- (point)) (point-at-eol)))
8634 ts)))))
8636 (defvar org-log-note-marker (make-marker))
8637 (defvar org-log-note-purpose nil)
8638 (defvar org-log-note-state nil)
8639 (defvar org-log-note-how nil)
8640 (defvar org-log-note-extra nil)
8641 (defvar org-log-note-window-configuration nil)
8642 (defvar org-log-note-return-to (make-marker))
8643 (defvar org-log-post-message nil
8644 "Message to be displayed after a log note has been stored.
8645 The auto-repeater uses this.")
8647 (defun org-add-note ()
8648 "Add a note to the current entry.
8649 This is done in the same way as adding a state change note."
8650 (interactive)
8651 (org-add-log-setup 'note nil 'findpos nil))
8653 (defvar org-property-end-re)
8654 (defun org-add-log-setup (&optional purpose state findpos how &optional extra)
8655 "Set up the post command hook to take a note.
8656 If this is about to TODO state change, the new state is expected in STATE.
8657 When FINDPOS is non-nil, find the correct position for the note in
8658 the current entry. If not, assume that it can be inserted at point.
8659 HOW is an indicator what kind of note should be created.
8660 EXTRA is additional text that will be inserted into the notes buffer."
8661 (save-restriction
8662 (save-excursion
8663 (when findpos
8664 (org-back-to-heading t)
8665 (narrow-to-region (point) (save-excursion
8666 (outline-next-heading) (point)))
8667 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
8668 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
8669 "[^\r\n]*\\)?"))
8670 (goto-char (match-end 0))
8671 (when (and org-log-state-notes-insert-after-drawers
8672 (save-excursion
8673 (forward-line) (looking-at org-drawer-regexp)))
8674 (progn (forward-line)
8675 (while (looking-at org-drawer-regexp)
8676 (goto-char (match-end 0))
8677 (re-search-forward org-property-end-re (point-max) t)
8678 (forward-line))
8679 (forward-line -1)))
8680 (unless org-log-states-order-reversed
8681 (and (= (char-after) ?\n) (forward-char 1))
8682 (org-skip-over-state-notes)
8683 (skip-chars-backward " \t\n\r")))
8684 (move-marker org-log-note-marker (point))
8685 (setq org-log-note-purpose purpose
8686 org-log-note-state state
8687 org-log-note-how how
8688 org-log-note-extra extra)
8689 (add-hook 'post-command-hook 'org-add-log-note 'append))))
8691 (defun org-skip-over-state-notes ()
8692 "Skip past the list of State notes in an entry."
8693 (if (looking-at "\n[ \t]*- State") (forward-char 1))
8694 (while (looking-at "[ \t]*- State")
8695 (condition-case nil
8696 (org-next-item)
8697 (error (org-end-of-item)))))
8699 (defun org-add-log-note (&optional purpose)
8700 "Pop up a window for taking a note, and add this note later at point."
8701 (remove-hook 'post-command-hook 'org-add-log-note)
8702 (setq org-log-note-window-configuration (current-window-configuration))
8703 (delete-other-windows)
8704 (move-marker org-log-note-return-to (point))
8705 (switch-to-buffer (marker-buffer org-log-note-marker))
8706 (goto-char org-log-note-marker)
8707 (org-switch-to-buffer-other-window "*Org Note*")
8708 (erase-buffer)
8709 (if (memq org-log-note-how '(time state))
8710 (let (current-prefix-arg) (org-store-log-note))
8711 (let ((org-inhibit-startup t)) (org-mode))
8712 (insert (format "# Insert note for %s.
8713 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
8714 (cond
8715 ((eq org-log-note-purpose 'clock-out) "stopped clock")
8716 ((eq org-log-note-purpose 'done) "closed todo item")
8717 ((eq org-log-note-purpose 'state)
8718 (format "state change to \"%s\"" org-log-note-state))
8719 ((eq org-log-note-purpose 'note)
8720 "this entry")
8721 (t (error "This should not happen")))))
8722 (if org-log-note-extra (insert org-log-note-extra))
8723 (org-set-local 'org-finish-function 'org-store-log-note)))
8725 (defvar org-note-abort nil) ; dynamically scoped
8726 (defun org-store-log-note ()
8727 "Finish taking a log note, and insert it to where it belongs."
8728 (let ((txt (buffer-string))
8729 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
8730 lines ind)
8731 (kill-buffer (current-buffer))
8732 (while (string-match "\\`#.*\n[ \t\n]*" txt)
8733 (setq txt (replace-match "" t t txt)))
8734 (if (string-match "\\s-+\\'" txt)
8735 (setq txt (replace-match "" t t txt)))
8736 (setq lines (org-split-string txt "\n"))
8737 (when (and note (string-match "\\S-" note))
8738 (setq note
8739 (org-replace-escapes
8740 note
8741 (list (cons "%u" (user-login-name))
8742 (cons "%U" user-full-name)
8743 (cons "%t" (format-time-string
8744 (org-time-stamp-format 'long 'inactive)
8745 (current-time)))
8746 (cons "%s" (if org-log-note-state
8747 (concat "\"" org-log-note-state "\"")
8748 "")))))
8749 (if lines (setq note (concat note " \\\\")))
8750 (push note lines))
8751 (when (or current-prefix-arg org-note-abort) (setq lines nil))
8752 (when lines
8753 (save-excursion
8754 (set-buffer (marker-buffer org-log-note-marker))
8755 (save-excursion
8756 (goto-char org-log-note-marker)
8757 (move-marker org-log-note-marker nil)
8758 (end-of-line 1)
8759 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
8760 (indent-relative nil)
8761 (insert "- " (pop lines))
8762 (org-indent-line-function)
8763 (beginning-of-line 1)
8764 (looking-at "[ \t]*")
8765 (setq ind (concat (match-string 0) " "))
8766 (end-of-line 1)
8767 (while lines (insert "\n" ind (pop lines)))))))
8768 (set-window-configuration org-log-note-window-configuration)
8769 (with-current-buffer (marker-buffer org-log-note-return-to)
8770 (goto-char org-log-note-return-to))
8771 (move-marker org-log-note-return-to nil)
8772 (and org-log-post-message (message "%s" org-log-post-message)))
8774 (defun org-sparse-tree (&optional arg)
8775 "Create a sparse tree, prompt for the details.
8776 This command can create sparse trees. You first need to select the type
8777 of match used to create the tree:
8779 t Show entries with a specific TODO keyword.
8780 T Show entries selected by a tags match.
8781 p Enter a property name and its value (both with completion on existing
8782 names/values) and show entries with that property.
8783 r Show entries matching a regular expression
8784 d Show deadlines due within `org-deadline-warning-days'."
8785 (interactive "P")
8786 (let (ans kwd value)
8787 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
8788 (setq ans (read-char-exclusive))
8789 (cond
8790 ((equal ans ?d)
8791 (call-interactively 'org-check-deadlines))
8792 ((equal ans ?b)
8793 (call-interactively 'org-check-before-date))
8794 ((equal ans ?t)
8795 (org-show-todo-tree '(4)))
8796 ((equal ans ?T)
8797 (call-interactively 'org-tags-sparse-tree))
8798 ((member ans '(?p ?P))
8799 (setq kwd (org-ido-completing-read "Property: "
8800 (mapcar 'list (org-buffer-property-keys))))
8801 (setq value (org-ido-completing-read "Value: "
8802 (mapcar 'list (org-property-values kwd))))
8803 (unless (string-match "\\`{.*}\\'" value)
8804 (setq value (concat "\"" value "\"")))
8805 (org-tags-sparse-tree arg (concat kwd "=" value)))
8806 ((member ans '(?r ?R ?/))
8807 (call-interactively 'org-occur))
8808 (t (error "No such sparse tree command \"%c\"" ans)))))
8810 (defvar org-occur-highlights nil
8811 "List of overlays used for occur matches.")
8812 (make-variable-buffer-local 'org-occur-highlights)
8813 (defvar org-occur-parameters nil
8814 "Parameters of the active org-occur calls.
8815 This is a list, each call to org-occur pushes as cons cell,
8816 containing the regular expression and the callback, onto the list.
8817 The list can contain several entries if `org-occur' has been called
8818 several time with the KEEP-PREVIOUS argument. Otherwise, this list
8819 will only contain one set of parameters. When the highlights are
8820 removed (for example with `C-c C-c', or with the next edit (depending
8821 on `org-remove-highlights-with-change'), this variable is emptied
8822 as well.")
8823 (make-variable-buffer-local 'org-occur-parameters)
8825 (defun org-occur (regexp &optional keep-previous callback)
8826 "Make a compact tree which shows all matches of REGEXP.
8827 The tree will show the lines where the regexp matches, and all higher
8828 headlines above the match. It will also show the heading after the match,
8829 to make sure editing the matching entry is easy.
8830 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
8831 call to `org-occur' will be kept, to allow stacking of calls to this
8832 command.
8833 If CALLBACK is non-nil, it is a function which is called to confirm
8834 that the match should indeed be shown."
8835 (interactive "sRegexp: \nP")
8836 (unless keep-previous
8837 (org-remove-occur-highlights nil nil t))
8838 (push (cons regexp callback) org-occur-parameters)
8839 (let ((cnt 0))
8840 (save-excursion
8841 (goto-char (point-min))
8842 (if (or (not keep-previous) ; do not want to keep
8843 (not org-occur-highlights)) ; no previous matches
8844 ;; hide everything
8845 (org-overview))
8846 (while (re-search-forward regexp nil t)
8847 (when (or (not callback)
8848 (save-match-data (funcall callback)))
8849 (setq cnt (1+ cnt))
8850 (when org-highlight-sparse-tree-matches
8851 (org-highlight-new-match (match-beginning 0) (match-end 0)))
8852 (org-show-context 'occur-tree))))
8853 (when org-remove-highlights-with-change
8854 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
8855 nil 'local))
8856 (unless org-sparse-tree-open-archived-trees
8857 (org-hide-archived-subtrees (point-min) (point-max)))
8858 (run-hooks 'org-occur-hook)
8859 (if (interactive-p)
8860 (message "%d match(es) for regexp %s" cnt regexp))
8861 cnt))
8863 (defun org-show-context (&optional key)
8864 "Make sure point and context and visible.
8865 How much context is shown depends upon the variables
8866 `org-show-hierarchy-above', `org-show-following-heading'. and
8867 `org-show-siblings'."
8868 (let ((heading-p (org-on-heading-p t))
8869 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
8870 (following-p (org-get-alist-option org-show-following-heading key))
8871 (entry-p (org-get-alist-option org-show-entry-below key))
8872 (siblings-p (org-get-alist-option org-show-siblings key)))
8873 (catch 'exit
8874 ;; Show heading or entry text
8875 (if (and heading-p (not entry-p))
8876 (org-flag-heading nil) ; only show the heading
8877 (and (or entry-p (org-invisible-p) (org-invisible-p2))
8878 (org-show-hidden-entry))) ; show entire entry
8879 (when following-p
8880 ;; Show next sibling, or heading below text
8881 (save-excursion
8882 (and (if heading-p (org-goto-sibling) (outline-next-heading))
8883 (org-flag-heading nil))))
8884 (when siblings-p (org-show-siblings))
8885 (when hierarchy-p
8886 ;; show all higher headings, possibly with siblings
8887 (save-excursion
8888 (while (and (condition-case nil
8889 (progn (org-up-heading-all 1) t)
8890 (error nil))
8891 (not (bobp)))
8892 (org-flag-heading nil)
8893 (when siblings-p (org-show-siblings))))))))
8895 (defun org-reveal (&optional siblings)
8896 "Show current entry, hierarchy above it, and the following headline.
8897 This can be used to show a consistent set of context around locations
8898 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
8899 not t for the search context.
8901 With optional argument SIBLINGS, on each level of the hierarchy all
8902 siblings are shown. This repairs the tree structure to what it would
8903 look like when opened with hierarchical calls to `org-cycle'."
8904 (interactive "P")
8905 (let ((org-show-hierarchy-above t)
8906 (org-show-following-heading t)
8907 (org-show-siblings (if siblings t org-show-siblings)))
8908 (org-show-context nil)))
8910 (defun org-highlight-new-match (beg end)
8911 "Highlight from BEG to END and mark the highlight is an occur headline."
8912 (let ((ov (org-make-overlay beg end)))
8913 (org-overlay-put ov 'face 'secondary-selection)
8914 (push ov org-occur-highlights)))
8916 (defun org-remove-occur-highlights (&optional beg end noremove)
8917 "Remove the occur highlights from the buffer.
8918 BEG and END are ignored. If NOREMOVE is nil, remove this function
8919 from the `before-change-functions' in the current buffer."
8920 (interactive)
8921 (unless org-inhibit-highlight-removal
8922 (mapc 'org-delete-overlay org-occur-highlights)
8923 (setq org-occur-highlights nil)
8924 (setq org-occur-parameters nil)
8925 (unless noremove
8926 (remove-hook 'before-change-functions
8927 'org-remove-occur-highlights 'local))))
8929 ;;;; Priorities
8931 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
8932 "Regular expression matching the priority indicator.")
8934 (defvar org-remove-priority-next-time nil)
8936 (defun org-priority-up ()
8937 "Increase the priority of the current item."
8938 (interactive)
8939 (org-priority 'up))
8941 (defun org-priority-down ()
8942 "Decrease the priority of the current item."
8943 (interactive)
8944 (org-priority 'down))
8946 (defun org-priority (&optional action)
8947 "Change the priority of an item by ARG.
8948 ACTION can be `set', `up', `down', or a character."
8949 (interactive)
8950 (setq action (or action 'set))
8951 (let (current new news have remove)
8952 (save-excursion
8953 (org-back-to-heading)
8954 (if (looking-at org-priority-regexp)
8955 (setq current (string-to-char (match-string 2))
8956 have t)
8957 (setq current org-default-priority))
8958 (cond
8959 ((or (eq action 'set)
8960 (if (featurep 'xemacs) (characterp action) (integerp action)))
8961 (if (not (eq action 'set))
8962 (setq new action)
8963 (message "Priority %c-%c, SPC to remove: "
8964 org-highest-priority org-lowest-priority)
8965 (setq new (read-char-exclusive)))
8966 (if (and (= (upcase org-highest-priority) org-highest-priority)
8967 (= (upcase org-lowest-priority) org-lowest-priority))
8968 (setq new (upcase new)))
8969 (cond ((equal new ?\ ) (setq remove t))
8970 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
8971 (error "Priority must be between `%c' and `%c'"
8972 org-highest-priority org-lowest-priority))))
8973 ((eq action 'up)
8974 (if (and (not have) (eq last-command this-command))
8975 (setq new org-lowest-priority)
8976 (setq new (if (and org-priority-start-cycle-with-default (not have))
8977 org-default-priority (1- current)))))
8978 ((eq action 'down)
8979 (if (and (not have) (eq last-command this-command))
8980 (setq new org-highest-priority)
8981 (setq new (if (and org-priority-start-cycle-with-default (not have))
8982 org-default-priority (1+ current)))))
8983 (t (error "Invalid action")))
8984 (if (or (< (upcase new) org-highest-priority)
8985 (> (upcase new) org-lowest-priority))
8986 (setq remove t))
8987 (setq news (format "%c" new))
8988 (if have
8989 (if remove
8990 (replace-match "" t t nil 1)
8991 (replace-match news t t nil 2))
8992 (if remove
8993 (error "No priority cookie found in line")
8994 (looking-at org-todo-line-regexp)
8995 (if (match-end 2)
8996 (progn
8997 (goto-char (match-end 2))
8998 (insert " [#" news "]"))
8999 (goto-char (match-beginning 3))
9000 (insert "[#" news "] ")))))
9001 (org-preserve-lc (org-set-tags nil 'align))
9002 (if remove
9003 (message "Priority removed")
9004 (message "Priority of current item set to %s" news))))
9007 (defun org-get-priority (s)
9008 "Find priority cookie and return priority."
9009 (save-match-data
9010 (if (not (string-match org-priority-regexp s))
9011 (* 1000 (- org-lowest-priority org-default-priority))
9012 (* 1000 (- org-lowest-priority
9013 (string-to-char (match-string 2 s)))))))
9015 ;;;; Tags
9017 (defvar org-agenda-archives-mode)
9018 (defun org-scan-tags (action matcher &optional todo-only)
9019 "Scan headline tags with inheritance and produce output ACTION.
9021 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
9022 or `agenda' to produce an entry list for an agenda view. It can also be
9023 a Lisp form or a function that should be called at each matched headline, in
9024 this case the return value is a list of all return values from these calls.
9026 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
9027 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
9028 only lines with a TODO keyword are included in the output."
9029 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
9030 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
9031 (org-re
9032 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
9033 (props (list 'face 'default
9034 'done-face 'org-done
9035 'undone-face 'default
9036 'mouse-face 'highlight
9037 'org-not-done-regexp org-not-done-regexp
9038 'org-todo-regexp org-todo-regexp
9039 'keymap org-agenda-keymap
9040 'help-echo
9041 (format "mouse-2 or RET jump to org file %s"
9042 (abbreviate-file-name
9043 (or (buffer-file-name (buffer-base-buffer))
9044 (buffer-name (buffer-base-buffer)))))))
9045 (case-fold-search nil)
9046 lspos tags tags-list
9047 (tags-alist (list (cons 0 (mapcar 'downcase org-file-tags))))
9048 (llast 0) rtn rtn1 level category i txt
9049 todo marker entry priority)
9050 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
9051 (setq action (list 'lambda nil action)))
9052 (save-excursion
9053 (goto-char (point-min))
9054 (when (eq action 'sparse-tree)
9055 (org-overview)
9056 (org-remove-occur-highlights))
9057 (while (re-search-forward re nil t)
9058 (catch :skip
9059 (setq todo (if (match-end 1) (match-string 2))
9060 tags (if (match-end 4) (match-string 4)))
9061 (goto-char (setq lspos (1+ (match-beginning 0))))
9062 (setq level (org-reduced-level (funcall outline-level))
9063 category (org-get-category))
9064 (setq i llast llast level)
9065 ;; remove tag lists from same and sublevels
9066 (while (>= i level)
9067 (when (setq entry (assoc i tags-alist))
9068 (setq tags-alist (delete entry tags-alist)))
9069 (setq i (1- i)))
9070 ;; add the next tags
9071 (when tags
9072 (setq tags (mapcar 'downcase (org-split-string tags ":"))
9073 tags-alist
9074 (cons (cons level tags) tags-alist)))
9075 ;; compile tags for current headline
9076 (setq tags-list
9077 (if org-use-tag-inheritance
9078 (apply 'append (mapcar 'cdr (reverse tags-alist)))
9079 tags))
9080 (when org-use-tag-inheritance
9081 (setcdr (car tags-alist)
9082 (mapcar (lambda (x)
9083 (setq x (copy-sequence x))
9084 (org-add-prop-inherited x))
9085 (cdar tags-alist))))
9086 (when (and tags org-use-tag-inheritance
9087 (not (eq t org-use-tag-inheritance)))
9088 ;; selective inheritance, remove uninherited ones
9089 (setcdr (car tags-alist)
9090 (org-remove-uniherited-tags (cdar tags-alist))))
9091 (when (and (or (not todo-only) (member todo org-not-done-keywords))
9092 (let ((case-fold-search t)) (eval matcher))
9094 (not (member org-archive-tag tags-list))
9095 ;; we have an archive tag, should we use this anyway?
9096 (or (not org-agenda-skip-archived-trees)
9097 (and (eq action 'agenda) org-agenda-archives-mode))))
9098 (unless (eq action 'sparse-tree) (org-agenda-skip))
9100 ;; select this headline
9102 (cond
9103 ((eq action 'sparse-tree)
9104 (and org-highlight-sparse-tree-matches
9105 (org-get-heading) (match-end 0)
9106 (org-highlight-new-match
9107 (match-beginning 0) (match-beginning 1)))
9108 (org-show-context 'tags-tree))
9109 ((eq action 'agenda)
9110 (setq txt (org-format-agenda-item
9112 (concat
9113 (if org-tags-match-list-sublevels
9114 (make-string (1- level) ?.) "")
9115 (org-get-heading))
9116 category tags-list)
9117 priority (org-get-priority txt))
9118 (goto-char lspos)
9119 (setq marker (org-agenda-new-marker))
9120 (org-add-props txt props
9121 'org-marker marker 'org-hd-marker marker 'org-category category
9122 'priority priority 'type "tagsmatch")
9123 (push txt rtn))
9124 ((functionp action)
9125 (save-excursion
9126 (setq rtn1 (funcall action))
9127 (push rtn1 rtn))
9128 (goto-char (point-at-eol)))
9129 (t (error "Invalid action")))
9131 ;; if we are to skip sublevels, jump to end of subtree
9132 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
9133 (when (and (eq action 'sparse-tree)
9134 (not org-sparse-tree-open-archived-trees))
9135 (org-hide-archived-subtrees (point-min) (point-max)))
9136 (nreverse rtn)))
9138 (defun org-remove-uniherited-tags (tags)
9139 "Remove all tags that are not inherited from the list TAGS."
9140 (cond
9141 ((eq org-use-tag-inheritance t)
9142 (if org-tags-exclude-from-inheritance
9143 (org-delete-all org-tags-exclude-from-inheritance tags)
9144 tags))
9145 ((not org-use-tag-inheritance) nil)
9146 ((stringp org-use-tag-inheritance)
9147 (delq nil (mapcar
9148 (lambda (x)
9149 (if (and (string-match org-use-tag-inheritance x)
9150 (not (member x org-tags-exclude-from-inheritance)))
9151 x nil))
9152 tags)))
9153 ((listp org-use-tag-inheritance)
9154 (delq nil (mapcar
9155 (lambda (x)
9156 (if (member x org-use-tag-inheritance) x nil))
9157 tags)))))
9159 (defvar todo-only) ;; dynamically scoped
9161 (defun org-tags-sparse-tree (&optional todo-only match)
9162 "Create a sparse tree according to tags string MATCH.
9163 MATCH can contain positive and negative selection of tags, like
9164 \"+WORK+URGENT-WITHBOSS\".
9165 If optional argument TODO-ONLY is non-nil, only select lines that are
9166 also TODO lines."
9167 (interactive "P")
9168 (org-prepare-agenda-buffers (list (current-buffer)))
9169 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
9171 (defvar org-cached-props nil)
9172 (defun org-cached-entry-get (pom property)
9173 (if (or (eq t org-use-property-inheritance)
9174 (and (stringp org-use-property-inheritance)
9175 (string-match org-use-property-inheritance property))
9176 (and (listp org-use-property-inheritance)
9177 (member property org-use-property-inheritance)))
9178 ;; Caching is not possible, check it directly
9179 (org-entry-get pom property 'inherit)
9180 ;; Get all properties, so that we can do complicated checks easily
9181 (cdr (assoc property (or org-cached-props
9182 (setq org-cached-props
9183 (org-entry-properties pom)))))))
9185 (defun org-global-tags-completion-table (&optional files)
9186 "Return the list of all tags in all agenda buffer/files."
9187 (save-excursion
9188 (org-uniquify
9189 (delq nil
9190 (apply 'append
9191 (mapcar
9192 (lambda (file)
9193 (set-buffer (find-file-noselect file))
9194 (append (org-get-buffer-tags)
9195 (mapcar (lambda (x) (if (stringp (car-safe x))
9196 (list (car-safe x)) nil))
9197 org-tag-alist)))
9198 (if (and files (car files))
9199 files
9200 (org-agenda-files))))))))
9202 (defun org-make-tags-matcher (match)
9203 "Create the TAGS//TODO matcher form for the selection string MATCH."
9204 ;; todo-only is scoped dynamically into this function, and the function
9205 ;; may change it it the matcher asksk for it.
9206 (unless match
9207 ;; Get a new match request, with completion
9208 (let ((org-last-tags-completion-table
9209 (org-global-tags-completion-table)))
9210 (setq match (org-ido-completing-read
9211 "Match: " 'org-tags-completion-function nil nil nil
9212 'org-tags-history))))
9214 ;; Parse the string and create a lisp form
9215 (let ((match0 match)
9216 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
9217 minus tag mm
9218 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
9219 orterms term orlist re-p str-p level-p level-op time-p
9220 prop-p pn pv po cat-p gv rest)
9221 (if (string-match "/+" match)
9222 ;; match contains also a todo-matching request
9223 (progn
9224 (setq tagsmatch (substring match 0 (match-beginning 0))
9225 todomatch (substring match (match-end 0)))
9226 (if (string-match "^!" todomatch)
9227 (setq todo-only t todomatch (substring todomatch 1)))
9228 (if (string-match "^\\s-*$" todomatch)
9229 (setq todomatch nil)))
9230 ;; only matching tags
9231 (setq tagsmatch match todomatch nil))
9233 ;; Make the tags matcher
9234 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
9235 (setq tagsmatcher t)
9236 (setq orterms (org-split-string tagsmatch "|") orlist nil)
9237 (while (setq term (pop orterms))
9238 (while (and (equal (substring term -1) "\\") orterms)
9239 (setq term (concat term "|" (pop orterms)))) ; repair bad split
9240 (while (string-match re term)
9241 (setq rest (substring term (match-end 0))
9242 minus (and (match-end 1)
9243 (equal (match-string 1 term) "-"))
9244 tag (match-string 2 term)
9245 re-p (equal (string-to-char tag) ?{)
9246 level-p (match-end 4)
9247 prop-p (match-end 5)
9248 mm (cond
9249 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
9250 (level-p
9251 (setq level-op (org-op-to-function (match-string 3 term)))
9252 `(,level-op level ,(string-to-number
9253 (match-string 4 term))))
9254 (prop-p
9255 (setq pn (match-string 5 term)
9256 po (match-string 6 term)
9257 pv (match-string 7 term)
9258 cat-p (equal pn "CATEGORY")
9259 re-p (equal (string-to-char pv) ?{)
9260 str-p (equal (string-to-char pv) ?\")
9261 time-p (save-match-data
9262 (string-match "^\"[[<].*[]>]\"$" pv))
9263 pv (if (or re-p str-p) (substring pv 1 -1) pv))
9264 (if time-p (setq pv (org-matcher-time pv)))
9265 (setq po (org-op-to-function po (if time-p 'time str-p)))
9266 (cond
9267 ((equal pn "CATEGORY")
9268 (setq gv '(get-text-property (point) 'org-category)))
9269 ((equal pn "TODO")
9270 (setq gv 'todo))
9272 (setq gv `(org-cached-entry-get nil ,pn))))
9273 (if re-p
9274 (if (eq po 'org<>)
9275 `(not (string-match ,pv (or ,gv "")))
9276 `(string-match ,pv (or ,gv "")))
9277 (if str-p
9278 `(,po (or ,gv "") ,pv)
9279 `(,po (string-to-number (or ,gv ""))
9280 ,(string-to-number pv) ))))
9281 (t `(member ,(downcase tag) tags-list)))
9282 mm (if minus (list 'not mm) mm)
9283 term rest)
9284 (push mm tagsmatcher))
9285 (push (if (> (length tagsmatcher) 1)
9286 (cons 'and tagsmatcher)
9287 (car tagsmatcher))
9288 orlist)
9289 (setq tagsmatcher nil))
9290 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
9291 (setq tagsmatcher
9292 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
9293 ;; Make the todo matcher
9294 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
9295 (setq todomatcher t)
9296 (setq orterms (org-split-string todomatch "|") orlist nil)
9297 (while (setq term (pop orterms))
9298 (while (string-match re term)
9299 (setq minus (and (match-end 1)
9300 (equal (match-string 1 term) "-"))
9301 kwd (match-string 2 term)
9302 re-p (equal (string-to-char kwd) ?{)
9303 term (substring term (match-end 0))
9304 mm (if re-p
9305 `(string-match ,(substring kwd 1 -1) todo)
9306 (list 'equal 'todo kwd))
9307 mm (if minus (list 'not mm) mm))
9308 (push mm todomatcher))
9309 (push (if (> (length todomatcher) 1)
9310 (cons 'and todomatcher)
9311 (car todomatcher))
9312 orlist)
9313 (setq todomatcher nil))
9314 (setq todomatcher (if (> (length orlist) 1)
9315 (cons 'or orlist) (car orlist))))
9317 ;; Return the string and lisp forms of the matcher
9318 (setq matcher (if todomatcher
9319 (list 'and tagsmatcher todomatcher)
9320 tagsmatcher))
9321 (cons match0 matcher)))
9323 (defun org-op-to-function (op &optional stringp)
9324 "Turn an operator into the appropriate function."
9325 (setq op
9326 (cond
9327 ((equal op "<" ) '(< string< org-time<))
9328 ((equal op ">" ) '(> org-string> org-time>))
9329 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
9330 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
9331 ((member op '("=" "==")) '(= string= org-time=))
9332 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
9333 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
9335 (defun org<> (a b) (not (= a b)))
9336 (defun org-string<= (a b) (or (string= a b) (string< a b)))
9337 (defun org-string>= (a b) (not (string< a b)))
9338 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
9339 (defun org-string<> (a b) (not (string= a b)))
9340 (defun org-time= (a b) (= (org-2ft a) (org-2ft b)))
9341 (defun org-time< (a b) (< (org-2ft a) (org-2ft b)))
9342 (defun org-time<= (a b) (<= (org-2ft a) (org-2ft b)))
9343 (defun org-time> (a b) (> (org-2ft a) (org-2ft b)))
9344 (defun org-time>= (a b) (>= (org-2ft a) (org-2ft b)))
9345 (defun org-time<> (a b) (org<> (org-2ft a) (org-2ft b)))
9346 (defun org-2ft (s)
9347 "Convert S to a floating point time.
9348 If S is already a number, just return it. If it is a string, parse
9349 it as a time string and apply `float-time' to it. f S is nil, just return 0."
9350 (cond
9351 ((numberp s) s)
9352 ((stringp s)
9353 (condition-case nil
9354 (float-time (apply 'encode-time (org-parse-time-string s)))
9355 (error 0.)))
9356 (t 0.)))
9358 (defun org-time-today ()
9359 "Time in seconds today at 0:00.
9360 Returns the float number of seconds since the beginning of the
9361 epoch to the beginning of today (00:00)."
9362 (float-time (apply 'encode-time
9363 (append '(0 0 0) (nthcdr 3 (decode-time))))))
9365 (defun org-matcher-time (s)
9366 "Interprete a time comparison value."
9367 (save-match-data
9368 (cond
9369 ((string= s "<now>") (float-time))
9370 ((string= s "<today>") (org-time-today))
9371 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
9372 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
9373 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
9374 (+ (org-time-today)
9375 (* (string-to-number (match-string 1 s))
9376 (cdr (assoc (match-string 2 s)
9377 '(("d" . 86400.0) ("w" . 604800.0)
9378 ("m" . 2678400.0) ("y" . 31557600.0)))))))
9379 (t (org-2ft s)))))
9381 (defun org-match-any-p (re list)
9382 "Does re match any element of list?"
9383 (setq list (mapcar (lambda (x) (string-match re x)) list))
9384 (delq nil list))
9386 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
9387 (defvar org-tags-overlay (org-make-overlay 1 1))
9388 (org-detach-overlay org-tags-overlay)
9390 (defun org-get-local-tags-at (&optional pos)
9391 "Get a list of tags defined in the current headline."
9392 (org-get-tags-at pos 'local))
9394 (defun org-get-local-tags ()
9395 "Get a list of tags defined in the current headline."
9396 (org-get-tags-at nil 'local))
9398 (defun org-get-tags-at (&optional pos local)
9399 "Get a list of all headline tags applicable at POS.
9400 POS defaults to point. If tags are inherited, the list contains
9401 the targets in the same sequence as the headlines appear, i.e.
9402 the tags of the current headline come last.
9403 When LOCAL is non-nil, only return tags from the current headline,
9404 ignore inherited ones."
9405 (interactive)
9406 (let (tags ltags lastpos parent)
9407 (save-excursion
9408 (save-restriction
9409 (widen)
9410 (goto-char (or pos (point)))
9411 (save-match-data
9412 (catch 'done
9413 (condition-case nil
9414 (progn
9415 (org-back-to-heading t)
9416 (while (not (equal lastpos (point)))
9417 (setq lastpos (point))
9418 (when (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
9419 (setq ltags (org-split-string
9420 (org-match-string-no-properties 1) ":"))
9421 (when parent
9422 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
9423 (setq tags (append
9424 (if parent
9425 (org-remove-uniherited-tags ltags)
9426 ltags)
9427 tags)))
9428 (or org-use-tag-inheritance (throw 'done t))
9429 (if local (throw 'done t))
9430 (org-up-heading-all 1)
9431 (setq parent t)))
9432 (error nil)))))
9433 (append (org-remove-uniherited-tags org-file-tags) tags))))
9435 (defun org-add-prop-inherited (s)
9436 (add-text-properties 0 (length s) '(inherited t) s)
9439 (defun org-toggle-tag (tag &optional onoff)
9440 "Toggle the tag TAG for the current line.
9441 If ONOFF is `on' or `off', don't toggle but set to this state."
9442 (unless (org-on-heading-p t) (error "Not on headling"))
9443 (let (res current)
9444 (save-excursion
9445 (beginning-of-line)
9446 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
9447 (point-at-eol) t)
9448 (progn
9449 (setq current (match-string 1))
9450 (replace-match ""))
9451 (setq current ""))
9452 (setq current (nreverse (org-split-string current ":")))
9453 (cond
9454 ((eq onoff 'on)
9455 (setq res t)
9456 (or (member tag current) (push tag current)))
9457 ((eq onoff 'off)
9458 (or (not (member tag current)) (setq current (delete tag current))))
9459 (t (if (member tag current)
9460 (setq current (delete tag current))
9461 (setq res t)
9462 (push tag current))))
9463 (end-of-line 1)
9464 (if current
9465 (progn
9466 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
9467 (org-set-tags nil t))
9468 (delete-horizontal-space))
9469 (run-hooks 'org-after-tags-change-hook))
9470 res))
9472 (defun org-align-tags-here (to-col)
9473 ;; Assumes that this is a headline
9474 (let ((pos (point)) (col (current-column)) ncol tags-l p)
9475 (beginning-of-line 1)
9476 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9477 (< pos (match-beginning 2)))
9478 (progn
9479 (setq tags-l (- (match-end 2) (match-beginning 2)))
9480 (goto-char (match-beginning 1))
9481 (insert " ")
9482 (delete-region (point) (1+ (match-beginning 2)))
9483 (setq ncol (max (1+ (current-column))
9484 (1+ col)
9485 (if (> to-col 0)
9486 to-col
9487 (- (abs to-col) tags-l))))
9488 (setq p (point))
9489 (insert (make-string (- ncol (current-column)) ?\ ))
9490 (setq ncol (current-column))
9491 (when indent-tabs-mode (tabify p (point-at-eol)))
9492 (org-move-to-column (min ncol col) t))
9493 (goto-char pos))))
9495 (defun org-set-tags-command (&optional arg just-align)
9496 "Call the set-tags command for the current entry."
9497 (interactive "P")
9498 (if (org-on-heading-p)
9499 (org-set-tags arg just-align)
9500 (save-excursion
9501 (org-back-to-heading t)
9502 (org-set-tags arg just-align))))
9504 (defun org-set-tags (&optional arg just-align)
9505 "Set the tags for the current headline.
9506 With prefix ARG, realign all tags in headings in the current buffer."
9507 (interactive "P")
9508 (let* ((re (concat "^" outline-regexp))
9509 (current (org-get-tags-string))
9510 (col (current-column))
9511 (org-setting-tags t)
9512 table current-tags inherited-tags ; computed below when needed
9513 tags p0 c0 c1 rpl)
9514 (if arg
9515 (save-excursion
9516 (goto-char (point-min))
9517 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
9518 (while (re-search-forward re nil t)
9519 (org-set-tags nil t)
9520 (end-of-line 1)))
9521 (message "All tags realigned to column %d" org-tags-column))
9522 (if just-align
9523 (setq tags current)
9524 ;; Get a new set of tags from the user
9525 (save-excursion
9526 (setq table (or org-tag-alist (org-get-buffer-tags))
9527 org-last-tags-completion-table table
9528 current-tags (org-split-string current ":")
9529 inherited-tags (nreverse
9530 (nthcdr (length current-tags)
9531 (nreverse (org-get-tags-at))))
9532 tags
9533 (if (or (eq t org-use-fast-tag-selection)
9534 (and org-use-fast-tag-selection
9535 (delq nil (mapcar 'cdr table))))
9536 (org-fast-tag-selection
9537 current-tags inherited-tags table
9538 (if org-fast-tag-selection-include-todo org-todo-key-alist))
9539 (let ((org-add-colon-after-tag-completion t))
9540 (org-trim
9541 (org-without-partial-completion
9542 (org-ido-completing-read "Tags: " 'org-tags-completion-function
9543 nil nil current 'org-tags-history)))))))
9544 (while (string-match "[-+&]+" tags)
9545 ;; No boolean logic, just a list
9546 (setq tags (replace-match ":" t t tags))))
9548 (if (string-match "\\`[\t ]*\\'" tags)
9549 (setq tags "")
9550 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
9551 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
9553 ;; Insert new tags at the correct column
9554 (beginning-of-line 1)
9555 (cond
9556 ((and (equal current "") (equal tags "")))
9557 ((re-search-forward
9558 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
9559 (point-at-eol) t)
9560 (if (equal tags "")
9561 (setq rpl "")
9562 (goto-char (match-beginning 0))
9563 (setq c0 (current-column) p0 (point)
9564 c1 (max (1+ c0) (if (> org-tags-column 0)
9565 org-tags-column
9566 (- (- org-tags-column) (length tags))))
9567 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
9568 (replace-match rpl t t)
9569 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
9570 tags)
9571 (t (error "Tags alignment failed")))
9572 (org-move-to-column col)
9573 (unless just-align
9574 (run-hooks 'org-after-tags-change-hook)))))
9576 (defun org-change-tag-in-region (beg end tag off)
9577 "Add or remove TAG for each entry in the region.
9578 This works in the agenda, and also in an org-mode buffer."
9579 (interactive
9580 (list (region-beginning) (region-end)
9581 (let ((org-last-tags-completion-table
9582 (if (org-mode-p)
9583 (org-get-buffer-tags)
9584 (org-global-tags-completion-table))))
9585 (org-ido-completing-read
9586 "Tag: " 'org-tags-completion-function nil nil nil
9587 'org-tags-history))
9588 (progn
9589 (message "[s]et or [r]emove? ")
9590 (equal (read-char-exclusive) ?r))))
9591 (if (fboundp 'deactivate-mark) (deactivate-mark))
9592 (let ((agendap (equal major-mode 'org-agenda-mode))
9593 l1 l2 m buf pos newhead (cnt 0))
9594 (goto-char end)
9595 (setq l2 (1- (org-current-line)))
9596 (goto-char beg)
9597 (setq l1 (org-current-line))
9598 (loop for l from l1 to l2 do
9599 (goto-line l)
9600 (setq m (get-text-property (point) 'org-hd-marker))
9601 (when (or (and (org-mode-p) (org-on-heading-p))
9602 (and agendap m))
9603 (setq buf (if agendap (marker-buffer m) (current-buffer))
9604 pos (if agendap m (point)))
9605 (with-current-buffer buf
9606 (save-excursion
9607 (save-restriction
9608 (goto-char pos)
9609 (setq cnt (1+ cnt))
9610 (org-toggle-tag tag (if off 'off 'on))
9611 (setq newhead (org-get-heading)))))
9612 (and agendap (org-agenda-change-all-lines newhead m))))
9613 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
9615 (defun org-tags-completion-function (string predicate &optional flag)
9616 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
9617 (confirm (lambda (x) (stringp (car x)))))
9618 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
9619 (setq s1 (match-string 1 string)
9620 s2 (match-string 2 string))
9621 (setq s1 "" s2 string))
9622 (cond
9623 ((eq flag nil)
9624 ;; try completion
9625 (setq rtn (try-completion s2 ctable confirm))
9626 (if (stringp rtn)
9627 (setq rtn
9628 (concat s1 s2 (substring rtn (length s2))
9629 (if (and org-add-colon-after-tag-completion
9630 (assoc rtn ctable))
9631 ":" ""))))
9632 rtn)
9633 ((eq flag t)
9634 ;; all-completions
9635 (all-completions s2 ctable confirm)
9637 ((eq flag 'lambda)
9638 ;; exact match?
9639 (assoc s2 ctable)))
9642 (defun org-fast-tag-insert (kwd tags face &optional end)
9643 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
9644 (insert (format "%-12s" (concat kwd ":"))
9645 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
9646 (or end "")))
9648 (defun org-fast-tag-show-exit (flag)
9649 (save-excursion
9650 (goto-line 3)
9651 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
9652 (replace-match ""))
9653 (when flag
9654 (end-of-line 1)
9655 (org-move-to-column (- (window-width) 19) t)
9656 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
9658 (defun org-set-current-tags-overlay (current prefix)
9659 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
9660 (if (featurep 'xemacs)
9661 (org-overlay-display org-tags-overlay (concat prefix s)
9662 'secondary-selection)
9663 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
9664 (org-overlay-display org-tags-overlay (concat prefix s)))))
9666 (defun org-fast-tag-selection (current inherited table &optional todo-table)
9667 "Fast tag selection with single keys.
9668 CURRENT is the current list of tags in the headline, INHERITED is the
9669 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
9670 possibly with grouping information. TODO-TABLE is a similar table with
9671 TODO keywords, should these have keys assigned to them.
9672 If the keys are nil, a-z are automatically assigned.
9673 Returns the new tags string, or nil to not change the current settings."
9674 (let* ((fulltable (append table todo-table))
9675 (maxlen (apply 'max (mapcar
9676 (lambda (x)
9677 (if (stringp (car x)) (string-width (car x)) 0))
9678 fulltable)))
9679 (buf (current-buffer))
9680 (expert (eq org-fast-tag-selection-single-key 'expert))
9681 (buffer-tags nil)
9682 (fwidth (+ maxlen 3 1 3))
9683 (ncol (/ (- (window-width) 4) fwidth))
9684 (i-face 'org-done)
9685 (c-face 'org-todo)
9686 tg cnt e c char c1 c2 ntable tbl rtn
9687 ov-start ov-end ov-prefix
9688 (exit-after-next org-fast-tag-selection-single-key)
9689 (done-keywords org-done-keywords)
9690 groups ingroup)
9691 (save-excursion
9692 (beginning-of-line 1)
9693 (if (looking-at
9694 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9695 (setq ov-start (match-beginning 1)
9696 ov-end (match-end 1)
9697 ov-prefix "")
9698 (setq ov-start (1- (point-at-eol))
9699 ov-end (1+ ov-start))
9700 (skip-chars-forward "^\n\r")
9701 (setq ov-prefix
9702 (concat
9703 (buffer-substring (1- (point)) (point))
9704 (if (> (current-column) org-tags-column)
9706 (make-string (- org-tags-column (current-column)) ?\ ))))))
9707 (org-move-overlay org-tags-overlay ov-start ov-end)
9708 (save-window-excursion
9709 (if expert
9710 (set-buffer (get-buffer-create " *Org tags*"))
9711 (delete-other-windows)
9712 (split-window-vertically)
9713 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
9714 (erase-buffer)
9715 (org-set-local 'org-done-keywords done-keywords)
9716 (org-fast-tag-insert "Inherited" inherited i-face "\n")
9717 (org-fast-tag-insert "Current" current c-face "\n\n")
9718 (org-fast-tag-show-exit exit-after-next)
9719 (org-set-current-tags-overlay current ov-prefix)
9720 (setq tbl fulltable char ?a cnt 0)
9721 (while (setq e (pop tbl))
9722 (cond
9723 ((equal e '(:startgroup))
9724 (push '() groups) (setq ingroup t)
9725 (when (not (= cnt 0))
9726 (setq cnt 0)
9727 (insert "\n"))
9728 (insert "{ "))
9729 ((equal e '(:endgroup))
9730 (setq ingroup nil cnt 0)
9731 (insert "}\n"))
9733 (setq tg (car e) c2 nil)
9734 (if (cdr e)
9735 (setq c (cdr e))
9736 ;; automatically assign a character.
9737 (setq c1 (string-to-char
9738 (downcase (substring
9739 tg (if (= (string-to-char tg) ?@) 1 0)))))
9740 (if (or (rassoc c1 ntable) (rassoc c1 table))
9741 (while (or (rassoc char ntable) (rassoc char table))
9742 (setq char (1+ char)))
9743 (setq c2 c1))
9744 (setq c (or c2 char)))
9745 (if ingroup (push tg (car groups)))
9746 (setq tg (org-add-props tg nil 'face
9747 (cond
9748 ((not (assoc tg table))
9749 (org-get-todo-face tg))
9750 ((member tg current) c-face)
9751 ((member tg inherited) i-face)
9752 (t nil))))
9753 (if (and (= cnt 0) (not ingroup)) (insert " "))
9754 (insert "[" c "] " tg (make-string
9755 (- fwidth 4 (length tg)) ?\ ))
9756 (push (cons tg c) ntable)
9757 (when (= (setq cnt (1+ cnt)) ncol)
9758 (insert "\n")
9759 (if ingroup (insert " "))
9760 (setq cnt 0)))))
9761 (setq ntable (nreverse ntable))
9762 (insert "\n")
9763 (goto-char (point-min))
9764 (if (not expert) (org-fit-window-to-buffer))
9765 (setq rtn
9766 (catch 'exit
9767 (while t
9768 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
9769 (if groups " [!] no groups" " [!]groups")
9770 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
9771 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9772 (cond
9773 ((= c ?\r) (throw 'exit t))
9774 ((= c ?!)
9775 (setq groups (not groups))
9776 (goto-char (point-min))
9777 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
9778 ((= c ?\C-c)
9779 (if (not expert)
9780 (org-fast-tag-show-exit
9781 (setq exit-after-next (not exit-after-next)))
9782 (setq expert nil)
9783 (delete-other-windows)
9784 (split-window-vertically)
9785 (org-switch-to-buffer-other-window " *Org tags*")
9786 (org-fit-window-to-buffer)))
9787 ((or (= c ?\C-g)
9788 (and (= c ?q) (not (rassoc c ntable))))
9789 (org-detach-overlay org-tags-overlay)
9790 (setq quit-flag t))
9791 ((= c ?\ )
9792 (setq current nil)
9793 (if exit-after-next (setq exit-after-next 'now)))
9794 ((= c ?\t)
9795 (condition-case nil
9796 (setq tg (org-ido-completing-read
9797 "Tag: "
9798 (or buffer-tags
9799 (with-current-buffer buf
9800 (org-get-buffer-tags)))))
9801 (quit (setq tg "")))
9802 (when (string-match "\\S-" tg)
9803 (add-to-list 'buffer-tags (list tg))
9804 (if (member tg current)
9805 (setq current (delete tg current))
9806 (push tg current)))
9807 (if exit-after-next (setq exit-after-next 'now)))
9808 ((setq e (rassoc c todo-table) tg (car e))
9809 (with-current-buffer buf
9810 (save-excursion (org-todo tg)))
9811 (if exit-after-next (setq exit-after-next 'now)))
9812 ((setq e (rassoc c ntable) tg (car e))
9813 (if (member tg current)
9814 (setq current (delete tg current))
9815 (loop for g in groups do
9816 (if (member tg g)
9817 (mapc (lambda (x)
9818 (setq current (delete x current)))
9819 g)))
9820 (push tg current))
9821 (if exit-after-next (setq exit-after-next 'now))))
9823 ;; Create a sorted list
9824 (setq current
9825 (sort current
9826 (lambda (a b)
9827 (assoc b (cdr (memq (assoc a ntable) ntable))))))
9828 (if (eq exit-after-next 'now) (throw 'exit t))
9829 (goto-char (point-min))
9830 (beginning-of-line 2)
9831 (delete-region (point) (point-at-eol))
9832 (org-fast-tag-insert "Current" current c-face)
9833 (org-set-current-tags-overlay current ov-prefix)
9834 (while (re-search-forward
9835 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
9836 (setq tg (match-string 1))
9837 (add-text-properties
9838 (match-beginning 1) (match-end 1)
9839 (list 'face
9840 (cond
9841 ((member tg current) c-face)
9842 ((member tg inherited) i-face)
9843 (t (get-text-property (match-beginning 1) 'face))))))
9844 (goto-char (point-min)))))
9845 (org-detach-overlay org-tags-overlay)
9846 (if rtn
9847 (mapconcat 'identity current ":")
9848 nil))))
9850 (defun org-get-tags-string ()
9851 "Get the TAGS string in the current headline."
9852 (unless (org-on-heading-p t)
9853 (error "Not on a heading"))
9854 (save-excursion
9855 (beginning-of-line 1)
9856 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9857 (org-match-string-no-properties 1)
9858 "")))
9860 (defun org-get-tags ()
9861 "Get the list of tags specified in the current headline."
9862 (org-split-string (org-get-tags-string) ":"))
9864 (defun org-get-buffer-tags ()
9865 "Get a table of all tags used in the buffer, for completion."
9866 (let (tags)
9867 (save-excursion
9868 (goto-char (point-min))
9869 (while (re-search-forward
9870 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
9871 (when (equal (char-after (point-at-bol 0)) ?*)
9872 (mapc (lambda (x) (add-to-list 'tags x))
9873 (org-split-string (org-match-string-no-properties 1) ":")))))
9874 (mapcar 'list tags)))
9876 ;;;; The mapping API
9878 ;;;###autoload
9879 (defun org-map-entries (func &optional match scope &rest skip)
9880 "Call FUNC at each headline selected by MATCH in SCOPE.
9882 FUNC is a function or a lisp form. The function will be called without
9883 arguments, with the cursor positioned at the beginning of the headline.
9884 The return values of all calls to the function will be collected and
9885 returned as a list.
9887 MATCH is a tags/property/todo match as it is used in the agenda tags view.
9888 Only headlines that are matched by this query will be considered during
9889 the iteration. When MATCH is nil or t, all headlines will be
9890 visited by the iteration.
9892 SCOPE determines the scope of this command. It can be any of:
9894 nil The current buffer, respecting the restriction if any
9895 tree The subtree started with the entry at point
9896 file The current buffer, without restriction
9897 file-with-archives
9898 The current buffer, and any archives associated with it
9899 agenda All agenda files
9900 agenda-with-archives
9901 All agenda files with any archive files associated with them
9902 \(file1 file2 ...)
9903 If this is a list, all files in the list will be scanned
9905 The remaining args are treated as settings for the skipping facilities of
9906 the scanner. The following items can be given here:
9908 archive skip trees with the archive tag.
9909 comment skip trees with the COMMENT keyword
9910 function or Emacs Lisp form:
9911 will be used as value for `org-agenda-skip-function', so whenever
9912 the the function returns t, FUNC will not be called for that
9913 entry and search will continue from the point where the
9914 function leaves it."
9915 (let* ((org-agenda-archives-mode nil) ; just to make sure
9916 (org-agenda-skip-archived-trees (memq 'archive skip))
9917 (org-agenda-skip-comment-trees (memq 'comment skip))
9918 (org-agenda-skip-function
9919 (car (org-delete-all '(comment archive) skip)))
9920 (org-tags-match-list-sublevels t)
9921 matcher pos file res
9922 org-todo-keywords-for-agenda
9923 org-done-keywords-for-agenda
9924 org-todo-keyword-alist-for-agenda
9925 org-tag-alist-for-agenda)
9927 (cond
9928 ((eq match t) (setq matcher t))
9929 ((eq match nil) (setq matcher t))
9930 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
9932 (when (eq scope 'tree)
9933 (org-back-to-heading t)
9934 (org-narrow-to-subtree)
9935 (setq scope nil))
9937 (if (not scope)
9938 (progn
9939 (org-prepare-agenda-buffers
9940 (list (buffer-file-name (current-buffer))))
9941 (org-scan-tags func matcher))
9942 ;; Get the right scope
9943 (setq pos (point))
9944 (cond
9945 ((and scope (listp scope) (symbolp (car scope)))
9946 (setq scope (eval scope)))
9947 ((eq scope 'agenda)
9948 (setq scope (org-agenda-files t)))
9949 ((eq scope 'agenda-with-archives)
9950 (setq scope (org-agenda-files t))
9951 (setq scope (org-add-archive-files scope)))
9952 ((eq scope 'file)
9953 (setq scope (list (buffer-file-name))))
9954 ((eq scope 'file-with-archives)
9955 (setq scope (org-add-archive-files (list (buffer-file-name))))))
9956 (org-prepare-agenda-buffers scope)
9957 (while (setq file (pop scope))
9958 (with-current-buffer (org-find-base-buffer-visiting file)
9959 (save-excursion
9960 (save-restriction
9961 (widen)
9962 (goto-char (point-min))
9963 (setq res (append res (org-scan-tags func matcher)))))))
9964 res)))
9966 ;;;; Properties
9968 ;;; Setting and retrieving properties
9970 (defconst org-special-properties
9971 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
9972 "TIMESTAMP" "TIMESTAMP_IA")
9973 "The special properties valid in Org-mode.
9975 These are properties that are not defined in the property drawer,
9976 but in some other way.")
9978 (defconst org-default-properties
9979 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
9980 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
9981 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
9982 "EXPORT_FILE_NAME" "EXPORT_TITLE")
9983 "Some properties that are used by Org-mode for various purposes.
9984 Being in this list makes sure that they are offered for completion.")
9986 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
9987 "Regular expression matching the first line of a property drawer.")
9989 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
9990 "Regular expression matching the first line of a property drawer.")
9992 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
9993 "Regular expression matching the first line of a property drawer.")
9995 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
9996 "Regular expression matching the first line of a property drawer.")
9998 (defconst org-property-drawer-re
9999 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
10000 org-property-end-re "\\)\n?")
10001 "Matches an entire property drawer.")
10003 (defconst org-clock-drawer-re
10004 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
10005 org-property-end-re "\\)\n?")
10006 "Matches an entire clock drawer.")
10008 (defun org-property-action ()
10009 "Do an action on properties."
10010 (interactive)
10011 (let (c)
10012 (org-at-property-p)
10013 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
10014 (setq c (read-char-exclusive))
10015 (cond
10016 ((equal c ?s)
10017 (call-interactively 'org-set-property))
10018 ((equal c ?d)
10019 (call-interactively 'org-delete-property))
10020 ((equal c ?D)
10021 (call-interactively 'org-delete-property-globally))
10022 ((equal c ?c)
10023 (call-interactively 'org-compute-property-at-point))
10024 (t (error "No such property action %c" c)))))
10026 (defun org-at-property-p ()
10027 "Is the cursor in a property line?"
10028 ;; FIXME: Does not check if we are actually in the drawer.
10029 ;; FIXME: also returns true on any drawers.....
10030 ;; This is used by C-c C-c for property action.
10031 (save-excursion
10032 (beginning-of-line 1)
10033 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
10035 (defun org-get-property-block (&optional beg end force)
10036 "Return the (beg . end) range of the body of the property drawer.
10037 BEG and END can be beginning and end of subtree, if not given
10038 they will be found.
10039 If the drawer does not exist and FORCE is non-nil, create the drawer."
10040 (catch 'exit
10041 (save-excursion
10042 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
10043 (end (or end (progn (outline-next-heading) (point)))))
10044 (goto-char beg)
10045 (if (re-search-forward org-property-start-re end t)
10046 (setq beg (1+ (match-end 0)))
10047 (if force
10048 (save-excursion
10049 (org-insert-property-drawer)
10050 (setq end (progn (outline-next-heading) (point))))
10051 (throw 'exit nil))
10052 (goto-char beg)
10053 (if (re-search-forward org-property-start-re end t)
10054 (setq beg (1+ (match-end 0)))))
10055 (if (re-search-forward org-property-end-re end t)
10056 (setq end (match-beginning 0))
10057 (or force (throw 'exit nil))
10058 (goto-char beg)
10059 (setq end beg)
10060 (org-indent-line-function)
10061 (insert ":END:\n"))
10062 (cons beg end)))))
10064 (defun org-entry-properties (&optional pom which)
10065 "Get all properties of the entry at point-or-marker POM.
10066 This includes the TODO keyword, the tags, time strings for deadline,
10067 scheduled, and clocking, and any additional properties defined in the
10068 entry. The return value is an alist, keys may occur multiple times
10069 if the property key was used several times.
10070 POM may also be nil, in which case the current entry is used.
10071 If WHICH is nil or `all', get all properties. If WHICH is
10072 `special' or `standard', only get that subclass."
10073 (setq which (or which 'all))
10074 (org-with-point-at pom
10075 (let ((clockstr (substring org-clock-string 0 -1))
10076 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
10077 beg end range props sum-props key value string clocksum)
10078 (save-excursion
10079 (when (condition-case nil (org-back-to-heading t) (error nil))
10080 (setq beg (point))
10081 (setq sum-props (get-text-property (point) 'org-summaries))
10082 (setq clocksum (get-text-property (point) :org-clock-minutes))
10083 (outline-next-heading)
10084 (setq end (point))
10085 (when (memq which '(all special))
10086 ;; Get the special properties, like TODO and tags
10087 (goto-char beg)
10088 (when (and (looking-at org-todo-line-regexp) (match-end 2))
10089 (push (cons "TODO" (org-match-string-no-properties 2)) props))
10090 (when (looking-at org-priority-regexp)
10091 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
10092 (when (and (setq value (org-get-tags-string))
10093 (string-match "\\S-" value))
10094 (push (cons "TAGS" value) props))
10095 (when (setq value (org-get-tags-at))
10096 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
10097 props))
10098 (while (re-search-forward org-maybe-keyword-time-regexp end t)
10099 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
10100 string (if (equal key clockstr)
10101 (org-no-properties
10102 (org-trim
10103 (buffer-substring
10104 (match-beginning 3) (goto-char (point-at-eol)))))
10105 (substring (org-match-string-no-properties 3) 1 -1)))
10106 (unless key
10107 (if (= (char-after (match-beginning 3)) ?\[)
10108 (setq key "TIMESTAMP_IA")
10109 (setq key "TIMESTAMP")))
10110 (when (or (equal key clockstr) (not (assoc key props)))
10111 (push (cons key string) props)))
10115 (when (memq which '(all standard))
10116 ;; Get the standard properties, like :PORP: ...
10117 (setq range (org-get-property-block beg end))
10118 (when range
10119 (goto-char (car range))
10120 (while (re-search-forward
10121 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
10122 (cdr range) t)
10123 (setq key (org-match-string-no-properties 1)
10124 value (org-trim (or (org-match-string-no-properties 2) "")))
10125 (unless (member key excluded)
10126 (push (cons key (or value "")) props)))))
10127 (if clocksum
10128 (push (cons "CLOCKSUM"
10129 (org-columns-number-to-string (/ (float clocksum) 60.)
10130 'add_times))
10131 props))
10132 (unless (assoc "CATEGORY" props)
10133 (setq value (or (org-get-category)
10134 (progn (org-refresh-category-properties)
10135 (org-get-category))))
10136 (push (cons "CATEGORY" value) props))
10137 (append sum-props (nreverse props)))))))
10139 (defun org-entry-get (pom property &optional inherit)
10140 "Get value of PROPERTY for entry at point-or-marker POM.
10141 If INHERIT is non-nil and the entry does not have the property,
10142 then also check higher levels of the hierarchy.
10143 If INHERIT is the symbol `selective', use inheritance only if the setting
10144 in `org-use-property-inheritance' selects PROPERTY for inheritance.
10145 If the property is present but empty, the return value is the empty string.
10146 If the property is not present at all, nil is returned."
10147 (org-with-point-at pom
10148 (if (and inherit (if (eq inherit 'selective)
10149 (org-property-inherit-p property)
10151 (org-entry-get-with-inheritance property)
10152 (if (member property org-special-properties)
10153 ;; We need a special property. Use brute force, get all properties.
10154 (cdr (assoc property (org-entry-properties nil 'special)))
10155 (let ((range (org-get-property-block)))
10156 (if (and range
10157 (goto-char (car range))
10158 (re-search-forward
10159 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
10160 (cdr range) t))
10161 ;; Found the property, return it.
10162 (if (match-end 1)
10163 (org-match-string-no-properties 1)
10164 "")))))))
10166 (defun org-property-or-variable-value (var &optional inherit)
10167 "Check if there is a property fixing the value of VAR.
10168 If yes, return this value. If not, return the current value of the variable."
10169 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
10170 (if (and prop (stringp prop) (string-match "\\S-" prop))
10171 (read prop)
10172 (symbol-value var))))
10174 (defun org-entry-delete (pom property)
10175 "Delete the property PROPERTY from entry at point-or-marker POM."
10176 (org-with-point-at pom
10177 (if (member property org-special-properties)
10178 nil ; cannot delete these properties.
10179 (let ((range (org-get-property-block)))
10180 (if (and range
10181 (goto-char (car range))
10182 (re-search-forward
10183 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
10184 (cdr range) t))
10185 (progn
10186 (delete-region (match-beginning 0) (1+ (point-at-eol)))
10188 nil)))))
10190 ;; Multi-values properties are properties that contain multiple values
10191 ;; These values are assumed to be single words, separated by whitespace.
10192 (defun org-entry-add-to-multivalued-property (pom property value)
10193 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
10194 (let* ((old (org-entry-get pom property))
10195 (values (and old (org-split-string old "[ \t]"))))
10196 (setq value (org-entry-protect-space value))
10197 (unless (member value values)
10198 (setq values (cons value values))
10199 (org-entry-put pom property
10200 (mapconcat 'identity values " ")))))
10202 (defun org-entry-remove-from-multivalued-property (pom property value)
10203 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
10204 (let* ((old (org-entry-get pom property))
10205 (values (and old (org-split-string old "[ \t]"))))
10206 (setq value (org-entry-protect-space value))
10207 (when (member value values)
10208 (setq values (delete value values))
10209 (org-entry-put pom property
10210 (mapconcat 'identity values " ")))))
10212 (defun org-entry-member-in-multivalued-property (pom property value)
10213 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
10214 (let* ((old (org-entry-get pom property))
10215 (values (and old (org-split-string old "[ \t]"))))
10216 (setq value (org-entry-protect-space value))
10217 (member value values)))
10219 (defun org-entry-get-multivalued-property (pom property)
10220 "Return a list of values in a multivalued property."
10221 (let* ((value (org-entry-get pom property))
10222 (values (and value (org-split-string value "[ \t]"))))
10223 (mapcar 'org-entry-restore-space values)))
10225 (defun org-entry-put-multivalued-property (pom property &rest values)
10226 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
10227 VALUES should be a list of strings. Spaces will be protected."
10228 (org-entry-put pom property
10229 (mapconcat 'org-entry-protect-space values " "))
10230 (let* ((value (org-entry-get pom property))
10231 (values (and value (org-split-string value "[ \t]"))))
10232 (mapcar 'org-entry-restore-space values)))
10234 (defun org-entry-protect-space (s)
10235 "Protect spaces and newline in string S."
10236 (while (string-match " " s)
10237 (setq s (replace-match "%20" t t s)))
10238 (while (string-match "\n" s)
10239 (setq s (replace-match "%0A" t t s)))
10242 (defun org-entry-restore-space (s)
10243 "Restore spaces and newline in string S."
10244 (while (string-match "%20" s)
10245 (setq s (replace-match " " t t s)))
10246 (while (string-match "%0A" s)
10247 (setq s (replace-match "\n" t t s)))
10250 (defvar org-entry-property-inherited-from (make-marker)
10251 "Marker pointing to the entry from where a proerty was inherited.
10252 Each call to `org-entry-get-with-inheritance' will set this marker to the
10253 location of the entry where the inheriance search matched. If there was
10254 no match, the marker will point nowhere.
10255 Note that also `org-entry-get' calls this function, if the INHERIT flag
10256 is set.")
10258 (defun org-entry-get-with-inheritance (property)
10259 "Get entry property, and search higher levels if not present."
10260 (move-marker org-entry-property-inherited-from nil)
10261 (let (tmp)
10262 (save-excursion
10263 (save-restriction
10264 (widen)
10265 (catch 'ex
10266 (while t
10267 (when (setq tmp (org-entry-get nil property))
10268 (org-back-to-heading t)
10269 (move-marker org-entry-property-inherited-from (point))
10270 (throw 'ex tmp))
10271 (or (org-up-heading-safe) (throw 'ex nil)))))
10272 (or tmp
10273 (cdr (assoc property org-file-properties))
10274 (cdr (assoc property org-global-properties))
10275 (cdr (assoc property org-global-properties-fixed))))))
10277 (defun org-entry-put (pom property value)
10278 "Set PROPERTY to VALUE for entry at point-or-marker POM."
10279 (org-with-point-at pom
10280 (org-back-to-heading t)
10281 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
10282 range)
10283 (cond
10284 ((equal property "TODO")
10285 (when (and (stringp value) (string-match "\\S-" value)
10286 (not (member value org-todo-keywords-1)))
10287 (error "\"%s\" is not a valid TODO state" value))
10288 (if (or (not value)
10289 (not (string-match "\\S-" value)))
10290 (setq value 'none))
10291 (org-todo value)
10292 (org-set-tags nil 'align))
10293 ((equal property "PRIORITY")
10294 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
10295 (string-to-char value) ?\ ))
10296 (org-set-tags nil 'align))
10297 ((equal property "SCHEDULED")
10298 (if (re-search-forward org-scheduled-time-regexp end t)
10299 (cond
10300 ((eq value 'earlier) (org-timestamp-change -1 'day))
10301 ((eq value 'later) (org-timestamp-change 1 'day))
10302 (t (call-interactively 'org-schedule)))
10303 (call-interactively 'org-schedule)))
10304 ((equal property "DEADLINE")
10305 (if (re-search-forward org-deadline-time-regexp end t)
10306 (cond
10307 ((eq value 'earlier) (org-timestamp-change -1 'day))
10308 ((eq value 'later) (org-timestamp-change 1 'day))
10309 (t (call-interactively 'org-deadline)))
10310 (call-interactively 'org-deadline)))
10311 ((member property org-special-properties)
10312 (error "The %s property can not yet be set with `org-entry-put'"
10313 property))
10314 (t ; a non-special property
10315 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
10316 (setq range (org-get-property-block beg end 'force))
10317 (goto-char (car range))
10318 (if (re-search-forward
10319 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
10320 (progn
10321 (delete-region (match-beginning 1) (match-end 1))
10322 (goto-char (match-beginning 1)))
10323 (goto-char (cdr range))
10324 (insert "\n")
10325 (backward-char 1)
10326 (org-indent-line-function)
10327 (insert ":" property ":"))
10328 (and value (insert " " value))
10329 (org-indent-line-function)))))))
10331 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
10332 "Get all property keys in the current buffer.
10333 With INCLUDE-SPECIALS, also list the special properties that relect things
10334 like tags and TODO state.
10335 With INCLUDE-DEFAULTS, also include properties that has special meaning
10336 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
10337 With INCLUDE-COLUMNS, also include property names given in COLUMN
10338 formats in the current buffer."
10339 (let (rtn range cfmt cols s p)
10340 (save-excursion
10341 (save-restriction
10342 (widen)
10343 (goto-char (point-min))
10344 (while (re-search-forward org-property-start-re nil t)
10345 (setq range (org-get-property-block))
10346 (goto-char (car range))
10347 (while (re-search-forward
10348 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
10349 (cdr range) t)
10350 (add-to-list 'rtn (org-match-string-no-properties 1)))
10351 (outline-next-heading))))
10353 (when include-specials
10354 (setq rtn (append org-special-properties rtn)))
10356 (when include-defaults
10357 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
10359 (when include-columns
10360 (save-excursion
10361 (save-restriction
10362 (widen)
10363 (goto-char (point-min))
10364 (while (re-search-forward
10365 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
10366 nil t)
10367 (setq cfmt (match-string 2) s 0)
10368 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
10369 cfmt s)
10370 (setq s (match-end 0)
10371 p (match-string 1 cfmt))
10372 (unless (or (equal p "ITEM")
10373 (member p org-special-properties))
10374 (add-to-list 'rtn (match-string 1 cfmt))))))))
10376 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
10378 (defun org-property-values (key)
10379 "Return a list of all values of property KEY."
10380 (save-excursion
10381 (save-restriction
10382 (widen)
10383 (goto-char (point-min))
10384 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
10385 values)
10386 (while (re-search-forward re nil t)
10387 (add-to-list 'values (org-trim (match-string 1))))
10388 (delete "" values)))))
10390 (defun org-insert-property-drawer ()
10391 "Insert a property drawer into the current entry."
10392 (interactive)
10393 (org-back-to-heading t)
10394 (looking-at outline-regexp)
10395 (let ((indent (- (match-end 0)(match-beginning 0)))
10396 (beg (point))
10397 (re (concat "^[ \t]*" org-keyword-time-regexp))
10398 end hiddenp)
10399 (outline-next-heading)
10400 (setq end (point))
10401 (goto-char beg)
10402 (while (re-search-forward re end t))
10403 (setq hiddenp (org-invisible-p))
10404 (end-of-line 1)
10405 (and (equal (char-after) ?\n) (forward-char 1))
10406 (while (looking-at "^[ \t]*\\(:CLOCK:\\|CLOCK\\|:END:\\)")
10407 (beginning-of-line 2))
10408 (org-skip-over-state-notes)
10409 (skip-chars-backward " \t\n\r")
10410 (if (eq (char-before) ?*) (forward-char 1))
10411 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
10412 (beginning-of-line 0)
10413 (org-indent-to-column indent)
10414 (beginning-of-line 2)
10415 (org-indent-to-column indent)
10416 (beginning-of-line 0)
10417 (if hiddenp
10418 (save-excursion
10419 (org-back-to-heading t)
10420 (hide-entry))
10421 (org-flag-drawer t))))
10423 (defun org-set-property (property value)
10424 "In the current entry, set PROPERTY to VALUE.
10425 When called interactively, this will prompt for a property name, offering
10426 completion on existing and default properties. And then it will prompt
10427 for a value, offering competion either on allowed values (via an inherited
10428 xxx_ALL property) or on existing values in other instances of this property
10429 in the current file."
10430 (interactive
10431 (let* ((completion-ignore-case t)
10432 (keys (org-buffer-property-keys nil t t))
10433 (prop0 (org-ido-completing-read "Property: " (mapcar 'list keys)))
10434 (prop (if (member prop0 keys)
10435 prop0
10436 (or (cdr (assoc (downcase prop0)
10437 (mapcar (lambda (x) (cons (downcase x) x))
10438 keys)))
10439 prop0)))
10440 (cur (org-entry-get nil prop))
10441 (allowed (org-property-get-allowed-values nil prop 'table))
10442 (existing (mapcar 'list (org-property-values prop)))
10443 (val (if allowed
10444 (org-completing-read "Value: " allowed nil 'req-match)
10445 (org-completing-read
10446 (concat "Value" (if (and cur (string-match "\\S-" cur))
10447 (concat "[" cur "]") "")
10448 ": ")
10449 existing nil nil "" nil cur))))
10450 (list prop (if (equal val "") cur val))))
10451 (unless (equal (org-entry-get nil property) value)
10452 (org-entry-put nil property value)))
10454 (defun org-delete-property (property)
10455 "In the current entry, delete PROPERTY."
10456 (interactive
10457 (let* ((completion-ignore-case t)
10458 (prop (org-ido-completing-read
10459 "Property: " (org-entry-properties nil 'standard))))
10460 (list prop)))
10461 (message "Property %s %s" property
10462 (if (org-entry-delete nil property)
10463 "deleted"
10464 "was not present in the entry")))
10466 (defun org-delete-property-globally (property)
10467 "Remove PROPERTY globally, from all entries."
10468 (interactive
10469 (let* ((completion-ignore-case t)
10470 (prop (org-ido-completing-read
10471 "Globally remove property: "
10472 (mapcar 'list (org-buffer-property-keys)))))
10473 (list prop)))
10474 (save-excursion
10475 (save-restriction
10476 (widen)
10477 (goto-char (point-min))
10478 (let ((cnt 0))
10479 (while (re-search-forward
10480 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
10481 nil t)
10482 (setq cnt (1+ cnt))
10483 (replace-match ""))
10484 (message "Property \"%s\" removed from %d entries" property cnt)))))
10486 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
10488 (defun org-compute-property-at-point ()
10489 "Compute the property at point.
10490 This looks for an enclosing column format, extracts the operator and
10491 then applies it to the proerty in the column format's scope."
10492 (interactive)
10493 (unless (org-at-property-p)
10494 (error "Not at a property"))
10495 (let ((prop (org-match-string-no-properties 2)))
10496 (org-columns-get-format-and-top-level)
10497 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
10498 (error "No operator defined for property %s" prop))
10499 (org-columns-compute prop)))
10501 (defun org-property-get-allowed-values (pom property &optional table)
10502 "Get allowed values for the property PROPERTY.
10503 When TABLE is non-nil, return an alist that can directly be used for
10504 completion."
10505 (let (vals)
10506 (cond
10507 ((equal property "TODO")
10508 (setq vals (org-with-point-at pom
10509 (append org-todo-keywords-1 '("")))))
10510 ((equal property "PRIORITY")
10511 (let ((n org-lowest-priority))
10512 (while (>= n org-highest-priority)
10513 (push (char-to-string n) vals)
10514 (setq n (1- n)))))
10515 ((member property org-special-properties))
10517 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
10519 (when (and vals (string-match "\\S-" vals))
10520 (setq vals (car (read-from-string (concat "(" vals ")"))))
10521 (setq vals (mapcar (lambda (x)
10522 (cond ((stringp x) x)
10523 ((numberp x) (number-to-string x))
10524 ((symbolp x) (symbol-name x))
10525 (t "???")))
10526 vals)))))
10527 (if table (mapcar 'list vals) vals)))
10529 (defun org-property-previous-allowed-value (&optional previous)
10530 "Switch to the next allowed value for this property."
10531 (interactive)
10532 (org-property-next-allowed-value t))
10534 (defun org-property-next-allowed-value (&optional previous)
10535 "Switch to the next allowed value for this property."
10536 (interactive)
10537 (unless (org-at-property-p)
10538 (error "Not at a property"))
10539 (let* ((key (match-string 2))
10540 (value (match-string 3))
10541 (allowed (or (org-property-get-allowed-values (point) key)
10542 (and (member value '("[ ]" "[-]" "[X]"))
10543 '("[ ]" "[X]"))))
10544 nval)
10545 (unless allowed
10546 (error "Allowed values for this property have not been defined"))
10547 (if previous (setq allowed (reverse allowed)))
10548 (if (member value allowed)
10549 (setq nval (car (cdr (member value allowed)))))
10550 (setq nval (or nval (car allowed)))
10551 (if (equal nval value)
10552 (error "Only one allowed value for this property"))
10553 (org-at-property-p)
10554 (replace-match (concat " :" key ": " nval) t t)
10555 (org-indent-line-function)
10556 (beginning-of-line 1)
10557 (skip-chars-forward " \t")))
10559 (defun org-find-entry-with-id (ident)
10560 "Locate the entry that contains the ID property with exact value IDENT.
10561 IDENT can be a string, a symbol or a number, this function will search for
10562 the string representation of it.
10563 Return the position where this entry starts, or nil if there is no such entry."
10564 (let ((id (cond
10565 ((stringp ident) ident)
10566 ((symbol-name ident) (symbol-name ident))
10567 ((numberp ident) (number-to-string ident))
10568 (t (error "IDENT %s must be a string, symbol or number" ident))))
10569 (case-fold-search nil))
10570 (save-excursion
10571 (save-restriction
10572 (widen)
10573 (goto-char (point-min))
10574 (when (re-search-forward
10575 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
10576 nil t)
10577 (org-back-to-heading)
10578 (point))))))
10580 ;;;; Timestamps
10582 (defvar org-last-changed-timestamp nil)
10583 (defvar org-last-inserted-timestamp nil
10584 "The last time stamp inserted with `org-insert-time-stamp'.")
10585 (defvar org-time-was-given) ; dynamically scoped parameter
10586 (defvar org-end-time-was-given) ; dynamically scoped parameter
10587 (defvar org-ts-what) ; dynamically scoped parameter
10589 (defun org-time-stamp (arg &optional inactive)
10590 "Prompt for a date/time and insert a time stamp.
10591 If the user specifies a time like HH:MM, or if this command is called
10592 with a prefix argument, the time stamp will contain date and time.
10593 Otherwise, only the date will be included. All parts of a date not
10594 specified by the user will be filled in from the current date/time.
10595 So if you press just return without typing anything, the time stamp
10596 will represent the current date/time. If there is already a timestamp
10597 at the cursor, it will be modified."
10598 (interactive "P")
10599 (let* ((ts nil)
10600 (default-time
10601 ;; Default time is either today, or, when entering a range,
10602 ;; the range start.
10603 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
10604 (save-excursion
10605 (re-search-backward
10606 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
10607 (- (point) 20) t)))
10608 (apply 'encode-time (org-parse-time-string (match-string 1)))
10609 (current-time)))
10610 (default-input (and ts (org-get-compact-tod ts)))
10611 org-time-was-given org-end-time-was-given time)
10612 (cond
10613 ((and (org-at-timestamp-p t)
10614 (memq last-command '(org-time-stamp org-time-stamp-inactive))
10615 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
10616 (insert "--")
10617 (setq time (let ((this-command this-command))
10618 (org-read-date arg 'totime nil nil
10619 default-time default-input)))
10620 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
10621 ((org-at-timestamp-p t)
10622 (setq time (let ((this-command this-command))
10623 (org-read-date arg 'totime nil nil default-time default-input)))
10624 (when (org-at-timestamp-p t) ; just to get the match data
10625 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
10626 (replace-match "")
10627 (setq org-last-changed-timestamp
10628 (org-insert-time-stamp
10629 time (or org-time-was-given arg)
10630 inactive nil nil (list org-end-time-was-given))))
10631 (message "Timestamp updated"))
10633 (setq time (let ((this-command this-command))
10634 (org-read-date arg 'totime nil nil default-time default-input)))
10635 (org-insert-time-stamp time (or org-time-was-given arg) inactive
10636 nil nil (list org-end-time-was-given))))))
10638 ;; FIXME: can we use this for something else, like computing time differences?
10639 (defun org-get-compact-tod (s)
10640 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
10641 (let* ((t1 (match-string 1 s))
10642 (h1 (string-to-number (match-string 2 s)))
10643 (m1 (string-to-number (match-string 3 s)))
10644 (t2 (and (match-end 4) (match-string 5 s)))
10645 (h2 (and t2 (string-to-number (match-string 6 s))))
10646 (m2 (and t2 (string-to-number (match-string 7 s))))
10647 dh dm)
10648 (if (not t2)
10650 (setq dh (- h2 h1) dm (- m2 m1))
10651 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
10652 (concat t1 "+" (number-to-string dh)
10653 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
10655 (defun org-time-stamp-inactive (&optional arg)
10656 "Insert an inactive time stamp.
10657 An inactive time stamp is enclosed in square brackets instead of angle
10658 brackets. It is inactive in the sense that it does not trigger agenda entries,
10659 does not link to the calendar and cannot be changed with the S-cursor keys.
10660 So these are more for recording a certain time/date."
10661 (interactive "P")
10662 (org-time-stamp arg 'inactive))
10664 (defvar org-date-ovl (org-make-overlay 1 1))
10665 (org-overlay-put org-date-ovl 'face 'org-warning)
10666 (org-detach-overlay org-date-ovl)
10668 (defvar org-ans1) ; dynamically scoped parameter
10669 (defvar org-ans2) ; dynamically scoped parameter
10671 (defvar org-plain-time-of-day-regexp) ; defined below
10673 (defvar org-overriding-default-time nil) ; dynamically scoped
10674 (defvar org-read-date-overlay nil)
10675 (defvar org-dcst nil) ; dynamically scoped
10677 (defun org-read-date (&optional with-time to-time from-string prompt
10678 default-time default-input)
10679 "Read a date, possibly a time, and make things smooth for the user.
10680 The prompt will suggest to enter an ISO date, but you can also enter anything
10681 which will at least partially be understood by `parse-time-string'.
10682 Unrecognized parts of the date will default to the current day, month, year,
10683 hour and minute. If this command is called to replace a timestamp at point,
10684 of to enter the second timestamp of a range, the default time is taken from the
10685 existing stamp. For example,
10686 3-2-5 --> 2003-02-05
10687 feb 15 --> currentyear-02-15
10688 sep 12 9 --> 2009-09-12
10689 12:45 --> today 12:45
10690 22 sept 0:34 --> currentyear-09-22 0:34
10691 12 --> currentyear-currentmonth-12
10692 Fri --> nearest Friday (today or later)
10693 etc.
10695 Furthermore you can specify a relative date by giving, as the *first* thing
10696 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
10697 change in days weeks, months, years.
10698 With a single plus or minus, the date is relative to today. With a double
10699 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
10700 +4d --> four days from today
10701 +4 --> same as above
10702 +2w --> two weeks from today
10703 ++5 --> five days from default date
10705 The function understands only English month and weekday abbreviations,
10706 but this can be configured with the variables `parse-time-months' and
10707 `parse-time-weekdays'.
10709 While prompting, a calendar is popped up - you can also select the
10710 date with the mouse (button 1). The calendar shows a period of three
10711 months. To scroll it to other months, use the keys `>' and `<'.
10712 If you don't like the calendar, turn it off with
10713 \(setq org-read-date-popup-calendar nil)
10715 With optional argument TO-TIME, the date will immediately be converted
10716 to an internal time.
10717 With an optional argument WITH-TIME, the prompt will suggest to also
10718 insert a time. Note that when WITH-TIME is not set, you can still
10719 enter a time, and this function will inform the calling routine about
10720 this change. The calling routine may then choose to change the format
10721 used to insert the time stamp into the buffer to include the time.
10722 With optional argument FROM-STRING, read from this string instead from
10723 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
10724 the time/date that is used for everything that is not specified by the
10725 user."
10726 (require 'parse-time)
10727 (let* ((org-time-stamp-rounding-minutes
10728 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
10729 (org-dcst org-display-custom-times)
10730 (ct (org-current-time))
10731 (def (or org-overriding-default-time default-time ct))
10732 (defdecode (decode-time def))
10733 (dummy (progn
10734 (when (< (nth 2 defdecode) org-extend-today-until)
10735 (setcar (nthcdr 2 defdecode) -1)
10736 (setcar (nthcdr 1 defdecode) 59)
10737 (setq def (apply 'encode-time defdecode)
10738 defdecode (decode-time def)))))
10739 (calendar-move-hook nil)
10740 (calendar-view-diary-initially-flag nil)
10741 (view-diary-entries-initially nil)
10742 (calendar-view-holidays-initially-flag nil)
10743 (view-calendar-holidays-initially nil)
10744 (timestr (format-time-string
10745 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
10746 (prompt (concat (if prompt (concat prompt " ") "")
10747 (format "Date+time [%s]: " timestr)))
10748 ans (org-ans0 "") org-ans1 org-ans2 final)
10750 (cond
10751 (from-string (setq ans from-string))
10752 (org-read-date-popup-calendar
10753 (save-excursion
10754 (save-window-excursion
10755 (calendar)
10756 (calendar-forward-day (- (time-to-days def)
10757 (calendar-absolute-from-gregorian
10758 (calendar-current-date))))
10759 (org-eval-in-calendar nil t)
10760 (let* ((old-map (current-local-map))
10761 (map (copy-keymap calendar-mode-map))
10762 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
10763 (org-defkey map (kbd "RET") 'org-calendar-select)
10764 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
10765 'org-calendar-select-mouse)
10766 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
10767 'org-calendar-select-mouse)
10768 (org-defkey minibuffer-local-map [(meta shift left)]
10769 (lambda () (interactive)
10770 (org-eval-in-calendar '(calendar-backward-month 1))))
10771 (org-defkey minibuffer-local-map [(meta shift right)]
10772 (lambda () (interactive)
10773 (org-eval-in-calendar '(calendar-forward-month 1))))
10774 (org-defkey minibuffer-local-map [(meta shift up)]
10775 (lambda () (interactive)
10776 (org-eval-in-calendar '(calendar-backward-year 1))))
10777 (org-defkey minibuffer-local-map [(meta shift down)]
10778 (lambda () (interactive)
10779 (org-eval-in-calendar '(calendar-forward-year 1))))
10780 (org-defkey minibuffer-local-map [(shift up)]
10781 (lambda () (interactive)
10782 (org-eval-in-calendar '(calendar-backward-week 1))))
10783 (org-defkey minibuffer-local-map [(shift down)]
10784 (lambda () (interactive)
10785 (org-eval-in-calendar '(calendar-forward-week 1))))
10786 (org-defkey minibuffer-local-map [(shift left)]
10787 (lambda () (interactive)
10788 (org-eval-in-calendar '(calendar-backward-day 1))))
10789 (org-defkey minibuffer-local-map [(shift right)]
10790 (lambda () (interactive)
10791 (org-eval-in-calendar '(calendar-forward-day 1))))
10792 (org-defkey minibuffer-local-map ">"
10793 (lambda () (interactive)
10794 (org-eval-in-calendar '(scroll-calendar-left 1))))
10795 (org-defkey minibuffer-local-map "<"
10796 (lambda () (interactive)
10797 (org-eval-in-calendar '(scroll-calendar-right 1))))
10798 (unwind-protect
10799 (progn
10800 (use-local-map map)
10801 (add-hook 'post-command-hook 'org-read-date-display)
10802 (setq org-ans0 (read-string prompt default-input nil nil))
10803 ;; org-ans0: from prompt
10804 ;; org-ans1: from mouse click
10805 ;; org-ans2: from calendar motion
10806 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
10807 (remove-hook 'post-command-hook 'org-read-date-display)
10808 (use-local-map old-map)
10809 (when org-read-date-overlay
10810 (org-delete-overlay org-read-date-overlay)
10811 (setq org-read-date-overlay nil)))))))
10813 (t ; Naked prompt only
10814 (unwind-protect
10815 (setq ans (read-string prompt default-input nil timestr))
10816 (when org-read-date-overlay
10817 (org-delete-overlay org-read-date-overlay)
10818 (setq org-read-date-overlay nil)))))
10820 (setq final (org-read-date-analyze ans def defdecode))
10822 (if to-time
10823 (apply 'encode-time final)
10824 (if (and (boundp 'org-time-was-given) org-time-was-given)
10825 (format "%04d-%02d-%02d %02d:%02d"
10826 (nth 5 final) (nth 4 final) (nth 3 final)
10827 (nth 2 final) (nth 1 final))
10828 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
10829 (defvar def)
10830 (defvar defdecode)
10831 (defvar with-time)
10832 (defun org-read-date-display ()
10833 "Display the currrent date prompt interpretation in the minibuffer."
10834 (when org-read-date-display-live
10835 (when org-read-date-overlay
10836 (org-delete-overlay org-read-date-overlay))
10837 (let ((p (point)))
10838 (end-of-line 1)
10839 (while (not (equal (buffer-substring
10840 (max (point-min) (- (point) 4)) (point))
10841 " "))
10842 (insert " "))
10843 (goto-char p))
10844 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
10845 " " (or org-ans1 org-ans2)))
10846 (org-end-time-was-given nil)
10847 (f (org-read-date-analyze ans def defdecode))
10848 (fmts (if org-dcst
10849 org-time-stamp-custom-formats
10850 org-time-stamp-formats))
10851 (fmt (if (or with-time
10852 (and (boundp 'org-time-was-given) org-time-was-given))
10853 (cdr fmts)
10854 (car fmts)))
10855 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
10856 (when (and org-end-time-was-given
10857 (string-match org-plain-time-of-day-regexp txt))
10858 (setq txt (concat (substring txt 0 (match-end 0)) "-"
10859 org-end-time-was-given
10860 (substring txt (match-end 0)))))
10861 (setq org-read-date-overlay
10862 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
10863 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
10865 (defun org-read-date-analyze (ans def defdecode)
10866 "Analyze the combined answer of the date prompt."
10867 ;; FIXME: cleanup and comment
10868 (let (delta deltan deltaw deltadef year month day
10869 hour minute second wday pm h2 m2 tl wday1
10870 iso-year iso-weekday iso-week iso-year iso-date)
10872 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
10873 (setq ans "+0"))
10875 (when (setq delta (org-read-date-get-relative ans (current-time) def))
10876 (setq ans (replace-match "" t t ans)
10877 deltan (car delta)
10878 deltaw (nth 1 delta)
10879 deltadef (nth 2 delta)))
10881 ;; Check if there is an iso week date in there
10882 ;; If yes, sore the info and ostpone interpreting it until the rest
10883 ;; of the parsing is done
10884 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
10885 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
10886 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
10887 iso-week (string-to-number (match-string 2 ans)))
10888 (setq ans (replace-match "" t t ans)))
10890 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
10891 (when (string-match
10892 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
10893 (setq year (if (match-end 2)
10894 (string-to-number (match-string 2 ans))
10895 (string-to-number (format-time-string "%Y")))
10896 month (string-to-number (match-string 3 ans))
10897 day (string-to-number (match-string 4 ans)))
10898 (if (< year 100) (setq year (+ 2000 year)))
10899 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
10900 t nil ans)))
10901 ;; Help matching am/pm times, because `parse-time-string' does not do that.
10902 ;; If there is a time with am/pm, and *no* time without it, we convert
10903 ;; so that matching will be successful.
10904 (loop for i from 1 to 2 do ; twice, for end time as well
10905 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
10906 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
10907 (setq hour (string-to-number (match-string 1 ans))
10908 minute (if (match-end 3)
10909 (string-to-number (match-string 3 ans))
10911 pm (equal ?p
10912 (string-to-char (downcase (match-string 4 ans)))))
10913 (if (and (= hour 12) (not pm))
10914 (setq hour 0)
10915 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
10916 (setq ans (replace-match (format "%02d:%02d" hour minute)
10917 t t ans))))
10919 ;; Check if a time range is given as a duration
10920 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
10921 (setq hour (string-to-number (match-string 1 ans))
10922 h2 (+ hour (string-to-number (match-string 3 ans)))
10923 minute (string-to-number (match-string 2 ans))
10924 m2 (+ minute (if (match-end 5) (string-to-number
10925 (match-string 5 ans))0)))
10926 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
10927 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
10928 t t ans)))
10930 ;; Check if there is a time range
10931 (when (boundp 'org-end-time-was-given)
10932 (setq org-time-was-given nil)
10933 (when (and (string-match org-plain-time-of-day-regexp ans)
10934 (match-end 8))
10935 (setq org-end-time-was-given (match-string 8 ans))
10936 (setq ans (concat (substring ans 0 (match-beginning 7))
10937 (substring ans (match-end 7))))))
10939 (setq tl (parse-time-string ans)
10940 day (or (nth 3 tl) (nth 3 defdecode))
10941 month (or (nth 4 tl)
10942 (if (and org-read-date-prefer-future
10943 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
10944 (1+ (nth 4 defdecode))
10945 (nth 4 defdecode)))
10946 year (or (nth 5 tl)
10947 (if (and org-read-date-prefer-future
10948 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
10949 (1+ (nth 5 defdecode))
10950 (nth 5 defdecode)))
10951 hour (or (nth 2 tl) (nth 2 defdecode))
10952 minute (or (nth 1 tl) (nth 1 defdecode))
10953 second (or (nth 0 tl) 0)
10954 wday (nth 6 tl))
10956 ;; Special date definitions below
10957 (cond
10958 (iso-week
10959 ;; There was an iso week
10960 (setq year (or iso-year year)
10961 day (or iso-weekday wday 1)
10962 wday nil ; to make sure that the trigger below does not match
10963 iso-date (calendar-gregorian-from-absolute
10964 (calendar-absolute-from-iso
10965 (list iso-week day year))))
10966 ; FIXME: Should we also push ISO weeks into the future?
10967 ; (when (and org-read-date-prefer-future
10968 ; (not iso-year)
10969 ; (< (calendar-absolute-from-gregorian iso-date)
10970 ; (time-to-days (current-time))))
10971 ; (setq year (1+ year)
10972 ; iso-date (calendar-gregorian-from-absolute
10973 ; (calendar-absolute-from-iso
10974 ; (list iso-week day year)))))
10975 (setq month (car iso-date)
10976 year (nth 2 iso-date)
10977 day (nth 1 iso-date)))
10978 (deltan
10979 (unless deltadef
10980 (let ((now (decode-time (current-time))))
10981 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
10982 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
10983 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
10984 ((equal deltaw "m") (setq month (+ month deltan)))
10985 ((equal deltaw "y") (setq year (+ year deltan)))))
10986 ((and wday (not (nth 3 tl)))
10987 ;; Weekday was given, but no day, so pick that day in the week
10988 ;; on or after the derived date.
10989 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
10990 (unless (equal wday wday1)
10991 (setq day (+ day (% (- wday wday1 -7) 7))))))
10992 (if (and (boundp 'org-time-was-given)
10993 (nth 2 tl))
10994 (setq org-time-was-given t))
10995 (if (< year 100) (setq year (+ 2000 year)))
10996 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
10997 (list second minute hour day month year)))
10999 (defvar parse-time-weekdays)
11001 (defun org-read-date-get-relative (s today default)
11002 "Check string S for special relative date string.
11003 TODAY and DEFAULT are internal times, for today and for a default.
11004 Return shift list (N what def-flag)
11005 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
11006 N is the number of WHATs to shift.
11007 DEF-FLAG is t when a double ++ or -- indicates shift relative to
11008 the DEFAULT date rather than TODAY."
11009 (when (and
11010 (string-match
11011 (concat
11012 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
11013 "\\([0-9]+\\)?"
11014 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
11015 "\\([ \t]\\|$\\)") s)
11016 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
11017 (let* ((dir (if (> (match-end 1) (match-beginning 1))
11018 (string-to-char (substring (match-string 1 s) -1))
11019 ?+))
11020 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
11021 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
11022 (what (if (match-end 3) (match-string 3 s) "d"))
11023 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
11024 (date (if rel default today))
11025 (wday (nth 6 (decode-time date)))
11026 delta)
11027 (if wday1
11028 (progn
11029 (setq delta (mod (+ 7 (- wday1 wday)) 7))
11030 (if (= dir ?-) (setq delta (- delta 7)))
11031 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
11032 (list delta "d" rel))
11033 (list (* n (if (= dir ?-) -1 1)) what rel)))))
11035 (defun org-eval-in-calendar (form &optional keepdate)
11036 "Eval FORM in the calendar window and return to current window.
11037 Also, store the cursor date in variable org-ans2."
11038 (let ((sw (selected-window)))
11039 (select-window (get-buffer-window "*Calendar*"))
11040 (eval form)
11041 (when (and (not keepdate) (calendar-cursor-to-date))
11042 (let* ((date (calendar-cursor-to-date))
11043 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11044 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
11045 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
11046 (select-window sw)))
11048 (defun org-calendar-select ()
11049 "Return to `org-read-date' with the date currently selected.
11050 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11051 (interactive)
11052 (when (calendar-cursor-to-date)
11053 (let* ((date (calendar-cursor-to-date))
11054 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11055 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11056 (if (active-minibuffer-window) (exit-minibuffer))))
11058 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
11059 "Insert a date stamp for the date given by the internal TIME.
11060 WITH-HM means, use the stamp format that includes the time of the day.
11061 INACTIVE means use square brackets instead of angular ones, so that the
11062 stamp will not contribute to the agenda.
11063 PRE and POST are optional strings to be inserted before and after the
11064 stamp.
11065 The command returns the inserted time stamp."
11066 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
11067 stamp)
11068 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
11069 (insert-before-markers (or pre ""))
11070 (insert-before-markers (setq stamp (format-time-string fmt time)))
11071 (when (listp extra)
11072 (setq extra (car extra))
11073 (if (and (stringp extra)
11074 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
11075 (setq extra (format "-%02d:%02d"
11076 (string-to-number (match-string 1 extra))
11077 (string-to-number (match-string 2 extra))))
11078 (setq extra nil)))
11079 (when extra
11080 (backward-char 1)
11081 (insert-before-markers extra)
11082 (forward-char 1))
11083 (insert-before-markers (or post ""))
11084 (setq org-last-inserted-timestamp stamp)))
11086 (defun org-toggle-time-stamp-overlays ()
11087 "Toggle the use of custom time stamp formats."
11088 (interactive)
11089 (setq org-display-custom-times (not org-display-custom-times))
11090 (unless org-display-custom-times
11091 (let ((p (point-min)) (bmp (buffer-modified-p)))
11092 (while (setq p (next-single-property-change p 'display))
11093 (if (and (get-text-property p 'display)
11094 (eq (get-text-property p 'face) 'org-date))
11095 (remove-text-properties
11096 p (setq p (next-single-property-change p 'display))
11097 '(display t))))
11098 (set-buffer-modified-p bmp)))
11099 (if (featurep 'xemacs)
11100 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
11101 (org-restart-font-lock)
11102 (setq org-table-may-need-update t)
11103 (if org-display-custom-times
11104 (message "Time stamps are overlayed with custom format")
11105 (message "Time stamp overlays removed")))
11107 (defun org-display-custom-time (beg end)
11108 "Overlay modified time stamp format over timestamp between BEG and END."
11109 (let* ((ts (buffer-substring beg end))
11110 t1 w1 with-hm tf time str w2 (off 0))
11111 (save-match-data
11112 (setq t1 (org-parse-time-string ts t))
11113 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
11114 (setq off (- (match-end 0) (match-beginning 0)))))
11115 (setq end (- end off))
11116 (setq w1 (- end beg)
11117 with-hm (and (nth 1 t1) (nth 2 t1))
11118 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
11119 time (org-fix-decoded-time t1)
11120 str (org-add-props
11121 (format-time-string
11122 (substring tf 1 -1) (apply 'encode-time time))
11123 nil 'mouse-face 'highlight)
11124 w2 (length str))
11125 (if (not (= w2 w1))
11126 (add-text-properties (1+ beg) (+ 2 beg)
11127 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
11128 (if (featurep 'xemacs)
11129 (progn
11130 (put-text-property beg end 'invisible t)
11131 (put-text-property beg end 'end-glyph (make-glyph str)))
11132 (put-text-property beg end 'display str))))
11134 (defun org-translate-time (string)
11135 "Translate all timestamps in STRING to custom format.
11136 But do this only if the variable `org-display-custom-times' is set."
11137 (when org-display-custom-times
11138 (save-match-data
11139 (let* ((start 0)
11140 (re org-ts-regexp-both)
11141 t1 with-hm inactive tf time str beg end)
11142 (while (setq start (string-match re string start))
11143 (setq beg (match-beginning 0)
11144 end (match-end 0)
11145 t1 (save-match-data
11146 (org-parse-time-string (substring string beg end) t))
11147 with-hm (and (nth 1 t1) (nth 2 t1))
11148 inactive (equal (substring string beg (1+ beg)) "[")
11149 tf (funcall (if with-hm 'cdr 'car)
11150 org-time-stamp-custom-formats)
11151 time (org-fix-decoded-time t1)
11152 str (format-time-string
11153 (concat
11154 (if inactive "[" "<") (substring tf 1 -1)
11155 (if inactive "]" ">"))
11156 (apply 'encode-time time))
11157 string (replace-match str t t string)
11158 start (+ start (length str)))))))
11159 string)
11161 (defun org-fix-decoded-time (time)
11162 "Set 0 instead of nil for the first 6 elements of time.
11163 Don't touch the rest."
11164 (let ((n 0))
11165 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
11167 (defun org-days-to-time (timestamp-string)
11168 "Difference between TIMESTAMP-STRING and now in days."
11169 (- (time-to-days (org-time-string-to-time timestamp-string))
11170 (time-to-days (current-time))))
11172 (defun org-deadline-close (timestamp-string &optional ndays)
11173 "Is the time in TIMESTAMP-STRING close to the current date?"
11174 (setq ndays (or ndays (org-get-wdays timestamp-string)))
11175 (and (< (org-days-to-time timestamp-string) ndays)
11176 (not (org-entry-is-done-p))))
11178 (defun org-get-wdays (ts)
11179 "Get the deadline lead time appropriate for timestring TS."
11180 (cond
11181 ((<= org-deadline-warning-days 0)
11182 ;; 0 or negative, enforce this value no matter what
11183 (- org-deadline-warning-days))
11184 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
11185 ;; lead time is specified.
11186 (floor (* (string-to-number (match-string 1 ts))
11187 (cdr (assoc (match-string 2 ts)
11188 '(("d" . 1) ("w" . 7)
11189 ("m" . 30.4) ("y" . 365.25)))))))
11190 ;; go for the default.
11191 (t org-deadline-warning-days)))
11193 (defun org-calendar-select-mouse (ev)
11194 "Return to `org-read-date' with the date currently selected.
11195 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11196 (interactive "e")
11197 (mouse-set-point ev)
11198 (when (calendar-cursor-to-date)
11199 (let* ((date (calendar-cursor-to-date))
11200 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11201 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11202 (if (active-minibuffer-window) (exit-minibuffer))))
11204 (defun org-check-deadlines (ndays)
11205 "Check if there are any deadlines due or past due.
11206 A deadline is considered due if it happens within `org-deadline-warning-days'
11207 days from today's date. If the deadline appears in an entry marked DONE,
11208 it is not shown. The prefix arg NDAYS can be used to test that many
11209 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
11210 (interactive "P")
11211 (let* ((org-warn-days
11212 (cond
11213 ((equal ndays '(4)) 100000)
11214 (ndays (prefix-numeric-value ndays))
11215 (t (abs org-deadline-warning-days))))
11216 (case-fold-search nil)
11217 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
11218 (callback
11219 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
11221 (message "%d deadlines past-due or due within %d days"
11222 (org-occur regexp nil callback)
11223 org-warn-days)))
11225 (defun org-check-before-date (date)
11226 "Check if there are deadlines or scheduled entries before DATE."
11227 (interactive (list (org-read-date)))
11228 (let ((case-fold-search nil)
11229 (regexp (concat "\\<\\(" org-deadline-string
11230 "\\|" org-scheduled-string
11231 "\\) *<\\([^>]+\\)>"))
11232 (callback
11233 (lambda () (time-less-p
11234 (org-time-string-to-time (match-string 2))
11235 (org-time-string-to-time date)))))
11236 (message "%d entries before %s"
11237 (org-occur regexp nil callback) date)))
11239 (defun org-evaluate-time-range (&optional to-buffer)
11240 "Evaluate a time range by computing the difference between start and end.
11241 Normally the result is just printed in the echo area, but with prefix arg
11242 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
11243 If the time range is actually in a table, the result is inserted into the
11244 next column.
11245 For time difference computation, a year is assumed to be exactly 365
11246 days in order to avoid rounding problems."
11247 (interactive "P")
11249 (org-clock-update-time-maybe)
11250 (save-excursion
11251 (unless (org-at-date-range-p t)
11252 (goto-char (point-at-bol))
11253 (re-search-forward org-tr-regexp-both (point-at-eol) t))
11254 (if (not (org-at-date-range-p t))
11255 (error "Not at a time-stamp range, and none found in current line")))
11256 (let* ((ts1 (match-string 1))
11257 (ts2 (match-string 2))
11258 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
11259 (match-end (match-end 0))
11260 (time1 (org-time-string-to-time ts1))
11261 (time2 (org-time-string-to-time ts2))
11262 (t1 (time-to-seconds time1))
11263 (t2 (time-to-seconds time2))
11264 (diff (abs (- t2 t1)))
11265 (negative (< (- t2 t1) 0))
11266 ;; (ys (floor (* 365 24 60 60)))
11267 (ds (* 24 60 60))
11268 (hs (* 60 60))
11269 (fy "%dy %dd %02d:%02d")
11270 (fy1 "%dy %dd")
11271 (fd "%dd %02d:%02d")
11272 (fd1 "%dd")
11273 (fh "%02d:%02d")
11274 y d h m align)
11275 (if havetime
11276 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11278 d (floor (/ diff ds)) diff (mod diff ds)
11279 h (floor (/ diff hs)) diff (mod diff hs)
11280 m (floor (/ diff 60)))
11281 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11283 d (floor (+ (/ diff ds) 0.5))
11284 h 0 m 0))
11285 (if (not to-buffer)
11286 (message "%s" (org-make-tdiff-string y d h m))
11287 (if (org-at-table-p)
11288 (progn
11289 (goto-char match-end)
11290 (setq align t)
11291 (and (looking-at " *|") (goto-char (match-end 0))))
11292 (goto-char match-end))
11293 (if (looking-at
11294 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
11295 (replace-match ""))
11296 (if negative (insert " -"))
11297 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
11298 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
11299 (insert " " (format fh h m))))
11300 (if align (org-table-align))
11301 (message "Time difference inserted")))))
11303 (defun org-make-tdiff-string (y d h m)
11304 (let ((fmt "")
11305 (l nil))
11306 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
11307 l (push y l)))
11308 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
11309 l (push d l)))
11310 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
11311 l (push h l)))
11312 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
11313 l (push m l)))
11314 (apply 'format fmt (nreverse l))))
11316 (defun org-time-string-to-time (s)
11317 (apply 'encode-time (org-parse-time-string s)))
11319 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
11320 "Convert a time stamp to an absolute day number.
11321 If there is a specifyer for a cyclic time stamp, get the closest date to
11322 DAYNR.
11323 PREFER and SHOW-ALL are passed through to `org-closest-date'."
11324 (cond
11325 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
11326 (if (org-diary-sexp-entry (match-string 1 s) "" date)
11327 daynr
11328 (+ daynr 1000)))
11329 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
11330 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
11331 (time-to-days (current-time))) (match-string 0 s)
11332 prefer show-all))
11333 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
11335 (defun org-days-to-iso-week (days)
11336 "Return the iso week number."
11337 (require 'cal-iso)
11338 (car (calendar-iso-from-absolute days)))
11340 (defun org-small-year-to-year (year)
11341 "Convert 2-digit years into 4-digit years.
11342 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
11343 The year 2000 cannot be abbreviated. Any year larger than 99
11344 is returned unchanged."
11345 (if (< year 38)
11346 (setq year (+ 2000 year))
11347 (if (< year 100)
11348 (setq year (+ 1900 year))))
11349 year)
11351 (defun org-time-from-absolute (d)
11352 "Return the time corresponding to date D.
11353 D may be an absolute day number, or a calendar-type list (month day year)."
11354 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
11355 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
11357 (defun org-calendar-holiday ()
11358 "List of holidays, for Diary display in Org-mode."
11359 (require 'holidays)
11360 (let ((hl (funcall
11361 (if (fboundp 'calendar-check-holidays)
11362 'calendar-check-holidays 'check-calendar-holidays) date)))
11363 (if hl (mapconcat 'identity hl "; "))))
11365 (defun org-diary-sexp-entry (sexp entry date)
11366 "Process a SEXP diary ENTRY for DATE."
11367 (require 'diary-lib)
11368 (let ((result (if calendar-debug-sexp
11369 (let ((stack-trace-on-error t))
11370 (eval (car (read-from-string sexp))))
11371 (condition-case nil
11372 (eval (car (read-from-string sexp)))
11373 (error
11374 (beep)
11375 (message "Bad sexp at line %d in %s: %s"
11376 (org-current-line)
11377 (buffer-file-name) sexp)
11378 (sleep-for 2))))))
11379 (cond ((stringp result) result)
11380 ((and (consp result)
11381 (stringp (cdr result))) (cdr result))
11382 (result entry)
11383 (t nil))))
11385 (defun org-diary-to-ical-string (frombuf)
11386 "Get iCalendar entries from diary entries in buffer FROMBUF.
11387 This uses the icalendar.el library."
11388 (let* ((tmpdir (if (featurep 'xemacs)
11389 (temp-directory)
11390 temporary-file-directory))
11391 (tmpfile (make-temp-name
11392 (expand-file-name "orgics" tmpdir)))
11393 buf rtn b e)
11394 (save-excursion
11395 (set-buffer frombuf)
11396 (icalendar-export-region (point-min) (point-max) tmpfile)
11397 (setq buf (find-buffer-visiting tmpfile))
11398 (set-buffer buf)
11399 (goto-char (point-min))
11400 (if (re-search-forward "^BEGIN:VEVENT" nil t)
11401 (setq b (match-beginning 0)))
11402 (goto-char (point-max))
11403 (if (re-search-backward "^END:VEVENT" nil t)
11404 (setq e (match-end 0)))
11405 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
11406 (kill-buffer buf)
11407 (delete-file tmpfile)
11408 rtn))
11410 (defun org-closest-date (start current change prefer show-all)
11411 "Find the date closest to CURRENT that is consistent with START and CHANGE.
11412 When PREFER is `past' return a date that is either CURRENT or past.
11413 When PREFER is `future', return a date that is either CURRENT or future.
11414 When SHOW-ALL is nil, only return the current occurence of a time stamp."
11415 ;; Make the proper lists from the dates
11416 (catch 'exit
11417 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
11418 dn dw sday cday n1 n2
11419 d m y y1 y2 date1 date2 nmonths nm ny m2)
11421 (setq start (org-date-to-gregorian start)
11422 current (org-date-to-gregorian
11423 (if show-all
11424 current
11425 (time-to-days (current-time))))
11426 sday (calendar-absolute-from-gregorian start)
11427 cday (calendar-absolute-from-gregorian current))
11429 (if (<= cday sday) (throw 'exit sday))
11431 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
11432 (setq dn (string-to-number (match-string 1 change))
11433 dw (cdr (assoc (match-string 2 change) a1)))
11434 (error "Invalid change specifyer: %s" change))
11435 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
11436 (cond
11437 ((eq dw 'day)
11438 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
11439 n2 (+ n1 dn)))
11440 ((eq dw 'year)
11441 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
11442 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
11443 (setq date1 (list m d y1)
11444 n1 (calendar-absolute-from-gregorian date1)
11445 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
11446 n2 (calendar-absolute-from-gregorian date2)))
11447 ((eq dw 'month)
11448 ;; approx number of month between the two dates
11449 (setq nmonths (floor (/ (- cday sday) 30.436875)))
11450 ;; How often does dn fit in there?
11451 (setq d (nth 1 start) m (car start) y (nth 2 start)
11452 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
11453 m (+ m nm)
11454 ny (floor (/ m 12))
11455 y (+ y ny)
11456 m (- m (* ny 12)))
11457 (while (> m 12) (setq m (- m 12) y (1+ y)))
11458 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
11459 (setq m2 (+ m dn) y2 y)
11460 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11461 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
11462 (while (<= n2 cday)
11463 (setq n1 n2 m m2 y y2)
11464 (setq m2 (+ m dn) y2 y)
11465 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11466 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
11467 (if show-all
11468 (cond
11469 ((eq prefer 'past) n1)
11470 ((eq prefer 'future) (if (= cday n1) n1 n2))
11471 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
11472 (cond
11473 ((eq prefer 'past) n1)
11474 ((eq prefer 'future) (if (= cday n1) n1 n2))
11475 (t (if (= cday n1) n1 n2)))))))
11477 (defun org-date-to-gregorian (date)
11478 "Turn any specification of DATE into a gregorian date for the calendar."
11479 (cond ((integerp date) (calendar-gregorian-from-absolute date))
11480 ((and (listp date) (= (length date) 3)) date)
11481 ((stringp date)
11482 (setq date (org-parse-time-string date))
11483 (list (nth 4 date) (nth 3 date) (nth 5 date)))
11484 ((listp date)
11485 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
11487 (defun org-parse-time-string (s &optional nodefault)
11488 "Parse the standard Org-mode time string.
11489 This should be a lot faster than the normal `parse-time-string'.
11490 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
11491 hour and minute fields will be nil if not given."
11492 (if (string-match org-ts-regexp0 s)
11493 (list 0
11494 (if (or (match-beginning 8) (not nodefault))
11495 (string-to-number (or (match-string 8 s) "0")))
11496 (if (or (match-beginning 7) (not nodefault))
11497 (string-to-number (or (match-string 7 s) "0")))
11498 (string-to-number (match-string 4 s))
11499 (string-to-number (match-string 3 s))
11500 (string-to-number (match-string 2 s))
11501 nil nil nil)
11502 (make-list 9 0)))
11504 (defun org-timestamp-up (&optional arg)
11505 "Increase the date item at the cursor by one.
11506 If the cursor is on the year, change the year. If it is on the month or
11507 the day, change that.
11508 With prefix ARG, change by that many units."
11509 (interactive "p")
11510 (org-timestamp-change (prefix-numeric-value arg)))
11512 (defun org-timestamp-down (&optional arg)
11513 "Decrease the date item at the cursor by one.
11514 If the cursor is on the year, change the year. If it is on the month or
11515 the day, change that.
11516 With prefix ARG, change by that many units."
11517 (interactive "p")
11518 (org-timestamp-change (- (prefix-numeric-value arg))))
11520 (defun org-timestamp-up-day (&optional arg)
11521 "Increase the date in the time stamp by one day.
11522 With prefix ARG, change that many days."
11523 (interactive "p")
11524 (if (and (not (org-at-timestamp-p t))
11525 (org-on-heading-p))
11526 (org-todo 'up)
11527 (org-timestamp-change (prefix-numeric-value arg) 'day)))
11529 (defun org-timestamp-down-day (&optional arg)
11530 "Decrease the date in the time stamp by one day.
11531 With prefix ARG, change that many days."
11532 (interactive "p")
11533 (if (and (not (org-at-timestamp-p t))
11534 (org-on-heading-p))
11535 (org-todo 'down)
11536 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
11538 (defun org-at-timestamp-p (&optional inactive-ok)
11539 "Determine if the cursor is in or at a timestamp."
11540 (interactive)
11541 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
11542 (pos (point))
11543 (ans (or (looking-at tsr)
11544 (save-excursion
11545 (skip-chars-backward "^[<\n\r\t")
11546 (if (> (point) (point-min)) (backward-char 1))
11547 (and (looking-at tsr)
11548 (> (- (match-end 0) pos) -1))))))
11549 (and ans
11550 (boundp 'org-ts-what)
11551 (setq org-ts-what
11552 (cond
11553 ((= pos (match-beginning 0)) 'bracket)
11554 ((= pos (1- (match-end 0))) 'bracket)
11555 ((org-pos-in-match-range pos 2) 'year)
11556 ((org-pos-in-match-range pos 3) 'month)
11557 ((org-pos-in-match-range pos 7) 'hour)
11558 ((org-pos-in-match-range pos 8) 'minute)
11559 ((or (org-pos-in-match-range pos 4)
11560 (org-pos-in-match-range pos 5)) 'day)
11561 ((and (> pos (or (match-end 8) (match-end 5)))
11562 (< pos (match-end 0)))
11563 (- pos (or (match-end 8) (match-end 5))))
11564 (t 'day))))
11565 ans))
11567 (defun org-toggle-timestamp-type ()
11568 "Toggle the type (<active> or [inactive]) of a time stamp."
11569 (interactive)
11570 (when (org-at-timestamp-p t)
11571 (let ((beg (match-beginning 0)) (end (match-end 0))
11572 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
11573 (save-excursion
11574 (goto-char beg)
11575 (while (re-search-forward "[][<>]" end t)
11576 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
11577 t t)))
11578 (message "Timestamp is now %sactive"
11579 (if (equal (char-after beg) ?<) "" "in")))))
11581 (defun org-timestamp-change (n &optional what)
11582 "Change the date in the time stamp at point.
11583 The date will be changed by N times WHAT. WHAT can be `day', `month',
11584 `year', `minute', `second'. If WHAT is not given, the cursor position
11585 in the timestamp determines what will be changed."
11586 (let ((pos (point))
11587 with-hm inactive
11588 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
11589 org-ts-what
11590 extra rem
11591 ts time time0)
11592 (if (not (org-at-timestamp-p t))
11593 (error "Not at a timestamp"))
11594 (if (and (not what) (eq org-ts-what 'bracket))
11595 (org-toggle-timestamp-type)
11596 (if (and (not what) (not (eq org-ts-what 'day))
11597 org-display-custom-times
11598 (get-text-property (point) 'display)
11599 (not (get-text-property (1- (point)) 'display)))
11600 (setq org-ts-what 'day))
11601 (setq org-ts-what (or what org-ts-what)
11602 inactive (= (char-after (match-beginning 0)) ?\[)
11603 ts (match-string 0))
11604 (replace-match "")
11605 (if (string-match
11606 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
11608 (setq extra (match-string 1 ts)))
11609 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
11610 (setq with-hm t))
11611 (setq time0 (org-parse-time-string ts))
11612 (when (and (eq org-ts-what 'minute)
11613 (eq current-prefix-arg nil))
11614 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
11615 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
11616 (setcar (cdr time0) (+ (nth 1 time0)
11617 (if (> n 0) (- rem) (- dm rem))))))
11618 (setq time
11619 (encode-time (or (car time0) 0)
11620 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
11621 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
11622 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
11623 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
11624 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
11625 (nthcdr 6 time0)))
11626 (when (integerp org-ts-what)
11627 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
11628 (if (eq what 'calendar)
11629 (let ((cal-date (org-get-date-from-calendar)))
11630 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
11631 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
11632 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
11633 (setcar time0 (or (car time0) 0))
11634 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
11635 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
11636 (setq time (apply 'encode-time time0))))
11637 (setq org-last-changed-timestamp
11638 (org-insert-time-stamp time with-hm inactive nil nil extra))
11639 (org-clock-update-time-maybe)
11640 (goto-char pos)
11641 ;; Try to recenter the calendar window, if any
11642 (if (and org-calendar-follow-timestamp-change
11643 (get-buffer-window "*Calendar*" t)
11644 (memq org-ts-what '(day month year)))
11645 (org-recenter-calendar (time-to-days time))))))
11647 (defun org-modify-ts-extra (s pos n dm)
11648 "Change the different parts of the lead-time and repeat fields in timestamp."
11649 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
11650 ng h m new rem)
11651 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
11652 (cond
11653 ((or (org-pos-in-match-range pos 2)
11654 (org-pos-in-match-range pos 3))
11655 (setq m (string-to-number (match-string 3 s))
11656 h (string-to-number (match-string 2 s)))
11657 (if (org-pos-in-match-range pos 2)
11658 (setq h (+ h n))
11659 (setq n (* dm (org-no-warnings (signum n))))
11660 (when (not (= 0 (setq rem (% m dm))))
11661 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
11662 (setq m (+ m n)))
11663 (if (< m 0) (setq m (+ m 60) h (1- h)))
11664 (if (> m 59) (setq m (- m 60) h (1+ h)))
11665 (setq h (min 24 (max 0 h)))
11666 (setq ng 1 new (format "-%02d:%02d" h m)))
11667 ((org-pos-in-match-range pos 6)
11668 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
11669 ((org-pos-in-match-range pos 5)
11670 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
11672 ((org-pos-in-match-range pos 9)
11673 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
11674 ((org-pos-in-match-range pos 8)
11675 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
11677 (when ng
11678 (setq s (concat
11679 (substring s 0 (match-beginning ng))
11681 (substring s (match-end ng))))))
11684 (defun org-recenter-calendar (date)
11685 "If the calendar is visible, recenter it to DATE."
11686 (let* ((win (selected-window))
11687 (cwin (get-buffer-window "*Calendar*" t))
11688 (calendar-move-hook nil))
11689 (when cwin
11690 (select-window cwin)
11691 (calendar-goto-date (if (listp date) date
11692 (calendar-gregorian-from-absolute date)))
11693 (select-window win))))
11695 (defun org-goto-calendar (&optional arg)
11696 "Go to the Emacs calendar at the current date.
11697 If there is a time stamp in the current line, go to that date.
11698 A prefix ARG can be used to force the current date."
11699 (interactive "P")
11700 (let ((tsr org-ts-regexp) diff
11701 (calendar-move-hook nil)
11702 (calendar-view-holidays-initially-flag nil)
11703 (view-calendar-holidays-initially nil)
11704 (calendar-view-diary-initially-flag nil)
11705 (view-diary-entries-initially nil))
11706 (if (or (org-at-timestamp-p)
11707 (save-excursion
11708 (beginning-of-line 1)
11709 (looking-at (concat ".*" tsr))))
11710 (let ((d1 (time-to-days (current-time)))
11711 (d2 (time-to-days
11712 (org-time-string-to-time (match-string 1)))))
11713 (setq diff (- d2 d1))))
11714 (calendar)
11715 (calendar-goto-today)
11716 (if (and diff (not arg)) (calendar-forward-day diff))))
11718 (defun org-get-date-from-calendar ()
11719 "Return a list (month day year) of date at point in calendar."
11720 (with-current-buffer "*Calendar*"
11721 (save-match-data
11722 (calendar-cursor-to-date))))
11724 (defun org-date-from-calendar ()
11725 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
11726 If there is already a time stamp at the cursor position, update it."
11727 (interactive)
11728 (if (org-at-timestamp-p t)
11729 (org-timestamp-change 0 'calendar)
11730 (let ((cal-date (org-get-date-from-calendar)))
11731 (org-insert-time-stamp
11732 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
11734 (defun org-minutes-to-hh:mm-string (m)
11735 "Compute H:MM from a number of minutes."
11736 (let ((h (/ m 60)))
11737 (setq m (- m (* 60 h)))
11738 (format org-time-clocksum-format h m)))
11740 (defun org-hh:mm-string-to-minutes (s)
11741 "Convert a string H:MM to a number of minutes."
11742 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
11743 (+ (* (string-to-number (match-string 1 s)) 60)
11744 (string-to-number (match-string 2 s)))
11747 ;;;; Agenda files
11749 ;;;###autoload
11750 (defun org-iswitchb (&optional arg)
11751 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
11752 With a prefix argument, restrict available to files.
11753 With two prefix arguments, restrict available buffers to agenda files.
11755 Due to some yet unresolved reason, the global function
11756 `iswitchb-mode' needs to be active for this function to work."
11757 (interactive "P")
11758 (require 'iswitchb)
11759 (let ((enabled iswitchb-mode) blist)
11760 (or enabled (iswitchb-mode 1))
11761 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
11762 ((equal arg '(16)) (org-buffer-list 'agenda))
11763 (t (org-buffer-list))))
11764 (unwind-protect
11765 (let ((iswitchb-make-buflist-hook
11766 (lambda ()
11767 (setq iswitchb-temp-buflist
11768 (mapcar 'buffer-name blist)))))
11769 (switch-to-buffer
11770 (iswitchb-read-buffer
11771 "Switch-to: " nil t))
11772 (or enabled (iswitchb-mode -1))))))
11774 (defun org-buffer-list (&optional predicate exclude-tmp)
11775 "Return a list of Org buffers.
11776 PREDICATE can be `export', `files' or `agenda'.
11778 export restrict the list to Export buffers.
11779 files restrict the list to buffers visiting Org files.
11780 agenda restrict the list to buffers visiting agenda files.
11782 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
11783 (let* ((bfn nil)
11784 (agenda-files (and (eq predicate 'agenda)
11785 (mapcar 'file-truename (org-agenda-files t))))
11786 (filter
11787 (cond
11788 ((eq predicate 'files)
11789 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
11790 ((eq predicate 'export)
11791 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
11792 ((eq predicate 'agenda)
11793 (lambda (b)
11794 (with-current-buffer b
11795 (and (eq major-mode 'org-mode)
11796 (setq bfn (buffer-file-name b))
11797 (member (file-truename bfn) agenda-files)))))
11798 (t (lambda (b) (with-current-buffer b
11799 (or (eq major-mode 'org-mode)
11800 (string-match "\*Org .*Export"
11801 (buffer-name b)))))))))
11802 (delq nil
11803 (mapcar
11804 (lambda(b)
11805 (if (and (funcall filter b)
11806 (or (not exclude-tmp)
11807 (not (string-match "tmp" (buffer-name b)))))
11809 nil))
11810 (buffer-list)))))
11812 (defun org-agenda-files (&optional unrestricted archives)
11813 "Get the list of agenda files.
11814 Optional UNRESTRICTED means return the full list even if a restriction
11815 is currently in place.
11816 When ARCHIVES is t, include all archive files hat are really being
11817 used by the agenda files. If ARCHIVE is `ifmode', do this only if
11818 `org-agenda-archives-mode' is t."
11819 (let ((files
11820 (cond
11821 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
11822 ((stringp org-agenda-files) (org-read-agenda-file-list))
11823 ((listp org-agenda-files) org-agenda-files)
11824 (t (error "Invalid value of `org-agenda-files'")))))
11825 (setq files (apply 'append
11826 (mapcar (lambda (f)
11827 (if (file-directory-p f)
11828 (directory-files
11829 f t org-agenda-file-regexp)
11830 (list f)))
11831 files)))
11832 (when org-agenda-skip-unavailable-files
11833 (setq files (delq nil
11834 (mapcar (function
11835 (lambda (file)
11836 (and (file-readable-p file) file)))
11837 files))))
11838 (when (or (eq archives t)
11839 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
11840 (setq files (org-add-archive-files files)))
11841 files))
11843 (defun org-edit-agenda-file-list ()
11844 "Edit the list of agenda files.
11845 Depending on setup, this either uses customize to edit the variable
11846 `org-agenda-files', or it visits the file that is holding the list. In the
11847 latter case, the buffer is set up in a way that saving it automatically kills
11848 the buffer and restores the previous window configuration."
11849 (interactive)
11850 (if (stringp org-agenda-files)
11851 (let ((cw (current-window-configuration)))
11852 (find-file org-agenda-files)
11853 (org-set-local 'org-window-configuration cw)
11854 (org-add-hook 'after-save-hook
11855 (lambda ()
11856 (set-window-configuration
11857 (prog1 org-window-configuration
11858 (kill-buffer (current-buffer))))
11859 (org-install-agenda-files-menu)
11860 (message "New agenda file list installed"))
11861 nil 'local)
11862 (message "%s" (substitute-command-keys
11863 "Edit list and finish with \\[save-buffer]")))
11864 (customize-variable 'org-agenda-files)))
11866 (defun org-store-new-agenda-file-list (list)
11867 "Set new value for the agenda file list and save it correcly."
11868 (if (stringp org-agenda-files)
11869 (let ((f org-agenda-files) b)
11870 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
11871 (with-temp-file f
11872 (insert (mapconcat 'identity list "\n") "\n")))
11873 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
11874 (setq org-agenda-files list)
11875 (customize-save-variable 'org-agenda-files org-agenda-files))))
11877 (defun org-read-agenda-file-list ()
11878 "Read the list of agenda files from a file."
11879 (when (file-directory-p org-agenda-files)
11880 (error "`org-agenda-files' cannot be a single directory"))
11881 (when (stringp org-agenda-files)
11882 (with-temp-buffer
11883 (insert-file-contents org-agenda-files)
11884 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
11887 ;;;###autoload
11888 (defun org-cycle-agenda-files ()
11889 "Cycle through the files in `org-agenda-files'.
11890 If the current buffer visits an agenda file, find the next one in the list.
11891 If the current buffer does not, find the first agenda file."
11892 (interactive)
11893 (let* ((fs (org-agenda-files t))
11894 (files (append fs (list (car fs))))
11895 (tcf (if buffer-file-name (file-truename buffer-file-name)))
11896 file)
11897 (unless files (error "No agenda files"))
11898 (catch 'exit
11899 (while (setq file (pop files))
11900 (if (equal (file-truename file) tcf)
11901 (when (car files)
11902 (find-file (car files))
11903 (throw 'exit t))))
11904 (find-file (car fs)))
11905 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
11907 (defun org-agenda-file-to-front (&optional to-end)
11908 "Move/add the current file to the top of the agenda file list.
11909 If the file is not present in the list, it is added to the front. If it is
11910 present, it is moved there. With optional argument TO-END, add/move to the
11911 end of the list."
11912 (interactive "P")
11913 (let ((org-agenda-skip-unavailable-files nil)
11914 (file-alist (mapcar (lambda (x)
11915 (cons (file-truename x) x))
11916 (org-agenda-files t)))
11917 (ctf (file-truename buffer-file-name))
11918 x had)
11919 (setq x (assoc ctf file-alist) had x)
11921 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
11922 (if to-end
11923 (setq file-alist (append (delq x file-alist) (list x)))
11924 (setq file-alist (cons x (delq x file-alist))))
11925 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
11926 (org-install-agenda-files-menu)
11927 (message "File %s to %s of agenda file list"
11928 (if had "moved" "added") (if to-end "end" "front"))))
11930 (defun org-remove-file (&optional file)
11931 "Remove current file from the list of files in variable `org-agenda-files'.
11932 These are the files which are being checked for agenda entries.
11933 Optional argument FILE means, use this file instead of the current."
11934 (interactive)
11935 (let* ((org-agenda-skip-unavailable-files nil)
11936 (file (or file buffer-file-name))
11937 (true-file (file-truename file))
11938 (afile (abbreviate-file-name file))
11939 (files (delq nil (mapcar
11940 (lambda (x)
11941 (if (equal true-file
11942 (file-truename x))
11943 nil x))
11944 (org-agenda-files t)))))
11945 (if (not (= (length files) (length (org-agenda-files t))))
11946 (progn
11947 (org-store-new-agenda-file-list files)
11948 (org-install-agenda-files-menu)
11949 (message "Removed file: %s" afile))
11950 (message "File was not in list: %s (not removed)" afile))))
11952 (defun org-file-menu-entry (file)
11953 (vector file (list 'find-file file) t))
11955 (defun org-check-agenda-file (file)
11956 "Make sure FILE exists. If not, ask user what to do."
11957 (when (not (file-exists-p file))
11958 (message "non-existent file %s. [R]emove from list or [A]bort?"
11959 (abbreviate-file-name file))
11960 (let ((r (downcase (read-char-exclusive))))
11961 (cond
11962 ((equal r ?r)
11963 (org-remove-file file)
11964 (throw 'nextfile t))
11965 (t (error "Abort"))))))
11967 (defun org-get-agenda-file-buffer (file)
11968 "Get a buffer visiting FILE. If the buffer needs to be created, add
11969 it to the list of buffers which might be released later."
11970 (let ((buf (org-find-base-buffer-visiting file)))
11971 (if buf
11972 buf ; just return it
11973 ;; Make a new buffer and remember it
11974 (setq buf (find-file-noselect file))
11975 (if buf (push buf org-agenda-new-buffers))
11976 buf)))
11978 (defun org-release-buffers (blist)
11979 "Release all buffers in list, asking the user for confirmation when needed.
11980 When a buffer is unmodified, it is just killed. When modified, it is saved
11981 \(if the user agrees) and then killed."
11982 (let (buf file)
11983 (while (setq buf (pop blist))
11984 (setq file (buffer-file-name buf))
11985 (when (and (buffer-modified-p buf)
11986 file
11987 (y-or-n-p (format "Save file %s? " file)))
11988 (with-current-buffer buf (save-buffer)))
11989 (kill-buffer buf))))
11991 (defun org-prepare-agenda-buffers (files)
11992 "Create buffers for all agenda files, protect archived trees and comments."
11993 (interactive)
11994 (let ((pa '(:org-archived t))
11995 (pc '(:org-comment t))
11996 (pall '(:org-archived t :org-comment t))
11997 (inhibit-read-only t)
11998 (rea (concat ":" org-archive-tag ":"))
11999 bmp file re)
12000 (save-excursion
12001 (save-restriction
12002 (while (setq file (pop files))
12003 (if (bufferp file)
12004 (set-buffer file)
12005 (org-check-agenda-file file)
12006 (set-buffer (org-get-agenda-file-buffer file)))
12007 (widen)
12008 (setq bmp (buffer-modified-p))
12009 (org-refresh-category-properties)
12010 (setq org-todo-keywords-for-agenda
12011 (append org-todo-keywords-for-agenda org-todo-keywords-1))
12012 (setq org-done-keywords-for-agenda
12013 (append org-done-keywords-for-agenda org-done-keywords))
12014 (setq org-todo-keyword-alist-for-agenda
12015 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
12016 (setq org-tag-alist-for-agenda
12017 (append org-tag-alist-for-agenda org-tag-alist))
12019 (save-excursion
12020 (remove-text-properties (point-min) (point-max) pall)
12021 (when org-agenda-skip-archived-trees
12022 (goto-char (point-min))
12023 (while (re-search-forward rea nil t)
12024 (if (org-on-heading-p t)
12025 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
12026 (goto-char (point-min))
12027 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
12028 (while (re-search-forward re nil t)
12029 (add-text-properties
12030 (match-beginning 0) (org-end-of-subtree t) pc)))
12031 (set-buffer-modified-p bmp))))
12032 (setq org-todo-keyword-alist-for-agenda
12033 (org-uniquify org-todo-keyword-alist-for-agenda)
12034 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
12036 ;;;; Embedded LaTeX
12038 (defvar org-cdlatex-mode-map (make-sparse-keymap)
12039 "Keymap for the minor `org-cdlatex-mode'.")
12041 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
12042 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
12043 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
12044 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
12045 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
12047 (defvar org-cdlatex-texmathp-advice-is-done nil
12048 "Flag remembering if we have applied the advice to texmathp already.")
12050 (define-minor-mode org-cdlatex-mode
12051 "Toggle the minor `org-cdlatex-mode'.
12052 This mode supports entering LaTeX environment and math in LaTeX fragments
12053 in Org-mode.
12054 \\{org-cdlatex-mode-map}"
12055 nil " OCDL" nil
12056 (when org-cdlatex-mode (require 'cdlatex))
12057 (unless org-cdlatex-texmathp-advice-is-done
12058 (setq org-cdlatex-texmathp-advice-is-done t)
12059 (defadvice texmathp (around org-math-always-on activate)
12060 "Always return t in org-mode buffers.
12061 This is because we want to insert math symbols without dollars even outside
12062 the LaTeX math segments. If Orgmode thinks that point is actually inside
12063 en embedded LaTeX fragement, let texmathp do its job.
12064 \\[org-cdlatex-mode-map]"
12065 (interactive)
12066 (let (p)
12067 (cond
12068 ((not (org-mode-p)) ad-do-it)
12069 ((eq this-command 'cdlatex-math-symbol)
12070 (setq ad-return-value t
12071 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
12073 (let ((p (org-inside-LaTeX-fragment-p)))
12074 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
12075 (setq ad-return-value t
12076 texmathp-why '("Org-mode embedded math" . 0))
12077 (if p ad-do-it)))))))))
12079 (defun turn-on-org-cdlatex ()
12080 "Unconditionally turn on `org-cdlatex-mode'."
12081 (org-cdlatex-mode 1))
12083 (defun org-inside-LaTeX-fragment-p ()
12084 "Test if point is inside a LaTeX fragment.
12085 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
12086 sequence appearing also before point.
12087 Even though the matchers for math are configurable, this function assumes
12088 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
12089 delimiters are skipped when they have been removed by customization.
12090 The return value is nil, or a cons cell with the delimiter and
12091 and the position of this delimiter.
12093 This function does a reasonably good job, but can locally be fooled by
12094 for example currency specifications. For example it will assume being in
12095 inline math after \"$22.34\". The LaTeX fragment formatter will only format
12096 fragments that are properly closed, but during editing, we have to live
12097 with the uncertainty caused by missing closing delimiters. This function
12098 looks only before point, not after."
12099 (catch 'exit
12100 (let ((pos (point))
12101 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
12102 (lim (progn
12103 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
12104 (point)))
12105 dd-on str (start 0) m re)
12106 (goto-char pos)
12107 (when dodollar
12108 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
12109 re (nth 1 (assoc "$" org-latex-regexps)))
12110 (while (string-match re str start)
12111 (cond
12112 ((= (match-end 0) (length str))
12113 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
12114 ((= (match-end 0) (- (length str) 5))
12115 (throw 'exit nil))
12116 (t (setq start (match-end 0))))))
12117 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
12118 (goto-char pos)
12119 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
12120 (and (match-beginning 2) (throw 'exit nil))
12121 ;; count $$
12122 (while (re-search-backward "\\$\\$" lim t)
12123 (setq dd-on (not dd-on)))
12124 (goto-char pos)
12125 (if dd-on (cons "$$" m))))))
12128 (defun org-try-cdlatex-tab ()
12129 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
12130 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
12131 - inside a LaTeX fragment, or
12132 - after the first word in a line, where an abbreviation expansion could
12133 insert a LaTeX environment."
12134 (when org-cdlatex-mode
12135 (cond
12136 ((save-excursion
12137 (skip-chars-backward "a-zA-Z0-9*")
12138 (skip-chars-backward " \t")
12139 (bolp))
12140 (cdlatex-tab) t)
12141 ((org-inside-LaTeX-fragment-p)
12142 (cdlatex-tab) t)
12143 (t nil))))
12145 (defun org-cdlatex-underscore-caret (&optional arg)
12146 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
12147 Revert to the normal definition outside of these fragments."
12148 (interactive "P")
12149 (if (org-inside-LaTeX-fragment-p)
12150 (call-interactively 'cdlatex-sub-superscript)
12151 (let (org-cdlatex-mode)
12152 (call-interactively (key-binding (vector last-input-event))))))
12154 (defun org-cdlatex-math-modify (&optional arg)
12155 "Execute `cdlatex-math-modify' in LaTeX fragments.
12156 Revert to the normal definition outside of these fragments."
12157 (interactive "P")
12158 (if (org-inside-LaTeX-fragment-p)
12159 (call-interactively 'cdlatex-math-modify)
12160 (let (org-cdlatex-mode)
12161 (call-interactively (key-binding (vector last-input-event))))))
12163 (defvar org-latex-fragment-image-overlays nil
12164 "List of overlays carrying the images of latex fragments.")
12165 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
12167 (defun org-remove-latex-fragment-image-overlays ()
12168 "Remove all overlays with LaTeX fragment images in current buffer."
12169 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
12170 (setq org-latex-fragment-image-overlays nil))
12172 (defun org-preview-latex-fragment (&optional subtree)
12173 "Preview the LaTeX fragment at point, or all locally or globally.
12174 If the cursor is in a LaTeX fragment, create the image and overlay
12175 it over the source code. If there is no fragment at point, display
12176 all fragments in the current text, from one headline to the next. With
12177 prefix SUBTREE, display all fragments in the current subtree. With a
12178 double prefix `C-u C-u', or when the cursor is before the first headline,
12179 display all fragments in the buffer.
12180 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
12181 (interactive "P")
12182 (org-remove-latex-fragment-image-overlays)
12183 (save-excursion
12184 (save-restriction
12185 (let (beg end at msg)
12186 (cond
12187 ((or (equal subtree '(16))
12188 (not (save-excursion
12189 (re-search-backward (concat "^" outline-regexp) nil t))))
12190 (setq beg (point-min) end (point-max)
12191 msg "Creating images for buffer...%s"))
12192 ((equal subtree '(4))
12193 (org-back-to-heading)
12194 (setq beg (point) end (org-end-of-subtree t)
12195 msg "Creating images for subtree...%s"))
12197 (if (setq at (org-inside-LaTeX-fragment-p))
12198 (goto-char (max (point-min) (- (cdr at) 2)))
12199 (org-back-to-heading))
12200 (setq beg (point) end (progn (outline-next-heading) (point))
12201 msg (if at "Creating image...%s"
12202 "Creating images for entry...%s"))))
12203 (message msg "")
12204 (narrow-to-region beg end)
12205 (goto-char beg)
12206 (org-format-latex
12207 (concat "ltxpng/" (file-name-sans-extension
12208 (file-name-nondirectory
12209 buffer-file-name)))
12210 default-directory 'overlays msg at 'forbuffer)
12211 (message msg "done. Use `C-c C-c' to remove images.")))))
12213 (defvar org-latex-regexps
12214 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
12215 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
12216 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
12217 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
12218 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
12219 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
12220 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
12221 "Regular expressions for matching embedded LaTeX.")
12223 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
12224 "Replace LaTeX fragments with links to an image, and produce images."
12225 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
12226 (let* ((prefixnodir (file-name-nondirectory prefix))
12227 (absprefix (expand-file-name prefix dir))
12228 (todir (file-name-directory absprefix))
12229 (opt org-format-latex-options)
12230 (matchers (plist-get opt :matchers))
12231 (re-list org-latex-regexps)
12232 (cnt 0) txt link beg end re e checkdir
12233 m n block linkfile movefile ov)
12234 ;; Check if there are old images files with this prefix, and remove them
12235 (when (file-directory-p todir)
12236 (mapc 'delete-file
12237 (directory-files
12238 todir 'full
12239 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
12240 ;; Check the different regular expressions
12241 (while (setq e (pop re-list))
12242 (setq m (car e) re (nth 1 e) n (nth 2 e)
12243 block (if (nth 3 e) "\n\n" ""))
12244 (when (member m matchers)
12245 (goto-char (point-min))
12246 (while (re-search-forward re nil t)
12247 (when (or (not at) (equal (cdr at) (match-beginning n)))
12248 (setq txt (match-string n)
12249 beg (match-beginning n) end (match-end n)
12250 cnt (1+ cnt)
12251 linkfile (format "%s_%04d.png" prefix cnt)
12252 movefile (format "%s_%04d.png" absprefix cnt)
12253 link (concat block "[[file:" linkfile "]]" block))
12254 (if msg (message msg cnt))
12255 (goto-char beg)
12256 (unless checkdir ; make sure the directory exists
12257 (setq checkdir t)
12258 (or (file-directory-p todir) (make-directory todir)))
12259 (org-create-formula-image
12260 txt movefile opt forbuffer)
12261 (if overlays
12262 (progn
12263 (setq ov (org-make-overlay beg end))
12264 (if (featurep 'xemacs)
12265 (progn
12266 (org-overlay-put ov 'invisible t)
12267 (org-overlay-put
12268 ov 'end-glyph
12269 (make-glyph (vector 'png :file movefile))))
12270 (org-overlay-put
12271 ov 'display
12272 (list 'image :type 'png :file movefile :ascent 'center)))
12273 (push ov org-latex-fragment-image-overlays)
12274 (goto-char end))
12275 (delete-region beg end)
12276 (insert link))))))))
12278 ;; This function borrows from Ganesh Swami's latex2png.el
12279 (defun org-create-formula-image (string tofile options buffer)
12280 (let* ((tmpdir (if (featurep 'xemacs)
12281 (temp-directory)
12282 temporary-file-directory))
12283 (texfilebase (make-temp-name
12284 (expand-file-name "orgtex" tmpdir)))
12285 (texfile (concat texfilebase ".tex"))
12286 (dvifile (concat texfilebase ".dvi"))
12287 (pngfile (concat texfilebase ".png"))
12288 (fnh (if (featurep 'xemacs)
12289 (font-height (get-face-font 'default))
12290 (face-attribute 'default :height nil)))
12291 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
12292 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
12293 (fg (or (plist-get options (if buffer :foreground :html-foreground))
12294 "Black"))
12295 (bg (or (plist-get options (if buffer :background :html-background))
12296 "Transparent")))
12297 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
12298 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
12299 (with-temp-file texfile
12300 (insert org-format-latex-header
12301 "\n\\begin{document}\n" string "\n\\end{document}\n"))
12302 (let ((dir default-directory))
12303 (condition-case nil
12304 (progn
12305 (cd tmpdir)
12306 (call-process "latex" nil nil nil texfile))
12307 (error nil))
12308 (cd dir))
12309 (if (not (file-exists-p dvifile))
12310 (progn (message "Failed to create dvi file from %s" texfile) nil)
12311 (condition-case nil
12312 (call-process "dvipng" nil nil nil
12313 "-E" "-fg" fg "-bg" bg
12314 "-D" dpi
12315 ;;"-x" scale "-y" scale
12316 "-T" "tight"
12317 "-o" pngfile
12318 dvifile)
12319 (error nil))
12320 (if (not (file-exists-p pngfile))
12321 (progn (message "Failed to create png file from %s" texfile) nil)
12322 ;; Use the requested file name and clean up
12323 (copy-file pngfile tofile 'replace)
12324 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
12325 (delete-file (concat texfilebase e)))
12326 pngfile))))
12328 (defun org-dvipng-color (attr)
12329 "Return an rgb color specification for dvipng."
12330 (apply 'format "rgb %s %s %s"
12331 (mapcar 'org-normalize-color
12332 (color-values (face-attribute 'default attr nil)))))
12334 (defun org-normalize-color (value)
12335 "Return string to be used as color value for an RGB component."
12336 (format "%g" (/ value 65535.0)))
12339 ;;;; Key bindings
12341 ;; Make `C-c C-x' a prefix key
12342 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
12344 ;; TAB key with modifiers
12345 (org-defkey org-mode-map "\C-i" 'org-cycle)
12346 (org-defkey org-mode-map [(tab)] 'org-cycle)
12347 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
12348 (org-defkey org-mode-map [(meta tab)] 'org-complete)
12349 (org-defkey org-mode-map "\M-\t" 'org-complete)
12350 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
12351 ;; The following line is necessary under Suse GNU/Linux
12352 (unless (featurep 'xemacs)
12353 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
12354 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
12355 (define-key org-mode-map [backtab] 'org-shifttab)
12357 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
12358 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
12359 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
12361 ;; Cursor keys with modifiers
12362 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
12363 (org-defkey org-mode-map [(meta right)] 'org-metaright)
12364 (org-defkey org-mode-map [(meta up)] 'org-metaup)
12365 (org-defkey org-mode-map [(meta down)] 'org-metadown)
12367 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
12368 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
12369 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
12370 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
12372 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
12373 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
12374 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
12375 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
12377 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
12378 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
12380 ;;; Extra keys for tty access.
12381 ;; We only set them when really needed because otherwise the
12382 ;; menus don't show the simple keys
12384 (when (or org-use-extra-keys
12385 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
12386 (not window-system))
12387 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
12388 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
12389 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
12390 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
12391 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
12392 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
12393 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
12394 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
12395 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
12396 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
12397 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
12398 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
12399 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
12400 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
12401 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
12402 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
12403 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
12404 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
12405 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
12406 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
12407 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
12408 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
12410 ;; All the other keys
12412 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
12413 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
12414 (if (boundp 'narrow-map)
12415 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
12416 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
12417 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
12418 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
12419 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
12420 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
12421 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
12422 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
12423 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
12424 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
12425 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
12426 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
12427 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
12428 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
12429 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
12430 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
12431 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
12432 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
12433 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
12434 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
12435 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
12436 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
12437 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
12438 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
12439 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
12440 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
12441 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
12442 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
12443 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
12444 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
12445 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
12446 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
12447 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
12448 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
12449 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
12450 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
12451 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
12452 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
12453 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
12454 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
12455 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
12456 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
12457 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
12458 (org-defkey org-mode-map "\C-c^" 'org-sort)
12459 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
12460 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
12461 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
12462 (org-defkey org-mode-map "\C-m" 'org-return)
12463 (org-defkey org-mode-map "\C-j" 'org-return-indent)
12464 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
12465 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
12466 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
12467 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
12468 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
12469 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
12470 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
12471 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
12472 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
12473 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
12474 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
12475 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
12476 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
12477 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
12478 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
12480 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
12481 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
12482 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
12483 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
12485 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
12486 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
12487 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
12488 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
12489 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
12490 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
12491 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
12492 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
12493 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
12494 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
12495 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
12496 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
12498 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
12499 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
12500 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
12502 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
12504 (when (featurep 'xemacs)
12505 (org-defkey org-mode-map 'button3 'popup-mode-menu))
12507 (defvar org-table-auto-blank-field) ; defined in org-table.el
12508 (defun org-self-insert-command (N)
12509 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
12510 If the cursor is in a table looking at whitespace, the whitespace is
12511 overwritten, and the table is not marked as requiring realignment."
12512 (interactive "p")
12513 (if (and (org-table-p)
12514 (progn
12515 ;; check if we blank the field, and if that triggers align
12516 (and (featurep 'org-table) org-table-auto-blank-field
12517 (member last-command
12518 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
12519 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
12520 ;; got extra space, this field does not determine column width
12521 (let (org-table-may-need-update) (org-table-blank-field))
12522 ;; no extra space, this field may determine column width
12523 (org-table-blank-field)))
12525 (eq N 1)
12526 (looking-at "[^|\n]* |"))
12527 (let (org-table-may-need-update)
12528 (goto-char (1- (match-end 0)))
12529 (delete-backward-char 1)
12530 (goto-char (match-beginning 0))
12531 (self-insert-command N))
12532 (setq org-table-may-need-update t)
12533 (self-insert-command N)
12534 (org-fix-tags-on-the-fly)))
12536 (defun org-fix-tags-on-the-fly ()
12537 (when (and (equal (char-after (point-at-bol)) ?*)
12538 (org-on-heading-p))
12539 (org-align-tags-here org-tags-column)))
12541 (defun org-delete-backward-char (N)
12542 "Like `delete-backward-char', insert whitespace at field end in tables.
12543 When deleting backwards, in tables this function will insert whitespace in
12544 front of the next \"|\" separator, to keep the table aligned. The table will
12545 still be marked for re-alignment if the field did fill the entire column,
12546 because, in this case the deletion might narrow the column."
12547 (interactive "p")
12548 (if (and (org-table-p)
12549 (eq N 1)
12550 (string-match "|" (buffer-substring (point-at-bol) (point)))
12551 (looking-at ".*?|"))
12552 (let ((pos (point))
12553 (noalign (looking-at "[^|\n\r]* |"))
12554 (c org-table-may-need-update))
12555 (backward-delete-char N)
12556 (skip-chars-forward "^|")
12557 (insert " ")
12558 (goto-char (1- pos))
12559 ;; noalign: if there were two spaces at the end, this field
12560 ;; does not determine the width of the column.
12561 (if noalign (setq org-table-may-need-update c)))
12562 (backward-delete-char N)
12563 (org-fix-tags-on-the-fly)))
12565 (defun org-delete-char (N)
12566 "Like `delete-char', but insert whitespace at field end in tables.
12567 When deleting characters, in tables this function will insert whitespace in
12568 front of the next \"|\" separator, to keep the table aligned. The table will
12569 still be marked for re-alignment if the field did fill the entire column,
12570 because, in this case the deletion might narrow the column."
12571 (interactive "p")
12572 (if (and (org-table-p)
12573 (not (bolp))
12574 (not (= (char-after) ?|))
12575 (eq N 1))
12576 (if (looking-at ".*?|")
12577 (let ((pos (point))
12578 (noalign (looking-at "[^|\n\r]* |"))
12579 (c org-table-may-need-update))
12580 (replace-match (concat
12581 (substring (match-string 0) 1 -1)
12582 " |"))
12583 (goto-char pos)
12584 ;; noalign: if there were two spaces at the end, this field
12585 ;; does not determine the width of the column.
12586 (if noalign (setq org-table-may-need-update c)))
12587 (delete-char N))
12588 (delete-char N)
12589 (org-fix-tags-on-the-fly)))
12591 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
12592 (put 'org-self-insert-command 'delete-selection t)
12593 (put 'orgtbl-self-insert-command 'delete-selection t)
12594 (put 'org-delete-char 'delete-selection 'supersede)
12595 (put 'org-delete-backward-char 'delete-selection 'supersede)
12597 ;; Make `flyspell-mode' delay after some commands
12598 (put 'org-self-insert-command 'flyspell-delayed t)
12599 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
12600 (put 'org-delete-char 'flyspell-delayed t)
12601 (put 'org-delete-backward-char 'flyspell-delayed t)
12603 ;; Make pabbrev-mode expand after org-mode commands
12604 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
12605 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
12607 ;; How to do this: Measure non-white length of current string
12608 ;; If equal to column width, we should realign.
12610 (defun org-remap (map &rest commands)
12611 "In MAP, remap the functions given in COMMANDS.
12612 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
12613 (let (new old)
12614 (while commands
12615 (setq old (pop commands) new (pop commands))
12616 (if (fboundp 'command-remapping)
12617 (org-defkey map (vector 'remap old) new)
12618 (substitute-key-definition old new map global-map)))))
12620 (when (eq org-enable-table-editor 'optimized)
12621 ;; If the user wants maximum table support, we need to hijack
12622 ;; some standard editing functions
12623 (org-remap org-mode-map
12624 'self-insert-command 'org-self-insert-command
12625 'delete-char 'org-delete-char
12626 'delete-backward-char 'org-delete-backward-char)
12627 (org-defkey org-mode-map "|" 'org-force-self-insert))
12629 (defun org-shiftcursor-error ()
12630 "Throw an error because Shift-Cursor command was applied in wrong context."
12631 (error "This command is active in special context like tables, headlines or timestamps"))
12633 (defun org-shifttab (&optional arg)
12634 "Global visibility cycling or move to previous table field.
12635 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
12636 on context.
12637 See the individual commands for more information."
12638 (interactive "P")
12639 (cond
12640 ((org-at-table-p) (call-interactively 'org-table-previous-field))
12641 ((integerp arg)
12642 (message "Content view to level: %d" arg)
12643 (org-content (prefix-numeric-value arg))
12644 (setq org-cycle-global-status 'overview))
12645 (t (call-interactively 'org-global-cycle))))
12647 (defun org-shiftmetaleft ()
12648 "Promote subtree or delete table column.
12649 Calls `org-promote-subtree', `org-outdent-item',
12650 or `org-table-delete-column', depending on context.
12651 See the individual commands for more information."
12652 (interactive)
12653 (cond
12654 ((org-at-table-p) (call-interactively 'org-table-delete-column))
12655 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
12656 ((org-at-item-p) (call-interactively 'org-outdent-item))
12657 (t (org-shiftcursor-error))))
12659 (defun org-shiftmetaright ()
12660 "Demote subtree or insert table column.
12661 Calls `org-demote-subtree', `org-indent-item',
12662 or `org-table-insert-column', depending on context.
12663 See the individual commands for more information."
12664 (interactive)
12665 (cond
12666 ((org-at-table-p) (call-interactively 'org-table-insert-column))
12667 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
12668 ((org-at-item-p) (call-interactively 'org-indent-item))
12669 (t (org-shiftcursor-error))))
12671 (defun org-shiftmetaup (&optional arg)
12672 "Move subtree up or kill table row.
12673 Calls `org-move-subtree-up' or `org-table-kill-row' or
12674 `org-move-item-up' depending on context. See the individual commands
12675 for more information."
12676 (interactive "P")
12677 (cond
12678 ((org-at-table-p) (call-interactively 'org-table-kill-row))
12679 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12680 ((org-at-item-p) (call-interactively 'org-move-item-up))
12681 (t (org-shiftcursor-error))))
12682 (defun org-shiftmetadown (&optional arg)
12683 "Move subtree down or insert table row.
12684 Calls `org-move-subtree-down' or `org-table-insert-row' or
12685 `org-move-item-down', depending on context. See the individual
12686 commands for more information."
12687 (interactive "P")
12688 (cond
12689 ((org-at-table-p) (call-interactively 'org-table-insert-row))
12690 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12691 ((org-at-item-p) (call-interactively 'org-move-item-down))
12692 (t (org-shiftcursor-error))))
12694 (defun org-metaleft (&optional arg)
12695 "Promote heading or move table column to left.
12696 Calls `org-do-promote' or `org-table-move-column', depending on context.
12697 With no specific context, calls the Emacs default `backward-word'.
12698 See the individual commands for more information."
12699 (interactive "P")
12700 (cond
12701 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
12702 ((or (org-on-heading-p) (org-region-active-p))
12703 (call-interactively 'org-do-promote))
12704 ((org-at-item-p) (call-interactively 'org-outdent-item))
12705 (t (call-interactively 'backward-word))))
12707 (defun org-metaright (&optional arg)
12708 "Demote subtree or move table column to right.
12709 Calls `org-do-demote' or `org-table-move-column', depending on context.
12710 With no specific context, calls the Emacs default `forward-word'.
12711 See the individual commands for more information."
12712 (interactive "P")
12713 (cond
12714 ((org-at-table-p) (call-interactively 'org-table-move-column))
12715 ((or (org-on-heading-p) (org-region-active-p))
12716 (call-interactively 'org-do-demote))
12717 ((org-at-item-p) (call-interactively 'org-indent-item))
12718 (t (call-interactively 'forward-word))))
12720 (defun org-metaup (&optional arg)
12721 "Move subtree up or move table row up.
12722 Calls `org-move-subtree-up' or `org-table-move-row' or
12723 `org-move-item-up', depending on context. See the individual commands
12724 for more information."
12725 (interactive "P")
12726 (cond
12727 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
12728 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12729 ((org-at-item-p) (call-interactively 'org-move-item-up))
12730 (t (transpose-lines 1) (beginning-of-line -1))))
12732 (defun org-metadown (&optional arg)
12733 "Move subtree down or move table row down.
12734 Calls `org-move-subtree-down' or `org-table-move-row' or
12735 `org-move-item-down', depending on context. See the individual
12736 commands for more information."
12737 (interactive "P")
12738 (cond
12739 ((org-at-table-p) (call-interactively 'org-table-move-row))
12740 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12741 ((org-at-item-p) (call-interactively 'org-move-item-down))
12742 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
12744 (defun org-shiftup (&optional arg)
12745 "Increase item in timestamp or increase priority of current headline.
12746 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
12747 depending on context. See the individual commands for more information."
12748 (interactive "P")
12749 (cond
12750 ((org-at-timestamp-p t)
12751 (call-interactively (if org-edit-timestamp-down-means-later
12752 'org-timestamp-down 'org-timestamp-up)))
12753 ((org-on-heading-p) (call-interactively 'org-priority-up))
12754 ((org-at-item-p) (call-interactively 'org-previous-item))
12755 ((org-clocktable-try-shift 'up arg))
12756 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
12758 (defun org-shiftdown (&optional arg)
12759 "Decrease item in timestamp or decrease priority of current headline.
12760 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
12761 depending on context. See the individual commands for more information."
12762 (interactive "P")
12763 (cond
12764 ((org-at-timestamp-p t)
12765 (call-interactively (if org-edit-timestamp-down-means-later
12766 'org-timestamp-up 'org-timestamp-down)))
12767 ((org-on-heading-p) (call-interactively 'org-priority-down))
12768 ((org-clocktable-try-shift 'down arg))
12769 (t (call-interactively 'org-next-item))))
12771 (defun org-shiftright (&optional arg)
12772 "Cycle the thing at point or in the current line, depending on context.
12773 Depending on context, this does one of the following:
12775 - switch a timestamp at point one day into the future
12776 - on a headline, switch to the next TODO keyword.
12777 - on an item, switch entire list to the next bullet type
12778 - on a property line, switch to the next allowed value
12779 - on a clocktable definition line, move time block into the future"
12780 (interactive "P")
12781 (cond
12782 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
12783 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
12784 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
12785 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
12786 ((org-clocktable-try-shift 'right arg))
12787 (t (org-shiftcursor-error))))
12789 (defun org-shiftleft (&optional arg)
12790 "Cycle the thing at point or in the current line, depending on context.
12791 Depending on context, this does one of the following:
12793 - switch a timestamp at point one day into the past
12794 - on a headline, switch to the previous TODO keyword.
12795 - on an item, switch entire list to the previous bullet type
12796 - on a property line, switch to the previous allowed value
12797 - on a clocktable definition line, move time block into the past"
12798 (interactive "P")
12799 (cond
12800 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
12801 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
12802 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
12803 ((org-at-property-p)
12804 (call-interactively 'org-property-previous-allowed-value))
12805 ((org-clocktable-try-shift 'left arg))
12806 (t (org-shiftcursor-error))))
12808 (defun org-shiftcontrolright ()
12809 "Switch to next TODO set."
12810 (interactive)
12811 (cond
12812 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
12813 (t (org-shiftcursor-error))))
12815 (defun org-shiftcontrolleft ()
12816 "Switch to previous TODO set."
12817 (interactive)
12818 (cond
12819 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
12820 (t (org-shiftcursor-error))))
12822 (defun org-ctrl-c-ret ()
12823 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
12824 (interactive)
12825 (cond
12826 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
12827 (t (call-interactively 'org-insert-heading))))
12829 (defun org-copy-special ()
12830 "Copy region in table or copy current subtree.
12831 Calls `org-table-copy' or `org-copy-subtree', depending on context.
12832 See the individual commands for more information."
12833 (interactive)
12834 (call-interactively
12835 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
12837 (defun org-cut-special ()
12838 "Cut region in table or cut current subtree.
12839 Calls `org-table-copy' or `org-cut-subtree', depending on context.
12840 See the individual commands for more information."
12841 (interactive)
12842 (call-interactively
12843 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
12845 (defun org-paste-special (arg)
12846 "Paste rectangular region into table, or past subtree relative to level.
12847 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
12848 See the individual commands for more information."
12849 (interactive "P")
12850 (if (org-at-table-p)
12851 (org-table-paste-rectangle)
12852 (org-paste-subtree arg)))
12854 (defun org-edit-special ()
12855 "Call a special editor for the stuff at point.
12856 When at a table, call the formula editor with `org-table-edit-formulas'.
12857 When at the first line of an src example, call `org-edit-src-code'.
12858 When in an #+include line, visit the include file. Otherwise call
12859 `ffap' to visit the file at point."
12860 (interactive)
12861 (cond
12862 ((org-at-table-p)
12863 (call-interactively 'org-table-edit-formulas))
12864 ((save-excursion
12865 (beginning-of-line 1)
12866 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
12867 (find-file (org-trim (match-string 1))))
12868 ((org-edit-src-code))
12869 ((org-edit-fixed-width-region))
12870 (t (call-interactively 'ffap))))
12872 (defun org-ctrl-c-ctrl-c (&optional arg)
12873 "Set tags in headline, or update according to changed information at point.
12875 This command does many different things, depending on context:
12877 - If the cursor is in a headline, prompt for tags and insert them
12878 into the current line, aligned to `org-tags-column'. When called
12879 with prefix arg, realign all tags in the current buffer.
12881 - If the cursor is in one of the special #+KEYWORD lines, this
12882 triggers scanning the buffer for these lines and updating the
12883 information.
12885 - If the cursor is inside a table, realign the table. This command
12886 works even if the automatic table editor has been turned off.
12888 - If the cursor is on a #+TBLFM line, re-apply the formulas to
12889 the entire table.
12891 - If the cursor is a the beginning of a dynamic block, update it.
12893 - If the cursor is inside a table created by the table.el package,
12894 activate that table.
12896 - If the current buffer is a remember buffer, close note and file
12897 it. A prefix argument of 1 files to the default location
12898 without further interaction. A prefix argument of 2 files to
12899 the currently clocking task.
12901 - If the cursor is on a <<<target>>>, update radio targets and corresponding
12902 links in this buffer.
12904 - If the cursor is on a numbered item in a plain list, renumber the
12905 ordered list.
12907 - If the cursor is on a checkbox, toggle it."
12908 (interactive "P")
12909 (let ((org-enable-table-editor t))
12910 (cond
12911 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
12912 org-occur-highlights
12913 org-latex-fragment-image-overlays)
12914 (and (boundp 'org-clock-overlays) (org-remove-clock-overlays))
12915 (org-remove-occur-highlights)
12916 (org-remove-latex-fragment-image-overlays)
12917 (message "Temporary highlights/overlays removed from current buffer"))
12918 ((and (local-variable-p 'org-finish-function (current-buffer))
12919 (fboundp org-finish-function))
12920 (funcall org-finish-function))
12921 ((org-at-property-p)
12922 (call-interactively 'org-property-action))
12923 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
12924 ((org-on-heading-p) (call-interactively 'org-set-tags))
12925 ((org-at-table.el-p)
12926 (require 'table)
12927 (beginning-of-line 1)
12928 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
12929 (call-interactively 'table-recognize-table))
12930 ((org-at-table-p)
12931 (org-table-maybe-eval-formula)
12932 (if arg
12933 (call-interactively 'org-table-recalculate)
12934 (org-table-maybe-recalculate-line))
12935 (call-interactively 'org-table-align))
12936 ((org-at-item-checkbox-p)
12937 (call-interactively 'org-toggle-checkbox))
12938 ((org-at-item-p)
12939 (call-interactively 'org-maybe-renumber-ordered-list))
12940 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
12941 ;; Dynamic block
12942 (beginning-of-line 1)
12943 (save-excursion (org-update-dblock)))
12944 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
12945 (cond
12946 ((equal (match-string 1) "TBLFM")
12947 ;; Recalculate the table before this line
12948 (save-excursion
12949 (beginning-of-line 1)
12950 (skip-chars-backward " \r\n\t")
12951 (if (org-at-table-p)
12952 (org-call-with-arg 'org-table-recalculate t))))
12954 ; (org-set-regexps-and-options)
12955 ; (org-restart-font-lock)
12956 (let ((org-inhibit-startup t)) (org-mode-restart))
12957 (message "Local setup has been refreshed"))))
12958 (t (error "C-c C-c can do nothing useful at this location.")))))
12960 (defun org-mode-restart ()
12961 "Restart Org-mode, to scan again for special lines.
12962 Also updates the keyword regular expressions."
12963 (interactive)
12964 (org-mode)
12965 (message "Org-mode restarted"))
12967 (defun org-kill-note-or-show-branches ()
12968 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
12969 (interactive)
12970 (if (not org-finish-function)
12971 (call-interactively 'show-branches)
12972 (let ((org-note-abort t))
12973 (funcall org-finish-function))))
12975 (defun org-return (&optional indent)
12976 "Goto next table row or insert a newline.
12977 Calls `org-table-next-row' or `newline', depending on context.
12978 See the individual commands for more information."
12979 (interactive)
12980 (cond
12981 ((bobp) (if indent (newline-and-indent) (newline)))
12982 ((and (org-at-heading-p)
12983 (looking-at
12984 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
12985 (org-show-entry)
12986 (end-of-line 1)
12987 (newline))
12988 ((org-at-table-p)
12989 (org-table-justify-field-maybe)
12990 (call-interactively 'org-table-next-row))
12991 (t (if indent (newline-and-indent) (newline)))))
12993 (defun org-return-indent ()
12994 "Goto next table row or insert a newline and indent.
12995 Calls `org-table-next-row' or `newline-and-indent', depending on
12996 context. See the individual commands for more information."
12997 (interactive)
12998 (org-return t))
13000 (defun org-ctrl-c-star ()
13001 "Compute table, or change heading status of lines.
13002 Calls `org-table-recalculate' or `org-toggle-region-headings',
13003 depending on context. This will also turn a plain list item or a normal
13004 line into a subheading."
13005 (interactive)
13006 (cond
13007 ((org-at-table-p)
13008 (call-interactively 'org-table-recalculate))
13009 ((org-region-active-p)
13010 ;; Convert all lines in region to list items
13011 (call-interactively 'org-toggle-region-headings))
13012 ((org-on-heading-p)
13013 (org-toggle-region-headings (point-at-bol)
13014 (min (1+ (point-at-eol)) (point-max))))
13015 ((org-at-item-p)
13016 ;; Convert to heading
13017 (let ((level (save-match-data
13018 (save-excursion
13019 (condition-case nil
13020 (progn
13021 (org-back-to-heading t)
13022 (funcall outline-level))
13023 (error 0))))))
13024 (replace-match
13025 (concat (make-string (org-get-valid-level level 1) ?*) " ") t t)))
13026 (t (org-toggle-region-headings (point-at-bol)
13027 (min (1+ (point-at-eol)) (point-max))))))
13029 (defun org-ctrl-c-minus ()
13030 "Insert separator line in table or modify bullet status of line.
13031 Also turns a plain line or a region of lines into list items.
13032 Calls `org-table-insert-hline', `org-toggle-region-items', or
13033 `org-cycle-list-bullet', depending on context."
13034 (interactive)
13035 (cond
13036 ((org-at-table-p)
13037 (call-interactively 'org-table-insert-hline))
13038 ((org-on-heading-p)
13039 ;; Convert to item
13040 (save-excursion
13041 (beginning-of-line 1)
13042 (if (looking-at "\\*+ ")
13043 (replace-match (concat (make-string (- (match-end 0) (point) 1) ?\ ) "- ")))))
13044 ((org-region-active-p)
13045 ;; Convert all lines in region to list items
13046 (call-interactively 'org-toggle-region-items))
13047 ((org-in-item-p)
13048 (call-interactively 'org-cycle-list-bullet))
13049 (t (org-toggle-region-items (point-at-bol)
13050 (min (1+ (point-at-eol)) (point-max))))))
13052 (defun org-toggle-region-items (beg end)
13053 "Convert all lines in region to list items.
13054 If the first line is already an item, convert all list items in the region
13055 to normal lines."
13056 (interactive "r")
13057 (let (l2 l)
13058 (save-excursion
13059 (goto-char end)
13060 (setq l2 (org-current-line))
13061 (goto-char beg)
13062 (beginning-of-line 1)
13063 (setq l (1- (org-current-line)))
13064 (if (org-at-item-p)
13065 ;; We already have items, de-itemize
13066 (while (< (setq l (1+ l)) l2)
13067 (when (org-at-item-p)
13068 (goto-char (match-beginning 2))
13069 (delete-region (match-beginning 2) (match-end 2))
13070 (and (looking-at "[ \t]+") (replace-match "")))
13071 (beginning-of-line 2))
13072 (while (< (setq l (1+ l)) l2)
13073 (unless (org-at-item-p)
13074 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
13075 (replace-match "\\1- \\2")))
13076 (beginning-of-line 2))))))
13078 (defun org-toggle-region-headings (beg end)
13079 "Convert all lines in region to list items.
13080 If the first line is already an item, convert all list items in the region
13081 to normal lines."
13082 (interactive "r")
13083 (let (l2 l)
13084 (save-excursion
13085 (goto-char end)
13086 (setq l2 (org-current-line))
13087 (goto-char beg)
13088 (beginning-of-line 1)
13089 (setq l (1- (org-current-line)))
13090 (if (org-on-heading-p)
13091 ;; We already have headlines, de-star them
13092 (while (< (setq l (1+ l)) l2)
13093 (when (org-on-heading-p t)
13094 (and (looking-at outline-regexp) (replace-match "")))
13095 (beginning-of-line 2))
13096 (let* ((stars (save-excursion
13097 (re-search-backward org-complex-heading-regexp nil t)
13098 (or (match-string 1) "*")))
13099 (add-stars (if org-odd-levels-only "**" "*"))
13100 (rpl (concat stars add-stars " \\2")))
13101 (while (< (setq l (1+ l)) l2)
13102 (unless (org-on-heading-p)
13103 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
13104 (replace-match rpl)))
13105 (beginning-of-line 2)))))))
13107 (defun org-meta-return (&optional arg)
13108 "Insert a new heading or wrap a region in a table.
13109 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
13110 See the individual commands for more information."
13111 (interactive "P")
13112 (cond
13113 ((org-at-table-p)
13114 (call-interactively 'org-table-wrap-region))
13115 (t (call-interactively 'org-insert-heading))))
13117 ;;; Menu entries
13119 ;; Define the Org-mode menus
13120 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
13121 '("Tbl"
13122 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
13123 ["Next Field" org-cycle (org-at-table-p)]
13124 ["Previous Field" org-shifttab (org-at-table-p)]
13125 ["Next Row" org-return (org-at-table-p)]
13126 "--"
13127 ["Blank Field" org-table-blank-field (org-at-table-p)]
13128 ["Edit Field" org-table-edit-field (org-at-table-p)]
13129 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
13130 "--"
13131 ("Column"
13132 ["Move Column Left" org-metaleft (org-at-table-p)]
13133 ["Move Column Right" org-metaright (org-at-table-p)]
13134 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
13135 ["Insert Column" org-shiftmetaright (org-at-table-p)])
13136 ("Row"
13137 ["Move Row Up" org-metaup (org-at-table-p)]
13138 ["Move Row Down" org-metadown (org-at-table-p)]
13139 ["Delete Row" org-shiftmetaup (org-at-table-p)]
13140 ["Insert Row" org-shiftmetadown (org-at-table-p)]
13141 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
13142 "--"
13143 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
13144 ("Rectangle"
13145 ["Copy Rectangle" org-copy-special (org-at-table-p)]
13146 ["Cut Rectangle" org-cut-special (org-at-table-p)]
13147 ["Paste Rectangle" org-paste-special (org-at-table-p)]
13148 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
13149 "--"
13150 ("Calculate"
13151 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
13152 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
13153 ["Edit Formulas" org-edit-special (org-at-table-p)]
13154 "--"
13155 ["Recalculate line" org-table-recalculate (org-at-table-p)]
13156 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
13157 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
13158 "--"
13159 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
13160 "--"
13161 ["Sum Column/Rectangle" org-table-sum
13162 (or (org-at-table-p) (org-region-active-p))]
13163 ["Which Column?" org-table-current-column (org-at-table-p)])
13164 ["Debug Formulas"
13165 org-table-toggle-formula-debugger
13166 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
13167 ["Show Col/Row Numbers"
13168 org-table-toggle-coordinate-overlays
13169 :style toggle
13170 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
13171 "--"
13172 ["Create" org-table-create (and (not (org-at-table-p))
13173 org-enable-table-editor)]
13174 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
13175 ["Import from File" org-table-import (not (org-at-table-p))]
13176 ["Export to File" org-table-export (org-at-table-p)]
13177 "--"
13178 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
13180 (easy-menu-define org-org-menu org-mode-map "Org menu"
13181 '("Org"
13182 ("Show/Hide"
13183 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
13184 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
13185 ["Sparse Tree..." org-sparse-tree t]
13186 ["Reveal Context" org-reveal t]
13187 ["Show All" show-all t]
13188 "--"
13189 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
13190 "--"
13191 ["New Heading" org-insert-heading t]
13192 ("Navigate Headings"
13193 ["Up" outline-up-heading t]
13194 ["Next" outline-next-visible-heading t]
13195 ["Previous" outline-previous-visible-heading t]
13196 ["Next Same Level" outline-forward-same-level t]
13197 ["Previous Same Level" outline-backward-same-level t]
13198 "--"
13199 ["Jump" org-goto t])
13200 ("Edit Structure"
13201 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
13202 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
13203 "--"
13204 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
13205 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
13206 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
13207 "--"
13208 ["Promote Heading" org-metaleft (not (org-at-table-p))]
13209 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
13210 ["Demote Heading" org-metaright (not (org-at-table-p))]
13211 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
13212 "--"
13213 ["Sort Region/Children" org-sort (not (org-at-table-p))]
13214 "--"
13215 ["Convert to odd levels" org-convert-to-odd-levels t]
13216 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
13217 ("Editing"
13218 ["Emphasis..." org-emphasize t]
13219 ["Edit Source Example" org-edit-special t])
13220 ("Archive"
13221 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
13222 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
13223 ; :active t :keys "C-u C-c C-x C-a"]
13224 ["Sparse trees open ARCHIVE trees"
13225 (setq org-sparse-tree-open-archived-trees
13226 (not org-sparse-tree-open-archived-trees))
13227 :style toggle :selected org-sparse-tree-open-archived-trees]
13228 ["Cycling opens ARCHIVE trees"
13229 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
13230 :style toggle :selected org-cycle-open-archived-trees]
13231 "--"
13232 ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
13233 ["Move Subtree to Archive" org-advertized-archive-subtree t]
13234 ; ["Check and Move Children" (org-archive-subtree '(4))
13235 ; :active t :keys "C-u C-c C-x C-s"]
13237 "--"
13238 ("TODO Lists"
13239 ["TODO/DONE/-" org-todo t]
13240 ("Select keyword"
13241 ["Next keyword" org-shiftright (org-on-heading-p)]
13242 ["Previous keyword" org-shiftleft (org-on-heading-p)]
13243 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
13244 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
13245 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
13246 ["Show TODO Tree" org-show-todo-tree t]
13247 ["Global TODO list" org-todo-list t]
13248 "--"
13249 ["Set Priority" org-priority t]
13250 ["Priority Up" org-shiftup t]
13251 ["Priority Down" org-shiftdown t])
13252 ("TAGS and Properties"
13253 ["Set Tags" 'org-set-tags-command t]
13254 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
13255 "--"
13256 ["Set property" 'org-set-property t]
13257 ["Column view of properties" org-columns t]
13258 ["Insert Column View DBlock" org-insert-columns-dblock t])
13259 ("Dates and Scheduling"
13260 ["Timestamp" org-time-stamp t]
13261 ["Timestamp (inactive)" org-time-stamp-inactive t]
13262 ("Change Date"
13263 ["1 Day Later" org-shiftright t]
13264 ["1 Day Earlier" org-shiftleft t]
13265 ["1 ... Later" org-shiftup t]
13266 ["1 ... Earlier" org-shiftdown t])
13267 ["Compute Time Range" org-evaluate-time-range t]
13268 ["Schedule Item" org-schedule t]
13269 ["Deadline" org-deadline t]
13270 "--"
13271 ["Custom time format" org-toggle-time-stamp-overlays
13272 :style radio :selected org-display-custom-times]
13273 "--"
13274 ["Goto Calendar" org-goto-calendar t]
13275 ["Date from Calendar" org-date-from-calendar t]
13276 "--"
13277 ["Start/restart timer" org-timer-start t]
13278 ["Insert timer string" org-timer t]
13279 ["Insert timer item" org-timer-item t])
13280 ("Logging work"
13281 ["Clock in" org-clock-in t]
13282 ["Clock out" org-clock-out t]
13283 ["Clock cancel" org-clock-cancel t]
13284 ["Goto running clock" org-clock-goto t]
13285 ["Display times" org-clock-display t]
13286 ["Create clock table" org-clock-report t]
13287 "--"
13288 ["Record DONE time"
13289 (progn (setq org-log-done (not org-log-done))
13290 (message "Switching to %s will %s record a timestamp"
13291 (car org-done-keywords)
13292 (if org-log-done "automatically" "not")))
13293 :style toggle :selected org-log-done])
13294 "--"
13295 ["Agenda Command..." org-agenda t]
13296 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
13297 ("File List for Agenda")
13298 ("Special views current file"
13299 ["TODO Tree" org-show-todo-tree t]
13300 ["Check Deadlines" org-check-deadlines t]
13301 ["Timeline" org-timeline t]
13302 ["Tags Tree" org-tags-sparse-tree t])
13303 "--"
13304 ("Hyperlinks"
13305 ["Store Link (Global)" org-store-link t]
13306 ["Insert Link" org-insert-link t]
13307 ["Follow Link" org-open-at-point t]
13308 "--"
13309 ["Next link" org-next-link t]
13310 ["Previous link" org-previous-link t]
13311 "--"
13312 ["Descriptive Links"
13313 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
13314 :style radio
13315 :selected (member '(org-link) buffer-invisibility-spec)]
13316 ["Literal Links"
13317 (progn
13318 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
13319 :style radio
13320 :selected (not (member '(org-link) buffer-invisibility-spec))])
13321 "--"
13322 ["Export/Publish..." org-export t]
13323 ("LaTeX"
13324 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
13325 :selected org-cdlatex-mode]
13326 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
13327 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
13328 ["Modify math symbol" org-cdlatex-math-modify
13329 (org-inside-LaTeX-fragment-p)]
13330 ["Export LaTeX fragments as images"
13331 (if (featurep 'org-exp)
13332 (setq org-export-with-LaTeX-fragments
13333 (not org-export-with-LaTeX-fragments))
13334 (require 'org-exp))
13335 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
13336 org-export-with-LaTeX-fragments)])
13337 "--"
13338 ("Documentation"
13339 ["Show Version" org-version t]
13340 ["Info Documentation" org-info t])
13341 ("Customize"
13342 ["Browse Org Group" org-customize t]
13343 "--"
13344 ["Expand This Menu" org-create-customize-menu
13345 (fboundp 'customize-menu-create)])
13346 "--"
13347 ["Refresh setup" org-mode-restart t]
13350 (defun org-info (&optional node)
13351 "Read documentation for Org-mode in the info system.
13352 With optional NODE, go directly to that node."
13353 (interactive)
13354 (info (format "(org)%s" (or node ""))))
13356 (defun org-install-agenda-files-menu ()
13357 (let ((bl (buffer-list)))
13358 (save-excursion
13359 (while bl
13360 (set-buffer (pop bl))
13361 (if (org-mode-p) (setq bl nil)))
13362 (when (org-mode-p)
13363 (easy-menu-change
13364 '("Org") "File List for Agenda"
13365 (append
13366 (list
13367 ["Edit File List" (org-edit-agenda-file-list) t]
13368 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
13369 ["Remove Current File from List" org-remove-file t]
13370 ["Cycle through agenda files" org-cycle-agenda-files t]
13371 ["Occur in all agenda files" org-occur-in-agenda-files t]
13372 "--")
13373 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
13375 ;;;; Documentation
13377 ;;;###autoload
13378 (defun org-require-autoloaded-modules ()
13379 (interactive)
13380 (mapc 'require
13381 '(org-agenda org-archive org-clock org-colview
13382 org-exp org-id org-export-latex org-publish
13383 org-remember org-table)))
13385 ;;;###autoload
13386 (defun org-customize ()
13387 "Call the customize function with org as argument."
13388 (interactive)
13389 (org-load-modules-maybe)
13390 (org-require-autoloaded-modules)
13391 (customize-browse 'org))
13393 (defun org-create-customize-menu ()
13394 "Create a full customization menu for Org-mode, insert it into the menu."
13395 (interactive)
13396 (org-load-modules-maybe)
13397 (org-require-autoloaded-modules)
13398 (if (fboundp 'customize-menu-create)
13399 (progn
13400 (easy-menu-change
13401 '("Org") "Customize"
13402 `(["Browse Org group" org-customize t]
13403 "--"
13404 ,(customize-menu-create 'org)
13405 ["Set" Custom-set t]
13406 ["Save" Custom-save t]
13407 ["Reset to Current" Custom-reset-current t]
13408 ["Reset to Saved" Custom-reset-saved t]
13409 ["Reset to Standard Settings" Custom-reset-standard t]))
13410 (message "\"Org\"-menu now contains full customization menu"))
13411 (error "Cannot expand menu (outdated version of cus-edit.el)")))
13413 ;;;; Miscellaneous stuff
13415 ;;; Generally useful functions
13417 (defun org-find-text-property-in-string (prop s)
13418 "Return the first non-nil value of property PROP in string S."
13419 (or (get-text-property 0 prop s)
13420 (get-text-property (or (next-single-property-change 0 prop s) 0)
13421 prop s)))
13423 (defun org-display-warning (message) ;; Copied from Emacs-Muse
13424 "Display the given MESSAGE as a warning."
13425 (if (fboundp 'display-warning)
13426 (display-warning 'org message
13427 (if (featurep 'xemacs)
13428 'warning
13429 :warning))
13430 (let ((buf (get-buffer-create "*Org warnings*")))
13431 (with-current-buffer buf
13432 (goto-char (point-max))
13433 (insert "Warning (Org): " message)
13434 (unless (bolp)
13435 (newline)))
13436 (display-buffer buf)
13437 (sit-for 0))))
13439 (defun org-goto-marker-or-bmk (marker &optional bookmark)
13440 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
13441 (if (and marker (marker-buffer marker)
13442 (buffer-live-p (marker-buffer marker)))
13443 (progn
13444 (switch-to-buffer (marker-buffer marker))
13445 (if (or (> marker (point-max)) (< marker (point-min)))
13446 (widen))
13447 (goto-char marker))
13448 (if bookmark
13449 (bookmark-jump bookmark)
13450 (error "Cannot find location"))))
13452 (defun org-quote-csv-field (s)
13453 "Quote field for inclusion in CSV material."
13454 (if (string-match "[\",]" s)
13455 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
13458 (defun org-plist-delete (plist property)
13459 "Delete PROPERTY from PLIST.
13460 This is in contrast to merely setting it to 0."
13461 (let (p)
13462 (while plist
13463 (if (not (eq property (car plist)))
13464 (setq p (plist-put p (car plist) (nth 1 plist))))
13465 (setq plist (cddr plist)))
13468 (defun org-force-self-insert (N)
13469 "Needed to enforce self-insert under remapping."
13470 (interactive "p")
13471 (self-insert-command N))
13473 (defun org-string-width (s)
13474 "Compute width of string, ignoring invisible characters.
13475 This ignores character with invisibility property `org-link', and also
13476 characters with property `org-cwidth', because these will become invisible
13477 upon the next fontification round."
13478 (let (b l)
13479 (when (or (eq t buffer-invisibility-spec)
13480 (assq 'org-link buffer-invisibility-spec))
13481 (while (setq b (text-property-any 0 (length s)
13482 'invisible 'org-link s))
13483 (setq s (concat (substring s 0 b)
13484 (substring s (or (next-single-property-change
13485 b 'invisible s) (length s)))))))
13486 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
13487 (setq s (concat (substring s 0 b)
13488 (substring s (or (next-single-property-change
13489 b 'org-cwidth s) (length s))))))
13490 (setq l (string-width s) b -1)
13491 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
13492 (setq l (- l (get-text-property b 'org-dwidth-n s))))
13495 (defun org-get-indentation (&optional line)
13496 "Get the indentation of the current line, interpreting tabs.
13497 When LINE is given, assume it represents a line and compute its indentation."
13498 (if line
13499 (if (string-match "^ *" (org-remove-tabs line))
13500 (match-end 0))
13501 (save-excursion
13502 (beginning-of-line 1)
13503 (skip-chars-forward " \t")
13504 (current-column))))
13506 (defun org-remove-tabs (s &optional width)
13507 "Replace tabulators in S with spaces.
13508 Assumes that s is a single line, starting in column 0."
13509 (setq width (or width tab-width))
13510 (while (string-match "\t" s)
13511 (setq s (replace-match
13512 (make-string
13513 (- (* width (/ (+ (match-beginning 0) width) width))
13514 (match-beginning 0)) ?\ )
13515 t t s)))
13518 (defun org-fix-indentation (line ind)
13519 "Fix indentation in LINE.
13520 IND is a cons cell with target and minimum indentation.
13521 If the current indenation in LINE is smaller than the minimum,
13522 leave it alone. If it is larger than ind, set it to the target."
13523 (let* ((l (org-remove-tabs line))
13524 (i (org-get-indentation l))
13525 (i1 (car ind)) (i2 (cdr ind)))
13526 (if (>= i i2) (setq l (substring line i2)))
13527 (if (> i1 0)
13528 (concat (make-string i1 ?\ ) l)
13529 l)))
13531 (defun org-base-buffer (buffer)
13532 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
13533 (if (not buffer)
13534 buffer
13535 (or (buffer-base-buffer buffer)
13536 buffer)))
13538 (defun org-trim (s)
13539 "Remove whitespace at beginning and end of string."
13540 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
13541 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
13544 (defun org-wrap (string &optional width lines)
13545 "Wrap string to either a number of lines, or a width in characters.
13546 If WIDTH is non-nil, the string is wrapped to that width, however many lines
13547 that costs. If there is a word longer than WIDTH, the text is actually
13548 wrapped to the length of that word.
13549 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
13550 many lines, whatever width that takes.
13551 The return value is a list of lines, without newlines at the end."
13552 (let* ((words (org-split-string string "[ \t\n]+"))
13553 (maxword (apply 'max (mapcar 'org-string-width words)))
13554 w ll)
13555 (cond (width
13556 (org-do-wrap words (max maxword width)))
13557 (lines
13558 (setq w maxword)
13559 (setq ll (org-do-wrap words maxword))
13560 (if (<= (length ll) lines)
13562 (setq ll words)
13563 (while (> (length ll) lines)
13564 (setq w (1+ w))
13565 (setq ll (org-do-wrap words w)))
13566 ll))
13567 (t (error "Cannot wrap this")))))
13569 (defun org-do-wrap (words width)
13570 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
13571 (let (lines line)
13572 (while words
13573 (setq line (pop words))
13574 (while (and words (< (+ (length line) (length (car words))) width))
13575 (setq line (concat line " " (pop words))))
13576 (setq lines (push line lines)))
13577 (nreverse lines)))
13579 (defun org-split-string (string &optional separators)
13580 "Splits STRING into substrings at SEPARATORS.
13581 No empty strings are returned if there are matches at the beginning
13582 and end of string."
13583 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
13584 (start 0)
13585 notfirst
13586 (list nil))
13587 (while (and (string-match rexp string
13588 (if (and notfirst
13589 (= start (match-beginning 0))
13590 (< start (length string)))
13591 (1+ start) start))
13592 (< (match-beginning 0) (length string)))
13593 (setq notfirst t)
13594 (or (eq (match-beginning 0) 0)
13595 (and (eq (match-beginning 0) (match-end 0))
13596 (eq (match-beginning 0) start))
13597 (setq list
13598 (cons (substring string start (match-beginning 0))
13599 list)))
13600 (setq start (match-end 0)))
13601 (or (eq start (length string))
13602 (setq list
13603 (cons (substring string start)
13604 list)))
13605 (nreverse list)))
13607 (defun org-context ()
13608 "Return a list of contexts of the current cursor position.
13609 If several contexts apply, all are returned.
13610 Each context entry is a list with a symbol naming the context, and
13611 two positions indicating start and end of the context. Possible
13612 contexts are:
13614 :headline anywhere in a headline
13615 :headline-stars on the leading stars in a headline
13616 :todo-keyword on a TODO keyword (including DONE) in a headline
13617 :tags on the TAGS in a headline
13618 :priority on the priority cookie in a headline
13619 :item on the first line of a plain list item
13620 :item-bullet on the bullet/number of a plain list item
13621 :checkbox on the checkbox in a plain list item
13622 :table in an org-mode table
13623 :table-special on a special filed in a table
13624 :table-table in a table.el table
13625 :link on a hyperlink
13626 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
13627 :target on a <<target>>
13628 :radio-target on a <<<radio-target>>>
13629 :latex-fragment on a LaTeX fragment
13630 :latex-preview on a LaTeX fragment with overlayed preview image
13632 This function expects the position to be visible because it uses font-lock
13633 faces as a help to recognize the following contexts: :table-special, :link,
13634 and :keyword."
13635 (let* ((f (get-text-property (point) 'face))
13636 (faces (if (listp f) f (list f)))
13637 (p (point)) clist o)
13638 ;; First the large context
13639 (cond
13640 ((org-on-heading-p t)
13641 (push (list :headline (point-at-bol) (point-at-eol)) clist)
13642 (when (progn
13643 (beginning-of-line 1)
13644 (looking-at org-todo-line-tags-regexp))
13645 (push (org-point-in-group p 1 :headline-stars) clist)
13646 (push (org-point-in-group p 2 :todo-keyword) clist)
13647 (push (org-point-in-group p 4 :tags) clist))
13648 (goto-char p)
13649 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
13650 (if (looking-at "\\[#[A-Z0-9]\\]")
13651 (push (org-point-in-group p 0 :priority) clist)))
13653 ((org-at-item-p)
13654 (push (org-point-in-group p 2 :item-bullet) clist)
13655 (push (list :item (point-at-bol)
13656 (save-excursion (org-end-of-item) (point)))
13657 clist)
13658 (and (org-at-item-checkbox-p)
13659 (push (org-point-in-group p 0 :checkbox) clist)))
13661 ((org-at-table-p)
13662 (push (list :table (org-table-begin) (org-table-end)) clist)
13663 (if (memq 'org-formula faces)
13664 (push (list :table-special
13665 (previous-single-property-change p 'face)
13666 (next-single-property-change p 'face)) clist)))
13667 ((org-at-table-p 'any)
13668 (push (list :table-table) clist)))
13669 (goto-char p)
13671 ;; Now the small context
13672 (cond
13673 ((org-at-timestamp-p)
13674 (push (org-point-in-group p 0 :timestamp) clist))
13675 ((memq 'org-link faces)
13676 (push (list :link
13677 (previous-single-property-change p 'face)
13678 (next-single-property-change p 'face)) clist))
13679 ((memq 'org-special-keyword faces)
13680 (push (list :keyword
13681 (previous-single-property-change p 'face)
13682 (next-single-property-change p 'face)) clist))
13683 ((org-on-target-p)
13684 (push (org-point-in-group p 0 :target) clist)
13685 (goto-char (1- (match-beginning 0)))
13686 (if (looking-at org-radio-target-regexp)
13687 (push (org-point-in-group p 0 :radio-target) clist))
13688 (goto-char p))
13689 ((setq o (car (delq nil
13690 (mapcar
13691 (lambda (x)
13692 (if (memq x org-latex-fragment-image-overlays) x))
13693 (org-overlays-at (point))))))
13694 (push (list :latex-fragment
13695 (org-overlay-start o) (org-overlay-end o)) clist)
13696 (push (list :latex-preview
13697 (org-overlay-start o) (org-overlay-end o)) clist))
13698 ((org-inside-LaTeX-fragment-p)
13699 ;; FIXME: positions wrong.
13700 (push (list :latex-fragment (point) (point)) clist)))
13702 (setq clist (nreverse (delq nil clist)))
13703 clist))
13705 ;; FIXME: Compare with at-regexp-p Do we need both?
13706 (defun org-in-regexp (re &optional nlines visually)
13707 "Check if point is inside a match of regexp.
13708 Normally only the current line is checked, but you can include NLINES extra
13709 lines both before and after point into the search.
13710 If VISUALLY is set, require that the cursor is not after the match but
13711 really on, so that the block visually is on the match."
13712 (catch 'exit
13713 (let ((pos (point))
13714 (eol (point-at-eol (+ 1 (or nlines 0))))
13715 (inc (if visually 1 0)))
13716 (save-excursion
13717 (beginning-of-line (- 1 (or nlines 0)))
13718 (while (re-search-forward re eol t)
13719 (if (and (<= (match-beginning 0) pos)
13720 (>= (+ inc (match-end 0)) pos))
13721 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
13723 (defun org-at-regexp-p (regexp)
13724 "Is point inside a match of REGEXP in the current line?"
13725 (catch 'exit
13726 (save-excursion
13727 (let ((pos (point)) (end (point-at-eol)))
13728 (beginning-of-line 1)
13729 (while (re-search-forward regexp end t)
13730 (if (and (<= (match-beginning 0) pos)
13731 (>= (match-end 0) pos))
13732 (throw 'exit t)))
13733 nil))))
13735 (defun org-occur-in-agenda-files (regexp &optional nlines)
13736 "Call `multi-occur' with buffers for all agenda files."
13737 (interactive "sOrg-files matching: \np")
13738 (let* ((files (org-agenda-files))
13739 (tnames (mapcar 'file-truename files))
13740 (extra org-agenda-text-search-extra-files)
13742 (when (eq (car extra) 'agenda-archives)
13743 (setq extra (cdr extra))
13744 (setq files (org-add-archive-files files)))
13745 (while (setq f (pop extra))
13746 (unless (member (file-truename f) tnames)
13747 (add-to-list 'files f 'append)
13748 (add-to-list 'tnames (file-truename f) 'append)))
13749 (multi-occur
13750 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
13751 regexp)))
13753 (if (boundp 'occur-mode-find-occurrence-hook)
13754 ;; Emacs 23
13755 (add-hook 'occur-mode-find-occurrence-hook
13756 (lambda ()
13757 (when (org-mode-p)
13758 (org-reveal))))
13759 ;; Emacs 22
13760 (defadvice occur-mode-goto-occurrence
13761 (after org-occur-reveal activate)
13762 (and (org-mode-p) (org-reveal)))
13763 (defadvice occur-mode-goto-occurrence-other-window
13764 (after org-occur-reveal activate)
13765 (and (org-mode-p) (org-reveal)))
13766 (defadvice occur-mode-display-occurrence
13767 (after org-occur-reveal activate)
13768 (when (org-mode-p)
13769 (let ((pos (occur-mode-find-occurrence)))
13770 (with-current-buffer (marker-buffer pos)
13771 (save-excursion
13772 (goto-char pos)
13773 (org-reveal)))))))
13775 (defun org-uniquify (list)
13776 "Remove duplicate elements from LIST."
13777 (let (res)
13778 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
13779 res))
13781 (defun org-delete-all (elts list)
13782 "Remove all elements in ELTS from LIST."
13783 (while elts
13784 (setq list (delete (pop elts) list)))
13785 list)
13787 (defun org-back-over-empty-lines ()
13788 "Move backwards over witespace, to the beginning of the first empty line.
13789 Returns the number of empty lines passed."
13790 (let ((pos (point)))
13791 (skip-chars-backward " \t\n\r")
13792 (beginning-of-line 2)
13793 (goto-char (min (point) pos))
13794 (count-lines (point) pos)))
13796 (defun org-skip-whitespace ()
13797 (skip-chars-forward " \t\n\r"))
13799 (defun org-point-in-group (point group &optional context)
13800 "Check if POINT is in match-group GROUP.
13801 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
13802 match. If the match group does ot exist or point is not inside it,
13803 return nil."
13804 (and (match-beginning group)
13805 (>= point (match-beginning group))
13806 (<= point (match-end group))
13807 (if context
13808 (list context (match-beginning group) (match-end group))
13809 t)))
13811 (defun org-switch-to-buffer-other-window (&rest args)
13812 "Switch to buffer in a second window on the current frame.
13813 In particular, do not allow pop-up frames."
13814 (let (pop-up-frames special-display-buffer-names special-display-regexps
13815 special-display-function)
13816 (apply 'switch-to-buffer-other-window args)))
13818 (defun org-combine-plists (&rest plists)
13819 "Create a single property list from all plists in PLISTS.
13820 The process starts by copying the first list, and then setting properties
13821 from the other lists. Settings in the last list are the most significant
13822 ones and overrule settings in the other lists."
13823 (let ((rtn (copy-sequence (pop plists)))
13824 p v ls)
13825 (while plists
13826 (setq ls (pop plists))
13827 (while ls
13828 (setq p (pop ls) v (pop ls))
13829 (setq rtn (plist-put rtn p v))))
13830 rtn))
13832 (defun org-move-line-down (arg)
13833 "Move the current line down. With prefix argument, move it past ARG lines."
13834 (interactive "p")
13835 (let ((col (current-column))
13836 beg end pos)
13837 (beginning-of-line 1) (setq beg (point))
13838 (beginning-of-line 2) (setq end (point))
13839 (beginning-of-line (+ 1 arg))
13840 (setq pos (move-marker (make-marker) (point)))
13841 (insert (delete-and-extract-region beg end))
13842 (goto-char pos)
13843 (org-move-to-column col)))
13845 (defun org-move-line-up (arg)
13846 "Move the current line up. With prefix argument, move it past ARG lines."
13847 (interactive "p")
13848 (let ((col (current-column))
13849 beg end pos)
13850 (beginning-of-line 1) (setq beg (point))
13851 (beginning-of-line 2) (setq end (point))
13852 (beginning-of-line (- arg))
13853 (setq pos (move-marker (make-marker) (point)))
13854 (insert (delete-and-extract-region beg end))
13855 (goto-char pos)
13856 (org-move-to-column col)))
13858 (defun org-replace-escapes (string table)
13859 "Replace %-escapes in STRING with values in TABLE.
13860 TABLE is an association list with keys like \"%a\" and string values.
13861 The sequences in STRING may contain normal field width and padding information,
13862 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
13863 so values can contain further %-escapes if they are define later in TABLE."
13864 (let ((case-fold-search nil)
13865 e re rpl)
13866 (while (setq e (pop table))
13867 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
13868 (while (string-match re string)
13869 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
13870 (cdr e)))
13871 (setq string (replace-match rpl t t string))))
13872 string))
13875 (defun org-sublist (list start end)
13876 "Return a section of LIST, from START to END.
13877 Counting starts at 1."
13878 (let (rtn (c start))
13879 (setq list (nthcdr (1- start) list))
13880 (while (and list (<= c end))
13881 (push (pop list) rtn)
13882 (setq c (1+ c)))
13883 (nreverse rtn)))
13885 (defun org-find-base-buffer-visiting (file)
13886 "Like `find-buffer-visiting' but alway return the base buffer and
13887 not an indirect buffer."
13888 (let ((buf (find-buffer-visiting file)))
13889 (if buf
13890 (or (buffer-base-buffer buf) buf)
13891 nil)))
13893 (defun org-image-file-name-regexp ()
13894 "Return regexp matching the file names of images."
13895 (if (fboundp 'image-file-name-regexp)
13896 (image-file-name-regexp)
13897 (let ((image-file-name-extensions
13898 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
13899 "xbm" "xpm" "pbm" "pgm" "ppm")))
13900 (concat "\\."
13901 (regexp-opt (nconc (mapcar 'upcase
13902 image-file-name-extensions)
13903 image-file-name-extensions)
13905 "\\'"))))
13907 (defun org-file-image-p (file)
13908 "Return non-nil if FILE is an image."
13909 (save-match-data
13910 (string-match (org-image-file-name-regexp) file)))
13912 (defun org-get-cursor-date ()
13913 "Return the date at cursor in as a time.
13914 This works in the calendar and in the agenda, anywhere else it just
13915 returns the current time."
13916 (let (date day defd)
13917 (cond
13918 ((eq major-mode 'calendar-mode)
13919 (setq date (calendar-cursor-to-date)
13920 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13921 ((eq major-mode 'org-agenda-mode)
13922 (setq day (get-text-property (point) 'day))
13923 (if day
13924 (setq date (calendar-gregorian-from-absolute day)
13925 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
13926 (nth 2 date))))))
13927 (or defd (current-time))))
13929 (defvar org-agenda-action-marker (make-marker)
13930 "Marker pointing to the entry for the next agenda action.")
13932 (defun org-mark-entry-for-agenda-action ()
13933 "Mark the current entry as target of an agenda action.
13934 Agenda actions are actions executed from the agenda with the key `k',
13935 which make use of the date at the cursor."
13936 (interactive)
13937 (move-marker org-agenda-action-marker
13938 (save-excursion (org-back-to-heading t) (point))
13939 (current-buffer))
13940 (message
13941 "Entry marked for action; press `k' at desired date in agenda or calendar"))
13943 ;;; Paragraph filling stuff.
13944 ;; We want this to be just right, so use the full arsenal.
13946 (defun org-indent-line-function ()
13947 "Indent line like previous, but further if previous was headline or item."
13948 (interactive)
13949 (let* ((pos (point))
13950 (itemp (org-at-item-p))
13951 column bpos bcol tpos tcol bullet btype bullet-type)
13952 ;; Find the previous relevant line
13953 (beginning-of-line 1)
13954 (cond
13955 ((looking-at "#") (setq column 0))
13956 ((looking-at "\\*+ ") (setq column 0))
13958 (beginning-of-line 0)
13959 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
13960 (beginning-of-line 0))
13961 (cond
13962 ((looking-at "\\*+[ \t]+")
13963 (if (not org-adapt-indentation)
13964 (setq column 0)
13965 (goto-char (match-end 0))
13966 (setq column (current-column))))
13967 ((org-in-item-p)
13968 (org-beginning-of-item)
13969 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
13970 (setq bpos (match-beginning 1) tpos (match-end 0)
13971 bcol (progn (goto-char bpos) (current-column))
13972 tcol (progn (goto-char tpos) (current-column))
13973 bullet (match-string 1)
13974 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
13975 (if (> tcol (+ bcol org-description-max-indent))
13976 (setq tcol (+ bcol 5)))
13977 (if (not itemp)
13978 (setq column tcol)
13979 (goto-char pos)
13980 (beginning-of-line 1)
13981 (if (looking-at "\\S-")
13982 (progn
13983 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
13984 (setq bullet (match-string 1)
13985 btype (if (string-match "[0-9]" bullet) "n" bullet))
13986 (setq column (if (equal btype bullet-type) bcol tcol)))
13987 (setq column (org-get-indentation)))))
13988 (t (setq column (org-get-indentation))))))
13989 (goto-char pos)
13990 (if (<= (current-column) (current-indentation))
13991 (org-indent-line-to column)
13992 (save-excursion (org-indent-line-to column)))
13993 (setq column (current-column))
13994 (beginning-of-line 1)
13995 (if (looking-at
13996 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
13997 (replace-match (concat "\\1" (format org-property-format
13998 (match-string 2) (match-string 3)))
13999 t nil))
14000 (org-move-to-column column)))
14002 (defun org-set-autofill-regexps ()
14003 (interactive)
14004 ;; In the paragraph separator we include headlines, because filling
14005 ;; text in a line directly attached to a headline would otherwise
14006 ;; fill the headline as well.
14007 (org-set-local 'comment-start-skip "^#+[ \t]*")
14008 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
14009 ;; The paragraph starter includes hand-formatted lists.
14010 (org-set-local 'paragraph-start
14011 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
14012 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
14013 ;; But only if the user has not turned off tables or fixed-width regions
14014 (org-set-local
14015 'auto-fill-inhibit-regexp
14016 (concat "\\*+ \\|#\\+"
14017 "\\|[ \t]*" org-keyword-time-regexp
14018 (if (or org-enable-table-editor org-enable-fixed-width-editor)
14019 (concat
14020 "\\|[ \t]*["
14021 (if org-enable-table-editor "|" "")
14022 (if org-enable-fixed-width-editor ":" "")
14023 "]"))))
14024 ;; We use our own fill-paragraph function, to make sure that tables
14025 ;; and fixed-width regions are not wrapped. That function will pass
14026 ;; through to `fill-paragraph' when appropriate.
14027 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
14028 ; Adaptive filling: To get full control, first make sure that
14029 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
14030 (org-set-local 'adaptive-fill-regexp "\000")
14031 (org-set-local 'adaptive-fill-function
14032 'org-adaptive-fill-function)
14033 (org-set-local
14034 'align-mode-rules-list
14035 '((org-in-buffer-settings
14036 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
14037 (modes . '(org-mode))))))
14039 (defun org-fill-paragraph (&optional justify)
14040 "Re-align a table, pass through to fill-paragraph if no table."
14041 (let ((table-p (org-at-table-p))
14042 (table.el-p (org-at-table.el-p)))
14043 (cond ((and (equal (char-after (point-at-bol)) ?*)
14044 (save-excursion (goto-char (point-at-bol))
14045 (looking-at outline-regexp)))
14046 t) ; skip headlines
14047 (table.el-p t) ; skip table.el tables
14048 (table-p (org-table-align) t) ; align org-mode tables
14049 (t nil)))) ; call paragraph-fill
14051 ;; For reference, this is the default value of adaptive-fill-regexp
14052 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
14054 (defun org-adaptive-fill-function ()
14055 "Return a fill prefix for org-mode files.
14056 In particular, this makes sure hanging paragraphs for hand-formatted lists
14057 work correctly."
14058 (cond ((looking-at "#[ \t]+")
14059 (match-string 0))
14060 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
14061 (save-excursion
14062 (if (> (match-end 1) (+ (match-beginning 1)
14063 org-description-max-indent))
14064 (goto-char (+ (match-beginning 1) 5))
14065 (goto-char (match-end 0)))
14066 (make-string (current-column) ?\ )))
14067 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
14068 (save-excursion
14069 (goto-char (match-end 0))
14070 (make-string (current-column) ?\ )))
14071 (t nil)))
14073 ;;; Other stuff.
14075 (defun org-toggle-fixed-width-section (arg)
14076 "Toggle the fixed-width export.
14077 If there is no active region, the QUOTE keyword at the current headline is
14078 inserted or removed. When present, it causes the text between this headline
14079 and the next to be exported as fixed-width text, and unmodified.
14080 If there is an active region, this command adds or removes a colon as the
14081 first character of this line. If the first character of a line is a colon,
14082 this line is also exported in fixed-width font."
14083 (interactive "P")
14084 (let* ((cc 0)
14085 (regionp (org-region-active-p))
14086 (beg (if regionp (region-beginning) (point)))
14087 (end (if regionp (region-end)))
14088 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
14089 (case-fold-search nil)
14090 (re "[ \t]*\\(:\\)")
14091 off)
14092 (if regionp
14093 (save-excursion
14094 (goto-char beg)
14095 (setq cc (current-column))
14096 (beginning-of-line 1)
14097 (setq off (looking-at re))
14098 (while (> nlines 0)
14099 (setq nlines (1- nlines))
14100 (beginning-of-line 1)
14101 (cond
14102 (arg
14103 (org-move-to-column cc t)
14104 (insert ":\n")
14105 (forward-line -1))
14106 ((and off (looking-at re))
14107 (replace-match "" t t nil 1))
14108 ((not off) (org-move-to-column cc t) (insert ":")))
14109 (forward-line 1)))
14110 (save-excursion
14111 (org-back-to-heading)
14112 (if (looking-at (concat outline-regexp
14113 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
14114 (replace-match "" t t nil 1)
14115 (if (looking-at outline-regexp)
14116 (progn
14117 (goto-char (match-end 0))
14118 (insert org-quote-string " "))))))))
14120 ;;;; Functions extending outline functionality
14122 (defun org-beginning-of-line (&optional arg)
14123 "Go to the beginning of the current line. If that is invisible, continue
14124 to a visible line beginning. This makes the function of C-a more intuitive.
14125 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
14126 first attempt, and only move to after the tags when the cursor is already
14127 beyond the end of the headline."
14128 (interactive "P")
14129 (let ((pos (point)) refpos)
14130 (beginning-of-line 1)
14131 (if (bobp)
14133 (backward-char 1)
14134 (if (org-invisible-p)
14135 (while (and (not (bobp)) (org-invisible-p))
14136 (backward-char 1)
14137 (beginning-of-line 1))
14138 (forward-char 1)))
14139 (when org-special-ctrl-a/e
14140 (cond
14141 ((and (looking-at org-complex-heading-regexp)
14142 (= (char-after (match-end 1)) ?\ ))
14143 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
14144 (point-at-eol)))
14145 (goto-char
14146 (if (eq org-special-ctrl-a/e t)
14147 (cond ((> pos refpos) refpos)
14148 ((= pos (point)) refpos)
14149 (t (point)))
14150 (cond ((> pos (point)) (point))
14151 ((not (eq last-command this-command)) (point))
14152 (t refpos)))))
14153 ((org-at-item-p)
14154 (goto-char
14155 (if (eq org-special-ctrl-a/e t)
14156 (cond ((> pos (match-end 4)) (match-end 4))
14157 ((= pos (point)) (match-end 4))
14158 (t (point)))
14159 (cond ((> pos (point)) (point))
14160 ((not (eq last-command this-command)) (point))
14161 (t (match-end 4))))))))
14162 (org-no-warnings
14163 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
14165 (defun org-end-of-line (&optional arg)
14166 "Go to the end of the line.
14167 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
14168 first attempt, and only move to after the tags when the cursor is already
14169 beyond the end of the headline."
14170 (interactive "P")
14171 (if (or (not org-special-ctrl-a/e)
14172 (not (org-on-heading-p)))
14173 (end-of-line arg)
14174 (let ((pos (point)))
14175 (beginning-of-line 1)
14176 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
14177 (if (eq org-special-ctrl-a/e t)
14178 (if (or (< pos (match-beginning 1))
14179 (= pos (match-end 0)))
14180 (goto-char (match-beginning 1))
14181 (goto-char (match-end 0)))
14182 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
14183 (goto-char (match-end 0))
14184 (goto-char (match-beginning 1))))
14185 (end-of-line arg))))
14186 (org-no-warnings
14187 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
14190 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
14191 (define-key org-mode-map "\C-e" 'org-end-of-line)
14193 (defun org-kill-line (&optional arg)
14194 "Kill line, to tags or end of line."
14195 (interactive "P")
14196 (cond
14197 ((or (not org-special-ctrl-k)
14198 (bolp)
14199 (not (org-on-heading-p)))
14200 (call-interactively 'kill-line))
14201 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
14202 (kill-region (point) (match-beginning 1))
14203 (org-set-tags nil t))
14204 (t (kill-region (point) (point-at-eol)))))
14206 (define-key org-mode-map "\C-k" 'org-kill-line)
14208 (defun org-yank (&optional arg)
14209 "Yank. If the kill is a subtree, treat it specially.
14210 This command will look at the current kill and check if is a single
14211 subtree, or a series of subtrees[1]. If it passes the test, and if the
14212 cursor is at the beginning of a line or after the stars of a currently
14213 empty headline, then the yank is handeled specially. How exactly depends
14214 on the value of the following variables, both set by default.
14216 org-yank-folded-subtrees
14217 When set, the subree(s) will be folded after insertion, but only
14218 if doing so would now swallow text after the yanked text.
14220 org-yank-adjusted-subtrees
14221 When set, the subtree will be promoted or demoted in order to
14222 fit into the local outline tree structure, which means that the level
14223 will be adjusted so that it becomes the smaller one of the two
14224 *visible* surrounding headings.
14226 Any prefix to this command will cause `yank' to be called directly with
14227 no special treatment. In particular, a simple `C-u' prefix will just
14228 plainly yank the text as it is.
14230 \[1] Basically, the test checks if the first non-white line is a heading
14231 and if there are no other headings with fewer stars."
14232 (interactive "P")
14233 (setq this-command 'yank)
14234 (if arg
14235 (call-interactively 'yank)
14236 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
14237 (and (org-kill-is-subtree-p)
14238 (or (bolp)
14239 (and (looking-at "[ \t]*$")
14240 (string-match
14241 "\\`\\*+\\'"
14242 (buffer-substring (point-at-bol) (point)))))))
14243 swallowp)
14244 (cond
14245 ((and subtreep org-yank-folded-subtrees)
14246 (let ((beg (point))
14247 end)
14248 (if (and subtreep org-yank-adjusted-subtrees)
14249 (org-paste-subtree nil nil 'for-yank)
14250 (call-interactively 'yank))
14251 (setq end (point))
14252 (goto-char beg)
14253 (when (and (bolp) subtreep
14254 (not (setq swallowp
14255 (org-yank-folding-would-swallow-text beg end))))
14256 (or (looking-at outline-regexp)
14257 (re-search-forward (concat "^" outline-regexp) end t))
14258 (while (and (< (point) end) (looking-at outline-regexp))
14259 (hide-subtree)
14260 (org-cycle-show-empty-lines 'folded)
14261 (condition-case nil
14262 (outline-forward-same-level 1)
14263 (error (goto-char end)))))
14264 (when swallowp
14265 (message
14266 "Yanked text not folded because that would swallow text"))
14267 (goto-char end)
14268 (skip-chars-forward " \t\n\r")
14269 (beginning-of-line 1)
14270 (push-mark beg 'nomsg)))
14271 ((and subtreep org-yank-adjusted-subtrees)
14272 (let ((beg (point-at-bol)))
14273 (org-paste-subtree nil nil 'for-yank)
14274 (push-mark beg 'nomsg)))
14276 (call-interactively 'yank))))))
14278 (defun org-yank-folding-would-swallow-text (beg end)
14279 "Would hide-subtree at BEG swallow any text after END?"
14280 (let (level)
14281 (save-excursion
14282 (goto-char beg)
14283 (when (or (looking-at outline-regexp)
14284 (re-search-forward (concat "^" outline-regexp) end t))
14285 (setq level (org-outline-level)))
14286 (goto-char end)
14287 (skip-chars-forward " \t\r\n\v\f")
14288 (if (or (eobp)
14289 (and (bolp) (looking-at org-outline-regexp)
14290 (<= (org-outline-level) level)))
14291 nil ; Nothing would be swallowed
14292 t)))) ; something would swallow
14294 (define-key org-mode-map "\C-y" 'org-yank)
14296 (defun org-invisible-p ()
14297 "Check if point is at a character currently not visible."
14298 ;; Early versions of noutline don't have `outline-invisible-p'.
14299 (if (fboundp 'outline-invisible-p)
14300 (outline-invisible-p)
14301 (get-char-property (point) 'invisible)))
14303 (defun org-invisible-p2 ()
14304 "Check if point is at a character currently not visible."
14305 (save-excursion
14306 (if (and (eolp) (not (bobp))) (backward-char 1))
14307 ;; Early versions of noutline don't have `outline-invisible-p'.
14308 (if (fboundp 'outline-invisible-p)
14309 (outline-invisible-p)
14310 (get-char-property (point) 'invisible))))
14312 (defun org-back-to-heading (&optional invisible-ok)
14313 "Call `outline-back-to-heading', but provide a better error message."
14314 (condition-case nil
14315 (outline-back-to-heading invisible-ok)
14316 (error (error "Before first headline at position %d in buffer %s"
14317 (point) (current-buffer)))))
14319 (defun org-before-first-heading-p ()
14320 "Before first heading?"
14321 (save-excursion
14322 (null (re-search-backward "^\\*+ " nil t))))
14324 (defalias 'org-on-heading-p 'outline-on-heading-p)
14325 (defalias 'org-at-heading-p 'outline-on-heading-p)
14326 (defun org-at-heading-or-item-p ()
14327 (or (org-on-heading-p) (org-at-item-p)))
14329 (defun org-on-target-p ()
14330 (or (org-in-regexp org-radio-target-regexp)
14331 (org-in-regexp org-target-regexp)))
14333 (defun org-up-heading-all (arg)
14334 "Move to the heading line of which the present line is a subheading.
14335 This function considers both visible and invisible heading lines.
14336 With argument, move up ARG levels."
14337 (if (fboundp 'outline-up-heading-all)
14338 (outline-up-heading-all arg) ; emacs 21 version of outline.el
14339 (outline-up-heading arg t))) ; emacs 22 version of outline.el
14341 (defun org-up-heading-safe ()
14342 "Move to the heading line of which the present line is a subheading.
14343 This version will not throw an error. It will return the level of the
14344 headline found, or nil if no higher level is found."
14345 (let ((pos (point)) start-level level
14346 (re (concat "^" outline-regexp)))
14347 (catch 'exit
14348 (org-back-to-heading t)
14349 (setq start-level (funcall outline-level))
14350 (if (equal start-level 1) (throw 'exit nil))
14351 (while (re-search-backward re nil t)
14352 (setq level (funcall outline-level))
14353 (if (< level start-level) (throw 'exit level)))
14354 nil)))
14356 (defun org-first-sibling-p ()
14357 "Is this heading the first child of its parents?"
14358 (interactive)
14359 (let ((re (concat "^" outline-regexp))
14360 level l)
14361 (unless (org-at-heading-p t)
14362 (error "Not at a heading"))
14363 (setq level (funcall outline-level))
14364 (save-excursion
14365 (if (not (re-search-backward re nil t))
14367 (setq l (funcall outline-level))
14368 (< l level)))))
14370 (defun org-goto-sibling (&optional previous)
14371 "Goto the next sibling, even if it is invisible.
14372 When PREVIOUS is set, go to the previous sibling instead. Returns t
14373 when a sibling was found. When none is found, return nil and don't
14374 move point."
14375 (let ((fun (if previous 're-search-backward 're-search-forward))
14376 (pos (point))
14377 (re (concat "^" outline-regexp))
14378 level l)
14379 (when (condition-case nil (org-back-to-heading t) (error nil))
14380 (setq level (funcall outline-level))
14381 (catch 'exit
14382 (or previous (forward-char 1))
14383 (while (funcall fun re nil t)
14384 (setq l (funcall outline-level))
14385 (when (< l level) (goto-char pos) (throw 'exit nil))
14386 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
14387 (goto-char pos)
14388 nil))))
14390 (defun org-show-siblings ()
14391 "Show all siblings of the current headline."
14392 (save-excursion
14393 (while (org-goto-sibling) (org-flag-heading nil)))
14394 (save-excursion
14395 (while (org-goto-sibling 'previous)
14396 (org-flag-heading nil))))
14398 (defun org-show-hidden-entry ()
14399 "Show an entry where even the heading is hidden."
14400 (save-excursion
14401 (org-show-entry)))
14403 (defun org-flag-heading (flag &optional entry)
14404 "Flag the current heading. FLAG non-nil means make invisible.
14405 When ENTRY is non-nil, show the entire entry."
14406 (save-excursion
14407 (org-back-to-heading t)
14408 ;; Check if we should show the entire entry
14409 (if entry
14410 (progn
14411 (org-show-entry)
14412 (save-excursion
14413 (and (outline-next-heading)
14414 (org-flag-heading nil))))
14415 (outline-flag-region (max (point-min) (1- (point)))
14416 (save-excursion (outline-end-of-heading) (point))
14417 flag))))
14419 (defun org-forward-same-level (arg)
14420 "Move forward to the ARG'th subheading at same level as this one.
14421 Stop at the first and last subheadings of a superior heading.
14422 This is like outline-forward-same-level, but invisible headings are ok."
14423 (interactive "p")
14424 (org-back-to-heading t)
14425 (while (> arg 0)
14426 (let ((point-to-move-to (save-excursion
14427 (org-get-next-sibling))))
14428 (if point-to-move-to
14429 (progn
14430 (goto-char point-to-move-to)
14431 (setq arg (1- arg)))
14432 (progn
14433 (setq arg 0)
14434 (error "No following same-level heading"))))))
14436 (defun org-get-next-sibling ()
14437 "Move to next heading of the same level, and return point.
14438 If there is no such heading, return nil.
14439 This is like outline-next-sibling, but invisible headings are ok."
14440 (let ((level (funcall outline-level)))
14441 (outline-next-heading)
14442 (while (and (not (eobp)) (> (funcall outline-level) level))
14443 (outline-next-heading))
14444 (if (or (eobp) (< (funcall outline-level) level))
14446 (point))))
14448 (defun org-end-of-subtree (&optional invisible-OK to-heading)
14449 ;; This is an exact copy of the original function, but it uses
14450 ;; `org-back-to-heading', to make it work also in invisible
14451 ;; trees. And is uses an invisible-OK argument.
14452 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
14453 (org-back-to-heading invisible-OK)
14454 (let ((first t)
14455 (level (funcall outline-level)))
14456 (while (and (not (eobp))
14457 (or first (> (funcall outline-level) level)))
14458 (setq first nil)
14459 (outline-next-heading))
14460 (unless to-heading
14461 (if (memq (preceding-char) '(?\n ?\^M))
14462 (progn
14463 ;; Go to end of line before heading
14464 (forward-char -1)
14465 (if (memq (preceding-char) '(?\n ?\^M))
14466 ;; leave blank line before heading
14467 (forward-char -1))))))
14468 (point))
14470 (defun org-show-subtree ()
14471 "Show everything after this heading at deeper levels."
14472 (outline-flag-region
14473 (point)
14474 (save-excursion
14475 (outline-end-of-subtree) (outline-next-heading) (point))
14476 nil))
14478 (defun org-show-entry ()
14479 "Show the body directly following this heading.
14480 Show the heading too, if it is currently invisible."
14481 (interactive)
14482 (save-excursion
14483 (condition-case nil
14484 (progn
14485 (org-back-to-heading t)
14486 (outline-flag-region
14487 (max (point-min) (1- (point)))
14488 (save-excursion
14489 (re-search-forward
14490 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
14491 (or (match-beginning 1) (point-max)))
14492 nil))
14493 (error nil))))
14495 (defun org-make-options-regexp (kwds)
14496 "Make a regular expression for keyword lines."
14497 (concat
14499 "#?[ \t]*\\+\\("
14500 (mapconcat 'regexp-quote kwds "\\|")
14501 "\\):[ \t]*"
14502 "\\(.+\\)"))
14504 ;; Make isearch reveal the necessary context
14505 (defun org-isearch-end ()
14506 "Reveal context after isearch exits."
14507 (when isearch-success ; only if search was successful
14508 (if (featurep 'xemacs)
14509 ;; Under XEmacs, the hook is run in the correct place,
14510 ;; we directly show the context.
14511 (org-show-context 'isearch)
14512 ;; In Emacs the hook runs *before* restoring the overlays.
14513 ;; So we have to use a one-time post-command-hook to do this.
14514 ;; (Emacs 22 has a special variable, see function `org-mode')
14515 (unless (and (boundp 'isearch-mode-end-hook-quit)
14516 isearch-mode-end-hook-quit)
14517 ;; Only when the isearch was not quitted.
14518 (org-add-hook 'post-command-hook 'org-isearch-post-command
14519 'append 'local)))))
14521 (defun org-isearch-post-command ()
14522 "Remove self from hook, and show context."
14523 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
14524 (org-show-context 'isearch))
14527 ;;;; Integration with and fixes for other packages
14529 ;;; Imenu support
14531 (defvar org-imenu-markers nil
14532 "All markers currently used by Imenu.")
14533 (make-variable-buffer-local 'org-imenu-markers)
14535 (defun org-imenu-new-marker (&optional pos)
14536 "Return a new marker for use by Imenu, and remember the marker."
14537 (let ((m (make-marker)))
14538 (move-marker m (or pos (point)))
14539 (push m org-imenu-markers)
14542 (defun org-imenu-get-tree ()
14543 "Produce the index for Imenu."
14544 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
14545 (setq org-imenu-markers nil)
14546 (let* ((n org-imenu-depth)
14547 (re (concat "^" outline-regexp))
14548 (subs (make-vector (1+ n) nil))
14549 (last-level 0)
14550 m tree level head)
14551 (save-excursion
14552 (save-restriction
14553 (widen)
14554 (goto-char (point-max))
14555 (while (re-search-backward re nil t)
14556 (setq level (org-reduced-level (funcall outline-level)))
14557 (when (<= level n)
14558 (looking-at org-complex-heading-regexp)
14559 (setq head (org-link-display-format
14560 (org-match-string-no-properties 4))
14561 m (org-imenu-new-marker))
14562 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
14563 (if (>= level last-level)
14564 (push (cons head m) (aref subs level))
14565 (push (cons head (aref subs (1+ level))) (aref subs level))
14566 (loop for i from (1+ level) to n do (aset subs i nil)))
14567 (setq last-level level)))))
14568 (aref subs 1)))
14570 (eval-after-load "imenu"
14571 '(progn
14572 (add-hook 'imenu-after-jump-hook
14573 (lambda ()
14574 (if (eq major-mode 'org-mode)
14575 (org-show-context 'org-goto))))))
14577 (defun org-link-display-format (link)
14578 "Replace a link with either the description, or the link target
14579 if no description is present"
14580 (save-match-data
14581 (if (string-match org-bracket-link-analytic-regexp link)
14582 (replace-match (or (match-string 5 link)
14583 (concat (match-string 1 link)
14584 (match-string 3 link)))
14585 nil nil link)
14586 link)))
14588 ;; Speedbar support
14590 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
14591 "Overlay marking the agenda restriction line in speedbar.")
14592 (org-overlay-put org-speedbar-restriction-lock-overlay
14593 'face 'org-agenda-restriction-lock)
14594 (org-overlay-put org-speedbar-restriction-lock-overlay
14595 'help-echo "Agendas are currently limited to this item.")
14596 (org-detach-overlay org-speedbar-restriction-lock-overlay)
14598 (defun org-speedbar-set-agenda-restriction ()
14599 "Restrict future agenda commands to the location at point in speedbar.
14600 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
14601 (interactive)
14602 (require 'org-agenda)
14603 (let (p m tp np dir txt w)
14604 (cond
14605 ((setq p (text-property-any (point-at-bol) (point-at-eol)
14606 'org-imenu t))
14607 (setq m (get-text-property p 'org-imenu-marker))
14608 (save-excursion
14609 (save-restriction
14610 (set-buffer (marker-buffer m))
14611 (goto-char m)
14612 (org-agenda-set-restriction-lock 'subtree))))
14613 ((setq p (text-property-any (point-at-bol) (point-at-eol)
14614 'speedbar-function 'speedbar-find-file))
14615 (setq tp (previous-single-property-change
14616 (1+ p) 'speedbar-function)
14617 np (next-single-property-change
14618 tp 'speedbar-function)
14619 dir (speedbar-line-directory)
14620 txt (buffer-substring-no-properties (or tp (point-min))
14621 (or np (point-max))))
14622 (save-excursion
14623 (save-restriction
14624 (set-buffer (find-file-noselect
14625 (let ((default-directory dir))
14626 (expand-file-name txt))))
14627 (unless (org-mode-p)
14628 (error "Cannot restrict to non-Org-mode file"))
14629 (org-agenda-set-restriction-lock 'file))))
14630 (t (error "Don't know how to restrict Org-mode's agenda")))
14631 (org-move-overlay org-speedbar-restriction-lock-overlay
14632 (point-at-bol) (point-at-eol))
14633 (setq current-prefix-arg nil)
14634 (org-agenda-maybe-redo)))
14636 (eval-after-load "speedbar"
14637 '(progn
14638 (speedbar-add-supported-extension ".org")
14639 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
14640 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
14641 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
14642 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
14643 (add-hook 'speedbar-visiting-tag-hook
14644 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
14647 ;;; Fixes and Hacks for problems with other packages
14649 ;; Make flyspell not check words in links, to not mess up our keymap
14650 (defun org-mode-flyspell-verify ()
14651 "Don't let flyspell put overlays at active buttons."
14652 (not (get-text-property (point) 'keymap)))
14654 ;; Make `bookmark-jump' show the jump location if it was hidden.
14655 (eval-after-load "bookmark"
14656 '(if (boundp 'bookmark-after-jump-hook)
14657 ;; We can use the hook
14658 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
14659 ;; Hook not available, use advice
14660 (defadvice bookmark-jump (after org-make-visible activate)
14661 "Make the position visible."
14662 (org-bookmark-jump-unhide))))
14664 ;; Make sure saveplace show the location if it was hidden
14665 (eval-after-load "saveplace"
14666 '(defadvice save-place-find-file-hook (after org-make-visible activate)
14667 "Make the position visible."
14668 (org-bookmark-jump-unhide)))
14670 (defun org-bookmark-jump-unhide ()
14671 "Unhide the current position, to show the bookmark location."
14672 (and (org-mode-p)
14673 (or (org-invisible-p)
14674 (save-excursion (goto-char (max (point-min) (1- (point))))
14675 (org-invisible-p)))
14676 (org-show-context 'bookmark-jump)))
14678 ;; Make session.el ignore our circular variable
14679 (eval-after-load "session"
14680 '(add-to-list 'session-globals-exclude 'org-mark-ring))
14682 ;;;; Experimental code
14684 (defun org-closed-in-range ()
14685 "Sparse tree of items closed in a certain time range.
14686 Still experimental, may disappear in the future."
14687 (interactive)
14688 ;; Get the time interval from the user.
14689 (let* ((time1 (time-to-seconds
14690 (org-read-date nil 'to-time nil "Starting date: ")))
14691 (time2 (time-to-seconds
14692 (org-read-date nil 'to-time nil "End date:")))
14693 ;; callback function
14694 (callback (lambda ()
14695 (let ((time
14696 (time-to-seconds
14697 (apply 'encode-time
14698 (org-parse-time-string
14699 (match-string 1))))))
14700 ;; check if time in interval
14701 (and (>= time time1) (<= time time2))))))
14702 ;; make tree, check each match with the callback
14703 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
14706 ;;;; Finish up
14708 (provide 'org)
14710 (run-hooks 'org-load-hook)
14712 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
14714 ;;; org.el ends here