Release 6.18a
[org-mode.git] / lisp / org.el
blobe03255d0db1d3cdd1387700e902ffb98da49271a
1 ;;; org.el --- Outline-based notes management and organizer
2 ;; Carstens outline-mode for keeping track of everything.
3 ;; Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009 Free Software Foundation, Inc.
4 ;;
5 ;; Author: Carsten Dominik <carsten at orgmode dot org>
6 ;; Keywords: outlines, hypermedia, calendar, wp
7 ;; Homepage: http://orgmode.org
8 ;; Version: TAG=6.18a
9 ;;
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
24 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
26 ;;; Commentary:
28 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
29 ;; project planning with a fast and effective plain-text system.
31 ;; Org-mode develops organizational tasks around NOTES files that contain
32 ;; information about projects as plain text. Org-mode is implemented on
33 ;; top of outline-mode, which makes it possible to keep the content of
34 ;; large files well structured. Visibility cycling and structure editing
35 ;; help to work with the tree. Tables are easily created with a built-in
36 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
37 ;; and scheduling. It dynamically compiles entries into an agenda that
38 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
39 ;; Plain text URL-like links connect to websites, emails, Usenet
40 ;; messages, BBDB entries, and any files related to the projects. For
41 ;; printing and sharing of notes, an Org-mode file can be exported as a
42 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
43 ;; iCalendar file. It can also serve as a publishing tool for a set of
44 ;; linked webpages.
46 ;; Installation and Activation
47 ;; ---------------------------
48 ;; See the corresponding sections in the manual at
50 ;; http://orgmode.org/org.html#Installation
52 ;; Documentation
53 ;; -------------
54 ;; The documentation of Org-mode can be found in the TeXInfo file. The
55 ;; distribution also contains a PDF version of it. At the homepage of
56 ;; Org-mode, you can read the same text online as HTML. There is also an
57 ;; excellent reference card made by Philip Rooke. This card can be found
58 ;; in the etc/ directory of Emacs 22.
60 ;; A list of recent changes can be found at
61 ;; http://orgmode.org/Changes.html
63 ;;; Code:
65 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
66 (defvar org-table-formula-constants-local nil
67 "Local version of `org-table-formula-constants'.")
68 (make-variable-buffer-local 'org-table-formula-constants-local)
70 ;;;; Require other packages
72 (eval-when-compile
73 (require 'cl)
74 (require 'gnus-sum)
75 (require 'calendar))
76 ;; For XEmacs, noutline is not yet provided by outline.el, so arrange for
77 ;; the file noutline.el being loaded.
78 (if (featurep 'xemacs) (condition-case nil (require 'noutline)))
79 ;; We require noutline, which might be provided in outline.el
80 (require 'outline) (require 'noutline)
81 ;; Other stuff we need.
82 (require 'time-date)
83 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
84 (require 'easymenu)
86 (require 'org-macs)
87 (require 'org-compat)
88 (require 'org-faces)
89 (require 'org-list)
90 (require 'org-footnote)
92 ;;;; Customization variables
94 ;;; Version
96 (defconst org-version "TAG=6.18a"
97 "The version number of the file org.el.")
99 (defun org-version (&optional here)
100 "Show the org-mode version in the echo area.
101 With prefix arg HERE, insert it at point."
102 (interactive "P")
103 (let ((version (format "Org-mode version %s" org-version)))
104 (message version)
105 (if here
106 (insert version))))
108 ;;; Compatibility constants
110 ;;; The custom variables
112 (defgroup org nil
113 "Outline-based notes management and organizer."
114 :tag "Org"
115 :group 'outlines
116 :group 'hypermedia
117 :group 'calendar)
119 (defcustom org-load-hook nil
120 "Hook that is run after org.el has been loaded."
121 :group 'org
122 :type 'hook)
124 (defvar org-modules) ; defined below
125 (defvar org-modules-loaded nil
126 "Have the modules been loaded already?")
128 (defun org-load-modules-maybe (&optional force)
129 "Load all extensions listed in `org-modules'."
130 (when (or force (not org-modules-loaded))
131 (mapc (lambda (ext)
132 (condition-case nil (require ext)
133 (error (message "Problems while trying to load feature `%s'" ext))))
134 org-modules)
135 (setq org-modules-loaded t)))
137 (defun org-set-modules (var value)
138 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
139 (set var value)
140 (when (featurep 'org)
141 (org-load-modules-maybe 'force)))
143 (when (org-bound-and-true-p org-modules)
144 (let ((a (member 'org-infojs org-modules)))
145 (and a (setcar a 'org-jsinfo))))
147 (defcustom org-modules '(org-bbdb org-bibtex org-gnus org-info org-jsinfo org-irc org-mew org-mhe org-rmail org-vm org-w3m org-wl)
148 "Modules that should always be loaded together with org.el.
149 If a description starts with <C>, the file is not part of Emacs
150 and loading it will require that you have downloaded and properly installed
151 the org-mode distribution.
153 You can also use this system to load external packages (i.e. neither Org
154 core modules, not modules from the CONTRIB directory). Just add symbols
155 to the end of the list. If the package is called org-xyz.el, then you need
156 to add the symbol `xyz', and the package must have a call to
158 (provide 'org-xyz)"
159 :group 'org
160 :set 'org-set-modules
161 :type
162 '(set :greedy t
163 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
164 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
165 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
166 (const :tag " id: Global IDs for identifying entries" org-id)
167 (const :tag " info: Links to Info nodes" org-info)
168 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
169 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
170 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
171 (const :tag " mew Links to Mew folders/messages" org-mew)
172 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
173 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
174 (const :tag " vm: Links to VM folders/messages" org-vm)
175 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
176 (const :tag " w3m: Special cut/past from w3m to Org." org-w3m)
177 (const :tag " mouse: Additional mouse support" org-mouse)
179 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
180 (const :tag "C annotation-helper: Call Remember directly from Browser" org-annotation-helper)
181 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
182 (const :tag "C browser-url: Store link, directly from Browser" org-browser-url)
183 (const :tag "C depend: TODO dependencies for Org-mode" org-depend)
184 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
185 (const :tag "C eval: Include command output as text" org-eval)
186 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
187 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
188 (const :tag "C exp-blocks: Pre-process blocks for export" org-exp-blocks)
189 (const :tag "C interactive-query: Interactive modification of tags query" org-interactive-query)
190 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
191 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
192 (const :tag "C mtags: Support for muse-like tags" org-mtags)
193 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
194 (const :tag "C registry: A registry for Org links" org-registry)
195 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
196 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
197 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
198 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
199 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
202 (defgroup org-startup nil
203 "Options concerning startup of Org-mode."
204 :tag "Org Startup"
205 :group 'org)
207 (defcustom org-startup-folded t
208 "Non-nil means, entering Org-mode will switch to OVERVIEW.
209 This can also be configured on a per-file basis by adding one of
210 the following lines anywhere in the buffer:
212 #+STARTUP: fold
213 #+STARTUP: nofold
214 #+STARTUP: content"
215 :group 'org-startup
216 :type '(choice
217 (const :tag "nofold: show all" nil)
218 (const :tag "fold: overview" t)
219 (const :tag "content: all headlines" content)))
221 (defcustom org-startup-truncated t
222 "Non-nil means, entering Org-mode will set `truncate-lines'.
223 This is useful since some lines containing links can be very long and
224 uninteresting. Also tables look terrible when wrapped."
225 :group 'org-startup
226 :type 'boolean)
228 (defcustom org-startup-align-all-tables nil
229 "Non-nil means, align all tables when visiting a file.
230 This is useful when the column width in tables is forced with <N> cookies
231 in table fields. Such tables will look correct only after the first re-align.
232 This can also be configured on a per-file basis by adding one of
233 the following lines anywhere in the buffer:
234 #+STARTUP: align
235 #+STARTUP: noalign"
236 :group 'org-startup
237 :type 'boolean)
239 (defcustom org-insert-mode-line-in-empty-file nil
240 "Non-nil means insert the first line setting Org-mode in empty files.
241 When the function `org-mode' is called interactively in an empty file, this
242 normally means that the file name does not automatically trigger Org-mode.
243 To ensure that the file will always be in Org-mode in the future, a
244 line enforcing Org-mode will be inserted into the buffer, if this option
245 has been set."
246 :group 'org-startup
247 :type 'boolean)
249 (defcustom org-replace-disputed-keys nil
250 "Non-nil means use alternative key bindings for some keys.
251 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
252 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
253 If you want to use Org-mode together with one of these other modes,
254 or more generally if you would like to move some Org-mode commands to
255 other keys, set this variable and configure the keys with the variable
256 `org-disputed-keys'.
258 This option is only relevant at load-time of Org-mode, and must be set
259 *before* org.el is loaded. Changing it requires a restart of Emacs to
260 become effective."
261 :group 'org-startup
262 :type 'boolean)
264 (defcustom org-use-extra-keys nil
265 "Non-nil means use extra key sequence definitions for certain
266 commands. This happens automatically if you run XEmacs or if
267 window-system is nil. This variable lets you do the same
268 manually. You must set it before loading org.
270 Example: on Carbon Emacs 22 running graphically, with an external
271 keyboard on a Powerbook, the default way of setting M-left might
272 not work for either Alt or ESC. Setting this variable will make
273 it work for ESC."
274 :group 'org-startup
275 :type 'boolean)
277 (if (fboundp 'defvaralias)
278 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
280 (defcustom org-disputed-keys
281 '(([(shift up)] . [(meta p)])
282 ([(shift down)] . [(meta n)])
283 ([(shift left)] . [(meta -)])
284 ([(shift right)] . [(meta +)])
285 ([(control shift right)] . [(meta shift +)])
286 ([(control shift left)] . [(meta shift -)]))
287 "Keys for which Org-mode and other modes compete.
288 This is an alist, cars are the default keys, second element specifies
289 the alternative to use when `org-replace-disputed-keys' is t.
291 Keys can be specified in any syntax supported by `define-key'.
292 The value of this option takes effect only at Org-mode's startup,
293 therefore you'll have to restart Emacs to apply it after changing."
294 :group 'org-startup
295 :type 'alist)
297 (defun org-key (key)
298 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
299 Or return the original if not disputed."
300 (if org-replace-disputed-keys
301 (let* ((nkey (key-description key))
302 (x (org-find-if (lambda (x)
303 (equal (key-description (car x)) nkey))
304 org-disputed-keys)))
305 (if x (cdr x) key))
306 key))
308 (defun org-find-if (predicate seq)
309 (catch 'exit
310 (while seq
311 (if (funcall predicate (car seq))
312 (throw 'exit (car seq))
313 (pop seq)))))
315 (defun org-defkey (keymap key def)
316 "Define a key, possibly translated, as returned by `org-key'."
317 (define-key keymap (org-key key) def))
319 (defcustom org-ellipsis nil
320 "The ellipsis to use in the Org-mode outline.
321 When nil, just use the standard three dots. When a string, use that instead,
322 When a face, use the standard 3 dots, but with the specified face.
323 The change affects only Org-mode (which will then use its own display table).
324 Changing this requires executing `M-x org-mode' in a buffer to become
325 effective."
326 :group 'org-startup
327 :type '(choice (const :tag "Default" nil)
328 (face :tag "Face" :value org-warning)
329 (string :tag "String" :value "...#")))
331 (defvar org-display-table nil
332 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
334 (defgroup org-keywords nil
335 "Keywords in Org-mode."
336 :tag "Org Keywords"
337 :group 'org)
339 (defcustom org-deadline-string "DEADLINE:"
340 "String to mark deadline entries.
341 A deadline is this string, followed by a time stamp. Should be a word,
342 terminated by a colon. You can insert a schedule keyword and
343 a timestamp with \\[org-deadline].
344 Changes become only effective after restarting Emacs."
345 :group 'org-keywords
346 :type 'string)
348 (defcustom org-scheduled-string "SCHEDULED:"
349 "String to mark scheduled TODO entries.
350 A schedule is this string, followed by a time stamp. Should be a word,
351 terminated by a colon. You can insert a schedule keyword and
352 a timestamp with \\[org-schedule].
353 Changes become only effective after restarting Emacs."
354 :group 'org-keywords
355 :type 'string)
357 (defcustom org-closed-string "CLOSED:"
358 "String used as the prefix for timestamps logging closing a TODO entry."
359 :group 'org-keywords
360 :type 'string)
362 (defcustom org-clock-string "CLOCK:"
363 "String used as prefix for timestamps clocking work hours on an item."
364 :group 'org-keywords
365 :type 'string)
367 (defcustom org-comment-string "COMMENT"
368 "Entries starting with this keyword will never be exported.
369 An entry can be toggled between COMMENT and normal with
370 \\[org-toggle-comment].
371 Changes become only effective after restarting Emacs."
372 :group 'org-keywords
373 :type 'string)
375 (defcustom org-quote-string "QUOTE"
376 "Entries starting with this keyword will be exported in fixed-width font.
377 Quoting applies only to the text in the entry following the headline, and does
378 not extend beyond the next headline, even if that is lower level.
379 An entry can be toggled between QUOTE and normal with
380 \\[org-toggle-fixed-width-section]."
381 :group 'org-keywords
382 :type 'string)
384 (defconst org-repeat-re
385 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\([.+]?\\+[0-9]+[dwmy]\\)"
386 "Regular expression for specifying repeated events.
387 After a match, group 1 contains the repeat expression.")
389 (defgroup org-structure nil
390 "Options concerning the general structure of Org-mode files."
391 :tag "Org Structure"
392 :group 'org)
394 (defgroup org-reveal-location nil
395 "Options about how to make context of a location visible."
396 :tag "Org Reveal Location"
397 :group 'org-structure)
399 (defconst org-context-choice
400 '(choice
401 (const :tag "Always" t)
402 (const :tag "Never" nil)
403 (repeat :greedy t :tag "Individual contexts"
404 (cons
405 (choice :tag "Context"
406 (const agenda)
407 (const org-goto)
408 (const occur-tree)
409 (const tags-tree)
410 (const link-search)
411 (const mark-goto)
412 (const bookmark-jump)
413 (const isearch)
414 (const default))
415 (boolean))))
416 "Contexts for the reveal options.")
418 (defcustom org-show-hierarchy-above '((default . t))
419 "Non-nil means, show full hierarchy when revealing a location.
420 Org-mode often shows locations in an org-mode file which might have
421 been invisible before. When this is set, the hierarchy of headings
422 above the exposed location is shown.
423 Turning this off for example for sparse trees makes them very compact.
424 Instead of t, this can also be an alist specifying this option for different
425 contexts. Valid contexts are
426 agenda when exposing an entry from the agenda
427 org-goto when using the command `org-goto' on key C-c C-j
428 occur-tree when using the command `org-occur' on key C-c /
429 tags-tree when constructing a sparse tree based on tags matches
430 link-search when exposing search matches associated with a link
431 mark-goto when exposing the jump goal of a mark
432 bookmark-jump when exposing a bookmark location
433 isearch when exiting from an incremental search
434 default default for all contexts not set explicitly"
435 :group 'org-reveal-location
436 :type org-context-choice)
438 (defcustom org-show-following-heading '((default . nil))
439 "Non-nil means, show following heading when revealing a location.
440 Org-mode often shows locations in an org-mode file which might have
441 been invisible before. When this is set, the heading following the
442 match is shown.
443 Turning this off for example for sparse trees makes them very compact,
444 but makes it harder to edit the location of the match. In such a case,
445 use the command \\[org-reveal] to show more context.
446 Instead of t, this can also be an alist specifying this option for different
447 contexts. See `org-show-hierarchy-above' for valid contexts."
448 :group 'org-reveal-location
449 :type org-context-choice)
451 (defcustom org-show-siblings '((default . nil) (isearch t))
452 "Non-nil means, show all sibling heading when revealing a location.
453 Org-mode often shows locations in an org-mode file which might have
454 been invisible before. When this is set, the sibling of the current entry
455 heading are all made visible. If `org-show-hierarchy-above' is t,
456 the same happens on each level of the hierarchy above the current entry.
458 By default this is on for the isearch context, off for all other contexts.
459 Turning this off for example for sparse trees makes them very compact,
460 but makes it harder to edit the location of the match. In such a case,
461 use the command \\[org-reveal] to show more context.
462 Instead of t, this can also be an alist specifying this option for different
463 contexts. See `org-show-hierarchy-above' for valid contexts."
464 :group 'org-reveal-location
465 :type org-context-choice)
467 (defcustom org-show-entry-below '((default . nil))
468 "Non-nil means, show the entry below a headline when revealing a location.
469 Org-mode often shows locations in an org-mode file which might have
470 been invisible before. When this is set, the text below the headline that is
471 exposed is also shown.
473 By default this is off for all contexts.
474 Instead of t, this can also be an alist specifying this option for different
475 contexts. See `org-show-hierarchy-above' for valid contexts."
476 :group 'org-reveal-location
477 :type org-context-choice)
479 (defcustom org-indirect-buffer-display 'other-window
480 "How should indirect tree buffers be displayed?
481 This applies to indirect buffers created with the commands
482 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
483 Valid values are:
484 current-window Display in the current window
485 other-window Just display in another window.
486 dedicated-frame Create one new frame, and re-use it each time.
487 new-frame Make a new frame each time. Note that in this case
488 previously-made indirect buffers are kept, and you need to
489 kill these buffers yourself."
490 :group 'org-structure
491 :group 'org-agenda-windows
492 :type '(choice
493 (const :tag "In current window" current-window)
494 (const :tag "In current frame, other window" other-window)
495 (const :tag "Each time a new frame" new-frame)
496 (const :tag "One dedicated frame" dedicated-frame)))
498 (defgroup org-cycle nil
499 "Options concerning visibility cycling in Org-mode."
500 :tag "Org Cycle"
501 :group 'org-structure)
503 (defcustom org-drawers '("PROPERTIES" "CLOCK")
504 "Names of drawers. Drawers are not opened by cycling on the headline above.
505 Drawers only open with a TAB on the drawer line itself. A drawer looks like
506 this:
507 :DRAWERNAME:
508 .....
509 :END:
510 The drawer \"PROPERTIES\" is special for capturing properties through
511 the property API.
513 Drawers can be defined on the per-file basis with a line like:
515 #+DRAWERS: HIDDEN STATE PROPERTIES"
516 :group 'org-structure
517 :type '(repeat (string :tag "Drawer Name")))
519 (defcustom org-cycle-global-at-bob nil
520 "Cycle globally if cursor is at beginning of buffer and not at a headline.
521 This makes it possible to do global cycling without having to use S-TAB or
522 C-u TAB. For this special case to work, the first line of the buffer
523 must not be a headline - it may be empty ot some other text. When used in
524 this way, `org-cycle-hook' is disables temporarily, to make sure the
525 cursor stays at the beginning of the buffer.
526 When this option is nil, don't do anything special at the beginning
527 of the buffer."
528 :group 'org-cycle
529 :type 'boolean)
531 (defcustom org-cycle-emulate-tab t
532 "Where should `org-cycle' emulate TAB.
533 nil Never
534 white Only in completely white lines
535 whitestart Only at the beginning of lines, before the first non-white char
536 t Everywhere except in headlines
537 exc-hl-bol Everywhere except at the start of a headline
538 If TAB is used in a place where it does not emulate TAB, the current subtree
539 visibility is cycled."
540 :group 'org-cycle
541 :type '(choice (const :tag "Never" nil)
542 (const :tag "Only in completely white lines" white)
543 (const :tag "Before first char in a line" whitestart)
544 (const :tag "Everywhere except in headlines" t)
545 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
548 (defcustom org-cycle-separator-lines 2
549 "Number of empty lines needed to keep an empty line between collapsed trees.
550 If you leave an empty line between the end of a subtree and the following
551 headline, this empty line is hidden when the subtree is folded.
552 Org-mode will leave (exactly) one empty line visible if the number of
553 empty lines is equal or larger to the number given in this variable.
554 So the default 2 means, at least 2 empty lines after the end of a subtree
555 are needed to produce free space between a collapsed subtree and the
556 following headline.
558 Special case: when 0, never leave empty lines in collapsed view."
559 :group 'org-cycle
560 :type 'integer)
561 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
563 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
564 org-cycle-hide-drawers
565 org-cycle-show-empty-lines
566 org-optimize-window-after-visibility-change)
567 "Hook that is run after `org-cycle' has changed the buffer visibility.
568 The function(s) in this hook must accept a single argument which indicates
569 the new state that was set by the most recent `org-cycle' command. The
570 argument is a symbol. After a global state change, it can have the values
571 `overview', `content', or `all'. After a local state change, it can have
572 the values `folded', `children', or `subtree'."
573 :group 'org-cycle
574 :type 'hook)
576 (defgroup org-edit-structure nil
577 "Options concerning structure editing in Org-mode."
578 :tag "Org Edit Structure"
579 :group 'org-structure)
581 (defcustom org-odd-levels-only nil
582 "Non-nil means, skip even levels and only use odd levels for the outline.
583 This has the effect that two stars are being added/taken away in
584 promotion/demotion commands. It also influences how levels are
585 handled by the exporters.
586 Changing it requires restart of `font-lock-mode' to become effective
587 for fontification also in regions already fontified.
588 You may also set this on a per-file basis by adding one of the following
589 lines to the buffer:
591 #+STARTUP: odd
592 #+STARTUP: oddeven"
593 :group 'org-edit-structure
594 :group 'org-font-lock
595 :type 'boolean)
597 (defcustom org-adapt-indentation t
598 "Non-nil means, adapt indentation when promoting and demoting.
599 When this is set and the *entire* text in an entry is indented, the
600 indentation is increased by one space in a demotion command, and
601 decreased by one in a promotion command. If any line in the entry
602 body starts at column 0, indentation is not changed at all."
603 :group 'org-edit-structure
604 :type 'boolean)
606 (defcustom org-special-ctrl-a/e nil
607 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
608 When t, `C-a' will bring back the cursor to the beginning of the
609 headline text, i.e. after the stars and after a possible TODO keyword.
610 In an item, this will be the position after the bullet.
611 When the cursor is already at that position, another `C-a' will bring
612 it to the beginning of the line.
613 `C-e' will jump to the end of the headline, ignoring the presence of tags
614 in the headline. A second `C-e' will then jump to the true end of the
615 line, after any tags.
616 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
617 and only a directly following, identical keypress will bring the cursor
618 to the special positions."
619 :group 'org-edit-structure
620 :type '(choice
621 (const :tag "off" nil)
622 (const :tag "after bullet first" t)
623 (const :tag "border first" reversed)))
625 (if (fboundp 'defvaralias)
626 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
628 (defcustom org-special-ctrl-k nil
629 "Non-nil means `C-k' will behave specially in headlines.
630 When nil, `C-k' will call the default `kill-line' command.
631 When t, the following will happen while the cursor is in the headline:
633 - When the cursor is at the beginning of a headline, kill the entire
634 line and possible the folded subtree below the line.
635 - When in the middle of the headline text, kill the headline up to the tags.
636 - When after the headline text, kill the tags."
637 :group 'org-edit-structure
638 :type 'boolean)
640 (defcustom org-yank-folded-subtrees t
641 "Non-nil means, when yanking subtrees, fold them.
642 If the kill is a single subtree, or a sequence of subtrees, i.e. if
643 it starts with a heading and all other headings in it are either children
644 or siblings, then fold all the subtrees. However, do this only if no
645 text after the yank would be swallowed into a folded tree by this action."
646 :group 'org-edit-structure
647 :type 'boolean)
649 (defcustom org-yank-adjusted-subtrees t
650 "Non-nil means, when yanking subtrees, adjust the level.
651 With this setting, `org-paste-subtree' is used to insert the subtree, see
652 this function for details."
653 :group 'org-edit-structure
654 :type 'boolean)
656 (defcustom org-M-RET-may-split-line '((default . t))
657 "Non-nil means, M-RET will split the line at the cursor position.
658 When nil, it will go to the end of the line before making a
659 new line.
660 You may also set this option in a different way for different
661 contexts. Valid contexts are:
663 headline when creating a new headline
664 item when creating a new item
665 table in a table field
666 default the value to be used for all contexts not explicitly
667 customized"
668 :group 'org-structure
669 :group 'org-table
670 :type '(choice
671 (const :tag "Always" t)
672 (const :tag "Never" nil)
673 (repeat :greedy t :tag "Individual contexts"
674 (cons
675 (choice :tag "Context"
676 (const headline)
677 (const item)
678 (const table)
679 (const default))
680 (boolean)))))
683 (defcustom org-insert-heading-respect-content nil
684 "Non-nil means, insert new headings after the current subtree.
685 When nil, the new heading is created directly after the current line.
686 The commands \\[org-insert-heading-respect-content] and
687 \\[org-insert-todo-heading-respect-content] turn this variable on
688 for the duration of the command."
689 :group 'org-structure
690 :type 'boolean)
692 (defcustom org-blank-before-new-entry '((heading . auto)
693 (plain-list-item . auto))
694 "Should `org-insert-heading' leave a blank line before new heading/item?
695 The value is an alist, with `heading' and `plain-list-item' as car,
696 and a boolean flag as cdr."
697 :group 'org-edit-structure
698 :type '(list
699 (cons (const heading)
700 (choice (const :tag "Never" nil)
701 (const :tag "Always" t)
702 (const :tag "Auto" auto)))
703 (cons (const plain-list-item)
704 (choice (const :tag "Never" nil)
705 (const :tag "Always" t)
706 (const :tag "Auto" auto)))))
708 (defcustom org-insert-heading-hook nil
709 "Hook being run after inserting a new heading."
710 :group 'org-edit-structure
711 :type 'hook)
713 (defcustom org-enable-fixed-width-editor t
714 "Non-nil means, lines starting with \":\" are treated as fixed-width.
715 This currently only means, they are never auto-wrapped.
716 When nil, such lines will be treated like ordinary lines.
717 See also the QUOTE keyword."
718 :group 'org-edit-structure
719 :type 'boolean)
721 (defcustom org-edit-src-region-extra nil
722 "Additional regexps to identify regions for editing with `org-edit-src-code'.
723 For examples see the function `org-edit-src-find-region-and-lang'.
724 The regular expression identifying the begin marker should end with a newline,
725 and the regexp marking the end line should start with a newline, to make sure
726 there are kept outside the narrowed region."
727 :group 'org-edit-structure
728 :type '(repeat
729 (list
730 (regexp :tag "begin regexp")
731 (regexp :tag "end regexp")
732 (choice :tag "language"
733 (string :tag "specify")
734 (integer :tag "from match group")
735 (const :tag "from `lang' element")
736 (const :tag "from `style' element")))))
738 (defcustom org-coderef-label-format "(ref:%s)"
739 "The default coderef format.
740 This format string will be used to search for coderef labels in literal
741 examples (EXAMPLE and SRC blocks). The format can be overwritten
742 an individual literal example with the -f option, like
744 #+BEGIN_SRC pascal +n -r -l \"((%s))\"
746 #+END_SRC
748 If you want to use this for HTML export, make sure that the format does
749 not introduce special font-locking, and avoid the HTML special
750 characters `<', `>', and `&'. The reason for this restriction is that
751 the labels are searched for only after htmlize has done its job."
752 :group 'org-edit-structure ; FIXME this is not in the right group
753 :type 'string)
755 (defcustom org-edit-fixed-width-region-mode 'artist-mode
756 "The mode that should be used to edit fixed-width regions.
757 These are the regions where each line starts with a colon."
758 :group 'org-edit-structure
759 :type '(choice
760 (const artist-mode)
761 (const picture-mode)
762 (const fundamental-mode)
763 (function :tag "Other (specify)")))
765 (defcustom org-goto-auto-isearch t
766 "Non-nil means, typing characters in org-goto starts incremental search."
767 :group 'org-edit-structure
768 :type 'boolean)
770 (defgroup org-sparse-trees nil
771 "Options concerning sparse trees in Org-mode."
772 :tag "Org Sparse Trees"
773 :group 'org-structure)
775 (defcustom org-highlight-sparse-tree-matches t
776 "Non-nil means, highlight all matches that define a sparse tree.
777 The highlights will automatically disappear the next time the buffer is
778 changed by an edit command."
779 :group 'org-sparse-trees
780 :type 'boolean)
782 (defcustom org-remove-highlights-with-change t
783 "Non-nil means, any change to the buffer will remove temporary highlights.
784 Such highlights are created by `org-occur' and `org-clock-display'.
785 When nil, `C-c C-c needs to be used to get rid of the highlights.
786 The highlights created by `org-preview-latex-fragment' always need
787 `C-c C-c' to be removed."
788 :group 'org-sparse-trees
789 :group 'org-time
790 :type 'boolean)
793 (defcustom org-occur-hook '(org-first-headline-recenter)
794 "Hook that is run after `org-occur' has constructed a sparse tree.
795 This can be used to recenter the window to show as much of the structure
796 as possible."
797 :group 'org-sparse-trees
798 :type 'hook)
800 (defgroup org-imenu-and-speedbar nil
801 "Options concerning imenu and speedbar in Org-mode."
802 :tag "Org Imenu and Speedbar"
803 :group 'org-structure)
805 (defcustom org-imenu-depth 2
806 "The maximum level for Imenu access to Org-mode headlines.
807 This also applied for speedbar access."
808 :group 'org-imenu-and-speedbar
809 :type 'number)
811 (defgroup org-table nil
812 "Options concerning tables in Org-mode."
813 :tag "Org Table"
814 :group 'org)
816 (defcustom org-enable-table-editor 'optimized
817 "Non-nil means, lines starting with \"|\" are handled by the table editor.
818 When nil, such lines will be treated like ordinary lines.
820 When equal to the symbol `optimized', the table editor will be optimized to
821 do the following:
822 - Automatic overwrite mode in front of whitespace in table fields.
823 This makes the structure of the table stay in tact as long as the edited
824 field does not exceed the column width.
825 - Minimize the number of realigns. Normally, the table is aligned each time
826 TAB or RET are pressed to move to another field. With optimization this
827 happens only if changes to a field might have changed the column width.
828 Optimization requires replacing the functions `self-insert-command',
829 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
830 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
831 very good at guessing when a re-align will be necessary, but you can always
832 force one with \\[org-ctrl-c-ctrl-c].
834 If you would like to use the optimized version in Org-mode, but the
835 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
837 This variable can be used to turn on and off the table editor during a session,
838 but in order to toggle optimization, a restart is required.
840 See also the variable `org-table-auto-blank-field'."
841 :group 'org-table
842 :type '(choice
843 (const :tag "off" nil)
844 (const :tag "on" t)
845 (const :tag "on, optimized" optimized)))
847 (defcustom org-table-tab-recognizes-table.el t
848 "Non-nil means, TAB will automatically notice a table.el table.
849 When it sees such a table, it moves point into it and - if necessary -
850 calls `table-recognize-table'."
851 :group 'org-table-editing
852 :type 'boolean)
854 (defgroup org-link nil
855 "Options concerning links in Org-mode."
856 :tag "Org Link"
857 :group 'org)
859 (defvar org-link-abbrev-alist-local nil
860 "Buffer-local version of `org-link-abbrev-alist', which see.
861 The value of this is taken from the #+LINK lines.")
862 (make-variable-buffer-local 'org-link-abbrev-alist-local)
864 (defcustom org-link-abbrev-alist nil
865 "Alist of link abbreviations.
866 The car of each element is a string, to be replaced at the start of a link.
867 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
868 links in Org-mode buffers can have an optional tag after a double colon, e.g.
870 [[linkkey:tag][description]]
872 If REPLACE is a string, the tag will simply be appended to create the link.
873 If the string contains \"%s\", the tag will be inserted there. Alternatively,
874 the placeholder \"%h\" will cause a url-encoded version of the tag to
875 be inserted at that point (see the function `url-hexify-string').
877 REPLACE may also be a function that will be called with the tag as the
878 only argument to create the link, which should be returned as a string.
880 See the manual for examples."
881 :group 'org-link
882 :type '(repeat
883 (cons
884 (string :tag "Protocol")
885 (choice
886 (string :tag "Format")
887 (function)))))
889 (defcustom org-descriptive-links t
890 "Non-nil means, hide link part and only show description of bracket links.
891 Bracket links are like [[link][description]]. This variable sets the initial
892 state in new org-mode buffers. The setting can then be toggled on a
893 per-buffer basis from the Org->Hyperlinks menu."
894 :group 'org-link
895 :type 'boolean)
897 (defcustom org-link-file-path-type 'adaptive
898 "How the path name in file links should be stored.
899 Valid values are:
901 relative Relative to the current directory, i.e. the directory of the file
902 into which the link is being inserted.
903 absolute Absolute path, if possible with ~ for home directory.
904 noabbrev Absolute path, no abbreviation of home directory.
905 adaptive Use relative path for files in the current directory and sub-
906 directories of it. For other files, use an absolute path."
907 :group 'org-link
908 :type '(choice
909 (const relative)
910 (const absolute)
911 (const noabbrev)
912 (const adaptive)))
914 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
915 "Types of links that should be activated in Org-mode files.
916 This is a list of symbols, each leading to the activation of a certain link
917 type. In principle, it does not hurt to turn on most link types - there may
918 be a small gain when turning off unused link types. The types are:
920 bracket The recommended [[link][description]] or [[link]] links with hiding.
921 angular Links in angular brackets that may contain whitespace like
922 <bbdb:Carsten Dominik>.
923 plain Plain links in normal text, no whitespace, like http://google.com.
924 radio Text that is matched by a radio target, see manual for details.
925 tag Tag settings in a headline (link to tag search).
926 date Time stamps (link to calendar).
927 footnote Footnote labels.
929 Changing this variable requires a restart of Emacs to become effective."
930 :group 'org-link
931 :type '(set :greedy t
932 (const :tag "Double bracket links (new style)" bracket)
933 (const :tag "Angular bracket links (old style)" angular)
934 (const :tag "Plain text links" plain)
935 (const :tag "Radio target matches" radio)
936 (const :tag "Tags" tag)
937 (const :tag "Timestamps" date)
938 (const :tag "Footnotes" footnote)))
940 (defcustom org-make-link-description-function nil
941 "Function to use to generate link descriptions from links. If
942 nil the link location will be used. This function must take two
943 parameters; the first is the link and the second the description
944 org-insert-link has generated, and should return the description
945 to use."
946 :group 'org-link
947 :type 'function)
949 (defgroup org-link-store nil
950 "Options concerning storing links in Org-mode."
951 :tag "Org Store Link"
952 :group 'org-link)
954 (defcustom org-email-link-description-format "Email %c: %.30s"
955 "Format of the description part of a link to an email or usenet message.
956 The following %-escapes will be replaced by corresponding information:
958 %F full \"From\" field
959 %f name, taken from \"From\" field, address if no name
960 %T full \"To\" field
961 %t first name in \"To\" field, address if no name
962 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
963 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
964 %s subject
965 %m message-id.
967 You may use normal field width specification between the % and the letter.
968 This is for example useful to limit the length of the subject.
970 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
971 :group 'org-link-store
972 :type 'string)
974 (defcustom org-from-is-user-regexp
975 (let (r1 r2)
976 (when (and user-mail-address (not (string= user-mail-address "")))
977 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
978 (when (and user-full-name (not (string= user-full-name "")))
979 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
980 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
981 "Regexp matched against the \"From:\" header of an email or usenet message.
982 It should match if the message is from the user him/herself."
983 :group 'org-link-store
984 :type 'regexp)
986 (defcustom org-link-to-org-use-id 'create-if-interactive
987 "Non-nil means, storing a link to an Org file will use entry IDs.
989 Note that before this variable is even considered, org-id must be loaded,
990 to please customize `org-modules' and turn it on.
992 The variable can have the following values:
994 t Create an ID if needed to make a link to the current entry.
996 create-if-interactive
997 If `org-store-link' is called directly (interactively, as a user
998 command), do create an ID to support the link. But when doing the
999 job for remember, only use the ID if it already exists. The
1000 purpose of this setting is to avoid proliferation of unwanted
1001 IDs, just because you happen to be in an Org file when you
1002 call `org-remember' that automatically and preemptively
1003 creates a link. If you do want to get an ID link in a remember
1004 template to an entry not having an ID, create it first by
1005 explicitly creating a link to it, using `C-c C-l' first.
1007 use-existing
1008 Use existing ID, do not create one.
1010 nil Never use an ID to make a link, instead link using a text search for
1011 the headline text."
1012 :group 'org-link-store
1013 :type '(choice
1014 (const :tag "Create ID to make link" t)
1015 (const :tag "Create if string link interactively"
1016 'create-if-interactive)
1017 (const :tag "Only use existing" 'use-existing)
1018 (const :tag "Do not use ID to create link" nil)))
1020 (defcustom org-context-in-file-links t
1021 "Non-nil means, file links from `org-store-link' contain context.
1022 A search string will be added to the file name with :: as separator and
1023 used to find the context when the link is activated by the command
1024 `org-open-at-point'.
1025 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1026 negates this setting for the duration of the command."
1027 :group 'org-link-store
1028 :type 'boolean)
1030 (defcustom org-keep-stored-link-after-insertion nil
1031 "Non-nil means, keep link in list for entire session.
1033 The command `org-store-link' adds a link pointing to the current
1034 location to an internal list. These links accumulate during a session.
1035 The command `org-insert-link' can be used to insert links into any
1036 Org-mode file (offering completion for all stored links). When this
1037 option is nil, every link which has been inserted once using \\[org-insert-link]
1038 will be removed from the list, to make completing the unused links
1039 more efficient."
1040 :group 'org-link-store
1041 :type 'boolean)
1043 (defgroup org-link-follow nil
1044 "Options concerning following links in Org-mode."
1045 :tag "Org Follow Link"
1046 :group 'org-link)
1048 (defcustom org-link-translation-function nil
1049 "Function to translate links with different syntax to Org syntax.
1050 This can be used to translate links created for example by the Planner
1051 or emacs-wiki packages to Org syntax.
1052 The function must accept two parameters, a TYPE containing the link
1053 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1054 which is everything after the link protocol. It should return a cons
1055 with possibly modified values of type and path.
1056 Org contains a function for this, so if you set this variable to
1057 `org-translate-link-from-planner', you should be able follow many
1058 links created by planner."
1059 :group 'org-link-follow
1060 :type 'function)
1062 (defcustom org-follow-link-hook nil
1063 "Hook that is run after a link has been followed."
1064 :group 'org-link-follow
1065 :type 'hook)
1067 (defcustom org-tab-follows-link nil
1068 "Non-nil means, on links TAB will follow the link.
1069 Needs to be set before org.el is loaded."
1070 :group 'org-link-follow
1071 :type 'boolean)
1073 (defcustom org-return-follows-link nil
1074 "Non-nil means, on links RET will follow the link.
1075 Needs to be set before org.el is loaded."
1076 :group 'org-link-follow
1077 :type 'boolean)
1079 (defcustom org-mouse-1-follows-link
1080 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1081 "Non-nil means, mouse-1 on a link will follow the link.
1082 A longer mouse click will still set point. Does not work on XEmacs.
1083 Needs to be set before org.el is loaded."
1084 :group 'org-link-follow
1085 :type 'boolean)
1087 (defcustom org-mark-ring-length 4
1088 "Number of different positions to be recorded in the ring
1089 Changing this requires a restart of Emacs to work correctly."
1090 :group 'org-link-follow
1091 :type 'integer)
1093 (defcustom org-link-frame-setup
1094 '((vm . vm-visit-folder-other-frame)
1095 (gnus . gnus-other-frame)
1096 (file . find-file-other-window))
1097 "Setup the frame configuration for following links.
1098 When following a link with Emacs, it may often be useful to display
1099 this link in another window or frame. This variable can be used to
1100 set this up for the different types of links.
1101 For VM, use any of
1102 `vm-visit-folder'
1103 `vm-visit-folder-other-frame'
1104 For Gnus, use any of
1105 `gnus'
1106 `gnus-other-frame'
1107 `org-gnus-no-new-news'
1108 For FILE, use any of
1109 `find-file'
1110 `find-file-other-window'
1111 `find-file-other-frame'
1112 For the calendar, use the variable `calendar-setup'.
1113 For BBDB, it is currently only possible to display the matches in
1114 another window."
1115 :group 'org-link-follow
1116 :type '(list
1117 (cons (const vm)
1118 (choice
1119 (const vm-visit-folder)
1120 (const vm-visit-folder-other-window)
1121 (const vm-visit-folder-other-frame)))
1122 (cons (const gnus)
1123 (choice
1124 (const gnus)
1125 (const gnus-other-frame)
1126 (const org-gnus-no-new-news)))
1127 (cons (const file)
1128 (choice
1129 (const find-file)
1130 (const find-file-other-window)
1131 (const find-file-other-frame)))))
1133 (defcustom org-display-internal-link-with-indirect-buffer nil
1134 "Non-nil means, use indirect buffer to display infile links.
1135 Activating internal links (from one location in a file to another location
1136 in the same file) normally just jumps to the location. When the link is
1137 activated with a C-u prefix (or with mouse-3), the link is displayed in
1138 another window. When this option is set, the other window actually displays
1139 an indirect buffer clone of the current buffer, to avoid any visibility
1140 changes to the current buffer."
1141 :group 'org-link-follow
1142 :type 'boolean)
1144 (defcustom org-open-non-existing-files nil
1145 "Non-nil means, `org-open-file' will open non-existing files.
1146 When nil, an error will be generated."
1147 :group 'org-link-follow
1148 :type 'boolean)
1150 (defcustom org-open-directory-means-index-dot-org nil
1151 "Non-nil means, a link to a directory really means to index.org.
1152 When nil, following a directory link will run dired or open a finder/explorer
1153 window on that directory."
1154 :group 'org-link-follow
1155 :type 'boolean)
1157 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1158 "Function and arguments to call for following mailto links.
1159 This is a list with the first element being a lisp function, and the
1160 remaining elements being arguments to the function. In string arguments,
1161 %a will be replaced by the address, and %s will be replaced by the subject
1162 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1163 :group 'org-link-follow
1164 :type '(choice
1165 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1166 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1167 (const :tag "message-mail" (message-mail "%a" "%s"))
1168 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1170 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1171 "Non-nil means, ask for confirmation before executing shell links.
1172 Shell links can be dangerous: just think about a link
1174 [[shell:rm -rf ~/*][Google Search]]
1176 This link would show up in your Org-mode document as \"Google Search\",
1177 but really it would remove your entire home directory.
1178 Therefore we advise against setting this variable to nil.
1179 Just change it to `y-or-n-p' of you want to confirm with a
1180 single keystroke rather than having to type \"yes\"."
1181 :group 'org-link-follow
1182 :type '(choice
1183 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1184 (const :tag "with y-or-n (faster)" y-or-n-p)
1185 (const :tag "no confirmation (dangerous)" nil)))
1187 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1188 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1189 Elisp links can be dangerous: just think about a link
1191 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1193 This link would show up in your Org-mode document as \"Google Search\",
1194 but really it would remove your entire home directory.
1195 Therefore we advise against setting this variable to nil.
1196 Just change it to `y-or-n-p' of you want to confirm with a
1197 single keystroke rather than having to type \"yes\"."
1198 :group 'org-link-follow
1199 :type '(choice
1200 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1201 (const :tag "with y-or-n (faster)" y-or-n-p)
1202 (const :tag "no confirmation (dangerous)" nil)))
1204 (defconst org-file-apps-defaults-gnu
1205 '((remote . emacs)
1206 (system . mailcap)
1207 (t . mailcap))
1208 "Default file applications on a UNIX or GNU/Linux system.
1209 See `org-file-apps'.")
1211 (defconst org-file-apps-defaults-macosx
1212 '((remote . emacs)
1213 (t . "open %s")
1214 (system . "open %s")
1215 ("ps.gz" . "gv %s")
1216 ("eps.gz" . "gv %s")
1217 ("dvi" . "xdvi %s")
1218 ("fig" . "xfig %s"))
1219 "Default file applications on a MacOS X system.
1220 The system \"open\" is known as a default, but we use X11 applications
1221 for some files for which the OS does not have a good default.
1222 See `org-file-apps'.")
1224 (defconst org-file-apps-defaults-windowsnt
1225 (list
1226 '(remote . emacs)
1227 (cons t
1228 (list (if (featurep 'xemacs)
1229 'mswindows-shell-execute
1230 'w32-shell-execute)
1231 "open" 'file))
1232 (cons 'system
1233 (list (if (featurep 'xemacs)
1234 'mswindows-shell-execute
1235 'w32-shell-execute)
1236 "open" 'file)))
1237 "Default file applications on a Windows NT system.
1238 The system \"open\" is used for most files.
1239 See `org-file-apps'.")
1241 (defcustom org-file-apps
1243 (auto-mode . emacs)
1244 ("\\.x?html?\\'" . default)
1245 ("\\.pdf\\'" . default)
1247 "External applications for opening `file:path' items in a document.
1248 Org-mode uses system defaults for different file types, but
1249 you can use this variable to set the application for a given file
1250 extension. The entries in this list are cons cells where the car identifies
1251 files and the cdr the corresponding command. Possible values for the
1252 file identifier are
1253 \"regex\" Regular expression matched against the file name. For backward
1254 compatibility, this can also be a string with only alphanumeric
1255 characters, which is then interpreted as an extension.
1256 `directory' Matches a directory
1257 `remote' Matches a remote file, accessible through tramp or efs.
1258 Remote files most likely should be visited through Emacs
1259 because external applications cannot handle such paths.
1260 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1261 so all files Emacs knows how to handle. Using this with
1262 command `emacs' will open most files in Emacs. Beware that this
1263 will also open html files inside Emacs, unless you add
1264 (\"html\" . default) to the list as well.
1265 t Default for files not matched by any of the other options.
1266 `system' The system command to open files, like `open' on Windows
1267 and Mac OS X, and mailcap under GNU/Linux. This is the command
1268 that will be selected if you call `C-c C-o' with a double
1269 `C-u C-u' prefix.
1271 Possible values for the command are:
1272 `emacs' The file will be visited by the current Emacs process.
1273 `default' Use the default application for this file type, which is the
1274 association for t in the list, most likely in the system-specific
1275 part.
1276 This can be used to overrule an unwanted setting in the
1277 system-specific variable.
1278 `system' Use the system command for opening files, like \"open\".
1279 This command is specified by the entry whose car is `system'.
1280 Most likely, the system-specific version of this variable
1281 does define this command, but you can overrule/replace it
1282 here.
1283 string A command to be executed by a shell; %s will be replaced
1284 by the path to the file.
1285 sexp A Lisp form which will be evaluated. The file path will
1286 be available in the Lisp variable `file'.
1287 For more examples, see the system specific constants
1288 `org-file-apps-defaults-macosx'
1289 `org-file-apps-defaults-windowsnt'
1290 `org-file-apps-defaults-gnu'."
1291 :group 'org-link-follow
1292 :type '(repeat
1293 (cons (choice :value ""
1294 (string :tag "Extension")
1295 (const :tag "System command to open files" system)
1296 (const :tag "Default for unrecognized files" t)
1297 (const :tag "Remote file" remote)
1298 (const :tag "Links to a directory" directory)
1299 (const :tag "Any files that have Emacs modes"
1300 auto-mode))
1301 (choice :value ""
1302 (const :tag "Visit with Emacs" emacs)
1303 (const :tag "Use default" default)
1304 (const :tag "Use the system command" system)
1305 (string :tag "Command")
1306 (sexp :tag "Lisp form")))))
1308 (defgroup org-refile nil
1309 "Options concerning refiling entries in Org-mode."
1310 :tag "Org Refile"
1311 :group 'org)
1313 (defcustom org-directory "~/org"
1314 "Directory with org files.
1315 This directory will be used as default to prompt for org files.
1316 Used by the hooks for remember.el."
1317 :group 'org-refile
1318 :group 'org-remember
1319 :type 'directory)
1321 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1322 "Default target for storing notes.
1323 Used by the hooks for remember.el. This can be a string, or nil to mean
1324 the value of `remember-data-file'.
1325 You can set this on a per-template basis with the variable
1326 `org-remember-templates'."
1327 :group 'org-refile
1328 :group 'org-remember
1329 :type '(choice
1330 (const :tag "Default from remember-data-file" nil)
1331 file))
1333 (defcustom org-goto-interface 'outline
1334 "The default interface to be used for `org-goto'.
1335 Allowed values are:
1336 outline The interface shows an outline of the relevant file
1337 and the correct heading is found by moving through
1338 the outline or by searching with incremental search.
1339 outline-path-completion Headlines in the current buffer are offered via
1340 completion. This is the interface also used by
1341 the refile command."
1342 :group 'org-refile
1343 :type '(choice
1344 (const :tag "Outline" outline)
1345 (const :tag "Outline-path-completion" outline-path-completion)))
1347 (defcustom org-goto-max-level 5
1348 "Maximum level to be considered when running org-goto with refile interface."
1349 :group 'org-refile
1350 :type 'number)
1352 (defcustom org-reverse-note-order nil
1353 "Non-nil means, store new notes at the beginning of a file or entry.
1354 When nil, new notes will be filed to the end of a file or entry.
1355 This can also be a list with cons cells of regular expressions that
1356 are matched against file names, and values."
1357 :group 'org-remember
1358 :group 'org-refile
1359 :type '(choice
1360 (const :tag "Reverse always" t)
1361 (const :tag "Reverse never" nil)
1362 (repeat :tag "By file name regexp"
1363 (cons regexp boolean))))
1365 (defcustom org-refile-targets nil
1366 "Targets for refiling entries with \\[org-refile].
1367 This is list of cons cells. Each cell contains:
1368 - a specification of the files to be considered, either a list of files,
1369 or a symbol whose function or variable value will be used to retrieve
1370 a file name or a list of file names. If you use `org-agenda-files' for
1371 that, all agenda files will be scanned for targets. Nil means, consider
1372 headings in the current buffer.
1373 - A specification of how to select find candidate refile targets. This
1374 may be any of
1375 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1376 This tag has to be present in all target headlines, inheritance will
1377 not be considered.
1378 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1379 todo keyword.
1380 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1381 headlines that are refiling targets.
1382 - a cons cell (:level . N). Any headline of level N is considered a target.
1383 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1385 When this variable is nil, all top-level headlines in the current buffer
1386 are used, equivalent to the value `((nil . (:level . 1))'."
1387 :group 'org-refile
1388 :type '(repeat
1389 (cons
1390 (choice :value org-agenda-files
1391 (const :tag "All agenda files" org-agenda-files)
1392 (const :tag "Current buffer" nil)
1393 (function) (variable) (file))
1394 (choice :tag "Identify target headline by"
1395 (cons :tag "Specific tag" (const :value :tag) (string))
1396 (cons :tag "TODO keyword" (const :value :todo) (string))
1397 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1398 (cons :tag "Level number" (const :value :level) (integer))
1399 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1401 (defcustom org-refile-use-outline-path nil
1402 "Non-nil means, provide refile targets as paths.
1403 So a level 3 headline will be available as level1/level2/level3.
1404 When the value is `file', also include the file name (without directory)
1405 into the path. When `full-file-path', include the full file path."
1406 :group 'org-refile
1407 :type '(choice
1408 (const :tag "Not" nil)
1409 (const :tag "Yes" t)
1410 (const :tag "Start with file name" file)
1411 (const :tag "Start with full file path" full-file-path)))
1413 (defcustom org-outline-path-complete-in-steps t
1414 "Non-nil means, complete the outline path in hierarchical steps.
1415 When Org-mode uses the refile interface to select an outline path
1416 \(see variable `org-refile-use-outline-path'), the completion of
1417 the path can be done is a single go, or if can be done in steps down
1418 the headline hierarchy. Going in steps is probably the best if you
1419 do not use a special completion package like `ido' or `icicles'.
1420 However, when using these packages, going in one step can be very
1421 fast, while still showing the whole path to the entry."
1422 :group 'org-refile
1423 :type 'boolean)
1425 (defgroup org-todo nil
1426 "Options concerning TODO items in Org-mode."
1427 :tag "Org TODO"
1428 :group 'org)
1430 (defgroup org-progress nil
1431 "Options concerning Progress logging in Org-mode."
1432 :tag "Org Progress"
1433 :group 'org-time)
1435 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1436 "List of TODO entry keyword sequences and their interpretation.
1437 \\<org-mode-map>This is a list of sequences.
1439 Each sequence starts with a symbol, either `sequence' or `type',
1440 indicating if the keywords should be interpreted as a sequence of
1441 action steps, or as different types of TODO items. The first
1442 keywords are states requiring action - these states will select a headline
1443 for inclusion into the global TODO list Org-mode produces. If one of
1444 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1445 signify that no further action is necessary. If \"|\" is not found,
1446 the last keyword is treated as the only DONE state of the sequence.
1448 The command \\[org-todo] cycles an entry through these states, and one
1449 additional state where no keyword is present. For details about this
1450 cycling, see the manual.
1452 TODO keywords and interpretation can also be set on a per-file basis with
1453 the special #+SEQ_TODO and #+TYP_TODO lines.
1455 Each keyword can optionally specify a character for fast state selection
1456 \(in combination with the variable `org-use-fast-todo-selection')
1457 and specifiers for state change logging, using the same syntax
1458 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1459 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1460 indicates to record a time stamp each time this state is selected.
1462 Each keyword may also specify if a timestamp or a note should be
1463 recorded when entering or leaving the state, by adding additional
1464 characters in the parenthesis after the keyword. This looks like this:
1465 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1466 record only the time of the state change. With X and Y being either
1467 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1468 Y when leaving the state if and only if the *target* state does not
1469 define X. You may omit any of the fast-selection key or X or /Y,
1470 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1472 For backward compatibility, this variable may also be just a list
1473 of keywords - in this case the interpretation (sequence or type) will be
1474 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1475 :group 'org-todo
1476 :group 'org-keywords
1477 :type '(choice
1478 (repeat :tag "Old syntax, just keywords"
1479 (string :tag "Keyword"))
1480 (repeat :tag "New syntax"
1481 (cons
1482 (choice
1483 :tag "Interpretation"
1484 (const :tag "Sequence (cycling hits every state)" sequence)
1485 (const :tag "Type (cycling directly to DONE)" type))
1486 (repeat
1487 (string :tag "Keyword"))))))
1489 (defvar org-todo-keywords-1 nil
1490 "All TODO and DONE keywords active in a buffer.")
1491 (make-variable-buffer-local 'org-todo-keywords-1)
1492 (defvar org-todo-keywords-for-agenda nil)
1493 (defvar org-done-keywords-for-agenda nil)
1494 (defvar org-todo-keyword-alist-for-agenda nil)
1495 (defvar org-tag-alist-for-agenda nil)
1496 (defvar org-agenda-contributing-files nil)
1497 (defvar org-not-done-keywords nil)
1498 (make-variable-buffer-local 'org-not-done-keywords)
1499 (defvar org-done-keywords nil)
1500 (make-variable-buffer-local 'org-done-keywords)
1501 (defvar org-todo-heads nil)
1502 (make-variable-buffer-local 'org-todo-heads)
1503 (defvar org-todo-sets nil)
1504 (make-variable-buffer-local 'org-todo-sets)
1505 (defvar org-todo-log-states nil)
1506 (make-variable-buffer-local 'org-todo-log-states)
1507 (defvar org-todo-kwd-alist nil)
1508 (make-variable-buffer-local 'org-todo-kwd-alist)
1509 (defvar org-todo-key-alist nil)
1510 (make-variable-buffer-local 'org-todo-key-alist)
1511 (defvar org-todo-key-trigger nil)
1512 (make-variable-buffer-local 'org-todo-key-trigger)
1514 (defcustom org-todo-interpretation 'sequence
1515 "Controls how TODO keywords are interpreted.
1516 This variable is in principle obsolete and is only used for
1517 backward compatibility, if the interpretation of todo keywords is
1518 not given already in `org-todo-keywords'. See that variable for
1519 more information."
1520 :group 'org-todo
1521 :group 'org-keywords
1522 :type '(choice (const sequence)
1523 (const type)))
1525 (defcustom org-use-fast-todo-selection 'prefix
1526 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1527 This variable describes if and under what circumstances the cycling
1528 mechanism for TODO keywords will be replaced by a single-key, direct
1529 selection scheme.
1531 When nil, fast selection is never used.
1533 When the symbol `prefix', it will be used when `org-todo' is called with
1534 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1535 in an agenda buffer.
1537 When t, fast selection is used by default. In this case, the prefix
1538 argument forces cycling instead.
1540 In all cases, the special interface is only used if access keys have actually
1541 been assigned by the user, i.e. if keywords in the configuration are followed
1542 by a letter in parenthesis, like TODO(t)."
1543 :group 'org-todo
1544 :type '(choice
1545 (const :tag "Never" nil)
1546 (const :tag "By default" t)
1547 (const :tag "Only with C-u C-c C-t" prefix)))
1549 (defcustom org-provide-todo-statistics t
1550 "Non-nil means, update todo statistics after insert and toggle.
1551 When this is set, todo statistics is updated in the parent of the current
1552 entry each time a todo state is changed."
1553 :group 'org-todo
1554 :type 'boolean)
1556 (defcustom org-after-todo-state-change-hook nil
1557 "Hook which is run after the state of a TODO item was changed.
1558 The new state (a string with a TODO keyword, or nil) is available in the
1559 Lisp variable `state'."
1560 :group 'org-todo
1561 :type 'hook)
1563 (defcustom org-todo-state-tags-triggers nil
1564 "Tag changes that should be triggered by TODO state changes.
1565 This is a list. Each entry is
1567 (state-change (tag . flag) .......)
1569 State-change can be a string with a state, and empty string to indicate the
1570 state that has no TODO keyword, or it can be one of the symbols `todo'
1571 or `done', meaning any not-done or done state, respectively."
1572 :group 'org-todo
1573 :group 'org-tags
1574 :type '(repeat
1575 (cons (choice :tag "When changing to"
1576 (const :tag "Not-done state" todo)
1577 (const :tag "Done state" done)
1578 (string :tag "State"))
1579 (repeat
1580 (cons :tag "Tag action"
1581 (string :tag "Tag")
1582 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1584 (defcustom org-log-done nil
1585 "Information to record when a task moves to the DONE state.
1587 Possible values are:
1589 nil Don't add anything, just change the keyword
1590 time Add a time stamp to the task
1591 note Prompt a closing note and add it with template `org-log-note-headings'
1593 This option can also be set with on a per-file-basis with
1595 #+STARTUP: nologdone
1596 #+STARTUP: logdone
1597 #+STARTUP: lognotedone
1599 You can have local logging settings for a subtree by setting the LOGGING
1600 property to one or more of these keywords."
1601 :group 'org-todo
1602 :group 'org-progress
1603 :type '(choice
1604 (const :tag "No logging" nil)
1605 (const :tag "Record CLOSED timestamp" time)
1606 (const :tag "Record CLOSED timestamp with closing note." note)))
1608 ;; Normalize old uses of org-log-done.
1609 (cond
1610 ((eq org-log-done t) (setq org-log-done 'time))
1611 ((and (listp org-log-done) (memq 'done org-log-done))
1612 (setq org-log-done 'note)))
1614 (defcustom org-log-note-clock-out nil
1615 "Non-nil means, record a note when clocking out of an item.
1616 This can also be configured on a per-file basis by adding one of
1617 the following lines anywhere in the buffer:
1619 #+STARTUP: lognoteclock-out
1620 #+STARTUP: nolognoteclock-out"
1621 :group 'org-todo
1622 :group 'org-progress
1623 :type 'boolean)
1625 (defcustom org-log-done-with-time t
1626 "Non-nil means, the CLOSED time stamp will contain date and time.
1627 When nil, only the date will be recorded."
1628 :group 'org-progress
1629 :type 'boolean)
1631 (defcustom org-log-note-headings
1632 '((done . "CLOSING NOTE %t")
1633 (state . "State %-12s %t")
1634 (note . "Note taken on %t")
1635 (clock-out . ""))
1636 "Headings for notes added to entries.
1637 The value is an alist, with the car being a symbol indicating the note
1638 context, and the cdr is the heading to be used. The heading may also be the
1639 empty string.
1640 %t in the heading will be replaced by a time stamp.
1641 %s will be replaced by the new TODO state, in double quotes.
1642 %u will be replaced by the user name.
1643 %U will be replaced by the full user name."
1644 :group 'org-todo
1645 :group 'org-progress
1646 :type '(list :greedy t
1647 (cons (const :tag "Heading when closing an item" done) string)
1648 (cons (const :tag
1649 "Heading when changing todo state (todo sequence only)"
1650 state) string)
1651 (cons (const :tag "Heading when just taking a note" note) string)
1652 (cons (const :tag "Heading when clocking out" clock-out) string)))
1654 (unless (assq 'note org-log-note-headings)
1655 (push '(note . "%t") org-log-note-headings))
1657 (defcustom org-log-state-notes-insert-after-drawers nil
1658 "Non-nil means, insert state change notes after any drawers in entry.
1659 Only the drawers that *immediately* follow the headline and the
1660 deadline/scheduled line are skipped.
1661 When nil, insert notes right after the heading and perhaps the line
1662 with deadline/scheduling if present."
1663 :group 'org-todo
1664 :group 'org-progress
1665 :type 'boolean)
1667 (defcustom org-log-states-order-reversed t
1668 "Non-nil means, the latest state change note will be directly after heading.
1669 When nil, the notes will be orderer according to time."
1670 :group 'org-todo
1671 :group 'org-progress
1672 :type 'boolean)
1674 (defcustom org-log-repeat 'time
1675 "Non-nil means, record moving through the DONE state when triggering repeat.
1676 An auto-repeating tasks is immediately switched back to TODO when marked
1677 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1678 the TODO keyword definition, or recording a closing note by setting
1679 `org-log-done', there will be no record of the task moving through DONE.
1680 This variable forces taking a note anyway. Possible values are:
1682 nil Don't force a record
1683 time Record a time stamp
1684 note Record a note
1686 This option can also be set with on a per-file-basis with
1688 #+STARTUP: logrepeat
1689 #+STARTUP: lognoterepeat
1690 #+STARTUP: nologrepeat
1692 You can have local logging settings for a subtree by setting the LOGGING
1693 property to one or more of these keywords."
1694 :group 'org-todo
1695 :group 'org-progress
1696 :type '(choice
1697 (const :tag "Don't force a record" nil)
1698 (const :tag "Force recording the DONE state" time)
1699 (const :tag "Force recording a note with the DONE state" note)))
1702 (defgroup org-priorities nil
1703 "Priorities in Org-mode."
1704 :tag "Org Priorities"
1705 :group 'org-todo)
1707 (defcustom org-highest-priority ?A
1708 "The highest priority of TODO items. A character like ?A, ?B etc.
1709 Must have a smaller ASCII number than `org-lowest-priority'."
1710 :group 'org-priorities
1711 :type 'character)
1713 (defcustom org-lowest-priority ?C
1714 "The lowest priority of TODO items. A character like ?A, ?B etc.
1715 Must have a larger ASCII number than `org-highest-priority'."
1716 :group 'org-priorities
1717 :type 'character)
1719 (defcustom org-default-priority ?B
1720 "The default priority of TODO items.
1721 This is the priority an item get if no explicit priority is given."
1722 :group 'org-priorities
1723 :type 'character)
1725 (defcustom org-priority-start-cycle-with-default t
1726 "Non-nil means, start with default priority when starting to cycle.
1727 When this is nil, the first step in the cycle will be (depending on the
1728 command used) one higher or lower that the default priority."
1729 :group 'org-priorities
1730 :type 'boolean)
1732 (defgroup org-time nil
1733 "Options concerning time stamps and deadlines in Org-mode."
1734 :tag "Org Time"
1735 :group 'org)
1737 (defcustom org-insert-labeled-timestamps-at-point nil
1738 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1739 When nil, these labeled time stamps are forces into the second line of an
1740 entry, just after the headline. When scheduling from the global TODO list,
1741 the time stamp will always be forced into the second line."
1742 :group 'org-time
1743 :type 'boolean)
1745 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1746 "Formats for `format-time-string' which are used for time stamps.
1747 It is not recommended to change this constant.")
1749 (defcustom org-time-stamp-rounding-minutes '(0 5)
1750 "Number of minutes to round time stamps to.
1751 These are two values, the first applies when first creating a time stamp.
1752 The second applies when changing it with the commands `S-up' and `S-down'.
1753 When changing the time stamp, this means that it will change in steps
1754 of N minutes, as given by the second value.
1756 When a setting is 0 or 1, insert the time unmodified. Useful rounding
1757 numbers should be factors of 60, so for example 5, 10, 15.
1759 When this is larger than 1, you can still force an exact time-stamp by using
1760 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
1761 and by using a prefix arg to `S-up/down' to specify the exact number
1762 of minutes to shift."
1763 :group 'org-time
1764 :get '(lambda (var) ; Make sure all entries have 5 elements
1765 (if (integerp (default-value var))
1766 (list (default-value var) 5)
1767 (default-value var)))
1768 :type '(list
1769 (integer :tag "when inserting times")
1770 (integer :tag "when modifying times")))
1772 ;; Normalize old customizations of this variable.
1773 (when (integerp org-time-stamp-rounding-minutes)
1774 (setq org-time-stamp-rounding-minutes
1775 (list org-time-stamp-rounding-minutes
1776 org-time-stamp-rounding-minutes)))
1778 (defcustom org-display-custom-times nil
1779 "Non-nil means, overlay custom formats over all time stamps.
1780 The formats are defined through the variable `org-time-stamp-custom-formats'.
1781 To turn this on on a per-file basis, insert anywhere in the file:
1782 #+STARTUP: customtime"
1783 :group 'org-time
1784 :set 'set-default
1785 :type 'sexp)
1786 (make-variable-buffer-local 'org-display-custom-times)
1788 (defcustom org-time-stamp-custom-formats
1789 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1790 "Custom formats for time stamps. See `format-time-string' for the syntax.
1791 These are overlayed over the default ISO format if the variable
1792 `org-display-custom-times' is set. Time like %H:%M should be at the
1793 end of the second format."
1794 :group 'org-time
1795 :type 'sexp)
1797 (defun org-time-stamp-format (&optional long inactive)
1798 "Get the right format for a time string."
1799 (let ((f (if long (cdr org-time-stamp-formats)
1800 (car org-time-stamp-formats))))
1801 (if inactive
1802 (concat "[" (substring f 1 -1) "]")
1803 f)))
1805 (defcustom org-time-clocksum-format "%d:%02d"
1806 "The format string used when creating CLOCKSUM lines, or when
1807 org-mode generates a time duration."
1808 :group 'org-time
1809 :type 'string)
1811 (defcustom org-deadline-warning-days 14
1812 "No. of days before expiration during which a deadline becomes active.
1813 This variable governs the display in sparse trees and in the agenda.
1814 When 0 or negative, it means use this number (the absolute value of it)
1815 even if a deadline has a different individual lead time specified."
1816 :group 'org-time
1817 :group 'org-agenda-daily/weekly
1818 :type 'number)
1820 (defcustom org-read-date-prefer-future t
1821 "Non-nil means, assume future for incomplete date input from user.
1822 This affects the following situations:
1823 1. The user gives a day, but no month.
1824 For example, if today is the 15th, and you enter \"3\", Org-mode will
1825 read this as the third of *next* month. However, if you enter \"17\",
1826 it will be considered as *this* month.
1827 2. The user gives a month but not a year.
1828 For example, if it is april and you enter \"feb 2\", this will be read
1829 as feb 2, *next* year. \"May 5\", however, will be this year.
1831 Currently this does not work for ISO week specifications.
1833 When this option is nil, the current month and year will always be used
1834 as defaults."
1835 :group 'org-time
1836 :type 'boolean)
1838 (defcustom org-read-date-display-live t
1839 "Non-nil means, display current interpretation of date prompt live.
1840 This display will be in an overlay, in the minibuffer."
1841 :group 'org-time
1842 :type 'boolean)
1844 (defcustom org-read-date-popup-calendar t
1845 "Non-nil means, pop up a calendar when prompting for a date.
1846 In the calendar, the date can be selected with mouse-1. However, the
1847 minibuffer will also be active, and you can simply enter the date as well.
1848 When nil, only the minibuffer will be available."
1849 :group 'org-time
1850 :type 'boolean)
1851 (if (fboundp 'defvaralias)
1852 (defvaralias 'org-popup-calendar-for-date-prompt
1853 'org-read-date-popup-calendar))
1855 (defcustom org-extend-today-until 0
1856 "The hour when your day really ends. Must be an integer.
1857 This has influence for the following applications:
1858 - When switching the agenda to \"today\". It it is still earlier than
1859 the time given here, the day recognized as TODAY is actually yesterday.
1860 - When a date is read from the user and it is still before the time given
1861 here, the current date and time will be assumed to be yesterday, 23:59.
1862 Also, timestamps inserted in remember templates follow this rule.
1864 IMPORTANT: This is a feature whose implementation is and likely will
1865 remain incomplete. Really, it is only here because past midnight seems to
1866 be the favorite working time of John Wiegley :-)"
1867 :group 'org-time
1868 :type 'number)
1870 (defcustom org-edit-timestamp-down-means-later nil
1871 "Non-nil means, S-down will increase the time in a time stamp.
1872 When nil, S-up will increase."
1873 :group 'org-time
1874 :type 'boolean)
1876 (defcustom org-calendar-follow-timestamp-change t
1877 "Non-nil means, make the calendar window follow timestamp changes.
1878 When a timestamp is modified and the calendar window is visible, it will be
1879 moved to the new date."
1880 :group 'org-time
1881 :type 'boolean)
1883 (defgroup org-tags nil
1884 "Options concerning tags in Org-mode."
1885 :tag "Org Tags"
1886 :group 'org)
1888 (defcustom org-tag-alist nil
1889 "List of tags allowed in Org-mode files.
1890 When this list is nil, Org-mode will base TAG input on what is already in the
1891 buffer.
1892 The value of this variable is an alist, the car of each entry must be a
1893 keyword as a string, the cdr may be a character that is used to select
1894 that tag through the fast-tag-selection interface.
1895 See the manual for details."
1896 :group 'org-tags
1897 :type '(repeat
1898 (choice
1899 (cons (string :tag "Tag name")
1900 (character :tag "Access char"))
1901 (const :tag "Start radio group" (:startgroup))
1902 (const :tag "End radio group" (:endgroup)))))
1904 (defvar org-file-tags nil
1905 "List of tags that can be inherited by all entries in the file.
1906 The tags will be inherited if the variable `org-use-tag-inheritance'
1907 says they should be.
1908 This variable is populated from #+TAG lines.")
1910 (defcustom org-use-fast-tag-selection 'auto
1911 "Non-nil means, use fast tag selection scheme.
1912 This is a special interface to select and deselect tags with single keys.
1913 When nil, fast selection is never used.
1914 When the symbol `auto', fast selection is used if and only if selection
1915 characters for tags have been configured, either through the variable
1916 `org-tag-alist' or through a #+TAGS line in the buffer.
1917 When t, fast selection is always used and selection keys are assigned
1918 automatically if necessary."
1919 :group 'org-tags
1920 :type '(choice
1921 (const :tag "Always" t)
1922 (const :tag "Never" nil)
1923 (const :tag "When selection characters are configured" 'auto)))
1925 (defcustom org-fast-tag-selection-single-key nil
1926 "Non-nil means, fast tag selection exits after first change.
1927 When nil, you have to press RET to exit it.
1928 During fast tag selection, you can toggle this flag with `C-c'.
1929 This variable can also have the value `expert'. In this case, the window
1930 displaying the tags menu is not even shown, until you press C-c again."
1931 :group 'org-tags
1932 :type '(choice
1933 (const :tag "No" nil)
1934 (const :tag "Yes" t)
1935 (const :tag "Expert" expert)))
1937 (defvar org-fast-tag-selection-include-todo nil
1938 "Non-nil means, fast tags selection interface will also offer TODO states.
1939 This is an undocumented feature, you should not rely on it.")
1941 (defcustom org-tags-column (if (featurep 'xemacs) -79 -80)
1942 "The column to which tags should be indented in a headline.
1943 If this number is positive, it specifies the column. If it is negative,
1944 it means that the tags should be flushright to that column. For example,
1945 -80 works well for a normal 80 character screen."
1946 :group 'org-tags
1947 :type 'integer)
1949 (defcustom org-auto-align-tags t
1950 "Non-nil means, realign tags after pro/demotion of TODO state change.
1951 These operations change the length of a headline and therefore shift
1952 the tags around. With this options turned on, after each such operation
1953 the tags are again aligned to `org-tags-column'."
1954 :group 'org-tags
1955 :type 'boolean)
1957 (defcustom org-use-tag-inheritance t
1958 "Non-nil means, tags in levels apply also for sublevels.
1959 When nil, only the tags directly given in a specific line apply there.
1960 This may also be a list of tags that should be inherited, or a regexp that
1961 matches tags that should be inherited. Additional control is possible
1962 with the variable `org-tags-exclude-from-inheritance' which gives an
1963 explicit list of tags to be excluded from inheritance., even if the value of
1964 `org-use-tag-inheritance' would select it for inheritance.
1966 If this option is t, a match early-on in a tree can lead to a large
1967 number of matches in the subtree when constructing the agenda or creating
1968 a sparse tree. If you only want to see the first match in a tree during
1969 a search, check out the variable `org-tags-match-list-sublevels'."
1970 :group 'org-tags
1971 :type '(choice
1972 (const :tag "Not" nil)
1973 (const :tag "Always" t)
1974 (repeat :tag "Specific tags" (string :tag "Tag"))
1975 (regexp :tag "Tags matched by regexp")))
1977 (defcustom org-tags-exclude-from-inheritance nil
1978 "List of tags that should never be inherited.
1979 This is a way to exclude a few tags from inheritance. For way to do
1980 the opposite, to actively allow inheritance for selected tags,
1981 see the variable `org-use-tag-inheritance'."
1982 :group 'org-tags
1983 :type '(repeat (string :tag "Tag")))
1985 (defun org-tag-inherit-p (tag)
1986 "Check if TAG is one that should be inherited."
1987 (cond
1988 ((member tag org-tags-exclude-from-inheritance) nil)
1989 ((eq org-use-tag-inheritance t) t)
1990 ((not org-use-tag-inheritance) nil)
1991 ((stringp org-use-tag-inheritance)
1992 (string-match org-use-tag-inheritance tag))
1993 ((listp org-use-tag-inheritance)
1994 (member tag org-use-tag-inheritance))
1995 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
1997 (defcustom org-tags-match-list-sublevels t
1998 "Non-nil means list also sublevels of headlines matching tag search.
1999 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2000 the sublevels of a headline matching a tag search often also match
2001 the same search. Listing all of them can create very long lists.
2002 Setting this variable to nil causes subtrees of a match to be skipped.
2003 This option is off by default, because inheritance in on. If you turn
2004 inheritance off, you very likely want to turn this option on.
2006 As a special case, if the tag search is restricted to TODO items, the
2007 value of this variable is ignored and sublevels are always checked, to
2008 make sure all corresponding TODO items find their way into the list.
2010 This variable is semi-obsolete and probably should always be true. It
2011 is better to limit inheritance to certain tags using the variables
2012 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2013 :group 'org-tags
2014 :type 'boolean)
2016 (defvar org-tags-history nil
2017 "History of minibuffer reads for tags.")
2018 (defvar org-last-tags-completion-table nil
2019 "The last used completion table for tags.")
2020 (defvar org-after-tags-change-hook nil
2021 "Hook that is run after the tags in a line have changed.")
2023 (defgroup org-properties nil
2024 "Options concerning properties in Org-mode."
2025 :tag "Org Properties"
2026 :group 'org)
2028 (defcustom org-property-format "%-10s %s"
2029 "How property key/value pairs should be formatted by `indent-line'.
2030 When `indent-line' hits a property definition, it will format the line
2031 according to this format, mainly to make sure that the values are
2032 lined-up with respect to each other."
2033 :group 'org-properties
2034 :type 'string)
2036 (defcustom org-use-property-inheritance nil
2037 "Non-nil means, properties apply also for sublevels.
2039 This setting is chiefly used during property searches. Turning it on can
2040 cause significant overhead when doing a search, which is why it is not
2041 on by default.
2043 When nil, only the properties directly given in the current entry count.
2044 When t, every property is inherited. The value may also be a list of
2045 properties that should have inheritance, or a regular expression matching
2046 properties that should be inherited.
2048 However, note that some special properties use inheritance under special
2049 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2050 and the properties ending in \"_ALL\" when they are used as descriptor
2051 for valid values of a property.
2053 Note for programmers:
2054 When querying an entry with `org-entry-get', you can control if inheritance
2055 should be used. By default, `org-entry-get' looks only at the local
2056 properties. You can request inheritance by setting the inherit argument
2057 to t (to force inheritance) or to `selective' (to respect the setting
2058 in this variable)."
2059 :group 'org-properties
2060 :type '(choice
2061 (const :tag "Not" nil)
2062 (const :tag "Always" t)
2063 (repeat :tag "Specific properties" (string :tag "Property"))
2064 (regexp :tag "Properties matched by regexp")))
2066 (defun org-property-inherit-p (property)
2067 "Check if PROPERTY is one that should be inherited."
2068 (cond
2069 ((eq org-use-property-inheritance t) t)
2070 ((not org-use-property-inheritance) nil)
2071 ((stringp org-use-property-inheritance)
2072 (string-match org-use-property-inheritance property))
2073 ((listp org-use-property-inheritance)
2074 (member property org-use-property-inheritance))
2075 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2077 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2078 "The default column format, if no other format has been defined.
2079 This variable can be set on the per-file basis by inserting a line
2081 #+COLUMNS: %25ITEM ....."
2082 :group 'org-properties
2083 :type 'string)
2085 (defcustom org-columns-ellipses ".."
2086 "The ellipses to be used when a field in column view is truncated.
2087 When this is the empty string, as many characters as possible are shown,
2088 but then there will be no visual indication that the field has been truncated.
2089 When this is a string of length N, the last N characters of a truncated
2090 field are replaced by this string. If the column is narrower than the
2091 ellipses string, only part of the ellipses string will be shown."
2092 :group 'org-properties
2093 :type 'string)
2095 (defcustom org-columns-modify-value-for-display-function nil
2096 "Function that modifies values for display in column view.
2097 For example, it can be used to cut out a certain part from a time stamp.
2098 The function must take 2 arguments:
2100 column-title The title of the column (*not* the property name)
2101 value The value that should be modified.
2103 The function should return the value that should be displayed,
2104 or nil if the normal value should be used."
2105 :group 'org-properties
2106 :type 'function)
2108 (defcustom org-effort-property "Effort"
2109 "The property that is being used to keep track of effort estimates.
2110 Effort estimates given in this property need to have the format H:MM."
2111 :group 'org-properties
2112 :group 'org-progress
2113 :type '(string :tag "Property"))
2115 (defconst org-global-properties-fixed
2116 '(("VISIBILITY_ALL" . "folded children content all"))
2117 "List of property/value pairs that can be inherited by any entry.
2118 These are fixed values, for the preset properties.")
2121 (defcustom org-global-properties nil
2122 "List of property/value pairs that can be inherited by any entry.
2123 You can set buffer-local values for the same purpose in the variable
2124 `org-file-properties' this by adding lines like
2126 #+PROPERTY: NAME VALUE"
2127 :group 'org-properties
2128 :type '(repeat
2129 (cons (string :tag "Property")
2130 (string :tag "Value"))))
2132 (defvar org-file-properties nil
2133 "List of property/value pairs that can be inherited by any entry.
2134 Valid for the current buffer.
2135 This variable is populated from #+PROPERTY lines.")
2136 (make-variable-buffer-local 'org-file-properties)
2138 (defgroup org-agenda nil
2139 "Options concerning agenda views in Org-mode."
2140 :tag "Org Agenda"
2141 :group 'org)
2143 (defvar org-category nil
2144 "Variable used by org files to set a category for agenda display.
2145 Such files should use a file variable to set it, for example
2147 # -*- mode: org; org-category: \"ELisp\"
2149 or contain a special line
2151 #+CATEGORY: ELisp
2153 If the file does not specify a category, then file's base name
2154 is used instead.")
2155 (make-variable-buffer-local 'org-category)
2156 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2158 (defcustom org-agenda-files nil
2159 "The files to be used for agenda display.
2160 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2161 \\[org-remove-file]. You can also use customize to edit the list.
2163 If an entry is a directory, all files in that directory that are matched by
2164 `org-agenda-file-regexp' will be part of the file list.
2166 If the value of the variable is not a list but a single file name, then
2167 the list of agenda files is actually stored and maintained in that file, one
2168 agenda file per line."
2169 :group 'org-agenda
2170 :type '(choice
2171 (repeat :tag "List of files and directories" file)
2172 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2174 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2175 "Regular expression to match files for `org-agenda-files'.
2176 If any element in the list in that variable contains a directory instead
2177 of a normal file, all files in that directory that are matched by this
2178 regular expression will be included."
2179 :group 'org-agenda
2180 :type 'regexp)
2182 (defcustom org-agenda-text-search-extra-files nil
2183 "List of extra files to be searched by text search commands.
2184 These files will be search in addition to the agenda files by the
2185 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2186 Note that these files will only be searched for text search commands,
2187 not for the other agenda views like todo lists, tag searches or the weekly
2188 agenda. This variable is intended to list notes and possibly archive files
2189 that should also be searched by these two commands.
2190 In fact, if the first element in the list is the symbol `agenda-archives',
2191 than all archive files of all agenda files will be added to the search
2192 scope."
2193 :group 'org-agenda
2194 :type '(set :greedy t
2195 (const :tag "Agenda Archives" agenda-archives)
2196 (repeat :inline t (file))))
2198 (if (fboundp 'defvaralias)
2199 (defvaralias 'org-agenda-multi-occur-extra-files
2200 'org-agenda-text-search-extra-files))
2202 (defcustom org-agenda-skip-unavailable-files nil
2203 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2204 A nil value means to remove them, after a query, from the list."
2205 :group 'org-agenda
2206 :type 'boolean)
2208 (defcustom org-calendar-to-agenda-key [?c]
2209 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2210 The command `org-calendar-goto-agenda' will be bound to this key. The
2211 default is the character `c' because then `c' can be used to switch back and
2212 forth between agenda and calendar."
2213 :group 'org-agenda
2214 :type 'sexp)
2216 (defcustom org-calendar-agenda-action-key [?k]
2217 "The key to be installed in `calendar-mode-map' for agenda-action.
2218 The command `org-agenda-action' will be bound to this key. The
2219 default is the character `k' because we use the same key in the agenda."
2220 :group 'org-agenda
2221 :type 'sexp)
2223 (eval-after-load "calendar"
2224 '(progn
2225 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2226 'org-calendar-goto-agenda)
2227 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2228 'org-agenda-action)))
2230 (defgroup org-latex nil
2231 "Options for embedding LaTeX code into Org-mode."
2232 :tag "Org LaTeX"
2233 :group 'org)
2235 (defcustom org-format-latex-options
2236 '(:foreground default :background default :scale 1.0
2237 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2238 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
2239 "Options for creating images from LaTeX fragments.
2240 This is a property list with the following properties:
2241 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2242 `default' means use the foreground of the default face.
2243 :background the background color, or \"Transparent\".
2244 `default' means use the background of the default face.
2245 :scale a scaling factor for the size of the images.
2246 :html-foreground, :html-background, :html-scale
2247 the same numbers for HTML export.
2248 :matchers a list indicating which matchers should be used to
2249 find LaTeX fragments. Valid members of this list are:
2250 \"begin\" find environments
2251 \"$1\" find single characters surrounded by $.$
2252 \"$\" find math expressions surrounded by $...$
2253 \"$$\" find math expressions surrounded by $$....$$
2254 \"\\(\" find math expressions surrounded by \\(...\\)
2255 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2256 :group 'org-latex
2257 :type 'plist)
2259 (defcustom org-format-latex-header "\\documentclass{article}
2260 \\usepackage{fullpage} % do not remove
2261 \\usepackage{amssymb}
2262 \\usepackage[usenames]{color}
2263 \\usepackage{amsmath}
2264 \\usepackage{latexsym}
2265 \\usepackage[mathscr]{eucal}
2266 \\pagestyle{empty} % do not remove"
2267 "The document header used for processing LaTeX fragments."
2268 :group 'org-latex
2269 :type 'string)
2272 (defgroup org-font-lock nil
2273 "Font-lock settings for highlighting in Org-mode."
2274 :tag "Org Font Lock"
2275 :group 'org)
2277 (defcustom org-level-color-stars-only nil
2278 "Non-nil means fontify only the stars in each headline.
2279 When nil, the entire headline is fontified.
2280 Changing it requires restart of `font-lock-mode' to become effective
2281 also in regions already fontified."
2282 :group 'org-font-lock
2283 :type 'boolean)
2285 (defcustom org-hide-leading-stars nil
2286 "Non-nil means, hide the first N-1 stars in a headline.
2287 This works by using the face `org-hide' for these stars. This
2288 face is white for a light background, and black for a dark
2289 background. You may have to customize the face `org-hide' to
2290 make this work.
2291 Changing it requires restart of `font-lock-mode' to become effective
2292 also in regions already fontified.
2293 You may also set this on a per-file basis by adding one of the following
2294 lines to the buffer:
2296 #+STARTUP: hidestars
2297 #+STARTUP: showstars"
2298 :group 'org-font-lock
2299 :type 'boolean)
2301 (defcustom org-fontify-done-headline nil
2302 "Non-nil means, change the face of a headline if it is marked DONE.
2303 Normally, only the TODO/DONE keyword indicates the state of a headline.
2304 When this is non-nil, the headline after the keyword is set to the
2305 `org-headline-done' as an additional indication."
2306 :group 'org-font-lock
2307 :type 'boolean)
2309 (defcustom org-fontify-emphasized-text t
2310 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2311 Changing this variable requires a restart of Emacs to take effect."
2312 :group 'org-font-lock
2313 :type 'boolean)
2315 (defcustom org-highlight-latex-fragments-and-specials nil
2316 "Non-nil means, fontify what is treated specially by the exporters."
2317 :group 'org-font-lock
2318 :type 'boolean)
2320 (defcustom org-hide-emphasis-markers nil
2321 "Non-nil mean font-lock should hide the emphasis marker characters."
2322 :group 'org-font-lock
2323 :type 'boolean)
2325 (defvar org-emph-re nil
2326 "Regular expression for matching emphasis.")
2327 (defvar org-verbatim-re nil
2328 "Regular expression for matching verbatim text.")
2329 (defvar org-emphasis-regexp-components) ; defined just below
2330 (defvar org-emphasis-alist) ; defined just below
2331 (defun org-set-emph-re (var val)
2332 "Set variable and compute the emphasis regular expression."
2333 (set var val)
2334 (when (and (boundp 'org-emphasis-alist)
2335 (boundp 'org-emphasis-regexp-components)
2336 org-emphasis-alist org-emphasis-regexp-components)
2337 (let* ((e org-emphasis-regexp-components)
2338 (pre (car e))
2339 (post (nth 1 e))
2340 (border (nth 2 e))
2341 (body (nth 3 e))
2342 (nl (nth 4 e))
2343 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
2344 (body1 (concat body "*?"))
2345 (markers (mapconcat 'car org-emphasis-alist ""))
2346 (vmarkers (mapconcat
2347 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2348 org-emphasis-alist "")))
2349 ;; make sure special characters appear at the right position in the class
2350 (if (string-match "\\^" markers)
2351 (setq markers (concat (replace-match "" t t markers) "^")))
2352 (if (string-match "-" markers)
2353 (setq markers (concat (replace-match "" t t markers) "-")))
2354 (if (string-match "\\^" vmarkers)
2355 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2356 (if (string-match "-" vmarkers)
2357 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2358 (if (> nl 0)
2359 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2360 (int-to-string nl) "\\}")))
2361 ;; Make the regexp
2362 (setq org-emph-re
2363 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
2364 "\\("
2365 "\\([" markers "]\\)"
2366 "\\("
2367 "[^" border "]\\|"
2368 "[^" border (if (and nil stacked) markers) "]"
2369 body1
2370 "[^" border (if (and nil stacked) markers) "]"
2371 "\\)"
2372 "\\3\\)"
2373 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
2374 (setq org-verbatim-re
2375 (concat "\\([" pre "]\\|^\\)"
2376 "\\("
2377 "\\([" vmarkers "]\\)"
2378 "\\("
2379 "[^" border "]\\|"
2380 "[^" border "]"
2381 body1
2382 "[^" border "]"
2383 "\\)"
2384 "\\3\\)"
2385 "\\([" post "]\\|$\\)")))))
2387 (defcustom org-emphasis-regexp-components
2388 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
2389 "Components used to build the regular expression for emphasis.
2390 This is a list with 6 entries. Terminology: In an emphasis string
2391 like \" *strong word* \", we call the initial space PREMATCH, the final
2392 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2393 and \"trong wor\" is the body. The different components in this variable
2394 specify what is allowed/forbidden in each part:
2396 pre Chars allowed as prematch. Beginning of line will be allowed too.
2397 post Chars allowed as postmatch. End of line will be allowed too.
2398 border The chars *forbidden* as border characters.
2399 body-regexp A regexp like \".\" to match a body character. Don't use
2400 non-shy groups here, and don't allow newline here.
2401 newline The maximum number of newlines allowed in an emphasis exp.
2403 Use customize to modify this, or restart Emacs after changing it."
2404 :group 'org-font-lock
2405 :set 'org-set-emph-re
2406 :type '(list
2407 (sexp :tag "Allowed chars in pre ")
2408 (sexp :tag "Allowed chars in post ")
2409 (sexp :tag "Forbidden chars in border ")
2410 (sexp :tag "Regexp for body ")
2411 (integer :tag "number of newlines allowed")
2412 (option (boolean :tag "Please ignore this button"))))
2414 (defcustom org-emphasis-alist
2415 `(("*" bold "<b>" "</b>")
2416 ("/" italic "<i>" "</i>")
2417 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
2418 ("=" org-code "<code>" "</code>" verbatim)
2419 ("~" org-verbatim "<code>" "</code>" verbatim)
2420 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2421 "<del>" "</del>")
2423 "Special syntax for emphasized text.
2424 Text starting and ending with a special character will be emphasized, for
2425 example *bold*, _underlined_ and /italic/. This variable sets the marker
2426 characters, the face to be used by font-lock for highlighting in Org-mode
2427 Emacs buffers, and the HTML tags to be used for this.
2428 Use customize to modify this, or restart Emacs after changing it."
2429 :group 'org-font-lock
2430 :set 'org-set-emph-re
2431 :type '(repeat
2432 (list
2433 (string :tag "Marker character")
2434 (choice
2435 (face :tag "Font-lock-face")
2436 (plist :tag "Face property list"))
2437 (string :tag "HTML start tag")
2438 (string :tag "HTML end tag")
2439 (option (const verbatim)))))
2441 ;;; Miscellaneous options
2443 (defgroup org-completion nil
2444 "Completion in Org-mode."
2445 :tag "Org Completion"
2446 :group 'org)
2448 (defcustom org-completion-use-ido nil
2449 "Non-nil means, use ido completion wherever possible.
2450 Note that `ido-mode' must be active for this variable to be relevant.
2451 If you decide to turn this variable on, you might well want to turn off
2452 `org-outline-path-complete-in-steps'."
2453 :group 'org-completion
2454 :type 'boolean)
2456 (defcustom org-completion-fallback-command 'hippie-expand
2457 "The expansion command called by \\[org-complete] in normal context.
2458 Normal means, no org-mode-specific context."
2459 :group 'org-completion
2460 :type 'function)
2462 ;;; Functions and variables from ther packages
2463 ;; Declared here to avoid compiler warnings
2465 ;; XEmacs only
2466 (defvar outline-mode-menu-heading)
2467 (defvar outline-mode-menu-show)
2468 (defvar outline-mode-menu-hide)
2469 (defvar zmacs-regions) ; XEmacs regions
2471 ;; Emacs only
2472 (defvar mark-active)
2474 ;; Various packages
2475 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2476 (declare-function calendar-forward-day "cal-move" (arg))
2477 (declare-function calendar-goto-date "cal-move" (date))
2478 (declare-function calendar-goto-today "cal-move" ())
2479 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2480 (defvar calc-embedded-close-formula)
2481 (defvar calc-embedded-open-formula)
2482 (declare-function cdlatex-tab "ext:cdlatex" ())
2483 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2484 (defvar font-lock-unfontify-region-function)
2485 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2486 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2487 (defvar iswitchb-temp-buflist)
2488 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2489 (declare-function org-agenda-skip "org-agenda" ())
2490 (declare-function org-format-agenda-item "org-agenda"
2491 (extra txt &optional category tags dotime noprefix remove-re))
2492 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2493 (declare-function org-agenda-change-all-lines "org-agenda"
2494 (newhead hdmarker &optional fixface just-this))
2495 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2496 (declare-function org-agenda-maybe-redo "org-agenda" ())
2497 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2498 (beg end))
2499 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
2500 (declare-function parse-time-string "parse-time" (string))
2501 (declare-function remember "remember" (&optional initial))
2502 (declare-function remember-buffer-desc "remember" ())
2503 (declare-function remember-finalize "remember" ())
2504 (defvar remember-save-after-remembering)
2505 (defvar remember-data-file)
2506 (defvar remember-register)
2507 (defvar remember-buffer)
2508 (defvar remember-handler-functions)
2509 (defvar remember-annotation-functions)
2510 (defvar texmathp-why)
2511 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2512 (declare-function table--at-cell-p "table" (position &optional object at-column))
2514 (defvar w3m-current-url)
2515 (defvar w3m-current-title)
2517 (defvar org-latex-regexps)
2519 ;;; Autoload and prepare some org modules
2521 ;; Some table stuff that needs to be defined here, because it is used
2522 ;; by the functions setting up org-mode or checking for table context.
2524 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2525 "Detects an org-type or table-type table.")
2526 (defconst org-table-line-regexp "^[ \t]*|"
2527 "Detects an org-type table line.")
2528 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2529 "Detects an org-type table line.")
2530 (defconst org-table-hline-regexp "^[ \t]*|-"
2531 "Detects an org-type table hline.")
2532 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2533 "Detects a table-type table hline.")
2534 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2535 "Searching from within a table (any type) this finds the first line
2536 outside the table.")
2538 ;; Autoload the functions in org-table.el that are needed by functions here.
2540 (eval-and-compile
2541 (org-autoload "org-table"
2542 '(org-table-align org-table-begin org-table-blank-field
2543 org-table-convert org-table-convert-region org-table-copy-down
2544 org-table-copy-region org-table-create
2545 org-table-create-or-convert-from-region
2546 org-table-create-with-table.el org-table-current-dline
2547 org-table-cut-region org-table-delete-column org-table-edit-field
2548 org-table-edit-formulas org-table-end org-table-eval-formula
2549 org-table-export org-table-field-info
2550 org-table-get-stored-formulas org-table-goto-column
2551 org-table-hline-and-move org-table-import org-table-insert-column
2552 org-table-insert-hline org-table-insert-row org-table-iterate
2553 org-table-justify-field-maybe org-table-kill-row
2554 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2555 org-table-move-column org-table-move-column-left
2556 org-table-move-column-right org-table-move-row
2557 org-table-move-row-down org-table-move-row-up
2558 org-table-next-field org-table-next-row org-table-paste-rectangle
2559 org-table-previous-field org-table-recalculate
2560 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2561 org-table-toggle-coordinate-overlays
2562 org-table-toggle-formula-debugger org-table-wrap-region
2563 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
2565 (defun org-at-table-p (&optional table-type)
2566 "Return t if the cursor is inside an org-type table.
2567 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2568 (if org-enable-table-editor
2569 (save-excursion
2570 (beginning-of-line 1)
2571 (looking-at (if table-type org-table-any-line-regexp
2572 org-table-line-regexp)))
2573 nil))
2574 (defsubst org-table-p () (org-at-table-p))
2576 (defun org-at-table.el-p ()
2577 "Return t if and only if we are at a table.el table."
2578 (and (org-at-table-p 'any)
2579 (save-excursion
2580 (goto-char (org-table-begin 'any))
2581 (looking-at org-table1-hline-regexp))))
2582 (defun org-table-recognize-table.el ()
2583 "If there is a table.el table nearby, recognize it and move into it."
2584 (if org-table-tab-recognizes-table.el
2585 (if (org-at-table.el-p)
2586 (progn
2587 (beginning-of-line 1)
2588 (if (looking-at org-table-dataline-regexp)
2590 (if (looking-at org-table1-hline-regexp)
2591 (progn
2592 (beginning-of-line 2)
2593 (if (looking-at org-table-any-border-regexp)
2594 (beginning-of-line -1)))))
2595 (if (re-search-forward "|" (org-table-end t) t)
2596 (progn
2597 (require 'table)
2598 (if (table--at-cell-p (point))
2600 (message "recognizing table.el table...")
2601 (table-recognize-table)
2602 (message "recognizing table.el table...done")))
2603 (error "This should not happen..."))
2605 nil)
2606 nil))
2608 (defun org-at-table-hline-p ()
2609 "Return t if the cursor is inside a hline in a table."
2610 (if org-enable-table-editor
2611 (save-excursion
2612 (beginning-of-line 1)
2613 (looking-at org-table-hline-regexp))
2614 nil))
2616 (defvar org-table-clean-did-remove-column nil)
2618 (defun org-table-map-tables (function)
2619 "Apply FUNCTION to the start of all tables in the buffer."
2620 (save-excursion
2621 (save-restriction
2622 (widen)
2623 (goto-char (point-min))
2624 (while (re-search-forward org-table-any-line-regexp nil t)
2625 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2626 (beginning-of-line 1)
2627 (if (looking-at org-table-line-regexp)
2628 (save-excursion (funcall function)))
2629 (re-search-forward org-table-any-border-regexp nil 1))))
2630 (message "Mapping tables: done"))
2632 ;; Declare and autoload functions from org-exp.el
2634 (declare-function org-default-export-plist "org-exp")
2635 (declare-function org-infile-export-plist "org-exp")
2636 (declare-function org-get-current-options "org-exp")
2637 (eval-and-compile
2638 (org-autoload "org-exp"
2639 '(org-export org-export-as-ascii org-export-visible
2640 org-insert-export-options-template org-export-as-html-and-open
2641 org-export-as-html-batch org-export-as-html-to-buffer
2642 org-replace-region-by-html org-export-region-as-html
2643 org-export-as-html org-export-icalendar-this-file
2644 org-export-icalendar-all-agenda-files
2645 org-table-clean-before-export
2646 org-export-icalendar-combine-agenda-files org-export-as-xoxo)))
2648 ;; Declare and autoload functions from org-agenda.el
2650 (eval-and-compile
2651 (org-autoload "org-agenda"
2652 '(org-agenda org-agenda-list org-search-view
2653 org-todo-list org-tags-view org-agenda-list-stuck-projects
2654 org-diary org-agenda-to-appt)))
2656 ;; Autoload org-remember
2658 (eval-and-compile
2659 (org-autoload "org-remember"
2660 '(org-remember-insinuate org-remember-annotation
2661 org-remember-apply-template org-remember org-remember-handler)))
2663 ;; Autoload org-clock.el
2666 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
2667 (beg end))
2668 (declare-function org-clock-update-mode-line "org-clock" ())
2669 (defvar org-clock-start-time)
2670 (defvar org-clock-marker (make-marker)
2671 "Marker recording the last clock-in.")
2673 (eval-and-compile
2674 (org-autoload
2675 "org-clock"
2676 '(org-clock-in org-clock-out org-clock-cancel
2677 org-clock-goto org-clock-sum org-clock-display
2678 org-clock-remove-overlays org-clock-report
2679 org-clocktable-shift org-dblock-write:clocktable
2680 org-get-clocktable)))
2682 (defun org-clock-update-time-maybe ()
2683 "If this is a CLOCK line, update it and return t.
2684 Otherwise, return nil."
2685 (interactive)
2686 (save-excursion
2687 (beginning-of-line 1)
2688 (skip-chars-forward " \t")
2689 (when (looking-at org-clock-string)
2690 (let ((re (concat "[ \t]*" org-clock-string
2691 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
2692 "\\([ \t]*=>.*\\)?\\)?"))
2693 ts te h m s neg)
2694 (cond
2695 ((not (looking-at re))
2696 nil)
2697 ((not (match-end 2))
2698 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2699 (> org-clock-marker (point))
2700 (<= org-clock-marker (point-at-eol)))
2701 ;; The clock is running here
2702 (setq org-clock-start-time
2703 (apply 'encode-time
2704 (org-parse-time-string (match-string 1))))
2705 (org-clock-update-mode-line)))
2707 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
2708 (end-of-line 1)
2709 (setq ts (match-string 1)
2710 te (match-string 3))
2711 (setq s (- (time-to-seconds
2712 (apply 'encode-time (org-parse-time-string te)))
2713 (time-to-seconds
2714 (apply 'encode-time (org-parse-time-string ts))))
2715 neg (< s 0)
2716 s (abs s)
2717 h (floor (/ s 3600))
2718 s (- s (* 3600 h))
2719 m (floor (/ s 60))
2720 s (- s (* 60 s)))
2721 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
2722 t))))))
2724 (defun org-check-running-clock ()
2725 "Check if the current buffer contains the running clock.
2726 If yes, offer to stop it and to save the buffer with the changes."
2727 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2728 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
2729 (buffer-name))))
2730 (org-clock-out)
2731 (when (y-or-n-p "Save changed buffer?")
2732 (save-buffer))))
2734 (defun org-clocktable-try-shift (dir n)
2735 "Check if this line starts a clock table, if yes, shift the time block."
2736 (when (org-match-line "#\\+BEGIN: clocktable\\>")
2737 (org-clocktable-shift dir n)))
2739 ;; Autoload org-timer.el
2741 ;(declare-function org-timer "org-timer")
2743 (eval-and-compile
2744 (org-autoload
2745 "org-timer"
2746 '(org-timer-start org-timer org-timer-item
2747 org-timer-change-times-in-region)))
2750 ;; Autoload archiving code
2751 ;; The stuff that is needed for cycling and tags has to be defined here.
2753 (defgroup org-archive nil
2754 "Options concerning archiving in Org-mode."
2755 :tag "Org Archive"
2756 :group 'org-structure)
2758 (defcustom org-archive-location "%s_archive::"
2759 "The location where subtrees should be archived.
2761 The value of this variable is a string, consisting of two parts,
2762 separated by a double-colon. The first part is a filename and
2763 the second part is a headline.
2765 When the filename is omitted, archiving happens in the same file.
2766 %s in the filename will be replaced by the current file
2767 name (without the directory part). Archiving to a different file
2768 is useful to keep archived entries from contributing to the
2769 Org-mode Agenda.
2771 The archived entries will be filed as subtrees of the specified
2772 headline. When the headline is omitted, the subtrees are simply
2773 filed away at the end of the file, as top-level entries. Also in
2774 the heading you can use %s to represent the file name, this can be
2775 useful when using the same archive for a number of different files.
2777 Here are a few examples:
2778 \"%s_archive::\"
2779 If the current file is Projects.org, archive in file
2780 Projects.org_archive, as top-level trees. This is the default.
2782 \"::* Archived Tasks\"
2783 Archive in the current file, under the top-level headline
2784 \"* Archived Tasks\".
2786 \"~/org/archive.org::\"
2787 Archive in file ~/org/archive.org (absolute path), as top-level trees.
2789 \"~/org/archive.org::From %s\"
2790 Archive in file ~/org/archive.org (absolute path), und headlines
2791 \"From FILENAME\" where file name is the current file name.
2793 \"basement::** Finished Tasks\"
2794 Archive in file ./basement (relative path), as level 3 trees
2795 below the level 2 heading \"** Finished Tasks\".
2797 You may set this option on a per-file basis by adding to the buffer a
2798 line like
2800 #+ARCHIVE: basement::** Finished Tasks
2802 You may also define it locally for a subtree by setting an ARCHIVE property
2803 in the entry. If such a property is found in an entry, or anywhere up
2804 the hierarchy, it will be used."
2805 :group 'org-archive
2806 :type 'string)
2808 (defcustom org-archive-tag "ARCHIVE"
2809 "The tag that marks a subtree as archived.
2810 An archived subtree does not open during visibility cycling, and does
2811 not contribute to the agenda listings.
2812 After changing this, font-lock must be restarted in the relevant buffers to
2813 get the proper fontification."
2814 :group 'org-archive
2815 :group 'org-keywords
2816 :type 'string)
2818 (defcustom org-agenda-skip-archived-trees t
2819 "Non-nil means, the agenda will skip any items located in archived trees.
2820 An archived tree is a tree marked with the tag ARCHIVE. The use of this
2821 variable is no longer recommended, you should leave it at the value t.
2822 Instead, use the key `v' to cycle the archives-mode in the agenda."
2823 :group 'org-archive
2824 :group 'org-agenda-skip
2825 :type 'boolean)
2827 (defcustom org-cycle-open-archived-trees nil
2828 "Non-nil means, `org-cycle' will open archived trees.
2829 An archived tree is a tree marked with the tag ARCHIVE.
2830 When nil, archived trees will stay folded. You can still open them with
2831 normal outline commands like `show-all', but not with the cycling commands."
2832 :group 'org-archive
2833 :group 'org-cycle
2834 :type 'boolean)
2836 (defcustom org-sparse-tree-open-archived-trees nil
2837 "Non-nil means sparse tree construction shows matches in archived trees.
2838 When nil, matches in these trees are highlighted, but the trees are kept in
2839 collapsed state."
2840 :group 'org-archive
2841 :group 'org-sparse-trees
2842 :type 'boolean)
2844 (defun org-cycle-hide-archived-subtrees (state)
2845 "Re-hide all archived subtrees after a visibility state change."
2846 (when (and (not org-cycle-open-archived-trees)
2847 (not (memq state '(overview folded))))
2848 (save-excursion
2849 (let* ((globalp (memq state '(contents all)))
2850 (beg (if globalp (point-min) (point)))
2851 (end (if globalp (point-max) (org-end-of-subtree t))))
2852 (org-hide-archived-subtrees beg end)
2853 (goto-char beg)
2854 (if (looking-at (concat ".*:" org-archive-tag ":"))
2855 (message "%s" (substitute-command-keys
2856 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
2858 (defun org-force-cycle-archived ()
2859 "Cycle subtree even if it is archived."
2860 (interactive)
2861 (setq this-command 'org-cycle)
2862 (let ((org-cycle-open-archived-trees t))
2863 (call-interactively 'org-cycle)))
2865 (defun org-hide-archived-subtrees (beg end)
2866 "Re-hide all archived subtrees after a visibility state change."
2867 (save-excursion
2868 (let* ((re (concat ":" org-archive-tag ":")))
2869 (goto-char beg)
2870 (while (re-search-forward re end t)
2871 (and (org-on-heading-p) (hide-subtree))
2872 (org-end-of-subtree t)))))
2874 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
2876 (eval-and-compile
2877 (org-autoload "org-archive"
2878 '(org-add-archive-files org-archive-subtree
2879 org-archive-to-archive-sibling org-toggle-archive-tag)))
2881 ;; Autoload Column View Code
2883 (declare-function org-columns-number-to-string "org-colview")
2884 (declare-function org-columns-get-format-and-top-level "org-colview")
2885 (declare-function org-columns-compute "org-colview")
2887 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
2888 '(org-columns-number-to-string org-columns-get-format-and-top-level
2889 org-columns-compute org-agenda-columns org-columns-remove-overlays
2890 org-columns org-insert-columns-dblock org-dblock-write:columnview))
2892 ;; Autoload ID code
2894 (declare-function org-id-store-link "org-id")
2895 (org-autoload "org-id"
2896 '(org-id-get-create org-id-new org-id-copy org-id-get
2897 org-id-get-with-outline-path-completion
2898 org-id-get-with-outline-drilling
2899 org-id-goto org-id-find org-id-store-link))
2901 ;;; Variables for pre-computed regular expressions, all buffer local
2903 (defvar org-drawer-regexp nil
2904 "Matches first line of a hidden block.")
2905 (make-variable-buffer-local 'org-drawer-regexp)
2906 (defvar org-todo-regexp nil
2907 "Matches any of the TODO state keywords.")
2908 (make-variable-buffer-local 'org-todo-regexp)
2909 (defvar org-not-done-regexp nil
2910 "Matches any of the TODO state keywords except the last one.")
2911 (make-variable-buffer-local 'org-not-done-regexp)
2912 (defvar org-todo-line-regexp nil
2913 "Matches a headline and puts TODO state into group 2 if present.")
2914 (make-variable-buffer-local 'org-todo-line-regexp)
2915 (defvar org-complex-heading-regexp nil
2916 "Matches a headline and puts everything into groups:
2917 group 1: the stars
2918 group 2: The todo keyword, maybe
2919 group 3: Priority cookie
2920 group 4: True headline
2921 group 5: Tags")
2922 (make-variable-buffer-local 'org-complex-heading-regexp)
2923 (defvar org-todo-line-tags-regexp nil
2924 "Matches a headline and puts TODO state into group 2 if present.
2925 Also put tags into group 4 if tags are present.")
2926 (make-variable-buffer-local 'org-todo-line-tags-regexp)
2927 (defvar org-nl-done-regexp nil
2928 "Matches newline followed by a headline with the DONE keyword.")
2929 (make-variable-buffer-local 'org-nl-done-regexp)
2930 (defvar org-looking-at-done-regexp nil
2931 "Matches the DONE keyword a point.")
2932 (make-variable-buffer-local 'org-looking-at-done-regexp)
2933 (defvar org-ds-keyword-length 12
2934 "Maximum length of the Deadline and SCHEDULED keywords.")
2935 (make-variable-buffer-local 'org-ds-keyword-length)
2936 (defvar org-deadline-regexp nil
2937 "Matches the DEADLINE keyword.")
2938 (make-variable-buffer-local 'org-deadline-regexp)
2939 (defvar org-deadline-time-regexp nil
2940 "Matches the DEADLINE keyword together with a time stamp.")
2941 (make-variable-buffer-local 'org-deadline-time-regexp)
2942 (defvar org-deadline-line-regexp nil
2943 "Matches the DEADLINE keyword and the rest of the line.")
2944 (make-variable-buffer-local 'org-deadline-line-regexp)
2945 (defvar org-scheduled-regexp nil
2946 "Matches the SCHEDULED keyword.")
2947 (make-variable-buffer-local 'org-scheduled-regexp)
2948 (defvar org-scheduled-time-regexp nil
2949 "Matches the SCHEDULED keyword together with a time stamp.")
2950 (make-variable-buffer-local 'org-scheduled-time-regexp)
2951 (defvar org-closed-time-regexp nil
2952 "Matches the CLOSED keyword together with a time stamp.")
2953 (make-variable-buffer-local 'org-closed-time-regexp)
2955 (defvar org-keyword-time-regexp nil
2956 "Matches any of the 4 keywords, together with the time stamp.")
2957 (make-variable-buffer-local 'org-keyword-time-regexp)
2958 (defvar org-keyword-time-not-clock-regexp nil
2959 "Matches any of the 3 keywords, together with the time stamp.")
2960 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
2961 (defvar org-maybe-keyword-time-regexp nil
2962 "Matches a timestamp, possibly preceeded by a keyword.")
2963 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
2964 (defvar org-planning-or-clock-line-re nil
2965 "Matches a line with planning or clock info.")
2966 (make-variable-buffer-local 'org-planning-or-clock-line-re)
2968 (defconst org-plain-time-of-day-regexp
2969 (concat
2970 "\\(\\<[012]?[0-9]"
2971 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2972 "\\(--?"
2973 "\\(\\<[012]?[0-9]"
2974 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2975 "\\)?")
2976 "Regular expression to match a plain time or time range.
2977 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2978 groups carry important information:
2979 0 the full match
2980 1 the first time, range or not
2981 8 the second time, if it is a range.")
2983 (defconst org-plain-time-extension-regexp
2984 (concat
2985 "\\(\\<[012]?[0-9]"
2986 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2987 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
2988 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
2989 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2990 groups carry important information:
2991 0 the full match
2992 7 hours of duration
2993 9 minutes of duration")
2995 (defconst org-stamp-time-of-day-regexp
2996 (concat
2997 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
2998 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
2999 "\\(--?"
3000 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
3001 "Regular expression to match a timestamp time or time range.
3002 After a match, the following groups carry important information:
3003 0 the full match
3004 1 date plus weekday, for backreferencing to make sure both times on same day
3005 2 the first time, range or not
3006 4 the second time, if it is a range.")
3008 (defconst org-startup-options
3009 '(("fold" org-startup-folded t)
3010 ("overview" org-startup-folded t)
3011 ("nofold" org-startup-folded nil)
3012 ("showall" org-startup-folded nil)
3013 ("content" org-startup-folded content)
3014 ("hidestars" org-hide-leading-stars t)
3015 ("showstars" org-hide-leading-stars nil)
3016 ("odd" org-odd-levels-only t)
3017 ("oddeven" org-odd-levels-only nil)
3018 ("align" org-startup-align-all-tables t)
3019 ("noalign" org-startup-align-all-tables nil)
3020 ("customtime" org-display-custom-times t)
3021 ("logdone" org-log-done time)
3022 ("lognotedone" org-log-done note)
3023 ("nologdone" org-log-done nil)
3024 ("lognoteclock-out" org-log-note-clock-out t)
3025 ("nolognoteclock-out" org-log-note-clock-out nil)
3026 ("logrepeat" org-log-repeat state)
3027 ("lognoterepeat" org-log-repeat note)
3028 ("nologrepeat" org-log-repeat nil)
3029 ("fninline" org-footnote-define-inline t)
3030 ("nofninline" org-footnote-define-inline nil)
3031 ("fnlocal" org-footnote-section nil)
3032 ("fnauto" org-footnote-auto-label t)
3033 ("fnprompt" org-footnote-auto-label nil)
3034 ("fnconfirm" org-footnote-auto-label confirm)
3035 ("fnplain" org-footnote-auto-label plain)
3036 ("constcgs" constants-unit-system cgs)
3037 ("constSI" constants-unit-system SI))
3038 "Variable associated with STARTUP options for org-mode.
3039 Each element is a list of three items: The startup options as written
3040 in the #+STARTUP line, the corresponding variable, and the value to
3041 set this variable to if the option is found. An optional forth element PUSH
3042 means to push this value onto the list in the variable.")
3044 (defun org-set-regexps-and-options ()
3045 "Precompute regular expressions for current buffer."
3046 (when (org-mode-p)
3047 (org-set-local 'org-todo-kwd-alist nil)
3048 (org-set-local 'org-todo-key-alist nil)
3049 (org-set-local 'org-todo-key-trigger nil)
3050 (org-set-local 'org-todo-keywords-1 nil)
3051 (org-set-local 'org-done-keywords nil)
3052 (org-set-local 'org-todo-heads nil)
3053 (org-set-local 'org-todo-sets nil)
3054 (org-set-local 'org-todo-log-states nil)
3055 (org-set-local 'org-file-properties nil)
3056 (org-set-local 'org-file-tags nil)
3057 (let ((re (org-make-options-regexp
3058 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
3059 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3060 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")))
3061 (splitre "[ \t]+")
3062 kwds kws0 kwsa key log value cat arch tags const links hw dws
3063 tail sep kws1 prio props ftags drawers
3064 ext-setup-or-nil setup-contents (start 0))
3065 (save-excursion
3066 (save-restriction
3067 (widen)
3068 (goto-char (point-min))
3069 (while (or (and ext-setup-or-nil
3070 (string-match re ext-setup-or-nil start)
3071 (setq start (match-end 0)))
3072 (and (setq ext-setup-or-nil nil start 0)
3073 (re-search-forward re nil t)))
3074 (setq key (upcase (match-string 1 ext-setup-or-nil))
3075 value (org-match-string-no-properties 2 ext-setup-or-nil))
3076 (cond
3077 ((equal key "CATEGORY")
3078 (if (string-match "[ \t]+$" value)
3079 (setq value (replace-match "" t t value)))
3080 (setq cat value))
3081 ((member key '("SEQ_TODO" "TODO"))
3082 (push (cons 'sequence (org-split-string value splitre)) kwds))
3083 ((equal key "TYP_TODO")
3084 (push (cons 'type (org-split-string value splitre)) kwds))
3085 ((equal key "TAGS")
3086 (setq tags (append tags (org-split-string value splitre))))
3087 ((equal key "COLUMNS")
3088 (org-set-local 'org-columns-default-format value))
3089 ((equal key "LINK")
3090 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3091 (push (cons (match-string 1 value)
3092 (org-trim (match-string 2 value)))
3093 links)))
3094 ((equal key "PRIORITIES")
3095 (setq prio (org-split-string value " +")))
3096 ((equal key "PROPERTY")
3097 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3098 (push (cons (match-string 1 value) (match-string 2 value))
3099 props)))
3100 ((equal key "FILETAGS")
3101 (when (string-match "\\S-" value)
3102 (setq ftags
3103 (append
3104 ftags
3105 (apply 'append
3106 (mapcar (lambda (x) (org-split-string x ":"))
3107 (org-split-string value)))))))
3108 ((equal key "DRAWERS")
3109 (setq drawers (org-split-string value splitre)))
3110 ((equal key "CONSTANTS")
3111 (setq const (append const (org-split-string value splitre))))
3112 ((equal key "STARTUP")
3113 (let ((opts (org-split-string value splitre))
3114 l var val)
3115 (while (setq l (pop opts))
3116 (when (setq l (assoc l org-startup-options))
3117 (setq var (nth 1 l) val (nth 2 l))
3118 (if (not (nth 3 l))
3119 (set (make-local-variable var) val)
3120 (if (not (listp (symbol-value var)))
3121 (set (make-local-variable var) nil))
3122 (set (make-local-variable var) (symbol-value var))
3123 (add-to-list var val))))))
3124 ((equal key "ARCHIVE")
3125 (string-match " *$" value)
3126 (setq arch (replace-match "" t t value))
3127 (remove-text-properties 0 (length arch)
3128 '(face t fontified t) arch))
3129 ((equal key "SETUPFILE")
3130 (setq setup-contents (org-file-contents
3131 (expand-file-name
3132 (org-remove-double-quotes value))
3133 'noerror))
3134 (if (not ext-setup-or-nil)
3135 (setq ext-setup-or-nil setup-contents start 0)
3136 (setq ext-setup-or-nil
3137 (concat (substring ext-setup-or-nil 0 start)
3138 "\n" setup-contents "\n"
3139 (substring ext-setup-or-nil start)))))
3140 ))))
3141 (when cat
3142 (org-set-local 'org-category (intern cat))
3143 (push (cons "CATEGORY" cat) props))
3144 (when prio
3145 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3146 (setq prio (mapcar 'string-to-char prio))
3147 (org-set-local 'org-highest-priority (nth 0 prio))
3148 (org-set-local 'org-lowest-priority (nth 1 prio))
3149 (org-set-local 'org-default-priority (nth 2 prio)))
3150 (and props (org-set-local 'org-file-properties (nreverse props)))
3151 (and ftags (org-set-local 'org-file-tags ftags))
3152 (and drawers (org-set-local 'org-drawers drawers))
3153 (and arch (org-set-local 'org-archive-location arch))
3154 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3155 ;; Process the TODO keywords
3156 (unless kwds
3157 ;; Use the global values as if they had been given locally.
3158 (setq kwds (default-value 'org-todo-keywords))
3159 (if (stringp (car kwds))
3160 (setq kwds (list (cons org-todo-interpretation
3161 (default-value 'org-todo-keywords)))))
3162 (setq kwds (reverse kwds)))
3163 (setq kwds (nreverse kwds))
3164 (let (inter kws kw)
3165 (while (setq kws (pop kwds))
3166 (setq inter (pop kws) sep (member "|" kws)
3167 kws0 (delete "|" (copy-sequence kws))
3168 kwsa nil
3169 kws1 (mapcar
3170 (lambda (x)
3171 ;; 1 2
3172 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3173 (progn
3174 (setq kw (match-string 1 x)
3175 key (and (match-end 2) (match-string 2 x))
3176 log (org-extract-log-state-settings x))
3177 (push (cons kw (and key (string-to-char key))) kwsa)
3178 (and log (push log org-todo-log-states))
3180 (error "Invalid TODO keyword %s" x)))
3181 kws0)
3182 kwsa (if kwsa (append '((:startgroup))
3183 (nreverse kwsa)
3184 '((:endgroup))))
3185 hw (car kws1)
3186 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3187 tail (list inter hw (car dws) (org-last dws)))
3188 (add-to-list 'org-todo-heads hw 'append)
3189 (push kws1 org-todo-sets)
3190 (setq org-done-keywords (append org-done-keywords dws nil))
3191 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3192 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3193 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3194 (setq org-todo-sets (nreverse org-todo-sets)
3195 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3196 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3197 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3198 ;; Process the constants
3199 (when const
3200 (let (e cst)
3201 (while (setq e (pop const))
3202 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3203 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3204 (setq org-table-formula-constants-local cst)))
3206 ;; Process the tags.
3207 (when tags
3208 (let (e tgs)
3209 (while (setq e (pop tags))
3210 (cond
3211 ((equal e "{") (push '(:startgroup) tgs))
3212 ((equal e "}") (push '(:endgroup) tgs))
3213 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3214 (push (cons (match-string 1 e)
3215 (string-to-char (match-string 2 e)))
3216 tgs))
3217 (t (push (list e) tgs))))
3218 (org-set-local 'org-tag-alist nil)
3219 (while (setq e (pop tgs))
3220 (or (and (stringp (car e))
3221 (assoc (car e) org-tag-alist))
3222 (push e org-tag-alist)))))
3224 ;; Compute the regular expressions and other local variables
3225 (if (not org-done-keywords)
3226 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
3227 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3228 (length org-scheduled-string)
3229 (length org-clock-string)
3230 (length org-closed-string)))
3231 org-drawer-regexp
3232 (concat "^[ \t]*:\\("
3233 (mapconcat 'regexp-quote org-drawers "\\|")
3234 "\\):[ \t]*$")
3235 org-not-done-keywords
3236 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3237 org-todo-regexp
3238 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3239 "\\|") "\\)\\>")
3240 org-not-done-regexp
3241 (concat "\\<\\("
3242 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3243 "\\)\\>")
3244 org-todo-line-regexp
3245 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3246 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3247 "\\)\\>\\)?[ \t]*\\(.*\\)")
3248 org-complex-heading-regexp
3249 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3250 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3251 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3252 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3253 org-nl-done-regexp
3254 (concat "\n\\*+[ \t]+"
3255 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3256 "\\)" "\\>")
3257 org-todo-line-tags-regexp
3258 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3259 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3260 (org-re
3261 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3262 org-looking-at-done-regexp
3263 (concat "^" "\\(?:"
3264 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3265 "\\>")
3266 org-deadline-regexp (concat "\\<" org-deadline-string)
3267 org-deadline-time-regexp
3268 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3269 org-deadline-line-regexp
3270 (concat "\\<\\(" org-deadline-string "\\).*")
3271 org-scheduled-regexp
3272 (concat "\\<" org-scheduled-string)
3273 org-scheduled-time-regexp
3274 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3275 org-closed-time-regexp
3276 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3277 org-keyword-time-regexp
3278 (concat "\\<\\(" org-scheduled-string
3279 "\\|" org-deadline-string
3280 "\\|" org-closed-string
3281 "\\|" org-clock-string "\\)"
3282 " *[[<]\\([^]>]+\\)[]>]")
3283 org-keyword-time-not-clock-regexp
3284 (concat "\\<\\(" org-scheduled-string
3285 "\\|" org-deadline-string
3286 "\\|" org-closed-string
3287 "\\)"
3288 " *[[<]\\([^]>]+\\)[]>]")
3289 org-maybe-keyword-time-regexp
3290 (concat "\\(\\<\\(" org-scheduled-string
3291 "\\|" org-deadline-string
3292 "\\|" org-closed-string
3293 "\\|" org-clock-string "\\)\\)?"
3294 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3295 org-planning-or-clock-line-re
3296 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3297 "\\|" org-deadline-string
3298 "\\|" org-closed-string "\\|" org-clock-string
3299 "\\)\\>\\)")
3301 (org-compute-latex-and-specials-regexp)
3302 (org-set-font-lock-defaults))))
3304 (defun org-file-contents (file &optional noerror)
3305 "Return the contents of FILE, as a string."
3306 (if (or (not file)
3307 (not (file-readable-p file)))
3308 (if noerror
3309 (progn
3310 (message "Cannot read file %s" file)
3311 (ding) (sit-for 2)
3313 (error "Cannot read file %s" file))
3314 (with-temp-buffer
3315 (insert-file-contents file)
3316 (buffer-string))))
3318 (defun org-extract-log-state-settings (x)
3319 "Extract the log state setting from a TODO keyword string.
3320 This will extract info from a string like \"WAIT(w@/!)\"."
3321 (let (kw key log1 log2)
3322 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3323 (setq kw (match-string 1 x)
3324 key (and (match-end 2) (match-string 2 x))
3325 log1 (and (match-end 3) (match-string 3 x))
3326 log2 (and (match-end 4) (match-string 4 x)))
3327 (and (or log1 log2)
3328 (list kw
3329 (and log1 (if (equal log1 "!") 'time 'note))
3330 (and log2 (if (equal log2 "!") 'time 'note)))))))
3332 (defun org-remove-keyword-keys (list)
3333 "Remove a pair of parenthesis at the end of each string in LIST."
3334 (mapcar (lambda (x)
3335 (if (string-match "(.*)$" x)
3336 (substring x 0 (match-beginning 0))
3338 list))
3340 ;; FIXME: this could be done much better, using second characters etc.
3341 (defun org-assign-fast-keys (alist)
3342 "Assign fast keys to a keyword-key alist.
3343 Respect keys that are already there."
3344 (let (new e k c c1 c2 (char ?a))
3345 (while (setq e (pop alist))
3346 (cond
3347 ((equal e '(:startgroup)) (push e new))
3348 ((equal e '(:endgroup)) (push e new))
3350 (setq k (car e) c2 nil)
3351 (if (cdr e)
3352 (setq c (cdr e))
3353 ;; automatically assign a character.
3354 (setq c1 (string-to-char
3355 (downcase (substring
3356 k (if (= (string-to-char k) ?@) 1 0)))))
3357 (if (or (rassoc c1 new) (rassoc c1 alist))
3358 (while (or (rassoc char new) (rassoc char alist))
3359 (setq char (1+ char)))
3360 (setq c2 c1))
3361 (setq c (or c2 char)))
3362 (push (cons k c) new))))
3363 (nreverse new)))
3365 ;;; Some variables used in various places
3367 (defvar org-window-configuration nil
3368 "Used in various places to store a window configuration.")
3369 (defvar org-finish-function nil
3370 "Function to be called when `C-c C-c' is used.
3371 This is for getting out of special buffers like remember.")
3374 ;; FIXME: Occasionally check by commenting these, to make sure
3375 ;; no other functions uses these, forgetting to let-bind them.
3376 (defvar entry)
3377 (defvar state)
3378 (defvar last-state)
3379 (defvar date)
3380 (defvar description)
3382 ;; Defined somewhere in this file, but used before definition.
3383 (defvar org-html-entities)
3384 (defvar org-struct-menu)
3385 (defvar org-org-menu)
3386 (defvar org-tbl-menu)
3387 (defvar org-agenda-keymap)
3389 ;;;; Define the Org-mode
3391 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3392 (error "Conflict with outdated version of allout.el. Load org.el before allout.el, or upgrade to newer allout, for example by switching to Emacs 22."))
3395 ;; We use a before-change function to check if a table might need
3396 ;; an update.
3397 (defvar org-table-may-need-update t
3398 "Indicates that a table might need an update.
3399 This variable is set by `org-before-change-function'.
3400 `org-table-align' sets it back to nil.")
3401 (defun org-before-change-function (beg end)
3402 "Every change indicates that a table might need an update."
3403 (setq org-table-may-need-update t))
3404 (defvar org-mode-map)
3405 (defvar org-mode-hook nil
3406 "Mode hook for Org-mode, run after the mode was turned on.")
3407 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3408 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3409 (defvar org-table-buffer-is-an nil)
3410 (defconst org-outline-regexp "\\*+ ")
3412 ;;;###autoload
3413 (define-derived-mode org-mode outline-mode "Org"
3414 "Outline-based notes management and organizer, alias
3415 \"Carsten's outline-mode for keeping track of everything.\"
3417 Org-mode develops organizational tasks around a NOTES file which
3418 contains information about projects as plain text. Org-mode is
3419 implemented on top of outline-mode, which is ideal to keep the content
3420 of large files well structured. It supports ToDo items, deadlines and
3421 time stamps, which magically appear in the diary listing of the Emacs
3422 calendar. Tables are easily created with a built-in table editor.
3423 Plain text URL-like links connect to websites, emails (VM), Usenet
3424 messages (Gnus), BBDB entries, and any files related to the project.
3425 For printing and sharing of notes, an Org-mode file (or a part of it)
3426 can be exported as a structured ASCII or HTML file.
3428 The following commands are available:
3430 \\{org-mode-map}"
3432 ;; Get rid of Outline menus, they are not needed
3433 ;; Need to do this here because define-derived-mode sets up
3434 ;; the keymap so late. Still, it is a waste to call this each time
3435 ;; we switch another buffer into org-mode.
3436 (if (featurep 'xemacs)
3437 (when (boundp 'outline-mode-menu-heading)
3438 ;; Assume this is Greg's port, it used easymenu
3439 (easy-menu-remove outline-mode-menu-heading)
3440 (easy-menu-remove outline-mode-menu-show)
3441 (easy-menu-remove outline-mode-menu-hide))
3442 (define-key org-mode-map [menu-bar headings] 'undefined)
3443 (define-key org-mode-map [menu-bar hide] 'undefined)
3444 (define-key org-mode-map [menu-bar show] 'undefined))
3446 (org-load-modules-maybe)
3447 (easy-menu-add org-org-menu)
3448 (easy-menu-add org-tbl-menu)
3449 (org-install-agenda-files-menu)
3450 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3451 (org-add-to-invisibility-spec '(org-cwidth))
3452 (when (featurep 'xemacs)
3453 (org-set-local 'line-move-ignore-invisible t))
3454 (org-set-local 'outline-regexp org-outline-regexp)
3455 (org-set-local 'outline-level 'org-outline-level)
3456 (when (and org-ellipsis
3457 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3458 (fboundp 'make-glyph-code))
3459 (unless org-display-table
3460 (setq org-display-table (make-display-table)))
3461 (set-display-table-slot
3462 org-display-table 4
3463 (vconcat (mapcar
3464 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3465 org-ellipsis)))
3466 (if (stringp org-ellipsis) org-ellipsis "..."))))
3467 (setq buffer-display-table org-display-table))
3468 (org-set-regexps-and-options)
3469 (when (and org-tag-faces (not org-tags-special-faces-re))
3470 ;; tag faces set outside customize.... force initialization.
3471 (org-set-tag-faces 'org-tag-faces org-tag-faces))
3472 ;; Calc embedded
3473 (org-set-local 'calc-embedded-open-mode "# ")
3474 (modify-syntax-entry ?# "<")
3475 (modify-syntax-entry ?@ "w")
3476 (if org-startup-truncated (setq truncate-lines t))
3477 (org-set-local 'font-lock-unfontify-region-function
3478 'org-unfontify-region)
3479 ;; Activate before-change-function
3480 (org-set-local 'org-table-may-need-update t)
3481 (org-add-hook 'before-change-functions 'org-before-change-function nil
3482 'local)
3483 ;; Check for running clock before killing a buffer
3484 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3485 ;; Paragraphs and auto-filling
3486 (org-set-autofill-regexps)
3487 (setq indent-line-function 'org-indent-line-function)
3488 (org-update-radio-target-regexp)
3490 ;; Comment characters
3491 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3492 (org-set-local 'comment-padding " ")
3494 ;; Align options lines
3495 (org-set-local
3496 'align-mode-rules-list
3497 '((org-in-buffer-settings
3498 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3499 (modes . '(org-mode)))))
3501 ;; Imenu
3502 (org-set-local 'imenu-create-index-function
3503 'org-imenu-get-tree)
3505 ;; Make isearch reveal context
3506 (if (or (featurep 'xemacs)
3507 (not (boundp 'outline-isearch-open-invisible-function)))
3508 ;; Emacs 21 and XEmacs make use of the hook
3509 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3510 ;; Emacs 22 deals with this through a special variable
3511 (org-set-local 'outline-isearch-open-invisible-function
3512 (lambda (&rest ignore) (org-show-context 'isearch))))
3514 ;; If empty file that did not turn on org-mode automatically, make it to.
3515 (if (and org-insert-mode-line-in-empty-file
3516 (interactive-p)
3517 (= (point-min) (point-max)))
3518 (insert "# -*- mode: org -*-\n\n"))
3520 (unless org-inhibit-startup
3521 (when org-startup-align-all-tables
3522 (let ((bmp (buffer-modified-p)))
3523 (org-table-map-tables 'org-table-align)
3524 (set-buffer-modified-p bmp)))
3525 (org-set-startup-visibility)))
3527 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3529 (defun org-current-time ()
3530 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3531 (if (> (car org-time-stamp-rounding-minutes) 1)
3532 (let ((r (car org-time-stamp-rounding-minutes))
3533 (time (decode-time)))
3534 (apply 'encode-time
3535 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3536 (nthcdr 2 time))))
3537 (current-time)))
3539 ;;;; Font-Lock stuff, including the activators
3541 (defvar org-mouse-map (make-sparse-keymap))
3542 (org-defkey org-mouse-map
3543 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3544 (org-defkey org-mouse-map
3545 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3546 (when org-mouse-1-follows-link
3547 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3548 (when org-tab-follows-link
3549 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3550 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3551 (when org-return-follows-link
3552 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
3553 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
3555 (require 'font-lock)
3557 (defconst org-non-link-chars "]\t\n\r<>")
3558 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3559 "shell" "elisp"))
3560 (defvar org-link-types-re nil
3561 "Matches a link that has a url-like prefix like \"http:\"")
3562 (defvar org-link-re-with-space nil
3563 "Matches a link with spaces, optional angular brackets around it.")
3564 (defvar org-link-re-with-space2 nil
3565 "Matches a link with spaces, optional angular brackets around it.")
3566 (defvar org-link-re-with-space3 nil
3567 "Matches a link with spaces, only for internal part in bracket links.")
3568 (defvar org-angle-link-re nil
3569 "Matches link with angular brackets, spaces are allowed.")
3570 (defvar org-plain-link-re nil
3571 "Matches plain link, without spaces.")
3572 (defvar org-bracket-link-regexp nil
3573 "Matches a link in double brackets.")
3574 (defvar org-bracket-link-analytic-regexp nil
3575 "Regular expression used to analyze links.
3576 Here is what the match groups contain after a match:
3577 1: http:
3578 2: http
3579 3: path
3580 4: [desc]
3581 5: desc")
3582 (defvar org-bracket-link-analytic-regexp++ nil
3583 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
3584 (defvar org-any-link-re nil
3585 "Regular expression matching any link.")
3587 (defun org-make-link-regexps ()
3588 "Update the link regular expressions.
3589 This should be called after the variable `org-link-types' has changed."
3590 (setq org-link-types-re
3591 (concat
3592 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3593 org-link-re-with-space
3594 (concat
3595 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3596 "\\([^" org-non-link-chars " ]"
3597 "[^" org-non-link-chars "]*"
3598 "[^" org-non-link-chars " ]\\)>?")
3599 org-link-re-with-space2
3600 (concat
3601 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3602 "\\([^" org-non-link-chars " ]"
3603 "[^\t\n\r]*"
3604 "[^" org-non-link-chars " ]\\)>?")
3605 org-link-re-with-space3
3606 (concat
3607 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3608 "\\([^" org-non-link-chars " ]"
3609 "[^\t\n\r]*\\)")
3610 org-angle-link-re
3611 (concat
3612 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3613 "\\([^" org-non-link-chars " ]"
3614 "[^" org-non-link-chars "]*"
3615 "\\)>")
3616 org-plain-link-re
3617 (concat
3618 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3619 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3620 org-bracket-link-regexp
3621 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3622 org-bracket-link-analytic-regexp
3623 (concat
3624 "\\[\\["
3625 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3626 "\\([^]]+\\)"
3627 "\\]"
3628 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3629 "\\]")
3630 org-bracket-link-analytic-regexp++
3631 (concat
3632 "\\[\\["
3633 "\\(\\(" (mapconcat 'identity (cons "coderef" org-link-types) "\\|") "\\):\\)?"
3634 "\\([^]]+\\)"
3635 "\\]"
3636 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3637 "\\]")
3638 org-any-link-re
3639 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3640 org-angle-link-re "\\)\\|\\("
3641 org-plain-link-re "\\)")))
3643 (org-make-link-regexps)
3645 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
3646 "Regular expression for fast time stamp matching.")
3647 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
3648 "Regular expression for fast time stamp matching.")
3649 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3650 "Regular expression matching time strings for analysis.
3651 This one does not require the space after the date, so it can be used
3652 on a string that terminates immediately after the date.")
3653 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3654 "Regular expression matching time strings for analysis.")
3655 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
3656 "Regular expression matching time stamps, with groups.")
3657 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
3658 "Regular expression matching time stamps (also [..]), with groups.")
3659 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3660 "Regular expression matching a time stamp range.")
3661 (defconst org-tr-regexp-both
3662 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3663 "Regular expression matching a time stamp range.")
3664 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3665 org-ts-regexp "\\)?")
3666 "Regular expression matching a time stamp or time stamp range.")
3667 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3668 org-ts-regexp-both "\\)?")
3669 "Regular expression matching a time stamp or time stamp range.
3670 The time stamps may be either active or inactive.")
3672 (defvar org-emph-face nil)
3674 (defun org-do-emphasis-faces (limit)
3675 "Run through the buffer and add overlays to links."
3676 (let (rtn)
3677 (while (and (not rtn) (re-search-forward org-emph-re limit t))
3678 (if (not (= (char-after (match-beginning 3))
3679 (char-after (match-beginning 4))))
3680 (progn
3681 (setq rtn t)
3682 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3683 'face
3684 (nth 1 (assoc (match-string 3)
3685 org-emphasis-alist)))
3686 (add-text-properties (match-beginning 2) (match-end 2)
3687 '(font-lock-multiline t))
3688 (when org-hide-emphasis-markers
3689 (add-text-properties (match-end 4) (match-beginning 5)
3690 '(invisible org-link))
3691 (add-text-properties (match-beginning 3) (match-end 3)
3692 '(invisible org-link)))))
3693 (backward-char 1))
3694 rtn))
3696 (defun org-emphasize (&optional char)
3697 "Insert or change an emphasis, i.e. a font like bold or italic.
3698 If there is an active region, change that region to a new emphasis.
3699 If there is no region, just insert the marker characters and position
3700 the cursor between them.
3701 CHAR should be either the marker character, or the first character of the
3702 HTML tag associated with that emphasis. If CHAR is a space, the means
3703 to remove the emphasis of the selected region.
3704 If char is not given (for example in an interactive call) it
3705 will be prompted for."
3706 (interactive)
3707 (let ((eal org-emphasis-alist) e det
3708 (erc org-emphasis-regexp-components)
3709 (prompt "")
3710 (string "") beg end move tag c s)
3711 (if (org-region-active-p)
3712 (setq beg (region-beginning) end (region-end)
3713 string (buffer-substring beg end))
3714 (setq move t))
3716 (while (setq e (pop eal))
3717 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
3718 c (aref tag 0))
3719 (push (cons c (string-to-char (car e))) det)
3720 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
3721 (substring tag 1)))))
3722 (setq det (nreverse det))
3723 (unless char
3724 (message "%s" (concat "Emphasis marker or tag:" prompt))
3725 (setq char (read-char-exclusive)))
3726 (setq char (or (cdr (assoc char det)) char))
3727 (if (equal char ?\ )
3728 (setq s "" move nil)
3729 (unless (assoc (char-to-string char) org-emphasis-alist)
3730 (error "No such emphasis marker: \"%c\"" char))
3731 (setq s (char-to-string char)))
3732 (while (and (> (length string) 1)
3733 (equal (substring string 0 1) (substring string -1))
3734 (assoc (substring string 0 1) org-emphasis-alist))
3735 (setq string (substring string 1 -1)))
3736 (setq string (concat s string s))
3737 (if beg (delete-region beg end))
3738 (unless (or (bolp)
3739 (string-match (concat "[" (nth 0 erc) "\n]")
3740 (char-to-string (char-before (point)))))
3741 (insert " "))
3742 (unless (string-match (concat "[" (nth 1 erc) "\n]")
3743 (char-to-string (char-after (point))))
3744 (insert " ") (backward-char 1))
3745 (insert string)
3746 (and move (backward-char 1))))
3748 (defconst org-nonsticky-props
3749 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
3752 (defun org-activate-plain-links (limit)
3753 "Run through the buffer and add overlays to links."
3754 (catch 'exit
3755 (let (f)
3756 (while (re-search-forward org-plain-link-re limit t)
3757 (setq f (get-text-property (match-beginning 0) 'face))
3758 (if (or (eq f 'org-tag)
3759 (and (listp f) (memq 'org-tag f)))
3761 (add-text-properties (match-beginning 0) (match-end 0)
3762 (list 'mouse-face 'highlight
3763 'rear-nonsticky org-nonsticky-props
3764 'keymap org-mouse-map
3766 (throw 'exit t))))))
3768 (defun org-activate-code (limit)
3769 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
3770 (progn
3771 (remove-text-properties (match-beginning 0) (match-end 0)
3772 '(display t invisible t intangible t))
3773 t)))
3775 (defun org-activate-angle-links (limit)
3776 "Run through the buffer and add overlays to links."
3777 (if (re-search-forward org-angle-link-re limit t)
3778 (progn
3779 (add-text-properties (match-beginning 0) (match-end 0)
3780 (list 'mouse-face 'highlight
3781 'rear-nonsticky org-nonsticky-props
3782 'keymap org-mouse-map
3784 t)))
3786 (defun org-activate-footnote-links (limit)
3787 "Run through the buffer and add overlays to links."
3788 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
3789 limit t)
3790 (progn
3791 (add-text-properties (match-beginning 1) (match-end 1)
3792 (list 'mouse-face 'highlight
3793 'rear-nonsticky org-nonsticky-props
3794 'keymap org-mouse-map
3795 'help-echo
3796 (if (= (point-at-bol) (match-beginning 1))
3797 "Footnote definition"
3798 "Footnote reference")
3800 t)))
3802 (defun org-activate-bracket-links (limit)
3803 "Run through the buffer and add overlays to bracketed links."
3804 (if (re-search-forward org-bracket-link-regexp limit t)
3805 (let* ((help (concat "LINK: "
3806 (org-match-string-no-properties 1)))
3807 ;; FIXME: above we should remove the escapes.
3808 ;; but that requires another match, protecting match data,
3809 ;; a lot of overhead for font-lock.
3810 (ip (org-maybe-intangible
3811 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
3812 'keymap org-mouse-map 'mouse-face 'highlight
3813 'font-lock-multiline t 'help-echo help)))
3814 (vp (list 'rear-nonsticky org-nonsticky-props
3815 'keymap org-mouse-map 'mouse-face 'highlight
3816 ' font-lock-multiline t 'help-echo help)))
3817 ;; We need to remove the invisible property here. Table narrowing
3818 ;; may have made some of this invisible.
3819 (remove-text-properties (match-beginning 0) (match-end 0)
3820 '(invisible nil))
3821 (if (match-end 3)
3822 (progn
3823 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3824 (add-text-properties (match-beginning 3) (match-end 3) vp)
3825 (add-text-properties (match-end 3) (match-end 0) ip))
3826 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3827 (add-text-properties (match-beginning 1) (match-end 1) vp)
3828 (add-text-properties (match-end 1) (match-end 0) ip))
3829 t)))
3831 (defun org-activate-dates (limit)
3832 "Run through the buffer and add overlays to dates."
3833 (if (re-search-forward org-tsr-regexp-both limit t)
3834 (progn
3835 (add-text-properties (match-beginning 0) (match-end 0)
3836 (list 'mouse-face 'highlight
3837 'rear-nonsticky org-nonsticky-props
3838 'keymap org-mouse-map))
3839 (when org-display-custom-times
3840 (if (match-end 3)
3841 (org-display-custom-time (match-beginning 3) (match-end 3)))
3842 (org-display-custom-time (match-beginning 1) (match-end 1)))
3843 t)))
3845 (defvar org-target-link-regexp nil
3846 "Regular expression matching radio targets in plain text.")
3847 (make-variable-buffer-local 'org-target-link-regexp)
3848 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3849 "Regular expression matching a link target.")
3850 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3851 "Regular expression matching a radio target.")
3852 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
3853 "Regular expression matching any target.")
3855 (defun org-activate-target-links (limit)
3856 "Run through the buffer and add overlays to target matches."
3857 (when org-target-link-regexp
3858 (let ((case-fold-search t))
3859 (if (re-search-forward org-target-link-regexp limit t)
3860 (progn
3861 (add-text-properties (match-beginning 0) (match-end 0)
3862 (list 'mouse-face 'highlight
3863 'rear-nonsticky org-nonsticky-props
3864 'keymap org-mouse-map
3865 'help-echo "Radio target link"
3866 'org-linked-text t))
3867 t)))))
3869 (defun org-update-radio-target-regexp ()
3870 "Find all radio targets in this file and update the regular expression."
3871 (interactive)
3872 (when (memq 'radio org-activate-links)
3873 (setq org-target-link-regexp
3874 (org-make-target-link-regexp (org-all-targets 'radio)))
3875 (org-restart-font-lock)))
3877 (defun org-hide-wide-columns (limit)
3878 (let (s e)
3879 (setq s (text-property-any (point) (or limit (point-max))
3880 'org-cwidth t))
3881 (when s
3882 (setq e (next-single-property-change s 'org-cwidth))
3883 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
3884 (goto-char e)
3885 t)))
3887 (defvar org-latex-and-specials-regexp nil
3888 "Regular expression for highlighting export special stuff.")
3889 (defvar org-match-substring-regexp)
3890 (defvar org-match-substring-with-braces-regexp)
3891 (defvar org-export-html-special-string-regexps)
3893 (defun org-compute-latex-and-specials-regexp ()
3894 "Compute regular expression for stuff treated specially by exporters."
3895 (if (not org-highlight-latex-fragments-and-specials)
3896 (org-set-local 'org-latex-and-specials-regexp nil)
3897 (require 'org-exp)
3898 (let*
3899 ((matchers (plist-get org-format-latex-options :matchers))
3900 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
3901 org-latex-regexps)))
3902 (options (org-combine-plists (org-default-export-plist)
3903 (org-infile-export-plist)))
3904 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
3905 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
3906 (org-export-with-TeX-macros (plist-get options :TeX-macros))
3907 (org-export-html-expand (plist-get options :expand-quoted-html))
3908 (org-export-with-special-strings (plist-get options :special-strings))
3909 (re-sub
3910 (cond
3911 ((equal org-export-with-sub-superscripts '{})
3912 (list org-match-substring-with-braces-regexp))
3913 (org-export-with-sub-superscripts
3914 (list org-match-substring-regexp))
3915 (t nil)))
3916 (re-latex
3917 (if org-export-with-LaTeX-fragments
3918 (mapcar (lambda (x) (nth 1 x)) latexs)))
3919 (re-macros
3920 (if org-export-with-TeX-macros
3921 (list (concat "\\\\"
3922 (regexp-opt
3923 (append (mapcar 'car org-html-entities)
3924 (if (boundp 'org-latex-entities)
3925 org-latex-entities nil))
3926 'words))) ; FIXME
3928 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
3929 (re-special (if org-export-with-special-strings
3930 (mapcar (lambda (x) (car x))
3931 org-export-html-special-string-regexps)))
3932 (re-rest
3933 (delq nil
3934 (list
3935 (if org-export-html-expand "@<[^>\n]+>")
3936 ))))
3937 (org-set-local
3938 'org-latex-and-specials-regexp
3939 (mapconcat 'identity (append re-latex re-sub re-macros re-special
3940 re-rest) "\\|")))))
3942 (defun org-do-latex-and-special-faces (limit)
3943 "Run through the buffer and add overlays to links."
3944 (when org-latex-and-specials-regexp
3945 (let (rtn d)
3946 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
3947 limit t))
3948 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
3949 'face))
3950 '(org-code org-verbatim underline)))
3951 (progn
3952 (setq rtn t
3953 d (cond ((member (char-after (1+ (match-beginning 0)))
3954 '(?_ ?^)) 1)
3955 (t 0)))
3956 (font-lock-prepend-text-property
3957 (+ d (match-beginning 0)) (match-end 0)
3958 'face 'org-latex-and-export-specials)
3959 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
3960 '(font-lock-multiline t)))))
3961 rtn)))
3963 (defun org-restart-font-lock ()
3964 "Restart font-lock-mode, to force refontification."
3965 (when (and (boundp 'font-lock-mode) font-lock-mode)
3966 (font-lock-mode -1)
3967 (font-lock-mode 1)))
3969 (defun org-all-targets (&optional radio)
3970 "Return a list of all targets in this file.
3971 With optional argument RADIO, only find radio targets."
3972 (let ((re (if radio org-radio-target-regexp org-target-regexp))
3973 rtn)
3974 (save-excursion
3975 (goto-char (point-min))
3976 (while (re-search-forward re nil t)
3977 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
3978 rtn)))
3980 (defun org-make-target-link-regexp (targets)
3981 "Make regular expression matching all strings in TARGETS.
3982 The regular expression finds the targets also if there is a line break
3983 between words."
3984 (and targets
3985 (concat
3986 "\\<\\("
3987 (mapconcat
3988 (lambda (x)
3989 (while (string-match " +" x)
3990 (setq x (replace-match "\\s-+" t t x)))
3992 targets
3993 "\\|")
3994 "\\)\\>")))
3996 (defun org-activate-tags (limit)
3997 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
3998 (progn
3999 (add-text-properties (match-beginning 1) (match-end 1)
4000 (list 'mouse-face 'highlight
4001 'rear-nonsticky org-nonsticky-props
4002 'keymap org-mouse-map))
4003 t)))
4005 (defun org-outline-level ()
4006 (save-excursion
4007 (looking-at outline-regexp)
4008 (if (match-beginning 1)
4009 (+ (org-get-string-indentation (match-string 1)) 1000)
4010 (1- (- (match-end 0) (match-beginning 0))))))
4012 (defvar org-font-lock-keywords nil)
4014 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
4015 "Regular expression matching a property line.")
4017 (defvar org-font-lock-hook nil
4018 "Functions to be called for special font lock stuff.")
4020 (defun org-font-lock-hook (limit)
4021 (run-hook-with-args 'org-font-lock-hook limit))
4023 (defun org-set-font-lock-defaults ()
4024 (let* ((em org-fontify-emphasized-text)
4025 (lk org-activate-links)
4026 (org-font-lock-extra-keywords
4027 (list
4028 ;; Call the hook
4029 '(org-font-lock-hook)
4030 ;; Headlines
4031 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
4032 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
4033 ;; Table lines
4034 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4035 (1 'org-table t))
4036 ;; Table internals
4037 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4038 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4039 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4040 ;; Drawers
4041 (list org-drawer-regexp '(0 'org-special-keyword t))
4042 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4043 ;; Properties
4044 (list org-property-re
4045 '(1 'org-special-keyword t)
4046 '(3 'org-property-value t))
4047 (if org-format-transports-properties-p
4048 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
4049 ;; Links
4050 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4051 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4052 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
4053 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4054 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4055 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4056 (if (memq 'footnote lk) '(org-activate-footnote-links
4057 (0 'org-footnote t)))
4058 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4059 '(org-hide-wide-columns (0 nil append))
4060 ;; TODO lines
4061 (list (concat "^\\*+[ \t]+" org-todo-regexp)
4062 '(1 (org-get-todo-face 1) t))
4063 ;; DONE
4064 (if org-fontify-done-headline
4065 (list (concat "^[*]+ +\\<\\("
4066 (mapconcat 'regexp-quote org-done-keywords "\\|")
4067 "\\)\\(.*\\)")
4068 '(2 'org-headline-done t))
4069 nil)
4070 ;; Priorities
4071 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
4072 ;; Tags
4073 '(org-font-lock-add-tag-faces)
4074 ;; Special keywords
4075 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4076 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4077 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4078 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4079 ;; Emphasis
4080 (if em
4081 (if (featurep 'xemacs)
4082 '(org-do-emphasis-faces (0 nil append))
4083 '(org-do-emphasis-faces)))
4084 ;; Checkboxes
4085 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
4086 2 'bold prepend)
4087 (if org-provide-checkbox-statistics
4088 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4089 (0 (org-get-checkbox-statistics-face) t)))
4090 ;; Description list items
4091 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
4092 2 'bold prepend)
4093 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
4094 '(1 'org-archived prepend))
4095 ;; Specials
4096 '(org-do-latex-and-special-faces)
4097 ;; Code
4098 '(org-activate-code (1 'org-code t))
4099 ;; COMMENT
4100 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
4101 "\\|" org-quote-string "\\)\\>")
4102 '(1 'org-special-keyword t))
4103 '("^#.*" (0 'font-lock-comment-face t))
4105 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
4106 ;; Now set the full font-lock-keywords
4107 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
4108 (org-set-local 'font-lock-defaults
4109 '(org-font-lock-keywords t nil nil backward-paragraph))
4110 (kill-local-variable 'font-lock-keywords) nil))
4112 (defvar org-m nil)
4113 (defvar org-l nil)
4114 (defvar org-f nil)
4115 (defun org-get-level-face (n)
4116 "Get the right face for match N in font-lock matching of headlines."
4117 (setq org-l (- (match-end 2) (match-beginning 1) 1))
4118 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
4119 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
4120 (cond
4121 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
4122 ((eq n 2) org-f)
4123 (t (if org-level-color-stars-only nil org-f))))
4125 (defun org-get-todo-face (kwd)
4126 "Get the right face for a TODO keyword KWD.
4127 If KWD is a number, get the corresponding match group."
4128 (if (numberp kwd) (setq kwd (match-string kwd)))
4129 (or (cdr (assoc kwd org-todo-keyword-faces))
4130 (and (member kwd org-done-keywords) 'org-done)
4131 'org-todo))
4133 (defun org-font-lock-add-tag-faces (limit)
4134 "Add the special tag faces."
4135 (when (and org-tag-faces org-tags-special-faces-re)
4136 (while (re-search-forward org-tags-special-faces-re limit t)
4137 (add-text-properties (match-beginning 1) (match-end 1)
4138 (list 'face (org-get-tag-face 1)
4139 'font-lock-fontified t))
4140 (backward-char 1))))
4142 (defun org-get-tag-face (kwd)
4143 "Get the right face for a TODO keyword KWD.
4144 If KWD is a number, get the corresponding match group."
4145 (if (numberp kwd) (setq kwd (match-string kwd)))
4146 (or (cdr (assoc kwd org-tag-faces))
4147 'org-tag))
4149 (defun org-unfontify-region (beg end &optional maybe_loudly)
4150 "Remove fontification and activation overlays from links."
4151 (font-lock-default-unfontify-region beg end)
4152 (let* ((buffer-undo-list t)
4153 (inhibit-read-only t) (inhibit-point-motion-hooks t)
4154 (inhibit-modification-hooks t)
4155 deactivate-mark buffer-file-name buffer-file-truename)
4156 (remove-text-properties beg end
4157 '(mouse-face t keymap t org-linked-text t
4158 invisible t intangible t))))
4160 ;;;; Visibility cycling, including org-goto and indirect buffer
4162 ;;; Cycling
4164 (defvar org-cycle-global-status nil)
4165 (make-variable-buffer-local 'org-cycle-global-status)
4166 (defvar org-cycle-subtree-status nil)
4167 (make-variable-buffer-local 'org-cycle-subtree-status)
4169 ;;;###autoload
4170 (defun org-cycle (&optional arg)
4171 "Visibility cycling for Org-mode.
4173 - When this function is called with a prefix argument, rotate the entire
4174 buffer through 3 states (global cycling)
4175 1. OVERVIEW: Show only top-level headlines.
4176 2. CONTENTS: Show all headlines of all levels, but no body text.
4177 3. SHOW ALL: Show everything.
4178 When called with two C-u C-u prefixes, switch to the startup visibility,
4179 determined by the variable `org-startup-folded', and by any VISIBILITY
4180 properties in the buffer.
4181 When called with three C-u C-u C-u prefixed, show the entire buffer,
4182 including drawers.
4184 - When point is at the beginning of a headline, rotate the subtree started
4185 by this line through 3 different states (local cycling)
4186 1. FOLDED: Only the main headline is shown.
4187 2. CHILDREN: The main headline and the direct children are shown.
4188 From this state, you can move to one of the children
4189 and zoom in further.
4190 3. SUBTREE: Show the entire subtree, including body text.
4192 - When there is a numeric prefix, go up to a heading with level ARG, do
4193 a `show-subtree' and return to the previous cursor position. If ARG
4194 is negative, go up that many levels.
4196 - When point is not at the beginning of a headline, execute the global
4197 binding for TAB, which is re-indenting the line. See the option
4198 `org-cycle-emulate-tab' for details.
4200 - Special case: if point is at the beginning of the buffer and there is
4201 no headline in line 1, this function will act as if called with prefix arg.
4202 But only if also the variable `org-cycle-global-at-bob' is t."
4203 (interactive "P")
4204 (org-load-modules-maybe)
4205 (let* ((outline-regexp
4206 (if (and (org-mode-p) org-cycle-include-plain-lists)
4207 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
4208 outline-regexp))
4209 (bob-special (and org-cycle-global-at-bob (bobp)
4210 (not (looking-at outline-regexp))))
4211 (org-cycle-hook
4212 (if bob-special
4213 (delq 'org-optimize-window-after-visibility-change
4214 (copy-sequence org-cycle-hook))
4215 org-cycle-hook))
4216 (pos (point)))
4218 (if (or bob-special (equal arg '(4)))
4219 ;; special case: use global cycling
4220 (setq arg t))
4222 (cond
4224 ((equal arg '(16))
4225 (org-set-startup-visibility)
4226 (message "Startup visibility, plus VISIBILITY properties"))
4228 ((equal arg '(64))
4229 (show-all)
4230 (message "Entire buffer visible, including drawers"))
4232 ((org-at-table-p 'any)
4233 ;; Enter the table or move to the next field in the table
4234 (or (org-table-recognize-table.el)
4235 (progn
4236 (if arg (org-table-edit-field t)
4237 (org-table-justify-field-maybe)
4238 (call-interactively 'org-table-next-field)))))
4240 ((eq arg t) ;; Global cycling
4242 (cond
4243 ((and (eq last-command this-command)
4244 (eq org-cycle-global-status 'overview))
4245 ;; We just created the overview - now do table of contents
4246 ;; This can be slow in very large buffers, so indicate action
4247 (message "CONTENTS...")
4248 (org-content)
4249 (message "CONTENTS...done")
4250 (setq org-cycle-global-status 'contents)
4251 (run-hook-with-args 'org-cycle-hook 'contents))
4253 ((and (eq last-command this-command)
4254 (eq org-cycle-global-status 'contents))
4255 ;; We just showed the table of contents - now show everything
4256 (show-all)
4257 (message "SHOW ALL")
4258 (setq org-cycle-global-status 'all)
4259 (run-hook-with-args 'org-cycle-hook 'all))
4262 ;; Default action: go to overview
4263 (org-overview)
4264 (message "OVERVIEW")
4265 (setq org-cycle-global-status 'overview)
4266 (run-hook-with-args 'org-cycle-hook 'overview))))
4268 ((and org-drawers org-drawer-regexp
4269 (save-excursion
4270 (beginning-of-line 1)
4271 (looking-at org-drawer-regexp)))
4272 ;; Toggle block visibility
4273 (org-flag-drawer
4274 (not (get-char-property (match-end 0) 'invisible))))
4276 ((integerp arg)
4277 ;; Show-subtree, ARG levels up from here.
4278 (save-excursion
4279 (org-back-to-heading)
4280 (outline-up-heading (if (< arg 0) (- arg)
4281 (- (funcall outline-level) arg)))
4282 (org-show-subtree)))
4284 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4285 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4286 ;; At a heading: rotate between three different views
4287 (org-back-to-heading)
4288 (let ((goal-column 0) eoh eol eos)
4289 ;; First, some boundaries
4290 (save-excursion
4291 (org-back-to-heading)
4292 (save-excursion
4293 (beginning-of-line 2)
4294 (while (and (not (eobp)) ;; this is like `next-line'
4295 (get-char-property (1- (point)) 'invisible))
4296 (beginning-of-line 2)) (setq eol (point)))
4297 (outline-end-of-heading) (setq eoh (point))
4298 (org-end-of-subtree t)
4299 (unless (eobp)
4300 (skip-chars-forward " \t\n")
4301 (beginning-of-line 1) ; in case this is an item
4303 (setq eos (1- (point))))
4304 ;; Find out what to do next and set `this-command'
4305 (cond
4306 ((= eos eoh)
4307 ;; Nothing is hidden behind this heading
4308 (message "EMPTY ENTRY")
4309 (setq org-cycle-subtree-status nil)
4310 (save-excursion
4311 (goto-char eos)
4312 (outline-next-heading)
4313 (if (org-invisible-p) (org-flag-heading nil))))
4314 ((or (>= eol eos)
4315 (not (string-match "\\S-" (buffer-substring eol eos))))
4316 ;; Entire subtree is hidden in one line: open it
4317 (org-show-entry)
4318 (show-children)
4319 (message "CHILDREN")
4320 (save-excursion
4321 (goto-char eos)
4322 (outline-next-heading)
4323 (if (org-invisible-p) (org-flag-heading nil)))
4324 (setq org-cycle-subtree-status 'children)
4325 (run-hook-with-args 'org-cycle-hook 'children))
4326 ((and (eq last-command this-command)
4327 (eq org-cycle-subtree-status 'children))
4328 ;; We just showed the children, now show everything.
4329 (org-show-subtree)
4330 (message "SUBTREE")
4331 (setq org-cycle-subtree-status 'subtree)
4332 (run-hook-with-args 'org-cycle-hook 'subtree))
4334 ;; Default action: hide the subtree.
4335 (hide-subtree)
4336 (message "FOLDED")
4337 (setq org-cycle-subtree-status 'folded)
4338 (run-hook-with-args 'org-cycle-hook 'folded)))))
4340 ;; TAB emulation and template completion
4341 (buffer-read-only (org-back-to-heading))
4343 ((org-try-structure-completion))
4345 ((org-try-cdlatex-tab))
4347 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4348 (or (not (bolp))
4349 (not (looking-at outline-regexp))))
4350 (call-interactively (global-key-binding "\t")))
4352 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4353 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4354 (or (and (eq org-cycle-emulate-tab 'white)
4355 (= (match-end 0) (point-at-eol)))
4356 (and (eq org-cycle-emulate-tab 'whitestart)
4357 (>= (match-end 0) pos))))
4359 (eq org-cycle-emulate-tab t))
4360 (call-interactively (global-key-binding "\t")))
4362 (t (save-excursion
4363 (org-back-to-heading)
4364 (org-cycle))))))
4366 ;;;###autoload
4367 (defun org-global-cycle (&optional arg)
4368 "Cycle the global visibility. For details see `org-cycle'.
4369 With C-u prefix arg, switch to startup visibility.
4370 With a numeric prefix, show all headlines up to that level."
4371 (interactive "P")
4372 (let ((org-cycle-include-plain-lists
4373 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4374 (cond
4375 ((integerp arg)
4376 (show-all)
4377 (hide-sublevels arg)
4378 (setq org-cycle-global-status 'contents))
4379 ((equal arg '(4))
4380 (org-set-startup-visibility)
4381 (message "Startup visibility, plus VISIBILITY properties."))
4383 (org-cycle '(4))))))
4385 (defun org-set-startup-visibility ()
4386 "Set the visibility required by startup options and properties."
4387 (cond
4388 ((eq org-startup-folded t)
4389 (org-cycle '(4)))
4390 ((eq org-startup-folded 'content)
4391 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4392 (org-cycle '(4)) (org-cycle '(4)))))
4393 (org-set-visibility-according-to-property 'no-cleanup)
4394 (org-cycle-hide-archived-subtrees 'all)
4395 (org-cycle-hide-drawers 'all)
4396 (org-cycle-show-empty-lines 'all))
4398 (defun org-set-visibility-according-to-property (&optional no-cleanup)
4399 "Switch subtree visibilities according to :VISIBILITY: property."
4400 (interactive)
4401 (let (state)
4402 (save-excursion
4403 (goto-char (point-min))
4404 (while (re-search-forward
4405 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
4406 nil t)
4407 (setq state (match-string 1))
4408 (save-excursion
4409 (org-back-to-heading t)
4410 (hide-subtree)
4411 (org-reveal)
4412 (cond
4413 ((equal state '("fold" "folded"))
4414 (hide-subtree))
4415 ((equal state "children")
4416 (org-show-hidden-entry)
4417 (show-children))
4418 ((equal state "content")
4419 (save-excursion
4420 (save-restriction
4421 (org-narrow-to-subtree)
4422 (org-content))))
4423 ((member state '("all" "showall"))
4424 (show-subtree)))))
4425 (unless no-cleanup
4426 (org-cycle-hide-archived-subtrees 'all)
4427 (org-cycle-hide-drawers 'all)
4428 (org-cycle-show-empty-lines 'all)))))
4430 (defun org-overview ()
4431 "Switch to overview mode, showing only top-level headlines.
4432 Really, this shows all headlines with level equal or greater than the level
4433 of the first headline in the buffer. This is important, because if the
4434 first headline is not level one, then (hide-sublevels 1) gives confusing
4435 results."
4436 (interactive)
4437 (let ((level (save-excursion
4438 (goto-char (point-min))
4439 (if (re-search-forward (concat "^" outline-regexp) nil t)
4440 (progn
4441 (goto-char (match-beginning 0))
4442 (funcall outline-level))))))
4443 (and level (hide-sublevels level))))
4445 (defun org-content (&optional arg)
4446 "Show all headlines in the buffer, like a table of contents.
4447 With numerical argument N, show content up to level N."
4448 (interactive "P")
4449 (save-excursion
4450 ;; Visit all headings and show their offspring
4451 (and (integerp arg) (org-overview))
4452 (goto-char (point-max))
4453 (catch 'exit
4454 (while (and (progn (condition-case nil
4455 (outline-previous-visible-heading 1)
4456 (error (goto-char (point-min))))
4458 (looking-at outline-regexp))
4459 (if (integerp arg)
4460 (show-children (1- arg))
4461 (show-branches))
4462 (if (bobp) (throw 'exit nil))))))
4465 (defun org-optimize-window-after-visibility-change (state)
4466 "Adjust the window after a change in outline visibility.
4467 This function is the default value of the hook `org-cycle-hook'."
4468 (when (get-buffer-window (current-buffer))
4469 (cond
4470 ; ((eq state 'overview) (org-first-headline-recenter 1))
4471 ; ((eq state 'overview) (org-beginning-of-line))
4472 ((eq state 'content) nil)
4473 ((eq state 'all) nil)
4474 ((eq state 'folded) nil)
4475 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4476 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4478 (defun org-compact-display-after-subtree-move ()
4479 (let (beg end)
4480 (save-excursion
4481 (if (org-up-heading-safe)
4482 (progn
4483 (hide-subtree)
4484 (show-entry)
4485 (show-children)
4486 (org-cycle-show-empty-lines 'children)
4487 (org-cycle-hide-drawers 'children))
4488 (org-overview)))))
4490 (defun org-cycle-show-empty-lines (state)
4491 "Show empty lines above all visible headlines.
4492 The region to be covered depends on STATE when called through
4493 `org-cycle-hook'. Lisp program can use t for STATE to get the
4494 entire buffer covered. Note that an empty line is only shown if there
4495 are at least `org-cycle-separator-lines' empty lines before the headline."
4496 (when (> org-cycle-separator-lines 0)
4497 (save-excursion
4498 (let* ((n org-cycle-separator-lines)
4499 (re (cond
4500 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
4501 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
4502 (t (let ((ns (number-to-string (- n 2))))
4503 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
4504 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
4505 beg end)
4506 (cond
4507 ((memq state '(overview contents t))
4508 (setq beg (point-min) end (point-max)))
4509 ((memq state '(children folded))
4510 (setq beg (point) end (progn (org-end-of-subtree t t)
4511 (beginning-of-line 2)
4512 (point)))))
4513 (when beg
4514 (goto-char beg)
4515 (while (re-search-forward re end t)
4516 (if (not (get-char-property (match-end 1) 'invisible))
4517 (outline-flag-region
4518 (match-beginning 1) (match-end 1) nil)))))))
4519 ;; Never hide empty lines at the end of the file.
4520 (save-excursion
4521 (goto-char (point-max))
4522 (outline-previous-heading)
4523 (outline-end-of-heading)
4524 (if (and (looking-at "[ \t\n]+")
4525 (= (match-end 0) (point-max)))
4526 (outline-flag-region (point) (match-end 0) nil))))
4528 (defun org-show-empty-lines-in-parent ()
4529 "Move to the parent and re-show empty lines before visible headlines."
4530 (save-excursion
4531 (let ((context (if (org-up-heading-safe) 'children 'overview)))
4532 (org-cycle-show-empty-lines context))))
4534 (defun org-cycle-hide-drawers (state)
4535 "Re-hide all drawers after a visibility state change."
4536 (when (and (org-mode-p)
4537 (not (memq state '(overview folded))))
4538 (save-excursion
4539 (let* ((globalp (memq state '(contents all)))
4540 (beg (if globalp (point-min) (point)))
4541 (end (if globalp (point-max) (org-end-of-subtree t))))
4542 (goto-char beg)
4543 (while (re-search-forward org-drawer-regexp end t)
4544 (org-flag-drawer t))))))
4546 (defun org-flag-drawer (flag)
4547 (save-excursion
4548 (beginning-of-line 1)
4549 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
4550 (let ((b (match-end 0))
4551 (outline-regexp org-outline-regexp))
4552 (if (re-search-forward
4553 "^[ \t]*:END:"
4554 (save-excursion (outline-next-heading) (point)) t)
4555 (outline-flag-region b (point-at-eol) flag)
4556 (error ":END: line missing"))))))
4558 (defun org-subtree-end-visible-p ()
4559 "Is the end of the current subtree visible?"
4560 (pos-visible-in-window-p
4561 (save-excursion (org-end-of-subtree t) (point))))
4563 (defun org-first-headline-recenter (&optional N)
4564 "Move cursor to the first headline and recenter the headline.
4565 Optional argument N means, put the headline into the Nth line of the window."
4566 (goto-char (point-min))
4567 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4568 (beginning-of-line)
4569 (recenter (prefix-numeric-value N))))
4571 ;;; Org-goto
4573 (defvar org-goto-window-configuration nil)
4574 (defvar org-goto-marker nil)
4575 (defvar org-goto-map
4576 (let ((map (make-sparse-keymap)))
4577 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
4578 (while (setq cmd (pop cmds))
4579 (substitute-key-definition cmd cmd map global-map)))
4580 (suppress-keymap map)
4581 (org-defkey map "\C-m" 'org-goto-ret)
4582 (org-defkey map [(return)] 'org-goto-ret)
4583 (org-defkey map [(left)] 'org-goto-left)
4584 (org-defkey map [(right)] 'org-goto-right)
4585 (org-defkey map [(control ?g)] 'org-goto-quit)
4586 (org-defkey map "\C-i" 'org-cycle)
4587 (org-defkey map [(tab)] 'org-cycle)
4588 (org-defkey map [(down)] 'outline-next-visible-heading)
4589 (org-defkey map [(up)] 'outline-previous-visible-heading)
4590 (if org-goto-auto-isearch
4591 (if (fboundp 'define-key-after)
4592 (define-key-after map [t] 'org-goto-local-auto-isearch)
4593 nil)
4594 (org-defkey map "q" 'org-goto-quit)
4595 (org-defkey map "n" 'outline-next-visible-heading)
4596 (org-defkey map "p" 'outline-previous-visible-heading)
4597 (org-defkey map "f" 'outline-forward-same-level)
4598 (org-defkey map "b" 'outline-backward-same-level)
4599 (org-defkey map "u" 'outline-up-heading))
4600 (org-defkey map "/" 'org-occur)
4601 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4602 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4603 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
4604 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
4605 (org-defkey map "\C-c\C-u" 'outline-up-heading)
4606 map))
4608 (defconst org-goto-help
4609 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4610 RET=jump to location [Q]uit and return to previous location
4611 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4613 (defvar org-goto-start-pos) ; dynamically scoped parameter
4615 ;; FIXME: Docstring doe not mention both interfaces
4616 (defun org-goto (&optional alternative-interface)
4617 "Look up a different location in the current file, keeping current visibility.
4619 When you want look-up or go to a different location in a document, the
4620 fastest way is often to fold the entire buffer and then dive into the tree.
4621 This method has the disadvantage, that the previous location will be folded,
4622 which may not be what you want.
4624 This command works around this by showing a copy of the current buffer
4625 in an indirect buffer, in overview mode. You can dive into the tree in
4626 that copy, use org-occur and incremental search to find a location.
4627 When pressing RET or `Q', the command returns to the original buffer in
4628 which the visibility is still unchanged. After RET is will also jump to
4629 the location selected in the indirect buffer and expose the
4630 the headline hierarchy above."
4631 (interactive "P")
4632 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
4633 (org-refile-use-outline-path t)
4634 (interface
4635 (if (not alternative-interface)
4636 org-goto-interface
4637 (if (eq org-goto-interface 'outline)
4638 'outline-path-completion
4639 'outline)))
4640 (org-goto-start-pos (point))
4641 (selected-point
4642 (if (eq interface 'outline)
4643 (car (org-get-location (current-buffer) org-goto-help))
4644 (nth 3 (org-refile-get-location "Goto: ")))))
4645 (if selected-point
4646 (progn
4647 (org-mark-ring-push org-goto-start-pos)
4648 (goto-char selected-point)
4649 (if (or (org-invisible-p) (org-invisible-p2))
4650 (org-show-context 'org-goto)))
4651 (message "Quit"))))
4653 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
4654 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
4655 (defvar org-goto-local-auto-isearch-map) ; defined below
4657 (defun org-get-location (buf help)
4658 "Let the user select a location in the Org-mode buffer BUF.
4659 This function uses a recursive edit. It returns the selected position
4660 or nil."
4661 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
4662 (isearch-hide-immediately nil)
4663 (isearch-search-fun-function
4664 (lambda () 'org-goto-local-search-headings))
4665 (org-goto-selected-point org-goto-exit-command))
4666 (save-excursion
4667 (save-window-excursion
4668 (delete-other-windows)
4669 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
4670 (switch-to-buffer
4671 (condition-case nil
4672 (make-indirect-buffer (current-buffer) "*org-goto*")
4673 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
4674 (with-output-to-temp-buffer "*Help*"
4675 (princ help))
4676 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
4677 (setq buffer-read-only nil)
4678 (let ((org-startup-truncated t)
4679 (org-startup-folded nil)
4680 (org-startup-align-all-tables nil))
4681 (org-mode)
4682 (org-overview))
4683 (setq buffer-read-only t)
4684 (if (and (boundp 'org-goto-start-pos)
4685 (integer-or-marker-p org-goto-start-pos))
4686 (let ((org-show-hierarchy-above t)
4687 (org-show-siblings t)
4688 (org-show-following-heading t))
4689 (goto-char org-goto-start-pos)
4690 (and (org-invisible-p) (org-show-context)))
4691 (goto-char (point-min)))
4692 (org-beginning-of-line)
4693 (message "Select location and press RET")
4694 (use-local-map org-goto-map)
4695 (recursive-edit)
4697 (kill-buffer "*org-goto*")
4698 (cons org-goto-selected-point org-goto-exit-command)))
4700 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
4701 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
4702 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
4703 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
4705 (defun org-goto-local-search-headings (string bound noerror)
4706 "Search and make sure that any matches are in headlines."
4707 (catch 'return
4708 (while (if isearch-forward
4709 (search-forward string bound noerror)
4710 (search-backward string bound noerror))
4711 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
4712 (and (member :headline context)
4713 (not (member :tags context))))
4714 (throw 'return (point))))))
4716 (defun org-goto-local-auto-isearch ()
4717 "Start isearch."
4718 (interactive)
4719 (goto-char (point-min))
4720 (let ((keys (this-command-keys)))
4721 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
4722 (isearch-mode t)
4723 (isearch-process-search-char (string-to-char keys)))))
4725 (defun org-goto-ret (&optional arg)
4726 "Finish `org-goto' by going to the new location."
4727 (interactive "P")
4728 (setq org-goto-selected-point (point)
4729 org-goto-exit-command 'return)
4730 (throw 'exit nil))
4732 (defun org-goto-left ()
4733 "Finish `org-goto' by going to the new location."
4734 (interactive)
4735 (if (org-on-heading-p)
4736 (progn
4737 (beginning-of-line 1)
4738 (setq org-goto-selected-point (point)
4739 org-goto-exit-command 'left)
4740 (throw 'exit nil))
4741 (error "Not on a heading")))
4743 (defun org-goto-right ()
4744 "Finish `org-goto' by going to the new location."
4745 (interactive)
4746 (if (org-on-heading-p)
4747 (progn
4748 (setq org-goto-selected-point (point)
4749 org-goto-exit-command 'right)
4750 (throw 'exit nil))
4751 (error "Not on a heading")))
4753 (defun org-goto-quit ()
4754 "Finish `org-goto' without cursor motion."
4755 (interactive)
4756 (setq org-goto-selected-point nil)
4757 (setq org-goto-exit-command 'quit)
4758 (throw 'exit nil))
4760 ;;; Indirect buffer display of subtrees
4762 (defvar org-indirect-dedicated-frame nil
4763 "This is the frame being used for indirect tree display.")
4764 (defvar org-last-indirect-buffer nil)
4766 (defun org-tree-to-indirect-buffer (&optional arg)
4767 "Create indirect buffer and narrow it to current subtree.
4768 With numerical prefix ARG, go up to this level and then take that tree.
4769 If ARG is negative, go up that many levels.
4770 If `org-indirect-buffer-display' is not `new-frame', the command removes the
4771 indirect buffer previously made with this command, to avoid proliferation of
4772 indirect buffers. However, when you call the command with a `C-u' prefix, or
4773 when `org-indirect-buffer-display' is `new-frame', the last buffer
4774 is kept so that you can work with several indirect buffers at the same time.
4775 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
4776 requests that a new frame be made for the new buffer, so that the dedicated
4777 frame is not changed."
4778 (interactive "P")
4779 (let ((cbuf (current-buffer))
4780 (cwin (selected-window))
4781 (pos (point))
4782 beg end level heading ibuf)
4783 (save-excursion
4784 (org-back-to-heading t)
4785 (when (numberp arg)
4786 (setq level (org-outline-level))
4787 (if (< arg 0) (setq arg (+ level arg)))
4788 (while (> (setq level (org-outline-level)) arg)
4789 (outline-up-heading 1 t)))
4790 (setq beg (point)
4791 heading (org-get-heading))
4792 (org-end-of-subtree t) (setq end (point)))
4793 (if (and (buffer-live-p org-last-indirect-buffer)
4794 (not (eq org-indirect-buffer-display 'new-frame))
4795 (not arg))
4796 (kill-buffer org-last-indirect-buffer))
4797 (setq ibuf (org-get-indirect-buffer cbuf)
4798 org-last-indirect-buffer ibuf)
4799 (cond
4800 ((or (eq org-indirect-buffer-display 'new-frame)
4801 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
4802 (select-frame (make-frame))
4803 (delete-other-windows)
4804 (switch-to-buffer ibuf)
4805 (org-set-frame-title heading))
4806 ((eq org-indirect-buffer-display 'dedicated-frame)
4807 (raise-frame
4808 (select-frame (or (and org-indirect-dedicated-frame
4809 (frame-live-p org-indirect-dedicated-frame)
4810 org-indirect-dedicated-frame)
4811 (setq org-indirect-dedicated-frame (make-frame)))))
4812 (delete-other-windows)
4813 (switch-to-buffer ibuf)
4814 (org-set-frame-title (concat "Indirect: " heading)))
4815 ((eq org-indirect-buffer-display 'current-window)
4816 (switch-to-buffer ibuf))
4817 ((eq org-indirect-buffer-display 'other-window)
4818 (pop-to-buffer ibuf))
4819 (t (error "Invalid value.")))
4820 (if (featurep 'xemacs)
4821 (save-excursion (org-mode) (turn-on-font-lock)))
4822 (narrow-to-region beg end)
4823 (show-all)
4824 (goto-char pos)
4825 (and (window-live-p cwin) (select-window cwin))))
4827 (defun org-get-indirect-buffer (&optional buffer)
4828 (setq buffer (or buffer (current-buffer)))
4829 (let ((n 1) (base (buffer-name buffer)) bname)
4830 (while (buffer-live-p
4831 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
4832 (setq n (1+ n)))
4833 (condition-case nil
4834 (make-indirect-buffer buffer bname 'clone)
4835 (error (make-indirect-buffer buffer bname)))))
4837 (defun org-set-frame-title (title)
4838 "Set the title of the current frame to the string TITLE."
4839 ;; FIXME: how to name a single frame in XEmacs???
4840 (unless (featurep 'xemacs)
4841 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
4843 ;;;; Structure editing
4845 ;;; Inserting headlines
4847 (defun org-previous-line-empty-p ()
4848 (save-excursion
4849 (and (not (bobp))
4850 (or (beginning-of-line 0) t)
4851 (save-match-data
4852 (looking-at "[ \t]*$")))))
4854 (defun org-insert-heading (&optional force-heading)
4855 "Insert a new heading or item with same depth at point.
4856 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
4857 If point is at the beginning of a headline, insert a sibling before the
4858 current headline. If point is not at the beginning, do not split the line,
4859 but create the new headline after the current line."
4860 (interactive "P")
4861 (if (= (buffer-size) 0)
4862 (insert "\n* ")
4863 (when (or force-heading (not (org-insert-item)))
4864 (let* ((empty-line-p nil)
4865 (head (save-excursion
4866 (condition-case nil
4867 (progn
4868 (org-back-to-heading)
4869 (setq empty-line-p (org-previous-line-empty-p))
4870 (match-string 0))
4871 (error "*"))))
4872 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
4873 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
4874 pos hide-previous previous-pos)
4875 (cond
4876 ((and (org-on-heading-p) (bolp)
4877 (or (bobp)
4878 (save-excursion (backward-char 1) (not (org-invisible-p)))))
4879 ;; insert before the current line
4880 (open-line (if blank 2 1)))
4881 ((and (bolp)
4882 (or (bobp)
4883 (save-excursion
4884 (backward-char 1) (not (org-invisible-p)))))
4885 ;; insert right here
4886 nil)
4888 ;; somewhere in the line
4889 (save-excursion
4890 (setq previous-pos (point-at-bol))
4891 (end-of-line)
4892 (setq hide-previous (org-invisible-p)))
4893 (and org-insert-heading-respect-content (org-show-subtree))
4894 (let ((split
4895 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
4896 (save-excursion
4897 (let ((p (point)))
4898 (goto-char (point-at-bol))
4899 (and (looking-at org-complex-heading-regexp)
4900 (> p (match-beginning 4)))))))
4901 tags pos)
4902 (cond
4903 (org-insert-heading-respect-content
4904 (org-end-of-subtree nil t)
4905 (or (bolp) (newline))
4906 (or (org-previous-line-empty-p)
4907 (and blank (newline)))
4908 (open-line 1))
4909 ((org-on-heading-p)
4910 (when hide-previous
4911 (show-children)
4912 (org-show-entry))
4913 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4914 (setq tags (and (match-end 2) (match-string 2)))
4915 (and (match-end 1)
4916 (delete-region (match-beginning 1) (match-end 1)))
4917 (setq pos (point-at-bol))
4918 (or split (end-of-line 1))
4919 (delete-horizontal-space)
4920 (newline (if blank 2 1))
4921 (when tags
4922 (save-excursion
4923 (goto-char pos)
4924 (end-of-line 1)
4925 (insert " " tags)
4926 (org-set-tags nil 'align))))
4928 (or split (end-of-line 1))
4929 (newline (if blank 2 1)))))))
4930 (insert head) (just-one-space)
4931 (setq pos (point))
4932 (end-of-line 1)
4933 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
4934 (when (and org-insert-heading-respect-content hide-previous)
4935 (save-excursion
4936 (goto-char previous-pos)
4937 (hide-subtree)))
4938 (run-hooks 'org-insert-heading-hook)))))
4940 (defun org-get-heading (&optional no-tags)
4941 "Return the heading of the current entry, without the stars."
4942 (save-excursion
4943 (org-back-to-heading t)
4944 (if (looking-at
4945 (if no-tags
4946 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
4947 "\\*+[ \t]+\\([^\r\n]*\\)"))
4948 (match-string 1) "")))
4950 (defun org-heading-components ()
4951 "Return the components of the current heading.
4952 This is a list with the following elements:
4953 - the level as an integer
4954 - the reduced level, different if `org-odd-levels-only' is set.
4955 - the TODO keyword, or nil
4956 - the priority character, like ?A, or nil if no priority is given
4957 - the headline text itself, or the tags string if no headline text
4958 - the tags string, or nil."
4959 (save-excursion
4960 (org-back-to-heading t)
4961 (if (looking-at org-complex-heading-regexp)
4962 (list (length (match-string 1))
4963 (org-reduced-level (length (match-string 1)))
4964 (org-match-string-no-properties 2)
4965 (and (match-end 3) (aref (match-string 3) 2))
4966 (org-match-string-no-properties 4)
4967 (org-match-string-no-properties 5)))))
4969 (defun org-insert-heading-after-current ()
4970 "Insert a new heading with same level as current, after current subtree."
4971 (interactive)
4972 (org-back-to-heading)
4973 (org-insert-heading)
4974 (org-move-subtree-down)
4975 (end-of-line 1))
4977 (defun org-insert-heading-respect-content ()
4978 (interactive)
4979 (let ((org-insert-heading-respect-content t))
4980 (org-insert-heading t)))
4982 (defun org-insert-todo-heading-respect-content (&optional force-state)
4983 (interactive "P")
4984 (let ((org-insert-heading-respect-content t))
4985 (org-insert-todo-heading force-state t)))
4987 (defun org-insert-todo-heading (arg &optional force-heading)
4988 "Insert a new heading with the same level and TODO state as current heading.
4989 If the heading has no TODO state, or if the state is DONE, use the first
4990 state (TODO by default). Also with prefix arg, force first state."
4991 (interactive "P")
4992 (when (or force-heading (not (org-insert-item 'checkbox)))
4993 (org-insert-heading force-heading)
4994 (save-excursion
4995 (org-back-to-heading)
4996 (outline-previous-heading)
4997 (looking-at org-todo-line-regexp))
4998 (if (or arg
4999 (not (match-beginning 2))
5000 (member (match-string 2) org-done-keywords))
5001 (insert (car org-todo-keywords-1) " ")
5002 (insert (match-string 2) " "))
5003 (when org-provide-todo-statistics
5004 (org-update-parent-todo-statistics))))
5006 (defun org-insert-subheading (arg)
5007 "Insert a new subheading and demote it.
5008 Works for outline headings and for plain lists alike."
5009 (interactive "P")
5010 (org-insert-heading arg)
5011 (cond
5012 ((org-on-heading-p) (org-do-demote))
5013 ((org-at-item-p) (org-indent-item 1))))
5015 (defun org-insert-todo-subheading (arg)
5016 "Insert a new subheading with TODO keyword or checkbox and demote it.
5017 Works for outline headings and for plain lists alike."
5018 (interactive "P")
5019 (org-insert-todo-heading arg)
5020 (cond
5021 ((org-on-heading-p) (org-do-demote))
5022 ((org-at-item-p) (org-indent-item 1))))
5024 ;;; Promotion and Demotion
5026 (defun org-promote-subtree ()
5027 "Promote the entire subtree.
5028 See also `org-promote'."
5029 (interactive)
5030 (save-excursion
5031 (org-map-tree 'org-promote))
5032 (org-fix-position-after-promote))
5034 (defun org-demote-subtree ()
5035 "Demote the entire subtree. See `org-demote'.
5036 See also `org-promote'."
5037 (interactive)
5038 (save-excursion
5039 (org-map-tree 'org-demote))
5040 (org-fix-position-after-promote))
5043 (defun org-do-promote ()
5044 "Promote the current heading higher up the tree.
5045 If the region is active in `transient-mark-mode', promote all headings
5046 in the region."
5047 (interactive)
5048 (save-excursion
5049 (if (org-region-active-p)
5050 (org-map-region 'org-promote (region-beginning) (region-end))
5051 (org-promote)))
5052 (org-fix-position-after-promote))
5054 (defun org-do-demote ()
5055 "Demote the current heading lower down the tree.
5056 If the region is active in `transient-mark-mode', demote all headings
5057 in the region."
5058 (interactive)
5059 (save-excursion
5060 (if (org-region-active-p)
5061 (org-map-region 'org-demote (region-beginning) (region-end))
5062 (org-demote)))
5063 (org-fix-position-after-promote))
5065 (defun org-fix-position-after-promote ()
5066 "Make sure that after pro/demotion cursor position is right."
5067 (let ((pos (point)))
5068 (when (save-excursion
5069 (beginning-of-line 1)
5070 (looking-at org-todo-line-regexp)
5071 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
5072 (cond ((eobp) (insert " "))
5073 ((eolp) (insert " "))
5074 ((equal (char-after) ?\ ) (forward-char 1))))))
5076 (defun org-reduced-level (l)
5077 "Compute the effective level of a heading.
5078 This takes into account the setting of `org-odd-levels-only'."
5079 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
5081 (defun org-get-valid-level (level &optional change)
5082 "Rectify a level change under the influence of `org-odd-levels-only'
5083 LEVEL is a current level, CHANGE is by how much the level should be
5084 modified. Even if CHANGE is nil, LEVEL may be returned modified because
5085 even level numbers will become the next higher odd number."
5086 (if org-odd-levels-only
5087 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
5088 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
5089 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
5090 (max 1 (+ level change))))
5092 (if (boundp 'define-obsolete-function-alias)
5093 (if (or (featurep 'xemacs) (< emacs-major-version 23))
5094 (define-obsolete-function-alias 'org-get-legal-level
5095 'org-get-valid-level)
5096 (define-obsolete-function-alias 'org-get-legal-level
5097 'org-get-valid-level "23.1")))
5099 (defun org-promote ()
5100 "Promote the current heading higher up the tree.
5101 If the region is active in `transient-mark-mode', promote all headings
5102 in the region."
5103 (org-back-to-heading t)
5104 (let* ((level (save-match-data (funcall outline-level)))
5105 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
5106 (diff (abs (- level (length up-head) -1))))
5107 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
5108 (replace-match up-head nil t)
5109 ;; Fixup tag positioning
5110 (and org-auto-align-tags (org-set-tags nil t))
5111 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
5113 (defun org-demote ()
5114 "Demote the current heading lower down the tree.
5115 If the region is active in `transient-mark-mode', demote all headings
5116 in the region."
5117 (org-back-to-heading t)
5118 (let* ((level (save-match-data (funcall outline-level)))
5119 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
5120 (diff (abs (- level (length down-head) -1))))
5121 (replace-match down-head nil t)
5122 ;; Fixup tag positioning
5123 (and org-auto-align-tags (org-set-tags nil t))
5124 (if org-adapt-indentation (org-fixup-indentation diff))))
5126 (defun org-map-tree (fun)
5127 "Call FUN for every heading underneath the current one."
5128 (org-back-to-heading)
5129 (let ((level (funcall outline-level)))
5130 (save-excursion
5131 (funcall fun)
5132 (while (and (progn
5133 (outline-next-heading)
5134 (> (funcall outline-level) level))
5135 (not (eobp)))
5136 (funcall fun)))))
5138 (defun org-map-region (fun beg end)
5139 "Call FUN for every heading between BEG and END."
5140 (let ((org-ignore-region t))
5141 (save-excursion
5142 (setq end (copy-marker end))
5143 (goto-char beg)
5144 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
5145 (< (point) end))
5146 (funcall fun))
5147 (while (and (progn
5148 (outline-next-heading)
5149 (< (point) end))
5150 (not (eobp)))
5151 (funcall fun)))))
5153 (defun org-fixup-indentation (diff)
5154 "Change the indentation in the current entry by DIFF
5155 However, if any line in the current entry has no indentation, or if it
5156 would end up with no indentation after the change, nothing at all is done."
5157 (save-excursion
5158 (let ((end (save-excursion (outline-next-heading)
5159 (point-marker)))
5160 (prohibit (if (> diff 0)
5161 "^\\S-"
5162 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
5163 col)
5164 (unless (save-excursion (end-of-line 1)
5165 (re-search-forward prohibit end t))
5166 (while (and (< (point) end)
5167 (re-search-forward "^[ \t]+" end t))
5168 (goto-char (match-end 0))
5169 (setq col (current-column))
5170 (if (< diff 0) (replace-match ""))
5171 (org-indent-to-column (+ diff col))))
5172 (move-marker end nil))))
5174 (defun org-convert-to-odd-levels ()
5175 "Convert an org-mode file with all levels allowed to one with odd levels.
5176 This will leave level 1 alone, convert level 2 to level 3, level 3 to
5177 level 5 etc."
5178 (interactive)
5179 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
5180 (let ((org-odd-levels-only nil) n)
5181 (save-excursion
5182 (goto-char (point-min))
5183 (while (re-search-forward "^\\*\\*+ " nil t)
5184 (setq n (- (length (match-string 0)) 2))
5185 (while (>= (setq n (1- n)) 0)
5186 (org-demote))
5187 (end-of-line 1))))))
5190 (defun org-convert-to-oddeven-levels ()
5191 "Convert an org-mode file with only odd levels to one with odd and even levels.
5192 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
5193 section with an even level, conversion would destroy the structure of the file. An error
5194 is signaled in this case."
5195 (interactive)
5196 (goto-char (point-min))
5197 ;; First check if there are no even levels
5198 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
5199 (org-show-context t)
5200 (error "Not all levels are odd in this file. Conversion not possible."))
5201 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
5202 (let ((org-odd-levels-only nil) n)
5203 (save-excursion
5204 (goto-char (point-min))
5205 (while (re-search-forward "^\\*\\*+ " nil t)
5206 (setq n (/ (1- (length (match-string 0))) 2))
5207 (while (>= (setq n (1- n)) 0)
5208 (org-promote))
5209 (end-of-line 1))))))
5211 (defun org-tr-level (n)
5212 "Make N odd if required."
5213 (if org-odd-levels-only (1+ (/ n 2)) n))
5215 ;;; Vertical tree motion, cutting and pasting of subtrees
5217 (defun org-move-subtree-up (&optional arg)
5218 "Move the current subtree up past ARG headlines of the same level."
5219 (interactive "p")
5220 (org-move-subtree-down (- (prefix-numeric-value arg))))
5222 (defun org-move-subtree-down (&optional arg)
5223 "Move the current subtree down past ARG headlines of the same level."
5224 (interactive "p")
5225 (setq arg (prefix-numeric-value arg))
5226 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
5227 'outline-get-last-sibling))
5228 (ins-point (make-marker))
5229 (cnt (abs arg))
5230 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
5231 ;; Select the tree
5232 (org-back-to-heading)
5233 (setq beg0 (point))
5234 (save-excursion
5235 (setq ne-beg (org-back-over-empty-lines))
5236 (setq beg (point)))
5237 (save-match-data
5238 (save-excursion (outline-end-of-heading)
5239 (setq folded (org-invisible-p)))
5240 (outline-end-of-subtree))
5241 (outline-next-heading)
5242 (setq ne-end (org-back-over-empty-lines))
5243 (setq end (point))
5244 (goto-char beg0)
5245 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
5246 ;; include less whitespace
5247 (save-excursion
5248 (goto-char beg)
5249 (forward-line (- ne-beg ne-end))
5250 (setq beg (point))))
5251 ;; Find insertion point, with error handling
5252 (while (> cnt 0)
5253 (or (and (funcall movfunc) (looking-at outline-regexp))
5254 (progn (goto-char beg0)
5255 (error "Cannot move past superior level or buffer limit")))
5256 (setq cnt (1- cnt)))
5257 (if (> arg 0)
5258 ;; Moving forward - still need to move over subtree
5259 (progn (org-end-of-subtree t t)
5260 (save-excursion
5261 (org-back-over-empty-lines)
5262 (or (bolp) (newline)))))
5263 (setq ne-ins (org-back-over-empty-lines))
5264 (move-marker ins-point (point))
5265 (setq txt (buffer-substring beg end))
5266 (org-save-markers-in-region beg end)
5267 (delete-region beg end)
5268 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
5269 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
5270 (let ((bbb (point)))
5271 (insert-before-markers txt)
5272 (org-reinstall-markers-in-region bbb)
5273 (move-marker ins-point bbb))
5274 (or (bolp) (insert "\n"))
5275 (setq ins-end (point))
5276 (goto-char ins-point)
5277 (org-skip-whitespace)
5278 (when (and (< arg 0)
5279 (org-first-sibling-p)
5280 (> ne-ins ne-beg))
5281 ;; Move whitespace back to beginning
5282 (save-excursion
5283 (goto-char ins-end)
5284 (let ((kill-whole-line t))
5285 (kill-line (- ne-ins ne-beg)) (point)))
5286 (insert (make-string (- ne-ins ne-beg) ?\n)))
5287 (move-marker ins-point nil)
5288 (org-compact-display-after-subtree-move)
5289 (org-show-empty-lines-in-parent)
5290 (unless folded
5291 (org-show-entry)
5292 (show-children)
5293 (org-cycle-hide-drawers 'children))))
5295 (defvar org-subtree-clip ""
5296 "Clipboard for cut and paste of subtrees.
5297 This is actually only a copy of the kill, because we use the normal kill
5298 ring. We need it to check if the kill was created by `org-copy-subtree'.")
5300 (defvar org-subtree-clip-folded nil
5301 "Was the last copied subtree folded?
5302 This is used to fold the tree back after pasting.")
5304 (defun org-cut-subtree (&optional n)
5305 "Cut the current subtree into the clipboard.
5306 With prefix arg N, cut this many sequential subtrees.
5307 This is a short-hand for marking the subtree and then cutting it."
5308 (interactive "p")
5309 (org-copy-subtree n 'cut))
5311 (defun org-copy-subtree (&optional n cut force-store-markers)
5312 "Cut the current subtree into the clipboard.
5313 With prefix arg N, cut this many sequential subtrees.
5314 This is a short-hand for marking the subtree and then copying it.
5315 If CUT is non-nil, actually cut the subtree.
5316 If FORCE-STORE-MARKERS is non-nil, store the relative locations
5317 of some markers in the region, even if CUT is non-nil. This is
5318 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
5319 (interactive "p")
5320 (let (beg end folded (beg0 (point)))
5321 (if (interactive-p)
5322 (org-back-to-heading nil) ; take what looks like a subtree
5323 (org-back-to-heading t)) ; take what is really there
5324 (org-back-over-empty-lines)
5325 (setq beg (point))
5326 (skip-chars-forward " \t\r\n")
5327 (save-match-data
5328 (save-excursion (outline-end-of-heading)
5329 (setq folded (org-invisible-p)))
5330 (condition-case nil
5331 (outline-forward-same-level (1- n))
5332 (error nil))
5333 (org-end-of-subtree t t))
5334 (org-back-over-empty-lines)
5335 (setq end (point))
5336 (goto-char beg0)
5337 (when (> end beg)
5338 (setq org-subtree-clip-folded folded)
5339 (when (or cut force-store-markers)
5340 (org-save-markers-in-region beg end))
5341 (if cut (kill-region beg end) (copy-region-as-kill beg end))
5342 (setq org-subtree-clip (current-kill 0))
5343 (message "%s: Subtree(s) with %d characters"
5344 (if cut "Cut" "Copied")
5345 (length org-subtree-clip)))))
5347 (defun org-paste-subtree (&optional level tree for-yank)
5348 "Paste the clipboard as a subtree, with modification of headline level.
5349 The entire subtree is promoted or demoted in order to match a new headline
5350 level.
5352 If the cursor is at the beginning of a headline, the same level as
5353 that headline is used to paste the tree
5355 If not, the new level is derived from the *visible* headings
5356 before and after the insertion point, and taken to be the inferior headline
5357 level of the two. So if the previous visible heading is level 3 and the
5358 next is level 4 (or vice versa), level 4 will be used for insertion.
5359 This makes sure that the subtree remains an independent subtree and does
5360 not swallow low level entries.
5362 You can also force a different level, either by using a numeric prefix
5363 argument, or by inserting the heading marker by hand. For example, if the
5364 cursor is after \"*****\", then the tree will be shifted to level 5.
5366 If optional TREE is given, use this text instead of the kill ring.
5368 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
5369 move back over whitespace before inserting, and move point to the end of
5370 the inserted text when done."
5371 (interactive "P")
5372 (unless (org-kill-is-subtree-p tree)
5373 (error "%s"
5374 (substitute-command-keys
5375 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
5376 (let* ((visp (not (org-invisible-p)))
5377 (txt (or tree (and kill-ring (current-kill 0))))
5378 (^re (concat "^\\(" outline-regexp "\\)"))
5379 (re (concat "\\(" outline-regexp "\\)"))
5380 (^re_ (concat "\\(\\*+\\)[ \t]*"))
5382 (old-level (if (string-match ^re txt)
5383 (- (match-end 0) (match-beginning 0) 1)
5384 -1))
5385 (force-level (cond (level (prefix-numeric-value level))
5386 ((and (looking-at "[ \t]*$")
5387 (string-match
5388 ^re_ (buffer-substring
5389 (point-at-bol) (point))))
5390 (- (match-end 1) (match-beginning 1)))
5391 ((and (bolp)
5392 (looking-at org-outline-regexp))
5393 (- (match-end 0) (point) 1))
5394 (t nil)))
5395 (previous-level (save-excursion
5396 (condition-case nil
5397 (progn
5398 (outline-previous-visible-heading 1)
5399 (if (looking-at re)
5400 (- (match-end 0) (match-beginning 0) 1)
5402 (error 1))))
5403 (next-level (save-excursion
5404 (condition-case nil
5405 (progn
5406 (or (looking-at outline-regexp)
5407 (outline-next-visible-heading 1))
5408 (if (looking-at re)
5409 (- (match-end 0) (match-beginning 0) 1)
5411 (error 1))))
5412 (new-level (or force-level (max previous-level next-level)))
5413 (shift (if (or (= old-level -1)
5414 (= new-level -1)
5415 (= old-level new-level))
5417 (- new-level old-level)))
5418 (delta (if (> shift 0) -1 1))
5419 (func (if (> shift 0) 'org-demote 'org-promote))
5420 (org-odd-levels-only nil)
5421 beg end newend)
5422 ;; Remove the forced level indicator
5423 (if force-level
5424 (delete-region (point-at-bol) (point)))
5425 ;; Paste
5426 (beginning-of-line 1)
5427 (unless for-yank (org-back-over-empty-lines))
5428 (setq beg (point))
5429 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
5430 (insert-before-markers txt)
5431 (unless (string-match "\n\\'" txt) (insert "\n"))
5432 (setq newend (point))
5433 (org-reinstall-markers-in-region beg)
5434 (setq end (point))
5435 (goto-char beg)
5436 (skip-chars-forward " \t\n\r")
5437 (setq beg (point))
5438 (if (and (org-invisible-p) visp)
5439 (save-excursion (outline-show-heading)))
5440 ;; Shift if necessary
5441 (unless (= shift 0)
5442 (save-restriction
5443 (narrow-to-region beg end)
5444 (while (not (= shift 0))
5445 (org-map-region func (point-min) (point-max))
5446 (setq shift (+ delta shift)))
5447 (goto-char (point-min))
5448 (setq newend (point-max))))
5449 (when (or (interactive-p) for-yank)
5450 (message "Clipboard pasted as level %d subtree" new-level))
5451 (if (and (not for-yank) ; in this case, org-yank will decide about folding
5452 kill-ring
5453 (eq org-subtree-clip (current-kill 0))
5454 org-subtree-clip-folded)
5455 ;; The tree was folded before it was killed/copied
5456 (hide-subtree))
5457 (and for-yank (goto-char newend))))
5459 (defun org-kill-is-subtree-p (&optional txt)
5460 "Check if the current kill is an outline subtree, or a set of trees.
5461 Returns nil if kill does not start with a headline, or if the first
5462 headline level is not the largest headline level in the tree.
5463 So this will actually accept several entries of equal levels as well,
5464 which is OK for `org-paste-subtree'.
5465 If optional TXT is given, check this string instead of the current kill."
5466 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
5467 (start-level (and kill
5468 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
5469 org-outline-regexp "\\)")
5470 kill)
5471 (- (match-end 2) (match-beginning 2) 1)))
5472 (re (concat "^" org-outline-regexp))
5473 (start (1+ (or (match-beginning 2) -1))))
5474 (if (not start-level)
5475 (progn
5476 nil) ;; does not even start with a heading
5477 (catch 'exit
5478 (while (setq start (string-match re kill (1+ start)))
5479 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
5480 (throw 'exit nil)))
5481 t))))
5483 (defvar org-markers-to-move nil
5484 "Markers that should be moved with a cut-and-paste operation.
5485 Those markers are stored together with their positions relative to
5486 the start of the region.")
5488 (defun org-save-markers-in-region (beg end)
5489 "Check markers in region.
5490 If these markers are between BEG and END, record their position relative
5491 to BEG, so that after moving the block of text, we can put the markers back
5492 into place.
5493 This function gets called just before an entry or tree gets cut from the
5494 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
5495 called immediately, to move the markers with the entries."
5496 (setq org-markers-to-move nil)
5497 (when (featurep 'org-clock)
5498 (org-clock-save-markers-for-cut-and-paste beg end))
5499 (when (featurep 'org-agenda)
5500 (org-agenda-save-markers-for-cut-and-paste beg end)))
5502 (defun org-check-and-save-marker (marker beg end)
5503 "Check if MARKER is between BEG and END.
5504 If yes, remember the marker and the distance to BEG."
5505 (when (and (marker-buffer marker)
5506 (equal (marker-buffer marker) (current-buffer)))
5507 (if (and (>= marker beg) (< marker end))
5508 (push (cons marker (- marker beg)) org-markers-to-move))))
5510 (defun org-reinstall-markers-in-region (beg)
5511 "Move all remembered markers to their position relative to BEG."
5512 (mapc (lambda (x)
5513 (move-marker (car x) (+ beg (cdr x))))
5514 org-markers-to-move)
5515 (setq org-markers-to-move nil))
5517 (defun org-narrow-to-subtree ()
5518 "Narrow buffer to the current subtree."
5519 (interactive)
5520 (save-excursion
5521 (save-match-data
5522 (narrow-to-region
5523 (progn (org-back-to-heading) (point))
5524 (progn (org-end-of-subtree t) (point))))))
5527 ;;; Outline Sorting
5529 (defun org-sort (with-case)
5530 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
5531 Optional argument WITH-CASE means sort case-sensitively."
5532 (interactive "P")
5533 (if (org-at-table-p)
5534 (org-call-with-arg 'org-table-sort-lines with-case)
5535 (org-call-with-arg 'org-sort-entries-or-items with-case)))
5537 (defun org-sort-remove-invisible (s)
5538 (remove-text-properties 0 (length s) org-rm-props s)
5539 (while (string-match org-bracket-link-regexp s)
5540 (setq s (replace-match (if (match-end 2)
5541 (match-string 3 s)
5542 (match-string 1 s)) t t s)))
5545 (defvar org-priority-regexp) ; defined later in the file
5547 (defun org-sort-entries-or-items
5548 (&optional with-case sorting-type getkey-func compare-func property)
5549 "Sort entries on a certain level of an outline tree.
5550 If there is an active region, the entries in the region are sorted.
5551 Else, if the cursor is before the first entry, sort the top-level items.
5552 Else, the children of the entry at point are sorted.
5554 Sorting can be alphabetically, numerically, and by date/time as given by
5555 the first time stamp in the entry. The command prompts for the sorting
5556 type unless it has been given to the function through the SORTING-TYPE
5557 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
5558 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
5559 called with point at the beginning of the record. It must return either
5560 a string or a number that should serve as the sorting key for that record.
5562 Comparing entries ignores case by default. However, with an optional argument
5563 WITH-CASE, the sorting considers case as well."
5564 (interactive "P")
5565 (let ((case-func (if with-case 'identity 'downcase))
5566 start beg end stars re re2
5567 txt what tmp plain-list-p)
5568 ;; Find beginning and end of region to sort
5569 (cond
5570 ((org-region-active-p)
5571 ;; we will sort the region
5572 (setq end (region-end)
5573 what "region")
5574 (goto-char (region-beginning))
5575 (if (not (org-on-heading-p)) (outline-next-heading))
5576 (setq start (point)))
5577 ((org-at-item-p)
5578 ;; we will sort this plain list
5579 (org-beginning-of-item-list) (setq start (point))
5580 (org-end-of-item-list) (setq end (point))
5581 (goto-char start)
5582 (setq plain-list-p t
5583 what "plain list"))
5584 ((or (org-on-heading-p)
5585 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
5586 ;; we will sort the children of the current headline
5587 (org-back-to-heading)
5588 (setq start (point)
5589 end (progn (org-end-of-subtree t t)
5590 (org-back-over-empty-lines)
5591 (point))
5592 what "children")
5593 (goto-char start)
5594 (show-subtree)
5595 (outline-next-heading))
5597 ;; we will sort the top-level entries in this file
5598 (goto-char (point-min))
5599 (or (org-on-heading-p) (outline-next-heading))
5600 (setq start (point) end (point-max) what "top-level")
5601 (goto-char start)
5602 (show-all)))
5604 (setq beg (point))
5605 (if (>= beg end) (error "Nothing to sort"))
5607 (unless plain-list-p
5608 (looking-at "\\(\\*+\\)")
5609 (setq stars (match-string 1)
5610 re (concat "^" (regexp-quote stars) " +")
5611 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
5612 txt (buffer-substring beg end))
5613 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
5614 (if (and (not (equal stars "*")) (string-match re2 txt))
5615 (error "Region to sort contains a level above the first entry")))
5617 (unless sorting-type
5618 (message
5619 (if plain-list-p
5620 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
5621 "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:")
5622 what)
5623 (setq sorting-type (read-char-exclusive))
5625 (and (= (downcase sorting-type) ?f)
5626 (setq getkey-func
5627 (org-ido-completing-read "Sort using function: "
5628 obarray 'fboundp t nil nil))
5629 (setq getkey-func (intern getkey-func)))
5631 (and (= (downcase sorting-type) ?r)
5632 (setq property
5633 (org-ido-completing-read "Property: "
5634 (mapcar 'list (org-buffer-property-keys t))
5635 nil t))))
5637 (message "Sorting entries...")
5639 (save-restriction
5640 (narrow-to-region start end)
5642 (let ((dcst (downcase sorting-type))
5643 (now (current-time)))
5644 (sort-subr
5645 (/= dcst sorting-type)
5646 ;; This function moves to the beginning character of the "record" to
5647 ;; be sorted.
5648 (if plain-list-p
5649 (lambda nil
5650 (if (org-at-item-p) t (goto-char (point-max))))
5651 (lambda nil
5652 (if (re-search-forward re nil t)
5653 (goto-char (match-beginning 0))
5654 (goto-char (point-max)))))
5655 ;; This function moves to the last character of the "record" being
5656 ;; sorted.
5657 (if plain-list-p
5658 'org-end-of-item
5659 (lambda nil
5660 (save-match-data
5661 (condition-case nil
5662 (outline-forward-same-level 1)
5663 (error
5664 (goto-char (point-max)))))))
5666 ;; This function returns the value that gets sorted against.
5667 (if plain-list-p
5668 (lambda nil
5669 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
5670 (cond
5671 ((= dcst ?n)
5672 (string-to-number (buffer-substring (match-end 0)
5673 (point-at-eol))))
5674 ((= dcst ?a)
5675 (buffer-substring (match-end 0) (point-at-eol)))
5676 ((= dcst ?t)
5677 (if (re-search-forward org-ts-regexp
5678 (point-at-eol) t)
5679 (org-time-string-to-time (match-string 0))
5680 now))
5681 ((= dcst ?f)
5682 (if getkey-func
5683 (progn
5684 (setq tmp (funcall getkey-func))
5685 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5686 tmp)
5687 (error "Invalid key function `%s'" getkey-func)))
5688 (t (error "Invalid sorting type `%c'" sorting-type)))))
5689 (lambda nil
5690 (cond
5691 ((= dcst ?n)
5692 (if (looking-at org-complex-heading-regexp)
5693 (string-to-number (match-string 4))
5694 nil))
5695 ((= dcst ?a)
5696 (if (looking-at org-complex-heading-regexp)
5697 (funcall case-func (match-string 4))
5698 nil))
5699 ((= dcst ?t)
5700 (if (re-search-forward org-ts-regexp
5701 (save-excursion
5702 (forward-line 2)
5703 (point)) t)
5704 (org-time-string-to-time (match-string 0))
5705 now))
5706 ((= dcst ?p)
5707 (if (re-search-forward org-priority-regexp (point-at-eol) t)
5708 (string-to-char (match-string 2))
5709 org-default-priority))
5710 ((= dcst ?r)
5711 (or (org-entry-get nil property) ""))
5712 ((= dcst ?o)
5713 (if (looking-at org-complex-heading-regexp)
5714 (- 9999 (length (member (match-string 2)
5715 org-todo-keywords-1)))))
5716 ((= dcst ?f)
5717 (if getkey-func
5718 (progn
5719 (setq tmp (funcall getkey-func))
5720 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5721 tmp)
5722 (error "Invalid key function `%s'" getkey-func)))
5723 (t (error "Invalid sorting type `%c'" sorting-type)))))
5725 (cond
5726 ((= dcst ?a) 'string<)
5727 ((= dcst ?t) 'time-less-p)
5728 ((= dcst ?f) compare-func)
5729 (t nil)))))
5730 (message "Sorting entries...done")))
5732 (defun org-do-sort (table what &optional with-case sorting-type)
5733 "Sort TABLE of WHAT according to SORTING-TYPE.
5734 The user will be prompted for the SORTING-TYPE if the call to this
5735 function does not specify it. WHAT is only for the prompt, to indicate
5736 what is being sorted. The sorting key will be extracted from
5737 the car of the elements of the table.
5738 If WITH-CASE is non-nil, the sorting will be case-sensitive."
5739 (unless sorting-type
5740 (message
5741 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
5742 what)
5743 (setq sorting-type (read-char-exclusive)))
5744 (let ((dcst (downcase sorting-type))
5745 extractfun comparefun)
5746 ;; Define the appropriate functions
5747 (cond
5748 ((= dcst ?n)
5749 (setq extractfun 'string-to-number
5750 comparefun (if (= dcst sorting-type) '< '>)))
5751 ((= dcst ?a)
5752 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
5753 (lambda(x) (downcase (org-sort-remove-invisible x))))
5754 comparefun (if (= dcst sorting-type)
5755 'string<
5756 (lambda (a b) (and (not (string< a b))
5757 (not (string= a b)))))))
5758 ((= dcst ?t)
5759 (setq extractfun
5760 (lambda (x)
5761 (if (string-match org-ts-regexp x)
5762 (time-to-seconds
5763 (org-time-string-to-time (match-string 0 x)))
5765 comparefun (if (= dcst sorting-type) '< '>)))
5766 (t (error "Invalid sorting type `%c'" sorting-type)))
5768 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5769 table)
5770 (lambda (a b) (funcall comparefun (car a) (car b))))))
5772 ;;; Editing source examples
5774 (defvar org-exit-edit-mode-map (make-sparse-keymap))
5775 (define-key org-exit-edit-mode-map "\C-c'" 'org-edit-src-exit)
5776 (defvar org-edit-src-force-single-line nil)
5777 (defvar org-edit-src-from-org-mode nil)
5778 (defvar org-edit-src-picture nil)
5780 (define-minor-mode org-exit-edit-mode
5781 "Minor mode installing a single key binding, \"C-c '\" to exit special edit.")
5783 (defun org-edit-src-code ()
5784 "Edit the source code example at point.
5785 An indirect buffer is created, and that buffer is then narrowed to the
5786 example at point and switched to the correct language mode. When done,
5787 exit by killing the buffer with \\[org-edit-src-exit]."
5788 (interactive)
5789 (let ((line (org-current-line))
5790 (case-fold-search t)
5791 (msg (substitute-command-keys
5792 "Edit, then exit with C-c ' (C-c and single quote)"))
5793 (info (org-edit-src-find-region-and-lang))
5794 (org-mode-p (eq major-mode 'org-mode))
5795 beg end lang lang-f single lfmt)
5796 (if (not info)
5798 (setq beg (nth 0 info)
5799 end (nth 1 info)
5800 lang (nth 2 info)
5801 single (nth 3 info)
5802 lfmt (nth 4 info)
5803 lang-f (intern (concat lang "-mode")))
5804 (unless (functionp lang-f)
5805 (error "No such language mode: %s" lang-f))
5806 (goto-line line)
5807 (if (get-buffer "*Org Edit Src Example*")
5808 (kill-buffer "*Org Edit Src Example*"))
5809 (switch-to-buffer (make-indirect-buffer (current-buffer)
5810 "*Org Edit Src Example*"))
5811 (narrow-to-region beg end)
5812 (remove-text-properties beg end '(display nil invisible nil
5813 intangible nil))
5814 (let ((org-inhibit-startup t))
5815 (funcall lang-f))
5816 (set (make-local-variable 'org-edit-src-force-single-line) single)
5817 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5818 (when lfmt
5819 (set (make-local-variable 'org-coderef-label-format) lfmt))
5820 (when org-mode-p
5821 (goto-char (point-min))
5822 (while (re-search-forward "^," nil t)
5823 (replace-match "")))
5824 (goto-line line)
5825 (org-exit-edit-mode)
5826 (org-set-local 'header-line-format msg)
5827 (message "%s" msg)
5828 t)))
5830 (defun org-edit-fixed-width-region ()
5831 "Edit the fixed-width ascii drawing at point.
5832 This must be a region where each line starts with a colon followed by
5833 a space character.
5834 An indirect buffer is created, and that buffer is then narrowed to the
5835 example at point and switched to artist-mode. When done,
5836 exit by killing the buffer with \\[org-edit-src-exit]."
5837 (interactive)
5838 (let ((line (org-current-line))
5839 (case-fold-search t)
5840 (msg (substitute-command-keys
5841 "Edit, then exit with C-c ' (C-c and single quote)"))
5842 (org-mode-p (eq major-mode 'org-mode))
5843 beg end lang lang-f)
5844 (beginning-of-line 1)
5845 (if (looking-at "[ \t]*[^:\n \t]")
5847 (if (looking-at "[ \t]*\\(\n\\|\\'\\)")
5848 (setq beg (point) end beg)
5849 (save-excursion
5850 (if (re-search-backward "^[ \t]*[^:]" nil 'move)
5851 (setq beg (point-at-bol 2))
5852 (setq beg (point))))
5853 (save-excursion
5854 (if (re-search-forward "^[ \t]*[^:]" nil 'move)
5855 (setq end (1- (match-beginning 0)))
5856 (setq end (point))))
5857 (goto-line line))
5858 (if (get-buffer "*Org Edit Picture*")
5859 (kill-buffer "*Org Edit Picture*"))
5860 (switch-to-buffer (make-indirect-buffer (current-buffer)
5861 "*Org Edit Picture*"))
5862 (narrow-to-region beg end)
5863 (remove-text-properties beg end '(display nil invisible nil
5864 intangible nil))
5865 (when (fboundp 'font-lock-unfontify-region)
5866 (font-lock-unfontify-region (point-min) (point-max)))
5867 (cond
5868 ((eq org-edit-fixed-width-region-mode 'artist-mode)
5869 (fundamental-mode)
5870 (artist-mode 1))
5871 (t (funcall org-edit-fixed-width-region-mode)))
5872 (set (make-local-variable 'org-edit-src-force-single-line) nil)
5873 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5874 (set (make-local-variable 'org-edit-src-picture) t)
5875 (goto-char (point-min))
5876 (while (re-search-forward "^[ \t]*: ?" nil t)
5877 (replace-match ""))
5878 (goto-line line)
5879 (org-exit-edit-mode)
5880 (org-set-local 'header-line-format msg)
5881 (message "%s" msg)
5882 t)))
5885 (defun org-edit-src-find-region-and-lang ()
5886 "Find the region and language for a local edit.
5887 Return a list with beginning and end of the region, a string representing
5888 the language, a switch telling of the content should be in a single line."
5889 (let ((re-list
5890 (append
5891 org-edit-src-region-extra
5893 ("<src\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</src>" lang)
5894 ("<literal\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</literal>" style)
5895 ("<example>[ \t]*\n?" "\n?[ \t]*</example>" "fundamental")
5896 ("<lisp>[ \t]*\n?" "\n?[ \t]*</lisp>" "emacs-lisp")
5897 ("<perl>[ \t]*\n?" "\n?[ \t]*</perl>" "perl")
5898 ("<python>[ \t]*\n?" "\n?[ \t]*</python>" "python")
5899 ("<ruby>[ \t]*\n?" "\n?[ \t]*</ruby>" "ruby")
5900 ("^#\\+begin_src\\( \\([^ \t\n]+\\)\\)?.*\n" "\n#\\+end_src" 2)
5901 ("^#\\+begin_example.*\n" "\n#\\+end_example" "fundamental")
5902 ("^#\\+html:" "\n" "html" single-line)
5903 ("^#\\+begin_html.*\n" "\n#\\+end_html" "html")
5904 ("^#\\+begin_latex.*\n" "\n#\\+end_latex" "latex")
5905 ("^#\\+latex:" "\n" "latex" single-line)
5906 ("^#\\+begin_ascii.*\n" "\n#\\+end_ascii" "fundamental")
5907 ("^#\\+ascii:" "\n" "ascii" single-line)
5909 (pos (point))
5910 re re1 re2 single beg end lang lfmt match-re1)
5911 (catch 'exit
5912 (while (setq entry (pop re-list))
5913 (setq re1 (car entry) re2 (nth 1 entry) lang (nth 2 entry)
5914 single (nth 3 entry))
5915 (save-excursion
5916 (if (or (looking-at re1)
5917 (re-search-backward re1 nil t))
5918 (progn
5919 (setq match-re1 (match-string 0))
5920 (setq beg (match-end 0)
5921 lang (org-edit-src-get-lang lang)
5922 lfmt (org-edit-src-get-label-format match-re1))
5923 (if (and (re-search-forward re2 nil t)
5924 (>= (match-end 0) pos))
5925 (throw 'exit (list beg (match-beginning 0)
5926 lang single lfmt))))
5927 (if (or (looking-at re2)
5928 (re-search-forward re2 nil t))
5929 (progn
5930 (setq end (match-beginning 0))
5931 (if (and (re-search-backward re1 nil t)
5932 (<= (match-beginning 0) pos))
5933 (progn
5934 (setq lfmt (org-edit-src-get-label-format
5935 (match-string 0)))
5936 (throw 'exit
5937 (list (match-end 0) end
5938 (org-edit-src-get-lang lang)
5939 single lfmt))))))))))))
5941 (defun org-edit-src-get-lang (lang)
5942 "Extract the src language."
5943 (let ((m (match-string 0)))
5944 (cond
5945 ((stringp lang) lang)
5946 ((integerp lang) (match-string lang))
5947 ((and (eq lang 'lang)
5948 (string-match "\\<lang=\"\\([^ \t\n\"]+\\)\"" m))
5949 (match-string 1 m))
5950 ((and (eq lang 'style)
5951 (string-match "\\<style=\"\\([^ \t\n\"]+\\)\"" m))
5952 (match-string 1 m))
5953 (t "fundamental"))))
5955 (defun org-edit-src-get-label-format (s)
5956 "Extract the label format."
5957 (save-match-data
5958 (if (string-match "-l[ \t]+\\\\?\"\\([^\t\r\n\"]+\\)\\\\?\"" s)
5959 (match-string 1 s))))
5961 (defun org-edit-src-exit ()
5962 "Exit special edit and protect problematic lines."
5963 (interactive)
5964 (unless (buffer-base-buffer (current-buffer))
5965 (error "This is not an indirect buffer, something is wrong..."))
5966 (unless (> (point-min) 1)
5967 (error "This buffer is not narrowed, something is wrong..."))
5968 (goto-char (point-min))
5969 (if (looking-at "[ \t\n]*\n") (replace-match ""))
5970 (if (re-search-forward "\n[ \t\n]*\\'" nil t) (replace-match ""))
5971 (when (org-bound-and-true-p org-edit-src-force-single-line)
5972 (goto-char (point-min))
5973 (while (re-search-forward "\n" nil t)
5974 (replace-match " "))
5975 (goto-char (point-min))
5976 (if (looking-at "\\s-*") (replace-match " "))
5977 (if (re-search-forward "\\s-+\\'" nil t)
5978 (replace-match "")))
5979 (when (org-bound-and-true-p org-edit-src-from-org-mode)
5980 (goto-char (point-min))
5981 (while (re-search-forward (if (org-mode-p) "^\\(.\\)" "^\\([*#]\\)") nil t)
5982 (replace-match ",\\1"))
5983 (when font-lock-mode
5984 (font-lock-unfontify-region (point-min) (point-max)))
5985 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
5986 (when (org-bound-and-true-p org-edit-src-picture)
5987 (untabify (point-min) (point-max))
5988 (goto-char (point-min))
5989 (while (re-search-forward "^" nil t)
5990 (replace-match ": "))
5991 (when font-lock-mode
5992 (font-lock-unfontify-region (point-min) (point-max)))
5993 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
5994 (kill-buffer (current-buffer))
5995 (and (org-mode-p) (org-restart-font-lock)))
5998 ;;; The orgstruct minor mode
6000 ;; Define a minor mode which can be used in other modes in order to
6001 ;; integrate the org-mode structure editing commands.
6003 ;; This is really a hack, because the org-mode structure commands use
6004 ;; keys which normally belong to the major mode. Here is how it
6005 ;; works: The minor mode defines all the keys necessary to operate the
6006 ;; structure commands, but wraps the commands into a function which
6007 ;; tests if the cursor is currently at a headline or a plain list
6008 ;; item. If that is the case, the structure command is used,
6009 ;; temporarily setting many Org-mode variables like regular
6010 ;; expressions for filling etc. However, when any of those keys is
6011 ;; used at a different location, function uses `key-binding' to look
6012 ;; up if the key has an associated command in another currently active
6013 ;; keymap (minor modes, major mode, global), and executes that
6014 ;; command. There might be problems if any of the keys is otherwise
6015 ;; used as a prefix key.
6017 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
6018 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
6019 ;; addresses this by checking explicitly for both bindings.
6021 (defvar orgstruct-mode-map (make-sparse-keymap)
6022 "Keymap for the minor `orgstruct-mode'.")
6024 (defvar org-local-vars nil
6025 "List of local variables, for use by `orgstruct-mode'")
6027 ;;;###autoload
6028 (define-minor-mode orgstruct-mode
6029 "Toggle the minor more `orgstruct-mode'.
6030 This mode is for using Org-mode structure commands in other modes.
6031 The following key behave as if Org-mode was active, if the cursor
6032 is on a headline, or on a plain list item (both in the definition
6033 of Org-mode).
6035 M-up Move entry/item up
6036 M-down Move entry/item down
6037 M-left Promote
6038 M-right Demote
6039 M-S-up Move entry/item up
6040 M-S-down Move entry/item down
6041 M-S-left Promote subtree
6042 M-S-right Demote subtree
6043 M-q Fill paragraph and items like in Org-mode
6044 C-c ^ Sort entries
6045 C-c - Cycle list bullet
6046 TAB Cycle item visibility
6047 M-RET Insert new heading/item
6048 S-M-RET Insert new TODO heading / Checkbox item
6049 C-c C-c Set tags / toggle checkbox"
6050 nil " OrgStruct" nil
6051 (org-load-modules-maybe)
6052 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
6054 ;;;###autoload
6055 (defun turn-on-orgstruct ()
6056 "Unconditionally turn on `orgstruct-mode'."
6057 (orgstruct-mode 1))
6059 ;;;###autoload
6060 (defun turn-on-orgstruct++ ()
6061 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
6062 In addition to setting orgstruct-mode, this also exports all indentation and
6063 autofilling variables from org-mode into the buffer. Note that turning
6064 off orgstruct-mode will *not* remove these additional settings."
6065 (orgstruct-mode 1)
6066 (let (var val)
6067 (mapc
6068 (lambda (x)
6069 (when (string-match
6070 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6071 (symbol-name (car x)))
6072 (setq var (car x) val (nth 1 x))
6073 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
6074 org-local-vars)))
6076 (defun orgstruct-error ()
6077 "Error when there is no default binding for a structure key."
6078 (interactive)
6079 (error "This key has no function outside structure elements"))
6081 (defun orgstruct-setup ()
6082 "Setup orgstruct keymaps."
6083 (let ((nfunc 0)
6084 (bindings
6085 (list
6086 '([(meta up)] org-metaup)
6087 '([(meta down)] org-metadown)
6088 '([(meta left)] org-metaleft)
6089 '([(meta right)] org-metaright)
6090 '([(meta shift up)] org-shiftmetaup)
6091 '([(meta shift down)] org-shiftmetadown)
6092 '([(meta shift left)] org-shiftmetaleft)
6093 '([(meta shift right)] org-shiftmetaright)
6094 '([(shift up)] org-shiftup)
6095 '([(shift down)] org-shiftdown)
6096 '([(shift left)] org-shiftleft)
6097 '([(shift right)] org-shiftright)
6098 '("\C-c\C-c" org-ctrl-c-ctrl-c)
6099 '("\M-q" fill-paragraph)
6100 '("\C-c^" org-sort)
6101 '("\C-c-" org-cycle-list-bullet)))
6102 elt key fun cmd)
6103 (while (setq elt (pop bindings))
6104 (setq nfunc (1+ nfunc))
6105 (setq key (org-key (car elt))
6106 fun (nth 1 elt)
6107 cmd (orgstruct-make-binding fun nfunc key))
6108 (org-defkey orgstruct-mode-map key cmd))
6110 ;; Special treatment needed for TAB and RET
6111 (org-defkey orgstruct-mode-map [(tab)]
6112 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
6113 (org-defkey orgstruct-mode-map "\C-i"
6114 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
6116 (org-defkey orgstruct-mode-map "\M-\C-m"
6117 (orgstruct-make-binding 'org-insert-heading 105
6118 "\M-\C-m" [(meta return)]))
6119 (org-defkey orgstruct-mode-map [(meta return)]
6120 (orgstruct-make-binding 'org-insert-heading 106
6121 [(meta return)] "\M-\C-m"))
6123 (org-defkey orgstruct-mode-map [(shift meta return)]
6124 (orgstruct-make-binding 'org-insert-todo-heading 107
6125 [(meta return)] "\M-\C-m"))
6127 (unless org-local-vars
6128 (setq org-local-vars (org-get-local-variables)))
6132 (defun orgstruct-make-binding (fun n &rest keys)
6133 "Create a function for binding in the structure minor mode.
6134 FUN is the command to call inside a table. N is used to create a unique
6135 command name. KEYS are keys that should be checked in for a command
6136 to execute outside of tables."
6137 (eval
6138 (list 'defun
6139 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6140 '(arg)
6141 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6142 "Outside of structure, run the binding of `"
6143 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6144 "'.")
6145 '(interactive "p")
6146 (list 'if
6147 '(org-context-p 'headline 'item)
6148 (list 'org-run-like-in-org-mode (list 'quote fun))
6149 (list 'let '(orgstruct-mode)
6150 (list 'call-interactively
6151 (append '(or)
6152 (mapcar (lambda (k)
6153 (list 'key-binding k))
6154 keys)
6155 '('orgstruct-error))))))))
6157 (defun org-context-p (&rest contexts)
6158 "Check if local context is any of CONTEXTS.
6159 Possible values in the list of contexts are `table', `headline', and `item'."
6160 (let ((pos (point)))
6161 (goto-char (point-at-bol))
6162 (prog1 (or (and (memq 'table contexts)
6163 (looking-at "[ \t]*|"))
6164 (and (memq 'headline contexts)
6165 ;;????????? (looking-at "\\*+"))
6166 (looking-at outline-regexp))
6167 (and (memq 'item contexts)
6168 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
6169 (goto-char pos))))
6171 (defun org-get-local-variables ()
6172 "Return a list of all local variables in an org-mode buffer."
6173 (let (varlist)
6174 (with-current-buffer (get-buffer-create "*Org tmp*")
6175 (erase-buffer)
6176 (org-mode)
6177 (setq varlist (buffer-local-variables)))
6178 (kill-buffer "*Org tmp*")
6179 (delq nil
6180 (mapcar
6181 (lambda (x)
6182 (setq x
6183 (if (symbolp x)
6184 (list x)
6185 (list (car x) (list 'quote (cdr x)))))
6186 (if (string-match
6187 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6188 (symbol-name (car x)))
6189 x nil))
6190 varlist))))
6192 ;;;###autoload
6193 (defun org-run-like-in-org-mode (cmd)
6194 (org-load-modules-maybe)
6195 (unless org-local-vars
6196 (setq org-local-vars (org-get-local-variables)))
6197 (eval (list 'let org-local-vars
6198 (list 'call-interactively (list 'quote cmd)))))
6200 ;;;; Archiving
6202 (defun org-get-category (&optional pos)
6203 "Get the category applying to position POS."
6204 (get-text-property (or pos (point)) 'org-category))
6206 (defun org-refresh-category-properties ()
6207 "Refresh category text properties in the buffer."
6208 (let ((def-cat (cond
6209 ((null org-category)
6210 (if buffer-file-name
6211 (file-name-sans-extension
6212 (file-name-nondirectory buffer-file-name))
6213 "???"))
6214 ((symbolp org-category) (symbol-name org-category))
6215 (t org-category)))
6216 beg end cat pos optionp)
6217 (org-unmodified
6218 (save-excursion
6219 (save-restriction
6220 (widen)
6221 (goto-char (point-min))
6222 (put-text-property (point) (point-max) 'org-category def-cat)
6223 (while (re-search-forward
6224 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6225 (setq pos (match-end 0)
6226 optionp (equal (char-after (match-beginning 0)) ?#)
6227 cat (org-trim (match-string 2)))
6228 (if optionp
6229 (setq beg (point-at-bol) end (point-max))
6230 (org-back-to-heading t)
6231 (setq beg (point) end (org-end-of-subtree t t)))
6232 (put-text-property beg end 'org-category cat)
6233 (goto-char pos)))))))
6236 ;;;; Link Stuff
6238 ;;; Link abbreviations
6240 (defun org-link-expand-abbrev (link)
6241 "Apply replacements as defined in `org-link-abbrev-alist."
6242 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6243 (let* ((key (match-string 1 link))
6244 (as (or (assoc key org-link-abbrev-alist-local)
6245 (assoc key org-link-abbrev-alist)))
6246 (tag (and (match-end 2) (match-string 3 link)))
6247 rpl)
6248 (if (not as)
6249 link
6250 (setq rpl (cdr as))
6251 (cond
6252 ((symbolp rpl) (funcall rpl tag))
6253 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
6254 ((string-match "%h" rpl)
6255 (replace-match (url-hexify-string (or tag "")) t t rpl))
6256 (t (concat rpl tag)))))
6257 link))
6259 ;;; Storing and inserting links
6261 (defvar org-insert-link-history nil
6262 "Minibuffer history for links inserted with `org-insert-link'.")
6264 (defvar org-stored-links nil
6265 "Contains the links stored with `org-store-link'.")
6267 (defvar org-store-link-plist nil
6268 "Plist with info about the most recently link created with `org-store-link'.")
6270 (defvar org-link-protocols nil
6271 "Link protocols added to Org-mode using `org-add-link-type'.")
6273 (defvar org-store-link-functions nil
6274 "List of functions that are called to create and store a link.
6275 Each function will be called in turn until one returns a non-nil
6276 value. Each function should check if it is responsible for creating
6277 this link (for example by looking at the major mode).
6278 If not, it must exit and return nil.
6279 If yes, it should return a non-nil value after a calling
6280 `org-store-link-props' with a list of properties and values.
6281 Special properties are:
6283 :type The link prefix. like \"http\". This must be given.
6284 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6285 This is obligatory as well.
6286 :description Optional default description for the second pair
6287 of brackets in an Org-mode link. The user can still change
6288 this when inserting this link into an Org-mode buffer.
6290 In addition to these, any additional properties can be specified
6291 and then used in remember templates.")
6293 (defun org-add-link-type (type &optional follow export)
6294 "Add TYPE to the list of `org-link-types'.
6295 Re-compute all regular expressions depending on `org-link-types'
6297 FOLLOW and EXPORT are two functions.
6299 FOLLOW should take the link path as the single argument and do whatever
6300 is necessary to follow the link, for example find a file or display
6301 a mail message.
6303 EXPORT should format the link path for export to one of the export formats.
6304 It should be a function accepting three arguments:
6306 path the path of the link, the text after the prefix (like \"http:\")
6307 desc the description of the link, if any, nil if there was no description
6308 format the export format, a symbol like `html' or `latex'.
6310 The function may use the FORMAT information to return different values
6311 depending on the format. The return value will be put literally into
6312 the exported file.
6313 Org-mode has a built-in default for exporting links. If you are happy with
6314 this default, there is no need to define an export function for the link
6315 type. For a simple example of an export function, see `org-bbdb.el'."
6316 (add-to-list 'org-link-types type t)
6317 (org-make-link-regexps)
6318 (if (assoc type org-link-protocols)
6319 (setcdr (assoc type org-link-protocols) (list follow export))
6320 (push (list type follow export) org-link-protocols)))
6322 ;;;###autoload
6323 (defun org-store-link (arg)
6324 "\\<org-mode-map>Store an org-link to the current location.
6325 This link is added to `org-stored-links' and can later be inserted
6326 into an org-buffer with \\[org-insert-link].
6328 For some link types, a prefix arg is interpreted:
6329 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
6330 For file links, arg negates `org-context-in-file-links'."
6331 (interactive "P")
6332 (org-load-modules-maybe)
6333 (setq org-store-link-plist nil) ; reset
6334 (let (link cpltxt desc description search txt)
6335 (cond
6337 ((run-hook-with-args-until-success 'org-store-link-functions)
6338 (setq link (plist-get org-store-link-plist :link)
6339 desc (or (plist-get org-store-link-plist :description) link)))
6341 ((equal (buffer-name) "*Org Edit Src Example*")
6342 (let (label gc)
6343 (while (or (not label)
6344 (save-excursion
6345 (save-restriction
6346 (widen)
6347 (goto-char (point-min))
6348 (re-search-forward
6349 (regexp-quote (format org-coderef-label-format label))
6350 nil t))))
6351 (when label (message "Label exists already") (sit-for 2))
6352 (setq label (read-string "Code line label: " label)))
6353 (end-of-line 1)
6354 (setq link (format org-coderef-label-format label))
6355 (setq gc (- 79 (length link)))
6356 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
6357 (insert link)
6358 (setq link (concat "(" label ")") desc nil)))
6360 ((eq major-mode 'calendar-mode)
6361 (let ((cd (calendar-cursor-to-date)))
6362 (setq link
6363 (format-time-string
6364 (car org-time-stamp-formats)
6365 (apply 'encode-time
6366 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6367 nil nil nil))))
6368 (org-store-link-props :type "calendar" :date cd)))
6370 ((eq major-mode 'w3-mode)
6371 (setq cpltxt (url-view-url t)
6372 link (org-make-link cpltxt))
6373 (org-store-link-props :type "w3" :url (url-view-url t)))
6375 ((eq major-mode 'w3m-mode)
6376 (setq cpltxt (or w3m-current-title w3m-current-url)
6377 link (org-make-link w3m-current-url))
6378 (org-store-link-props :type "w3m" :url (url-view-url t)))
6380 ((setq search (run-hook-with-args-until-success
6381 'org-create-file-search-functions))
6382 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6383 "::" search))
6384 (setq cpltxt (or description link)))
6386 ((eq major-mode 'image-mode)
6387 (setq cpltxt (concat "file:"
6388 (abbreviate-file-name buffer-file-name))
6389 link (org-make-link cpltxt))
6390 (org-store-link-props :type "image" :file buffer-file-name))
6392 ((eq major-mode 'dired-mode)
6393 ;; link to the file in the current line
6394 (setq cpltxt (concat "file:"
6395 (abbreviate-file-name
6396 (expand-file-name
6397 (dired-get-filename nil t))))
6398 link (org-make-link cpltxt)))
6400 ((and buffer-file-name (org-mode-p))
6401 (cond
6402 ((org-in-regexp "<<\\(.*?\\)>>")
6403 (setq cpltxt
6404 (concat "file:"
6405 (abbreviate-file-name buffer-file-name)
6406 "::" (match-string 1))
6407 link (org-make-link cpltxt)))
6408 ((and (featurep 'org-id)
6409 (or (eq org-link-to-org-use-id t)
6410 (and (eq org-link-to-org-use-id 'create-if-interactive)
6411 (interactive-p))
6412 (and org-link-to-org-use-id
6413 (condition-case nil
6414 (org-entry-get nil "ID")
6415 (error nil)))))
6416 ;; We can make a link using the ID.
6417 (setq link (condition-case nil
6418 (prog1 (org-id-store-link)
6419 (setq desc (plist-get org-store-link-plist
6420 :description)))
6421 (error
6422 ;; probably before first headline, link to file only
6423 (concat "file:"
6424 (abbreviate-file-name buffer-file-name))))))
6426 ;; Just link to current headline
6427 (setq cpltxt (concat "file:"
6428 (abbreviate-file-name buffer-file-name)))
6429 ;; Add a context search string
6430 (when (org-xor org-context-in-file-links arg)
6431 (setq txt (cond
6432 ((org-on-heading-p) nil)
6433 ((org-region-active-p)
6434 (buffer-substring (region-beginning) (region-end)))
6435 (t nil)))
6436 (when (or (null txt) (string-match "\\S-" txt))
6437 (setq cpltxt
6438 (concat cpltxt "::"
6439 (condition-case nil
6440 (org-make-org-heading-search-string txt)
6441 (error "")))
6442 desc "NONE")))
6443 (if (string-match "::\\'" cpltxt)
6444 (setq cpltxt (substring cpltxt 0 -2)))
6445 (setq link (org-make-link cpltxt)))))
6447 ((buffer-file-name (buffer-base-buffer))
6448 ;; Just link to this file here.
6449 (setq cpltxt (concat "file:"
6450 (abbreviate-file-name
6451 (buffer-file-name (buffer-base-buffer)))))
6452 ;; Add a context string
6453 (when (org-xor org-context-in-file-links arg)
6454 (setq txt (if (org-region-active-p)
6455 (buffer-substring (region-beginning) (region-end))
6456 (buffer-substring (point-at-bol) (point-at-eol))))
6457 ;; Only use search option if there is some text.
6458 (when (string-match "\\S-" txt)
6459 (setq cpltxt
6460 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6461 desc "NONE")))
6462 (setq link (org-make-link cpltxt)))
6464 ((interactive-p)
6465 (error "Cannot link to a buffer which is not visiting a file"))
6467 (t (setq link nil)))
6469 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6470 (setq link (or link cpltxt)
6471 desc (or desc cpltxt))
6472 (if (equal desc "NONE") (setq desc nil))
6474 (if (and (interactive-p) link)
6475 (progn
6476 (setq org-stored-links
6477 (cons (list link desc) org-stored-links))
6478 (message "Stored: %s" (or desc link)))
6479 (and link (org-make-link-string link desc)))))
6481 (defun org-store-link-props (&rest plist)
6482 "Store link properties, extract names and addresses."
6483 (let (x adr)
6484 (when (setq x (plist-get plist :from))
6485 (setq adr (mail-extract-address-components x))
6486 (setq plist (plist-put plist :fromname (car adr)))
6487 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
6488 (when (setq x (plist-get plist :to))
6489 (setq adr (mail-extract-address-components x))
6490 (setq plist (plist-put plist :toname (car adr)))
6491 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
6492 (let ((from (plist-get plist :from))
6493 (to (plist-get plist :to)))
6494 (when (and from to org-from-is-user-regexp)
6495 (setq plist
6496 (plist-put plist :fromto
6497 (if (string-match org-from-is-user-regexp from)
6498 (concat "to %t")
6499 (concat "from %f"))))))
6500 (setq org-store-link-plist plist))
6502 (defun org-add-link-props (&rest plist)
6503 "Add these properties to the link property list."
6504 (let (key value)
6505 (while plist
6506 (setq key (pop plist) value (pop plist))
6507 (setq org-store-link-plist
6508 (plist-put org-store-link-plist key value)))))
6510 (defun org-email-link-description (&optional fmt)
6511 "Return the description part of an email link.
6512 This takes information from `org-store-link-plist' and formats it
6513 according to FMT (default from `org-email-link-description-format')."
6514 (setq fmt (or fmt org-email-link-description-format))
6515 (let* ((p org-store-link-plist)
6516 (to (plist-get p :toaddress))
6517 (from (plist-get p :fromaddress))
6518 (table
6519 (list
6520 (cons "%c" (plist-get p :fromto))
6521 (cons "%F" (plist-get p :from))
6522 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
6523 (cons "%T" (plist-get p :to))
6524 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
6525 (cons "%s" (plist-get p :subject))
6526 (cons "%m" (plist-get p :message-id)))))
6527 (when (string-match "%c" fmt)
6528 ;; Check if the user wrote this message
6529 (if (and org-from-is-user-regexp from to
6530 (save-match-data (string-match org-from-is-user-regexp from)))
6531 (setq fmt (replace-match "to %t" t t fmt))
6532 (setq fmt (replace-match "from %f" t t fmt))))
6533 (org-replace-escapes fmt table)))
6535 (defun org-make-org-heading-search-string (&optional string heading)
6536 "Make search string for STRING or current headline."
6537 (interactive)
6538 (let ((s (or string (org-get-heading))))
6539 (unless (and string (not heading))
6540 ;; We are using a headline, clean up garbage in there.
6541 (if (string-match org-todo-regexp s)
6542 (setq s (replace-match "" t t s)))
6543 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
6544 (setq s (replace-match "" t t s)))
6545 (setq s (org-trim s))
6546 (if (string-match (concat "^\\(" org-quote-string "\\|"
6547 org-comment-string "\\)") s)
6548 (setq s (replace-match "" t t s)))
6549 (while (string-match org-ts-regexp s)
6550 (setq s (replace-match "" t t s))))
6551 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
6552 (setq s (replace-match " " t t s)))
6553 (or string (setq s (concat "*" s))) ; Add * for headlines
6554 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
6556 (defun org-make-link (&rest strings)
6557 "Concatenate STRINGS."
6558 (apply 'concat strings))
6560 (defun org-make-link-string (link &optional description)
6561 "Make a link with brackets, consisting of LINK and DESCRIPTION."
6562 (unless (string-match "\\S-" link)
6563 (error "Empty link"))
6564 (when (stringp description)
6565 ;; Remove brackets from the description, they are fatal.
6566 (while (string-match "\\[" description)
6567 (setq description (replace-match "{" t t description)))
6568 (while (string-match "\\]" description)
6569 (setq description (replace-match "}" t t description))))
6570 (when (equal (org-link-escape link) description)
6571 ;; No description needed, it is identical
6572 (setq description nil))
6573 (when (and (not description)
6574 (not (equal link (org-link-escape link))))
6575 (setq description (org-extract-attributes link)))
6576 (concat "[[" (org-link-escape link) "]"
6577 (if description (concat "[" description "]") "")
6578 "]"))
6580 (defconst org-link-escape-chars
6581 '((?\ . "%20")
6582 (?\[ . "%5B")
6583 (?\] . "%5D")
6584 (?\340 . "%E0") ; `a
6585 (?\342 . "%E2") ; ^a
6586 (?\347 . "%E7") ; ,c
6587 (?\350 . "%E8") ; `e
6588 (?\351 . "%E9") ; 'e
6589 (?\352 . "%EA") ; ^e
6590 (?\356 . "%EE") ; ^i
6591 (?\364 . "%F4") ; ^o
6592 (?\371 . "%F9") ; `u
6593 (?\373 . "%FB") ; ^u
6594 (?\; . "%3B")
6595 (?? . "%3F")
6596 (?= . "%3D")
6597 (?+ . "%2B")
6599 "Association list of escapes for some characters problematic in links.
6600 This is the list that is used for internal purposes.")
6602 (defconst org-link-escape-chars-browser
6603 '((?\ . "%20")) ; 32 for the SPC char
6604 "Association list of escapes for some characters problematic in links.
6605 This is the list that is used before handing over to the browser.")
6607 (defun org-link-escape (text &optional table)
6608 "Escape characters in TEXT that are problematic for links."
6609 (setq table (or table org-link-escape-chars))
6610 (when text
6611 (let ((re (mapconcat (lambda (x) (regexp-quote
6612 (char-to-string (car x))))
6613 table "\\|")))
6614 (while (string-match re text)
6615 (setq text
6616 (replace-match
6617 (cdr (assoc (string-to-char (match-string 0 text))
6618 table))
6619 t t text)))
6620 text)))
6622 (defun org-link-unescape (text &optional table)
6623 "Reverse the action of `org-link-escape'."
6624 (setq table (or table org-link-escape-chars))
6625 (when text
6626 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
6627 table "\\|")))
6628 (while (string-match re text)
6629 (setq text
6630 (replace-match
6631 (char-to-string (car (rassoc (match-string 0 text) table)))
6632 t t text)))
6633 text)))
6635 (defun org-xor (a b)
6636 "Exclusive or."
6637 (if a (not b) b))
6639 (defun org-fixup-message-id-for-http (s)
6640 "Replace special characters in a message id, so it can be used in an http query."
6641 (while (string-match "<" s)
6642 (setq s (replace-match "%3C" t t s)))
6643 (while (string-match ">" s)
6644 (setq s (replace-match "%3E" t t s)))
6645 (while (string-match "@" s)
6646 (setq s (replace-match "%40" t t s)))
6649 ;;;###autoload
6650 (defun org-insert-link-global ()
6651 "Insert a link like Org-mode does.
6652 This command can be called in any mode to insert a link in Org-mode syntax."
6653 (interactive)
6654 (org-load-modules-maybe)
6655 (org-run-like-in-org-mode 'org-insert-link))
6657 (defun org-insert-link (&optional complete-file link-location)
6658 "Insert a link. At the prompt, enter the link.
6660 Completion can be used to insert any of the link protocol prefixes like
6661 http or ftp in use.
6663 The history can be used to select a link previously stored with
6664 `org-store-link'. When the empty string is entered (i.e. if you just
6665 press RET at the prompt), the link defaults to the most recently
6666 stored link. As SPC triggers completion in the minibuffer, you need to
6667 use M-SPC or C-q SPC to force the insertion of a space character.
6669 You will also be prompted for a description, and if one is given, it will
6670 be displayed in the buffer instead of the link.
6672 If there is already a link at point, this command will allow you to edit link
6673 and description parts.
6675 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
6676 be selected using completion. The path to the file will be relative to the
6677 current directory if the file is in the current directory or a subdirectory.
6678 Otherwise, the link will be the absolute path as completed in the minibuffer
6679 \(i.e. normally ~/path/to/file). You can configure this behavior using the
6680 option `org-link-file-path-type'.
6682 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
6683 the current directory or below.
6685 With three \\[universal-argument] prefixes, negate the meaning of
6686 `org-keep-stored-link-after-insertion'.
6688 If `org-make-link-description-function' is non-nil, this function will be
6689 called with the link target, and the result will be the default
6690 link description.
6692 If the LINK-LOCATION parameter is non-nil, this value will be
6693 used as the link location instead of reading one interactively."
6694 (interactive "P")
6695 (let* ((wcf (current-window-configuration))
6696 (region (if (org-region-active-p)
6697 (buffer-substring (region-beginning) (region-end))))
6698 (remove (and region (list (region-beginning) (region-end))))
6699 (desc region)
6700 tmphist ; byte-compile incorrectly complains about this
6701 (link link-location)
6702 entry file)
6703 (cond
6704 (link-location) ; specified by arg, just use it.
6705 ((org-in-regexp org-bracket-link-regexp 1)
6706 ;; We do have a link at point, and we are going to edit it.
6707 (setq remove (list (match-beginning 0) (match-end 0)))
6708 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
6709 (setq link (read-string "Link: "
6710 (org-link-unescape
6711 (org-match-string-no-properties 1)))))
6712 ((or (org-in-regexp org-angle-link-re)
6713 (org-in-regexp org-plain-link-re))
6714 ;; Convert to bracket link
6715 (setq remove (list (match-beginning 0) (match-end 0))
6716 link (read-string "Link: "
6717 (org-remove-angle-brackets (match-string 0)))))
6718 ((member complete-file '((4) (16)))
6719 ;; Completing read for file names.
6720 (setq file (read-file-name "File: "))
6721 (let ((pwd (file-name-as-directory (expand-file-name ".")))
6722 (pwd1 (file-name-as-directory (abbreviate-file-name
6723 (expand-file-name ".")))))
6724 (cond
6725 ((equal complete-file '(16))
6726 (setq link (org-make-link
6727 "file:"
6728 (abbreviate-file-name (expand-file-name file)))))
6729 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
6730 (setq link (org-make-link "file:" (match-string 1 file))))
6731 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
6732 (expand-file-name file))
6733 (setq link (org-make-link
6734 "file:" (match-string 1 (expand-file-name file)))))
6735 (t (setq link (org-make-link "file:" file))))))
6737 ;; Read link, with completion for stored links.
6738 (with-output-to-temp-buffer "*Org Links*"
6739 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
6740 (when org-stored-links
6741 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
6742 (princ (mapconcat
6743 (lambda (x)
6744 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
6745 (reverse org-stored-links) "\n"))))
6746 (let ((cw (selected-window)))
6747 (select-window (get-buffer-window "*Org Links*"))
6748 (setq truncate-lines t)
6749 (org-fit-window-to-buffer)
6750 (select-window cw))
6751 ;; Fake a link history, containing the stored links.
6752 (setq tmphist (append (mapcar 'car org-stored-links)
6753 org-insert-link-history))
6754 (unwind-protect
6755 (setq link
6756 (let ((org-completion-use-ido nil))
6757 (org-completing-read
6758 "Link: "
6759 (append
6760 (mapcar (lambda (x) (list (concat (car x) ":")))
6761 (append org-link-abbrev-alist-local org-link-abbrev-alist))
6762 (mapcar (lambda (x) (list (concat x ":")))
6763 org-link-types))
6764 nil nil nil
6765 'tmphist
6766 (or (car (car org-stored-links))))))
6767 (set-window-configuration wcf)
6768 (kill-buffer "*Org Links*"))
6769 (setq entry (assoc link org-stored-links))
6770 (or entry (push link org-insert-link-history))
6771 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
6772 (not org-keep-stored-link-after-insertion))
6773 (setq org-stored-links (delq (assoc link org-stored-links)
6774 org-stored-links)))
6775 (setq desc (or desc (nth 1 entry)))))
6777 (if (string-match org-plain-link-re link)
6778 ;; URL-like link, normalize the use of angular brackets.
6779 (setq link (org-make-link (org-remove-angle-brackets link))))
6781 ;; Check if we are linking to the current file with a search option
6782 ;; If yes, simplify the link by using only the search option.
6783 (when (and buffer-file-name
6784 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
6785 (let* ((path (match-string 1 link))
6786 (case-fold-search nil)
6787 (search (match-string 2 link)))
6788 (save-match-data
6789 (if (equal (file-truename buffer-file-name) (file-truename path))
6790 ;; We are linking to this same file, with a search option
6791 (setq link search)))))
6793 ;; Check if we can/should use a relative path. If yes, simplify the link
6794 (when (string-match "^file:\\(.*\\)" link)
6795 (let* ((path (match-string 1 link))
6796 (origpath path)
6797 (case-fold-search nil))
6798 (cond
6799 ((or (eq org-link-file-path-type 'absolute)
6800 (equal complete-file '(16)))
6801 (setq path (abbreviate-file-name (expand-file-name path))))
6802 ((eq org-link-file-path-type 'noabbrev)
6803 (setq path (expand-file-name path)))
6804 ((eq org-link-file-path-type 'relative)
6805 (setq path (file-relative-name path)))
6807 (save-match-data
6808 (if (string-match (concat "^" (regexp-quote
6809 (file-name-as-directory
6810 (expand-file-name "."))))
6811 (expand-file-name path))
6812 ;; We are linking a file with relative path name.
6813 (setq path (substring (expand-file-name path)
6814 (match-end 0)))
6815 (setq path (abbreviate-file-name (expand-file-name path)))))))
6816 (setq link (concat "file:" path))
6817 (if (equal desc origpath)
6818 (setq desc path))))
6820 (if org-make-link-description-function
6821 (setq desc (funcall org-make-link-description-function link desc)))
6823 (setq desc (read-string "Description: " desc))
6824 (unless (string-match "\\S-" desc) (setq desc nil))
6825 (if remove (apply 'delete-region remove))
6826 (insert (org-make-link-string link desc))))
6828 (defun org-completing-read (&rest args)
6829 "Completing-read with SPACE being a normal character."
6830 (let ((minibuffer-local-completion-map
6831 (copy-keymap minibuffer-local-completion-map)))
6832 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
6833 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
6834 (apply 'org-ido-completing-read args)))
6836 (defun org-ido-completing-read (&rest args)
6837 "Completing-read using `ido-mode' speedups if available"
6838 (if (and org-completion-use-ido
6839 (fboundp 'ido-completing-read)
6840 (boundp 'ido-mode) ido-mode
6841 (listp (second args)))
6842 (apply 'ido-completing-read (concat (car args)) (cdr args))
6843 (apply 'completing-read args)))
6845 (defun org-extract-attributes (s)
6846 "Extract the attributes cookie from a string and set as text property."
6847 (let (a attr (start 0) key value)
6848 (save-match-data
6849 (when (string-match "{{\\([^}]+\\)}}$" s)
6850 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
6851 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
6852 (setq key (match-string 1 a) value (match-string 2 a)
6853 start (match-end 0)
6854 attr (plist-put attr (intern key) value))))
6855 (org-add-props s nil 'org-attr attr))
6858 (defun org-attributes-to-string (plist)
6859 "Format a property list into an HTML attribute list."
6860 (let ((s "") key value)
6861 (while plist
6862 (setq key (pop plist) value (pop plist))
6863 (and value
6864 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
6867 ;;; Opening/following a link
6869 (defvar org-link-search-failed nil)
6871 (defun org-next-link ()
6872 "Move forward to the next link.
6873 If the link is in hidden text, expose it."
6874 (interactive)
6875 (when (and org-link-search-failed (eq this-command last-command))
6876 (goto-char (point-min))
6877 (message "Link search wrapped back to beginning of buffer"))
6878 (setq org-link-search-failed nil)
6879 (let* ((pos (point))
6880 (ct (org-context))
6881 (a (assoc :link ct)))
6882 (if a (goto-char (nth 2 a)))
6883 (if (re-search-forward org-any-link-re nil t)
6884 (progn
6885 (goto-char (match-beginning 0))
6886 (if (org-invisible-p) (org-show-context)))
6887 (goto-char pos)
6888 (setq org-link-search-failed t)
6889 (error "No further link found"))))
6891 (defun org-previous-link ()
6892 "Move backward to the previous link.
6893 If the link is in hidden text, expose it."
6894 (interactive)
6895 (when (and org-link-search-failed (eq this-command last-command))
6896 (goto-char (point-max))
6897 (message "Link search wrapped back to end of buffer"))
6898 (setq org-link-search-failed nil)
6899 (let* ((pos (point))
6900 (ct (org-context))
6901 (a (assoc :link ct)))
6902 (if a (goto-char (nth 1 a)))
6903 (if (re-search-backward org-any-link-re nil t)
6904 (progn
6905 (goto-char (match-beginning 0))
6906 (if (org-invisible-p) (org-show-context)))
6907 (goto-char pos)
6908 (setq org-link-search-failed t)
6909 (error "No further link found"))))
6911 (defun org-translate-link (s)
6912 "Translate a link string if a translation function has been defined."
6913 (if (and org-link-translation-function
6914 (fboundp org-link-translation-function)
6915 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
6916 (progn
6917 (setq s (funcall org-link-translation-function
6918 (match-string 1) (match-string 2)))
6919 (concat (car s) ":" (cdr s)))
6922 (defun org-translate-link-from-planner (type path)
6923 "Translate a link from Emacs Planner syntax so that Org can follow it.
6924 This is still an experimental function, your mileage may vary."
6925 (cond
6926 ((member type '("http" "https" "news" "ftp"))
6927 ;; standard Internet links are the same.
6928 nil)
6929 ((and (equal type "irc") (string-match "^//" path))
6930 ;; Planner has two / at the beginning of an irc link, we have 1.
6931 ;; We should have zero, actually....
6932 (setq path (substring path 1)))
6933 ((and (equal type "lisp") (string-match "^/" path))
6934 ;; Planner has a slash, we do not.
6935 (setq type "elisp" path (substring path 1)))
6936 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
6937 ;; A typical message link. Planner has the id after the fina slash,
6938 ;; we separate it with a hash mark
6939 (setq path (concat (match-string 1 path) "#"
6940 (org-remove-angle-brackets (match-string 2 path)))))
6942 (cons type path))
6944 (defun org-find-file-at-mouse (ev)
6945 "Open file link or URL at mouse."
6946 (interactive "e")
6947 (mouse-set-point ev)
6948 (org-open-at-point 'in-emacs))
6950 (defun org-open-at-mouse (ev)
6951 "Open file link or URL at mouse."
6952 (interactive "e")
6953 (mouse-set-point ev)
6954 (if (eq major-mode 'org-agenda-mode)
6955 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
6956 (org-open-at-point))
6958 (defvar org-window-config-before-follow-link nil
6959 "The window configuration before following a link.
6960 This is saved in case the need arises to restore it.")
6962 (defvar org-open-link-marker (make-marker)
6963 "Marker pointing to the location where `org-open-at-point; was called.")
6965 ;;;###autoload
6966 (defun org-open-at-point-global ()
6967 "Follow a link like Org-mode does.
6968 This command can be called in any mode to follow a link that has
6969 Org-mode syntax."
6970 (interactive)
6971 (org-run-like-in-org-mode 'org-open-at-point))
6973 ;;;###autoload
6974 (defun org-open-link-from-string (s &optional arg)
6975 "Open a link in the string S, as if it was in Org-mode."
6976 (interactive "sLink: \nP")
6977 (with-temp-buffer
6978 (let ((org-inhibit-startup t))
6979 (org-mode)
6980 (insert s)
6981 (goto-char (point-min))
6982 (org-open-at-point arg))))
6984 (defun org-open-at-point (&optional in-emacs)
6985 "Open link at or after point.
6986 If there is no link at point, this function will search forward up to
6987 the end of the current subtree.
6988 Normally, files will be opened by an appropriate application. If the
6989 optional argument IN-EMACS is non-nil, Emacs will visit the file.
6990 With a double prefix argument, try to open outside of Emacs, in the
6991 application the system uses for this file type."
6992 (interactive "P")
6993 (org-load-modules-maybe)
6994 (move-marker org-open-link-marker (point))
6995 (setq org-window-config-before-follow-link (current-window-configuration))
6996 (org-remove-occur-highlights nil nil t)
6997 (cond
6998 ((org-at-timestamp-p t) (org-follow-timestamp-link))
6999 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
7000 (org-footnote-action))
7002 (let (type path link line search (pos (point)))
7003 (catch 'match
7004 (save-excursion
7005 (skip-chars-forward "^]\n\r")
7006 (when (org-in-regexp org-bracket-link-regexp)
7007 (setq link (org-extract-attributes
7008 (org-link-unescape (org-match-string-no-properties 1))))
7009 (while (string-match " *\n *" link)
7010 (setq link (replace-match " " t t link)))
7011 (setq link (org-link-expand-abbrev link))
7012 (cond
7013 ((or (file-name-absolute-p link)
7014 (string-match "^\\.\\.?/" link))
7015 (setq type "file" path link))
7016 ((string-match org-link-re-with-space3 link)
7017 (setq type (match-string 1 link) path (match-string 2 link)))
7018 (t (setq type "thisfile" path link)))
7019 (throw 'match t)))
7021 (when (get-text-property (point) 'org-linked-text)
7022 (setq type "thisfile"
7023 pos (if (get-text-property (1+ (point)) 'org-linked-text)
7024 (1+ (point)) (point))
7025 path (buffer-substring
7026 (previous-single-property-change pos 'org-linked-text)
7027 (next-single-property-change pos 'org-linked-text)))
7028 (throw 'match t))
7030 (save-excursion
7031 (when (or (org-in-regexp org-angle-link-re)
7032 (org-in-regexp org-plain-link-re))
7033 (setq type (match-string 1) path (match-string 2))
7034 (throw 'match t)))
7035 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
7036 (setq type "tree-match"
7037 path (match-string 1))
7038 (throw 'match t))
7039 (save-excursion
7040 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
7041 (setq type "tags"
7042 path (match-string 1))
7043 (while (string-match ":" path)
7044 (setq path (replace-match "+" t t path)))
7045 (throw 'match t))))
7046 (unless path
7047 (error "No link found"))
7048 ;; Remove any trailing spaces in path
7049 (if (string-match " +\\'" path)
7050 (setq path (replace-match "" t t path)))
7051 (if (and org-link-translation-function
7052 (fboundp org-link-translation-function))
7053 ;; Check if we need to translate the link
7054 (let ((tmp (funcall org-link-translation-function type path)))
7055 (setq type (car tmp) path (cdr tmp))))
7057 (cond
7059 ((assoc type org-link-protocols)
7060 (funcall (nth 1 (assoc type org-link-protocols)) path))
7062 ((equal type "mailto")
7063 (let ((cmd (car org-link-mailto-program))
7064 (args (cdr org-link-mailto-program)) args1
7065 (address path) (subject "") a)
7066 (if (string-match "\\(.*\\)::\\(.*\\)" path)
7067 (setq address (match-string 1 path)
7068 subject (org-link-escape (match-string 2 path))))
7069 (while args
7070 (cond
7071 ((not (stringp (car args))) (push (pop args) args1))
7072 (t (setq a (pop args))
7073 (if (string-match "%a" a)
7074 (setq a (replace-match address t t a)))
7075 (if (string-match "%s" a)
7076 (setq a (replace-match subject t t a)))
7077 (push a args1))))
7078 (apply cmd (nreverse args1))))
7080 ((member type '("http" "https" "ftp" "news"))
7081 (browse-url (concat type ":" (org-link-escape
7082 path org-link-escape-chars-browser))))
7084 ((member type '("message"))
7085 (browse-url (concat type ":" path)))
7087 ((string= type "tags")
7088 (org-tags-view in-emacs path))
7089 ((string= type "thisfile")
7090 (if in-emacs
7091 (switch-to-buffer-other-window
7092 (org-get-buffer-for-internal-link (current-buffer)))
7093 (org-mark-ring-push))
7094 (let ((cmd `(org-link-search
7095 ,path
7096 ,(cond ((equal in-emacs '(4)) 'occur)
7097 ((equal in-emacs '(16)) 'org-occur)
7098 (t nil))
7099 ,pos)))
7100 (condition-case nil (eval cmd)
7101 (error (progn (widen) (eval cmd))))))
7103 ((string= type "tree-match")
7104 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
7106 ((string= type "file")
7107 (if (string-match "::\\([0-9]+\\)\\'" path)
7108 (setq line (string-to-number (match-string 1 path))
7109 path (substring path 0 (match-beginning 0)))
7110 (if (string-match "::\\(.+\\)\\'" path)
7111 (setq search (match-string 1 path)
7112 path (substring path 0 (match-beginning 0)))))
7113 (if (string-match "[*?{]" (file-name-nondirectory path))
7114 (dired path)
7115 (org-open-file path in-emacs line search)))
7117 ((string= type "news")
7118 (require 'org-gnus)
7119 (org-gnus-follow-link path))
7121 ((string= type "shell")
7122 (let ((cmd path))
7123 (if (or (not org-confirm-shell-link-function)
7124 (funcall org-confirm-shell-link-function
7125 (format "Execute \"%s\" in shell? "
7126 (org-add-props cmd nil
7127 'face 'org-warning))))
7128 (progn
7129 (message "Executing %s" cmd)
7130 (shell-command cmd))
7131 (error "Abort"))))
7133 ((string= type "elisp")
7134 (let ((cmd path))
7135 (if (or (not org-confirm-elisp-link-function)
7136 (funcall org-confirm-elisp-link-function
7137 (format "Execute \"%s\" as elisp? "
7138 (org-add-props cmd nil
7139 'face 'org-warning))))
7140 (message "%s => %s" cmd
7141 (if (equal (string-to-char cmd) ?\()
7142 (eval (read cmd))
7143 (call-interactively (read cmd))))
7144 (error "Abort"))))
7147 (browse-url-at-point))))))
7148 (move-marker org-open-link-marker nil)
7149 (run-hook-with-args 'org-follow-link-hook))
7151 ;;;; Time estimates
7153 (defun org-get-effort (&optional pom)
7154 "Get the effort estimate for the current entry."
7155 (org-entry-get pom org-effort-property))
7157 ;;; File search
7159 (defvar org-create-file-search-functions nil
7160 "List of functions to construct the right search string for a file link.
7161 These functions are called in turn with point at the location to
7162 which the link should point.
7164 A function in the hook should first test if it would like to
7165 handle this file type, for example by checking the major-mode or
7166 the file extension. If it decides not to handle this file, it
7167 should just return nil to give other functions a chance. If it
7168 does handle the file, it must return the search string to be used
7169 when following the link. The search string will be part of the
7170 file link, given after a double colon, and `org-open-at-point'
7171 will automatically search for it. If special measures must be
7172 taken to make the search successful, another function should be
7173 added to the companion hook `org-execute-file-search-functions',
7174 which see.
7176 A function in this hook may also use `setq' to set the variable
7177 `description' to provide a suggestion for the descriptive text to
7178 be used for this link when it gets inserted into an Org-mode
7179 buffer with \\[org-insert-link].")
7181 (defvar org-execute-file-search-functions nil
7182 "List of functions to execute a file search triggered by a link.
7184 Functions added to this hook must accept a single argument, the
7185 search string that was part of the file link, the part after the
7186 double colon. The function must first check if it would like to
7187 handle this search, for example by checking the major-mode or the
7188 file extension. If it decides not to handle this search, it
7189 should just return nil to give other functions a chance. If it
7190 does handle the search, it must return a non-nil value to keep
7191 other functions from trying.
7193 Each function can access the current prefix argument through the
7194 variable `current-prefix-argument'. Note that a single prefix is
7195 used to force opening a link in Emacs, so it may be good to only
7196 use a numeric or double prefix to guide the search function.
7198 In case this is needed, a function in this hook can also restore
7199 the window configuration before `org-open-at-point' was called using:
7201 (set-window-configuration org-window-config-before-follow-link)")
7203 (defun org-link-search (s &optional type avoid-pos)
7204 "Search for a link search option.
7205 If S is surrounded by forward slashes, it is interpreted as a
7206 regular expression. In org-mode files, this will create an `org-occur'
7207 sparse tree. In ordinary files, `occur' will be used to list matches.
7208 If the current buffer is in `dired-mode', grep will be used to search
7209 in all files. If AVOID-POS is given, ignore matches near that position."
7210 (let ((case-fold-search t)
7211 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
7212 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
7213 (append '(("") (" ") ("\t") ("\n"))
7214 org-emphasis-alist)
7215 "\\|") "\\)"))
7216 (pos (point))
7217 (pre nil) (post nil)
7218 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
7219 (cond
7220 ;; First check if there are any special
7221 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
7222 ;; Now try the builtin stuff
7223 ((save-excursion
7224 (goto-char (point-min))
7225 (and
7226 (re-search-forward
7227 (concat "<<" (regexp-quote s0) ">>") nil t)
7228 (setq type 'dedicated
7229 pos (match-beginning 0))))
7230 ;; There is an exact target for this
7231 (goto-char pos))
7232 ((and (string-match "^(\\(.*\\))$" s0)
7233 (save-excursion
7234 (goto-char (point-min))
7235 (and
7236 (re-search-forward
7237 (concat "[^[]" (regexp-quote
7238 (format org-coderef-label-format
7239 (match-string 1 s0))))
7240 nil t)
7241 (setq type 'dedicated
7242 pos (1+ (match-beginning 0))))))
7243 ;; There is a coderef target for this
7244 (goto-char pos))
7245 ((string-match "^/\\(.*\\)/$" s)
7246 ;; A regular expression
7247 (cond
7248 ((org-mode-p)
7249 (org-occur (match-string 1 s)))
7250 ;;((eq major-mode 'dired-mode)
7251 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
7252 (t (org-do-occur (match-string 1 s)))))
7254 ;; A normal search strings
7255 (when (equal (string-to-char s) ?*)
7256 ;; Anchor on headlines, post may include tags.
7257 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
7258 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
7259 s (substring s 1)))
7260 (remove-text-properties
7261 0 (length s)
7262 '(face nil mouse-face nil keymap nil fontified nil) s)
7263 ;; Make a series of regular expressions to find a match
7264 (setq words (org-split-string s "[ \n\r\t]+")
7266 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
7267 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
7268 "\\)" markers)
7269 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
7270 re2a (concat "[ \t\r\n]" re2a_)
7271 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
7272 re4 (concat "[^a-zA-Z_]" re4_)
7274 re1 (concat pre re2 post)
7275 re3 (concat pre (if pre re4_ re4) post)
7276 re5 (concat pre ".*" re4)
7277 re2 (concat pre re2)
7278 re2a (concat pre (if pre re2a_ re2a))
7279 re4 (concat pre (if pre re4_ re4))
7280 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7281 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7282 re5 "\\)"
7284 (cond
7285 ((eq type 'org-occur) (org-occur reall))
7286 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7287 (t (goto-char (point-min))
7288 (setq type 'fuzzy)
7289 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
7290 (org-search-not-self 1 re1 nil t)
7291 (org-search-not-self 1 re2 nil t)
7292 (org-search-not-self 1 re2a nil t)
7293 (org-search-not-self 1 re3 nil t)
7294 (org-search-not-self 1 re4 nil t)
7295 (org-search-not-self 1 re5 nil t)
7297 (goto-char (match-beginning 1))
7298 (goto-char pos)
7299 (error "No match")))))
7301 ;; Normal string-search
7302 (goto-char (point-min))
7303 (if (search-forward s nil t)
7304 (goto-char (match-beginning 0))
7305 (error "No match"))))
7306 (and (org-mode-p) (org-show-context 'link-search))
7307 type))
7309 (defun org-search-not-self (group &rest args)
7310 "Execute `re-search-forward', but only accept matches that do not
7311 enclose the position of `org-open-link-marker'."
7312 (let ((m org-open-link-marker))
7313 (catch 'exit
7314 (while (apply 're-search-forward args)
7315 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
7316 (goto-char (match-end group))
7317 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
7318 (> (match-beginning 0) (marker-position m))
7319 (< (match-end 0) (marker-position m)))
7320 (save-match-data
7321 (or (not (org-in-regexp
7322 org-bracket-link-analytic-regexp 1))
7323 (not (match-end 4)) ; no description
7324 (and (<= (match-beginning 4) (point))
7325 (>= (match-end 4) (point))))))
7326 (throw 'exit (point))))))))
7328 (defun org-get-buffer-for-internal-link (buffer)
7329 "Return a buffer to be used for displaying the link target of internal links."
7330 (cond
7331 ((not org-display-internal-link-with-indirect-buffer)
7332 buffer)
7333 ((string-match "(Clone)$" (buffer-name buffer))
7334 (message "Buffer is already a clone, not making another one")
7335 ;; we also do not modify visibility in this case
7336 buffer)
7337 (t ; make a new indirect buffer for displaying the link
7338 (let* ((bn (buffer-name buffer))
7339 (ibn (concat bn "(Clone)"))
7340 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
7341 (with-current-buffer ib (org-overview))
7342 ib))))
7344 (defun org-do-occur (regexp &optional cleanup)
7345 "Call the Emacs command `occur'.
7346 If CLEANUP is non-nil, remove the printout of the regular expression
7347 in the *Occur* buffer. This is useful if the regex is long and not useful
7348 to read."
7349 (occur regexp)
7350 (when cleanup
7351 (let ((cwin (selected-window)) win beg end)
7352 (when (setq win (get-buffer-window "*Occur*"))
7353 (select-window win))
7354 (goto-char (point-min))
7355 (when (re-search-forward "match[a-z]+" nil t)
7356 (setq beg (match-end 0))
7357 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7358 (setq end (1- (match-beginning 0)))))
7359 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
7360 (goto-char (point-min))
7361 (select-window cwin))))
7363 ;;; The mark ring for links jumps
7365 (defvar org-mark-ring nil
7366 "Mark ring for positions before jumps in Org-mode.")
7367 (defvar org-mark-ring-last-goto nil
7368 "Last position in the mark ring used to go back.")
7369 ;; Fill and close the ring
7370 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7371 (loop for i from 1 to org-mark-ring-length do
7372 (push (make-marker) org-mark-ring))
7373 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7374 org-mark-ring)
7376 (defun org-mark-ring-push (&optional pos buffer)
7377 "Put the current position or POS into the mark ring and rotate it."
7378 (interactive)
7379 (setq pos (or pos (point)))
7380 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7381 (move-marker (car org-mark-ring)
7382 (or pos (point))
7383 (or buffer (current-buffer)))
7384 (message "%s"
7385 (substitute-command-keys
7386 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7388 (defun org-mark-ring-goto (&optional n)
7389 "Jump to the previous position in the mark ring.
7390 With prefix arg N, jump back that many stored positions. When
7391 called several times in succession, walk through the entire ring.
7392 Org-mode commands jumping to a different position in the current file,
7393 or to another Org-mode file, automatically push the old position
7394 onto the ring."
7395 (interactive "p")
7396 (let (p m)
7397 (if (eq last-command this-command)
7398 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7399 (setq p org-mark-ring))
7400 (setq org-mark-ring-last-goto p)
7401 (setq m (car p))
7402 (switch-to-buffer (marker-buffer m))
7403 (goto-char m)
7404 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
7406 (defun org-remove-angle-brackets (s)
7407 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7408 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7410 (defun org-add-angle-brackets (s)
7411 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7412 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7414 (defun org-remove-double-quotes (s)
7415 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
7416 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
7419 ;;; Following specific links
7421 (defun org-follow-timestamp-link ()
7422 (cond
7423 ((org-at-date-range-p t)
7424 (let ((org-agenda-start-on-weekday)
7425 (t1 (match-string 1))
7426 (t2 (match-string 2)))
7427 (setq t1 (time-to-days (org-time-string-to-time t1))
7428 t2 (time-to-days (org-time-string-to-time t2)))
7429 (org-agenda-list nil t1 (1+ (- t2 t1)))))
7430 ((org-at-timestamp-p t)
7431 (org-agenda-list nil (time-to-days (org-time-string-to-time
7432 (substring (match-string 1) 0 10)))
7434 (t (error "This should not happen"))))
7437 ;;; Following file links
7438 (defvar org-wait nil)
7439 (defun org-open-file (path &optional in-emacs line search)
7440 "Open the file at PATH.
7441 First, this expands any special file name abbreviations. Then the
7442 configuration variable `org-file-apps' is checked if it contains an
7443 entry for this file type, and if yes, the corresponding command is launched.
7445 If no application is found, Emacs simply visits the file.
7447 With optional prefix argument IN-EMACS, Emacs will visit the file.
7448 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
7449 and o use an external application to visit the file.
7451 Optional LINE specifies a line to go to, optional SEARCH a string to
7452 search for. If LINE or SEARCH is given, the file will always be
7453 opened in Emacs.
7454 If the file does not exist, an error is thrown."
7455 (setq in-emacs (or in-emacs line search))
7456 (let* ((file (if (equal path "")
7457 buffer-file-name
7458 (substitute-in-file-name (expand-file-name path))))
7459 (apps (append org-file-apps (org-default-apps)))
7460 (remp (and (assq 'remote apps) (org-file-remote-p file)))
7461 (dirp (if remp nil (file-directory-p file)))
7462 (file (if (and dirp org-open-directory-means-index-dot-org)
7463 (concat (file-name-as-directory file) "index.org")
7464 file))
7465 (a-m-a-p (assq 'auto-mode apps))
7466 (dfile (downcase file))
7467 (old-buffer (current-buffer))
7468 (old-pos (point))
7469 (old-mode major-mode)
7470 ext cmd)
7471 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7472 (setq ext (match-string 1 dfile))
7473 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7474 (setq ext (match-string 1 dfile))))
7475 (cond
7476 ((equal in-emacs '(16))
7477 (setq cmd (cdr (assoc 'system apps))))
7478 (in-emacs (setq cmd 'emacs))
7480 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
7481 (and dirp (cdr (assoc 'directory apps)))
7482 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
7483 'string-match)
7484 (cdr (assoc ext apps))
7485 (cdr (assoc t apps))))))
7486 (when (eq cmd 'system)
7487 (setq cmd (cdr (assoc 'system apps))))
7488 (when (eq cmd 'default)
7489 (setq cmd (cdr (assoc t apps))))
7490 (when (eq cmd 'mailcap)
7491 (require 'mailcap)
7492 (mailcap-parse-mailcaps)
7493 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7494 (command (mailcap-mime-info mime-type)))
7495 (if (stringp command)
7496 (setq cmd command)
7497 (setq cmd 'emacs))))
7498 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
7499 (not (file-exists-p file))
7500 (not org-open-non-existing-files))
7501 (error "No such file: %s" file))
7502 (cond
7503 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7504 ;; Remove quotes around the file name - we'll use shell-quote-argument.
7505 (while (string-match "['\"]%s['\"]" cmd)
7506 (setq cmd (replace-match "%s" t t cmd)))
7507 (while (string-match "%s" cmd)
7508 (setq cmd (replace-match
7509 (save-match-data
7510 (shell-quote-argument
7511 (convert-standard-filename file)))
7512 t t cmd)))
7513 (save-window-excursion
7514 (start-process-shell-command cmd nil cmd)
7515 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
7517 ((or (stringp cmd)
7518 (eq cmd 'emacs))
7519 (funcall (cdr (assq 'file org-link-frame-setup)) file)
7520 (widen)
7521 (if line (goto-line line)
7522 (if search (org-link-search search))))
7523 ((consp cmd)
7524 (let ((file (convert-standard-filename file)))
7525 (eval cmd)))
7526 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7527 (and (org-mode-p) (eq old-mode 'org-mode)
7528 (or (not (equal old-buffer (current-buffer)))
7529 (not (equal old-pos (point))))
7530 (org-mark-ring-push old-pos old-buffer))))
7532 (defun org-default-apps ()
7533 "Return the default applications for this operating system."
7534 (cond
7535 ((eq system-type 'darwin)
7536 org-file-apps-defaults-macosx)
7537 ((eq system-type 'windows-nt)
7538 org-file-apps-defaults-windowsnt)
7539 (t org-file-apps-defaults-gnu)))
7541 (defun org-apps-regexp-alist (list &optional add-auto-mode)
7542 "Convert extensions to regular expressions in the cars of LIST.
7543 Also, weed out any non-string entries, because the return value is used
7544 only for regexp matching.
7545 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
7546 point to the symbol `emacs', indicating that the file should
7547 be opened in Emacs."
7548 (append
7549 (delq nil
7550 (mapcar (lambda (x)
7551 (if (not (stringp (car x)))
7553 (if (string-match "\\W" (car x))
7555 (cons (concat "\\." (car x) "\\'") (cdr x)))))
7556 list))
7557 (if add-auto-mode
7558 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
7560 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
7561 (defun org-file-remote-p (file)
7562 "Test whether FILE specifies a location on a remote system.
7563 Return non-nil if the location is indeed remote.
7565 For example, the filename \"/user@host:/foo\" specifies a location
7566 on the system \"/user@host:\"."
7567 (cond ((fboundp 'file-remote-p)
7568 (file-remote-p file))
7569 ((fboundp 'tramp-handle-file-remote-p)
7570 (tramp-handle-file-remote-p file))
7571 ((and (boundp 'ange-ftp-name-format)
7572 (string-match (car ange-ftp-name-format) file))
7574 (t nil)))
7577 ;;;; Refiling
7579 (defun org-get-org-file ()
7580 "Read a filename, with default directory `org-directory'."
7581 (let ((default (or org-default-notes-file remember-data-file)))
7582 (read-file-name (format "File name [%s]: " default)
7583 (file-name-as-directory org-directory)
7584 default)))
7586 (defun org-notes-order-reversed-p ()
7587 "Check if the current file should receive notes in reversed order."
7588 (cond
7589 ((not org-reverse-note-order) nil)
7590 ((eq t org-reverse-note-order) t)
7591 ((not (listp org-reverse-note-order)) nil)
7592 (t (catch 'exit
7593 (let ((all org-reverse-note-order)
7594 entry)
7595 (while (setq entry (pop all))
7596 (if (string-match (car entry) buffer-file-name)
7597 (throw 'exit (cdr entry))))
7598 nil)))))
7600 (defvar org-refile-target-table nil
7601 "The list of refile targets, created by `org-refile'.")
7603 (defvar org-agenda-new-buffers nil
7604 "Buffers created to visit agenda files.")
7606 (defun org-get-refile-targets (&optional default-buffer)
7607 "Produce a table with refile targets."
7608 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
7609 targets txt re files f desc descre fast-path-p level)
7610 (message "Getting targets...")
7611 (with-current-buffer (or default-buffer (current-buffer))
7612 (while (setq entry (pop entries))
7613 (setq files (car entry) desc (cdr entry))
7614 (setq fast-path-p nil)
7615 (cond
7616 ((null files) (setq files (list (current-buffer))))
7617 ((eq files 'org-agenda-files)
7618 (setq files (org-agenda-files 'unrestricted)))
7619 ((and (symbolp files) (fboundp files))
7620 (setq files (funcall files)))
7621 ((and (symbolp files) (boundp files))
7622 (setq files (symbol-value files))))
7623 (if (stringp files) (setq files (list files)))
7624 (cond
7625 ((eq (car desc) :tag)
7626 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
7627 ((eq (car desc) :todo)
7628 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
7629 ((eq (car desc) :regexp)
7630 (setq descre (cdr desc)))
7631 ((eq (car desc) :level)
7632 (setq descre (concat "^\\*\\{" (number-to-string
7633 (if org-odd-levels-only
7634 (1- (* 2 (cdr desc)))
7635 (cdr desc)))
7636 "\\}[ \t]")))
7637 ((eq (car desc) :maxlevel)
7638 (setq fast-path-p t)
7639 (setq descre (concat "^\\*\\{1," (number-to-string
7640 (if org-odd-levels-only
7641 (1- (* 2 (cdr desc)))
7642 (cdr desc)))
7643 "\\}[ \t]")))
7644 (t (error "Bad refiling target description %s" desc)))
7645 (while (setq f (pop files))
7646 (save-excursion
7647 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
7648 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
7649 (setq f (expand-file-name f))
7650 (save-excursion
7651 (save-restriction
7652 (widen)
7653 (goto-char (point-min))
7654 (while (re-search-forward descre nil t)
7655 (goto-char (point-at-bol))
7656 (when (looking-at org-complex-heading-regexp)
7657 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
7658 txt (org-link-display-format (match-string 4))
7659 re (concat "^" (regexp-quote
7660 (buffer-substring (match-beginning 1)
7661 (match-end 4)))))
7662 (if (match-end 5) (setq re (concat re "[ \t]+"
7663 (regexp-quote
7664 (match-string 5)))))
7665 (setq re (concat re "[ \t]*$"))
7666 (when org-refile-use-outline-path
7667 (setq txt (mapconcat 'org-protect-slash
7668 (append
7669 (if (eq org-refile-use-outline-path 'file)
7670 (list (file-name-nondirectory
7671 (buffer-file-name (buffer-base-buffer))))
7672 (if (eq org-refile-use-outline-path 'full-file-path)
7673 (list (buffer-file-name (buffer-base-buffer)))))
7674 (org-get-outline-path fast-path-p level txt)
7675 (list txt))
7676 "/")))
7677 (push (list txt f re (point)) targets))
7678 (goto-char (point-at-eol))))))))
7679 (message "Getting targets...done")
7680 (nreverse targets))))
7682 (defun org-protect-slash (s)
7683 (while (string-match "/" s)
7684 (setq s (replace-match "\\" t t s)))
7687 (defvar org-olpa (make-vector 20 nil))
7689 (defun org-get-outline-path (&optional fastp level heading)
7690 "Return the outline path to the current entry, as a list."
7691 (if fastp
7692 (progn
7693 (if (> level 19)
7694 (error "Outline path failure, more than 19 levels."))
7695 (loop for i from level upto 19 do
7696 (aset org-olpa i nil))
7697 (prog1
7698 (delq nil (append org-olpa nil))
7699 (aset org-olpa level heading)))
7700 (let (rtn)
7701 (save-excursion
7702 (while (org-up-heading-safe)
7703 (when (looking-at org-complex-heading-regexp)
7704 (push (org-match-string-no-properties 4) rtn)))
7705 rtn))))
7707 (defvar org-refile-history nil
7708 "History for refiling operations.")
7710 (defun org-refile (&optional goto default-buffer)
7711 "Move the entry at point to another heading.
7712 The list of target headings is compiled using the information in
7713 `org-refile-targets', which see. This list is created before each use
7714 and will therefore always be up-to-date.
7716 At the target location, the entry is filed as a subitem of the target heading.
7717 Depending on `org-reverse-note-order', the new subitem will either be the
7718 first or the last subitem.
7720 If there is an active region, all entries in that region will be moved.
7721 However, the region must fulfil the requirement that the first heading
7722 is the first one sets the top-level of the moved text - at most siblings
7723 below it are allowed.
7725 With prefix arg GOTO, the command will only visit the target location,
7726 not actually move anything.
7727 With a double prefix `C-u C-u', go to the location where the last refiling
7728 operation has put the subtree."
7729 (interactive "P")
7730 (let* ((cbuf (current-buffer))
7731 (regionp (org-region-active-p))
7732 (region-start (and regionp (region-beginning)))
7733 (region-end (and regionp (region-end)))
7734 (region-length (and regionp (- region-end region-start)))
7735 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7736 pos it nbuf file re level reversed)
7737 (when regionp (goto-char region-start)
7738 (unless (org-kill-is-subtree-p
7739 (buffer-substring region-start region-end))
7740 (error "The region is not a (sequence of) subtree(s)")))
7741 (if (equal goto '(16))
7742 (org-refile-goto-last-stored)
7743 (when (setq it (org-refile-get-location
7744 (if goto "Goto: " "Refile to: ") default-buffer))
7745 (setq file (nth 1 it)
7746 re (nth 2 it)
7747 pos (nth 3 it))
7748 (if (and (equal (buffer-file-name) file)
7749 (if regionp
7750 (and (>= pos region-start)
7751 (<= pos region-end))
7752 (and (>= pos (point))
7753 (< pos (save-excursion
7754 (org-end-of-subtree t t))))))
7755 (error "Cannot refile to position inside the tree or region"))
7757 (setq nbuf (or (find-buffer-visiting file)
7758 (find-file-noselect file)))
7759 (if goto
7760 (progn
7761 (switch-to-buffer nbuf)
7762 (goto-char pos)
7763 (org-show-context 'org-goto))
7764 (if regionp
7765 (progn
7766 (kill-new (buffer-substring region-start region-end))
7767 (org-save-markers-in-region region-start region-end))
7768 (org-copy-subtree 1 nil t))
7769 (save-excursion
7770 (set-buffer (setq nbuf (or (find-buffer-visiting file)
7771 (find-file-noselect file))))
7772 (setq reversed (org-notes-order-reversed-p))
7773 (save-excursion
7774 (save-restriction
7775 (widen)
7776 (goto-char pos)
7777 (looking-at outline-regexp)
7778 (setq level (org-get-valid-level (funcall outline-level) 1))
7779 (goto-char
7780 (if reversed
7781 (or (outline-next-heading) (point-max))
7782 (or (save-excursion (outline-get-next-sibling))
7783 (org-end-of-subtree t t)
7784 (point-max))))
7785 (if (not (bolp)) (newline))
7786 (bookmark-set "org-refile-last-stored")
7787 (org-paste-subtree level))))
7788 (if regionp
7789 (delete-region (point) (+ (point) region-length))
7790 (org-cut-subtree))
7791 (setq org-markers-to-move nil)
7792 (message "Refiled to \"%s\"" (car it)))))))
7794 (defun org-refile-goto-last-stored ()
7795 "Go to the location where the last refile was stored."
7796 (interactive)
7797 (bookmark-jump "org-refile-last-stored")
7798 (message "This is the location of the last refile"))
7800 (defun org-refile-get-location (&optional prompt default-buffer)
7801 "Prompt the user for a refile location, using PROMPT."
7802 (let ((org-refile-targets org-refile-targets)
7803 (org-refile-use-outline-path org-refile-use-outline-path))
7804 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
7805 (unless org-refile-target-table
7806 (error "No refile targets"))
7807 (let* ((cbuf (current-buffer))
7808 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
7809 (cfunc (if (and org-refile-use-outline-path
7810 org-outline-path-complete-in-steps)
7811 'org-olpath-completing-read
7812 'org-ido-completing-read))
7813 (extra (if org-refile-use-outline-path "/" ""))
7814 (filename (and cfn (expand-file-name cfn)))
7815 (tbl (mapcar
7816 (lambda (x)
7817 (if (not (equal filename (nth 1 x)))
7818 (cons (concat (car x) extra " ("
7819 (file-name-nondirectory (nth 1 x)) ")")
7820 (cdr x))
7821 (cons (concat (car x) extra) (cdr x))))
7822 org-refile-target-table))
7823 (completion-ignore-case t))
7824 (assoc (funcall cfunc prompt tbl nil t nil 'org-refile-history)
7825 tbl)))
7827 (defun org-olpath-completing-read (prompt collection &rest args)
7828 "Read an outline path like a file name."
7829 (let ((thetable collection))
7830 (apply
7831 'org-ido-completing-read prompt
7832 (lambda (string predicate &optional flag)
7833 (let (rtn r s f (l (length string)))
7834 (cond
7835 ((eq flag nil)
7836 ;; try completion
7837 (try-completion string thetable))
7838 ((eq flag t)
7839 ;; all-completions
7840 (setq rtn (all-completions string thetable predicate))
7841 (mapcar
7842 (lambda (x)
7843 (setq r (substring x l))
7844 (if (string-match " ([^)]*)$" x)
7845 (setq f (match-string 0 x))
7846 (setq f ""))
7847 (if (string-match "/" r)
7848 (concat string (substring r 0 (match-end 0)) f)
7850 rtn))
7851 ((eq flag 'lambda)
7852 ;; exact match?
7853 (assoc string thetable)))
7855 args)))
7857 ;;;; Dynamic blocks
7859 (defun org-find-dblock (name)
7860 "Find the first dynamic block with name NAME in the buffer.
7861 If not found, stay at current position and return nil."
7862 (let (pos)
7863 (save-excursion
7864 (goto-char (point-min))
7865 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
7866 nil t)
7867 (match-beginning 0))))
7868 (if pos (goto-char pos))
7869 pos))
7871 (defconst org-dblock-start-re
7872 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
7873 "Matches the startline of a dynamic block, with parameters.")
7875 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
7876 "Matches the end of a dynamic block.")
7878 (defun org-create-dblock (plist)
7879 "Create a dynamic block section, with parameters taken from PLIST.
7880 PLIST must contain a :name entry which is used as name of the block."
7881 (unless (bolp) (newline))
7882 (let ((name (plist-get plist :name)))
7883 (insert "#+BEGIN: " name)
7884 (while plist
7885 (if (eq (car plist) :name)
7886 (setq plist (cddr plist))
7887 (insert " " (prin1-to-string (pop plist)))))
7888 (insert "\n\n#+END:\n")
7889 (beginning-of-line -2)))
7891 (defun org-prepare-dblock ()
7892 "Prepare dynamic block for refresh.
7893 This empties the block, puts the cursor at the insert position and returns
7894 the property list including an extra property :name with the block name."
7895 (unless (looking-at org-dblock-start-re)
7896 (error "Not at a dynamic block"))
7897 (let* ((begdel (1+ (match-end 0)))
7898 (name (org-no-properties (match-string 1)))
7899 (params (append (list :name name)
7900 (read (concat "(" (match-string 3) ")")))))
7901 (unless (re-search-forward org-dblock-end-re nil t)
7902 (error "Dynamic block not terminated"))
7903 (setq params
7904 (append params
7905 (list :content (buffer-substring
7906 begdel (match-beginning 0)))))
7907 (delete-region begdel (match-beginning 0))
7908 (goto-char begdel)
7909 (open-line 1)
7910 params))
7912 (defun org-map-dblocks (&optional command)
7913 "Apply COMMAND to all dynamic blocks in the current buffer.
7914 If COMMAND is not given, use `org-update-dblock'."
7915 (let ((cmd (or command 'org-update-dblock))
7916 pos)
7917 (save-excursion
7918 (goto-char (point-min))
7919 (while (re-search-forward org-dblock-start-re nil t)
7920 (goto-char (setq pos (match-beginning 0)))
7921 (condition-case nil
7922 (funcall cmd)
7923 (error (message "Error during update of dynamic block")))
7924 (goto-char pos)
7925 (unless (re-search-forward org-dblock-end-re nil t)
7926 (error "Dynamic block not terminated"))))))
7928 (defun org-dblock-update (&optional arg)
7929 "User command for updating dynamic blocks.
7930 Update the dynamic block at point. With prefix ARG, update all dynamic
7931 blocks in the buffer."
7932 (interactive "P")
7933 (if arg
7934 (org-update-all-dblocks)
7935 (or (looking-at org-dblock-start-re)
7936 (org-beginning-of-dblock))
7937 (org-update-dblock)))
7939 (defun org-update-dblock ()
7940 "Update the dynamic block at point
7941 This means to empty the block, parse for parameters and then call
7942 the correct writing function."
7943 (save-window-excursion
7944 (let* ((pos (point))
7945 (line (org-current-line))
7946 (params (org-prepare-dblock))
7947 (name (plist-get params :name))
7948 (cmd (intern (concat "org-dblock-write:" name))))
7949 (message "Updating dynamic block `%s' at line %d..." name line)
7950 (funcall cmd params)
7951 (message "Updating dynamic block `%s' at line %d...done" name line)
7952 (goto-char pos))))
7954 (defun org-beginning-of-dblock ()
7955 "Find the beginning of the dynamic block at point.
7956 Error if there is no such block at point."
7957 (let ((pos (point))
7958 beg)
7959 (end-of-line 1)
7960 (if (and (re-search-backward org-dblock-start-re nil t)
7961 (setq beg (match-beginning 0))
7962 (re-search-forward org-dblock-end-re nil t)
7963 (> (match-end 0) pos))
7964 (goto-char beg)
7965 (goto-char pos)
7966 (error "Not in a dynamic block"))))
7968 (defun org-update-all-dblocks ()
7969 "Update all dynamic blocks in the buffer.
7970 This function can be used in a hook."
7971 (when (org-mode-p)
7972 (org-map-dblocks 'org-update-dblock)))
7975 ;;;; Completion
7977 (defconst org-additional-option-like-keywords
7978 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
7979 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
7980 "BEGIN_EXAMPLE" "END_EXAMPLE"
7981 "BEGIN_QUOTE" "END_QUOTE"
7982 "BEGIN_VERSE" "END_VERSE"
7983 "BEGIN_SRC" "END_SRC"
7984 "CAPTION" "LABEL" "ATTR_HTML" "ATTR_LaTeX"))
7986 (defcustom org-structure-template-alist
7988 ("s" "#+begin_src ?\n\n#+end_src"
7989 "<src lang=\"?\">\n\n</src>")
7990 ("e" "#+begin_example\n?\n#+end_example"
7991 "<example>\n?\n</example>")
7992 ("q" "#+begin_quote\n?\n#+end_quote"
7993 "<quote>\n?\n</quote>")
7994 ("v" "#+begin_verse\n?\n#+end_verse"
7995 "<verse>\n?\n/verse>")
7996 ("l" "#+begin_latex\n?\n#+end_latex"
7997 "<literal style=\"latex\">\n?\n</literal>")
7998 ("L" "#+latex: "
7999 "<literal style=\"latex\">?</literal>")
8000 ("h" "#+begin_html\n?\n#+end_html"
8001 "<literal style=\"html\">\n?\n</literal>")
8002 ("H" "#+html: "
8003 "<literal style=\"html\">?</literal>")
8004 ("a" "#+begin_ascii\n?\n#+end_ascii")
8005 ("A" "#+ascii: ")
8006 ("i" "#+include %file ?"
8007 "<include file=%file markup=\"?\">")
8009 "Structure completion elements.
8010 This is a list of abbreviation keys and values. The value gets inserted
8011 it you type @samp{.} followed by the key and then the completion key,
8012 usually `M-TAB'. %file will be replaced by a file name after prompting
8013 for the file using completion.
8014 There are two templates for each key, the first uses the original Org syntax,
8015 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
8016 the default when the /org-mtags.el/ module has been loaded. See also the
8017 variable `org-mtags-prefer-muse-templates'.
8018 This is an experimental feature, it is undecided if it is going to stay in."
8019 :group 'org-completion
8020 :type '(repeat
8021 (string :tag "Key")
8022 (string :tag "Template")
8023 (string :tag "Muse Template")))
8025 (defun org-try-structure-completion ()
8026 "Try to complete a structure template before point.
8027 This looks for strings like \"<e\" on an otherwise empty line and
8028 expands them."
8029 (let ((l (buffer-substring (point-at-bol) (point)))
8031 (when (and (looking-at "[ \t]*$")
8032 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
8033 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
8034 (org-complete-expand-structure-template (+ -1 (point-at-bol)
8035 (match-beginning 1)) a)
8036 t)))
8038 (defun org-complete-expand-structure-template (start cell)
8039 "Expand a structure template."
8040 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
8041 (rpl (nth (if musep 2 1) cell)))
8042 (delete-region start (point))
8043 (when (string-match "\\`#\\+" rpl)
8044 (cond
8045 ((bolp))
8046 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
8047 (delete-region (point-at-bol) (point)))
8048 (t (newline))))
8049 (setq start (point))
8050 (if (string-match "%file" rpl)
8051 (setq rpl (replace-match
8052 (concat
8053 "\""
8054 (save-match-data
8055 (abbreviate-file-name (read-file-name "Include file: ")))
8056 "\"")
8057 t t rpl)))
8058 (insert rpl)
8059 (if (re-search-backward "\\?" start t) (delete-char 1))))
8062 (defun org-complete (&optional arg)
8063 "Perform completion on word at point.
8064 At the beginning of a headline, this completes TODO keywords as given in
8065 `org-todo-keywords'.
8066 If the current word is preceded by a backslash, completes the TeX symbols
8067 that are supported for HTML support.
8068 If the current word is preceded by \"#+\", completes special words for
8069 setting file options.
8070 In the line after \"#+STARTUP:, complete valid keywords.\"
8071 At all other locations, this simply calls the value of
8072 `org-completion-fallback-command'."
8073 (interactive "P")
8074 (org-without-partial-completion
8075 (catch 'exit
8076 (let* ((a nil)
8077 (end (point))
8078 (beg1 (save-excursion
8079 (skip-chars-backward (org-re "[:alnum:]_@"))
8080 (point)))
8081 (beg (save-excursion
8082 (skip-chars-backward "a-zA-Z0-9_:$")
8083 (point)))
8084 (confirm (lambda (x) (stringp (car x))))
8085 (searchhead (equal (char-before beg) ?*))
8086 (struct
8087 (when (and (member (char-before beg1) '(?. ?<))
8088 (setq a (assoc (buffer-substring beg1 (point))
8089 org-structure-template-alist)))
8090 (org-complete-expand-structure-template (1- beg1) a)
8091 (throw 'exit t)))
8092 (tag (and (equal (char-before beg1) ?:)
8093 (equal (char-after (point-at-bol)) ?*)))
8094 (prop (and (equal (char-before beg1) ?:)
8095 (not (equal (char-after (point-at-bol)) ?*))))
8096 (texp (equal (char-before beg) ?\\))
8097 (link (equal (char-before beg) ?\[))
8098 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
8099 beg)
8100 "#+"))
8101 (startup (string-match "^#\\+STARTUP:.*"
8102 (buffer-substring (point-at-bol) (point))))
8103 (completion-ignore-case opt)
8104 (type nil)
8105 (tbl nil)
8106 (table (cond
8107 (opt
8108 (setq type :opt)
8109 (require 'org-exp)
8110 (append
8111 (mapcar
8112 (lambda (x)
8113 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
8114 (cons (match-string 2 x) (match-string 1 x)))
8115 (org-split-string (org-get-current-options) "\n"))
8116 (mapcar 'list org-additional-option-like-keywords)))
8117 (startup
8118 (setq type :startup)
8119 org-startup-options)
8120 (link (append org-link-abbrev-alist-local
8121 org-link-abbrev-alist))
8122 (texp
8123 (setq type :tex)
8124 org-html-entities)
8125 ((string-match "\\`\\*+[ \t]+\\'"
8126 (buffer-substring (point-at-bol) beg))
8127 (setq type :todo)
8128 (mapcar 'list org-todo-keywords-1))
8129 (searchhead
8130 (setq type :searchhead)
8131 (save-excursion
8132 (goto-char (point-min))
8133 (while (re-search-forward org-todo-line-regexp nil t)
8134 (push (list
8135 (org-make-org-heading-search-string
8136 (match-string 3) t))
8137 tbl)))
8138 tbl)
8139 (tag (setq type :tag beg beg1)
8140 (or org-tag-alist (org-get-buffer-tags)))
8141 (prop (setq type :prop beg beg1)
8142 (mapcar 'list (org-buffer-property-keys nil t t)))
8143 (t (progn
8144 (call-interactively org-completion-fallback-command)
8145 (throw 'exit nil)))))
8146 (pattern (buffer-substring-no-properties beg end))
8147 (completion (try-completion pattern table confirm)))
8148 (cond ((eq completion t)
8149 (if (not (assoc (upcase pattern) table))
8150 (message "Already complete")
8151 (if (and (equal type :opt)
8152 (not (member (car (assoc (upcase pattern) table))
8153 org-additional-option-like-keywords)))
8154 (insert (substring (cdr (assoc (upcase pattern) table))
8155 (length pattern)))
8156 (if (memq type '(:tag :prop)) (insert ":")))))
8157 ((null completion)
8158 (message "Can't find completion for \"%s\"" pattern)
8159 (ding))
8160 ((not (string= pattern completion))
8161 (delete-region beg end)
8162 (if (string-match " +$" completion)
8163 (setq completion (replace-match "" t t completion)))
8164 (insert completion)
8165 (if (get-buffer-window "*Completions*")
8166 (delete-window (get-buffer-window "*Completions*")))
8167 (if (assoc completion table)
8168 (if (eq type :todo) (insert " ")
8169 (if (memq type '(:tag :prop)) (insert ":"))))
8170 (if (and (equal type :opt) (assoc completion table))
8171 (message "%s" (substitute-command-keys
8172 "Press \\[org-complete] again to insert example settings"))))
8174 (message "Making completion list...")
8175 (let ((list (sort (all-completions pattern table confirm)
8176 'string<)))
8177 (with-output-to-temp-buffer "*Completions*"
8178 (condition-case nil
8179 ;; Protection needed for XEmacs and emacs 21
8180 (display-completion-list list pattern)
8181 (error (display-completion-list list)))))
8182 (message "Making completion list...%s" "done")))))))
8184 ;;;; TODO, DEADLINE, Comments
8186 (defun org-toggle-comment ()
8187 "Change the COMMENT state of an entry."
8188 (interactive)
8189 (save-excursion
8190 (org-back-to-heading)
8191 (let (case-fold-search)
8192 (if (looking-at (concat outline-regexp
8193 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
8194 (replace-match "" t t nil 1)
8195 (if (looking-at outline-regexp)
8196 (progn
8197 (goto-char (match-end 0))
8198 (insert org-comment-string " ")))))))
8200 (defvar org-last-todo-state-is-todo nil
8201 "This is non-nil when the last TODO state change led to a TODO state.
8202 If the last change removed the TODO tag or switched to DONE, then
8203 this is nil.")
8205 (defvar org-setting-tags nil) ; dynamically skipped
8207 (defun org-parse-local-options (string var)
8208 "Parse STRING for startup setting relevant for variable VAR."
8209 (let ((rtn (symbol-value var))
8210 e opts)
8211 (save-match-data
8212 (if (or (not string) (not (string-match "\\S-" string)))
8214 (setq opts (delq nil (mapcar (lambda (x)
8215 (setq e (assoc x org-startup-options))
8216 (if (eq (nth 1 e) var) e nil))
8217 (org-split-string string "[ \t]+"))))
8218 (if (not opts)
8220 (setq rtn nil)
8221 (while (setq e (pop opts))
8222 (if (not (nth 3 e))
8223 (setq rtn (nth 2 e))
8224 (if (not (listp rtn)) (setq rtn nil))
8225 (push (nth 2 e) rtn)))
8226 rtn)))))
8228 (defvar org-blocker-hook nil
8229 "Hook for functions that are allowed to block a state change.
8231 Each function gets as its single argument a property list, see
8232 `org-trigger-hook' for more information about this list.
8234 If any of the functions in this hook returns nil, the state change
8235 is blocked.")
8237 (defvar org-trigger-hook nil
8238 "Hook for functions that are triggered by a state change.
8240 Each function gets as its single argument a property list with at least
8241 the following elements:
8243 (:type type-of-change :position pos-at-entry-start
8244 :from old-state :to new-state)
8246 Depending on the type, more properties may be present.
8248 This mechanism is currently implemented for:
8250 TODO state changes
8251 ------------------
8252 :type todo-state-change
8253 :from previous state (keyword as a string), or nil
8254 :to new state (keyword as a string), or nil")
8256 (defvar org-agenda-headline-snapshot-before-repeat)
8257 (defun org-todo (&optional arg)
8258 "Change the TODO state of an item.
8259 The state of an item is given by a keyword at the start of the heading,
8260 like
8261 *** TODO Write paper
8262 *** DONE Call mom
8264 The different keywords are specified in the variable `org-todo-keywords'.
8265 By default the available states are \"TODO\" and \"DONE\".
8266 So for this example: when the item starts with TODO, it is changed to DONE.
8267 When it starts with DONE, the DONE is removed. And when neither TODO nor
8268 DONE are present, add TODO at the beginning of the heading.
8270 With C-u prefix arg, use completion to determine the new state.
8271 With numeric prefix arg, switch to that state.
8273 For calling through lisp, arg is also interpreted in the following way:
8274 'none -> empty state
8275 \"\"(empty string) -> switch to empty state
8276 'done -> switch to DONE
8277 'nextset -> switch to the next set of keywords
8278 'previousset -> switch to the previous set of keywords
8279 \"WAITING\" -> switch to the specified keyword, but only if it
8280 really is a member of `org-todo-keywords'."
8281 (interactive "P")
8282 (save-excursion
8283 (catch 'exit
8284 (org-back-to-heading)
8285 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
8286 (or (looking-at (concat " +" org-todo-regexp " *"))
8287 (looking-at " *"))
8288 (let* ((match-data (match-data))
8289 (startpos (point-at-bol))
8290 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
8291 (org-log-done org-log-done)
8292 (org-log-repeat org-log-repeat)
8293 (org-todo-log-states org-todo-log-states)
8294 (this (match-string 1))
8295 (hl-pos (match-beginning 0))
8296 (head (org-get-todo-sequence-head this))
8297 (ass (assoc head org-todo-kwd-alist))
8298 (interpret (nth 1 ass))
8299 (done-word (nth 3 ass))
8300 (final-done-word (nth 4 ass))
8301 (last-state (or this ""))
8302 (completion-ignore-case t)
8303 (member (member this org-todo-keywords-1))
8304 (tail (cdr member))
8305 (state (cond
8306 ((and org-todo-key-trigger
8307 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
8308 (and (not arg) org-use-fast-todo-selection
8309 (not (eq org-use-fast-todo-selection 'prefix)))))
8310 ;; Use fast selection
8311 (org-fast-todo-selection))
8312 ((and (equal arg '(4))
8313 (or (not org-use-fast-todo-selection)
8314 (not org-todo-key-trigger)))
8315 ;; Read a state with completion
8316 (org-ido-completing-read "State: " (mapcar (lambda(x) (list x))
8317 org-todo-keywords-1)
8318 nil t))
8319 ((eq arg 'right)
8320 (if this
8321 (if tail (car tail) nil)
8322 (car org-todo-keywords-1)))
8323 ((eq arg 'left)
8324 (if (equal member org-todo-keywords-1)
8326 (if this
8327 (nth (- (length org-todo-keywords-1) (length tail) 2)
8328 org-todo-keywords-1)
8329 (org-last org-todo-keywords-1))))
8330 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
8331 (setq arg nil))) ; hack to fall back to cycling
8332 (arg
8333 ;; user or caller requests a specific state
8334 (cond
8335 ((equal arg "") nil)
8336 ((eq arg 'none) nil)
8337 ((eq arg 'done) (or done-word (car org-done-keywords)))
8338 ((eq arg 'nextset)
8339 (or (car (cdr (member head org-todo-heads)))
8340 (car org-todo-heads)))
8341 ((eq arg 'previousset)
8342 (let ((org-todo-heads (reverse org-todo-heads)))
8343 (or (car (cdr (member head org-todo-heads)))
8344 (car org-todo-heads))))
8345 ((car (member arg org-todo-keywords-1)))
8346 ((nth (1- (prefix-numeric-value arg))
8347 org-todo-keywords-1))))
8348 ((null member) (or head (car org-todo-keywords-1)))
8349 ((equal this final-done-word) nil) ;; -> make empty
8350 ((null tail) nil) ;; -> first entry
8351 ((eq interpret 'sequence)
8352 (car tail))
8353 ((memq interpret '(type priority))
8354 (if (eq this-command last-command)
8355 (car tail)
8356 (if (> (length tail) 0)
8357 (or done-word (car org-done-keywords))
8358 nil)))
8359 (t nil)))
8360 (next (if state (concat " " state " ") " "))
8361 (change-plist (list :type 'todo-state-change :from this :to state
8362 :position startpos))
8363 dolog now-done-p)
8364 (when org-blocker-hook
8365 (unless (save-excursion
8366 (save-match-data
8367 (run-hook-with-args-until-failure
8368 'org-blocker-hook change-plist)))
8369 (if (interactive-p)
8370 (error "TODO state change from %s to %s blocked" this state)
8371 ;; fail silently
8372 (message "TODO state change from %s to %s blocked" this state)
8373 (throw 'exit nil))))
8374 (store-match-data match-data)
8375 (replace-match next t t)
8376 (unless (pos-visible-in-window-p hl-pos)
8377 (message "TODO state changed to %s" (org-trim next)))
8378 (unless head
8379 (setq head (org-get-todo-sequence-head state)
8380 ass (assoc head org-todo-kwd-alist)
8381 interpret (nth 1 ass)
8382 done-word (nth 3 ass)
8383 final-done-word (nth 4 ass)))
8384 (when (memq arg '(nextset previousset))
8385 (message "Keyword-Set %d/%d: %s"
8386 (- (length org-todo-sets) -1
8387 (length (memq (assoc state org-todo-sets) org-todo-sets)))
8388 (length org-todo-sets)
8389 (mapconcat 'identity (assoc state org-todo-sets) " ")))
8390 (setq org-last-todo-state-is-todo
8391 (not (member state org-done-keywords)))
8392 (setq now-done-p (and (member state org-done-keywords)
8393 (not (member this org-done-keywords))))
8394 (and logging (org-local-logging logging))
8395 (when (and (or org-todo-log-states org-log-done)
8396 (not (memq arg '(nextset previousset))))
8397 ;; we need to look at recording a time and note
8398 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
8399 (nth 2 (assoc this org-todo-log-states))))
8400 (when (and state
8401 (member state org-not-done-keywords)
8402 (not (member this org-not-done-keywords)))
8403 ;; This is now a todo state and was not one before
8404 ;; If there was a CLOSED time stamp, get rid of it.
8405 (org-add-planning-info nil nil 'closed))
8406 (when (and now-done-p org-log-done)
8407 ;; It is now done, and it was not done before
8408 (org-add-planning-info 'closed (org-current-time))
8409 (if (and (not dolog) (eq 'note org-log-done))
8410 (org-add-log-setup 'done state 'findpos 'note)))
8411 (when (and state dolog)
8412 ;; This is a non-nil state, and we need to log it
8413 (org-add-log-setup 'state state 'findpos dolog)))
8414 ;; Fixup tag positioning
8415 (org-todo-trigger-tag-changes state)
8416 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
8417 (when org-provide-todo-statistics
8418 (org-update-parent-todo-statistics))
8419 (run-hooks 'org-after-todo-state-change-hook)
8420 (if (and arg (not (member state org-done-keywords)))
8421 (setq head (org-get-todo-sequence-head state)))
8422 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
8423 ;; Do we need to trigger a repeat?
8424 (when now-done-p
8425 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
8426 ;; This is for the agenda, take a snapshot of the headline.
8427 (save-match-data
8428 (setq org-agenda-headline-snapshot-before-repeat
8429 (org-get-heading))))
8430 (org-auto-repeat-maybe state))
8431 ;; Fixup cursor location if close to the keyword
8432 (if (and (outline-on-heading-p)
8433 (not (bolp))
8434 (save-excursion (beginning-of-line 1)
8435 (looking-at org-todo-line-regexp))
8436 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
8437 (progn
8438 (goto-char (or (match-end 2) (match-end 1)))
8439 (just-one-space)))
8440 (when org-trigger-hook
8441 (save-excursion
8442 (run-hook-with-args 'org-trigger-hook change-plist)))))))
8444 (defun org-update-parent-todo-statistics ()
8445 "Update any statistics cookie in the parent of the current headline."
8446 (interactive)
8447 (let ((box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
8448 level (cnt-all 0) (cnt-done 0) is-percent kwd)
8449 (catch 'exit
8450 (save-excursion
8451 (setq level (org-up-heading-safe))
8452 (unless (and level
8453 (re-search-forward box-re (point-at-eol) t))
8454 (throw 'exit nil))
8455 (setq is-percent (match-end 2))
8456 (save-match-data
8457 (unless (outline-next-heading) (throw 'exit nil))
8458 (while (looking-at org-todo-line-regexp)
8459 (setq kwd (match-string 2))
8460 (and kwd (setq cnt-all (1+ cnt-all)))
8461 (and (member kwd org-done-keywords)
8462 (setq cnt-done (1+ cnt-done)))
8463 (condition-case nil
8464 (org-forward-same-level 1)
8465 (error (end-of-line 1)))))
8466 (replace-match
8467 (if is-percent
8468 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
8469 (format "[%d/%d]" cnt-done cnt-all)))
8470 (run-hook-with-args 'org-after-todo-statistics-hook
8471 cnt-done (- cnt-all cnt-done))))))
8473 (defvar org-after-todo-statistics-hook nil
8474 "Hook that is called after a TODO statistics cookie has been updated.
8475 Each function is called with two arguments: the number of not-done entries
8476 and the number of done entries.
8478 For example, the following function, when added to this hook, will switch
8479 an entry to DONE when all children are done, and back to TODO when new
8480 entries are set to a TODO status. Note that this hook is only called
8481 when there is a statistics cookie in the headline!
8483 (defun org-summary-todo (n-done n-not-done)
8484 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
8485 (let (org-log-done org-log-states) ; turn off logging
8486 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
8489 (defun org-todo-trigger-tag-changes (state)
8490 "Apply the changes defined in `org-todo-state-tags-triggers'."
8491 (let ((l org-todo-state-tags-triggers)
8492 changes)
8493 (when (or (not state) (equal state ""))
8494 (setq changes (append changes (cdr (assoc "" l)))))
8495 (when (and (stringp state) (> (length state) 0))
8496 (setq changes (append changes (cdr (assoc state l)))))
8497 (when (member state org-not-done-keywords)
8498 (setq changes (append changes (cdr (assoc 'todo l)))))
8499 (when (member state org-done-keywords)
8500 (setq changes (append changes (cdr (assoc 'done l)))))
8501 (dolist (c changes)
8502 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
8504 (defun org-local-logging (value)
8505 "Get logging settings from a property VALUE."
8506 (let* (words w a)
8507 ;; directly set the variables, they are already local.
8508 (setq org-log-done nil
8509 org-log-repeat nil
8510 org-todo-log-states nil)
8511 (setq words (org-split-string value))
8512 (while (setq w (pop words))
8513 (cond
8514 ((setq a (assoc w org-startup-options))
8515 (and (member (nth 1 a) '(org-log-done org-log-repeat))
8516 (set (nth 1 a) (nth 2 a))))
8517 ((setq a (org-extract-log-state-settings w))
8518 (and (member (car a) org-todo-keywords-1)
8519 (push a org-todo-log-states)))))))
8521 (defun org-get-todo-sequence-head (kwd)
8522 "Return the head of the TODO sequence to which KWD belongs.
8523 If KWD is not set, check if there is a text property remembering the
8524 right sequence."
8525 (let (p)
8526 (cond
8527 ((not kwd)
8528 (or (get-text-property (point-at-bol) 'org-todo-head)
8529 (progn
8530 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
8531 nil (point-at-eol)))
8532 (get-text-property p 'org-todo-head))))
8533 ((not (member kwd org-todo-keywords-1))
8534 (car org-todo-keywords-1))
8535 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
8537 (defun org-fast-todo-selection ()
8538 "Fast TODO keyword selection with single keys.
8539 Returns the new TODO keyword, or nil if no state change should occur."
8540 (let* ((fulltable org-todo-key-alist)
8541 (done-keywords org-done-keywords) ;; needed for the faces.
8542 (maxlen (apply 'max (mapcar
8543 (lambda (x)
8544 (if (stringp (car x)) (string-width (car x)) 0))
8545 fulltable)))
8546 (expert nil)
8547 (fwidth (+ maxlen 3 1 3))
8548 (ncol (/ (- (window-width) 4) fwidth))
8549 tg cnt e c tbl
8550 groups ingroup)
8551 (save-window-excursion
8552 (if expert
8553 (set-buffer (get-buffer-create " *Org todo*"))
8554 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
8555 (erase-buffer)
8556 (org-set-local 'org-done-keywords done-keywords)
8557 (setq tbl fulltable cnt 0)
8558 (while (setq e (pop tbl))
8559 (cond
8560 ((equal e '(:startgroup))
8561 (push '() groups) (setq ingroup t)
8562 (when (not (= cnt 0))
8563 (setq cnt 0)
8564 (insert "\n"))
8565 (insert "{ "))
8566 ((equal e '(:endgroup))
8567 (setq ingroup nil cnt 0)
8568 (insert "}\n"))
8570 (setq tg (car e) c (cdr e))
8571 (if ingroup (push tg (car groups)))
8572 (setq tg (org-add-props tg nil 'face
8573 (org-get-todo-face tg)))
8574 (if (and (= cnt 0) (not ingroup)) (insert " "))
8575 (insert "[" c "] " tg (make-string
8576 (- fwidth 4 (length tg)) ?\ ))
8577 (when (= (setq cnt (1+ cnt)) ncol)
8578 (insert "\n")
8579 (if ingroup (insert " "))
8580 (setq cnt 0)))))
8581 (insert "\n")
8582 (goto-char (point-min))
8583 (if (not expert) (org-fit-window-to-buffer))
8584 (message "[a-z..]:Set [SPC]:clear")
8585 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
8586 (cond
8587 ((or (= c ?\C-g)
8588 (and (= c ?q) (not (rassoc c fulltable))))
8589 (setq quit-flag t))
8590 ((= c ?\ ) nil)
8591 ((setq e (rassoc c fulltable) tg (car e))
8593 (t (setq quit-flag t))))))
8595 (defun org-entry-is-todo-p ()
8596 (member (org-get-todo-state) org-not-done-keywords))
8598 (defun org-entry-is-done-p ()
8599 (member (org-get-todo-state) org-done-keywords))
8601 (defun org-get-todo-state ()
8602 (save-excursion
8603 (org-back-to-heading t)
8604 (and (looking-at org-todo-line-regexp)
8605 (match-end 2)
8606 (match-string 2))))
8608 (defun org-at-date-range-p (&optional inactive-ok)
8609 "Is the cursor inside a date range?"
8610 (interactive)
8611 (save-excursion
8612 (catch 'exit
8613 (let ((pos (point)))
8614 (skip-chars-backward "^[<\r\n")
8615 (skip-chars-backward "<[")
8616 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8617 (>= (match-end 0) pos)
8618 (throw 'exit t))
8619 (skip-chars-backward "^<[\r\n")
8620 (skip-chars-backward "<[")
8621 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8622 (>= (match-end 0) pos)
8623 (throw 'exit t)))
8624 nil)))
8626 (defun org-get-repeat ()
8627 "Check if there is a deadline/schedule with repeater in this entry."
8628 (save-match-data
8629 (save-excursion
8630 (org-back-to-heading t)
8631 (if (re-search-forward
8632 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
8633 (match-string 1)))))
8635 (defvar org-last-changed-timestamp)
8636 (defvar org-last-inserted-timestamp)
8637 (defvar org-log-post-message)
8638 (defvar org-log-note-purpose)
8639 (defvar org-log-note-how)
8640 (defvar org-log-note-extra)
8641 (defun org-auto-repeat-maybe (done-word)
8642 "Check if the current headline contains a repeated deadline/schedule.
8643 If yes, set TODO state back to what it was and change the base date
8644 of repeating deadline/scheduled time stamps to new date.
8645 This function is run automatically after each state change to a DONE state."
8646 ;; last-state is dynamically scoped into this function
8647 (let* ((repeat (org-get-repeat))
8648 (aa (assoc last-state org-todo-kwd-alist))
8649 (interpret (nth 1 aa))
8650 (head (nth 2 aa))
8651 (whata '(("d" . day) ("m" . month) ("y" . year)))
8652 (msg "Entry repeats: ")
8653 (org-log-done nil)
8654 (org-todo-log-states nil)
8655 (nshiftmax 10) (nshift 0)
8656 re type n what ts mb0 time)
8657 (when repeat
8658 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
8659 (org-todo (if (eq interpret 'type) last-state head))
8660 (when org-log-repeat
8661 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
8662 (memq 'org-add-log-note post-command-hook))
8663 ;; OK, we are already setup for some record
8664 (if (eq org-log-repeat 'note)
8665 ;; make sure we take a note, not only a time stamp
8666 (setq org-log-note-how 'note))
8667 ;; Set up for taking a record
8668 (org-add-log-setup 'state (or done-word (car org-done-keywords))
8669 'findpos org-log-repeat)))
8670 (org-back-to-heading t)
8671 (org-add-planning-info nil nil 'closed)
8672 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
8673 org-deadline-time-regexp "\\)\\|\\("
8674 org-ts-regexp "\\)"))
8675 (while (re-search-forward
8676 re (save-excursion (outline-next-heading) (point)) t)
8677 (setq type (if (match-end 1) org-scheduled-string
8678 (if (match-end 3) org-deadline-string "Plain:"))
8679 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0)))
8680 mb0 (match-beginning 0))
8681 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
8682 (setq n (string-to-number (match-string 2 ts))
8683 what (match-string 3 ts))
8684 (if (equal what "w") (setq n (* n 7) what "d"))
8685 ;; Preparation, see if we need to modify the start date for the change
8686 (when (match-end 1)
8687 (setq time (save-match-data (org-time-string-to-time ts)))
8688 (cond
8689 ((equal (match-string 1 ts) ".")
8690 ;; Shift starting date to today
8691 (org-timestamp-change
8692 (- (time-to-days (current-time)) (time-to-days time))
8693 'day))
8694 ((equal (match-string 1 ts) "+")
8695 (while (or (= nshift 0)
8696 (<= (time-to-days time) (time-to-days (current-time))))
8697 (when (= (incf nshift) nshiftmax)
8698 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
8699 (error "Abort")))
8700 (org-timestamp-change n (cdr (assoc what whata)))
8701 (org-at-timestamp-p t)
8702 (setq ts (match-string 1))
8703 (setq time (save-match-data (org-time-string-to-time ts))))
8704 (org-timestamp-change (- n) (cdr (assoc what whata)))
8705 ;; rematch, so that we have everything in place for the real shift
8706 (org-at-timestamp-p t)
8707 (setq ts (match-string 1))
8708 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
8709 (org-timestamp-change n (cdr (assoc what whata)))
8710 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
8711 (setq org-log-post-message msg)
8712 (message "%s" msg))))
8714 (defun org-show-todo-tree (arg)
8715 "Make a compact tree which shows all headlines marked with TODO.
8716 The tree will show the lines where the regexp matches, and all higher
8717 headlines above the match.
8718 With a \\[universal-argument] prefix, also show the DONE entries.
8719 With a numeric prefix N, construct a sparse tree for the Nth element
8720 of `org-todo-keywords-1'."
8721 (interactive "P")
8722 (let ((case-fold-search nil)
8723 (kwd-re
8724 (cond ((null arg) org-not-done-regexp)
8725 ((equal arg '(4))
8726 (let ((kwd (org-ido-completing-read "Keyword (or KWD1|KWD2|...): "
8727 (mapcar 'list org-todo-keywords-1))))
8728 (concat "\\("
8729 (mapconcat 'identity (org-split-string kwd "|") "\\|")
8730 "\\)\\>")))
8731 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
8732 (regexp-quote (nth (1- (prefix-numeric-value arg))
8733 org-todo-keywords-1)))
8734 (t (error "Invalid prefix argument: %s" arg)))))
8735 (message "%d TODO entries found"
8736 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
8738 (defun org-deadline (&optional remove time)
8739 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
8740 With argument REMOVE, remove any deadline from the item.
8741 When TIME is set, it should be an internal time specification, and the
8742 scheduling will use the corresponding date."
8743 (interactive "P")
8744 (if remove
8745 (progn
8746 (org-remove-timestamp-with-keyword org-deadline-string)
8747 (message "Item no longer has a deadline."))
8748 (if (org-get-repeat)
8749 (error "Cannot change deadline on task with repeater, please do that by hand")
8750 (org-add-planning-info 'deadline time 'closed)
8751 (message "Deadline on %s" org-last-inserted-timestamp))))
8753 (defun org-schedule (&optional remove time)
8754 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
8755 With argument REMOVE, remove any scheduling date from the item.
8756 When TIME is set, it should be an internal time specification, and the
8757 scheduling will use the corresponding date."
8758 (interactive "P")
8759 (if remove
8760 (progn
8761 (org-remove-timestamp-with-keyword org-scheduled-string)
8762 (message "Item is no longer scheduled."))
8763 (if (org-get-repeat)
8764 (error "Cannot reschedule task with repeater, please do that by hand")
8765 (org-add-planning-info 'scheduled time 'closed)
8766 (message "Scheduled to %s" org-last-inserted-timestamp))))
8768 (defun org-remove-timestamp-with-keyword (keyword)
8769 "Remove all time stamps with KEYWORD in the current entry."
8770 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
8771 beg)
8772 (save-excursion
8773 (org-back-to-heading t)
8774 (setq beg (point))
8775 (org-end-of-subtree t t)
8776 (while (re-search-backward re beg t)
8777 (replace-match "")
8778 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
8779 (equal (char-before) ?\ ))
8780 (backward-delete-char 1)
8781 (if (string-match "^[ \t]*$" (buffer-substring
8782 (point-at-bol) (point-at-eol)))
8783 (delete-region (point-at-bol)
8784 (min (point-max) (1+ (point-at-eol))))))))))
8786 (defun org-add-planning-info (what &optional time &rest remove)
8787 "Insert new timestamp with keyword in the line directly after the headline.
8788 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
8789 If non is given, the user is prompted for a date.
8790 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
8791 be removed."
8792 (interactive)
8793 (let (org-time-was-given org-end-time-was-given ts
8794 end default-time default-input)
8796 (when (and (not time) (memq what '(scheduled deadline)))
8797 ;; Try to get a default date/time from existing timestamp
8798 (save-excursion
8799 (org-back-to-heading t)
8800 (setq end (save-excursion (outline-next-heading) (point)))
8801 (when (re-search-forward (if (eq what 'scheduled)
8802 org-scheduled-time-regexp
8803 org-deadline-time-regexp)
8804 end t)
8805 (setq ts (match-string 1)
8806 default-time
8807 (apply 'encode-time (org-parse-time-string ts))
8808 default-input (and ts (org-get-compact-tod ts))))))
8809 (when what
8810 ;; If necessary, get the time from the user
8811 (setq time (or time (org-read-date nil 'to-time nil nil
8812 default-time default-input))))
8814 (when (and org-insert-labeled-timestamps-at-point
8815 (member what '(scheduled deadline)))
8816 (insert
8817 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
8818 (org-insert-time-stamp time org-time-was-given
8819 nil nil nil (list org-end-time-was-given))
8820 (setq what nil))
8821 (save-excursion
8822 (save-restriction
8823 (let (col list elt ts buffer-invisibility-spec)
8824 (org-back-to-heading t)
8825 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
8826 (goto-char (match-end 1))
8827 (setq col (current-column))
8828 (goto-char (match-end 0))
8829 (if (eobp) (insert "\n") (forward-char 1))
8830 (if (and (not (looking-at outline-regexp))
8831 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
8832 "[^\r\n]*"))
8833 (not (equal (match-string 1) org-clock-string)))
8834 (narrow-to-region (match-beginning 0) (match-end 0))
8835 (insert-before-markers "\n")
8836 (backward-char 1)
8837 (narrow-to-region (point) (point))
8838 (and org-adapt-indentation (org-indent-to-column col)))
8839 ;; Check if we have to remove something.
8840 (setq list (cons what remove))
8841 (while list
8842 (setq elt (pop list))
8843 (goto-char (point-min))
8844 (when (or (and (eq elt 'scheduled)
8845 (re-search-forward org-scheduled-time-regexp nil t))
8846 (and (eq elt 'deadline)
8847 (re-search-forward org-deadline-time-regexp nil t))
8848 (and (eq elt 'closed)
8849 (re-search-forward org-closed-time-regexp nil t)))
8850 (replace-match "")
8851 (if (looking-at "--+<[^>]+>") (replace-match ""))
8852 (if (looking-at " +") (replace-match ""))))
8853 (goto-char (point-max))
8854 (when what
8855 (insert
8856 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
8857 (cond ((eq what 'scheduled) org-scheduled-string)
8858 ((eq what 'deadline) org-deadline-string)
8859 ((eq what 'closed) org-closed-string))
8860 " ")
8861 (setq ts (org-insert-time-stamp
8862 time
8863 (or org-time-was-given
8864 (and (eq what 'closed) org-log-done-with-time))
8865 (eq what 'closed)
8866 nil nil (list org-end-time-was-given)))
8867 (end-of-line 1))
8868 (goto-char (point-min))
8869 (widen)
8870 (if (and (looking-at "[ \t]+\n")
8871 (equal (char-before) ?\n))
8872 (delete-region (1- (point)) (point-at-eol)))
8873 ts)))))
8875 (defvar org-log-note-marker (make-marker))
8876 (defvar org-log-note-purpose nil)
8877 (defvar org-log-note-state nil)
8878 (defvar org-log-note-how nil)
8879 (defvar org-log-note-extra nil)
8880 (defvar org-log-note-window-configuration nil)
8881 (defvar org-log-note-return-to (make-marker))
8882 (defvar org-log-post-message nil
8883 "Message to be displayed after a log note has been stored.
8884 The auto-repeater uses this.")
8886 (defun org-add-note ()
8887 "Add a note to the current entry.
8888 This is done in the same way as adding a state change note."
8889 (interactive)
8890 (org-add-log-setup 'note nil 'findpos nil))
8892 (defvar org-property-end-re)
8893 (defun org-add-log-setup (&optional purpose state findpos how &optional extra)
8894 "Set up the post command hook to take a note.
8895 If this is about to TODO state change, the new state is expected in STATE.
8896 When FINDPOS is non-nil, find the correct position for the note in
8897 the current entry. If not, assume that it can be inserted at point.
8898 HOW is an indicator what kind of note should be created.
8899 EXTRA is additional text that will be inserted into the notes buffer."
8900 (save-restriction
8901 (save-excursion
8902 (when findpos
8903 (org-back-to-heading t)
8904 (narrow-to-region (point) (save-excursion
8905 (outline-next-heading) (point)))
8906 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
8907 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
8908 "[^\r\n]*\\)?"))
8909 (goto-char (match-end 0))
8910 (when (and org-log-state-notes-insert-after-drawers
8911 (save-excursion
8912 (forward-line) (looking-at org-drawer-regexp)))
8913 (progn (forward-line)
8914 (while (looking-at org-drawer-regexp)
8915 (goto-char (match-end 0))
8916 (re-search-forward org-property-end-re (point-max) t)
8917 (forward-line))
8918 (forward-line -1)))
8919 (unless org-log-states-order-reversed
8920 (and (= (char-after) ?\n) (forward-char 1))
8921 (org-skip-over-state-notes)
8922 (skip-chars-backward " \t\n\r")))
8923 (move-marker org-log-note-marker (point))
8924 (setq org-log-note-purpose purpose
8925 org-log-note-state state
8926 org-log-note-how how
8927 org-log-note-extra extra)
8928 (add-hook 'post-command-hook 'org-add-log-note 'append))))
8930 (defun org-skip-over-state-notes ()
8931 "Skip past the list of State notes in an entry."
8932 (if (looking-at "\n[ \t]*- State") (forward-char 1))
8933 (while (looking-at "[ \t]*- State")
8934 (condition-case nil
8935 (org-next-item)
8936 (error (org-end-of-item)))))
8938 (defun org-add-log-note (&optional purpose)
8939 "Pop up a window for taking a note, and add this note later at point."
8940 (remove-hook 'post-command-hook 'org-add-log-note)
8941 (setq org-log-note-window-configuration (current-window-configuration))
8942 (delete-other-windows)
8943 (move-marker org-log-note-return-to (point))
8944 (switch-to-buffer (marker-buffer org-log-note-marker))
8945 (goto-char org-log-note-marker)
8946 (org-switch-to-buffer-other-window "*Org Note*")
8947 (erase-buffer)
8948 (if (memq org-log-note-how '(time state))
8949 (let (current-prefix-arg) (org-store-log-note))
8950 (let ((org-inhibit-startup t)) (org-mode))
8951 (insert (format "# Insert note for %s.
8952 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
8953 (cond
8954 ((eq org-log-note-purpose 'clock-out) "stopped clock")
8955 ((eq org-log-note-purpose 'done) "closed todo item")
8956 ((eq org-log-note-purpose 'state)
8957 (format "state change to \"%s\"" org-log-note-state))
8958 ((eq org-log-note-purpose 'note)
8959 "this entry")
8960 (t (error "This should not happen")))))
8961 (if org-log-note-extra (insert org-log-note-extra))
8962 (org-set-local 'org-finish-function 'org-store-log-note)))
8964 (defvar org-note-abort nil) ; dynamically scoped
8965 (defun org-store-log-note ()
8966 "Finish taking a log note, and insert it to where it belongs."
8967 (let ((txt (buffer-string))
8968 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
8969 lines ind)
8970 (kill-buffer (current-buffer))
8971 (while (string-match "\\`#.*\n[ \t\n]*" txt)
8972 (setq txt (replace-match "" t t txt)))
8973 (if (string-match "\\s-+\\'" txt)
8974 (setq txt (replace-match "" t t txt)))
8975 (setq lines (org-split-string txt "\n"))
8976 (when (and note (string-match "\\S-" note))
8977 (setq note
8978 (org-replace-escapes
8979 note
8980 (list (cons "%u" (user-login-name))
8981 (cons "%U" user-full-name)
8982 (cons "%t" (format-time-string
8983 (org-time-stamp-format 'long 'inactive)
8984 (current-time)))
8985 (cons "%s" (if org-log-note-state
8986 (concat "\"" org-log-note-state "\"")
8987 "")))))
8988 (if lines (setq note (concat note " \\\\")))
8989 (push note lines))
8990 (when (or current-prefix-arg org-note-abort) (setq lines nil))
8991 (when lines
8992 (save-excursion
8993 (set-buffer (marker-buffer org-log-note-marker))
8994 (save-excursion
8995 (goto-char org-log-note-marker)
8996 (move-marker org-log-note-marker nil)
8997 (end-of-line 1)
8998 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
8999 (indent-relative nil)
9000 (insert "- " (pop lines))
9001 (org-indent-line-function)
9002 (beginning-of-line 1)
9003 (looking-at "[ \t]*")
9004 (setq ind (concat (match-string 0) " "))
9005 (end-of-line 1)
9006 (while lines (insert "\n" ind (pop lines)))))))
9007 (set-window-configuration org-log-note-window-configuration)
9008 (with-current-buffer (marker-buffer org-log-note-return-to)
9009 (goto-char org-log-note-return-to))
9010 (move-marker org-log-note-return-to nil)
9011 (and org-log-post-message (message "%s" org-log-post-message)))
9013 (defun org-sparse-tree (&optional arg)
9014 "Create a sparse tree, prompt for the details.
9015 This command can create sparse trees. You first need to select the type
9016 of match used to create the tree:
9018 t Show entries with a specific TODO keyword.
9019 T Show entries selected by a tags match.
9020 p Enter a property name and its value (both with completion on existing
9021 names/values) and show entries with that property.
9022 r Show entries matching a regular expression
9023 d Show deadlines due within `org-deadline-warning-days'."
9024 (interactive "P")
9025 (let (ans kwd value)
9026 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
9027 (setq ans (read-char-exclusive))
9028 (cond
9029 ((equal ans ?d)
9030 (call-interactively 'org-check-deadlines))
9031 ((equal ans ?b)
9032 (call-interactively 'org-check-before-date))
9033 ((equal ans ?t)
9034 (org-show-todo-tree '(4)))
9035 ((equal ans ?T)
9036 (call-interactively 'org-tags-sparse-tree))
9037 ((member ans '(?p ?P))
9038 (setq kwd (org-ido-completing-read "Property: "
9039 (mapcar 'list (org-buffer-property-keys))))
9040 (setq value (org-ido-completing-read "Value: "
9041 (mapcar 'list (org-property-values kwd))))
9042 (unless (string-match "\\`{.*}\\'" value)
9043 (setq value (concat "\"" value "\"")))
9044 (org-tags-sparse-tree arg (concat kwd "=" value)))
9045 ((member ans '(?r ?R ?/))
9046 (call-interactively 'org-occur))
9047 (t (error "No such sparse tree command \"%c\"" ans)))))
9049 (defvar org-occur-highlights nil
9050 "List of overlays used for occur matches.")
9051 (make-variable-buffer-local 'org-occur-highlights)
9052 (defvar org-occur-parameters nil
9053 "Parameters of the active org-occur calls.
9054 This is a list, each call to org-occur pushes as cons cell,
9055 containing the regular expression and the callback, onto the list.
9056 The list can contain several entries if `org-occur' has been called
9057 several time with the KEEP-PREVIOUS argument. Otherwise, this list
9058 will only contain one set of parameters. When the highlights are
9059 removed (for example with `C-c C-c', or with the next edit (depending
9060 on `org-remove-highlights-with-change'), this variable is emptied
9061 as well.")
9062 (make-variable-buffer-local 'org-occur-parameters)
9064 (defun org-occur (regexp &optional keep-previous callback)
9065 "Make a compact tree which shows all matches of REGEXP.
9066 The tree will show the lines where the regexp matches, and all higher
9067 headlines above the match. It will also show the heading after the match,
9068 to make sure editing the matching entry is easy.
9069 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
9070 call to `org-occur' will be kept, to allow stacking of calls to this
9071 command.
9072 If CALLBACK is non-nil, it is a function which is called to confirm
9073 that the match should indeed be shown."
9074 (interactive "sRegexp: \nP")
9075 (unless keep-previous
9076 (org-remove-occur-highlights nil nil t))
9077 (push (cons regexp callback) org-occur-parameters)
9078 (let ((cnt 0))
9079 (save-excursion
9080 (goto-char (point-min))
9081 (if (or (not keep-previous) ; do not want to keep
9082 (not org-occur-highlights)) ; no previous matches
9083 ;; hide everything
9084 (org-overview))
9085 (while (re-search-forward regexp nil t)
9086 (when (or (not callback)
9087 (save-match-data (funcall callback)))
9088 (setq cnt (1+ cnt))
9089 (when org-highlight-sparse-tree-matches
9090 (org-highlight-new-match (match-beginning 0) (match-end 0)))
9091 (org-show-context 'occur-tree))))
9092 (when org-remove-highlights-with-change
9093 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
9094 nil 'local))
9095 (unless org-sparse-tree-open-archived-trees
9096 (org-hide-archived-subtrees (point-min) (point-max)))
9097 (run-hooks 'org-occur-hook)
9098 (if (interactive-p)
9099 (message "%d match(es) for regexp %s" cnt regexp))
9100 cnt))
9102 (defun org-show-context (&optional key)
9103 "Make sure point and context and visible.
9104 How much context is shown depends upon the variables
9105 `org-show-hierarchy-above', `org-show-following-heading'. and
9106 `org-show-siblings'."
9107 (let ((heading-p (org-on-heading-p t))
9108 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
9109 (following-p (org-get-alist-option org-show-following-heading key))
9110 (entry-p (org-get-alist-option org-show-entry-below key))
9111 (siblings-p (org-get-alist-option org-show-siblings key)))
9112 (catch 'exit
9113 ;; Show heading or entry text
9114 (if (and heading-p (not entry-p))
9115 (org-flag-heading nil) ; only show the heading
9116 (and (or entry-p (org-invisible-p) (org-invisible-p2))
9117 (org-show-hidden-entry))) ; show entire entry
9118 (when following-p
9119 ;; Show next sibling, or heading below text
9120 (save-excursion
9121 (and (if heading-p (org-goto-sibling) (outline-next-heading))
9122 (org-flag-heading nil))))
9123 (when siblings-p (org-show-siblings))
9124 (when hierarchy-p
9125 ;; show all higher headings, possibly with siblings
9126 (save-excursion
9127 (while (and (condition-case nil
9128 (progn (org-up-heading-all 1) t)
9129 (error nil))
9130 (not (bobp)))
9131 (org-flag-heading nil)
9132 (when siblings-p (org-show-siblings))))))))
9134 (defun org-reveal (&optional siblings)
9135 "Show current entry, hierarchy above it, and the following headline.
9136 This can be used to show a consistent set of context around locations
9137 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
9138 not t for the search context.
9140 With optional argument SIBLINGS, on each level of the hierarchy all
9141 siblings are shown. This repairs the tree structure to what it would
9142 look like when opened with hierarchical calls to `org-cycle'."
9143 (interactive "P")
9144 (let ((org-show-hierarchy-above t)
9145 (org-show-following-heading t)
9146 (org-show-siblings (if siblings t org-show-siblings)))
9147 (org-show-context nil)))
9149 (defun org-highlight-new-match (beg end)
9150 "Highlight from BEG to END and mark the highlight is an occur headline."
9151 (let ((ov (org-make-overlay beg end)))
9152 (org-overlay-put ov 'face 'secondary-selection)
9153 (push ov org-occur-highlights)))
9155 (defun org-remove-occur-highlights (&optional beg end noremove)
9156 "Remove the occur highlights from the buffer.
9157 BEG and END are ignored. If NOREMOVE is nil, remove this function
9158 from the `before-change-functions' in the current buffer."
9159 (interactive)
9160 (unless org-inhibit-highlight-removal
9161 (mapc 'org-delete-overlay org-occur-highlights)
9162 (setq org-occur-highlights nil)
9163 (setq org-occur-parameters nil)
9164 (unless noremove
9165 (remove-hook 'before-change-functions
9166 'org-remove-occur-highlights 'local))))
9168 ;;;; Priorities
9170 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
9171 "Regular expression matching the priority indicator.")
9173 (defvar org-remove-priority-next-time nil)
9175 (defun org-priority-up ()
9176 "Increase the priority of the current item."
9177 (interactive)
9178 (org-priority 'up))
9180 (defun org-priority-down ()
9181 "Decrease the priority of the current item."
9182 (interactive)
9183 (org-priority 'down))
9185 (defun org-priority (&optional action)
9186 "Change the priority of an item by ARG.
9187 ACTION can be `set', `up', `down', or a character."
9188 (interactive)
9189 (setq action (or action 'set))
9190 (let (current new news have remove)
9191 (save-excursion
9192 (org-back-to-heading)
9193 (if (looking-at org-priority-regexp)
9194 (setq current (string-to-char (match-string 2))
9195 have t)
9196 (setq current org-default-priority))
9197 (cond
9198 ((or (eq action 'set)
9199 (if (featurep 'xemacs) (characterp action) (integerp action)))
9200 (if (not (eq action 'set))
9201 (setq new action)
9202 (message "Priority %c-%c, SPC to remove: "
9203 org-highest-priority org-lowest-priority)
9204 (setq new (read-char-exclusive)))
9205 (if (and (= (upcase org-highest-priority) org-highest-priority)
9206 (= (upcase org-lowest-priority) org-lowest-priority))
9207 (setq new (upcase new)))
9208 (cond ((equal new ?\ ) (setq remove t))
9209 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
9210 (error "Priority must be between `%c' and `%c'"
9211 org-highest-priority org-lowest-priority))))
9212 ((eq action 'up)
9213 (if (and (not have) (eq last-command this-command))
9214 (setq new org-lowest-priority)
9215 (setq new (if (and org-priority-start-cycle-with-default (not have))
9216 org-default-priority (1- current)))))
9217 ((eq action 'down)
9218 (if (and (not have) (eq last-command this-command))
9219 (setq new org-highest-priority)
9220 (setq new (if (and org-priority-start-cycle-with-default (not have))
9221 org-default-priority (1+ current)))))
9222 (t (error "Invalid action")))
9223 (if (or (< (upcase new) org-highest-priority)
9224 (> (upcase new) org-lowest-priority))
9225 (setq remove t))
9226 (setq news (format "%c" new))
9227 (if have
9228 (if remove
9229 (replace-match "" t t nil 1)
9230 (replace-match news t t nil 2))
9231 (if remove
9232 (error "No priority cookie found in line")
9233 (looking-at org-todo-line-regexp)
9234 (if (match-end 2)
9235 (progn
9236 (goto-char (match-end 2))
9237 (insert " [#" news "]"))
9238 (goto-char (match-beginning 3))
9239 (insert "[#" news "] ")))))
9240 (org-preserve-lc (org-set-tags nil 'align))
9241 (if remove
9242 (message "Priority removed")
9243 (message "Priority of current item set to %s" news))))
9246 (defun org-get-priority (s)
9247 "Find priority cookie and return priority."
9248 (save-match-data
9249 (if (not (string-match org-priority-regexp s))
9250 (* 1000 (- org-lowest-priority org-default-priority))
9251 (* 1000 (- org-lowest-priority
9252 (string-to-char (match-string 2 s)))))))
9254 ;;;; Tags
9256 (defvar org-agenda-archives-mode)
9257 (defun org-scan-tags (action matcher &optional todo-only)
9258 "Scan headline tags with inheritance and produce output ACTION.
9260 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
9261 or `agenda' to produce an entry list for an agenda view. It can also be
9262 a Lisp form or a function that should be called at each matched headline, in
9263 this case the return value is a list of all return values from these calls.
9265 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
9266 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
9267 only lines with a TODO keyword are included in the output."
9268 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
9269 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
9270 (org-re
9271 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
9272 (props (list 'face 'default
9273 'done-face 'org-done
9274 'undone-face 'default
9275 'mouse-face 'highlight
9276 'org-not-done-regexp org-not-done-regexp
9277 'org-todo-regexp org-todo-regexp
9278 'keymap org-agenda-keymap
9279 'help-echo
9280 (format "mouse-2 or RET jump to org file %s"
9281 (abbreviate-file-name
9282 (or (buffer-file-name (buffer-base-buffer))
9283 (buffer-name (buffer-base-buffer)))))))
9284 (case-fold-search nil)
9285 lspos tags tags-list
9286 (tags-alist (list (cons 0 (mapcar 'downcase org-file-tags))))
9287 (llast 0) rtn rtn1 level category i txt
9288 todo marker entry priority)
9289 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
9290 (setq action (list 'lambda nil action)))
9291 (save-excursion
9292 (goto-char (point-min))
9293 (when (eq action 'sparse-tree)
9294 (org-overview)
9295 (org-remove-occur-highlights))
9296 (while (re-search-forward re nil t)
9297 (catch :skip
9298 (setq todo (if (match-end 1) (match-string 2))
9299 tags (if (match-end 4) (match-string 4)))
9300 (goto-char (setq lspos (1+ (match-beginning 0))))
9301 (setq level (org-reduced-level (funcall outline-level))
9302 category (org-get-category))
9303 (setq i llast llast level)
9304 ;; remove tag lists from same and sublevels
9305 (while (>= i level)
9306 (when (setq entry (assoc i tags-alist))
9307 (setq tags-alist (delete entry tags-alist)))
9308 (setq i (1- i)))
9309 ;; add the next tags
9310 (when tags
9311 (setq tags (mapcar 'downcase (org-split-string tags ":"))
9312 tags-alist
9313 (cons (cons level tags) tags-alist)))
9314 ;; compile tags for current headline
9315 (setq tags-list
9316 (if org-use-tag-inheritance
9317 (apply 'append (mapcar 'cdr (reverse tags-alist)))
9318 tags))
9319 (when org-use-tag-inheritance
9320 (setcdr (car tags-alist)
9321 (mapcar (lambda (x)
9322 (setq x (copy-sequence x))
9323 (org-add-prop-inherited x))
9324 (cdar tags-alist))))
9325 (when (and tags org-use-tag-inheritance
9326 (not (eq t org-use-tag-inheritance)))
9327 ;; selective inheritance, remove uninherited ones
9328 (setcdr (car tags-alist)
9329 (org-remove-uniherited-tags (cdar tags-alist))))
9330 (when (and (or (not todo-only) (member todo org-not-done-keywords))
9331 (let ((case-fold-search t)) (eval matcher))
9333 (not (member org-archive-tag tags-list))
9334 ;; we have an archive tag, should we use this anyway?
9335 (or (not org-agenda-skip-archived-trees)
9336 (and (eq action 'agenda) org-agenda-archives-mode))))
9337 (unless (eq action 'sparse-tree) (org-agenda-skip))
9339 ;; select this headline
9341 (cond
9342 ((eq action 'sparse-tree)
9343 (and org-highlight-sparse-tree-matches
9344 (org-get-heading) (match-end 0)
9345 (org-highlight-new-match
9346 (match-beginning 0) (match-beginning 1)))
9347 (org-show-context 'tags-tree))
9348 ((eq action 'agenda)
9349 (setq txt (org-format-agenda-item
9351 (concat
9352 (if org-tags-match-list-sublevels
9353 (make-string (1- level) ?.) "")
9354 (org-get-heading))
9355 category (org-get-tags-at))
9356 priority (org-get-priority txt))
9357 (goto-char lspos)
9358 (setq marker (org-agenda-new-marker))
9359 (org-add-props txt props
9360 'org-marker marker 'org-hd-marker marker 'org-category category
9361 'priority priority 'type "tagsmatch")
9362 (push txt rtn))
9363 ((functionp action)
9364 (save-excursion
9365 (setq rtn1 (funcall action))
9366 (push rtn1 rtn))
9367 (goto-char (point-at-eol)))
9368 (t (error "Invalid action")))
9370 ;; if we are to skip sublevels, jump to end of subtree
9371 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
9372 (when (and (eq action 'sparse-tree)
9373 (not org-sparse-tree-open-archived-trees))
9374 (org-hide-archived-subtrees (point-min) (point-max)))
9375 (nreverse rtn)))
9377 (defun org-remove-uniherited-tags (tags)
9378 "Remove all tags that are not inherited from the list TAGS."
9379 (cond
9380 ((eq org-use-tag-inheritance t)
9381 (if org-tags-exclude-from-inheritance
9382 (org-delete-all org-tags-exclude-from-inheritance tags)
9383 tags))
9384 ((not org-use-tag-inheritance) nil)
9385 ((stringp org-use-tag-inheritance)
9386 (delq nil (mapcar
9387 (lambda (x)
9388 (if (and (string-match org-use-tag-inheritance x)
9389 (not (member x org-tags-exclude-from-inheritance)))
9390 x nil))
9391 tags)))
9392 ((listp org-use-tag-inheritance)
9393 (delq nil (mapcar
9394 (lambda (x)
9395 (if (member x org-use-tag-inheritance) x nil))
9396 tags)))))
9398 (defvar todo-only) ;; dynamically scoped
9400 (defun org-tags-sparse-tree (&optional todo-only match)
9401 "Create a sparse tree according to tags string MATCH.
9402 MATCH can contain positive and negative selection of tags, like
9403 \"+WORK+URGENT-WITHBOSS\".
9404 If optional argument TODO-ONLY is non-nil, only select lines that are
9405 also TODO lines."
9406 (interactive "P")
9407 (org-prepare-agenda-buffers (list (current-buffer)))
9408 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
9410 (defvar org-cached-props nil)
9411 (defun org-cached-entry-get (pom property)
9412 (if (or (eq t org-use-property-inheritance)
9413 (and (stringp org-use-property-inheritance)
9414 (string-match org-use-property-inheritance property))
9415 (and (listp org-use-property-inheritance)
9416 (member property org-use-property-inheritance)))
9417 ;; Caching is not possible, check it directly
9418 (org-entry-get pom property 'inherit)
9419 ;; Get all properties, so that we can do complicated checks easily
9420 (cdr (assoc property (or org-cached-props
9421 (setq org-cached-props
9422 (org-entry-properties pom)))))))
9424 (defun org-global-tags-completion-table (&optional files)
9425 "Return the list of all tags in all agenda buffer/files."
9426 (save-excursion
9427 (org-uniquify
9428 (delq nil
9429 (apply 'append
9430 (mapcar
9431 (lambda (file)
9432 (set-buffer (find-file-noselect file))
9433 (append (org-get-buffer-tags)
9434 (mapcar (lambda (x) (if (stringp (car-safe x))
9435 (list (car-safe x)) nil))
9436 org-tag-alist)))
9437 (if (and files (car files))
9438 files
9439 (org-agenda-files))))))))
9441 (defun org-make-tags-matcher (match)
9442 "Create the TAGS//TODO matcher form for the selection string MATCH."
9443 ;; todo-only is scoped dynamically into this function, and the function
9444 ;; may change it if the matcher asks for it.
9445 (unless match
9446 ;; Get a new match request, with completion
9447 (let ((org-last-tags-completion-table
9448 (org-global-tags-completion-table)))
9449 (setq match (org-completing-read
9450 "Match: " 'org-tags-completion-function nil nil nil
9451 'org-tags-history))))
9453 ;; Parse the string and create a lisp form
9454 (let ((match0 match)
9455 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
9456 minus tag mm
9457 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
9458 orterms term orlist re-p str-p level-p level-op time-p
9459 prop-p pn pv po cat-p gv rest)
9460 (if (string-match "/+" match)
9461 ;; match contains also a todo-matching request
9462 (progn
9463 (setq tagsmatch (substring match 0 (match-beginning 0))
9464 todomatch (substring match (match-end 0)))
9465 (if (string-match "^!" todomatch)
9466 (setq todo-only t todomatch (substring todomatch 1)))
9467 (if (string-match "^\\s-*$" todomatch)
9468 (setq todomatch nil)))
9469 ;; only matching tags
9470 (setq tagsmatch match todomatch nil))
9472 ;; Make the tags matcher
9473 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
9474 (setq tagsmatcher t)
9475 (setq orterms (org-split-string tagsmatch "|") orlist nil)
9476 (while (setq term (pop orterms))
9477 (while (and (equal (substring term -1) "\\") orterms)
9478 (setq term (concat term "|" (pop orterms)))) ; repair bad split
9479 (while (string-match re term)
9480 (setq rest (substring term (match-end 0))
9481 minus (and (match-end 1)
9482 (equal (match-string 1 term) "-"))
9483 tag (match-string 2 term)
9484 re-p (equal (string-to-char tag) ?{)
9485 level-p (match-end 4)
9486 prop-p (match-end 5)
9487 mm (cond
9488 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
9489 (level-p
9490 (setq level-op (org-op-to-function (match-string 3 term)))
9491 `(,level-op level ,(string-to-number
9492 (match-string 4 term))))
9493 (prop-p
9494 (setq pn (match-string 5 term)
9495 po (match-string 6 term)
9496 pv (match-string 7 term)
9497 cat-p (equal pn "CATEGORY")
9498 re-p (equal (string-to-char pv) ?{)
9499 str-p (equal (string-to-char pv) ?\")
9500 time-p (save-match-data
9501 (string-match "^\"[[<].*[]>]\"$" pv))
9502 pv (if (or re-p str-p) (substring pv 1 -1) pv))
9503 (if time-p (setq pv (org-matcher-time pv)))
9504 (setq po (org-op-to-function po (if time-p 'time str-p)))
9505 (cond
9506 ((equal pn "CATEGORY")
9507 (setq gv '(get-text-property (point) 'org-category)))
9508 ((equal pn "TODO")
9509 (setq gv 'todo))
9511 (setq gv `(org-cached-entry-get nil ,pn))))
9512 (if re-p
9513 (if (eq po 'org<>)
9514 `(not (string-match ,pv (or ,gv "")))
9515 `(string-match ,pv (or ,gv "")))
9516 (if str-p
9517 `(,po (or ,gv "") ,pv)
9518 `(,po (string-to-number (or ,gv ""))
9519 ,(string-to-number pv) ))))
9520 (t `(member ,(downcase tag) tags-list)))
9521 mm (if minus (list 'not mm) mm)
9522 term rest)
9523 (push mm tagsmatcher))
9524 (push (if (> (length tagsmatcher) 1)
9525 (cons 'and tagsmatcher)
9526 (car tagsmatcher))
9527 orlist)
9528 (setq tagsmatcher nil))
9529 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
9530 (setq tagsmatcher
9531 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
9532 ;; Make the todo matcher
9533 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
9534 (setq todomatcher t)
9535 (setq orterms (org-split-string todomatch "|") orlist nil)
9536 (while (setq term (pop orterms))
9537 (while (string-match re term)
9538 (setq minus (and (match-end 1)
9539 (equal (match-string 1 term) "-"))
9540 kwd (match-string 2 term)
9541 re-p (equal (string-to-char kwd) ?{)
9542 term (substring term (match-end 0))
9543 mm (if re-p
9544 `(string-match ,(substring kwd 1 -1) todo)
9545 (list 'equal 'todo kwd))
9546 mm (if minus (list 'not mm) mm))
9547 (push mm todomatcher))
9548 (push (if (> (length todomatcher) 1)
9549 (cons 'and todomatcher)
9550 (car todomatcher))
9551 orlist)
9552 (setq todomatcher nil))
9553 (setq todomatcher (if (> (length orlist) 1)
9554 (cons 'or orlist) (car orlist))))
9556 ;; Return the string and lisp forms of the matcher
9557 (setq matcher (if todomatcher
9558 (list 'and tagsmatcher todomatcher)
9559 tagsmatcher))
9560 (cons match0 matcher)))
9562 (defun org-op-to-function (op &optional stringp)
9563 "Turn an operator into the appropriate function."
9564 (setq op
9565 (cond
9566 ((equal op "<" ) '(< string< org-time<))
9567 ((equal op ">" ) '(> org-string> org-time>))
9568 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
9569 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
9570 ((member op '("=" "==")) '(= string= org-time=))
9571 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
9572 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
9574 (defun org<> (a b) (not (= a b)))
9575 (defun org-string<= (a b) (or (string= a b) (string< a b)))
9576 (defun org-string>= (a b) (not (string< a b)))
9577 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
9578 (defun org-string<> (a b) (not (string= a b)))
9579 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
9580 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
9581 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
9582 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
9583 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
9584 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
9585 (defun org-2ft (s)
9586 "Convert S to a floating point time.
9587 If S is already a number, just return it. If it is a string, parse
9588 it as a time string and apply `float-time' to it. If S is nil, just return 0."
9589 (cond
9590 ((numberp s) s)
9591 ((stringp s)
9592 (condition-case nil
9593 (float-time (apply 'encode-time (org-parse-time-string s)))
9594 (error 0.)))
9595 (t 0.)))
9597 (defun org-time-today ()
9598 "Time in seconds today at 0:00.
9599 Returns the float number of seconds since the beginning of the
9600 epoch to the beginning of today (00:00)."
9601 (float-time (apply 'encode-time
9602 (append '(0 0 0) (nthcdr 3 (decode-time))))))
9604 (defun org-matcher-time (s)
9605 "Interpret a time comparison value."
9606 (save-match-data
9607 (cond
9608 ((string= s "<now>") (float-time))
9609 ((string= s "<today>") (org-time-today))
9610 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
9611 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
9612 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
9613 (+ (org-time-today)
9614 (* (string-to-number (match-string 1 s))
9615 (cdr (assoc (match-string 2 s)
9616 '(("d" . 86400.0) ("w" . 604800.0)
9617 ("m" . 2678400.0) ("y" . 31557600.0)))))))
9618 (t (org-2ft s)))))
9620 (defun org-match-any-p (re list)
9621 "Does re match any element of list?"
9622 (setq list (mapcar (lambda (x) (string-match re x)) list))
9623 (delq nil list))
9625 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
9626 (defvar org-tags-overlay (org-make-overlay 1 1))
9627 (org-detach-overlay org-tags-overlay)
9629 (defun org-get-local-tags-at (&optional pos)
9630 "Get a list of tags defined in the current headline."
9631 (org-get-tags-at pos 'local))
9633 (defun org-get-local-tags ()
9634 "Get a list of tags defined in the current headline."
9635 (org-get-tags-at nil 'local))
9637 (defun org-get-tags-at (&optional pos local)
9638 "Get a list of all headline tags applicable at POS.
9639 POS defaults to point. If tags are inherited, the list contains
9640 the targets in the same sequence as the headlines appear, i.e.
9641 the tags of the current headline come last.
9642 When LOCAL is non-nil, only return tags from the current headline,
9643 ignore inherited ones."
9644 (interactive)
9645 (let (tags ltags lastpos parent)
9646 (save-excursion
9647 (save-restriction
9648 (widen)
9649 (goto-char (or pos (point)))
9650 (save-match-data
9651 (catch 'done
9652 (condition-case nil
9653 (progn
9654 (org-back-to-heading t)
9655 (while (not (equal lastpos (point)))
9656 (setq lastpos (point))
9657 (when (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
9658 (setq ltags (org-split-string
9659 (org-match-string-no-properties 1) ":"))
9660 (when parent
9661 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
9662 (setq tags (append
9663 (if parent
9664 (org-remove-uniherited-tags ltags)
9665 ltags)
9666 tags)))
9667 (or org-use-tag-inheritance (throw 'done t))
9668 (if local (throw 'done t))
9669 (org-up-heading-all 1)
9670 (setq parent t)))
9671 (error nil)))))
9672 (append (org-remove-uniherited-tags org-file-tags) tags))))
9674 (defun org-add-prop-inherited (s)
9675 (add-text-properties 0 (length s) '(inherited t) s)
9678 (defun org-toggle-tag (tag &optional onoff)
9679 "Toggle the tag TAG for the current line.
9680 If ONOFF is `on' or `off', don't toggle but set to this state."
9681 (let (res current)
9682 (save-excursion
9683 (org-back-to-heading t)
9684 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
9685 (point-at-eol) t)
9686 (progn
9687 (setq current (match-string 1))
9688 (replace-match ""))
9689 (setq current ""))
9690 (setq current (nreverse (org-split-string current ":")))
9691 (cond
9692 ((eq onoff 'on)
9693 (setq res t)
9694 (or (member tag current) (push tag current)))
9695 ((eq onoff 'off)
9696 (or (not (member tag current)) (setq current (delete tag current))))
9697 (t (if (member tag current)
9698 (setq current (delete tag current))
9699 (setq res t)
9700 (push tag current))))
9701 (end-of-line 1)
9702 (if current
9703 (progn
9704 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
9705 (org-set-tags nil t))
9706 (delete-horizontal-space))
9707 (run-hooks 'org-after-tags-change-hook))
9708 res))
9710 (defun org-align-tags-here (to-col)
9711 ;; Assumes that this is a headline
9712 (let ((pos (point)) (col (current-column)) ncol tags-l p)
9713 (beginning-of-line 1)
9714 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9715 (< pos (match-beginning 2)))
9716 (progn
9717 (setq tags-l (- (match-end 2) (match-beginning 2)))
9718 (goto-char (match-beginning 1))
9719 (insert " ")
9720 (delete-region (point) (1+ (match-beginning 2)))
9721 (setq ncol (max (1+ (current-column))
9722 (1+ col)
9723 (if (> to-col 0)
9724 to-col
9725 (- (abs to-col) tags-l))))
9726 (setq p (point))
9727 (insert (make-string (- ncol (current-column)) ?\ ))
9728 (setq ncol (current-column))
9729 (when indent-tabs-mode (tabify p (point-at-eol)))
9730 (org-move-to-column (min ncol col) t))
9731 (goto-char pos))))
9733 (defun org-set-tags-command (&optional arg just-align)
9734 "Call the set-tags command for the current entry."
9735 (interactive "P")
9736 (if (org-on-heading-p)
9737 (org-set-tags arg just-align)
9738 (save-excursion
9739 (org-back-to-heading t)
9740 (org-set-tags arg just-align))))
9742 (defun org-set-tags (&optional arg just-align)
9743 "Set the tags for the current headline.
9744 With prefix ARG, realign all tags in headings in the current buffer."
9745 (interactive "P")
9746 (let* ((re (concat "^" outline-regexp))
9747 (current (org-get-tags-string))
9748 (col (current-column))
9749 (org-setting-tags t)
9750 table current-tags inherited-tags ; computed below when needed
9751 tags p0 c0 c1 rpl)
9752 (if arg
9753 (save-excursion
9754 (goto-char (point-min))
9755 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
9756 (while (re-search-forward re nil t)
9757 (org-set-tags nil t)
9758 (end-of-line 1)))
9759 (message "All tags realigned to column %d" org-tags-column))
9760 (if just-align
9761 (setq tags current)
9762 ;; Get a new set of tags from the user
9763 (save-excursion
9764 (setq table (or org-tag-alist (org-get-buffer-tags))
9765 org-last-tags-completion-table table
9766 current-tags (org-split-string current ":")
9767 inherited-tags (nreverse
9768 (nthcdr (length current-tags)
9769 (nreverse (org-get-tags-at))))
9770 tags
9771 (if (or (eq t org-use-fast-tag-selection)
9772 (and org-use-fast-tag-selection
9773 (delq nil (mapcar 'cdr table))))
9774 (org-fast-tag-selection
9775 current-tags inherited-tags table
9776 (if org-fast-tag-selection-include-todo org-todo-key-alist))
9777 (let ((org-add-colon-after-tag-completion t))
9778 (org-trim
9779 (org-without-partial-completion
9780 (org-ido-completing-read "Tags: " 'org-tags-completion-function
9781 nil nil current 'org-tags-history)))))))
9782 (while (string-match "[-+&]+" tags)
9783 ;; No boolean logic, just a list
9784 (setq tags (replace-match ":" t t tags))))
9786 (if (string-match "\\`[\t ]*\\'" tags)
9787 (setq tags "")
9788 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
9789 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
9791 ;; Insert new tags at the correct column
9792 (beginning-of-line 1)
9793 (cond
9794 ((and (equal current "") (equal tags "")))
9795 ((re-search-forward
9796 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
9797 (point-at-eol) t)
9798 (if (equal tags "")
9799 (setq rpl "")
9800 (goto-char (match-beginning 0))
9801 (setq c0 (current-column) p0 (point)
9802 c1 (max (1+ c0) (if (> org-tags-column 0)
9803 org-tags-column
9804 (- (- org-tags-column) (length tags))))
9805 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
9806 (replace-match rpl t t)
9807 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
9808 tags)
9809 (t (error "Tags alignment failed")))
9810 (org-move-to-column col)
9811 (unless just-align
9812 (run-hooks 'org-after-tags-change-hook)))))
9814 (defun org-change-tag-in-region (beg end tag off)
9815 "Add or remove TAG for each entry in the region.
9816 This works in the agenda, and also in an org-mode buffer."
9817 (interactive
9818 (list (region-beginning) (region-end)
9819 (let ((org-last-tags-completion-table
9820 (if (org-mode-p)
9821 (org-get-buffer-tags)
9822 (org-global-tags-completion-table))))
9823 (org-ido-completing-read
9824 "Tag: " 'org-tags-completion-function nil nil nil
9825 'org-tags-history))
9826 (progn
9827 (message "[s]et or [r]emove? ")
9828 (equal (read-char-exclusive) ?r))))
9829 (if (fboundp 'deactivate-mark) (deactivate-mark))
9830 (let ((agendap (equal major-mode 'org-agenda-mode))
9831 l1 l2 m buf pos newhead (cnt 0))
9832 (goto-char end)
9833 (setq l2 (1- (org-current-line)))
9834 (goto-char beg)
9835 (setq l1 (org-current-line))
9836 (loop for l from l1 to l2 do
9837 (goto-line l)
9838 (setq m (get-text-property (point) 'org-hd-marker))
9839 (when (or (and (org-mode-p) (org-on-heading-p))
9840 (and agendap m))
9841 (setq buf (if agendap (marker-buffer m) (current-buffer))
9842 pos (if agendap m (point)))
9843 (with-current-buffer buf
9844 (save-excursion
9845 (save-restriction
9846 (goto-char pos)
9847 (setq cnt (1+ cnt))
9848 (org-toggle-tag tag (if off 'off 'on))
9849 (setq newhead (org-get-heading)))))
9850 (and agendap (org-agenda-change-all-lines newhead m))))
9851 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
9853 (defun org-tags-completion-function (string predicate &optional flag)
9854 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
9855 (confirm (lambda (x) (stringp (car x)))))
9856 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
9857 (setq s1 (match-string 1 string)
9858 s2 (match-string 2 string))
9859 (setq s1 "" s2 string))
9860 (cond
9861 ((eq flag nil)
9862 ;; try completion
9863 (setq rtn (try-completion s2 ctable confirm))
9864 (if (stringp rtn)
9865 (setq rtn
9866 (concat s1 s2 (substring rtn (length s2))
9867 (if (and org-add-colon-after-tag-completion
9868 (assoc rtn ctable))
9869 ":" ""))))
9870 rtn)
9871 ((eq flag t)
9872 ;; all-completions
9873 (all-completions s2 ctable confirm)
9875 ((eq flag 'lambda)
9876 ;; exact match?
9877 (assoc s2 ctable)))
9880 (defun org-fast-tag-insert (kwd tags face &optional end)
9881 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
9882 (insert (format "%-12s" (concat kwd ":"))
9883 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
9884 (or end "")))
9886 (defun org-fast-tag-show-exit (flag)
9887 (save-excursion
9888 (goto-line 3)
9889 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
9890 (replace-match ""))
9891 (when flag
9892 (end-of-line 1)
9893 (org-move-to-column (- (window-width) 19) t)
9894 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
9896 (defun org-set-current-tags-overlay (current prefix)
9897 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
9898 (if (featurep 'xemacs)
9899 (org-overlay-display org-tags-overlay (concat prefix s)
9900 'secondary-selection)
9901 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
9902 (org-overlay-display org-tags-overlay (concat prefix s)))))
9904 (defun org-fast-tag-selection (current inherited table &optional todo-table)
9905 "Fast tag selection with single keys.
9906 CURRENT is the current list of tags in the headline, INHERITED is the
9907 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
9908 possibly with grouping information. TODO-TABLE is a similar table with
9909 TODO keywords, should these have keys assigned to them.
9910 If the keys are nil, a-z are automatically assigned.
9911 Returns the new tags string, or nil to not change the current settings."
9912 (let* ((fulltable (append table todo-table))
9913 (maxlen (apply 'max (mapcar
9914 (lambda (x)
9915 (if (stringp (car x)) (string-width (car x)) 0))
9916 fulltable)))
9917 (buf (current-buffer))
9918 (expert (eq org-fast-tag-selection-single-key 'expert))
9919 (buffer-tags nil)
9920 (fwidth (+ maxlen 3 1 3))
9921 (ncol (/ (- (window-width) 4) fwidth))
9922 (i-face 'org-done)
9923 (c-face 'org-todo)
9924 tg cnt e c char c1 c2 ntable tbl rtn
9925 ov-start ov-end ov-prefix
9926 (exit-after-next org-fast-tag-selection-single-key)
9927 (done-keywords org-done-keywords)
9928 groups ingroup)
9929 (save-excursion
9930 (beginning-of-line 1)
9931 (if (looking-at
9932 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9933 (setq ov-start (match-beginning 1)
9934 ov-end (match-end 1)
9935 ov-prefix "")
9936 (setq ov-start (1- (point-at-eol))
9937 ov-end (1+ ov-start))
9938 (skip-chars-forward "^\n\r")
9939 (setq ov-prefix
9940 (concat
9941 (buffer-substring (1- (point)) (point))
9942 (if (> (current-column) org-tags-column)
9944 (make-string (- org-tags-column (current-column)) ?\ ))))))
9945 (org-move-overlay org-tags-overlay ov-start ov-end)
9946 (save-window-excursion
9947 (if expert
9948 (set-buffer (get-buffer-create " *Org tags*"))
9949 (delete-other-windows)
9950 (split-window-vertically)
9951 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
9952 (erase-buffer)
9953 (org-set-local 'org-done-keywords done-keywords)
9954 (org-fast-tag-insert "Inherited" inherited i-face "\n")
9955 (org-fast-tag-insert "Current" current c-face "\n\n")
9956 (org-fast-tag-show-exit exit-after-next)
9957 (org-set-current-tags-overlay current ov-prefix)
9958 (setq tbl fulltable char ?a cnt 0)
9959 (while (setq e (pop tbl))
9960 (cond
9961 ((equal e '(:startgroup))
9962 (push '() groups) (setq ingroup t)
9963 (when (not (= cnt 0))
9964 (setq cnt 0)
9965 (insert "\n"))
9966 (insert "{ "))
9967 ((equal e '(:endgroup))
9968 (setq ingroup nil cnt 0)
9969 (insert "}\n"))
9971 (setq tg (car e) c2 nil)
9972 (if (cdr e)
9973 (setq c (cdr e))
9974 ;; automatically assign a character.
9975 (setq c1 (string-to-char
9976 (downcase (substring
9977 tg (if (= (string-to-char tg) ?@) 1 0)))))
9978 (if (or (rassoc c1 ntable) (rassoc c1 table))
9979 (while (or (rassoc char ntable) (rassoc char table))
9980 (setq char (1+ char)))
9981 (setq c2 c1))
9982 (setq c (or c2 char)))
9983 (if ingroup (push tg (car groups)))
9984 (setq tg (org-add-props tg nil 'face
9985 (cond
9986 ((not (assoc tg table))
9987 (org-get-todo-face tg))
9988 ((member tg current) c-face)
9989 ((member tg inherited) i-face)
9990 (t nil))))
9991 (if (and (= cnt 0) (not ingroup)) (insert " "))
9992 (insert "[" c "] " tg (make-string
9993 (- fwidth 4 (length tg)) ?\ ))
9994 (push (cons tg c) ntable)
9995 (when (= (setq cnt (1+ cnt)) ncol)
9996 (insert "\n")
9997 (if ingroup (insert " "))
9998 (setq cnt 0)))))
9999 (setq ntable (nreverse ntable))
10000 (insert "\n")
10001 (goto-char (point-min))
10002 (if (not expert) (org-fit-window-to-buffer))
10003 (setq rtn
10004 (catch 'exit
10005 (while t
10006 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
10007 (if groups " [!] no groups" " [!]groups")
10008 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
10009 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
10010 (cond
10011 ((= c ?\r) (throw 'exit t))
10012 ((= c ?!)
10013 (setq groups (not groups))
10014 (goto-char (point-min))
10015 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
10016 ((= c ?\C-c)
10017 (if (not expert)
10018 (org-fast-tag-show-exit
10019 (setq exit-after-next (not exit-after-next)))
10020 (setq expert nil)
10021 (delete-other-windows)
10022 (split-window-vertically)
10023 (org-switch-to-buffer-other-window " *Org tags*")
10024 (org-fit-window-to-buffer)))
10025 ((or (= c ?\C-g)
10026 (and (= c ?q) (not (rassoc c ntable))))
10027 (org-detach-overlay org-tags-overlay)
10028 (setq quit-flag t))
10029 ((= c ?\ )
10030 (setq current nil)
10031 (if exit-after-next (setq exit-after-next 'now)))
10032 ((= c ?\t)
10033 (condition-case nil
10034 (setq tg (org-ido-completing-read
10035 "Tag: "
10036 (or buffer-tags
10037 (with-current-buffer buf
10038 (org-get-buffer-tags)))))
10039 (quit (setq tg "")))
10040 (when (string-match "\\S-" tg)
10041 (add-to-list 'buffer-tags (list tg))
10042 (if (member tg current)
10043 (setq current (delete tg current))
10044 (push tg current)))
10045 (if exit-after-next (setq exit-after-next 'now)))
10046 ((setq e (rassoc c todo-table) tg (car e))
10047 (with-current-buffer buf
10048 (save-excursion (org-todo tg)))
10049 (if exit-after-next (setq exit-after-next 'now)))
10050 ((setq e (rassoc c ntable) tg (car e))
10051 (if (member tg current)
10052 (setq current (delete tg current))
10053 (loop for g in groups do
10054 (if (member tg g)
10055 (mapc (lambda (x)
10056 (setq current (delete x current)))
10057 g)))
10058 (push tg current))
10059 (if exit-after-next (setq exit-after-next 'now))))
10061 ;; Create a sorted list
10062 (setq current
10063 (sort current
10064 (lambda (a b)
10065 (assoc b (cdr (memq (assoc a ntable) ntable))))))
10066 (if (eq exit-after-next 'now) (throw 'exit t))
10067 (goto-char (point-min))
10068 (beginning-of-line 2)
10069 (delete-region (point) (point-at-eol))
10070 (org-fast-tag-insert "Current" current c-face)
10071 (org-set-current-tags-overlay current ov-prefix)
10072 (while (re-search-forward
10073 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
10074 (setq tg (match-string 1))
10075 (add-text-properties
10076 (match-beginning 1) (match-end 1)
10077 (list 'face
10078 (cond
10079 ((member tg current) c-face)
10080 ((member tg inherited) i-face)
10081 (t (get-text-property (match-beginning 1) 'face))))))
10082 (goto-char (point-min)))))
10083 (org-detach-overlay org-tags-overlay)
10084 (if rtn
10085 (mapconcat 'identity current ":")
10086 nil))))
10088 (defun org-get-tags-string ()
10089 "Get the TAGS string in the current headline."
10090 (unless (org-on-heading-p t)
10091 (error "Not on a heading"))
10092 (save-excursion
10093 (beginning-of-line 1)
10094 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10095 (org-match-string-no-properties 1)
10096 "")))
10098 (defun org-get-tags ()
10099 "Get the list of tags specified in the current headline."
10100 (org-split-string (org-get-tags-string) ":"))
10102 (defun org-get-buffer-tags ()
10103 "Get a table of all tags used in the buffer, for completion."
10104 (let (tags)
10105 (save-excursion
10106 (goto-char (point-min))
10107 (while (re-search-forward
10108 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
10109 (when (equal (char-after (point-at-bol 0)) ?*)
10110 (mapc (lambda (x) (add-to-list 'tags x))
10111 (org-split-string (org-match-string-no-properties 1) ":")))))
10112 (mapcar 'list tags)))
10114 ;;;; The mapping API
10116 ;;;###autoload
10117 (defun org-map-entries (func &optional match scope &rest skip)
10118 "Call FUNC at each headline selected by MATCH in SCOPE.
10120 FUNC is a function or a lisp form. The function will be called without
10121 arguments, with the cursor positioned at the beginning of the headline.
10122 The return values of all calls to the function will be collected and
10123 returned as a list.
10125 MATCH is a tags/property/todo match as it is used in the agenda tags view.
10126 Only headlines that are matched by this query will be considered during
10127 the iteration. When MATCH is nil or t, all headlines will be
10128 visited by the iteration.
10130 SCOPE determines the scope of this command. It can be any of:
10132 nil The current buffer, respecting the restriction if any
10133 tree The subtree started with the entry at point
10134 file The current buffer, without restriction
10135 file-with-archives
10136 The current buffer, and any archives associated with it
10137 agenda All agenda files
10138 agenda-with-archives
10139 All agenda files with any archive files associated with them
10140 \(file1 file2 ...)
10141 If this is a list, all files in the list will be scanned
10143 The remaining args are treated as settings for the skipping facilities of
10144 the scanner. The following items can be given here:
10146 archive skip trees with the archive tag.
10147 comment skip trees with the COMMENT keyword
10148 function or Emacs Lisp form:
10149 will be used as value for `org-agenda-skip-function', so whenever
10150 the the function returns t, FUNC will not be called for that
10151 entry and search will continue from the point where the
10152 function leaves it."
10153 (let* ((org-agenda-archives-mode nil) ; just to make sure
10154 (org-agenda-skip-archived-trees (memq 'archive skip))
10155 (org-agenda-skip-comment-trees (memq 'comment skip))
10156 (org-agenda-skip-function
10157 (car (org-delete-all '(comment archive) skip)))
10158 (org-tags-match-list-sublevels t)
10159 matcher pos file res
10160 org-todo-keywords-for-agenda
10161 org-done-keywords-for-agenda
10162 org-todo-keyword-alist-for-agenda
10163 org-tag-alist-for-agenda)
10165 (cond
10166 ((eq match t) (setq matcher t))
10167 ((eq match nil) (setq matcher t))
10168 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
10170 (save-excursion
10171 (save-restriction
10172 (when (eq scope 'tree)
10173 (org-back-to-heading t)
10174 (org-narrow-to-subtree)
10175 (setq scope nil))
10177 (if (not scope)
10178 (progn
10179 (org-prepare-agenda-buffers
10180 (list (buffer-file-name (current-buffer))))
10181 (setq res (org-scan-tags func matcher)))
10182 ;; Get the right scope
10183 (setq pos (point))
10184 (cond
10185 ((and scope (listp scope) (symbolp (car scope)))
10186 (setq scope (eval scope)))
10187 ((eq scope 'agenda)
10188 (setq scope (org-agenda-files t)))
10189 ((eq scope 'agenda-with-archives)
10190 (setq scope (org-agenda-files t))
10191 (setq scope (org-add-archive-files scope)))
10192 ((eq scope 'file)
10193 (setq scope (list (buffer-file-name))))
10194 ((eq scope 'file-with-archives)
10195 (setq scope (org-add-archive-files (list (buffer-file-name))))))
10196 (org-prepare-agenda-buffers scope)
10197 (while (setq file (pop scope))
10198 (with-current-buffer (org-find-base-buffer-visiting file)
10199 (save-excursion
10200 (save-restriction
10201 (widen)
10202 (goto-char (point-min))
10203 (setq res (append res (org-scan-tags func matcher))))))))))
10204 res))
10206 ;;;; Properties
10208 ;;; Setting and retrieving properties
10210 (defconst org-special-properties
10211 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
10212 "TIMESTAMP" "TIMESTAMP_IA")
10213 "The special properties valid in Org-mode.
10215 These are properties that are not defined in the property drawer,
10216 but in some other way.")
10218 (defconst org-default-properties
10219 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
10220 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
10221 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
10222 "EXPORT_FILE_NAME" "EXPORT_TITLE")
10223 "Some properties that are used by Org-mode for various purposes.
10224 Being in this list makes sure that they are offered for completion.")
10226 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
10227 "Regular expression matching the first line of a property drawer.")
10229 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
10230 "Regular expression matching the first line of a property drawer.")
10232 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
10233 "Regular expression matching the first line of a property drawer.")
10235 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
10236 "Regular expression matching the first line of a property drawer.")
10238 (defconst org-property-drawer-re
10239 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
10240 org-property-end-re "\\)\n?")
10241 "Matches an entire property drawer.")
10243 (defconst org-clock-drawer-re
10244 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
10245 org-property-end-re "\\)\n?")
10246 "Matches an entire clock drawer.")
10248 (defun org-property-action ()
10249 "Do an action on properties."
10250 (interactive)
10251 (let (c)
10252 (org-at-property-p)
10253 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
10254 (setq c (read-char-exclusive))
10255 (cond
10256 ((equal c ?s)
10257 (call-interactively 'org-set-property))
10258 ((equal c ?d)
10259 (call-interactively 'org-delete-property))
10260 ((equal c ?D)
10261 (call-interactively 'org-delete-property-globally))
10262 ((equal c ?c)
10263 (call-interactively 'org-compute-property-at-point))
10264 (t (error "No such property action %c" c)))))
10266 (defun org-at-property-p ()
10267 "Is the cursor in a property line?"
10268 ;; FIXME: Does not check if we are actually in the drawer.
10269 ;; FIXME: also returns true on any drawers.....
10270 ;; This is used by C-c C-c for property action.
10271 (save-excursion
10272 (beginning-of-line 1)
10273 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
10275 (defun org-get-property-block (&optional beg end force)
10276 "Return the (beg . end) range of the body of the property drawer.
10277 BEG and END can be beginning and end of subtree, if not given
10278 they will be found.
10279 If the drawer does not exist and FORCE is non-nil, create the drawer."
10280 (catch 'exit
10281 (save-excursion
10282 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
10283 (end (or end (progn (outline-next-heading) (point)))))
10284 (goto-char beg)
10285 (if (re-search-forward org-property-start-re end t)
10286 (setq beg (1+ (match-end 0)))
10287 (if force
10288 (save-excursion
10289 (org-insert-property-drawer)
10290 (setq end (progn (outline-next-heading) (point))))
10291 (throw 'exit nil))
10292 (goto-char beg)
10293 (if (re-search-forward org-property-start-re end t)
10294 (setq beg (1+ (match-end 0)))))
10295 (if (re-search-forward org-property-end-re end t)
10296 (setq end (match-beginning 0))
10297 (or force (throw 'exit nil))
10298 (goto-char beg)
10299 (setq end beg)
10300 (org-indent-line-function)
10301 (insert ":END:\n"))
10302 (cons beg end)))))
10304 (defun org-entry-properties (&optional pom which)
10305 "Get all properties of the entry at point-or-marker POM.
10306 This includes the TODO keyword, the tags, time strings for deadline,
10307 scheduled, and clocking, and any additional properties defined in the
10308 entry. The return value is an alist, keys may occur multiple times
10309 if the property key was used several times.
10310 POM may also be nil, in which case the current entry is used.
10311 If WHICH is nil or `all', get all properties. If WHICH is
10312 `special' or `standard', only get that subclass."
10313 (setq which (or which 'all))
10314 (org-with-point-at pom
10315 (let ((clockstr (substring org-clock-string 0 -1))
10316 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
10317 beg end range props sum-props key value string clocksum)
10318 (save-excursion
10319 (when (condition-case nil
10320 (and (org-mode-p) (org-back-to-heading t))
10321 (error nil))
10322 (setq beg (point))
10323 (setq sum-props (get-text-property (point) 'org-summaries))
10324 (setq clocksum (get-text-property (point) :org-clock-minutes))
10325 (outline-next-heading)
10326 (setq end (point))
10327 (when (memq which '(all special))
10328 ;; Get the special properties, like TODO and tags
10329 (goto-char beg)
10330 (when (and (looking-at org-todo-line-regexp) (match-end 2))
10331 (push (cons "TODO" (org-match-string-no-properties 2)) props))
10332 (when (looking-at org-priority-regexp)
10333 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
10334 (when (and (setq value (org-get-tags-string))
10335 (string-match "\\S-" value))
10336 (push (cons "TAGS" value) props))
10337 (when (setq value (org-get-tags-at))
10338 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
10339 props))
10340 (while (re-search-forward org-maybe-keyword-time-regexp end t)
10341 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
10342 string (if (equal key clockstr)
10343 (org-no-properties
10344 (org-trim
10345 (buffer-substring
10346 (match-beginning 3) (goto-char (point-at-eol)))))
10347 (substring (org-match-string-no-properties 3) 1 -1)))
10348 (unless key
10349 (if (= (char-after (match-beginning 3)) ?\[)
10350 (setq key "TIMESTAMP_IA")
10351 (setq key "TIMESTAMP")))
10352 (when (or (equal key clockstr) (not (assoc key props)))
10353 (push (cons key string) props)))
10357 (when (memq which '(all standard))
10358 ;; Get the standard properties, like :PORP: ...
10359 (setq range (org-get-property-block beg end))
10360 (when range
10361 (goto-char (car range))
10362 (while (re-search-forward
10363 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
10364 (cdr range) t)
10365 (setq key (org-match-string-no-properties 1)
10366 value (org-trim (or (org-match-string-no-properties 2) "")))
10367 (unless (member key excluded)
10368 (push (cons key (or value "")) props)))))
10369 (if clocksum
10370 (push (cons "CLOCKSUM"
10371 (org-columns-number-to-string (/ (float clocksum) 60.)
10372 'add_times))
10373 props))
10374 (unless (assoc "CATEGORY" props)
10375 (setq value (or (org-get-category)
10376 (progn (org-refresh-category-properties)
10377 (org-get-category))))
10378 (push (cons "CATEGORY" value) props))
10379 (append sum-props (nreverse props)))))))
10381 (defun org-entry-get (pom property &optional inherit)
10382 "Get value of PROPERTY for entry at point-or-marker POM.
10383 If INHERIT is non-nil and the entry does not have the property,
10384 then also check higher levels of the hierarchy.
10385 If INHERIT is the symbol `selective', use inheritance only if the setting
10386 in `org-use-property-inheritance' selects PROPERTY for inheritance.
10387 If the property is present but empty, the return value is the empty string.
10388 If the property is not present at all, nil is returned."
10389 (org-with-point-at pom
10390 (if (and inherit (if (eq inherit 'selective)
10391 (org-property-inherit-p property)
10393 (org-entry-get-with-inheritance property)
10394 (if (member property org-special-properties)
10395 ;; We need a special property. Use brute force, get all properties.
10396 (cdr (assoc property (org-entry-properties nil 'special)))
10397 (let ((range (org-get-property-block)))
10398 (if (and range
10399 (goto-char (car range))
10400 (re-search-forward
10401 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
10402 (cdr range) t))
10403 ;; Found the property, return it.
10404 (if (match-end 1)
10405 (org-match-string-no-properties 1)
10406 "")))))))
10408 (defun org-property-or-variable-value (var &optional inherit)
10409 "Check if there is a property fixing the value of VAR.
10410 If yes, return this value. If not, return the current value of the variable."
10411 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
10412 (if (and prop (stringp prop) (string-match "\\S-" prop))
10413 (read prop)
10414 (symbol-value var))))
10416 (defun org-entry-delete (pom property)
10417 "Delete the property PROPERTY from entry at point-or-marker POM."
10418 (org-with-point-at pom
10419 (if (member property org-special-properties)
10420 nil ; cannot delete these properties.
10421 (let ((range (org-get-property-block)))
10422 (if (and range
10423 (goto-char (car range))
10424 (re-search-forward
10425 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
10426 (cdr range) t))
10427 (progn
10428 (delete-region (match-beginning 0) (1+ (point-at-eol)))
10430 nil)))))
10432 ;; Multi-values properties are properties that contain multiple values
10433 ;; These values are assumed to be single words, separated by whitespace.
10434 (defun org-entry-add-to-multivalued-property (pom property value)
10435 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
10436 (let* ((old (org-entry-get pom property))
10437 (values (and old (org-split-string old "[ \t]"))))
10438 (setq value (org-entry-protect-space value))
10439 (unless (member value values)
10440 (setq values (cons value values))
10441 (org-entry-put pom property
10442 (mapconcat 'identity values " ")))))
10444 (defun org-entry-remove-from-multivalued-property (pom property value)
10445 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
10446 (let* ((old (org-entry-get pom property))
10447 (values (and old (org-split-string old "[ \t]"))))
10448 (setq value (org-entry-protect-space value))
10449 (when (member value values)
10450 (setq values (delete value values))
10451 (org-entry-put pom property
10452 (mapconcat 'identity values " ")))))
10454 (defun org-entry-member-in-multivalued-property (pom property value)
10455 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
10456 (let* ((old (org-entry-get pom property))
10457 (values (and old (org-split-string old "[ \t]"))))
10458 (setq value (org-entry-protect-space value))
10459 (member value values)))
10461 (defun org-entry-get-multivalued-property (pom property)
10462 "Return a list of values in a multivalued property."
10463 (let* ((value (org-entry-get pom property))
10464 (values (and value (org-split-string value "[ \t]"))))
10465 (mapcar 'org-entry-restore-space values)))
10467 (defun org-entry-put-multivalued-property (pom property &rest values)
10468 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
10469 VALUES should be a list of strings. Spaces will be protected."
10470 (org-entry-put pom property
10471 (mapconcat 'org-entry-protect-space values " "))
10472 (let* ((value (org-entry-get pom property))
10473 (values (and value (org-split-string value "[ \t]"))))
10474 (mapcar 'org-entry-restore-space values)))
10476 (defun org-entry-protect-space (s)
10477 "Protect spaces and newline in string S."
10478 (while (string-match " " s)
10479 (setq s (replace-match "%20" t t s)))
10480 (while (string-match "\n" s)
10481 (setq s (replace-match "%0A" t t s)))
10484 (defun org-entry-restore-space (s)
10485 "Restore spaces and newline in string S."
10486 (while (string-match "%20" s)
10487 (setq s (replace-match " " t t s)))
10488 (while (string-match "%0A" s)
10489 (setq s (replace-match "\n" t t s)))
10492 (defvar org-entry-property-inherited-from (make-marker)
10493 "Marker pointing to the entry from where a property was inherited.
10494 Each call to `org-entry-get-with-inheritance' will set this marker to the
10495 location of the entry where the inheritance search matched. If there was
10496 no match, the marker will point nowhere.
10497 Note that also `org-entry-get' calls this function, if the INHERIT flag
10498 is set.")
10500 (defun org-entry-get-with-inheritance (property)
10501 "Get entry property, and search higher levels if not present."
10502 (move-marker org-entry-property-inherited-from nil)
10503 (let (tmp)
10504 (save-excursion
10505 (save-restriction
10506 (widen)
10507 (catch 'ex
10508 (while t
10509 (when (setq tmp (org-entry-get nil property))
10510 (org-back-to-heading t)
10511 (move-marker org-entry-property-inherited-from (point))
10512 (throw 'ex tmp))
10513 (or (org-up-heading-safe) (throw 'ex nil)))))
10514 (or tmp
10515 (cdr (assoc property org-file-properties))
10516 (cdr (assoc property org-global-properties))
10517 (cdr (assoc property org-global-properties-fixed))))))
10519 (defun org-entry-put (pom property value)
10520 "Set PROPERTY to VALUE for entry at point-or-marker POM."
10521 (org-with-point-at pom
10522 (org-back-to-heading t)
10523 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
10524 range)
10525 (cond
10526 ((equal property "TODO")
10527 (when (and (stringp value) (string-match "\\S-" value)
10528 (not (member value org-todo-keywords-1)))
10529 (error "\"%s\" is not a valid TODO state" value))
10530 (if (or (not value)
10531 (not (string-match "\\S-" value)))
10532 (setq value 'none))
10533 (org-todo value)
10534 (org-set-tags nil 'align))
10535 ((equal property "PRIORITY")
10536 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
10537 (string-to-char value) ?\ ))
10538 (org-set-tags nil 'align))
10539 ((equal property "SCHEDULED")
10540 (if (re-search-forward org-scheduled-time-regexp end t)
10541 (cond
10542 ((eq value 'earlier) (org-timestamp-change -1 'day))
10543 ((eq value 'later) (org-timestamp-change 1 'day))
10544 (t (call-interactively 'org-schedule)))
10545 (call-interactively 'org-schedule)))
10546 ((equal property "DEADLINE")
10547 (if (re-search-forward org-deadline-time-regexp end t)
10548 (cond
10549 ((eq value 'earlier) (org-timestamp-change -1 'day))
10550 ((eq value 'later) (org-timestamp-change 1 'day))
10551 (t (call-interactively 'org-deadline)))
10552 (call-interactively 'org-deadline)))
10553 ((member property org-special-properties)
10554 (error "The %s property can not yet be set with `org-entry-put'"
10555 property))
10556 (t ; a non-special property
10557 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
10558 (setq range (org-get-property-block beg end 'force))
10559 (goto-char (car range))
10560 (if (re-search-forward
10561 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
10562 (progn
10563 (delete-region (match-beginning 1) (match-end 1))
10564 (goto-char (match-beginning 1)))
10565 (goto-char (cdr range))
10566 (insert "\n")
10567 (backward-char 1)
10568 (org-indent-line-function)
10569 (insert ":" property ":"))
10570 (and value (insert " " value))
10571 (org-indent-line-function)))))))
10573 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
10574 "Get all property keys in the current buffer.
10575 With INCLUDE-SPECIALS, also list the special properties that reflect things
10576 like tags and TODO state.
10577 With INCLUDE-DEFAULTS, also include properties that has special meaning
10578 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
10579 With INCLUDE-COLUMNS, also include property names given in COLUMN
10580 formats in the current buffer."
10581 (let (rtn range cfmt cols s p)
10582 (save-excursion
10583 (save-restriction
10584 (widen)
10585 (goto-char (point-min))
10586 (while (re-search-forward org-property-start-re nil t)
10587 (setq range (org-get-property-block))
10588 (goto-char (car range))
10589 (while (re-search-forward
10590 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
10591 (cdr range) t)
10592 (add-to-list 'rtn (org-match-string-no-properties 1)))
10593 (outline-next-heading))))
10595 (when include-specials
10596 (setq rtn (append org-special-properties rtn)))
10598 (when include-defaults
10599 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
10601 (when include-columns
10602 (save-excursion
10603 (save-restriction
10604 (widen)
10605 (goto-char (point-min))
10606 (while (re-search-forward
10607 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
10608 nil t)
10609 (setq cfmt (match-string 2) s 0)
10610 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
10611 cfmt s)
10612 (setq s (match-end 0)
10613 p (match-string 1 cfmt))
10614 (unless (or (equal p "ITEM")
10615 (member p org-special-properties))
10616 (add-to-list 'rtn (match-string 1 cfmt))))))))
10618 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
10620 (defun org-property-values (key)
10621 "Return a list of all values of property KEY."
10622 (save-excursion
10623 (save-restriction
10624 (widen)
10625 (goto-char (point-min))
10626 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
10627 values)
10628 (while (re-search-forward re nil t)
10629 (add-to-list 'values (org-trim (match-string 1))))
10630 (delete "" values)))))
10632 (defun org-insert-property-drawer ()
10633 "Insert a property drawer into the current entry."
10634 (interactive)
10635 (org-back-to-heading t)
10636 (looking-at outline-regexp)
10637 (let ((indent (- (match-end 0)(match-beginning 0)))
10638 (beg (point))
10639 (re (concat "^[ \t]*" org-keyword-time-regexp))
10640 end hiddenp)
10641 (outline-next-heading)
10642 (setq end (point))
10643 (goto-char beg)
10644 (while (re-search-forward re end t))
10645 (setq hiddenp (org-invisible-p))
10646 (end-of-line 1)
10647 (and (equal (char-after) ?\n) (forward-char 1))
10648 (while (looking-at "^[ \t]*\\(:CLOCK:\\|CLOCK\\|:END:\\)")
10649 (beginning-of-line 2))
10650 (org-skip-over-state-notes)
10651 (skip-chars-backward " \t\n\r")
10652 (if (eq (char-before) ?*) (forward-char 1))
10653 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
10654 (beginning-of-line 0)
10655 (org-indent-to-column indent)
10656 (beginning-of-line 2)
10657 (org-indent-to-column indent)
10658 (beginning-of-line 0)
10659 (if hiddenp
10660 (save-excursion
10661 (org-back-to-heading t)
10662 (hide-entry))
10663 (org-flag-drawer t))))
10665 (defun org-set-property (property value)
10666 "In the current entry, set PROPERTY to VALUE.
10667 When called interactively, this will prompt for a property name, offering
10668 completion on existing and default properties. And then it will prompt
10669 for a value, offering completion either on allowed values (via an inherited
10670 xxx_ALL property) or on existing values in other instances of this property
10671 in the current file."
10672 (interactive
10673 (let* ((completion-ignore-case t)
10674 (keys (org-buffer-property-keys nil t t))
10675 (prop0 (org-ido-completing-read "Property: " (mapcar 'list keys)))
10676 (prop (if (member prop0 keys)
10677 prop0
10678 (or (cdr (assoc (downcase prop0)
10679 (mapcar (lambda (x) (cons (downcase x) x))
10680 keys)))
10681 prop0)))
10682 (cur (org-entry-get nil prop))
10683 (allowed (org-property-get-allowed-values nil prop 'table))
10684 (existing (mapcar 'list (org-property-values prop)))
10685 (val (if allowed
10686 (org-completing-read "Value: " allowed nil 'req-match)
10687 (org-completing-read
10688 (concat "Value" (if (and cur (string-match "\\S-" cur))
10689 (concat "[" cur "]") "")
10690 ": ")
10691 existing nil nil "" nil cur))))
10692 (list prop (if (equal val "") cur val))))
10693 (unless (equal (org-entry-get nil property) value)
10694 (org-entry-put nil property value)))
10696 (defun org-delete-property (property)
10697 "In the current entry, delete PROPERTY."
10698 (interactive
10699 (let* ((completion-ignore-case t)
10700 (prop (org-ido-completing-read
10701 "Property: " (org-entry-properties nil 'standard))))
10702 (list prop)))
10703 (message "Property %s %s" property
10704 (if (org-entry-delete nil property)
10705 "deleted"
10706 "was not present in the entry")))
10708 (defun org-delete-property-globally (property)
10709 "Remove PROPERTY globally, from all entries."
10710 (interactive
10711 (let* ((completion-ignore-case t)
10712 (prop (org-ido-completing-read
10713 "Globally remove property: "
10714 (mapcar 'list (org-buffer-property-keys)))))
10715 (list prop)))
10716 (save-excursion
10717 (save-restriction
10718 (widen)
10719 (goto-char (point-min))
10720 (let ((cnt 0))
10721 (while (re-search-forward
10722 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
10723 nil t)
10724 (setq cnt (1+ cnt))
10725 (replace-match ""))
10726 (message "Property \"%s\" removed from %d entries" property cnt)))))
10728 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
10730 (defun org-compute-property-at-point ()
10731 "Compute the property at point.
10732 This looks for an enclosing column format, extracts the operator and
10733 then applies it to the property in the column format's scope."
10734 (interactive)
10735 (unless (org-at-property-p)
10736 (error "Not at a property"))
10737 (let ((prop (org-match-string-no-properties 2)))
10738 (org-columns-get-format-and-top-level)
10739 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
10740 (error "No operator defined for property %s" prop))
10741 (org-columns-compute prop)))
10743 (defun org-property-get-allowed-values (pom property &optional table)
10744 "Get allowed values for the property PROPERTY.
10745 When TABLE is non-nil, return an alist that can directly be used for
10746 completion."
10747 (let (vals)
10748 (cond
10749 ((equal property "TODO")
10750 (setq vals (org-with-point-at pom
10751 (append org-todo-keywords-1 '("")))))
10752 ((equal property "PRIORITY")
10753 (let ((n org-lowest-priority))
10754 (while (>= n org-highest-priority)
10755 (push (char-to-string n) vals)
10756 (setq n (1- n)))))
10757 ((member property org-special-properties))
10759 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
10761 (when (and vals (string-match "\\S-" vals))
10762 (setq vals (car (read-from-string (concat "(" vals ")"))))
10763 (setq vals (mapcar (lambda (x)
10764 (cond ((stringp x) x)
10765 ((numberp x) (number-to-string x))
10766 ((symbolp x) (symbol-name x))
10767 (t "???")))
10768 vals)))))
10769 (if table (mapcar 'list vals) vals)))
10771 (defun org-property-previous-allowed-value (&optional previous)
10772 "Switch to the next allowed value for this property."
10773 (interactive)
10774 (org-property-next-allowed-value t))
10776 (defun org-property-next-allowed-value (&optional previous)
10777 "Switch to the next allowed value for this property."
10778 (interactive)
10779 (unless (org-at-property-p)
10780 (error "Not at a property"))
10781 (let* ((key (match-string 2))
10782 (value (match-string 3))
10783 (allowed (or (org-property-get-allowed-values (point) key)
10784 (and (member value '("[ ]" "[-]" "[X]"))
10785 '("[ ]" "[X]"))))
10786 nval)
10787 (unless allowed
10788 (error "Allowed values for this property have not been defined"))
10789 (if previous (setq allowed (reverse allowed)))
10790 (if (member value allowed)
10791 (setq nval (car (cdr (member value allowed)))))
10792 (setq nval (or nval (car allowed)))
10793 (if (equal nval value)
10794 (error "Only one allowed value for this property"))
10795 (org-at-property-p)
10796 (replace-match (concat " :" key ": " nval) t t)
10797 (org-indent-line-function)
10798 (beginning-of-line 1)
10799 (skip-chars-forward " \t")))
10801 (defun org-find-entry-with-id (ident)
10802 "Locate the entry that contains the ID property with exact value IDENT.
10803 IDENT can be a string, a symbol or a number, this function will search for
10804 the string representation of it.
10805 Return the position where this entry starts, or nil if there is no such entry."
10806 (interactive "sID: ")
10807 (let ((id (cond
10808 ((stringp ident) ident)
10809 ((symbol-name ident) (symbol-name ident))
10810 ((numberp ident) (number-to-string ident))
10811 (t (error "IDENT %s must be a string, symbol or number" ident))))
10812 (case-fold-search nil))
10813 (save-excursion
10814 (save-restriction
10815 (widen)
10816 (goto-char (point-min))
10817 (when (re-search-forward
10818 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
10819 nil t)
10820 (org-back-to-heading)
10821 (point))))))
10823 ;;;; Timestamps
10825 (defvar org-last-changed-timestamp nil)
10826 (defvar org-last-inserted-timestamp nil
10827 "The last time stamp inserted with `org-insert-time-stamp'.")
10828 (defvar org-time-was-given) ; dynamically scoped parameter
10829 (defvar org-end-time-was-given) ; dynamically scoped parameter
10830 (defvar org-ts-what) ; dynamically scoped parameter
10832 (defun org-time-stamp (arg &optional inactive)
10833 "Prompt for a date/time and insert a time stamp.
10834 If the user specifies a time like HH:MM, or if this command is called
10835 with a prefix argument, the time stamp will contain date and time.
10836 Otherwise, only the date will be included. All parts of a date not
10837 specified by the user will be filled in from the current date/time.
10838 So if you press just return without typing anything, the time stamp
10839 will represent the current date/time. If there is already a timestamp
10840 at the cursor, it will be modified."
10841 (interactive "P")
10842 (let* ((ts nil)
10843 (default-time
10844 ;; Default time is either today, or, when entering a range,
10845 ;; the range start.
10846 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
10847 (save-excursion
10848 (re-search-backward
10849 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
10850 (- (point) 20) t)))
10851 (apply 'encode-time (org-parse-time-string (match-string 1)))
10852 (current-time)))
10853 (default-input (and ts (org-get-compact-tod ts)))
10854 org-time-was-given org-end-time-was-given time)
10855 (cond
10856 ((and (org-at-timestamp-p t)
10857 (memq last-command '(org-time-stamp org-time-stamp-inactive))
10858 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
10859 (insert "--")
10860 (setq time (let ((this-command this-command))
10861 (org-read-date arg 'totime nil nil
10862 default-time default-input)))
10863 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
10864 ((org-at-timestamp-p t)
10865 (setq time (let ((this-command this-command))
10866 (org-read-date arg 'totime nil nil default-time default-input)))
10867 (when (org-at-timestamp-p t) ; just to get the match data
10868 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
10869 (replace-match "")
10870 (setq org-last-changed-timestamp
10871 (org-insert-time-stamp
10872 time (or org-time-was-given arg)
10873 inactive nil nil (list org-end-time-was-given))))
10874 (message "Timestamp updated"))
10876 (setq time (let ((this-command this-command))
10877 (org-read-date arg 'totime nil nil default-time default-input)))
10878 (org-insert-time-stamp time (or org-time-was-given arg) inactive
10879 nil nil (list org-end-time-was-given))))))
10881 ;; FIXME: can we use this for something else, like computing time differences?
10882 (defun org-get-compact-tod (s)
10883 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
10884 (let* ((t1 (match-string 1 s))
10885 (h1 (string-to-number (match-string 2 s)))
10886 (m1 (string-to-number (match-string 3 s)))
10887 (t2 (and (match-end 4) (match-string 5 s)))
10888 (h2 (and t2 (string-to-number (match-string 6 s))))
10889 (m2 (and t2 (string-to-number (match-string 7 s))))
10890 dh dm)
10891 (if (not t2)
10893 (setq dh (- h2 h1) dm (- m2 m1))
10894 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
10895 (concat t1 "+" (number-to-string dh)
10896 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
10898 (defun org-time-stamp-inactive (&optional arg)
10899 "Insert an inactive time stamp.
10900 An inactive time stamp is enclosed in square brackets instead of angle
10901 brackets. It is inactive in the sense that it does not trigger agenda entries,
10902 does not link to the calendar and cannot be changed with the S-cursor keys.
10903 So these are more for recording a certain time/date."
10904 (interactive "P")
10905 (org-time-stamp arg 'inactive))
10907 (defvar org-date-ovl (org-make-overlay 1 1))
10908 (org-overlay-put org-date-ovl 'face 'org-warning)
10909 (org-detach-overlay org-date-ovl)
10911 (defvar org-ans1) ; dynamically scoped parameter
10912 (defvar org-ans2) ; dynamically scoped parameter
10914 (defvar org-plain-time-of-day-regexp) ; defined below
10916 (defvar org-overriding-default-time nil) ; dynamically scoped
10917 (defvar org-read-date-overlay nil)
10918 (defvar org-dcst nil) ; dynamically scoped
10920 (defun org-read-date (&optional with-time to-time from-string prompt
10921 default-time default-input)
10922 "Read a date, possibly a time, and make things smooth for the user.
10923 The prompt will suggest to enter an ISO date, but you can also enter anything
10924 which will at least partially be understood by `parse-time-string'.
10925 Unrecognized parts of the date will default to the current day, month, year,
10926 hour and minute. If this command is called to replace a timestamp at point,
10927 of to enter the second timestamp of a range, the default time is taken from the
10928 existing stamp. For example,
10929 3-2-5 --> 2003-02-05
10930 feb 15 --> currentyear-02-15
10931 sep 12 9 --> 2009-09-12
10932 12:45 --> today 12:45
10933 22 sept 0:34 --> currentyear-09-22 0:34
10934 12 --> currentyear-currentmonth-12
10935 Fri --> nearest Friday (today or later)
10936 etc.
10938 Furthermore you can specify a relative date by giving, as the *first* thing
10939 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
10940 change in days weeks, months, years.
10941 With a single plus or minus, the date is relative to today. With a double
10942 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
10943 +4d --> four days from today
10944 +4 --> same as above
10945 +2w --> two weeks from today
10946 ++5 --> five days from default date
10948 The function understands only English month and weekday abbreviations,
10949 but this can be configured with the variables `parse-time-months' and
10950 `parse-time-weekdays'.
10952 While prompting, a calendar is popped up - you can also select the
10953 date with the mouse (button 1). The calendar shows a period of three
10954 months. To scroll it to other months, use the keys `>' and `<'.
10955 If you don't like the calendar, turn it off with
10956 \(setq org-read-date-popup-calendar nil)
10958 With optional argument TO-TIME, the date will immediately be converted
10959 to an internal time.
10960 With an optional argument WITH-TIME, the prompt will suggest to also
10961 insert a time. Note that when WITH-TIME is not set, you can still
10962 enter a time, and this function will inform the calling routine about
10963 this change. The calling routine may then choose to change the format
10964 used to insert the time stamp into the buffer to include the time.
10965 With optional argument FROM-STRING, read from this string instead from
10966 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
10967 the time/date that is used for everything that is not specified by the
10968 user."
10969 (require 'parse-time)
10970 (let* ((org-time-stamp-rounding-minutes
10971 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
10972 (org-dcst org-display-custom-times)
10973 (ct (org-current-time))
10974 (def (or org-overriding-default-time default-time ct))
10975 (defdecode (decode-time def))
10976 (dummy (progn
10977 (when (< (nth 2 defdecode) org-extend-today-until)
10978 (setcar (nthcdr 2 defdecode) -1)
10979 (setcar (nthcdr 1 defdecode) 59)
10980 (setq def (apply 'encode-time defdecode)
10981 defdecode (decode-time def)))))
10982 (calendar-move-hook nil)
10983 (calendar-view-diary-initially-flag nil)
10984 (view-diary-entries-initially nil)
10985 (calendar-view-holidays-initially-flag nil)
10986 (view-calendar-holidays-initially nil)
10987 (timestr (format-time-string
10988 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
10989 (prompt (concat (if prompt (concat prompt " ") "")
10990 (format "Date+time [%s]: " timestr)))
10991 ans (org-ans0 "") org-ans1 org-ans2 final)
10993 (cond
10994 (from-string (setq ans from-string))
10995 (org-read-date-popup-calendar
10996 (save-excursion
10997 (save-window-excursion
10998 (calendar)
10999 (calendar-forward-day (- (time-to-days def)
11000 (calendar-absolute-from-gregorian
11001 (calendar-current-date))))
11002 (org-eval-in-calendar nil t)
11003 (let* ((old-map (current-local-map))
11004 (map (copy-keymap calendar-mode-map))
11005 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
11006 (org-defkey map (kbd "RET") 'org-calendar-select)
11007 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
11008 'org-calendar-select-mouse)
11009 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
11010 'org-calendar-select-mouse)
11011 (org-defkey minibuffer-local-map [(meta shift left)]
11012 (lambda () (interactive)
11013 (org-eval-in-calendar '(calendar-backward-month 1))))
11014 (org-defkey minibuffer-local-map [(meta shift right)]
11015 (lambda () (interactive)
11016 (org-eval-in-calendar '(calendar-forward-month 1))))
11017 (org-defkey minibuffer-local-map [(meta shift up)]
11018 (lambda () (interactive)
11019 (org-eval-in-calendar '(calendar-backward-year 1))))
11020 (org-defkey minibuffer-local-map [(meta shift down)]
11021 (lambda () (interactive)
11022 (org-eval-in-calendar '(calendar-forward-year 1))))
11023 (org-defkey minibuffer-local-map [(shift up)]
11024 (lambda () (interactive)
11025 (org-eval-in-calendar '(calendar-backward-week 1))))
11026 (org-defkey minibuffer-local-map [(shift down)]
11027 (lambda () (interactive)
11028 (org-eval-in-calendar '(calendar-forward-week 1))))
11029 (org-defkey minibuffer-local-map [(shift left)]
11030 (lambda () (interactive)
11031 (org-eval-in-calendar '(calendar-backward-day 1))))
11032 (org-defkey minibuffer-local-map [(shift right)]
11033 (lambda () (interactive)
11034 (org-eval-in-calendar '(calendar-forward-day 1))))
11035 (org-defkey minibuffer-local-map ">"
11036 (lambda () (interactive)
11037 (org-eval-in-calendar '(scroll-calendar-left 1))))
11038 (org-defkey minibuffer-local-map "<"
11039 (lambda () (interactive)
11040 (org-eval-in-calendar '(scroll-calendar-right 1))))
11041 (unwind-protect
11042 (progn
11043 (use-local-map map)
11044 (add-hook 'post-command-hook 'org-read-date-display)
11045 (setq org-ans0 (read-string prompt default-input nil nil))
11046 ;; org-ans0: from prompt
11047 ;; org-ans1: from mouse click
11048 ;; org-ans2: from calendar motion
11049 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
11050 (remove-hook 'post-command-hook 'org-read-date-display)
11051 (use-local-map old-map)
11052 (when org-read-date-overlay
11053 (org-delete-overlay org-read-date-overlay)
11054 (setq org-read-date-overlay nil)))))))
11056 (t ; Naked prompt only
11057 (unwind-protect
11058 (setq ans (read-string prompt default-input nil timestr))
11059 (when org-read-date-overlay
11060 (org-delete-overlay org-read-date-overlay)
11061 (setq org-read-date-overlay nil)))))
11063 (setq final (org-read-date-analyze ans def defdecode))
11065 (if to-time
11066 (apply 'encode-time final)
11067 (if (and (boundp 'org-time-was-given) org-time-was-given)
11068 (format "%04d-%02d-%02d %02d:%02d"
11069 (nth 5 final) (nth 4 final) (nth 3 final)
11070 (nth 2 final) (nth 1 final))
11071 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
11072 (defvar def)
11073 (defvar defdecode)
11074 (defvar with-time)
11075 (defun org-read-date-display ()
11076 "Display the current date prompt interpretation in the minibuffer."
11077 (when org-read-date-display-live
11078 (when org-read-date-overlay
11079 (org-delete-overlay org-read-date-overlay))
11080 (let ((p (point)))
11081 (end-of-line 1)
11082 (while (not (equal (buffer-substring
11083 (max (point-min) (- (point) 4)) (point))
11084 " "))
11085 (insert " "))
11086 (goto-char p))
11087 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
11088 " " (or org-ans1 org-ans2)))
11089 (org-end-time-was-given nil)
11090 (f (org-read-date-analyze ans def defdecode))
11091 (fmts (if org-dcst
11092 org-time-stamp-custom-formats
11093 org-time-stamp-formats))
11094 (fmt (if (or with-time
11095 (and (boundp 'org-time-was-given) org-time-was-given))
11096 (cdr fmts)
11097 (car fmts)))
11098 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
11099 (when (and org-end-time-was-given
11100 (string-match org-plain-time-of-day-regexp txt))
11101 (setq txt (concat (substring txt 0 (match-end 0)) "-"
11102 org-end-time-was-given
11103 (substring txt (match-end 0)))))
11104 (setq org-read-date-overlay
11105 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
11106 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
11108 (defun org-read-date-analyze (ans def defdecode)
11109 "Analyse the combined answer of the date prompt."
11110 ;; FIXME: cleanup and comment
11111 (let (delta deltan deltaw deltadef year month day
11112 hour minute second wday pm h2 m2 tl wday1
11113 iso-year iso-weekday iso-week iso-year iso-date)
11115 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
11116 (setq ans "+0"))
11118 (when (setq delta (org-read-date-get-relative ans (current-time) def))
11119 (setq ans (replace-match "" t t ans)
11120 deltan (car delta)
11121 deltaw (nth 1 delta)
11122 deltadef (nth 2 delta)))
11124 ;; Check if there is an iso week date in there
11125 ;; If yes, sore the info and postpone interpreting it until the rest
11126 ;; of the parsing is done
11127 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
11128 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
11129 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
11130 iso-week (string-to-number (match-string 2 ans)))
11131 (setq ans (replace-match "" t t ans)))
11133 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
11134 (when (string-match
11135 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
11136 (setq year (if (match-end 2)
11137 (string-to-number (match-string 2 ans))
11138 (string-to-number (format-time-string "%Y")))
11139 month (string-to-number (match-string 3 ans))
11140 day (string-to-number (match-string 4 ans)))
11141 (if (< year 100) (setq year (+ 2000 year)))
11142 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
11143 t nil ans)))
11144 ;; Help matching am/pm times, because `parse-time-string' does not do that.
11145 ;; If there is a time with am/pm, and *no* time without it, we convert
11146 ;; so that matching will be successful.
11147 (loop for i from 1 to 2 do ; twice, for end time as well
11148 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
11149 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
11150 (setq hour (string-to-number (match-string 1 ans))
11151 minute (if (match-end 3)
11152 (string-to-number (match-string 3 ans))
11154 pm (equal ?p
11155 (string-to-char (downcase (match-string 4 ans)))))
11156 (if (and (= hour 12) (not pm))
11157 (setq hour 0)
11158 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
11159 (setq ans (replace-match (format "%02d:%02d" hour minute)
11160 t t ans))))
11162 ;; Check if a time range is given as a duration
11163 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
11164 (setq hour (string-to-number (match-string 1 ans))
11165 h2 (+ hour (string-to-number (match-string 3 ans)))
11166 minute (string-to-number (match-string 2 ans))
11167 m2 (+ minute (if (match-end 5) (string-to-number
11168 (match-string 5 ans))0)))
11169 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
11170 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
11171 t t ans)))
11173 ;; Check if there is a time range
11174 (when (boundp 'org-end-time-was-given)
11175 (setq org-time-was-given nil)
11176 (when (and (string-match org-plain-time-of-day-regexp ans)
11177 (match-end 8))
11178 (setq org-end-time-was-given (match-string 8 ans))
11179 (setq ans (concat (substring ans 0 (match-beginning 7))
11180 (substring ans (match-end 7))))))
11182 (setq tl (parse-time-string ans)
11183 day (or (nth 3 tl) (nth 3 defdecode))
11184 month (or (nth 4 tl)
11185 (if (and org-read-date-prefer-future
11186 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
11187 (1+ (nth 4 defdecode))
11188 (nth 4 defdecode)))
11189 year (or (nth 5 tl)
11190 (if (and org-read-date-prefer-future
11191 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
11192 (1+ (nth 5 defdecode))
11193 (nth 5 defdecode)))
11194 hour (or (nth 2 tl) (nth 2 defdecode))
11195 minute (or (nth 1 tl) (nth 1 defdecode))
11196 second (or (nth 0 tl) 0)
11197 wday (nth 6 tl))
11199 ;; Special date definitions below
11200 (cond
11201 (iso-week
11202 ;; There was an iso week
11203 (setq year (or iso-year year)
11204 day (or iso-weekday wday 1)
11205 wday nil ; to make sure that the trigger below does not match
11206 iso-date (calendar-gregorian-from-absolute
11207 (calendar-absolute-from-iso
11208 (list iso-week day year))))
11209 ; FIXME: Should we also push ISO weeks into the future?
11210 ; (when (and org-read-date-prefer-future
11211 ; (not iso-year)
11212 ; (< (calendar-absolute-from-gregorian iso-date)
11213 ; (time-to-days (current-time))))
11214 ; (setq year (1+ year)
11215 ; iso-date (calendar-gregorian-from-absolute
11216 ; (calendar-absolute-from-iso
11217 ; (list iso-week day year)))))
11218 (setq month (car iso-date)
11219 year (nth 2 iso-date)
11220 day (nth 1 iso-date)))
11221 (deltan
11222 (unless deltadef
11223 (let ((now (decode-time (current-time))))
11224 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
11225 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
11226 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
11227 ((equal deltaw "m") (setq month (+ month deltan)))
11228 ((equal deltaw "y") (setq year (+ year deltan)))))
11229 ((and wday (not (nth 3 tl)))
11230 ;; Weekday was given, but no day, so pick that day in the week
11231 ;; on or after the derived date.
11232 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
11233 (unless (equal wday wday1)
11234 (setq day (+ day (% (- wday wday1 -7) 7))))))
11235 (if (and (boundp 'org-time-was-given)
11236 (nth 2 tl))
11237 (setq org-time-was-given t))
11238 (if (< year 100) (setq year (+ 2000 year)))
11239 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
11240 (list second minute hour day month year)))
11242 (defvar parse-time-weekdays)
11244 (defun org-read-date-get-relative (s today default)
11245 "Check string S for special relative date string.
11246 TODAY and DEFAULT are internal times, for today and for a default.
11247 Return shift list (N what def-flag)
11248 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
11249 N is the number of WHATs to shift.
11250 DEF-FLAG is t when a double ++ or -- indicates shift relative to
11251 the DEFAULT date rather than TODAY."
11252 (when (and
11253 (string-match
11254 (concat
11255 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
11256 "\\([0-9]+\\)?"
11257 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
11258 "\\([ \t]\\|$\\)") s)
11259 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
11260 (let* ((dir (if (> (match-end 1) (match-beginning 1))
11261 (string-to-char (substring (match-string 1 s) -1))
11262 ?+))
11263 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
11264 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
11265 (what (if (match-end 3) (match-string 3 s) "d"))
11266 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
11267 (date (if rel default today))
11268 (wday (nth 6 (decode-time date)))
11269 delta)
11270 (if wday1
11271 (progn
11272 (setq delta (mod (+ 7 (- wday1 wday)) 7))
11273 (if (= dir ?-) (setq delta (- delta 7)))
11274 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
11275 (list delta "d" rel))
11276 (list (* n (if (= dir ?-) -1 1)) what rel)))))
11278 (defun org-eval-in-calendar (form &optional keepdate)
11279 "Eval FORM in the calendar window and return to current window.
11280 Also, store the cursor date in variable org-ans2."
11281 (let ((sw (selected-window)))
11282 (select-window (get-buffer-window "*Calendar*"))
11283 (eval form)
11284 (when (and (not keepdate) (calendar-cursor-to-date))
11285 (let* ((date (calendar-cursor-to-date))
11286 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11287 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
11288 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
11289 (select-window sw)))
11291 (defun org-calendar-select ()
11292 "Return to `org-read-date' with the date currently selected.
11293 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11294 (interactive)
11295 (when (calendar-cursor-to-date)
11296 (let* ((date (calendar-cursor-to-date))
11297 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11298 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11299 (if (active-minibuffer-window) (exit-minibuffer))))
11301 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
11302 "Insert a date stamp for the date given by the internal TIME.
11303 WITH-HM means, use the stamp format that includes the time of the day.
11304 INACTIVE means use square brackets instead of angular ones, so that the
11305 stamp will not contribute to the agenda.
11306 PRE and POST are optional strings to be inserted before and after the
11307 stamp.
11308 The command returns the inserted time stamp."
11309 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
11310 stamp)
11311 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
11312 (insert-before-markers (or pre ""))
11313 (insert-before-markers (setq stamp (format-time-string fmt time)))
11314 (when (listp extra)
11315 (setq extra (car extra))
11316 (if (and (stringp extra)
11317 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
11318 (setq extra (format "-%02d:%02d"
11319 (string-to-number (match-string 1 extra))
11320 (string-to-number (match-string 2 extra))))
11321 (setq extra nil)))
11322 (when extra
11323 (backward-char 1)
11324 (insert-before-markers extra)
11325 (forward-char 1))
11326 (insert-before-markers (or post ""))
11327 (setq org-last-inserted-timestamp stamp)))
11329 (defun org-toggle-time-stamp-overlays ()
11330 "Toggle the use of custom time stamp formats."
11331 (interactive)
11332 (setq org-display-custom-times (not org-display-custom-times))
11333 (unless org-display-custom-times
11334 (let ((p (point-min)) (bmp (buffer-modified-p)))
11335 (while (setq p (next-single-property-change p 'display))
11336 (if (and (get-text-property p 'display)
11337 (eq (get-text-property p 'face) 'org-date))
11338 (remove-text-properties
11339 p (setq p (next-single-property-change p 'display))
11340 '(display t))))
11341 (set-buffer-modified-p bmp)))
11342 (if (featurep 'xemacs)
11343 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
11344 (org-restart-font-lock)
11345 (setq org-table-may-need-update t)
11346 (if org-display-custom-times
11347 (message "Time stamps are overlayed with custom format")
11348 (message "Time stamp overlays removed")))
11350 (defun org-display-custom-time (beg end)
11351 "Overlay modified time stamp format over timestamp between BEG and END."
11352 (let* ((ts (buffer-substring beg end))
11353 t1 w1 with-hm tf time str w2 (off 0))
11354 (save-match-data
11355 (setq t1 (org-parse-time-string ts t))
11356 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
11357 (setq off (- (match-end 0) (match-beginning 0)))))
11358 (setq end (- end off))
11359 (setq w1 (- end beg)
11360 with-hm (and (nth 1 t1) (nth 2 t1))
11361 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
11362 time (org-fix-decoded-time t1)
11363 str (org-add-props
11364 (format-time-string
11365 (substring tf 1 -1) (apply 'encode-time time))
11366 nil 'mouse-face 'highlight)
11367 w2 (length str))
11368 (if (not (= w2 w1))
11369 (add-text-properties (1+ beg) (+ 2 beg)
11370 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
11371 (if (featurep 'xemacs)
11372 (progn
11373 (put-text-property beg end 'invisible t)
11374 (put-text-property beg end 'end-glyph (make-glyph str)))
11375 (put-text-property beg end 'display str))))
11377 (defun org-translate-time (string)
11378 "Translate all timestamps in STRING to custom format.
11379 But do this only if the variable `org-display-custom-times' is set."
11380 (when org-display-custom-times
11381 (save-match-data
11382 (let* ((start 0)
11383 (re org-ts-regexp-both)
11384 t1 with-hm inactive tf time str beg end)
11385 (while (setq start (string-match re string start))
11386 (setq beg (match-beginning 0)
11387 end (match-end 0)
11388 t1 (save-match-data
11389 (org-parse-time-string (substring string beg end) t))
11390 with-hm (and (nth 1 t1) (nth 2 t1))
11391 inactive (equal (substring string beg (1+ beg)) "[")
11392 tf (funcall (if with-hm 'cdr 'car)
11393 org-time-stamp-custom-formats)
11394 time (org-fix-decoded-time t1)
11395 str (format-time-string
11396 (concat
11397 (if inactive "[" "<") (substring tf 1 -1)
11398 (if inactive "]" ">"))
11399 (apply 'encode-time time))
11400 string (replace-match str t t string)
11401 start (+ start (length str)))))))
11402 string)
11404 (defun org-fix-decoded-time (time)
11405 "Set 0 instead of nil for the first 6 elements of time.
11406 Don't touch the rest."
11407 (let ((n 0))
11408 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
11410 (defun org-days-to-time (timestamp-string)
11411 "Difference between TIMESTAMP-STRING and now in days."
11412 (- (time-to-days (org-time-string-to-time timestamp-string))
11413 (time-to-days (current-time))))
11415 (defun org-deadline-close (timestamp-string &optional ndays)
11416 "Is the time in TIMESTAMP-STRING close to the current date?"
11417 (setq ndays (or ndays (org-get-wdays timestamp-string)))
11418 (and (< (org-days-to-time timestamp-string) ndays)
11419 (not (org-entry-is-done-p))))
11421 (defun org-get-wdays (ts)
11422 "Get the deadline lead time appropriate for timestring TS."
11423 (cond
11424 ((<= org-deadline-warning-days 0)
11425 ;; 0 or negative, enforce this value no matter what
11426 (- org-deadline-warning-days))
11427 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
11428 ;; lead time is specified.
11429 (floor (* (string-to-number (match-string 1 ts))
11430 (cdr (assoc (match-string 2 ts)
11431 '(("d" . 1) ("w" . 7)
11432 ("m" . 30.4) ("y" . 365.25)))))))
11433 ;; go for the default.
11434 (t org-deadline-warning-days)))
11436 (defun org-calendar-select-mouse (ev)
11437 "Return to `org-read-date' with the date currently selected.
11438 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11439 (interactive "e")
11440 (mouse-set-point ev)
11441 (when (calendar-cursor-to-date)
11442 (let* ((date (calendar-cursor-to-date))
11443 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11444 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11445 (if (active-minibuffer-window) (exit-minibuffer))))
11447 (defun org-check-deadlines (ndays)
11448 "Check if there are any deadlines due or past due.
11449 A deadline is considered due if it happens within `org-deadline-warning-days'
11450 days from today's date. If the deadline appears in an entry marked DONE,
11451 it is not shown. The prefix arg NDAYS can be used to test that many
11452 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
11453 (interactive "P")
11454 (let* ((org-warn-days
11455 (cond
11456 ((equal ndays '(4)) 100000)
11457 (ndays (prefix-numeric-value ndays))
11458 (t (abs org-deadline-warning-days))))
11459 (case-fold-search nil)
11460 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
11461 (callback
11462 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
11464 (message "%d deadlines past-due or due within %d days"
11465 (org-occur regexp nil callback)
11466 org-warn-days)))
11468 (defun org-check-before-date (date)
11469 "Check if there are deadlines or scheduled entries before DATE."
11470 (interactive (list (org-read-date)))
11471 (let ((case-fold-search nil)
11472 (regexp (concat "\\<\\(" org-deadline-string
11473 "\\|" org-scheduled-string
11474 "\\) *<\\([^>]+\\)>"))
11475 (callback
11476 (lambda () (time-less-p
11477 (org-time-string-to-time (match-string 2))
11478 (org-time-string-to-time date)))))
11479 (message "%d entries before %s"
11480 (org-occur regexp nil callback) date)))
11482 (defun org-evaluate-time-range (&optional to-buffer)
11483 "Evaluate a time range by computing the difference between start and end.
11484 Normally the result is just printed in the echo area, but with prefix arg
11485 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
11486 If the time range is actually in a table, the result is inserted into the
11487 next column.
11488 For time difference computation, a year is assumed to be exactly 365
11489 days in order to avoid rounding problems."
11490 (interactive "P")
11492 (org-clock-update-time-maybe)
11493 (save-excursion
11494 (unless (org-at-date-range-p t)
11495 (goto-char (point-at-bol))
11496 (re-search-forward org-tr-regexp-both (point-at-eol) t))
11497 (if (not (org-at-date-range-p t))
11498 (error "Not at a time-stamp range, and none found in current line")))
11499 (let* ((ts1 (match-string 1))
11500 (ts2 (match-string 2))
11501 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
11502 (match-end (match-end 0))
11503 (time1 (org-time-string-to-time ts1))
11504 (time2 (org-time-string-to-time ts2))
11505 (t1 (time-to-seconds time1))
11506 (t2 (time-to-seconds time2))
11507 (diff (abs (- t2 t1)))
11508 (negative (< (- t2 t1) 0))
11509 ;; (ys (floor (* 365 24 60 60)))
11510 (ds (* 24 60 60))
11511 (hs (* 60 60))
11512 (fy "%dy %dd %02d:%02d")
11513 (fy1 "%dy %dd")
11514 (fd "%dd %02d:%02d")
11515 (fd1 "%dd")
11516 (fh "%02d:%02d")
11517 y d h m align)
11518 (if havetime
11519 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11521 d (floor (/ diff ds)) diff (mod diff ds)
11522 h (floor (/ diff hs)) diff (mod diff hs)
11523 m (floor (/ diff 60)))
11524 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11526 d (floor (+ (/ diff ds) 0.5))
11527 h 0 m 0))
11528 (if (not to-buffer)
11529 (message "%s" (org-make-tdiff-string y d h m))
11530 (if (org-at-table-p)
11531 (progn
11532 (goto-char match-end)
11533 (setq align t)
11534 (and (looking-at " *|") (goto-char (match-end 0))))
11535 (goto-char match-end))
11536 (if (looking-at
11537 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
11538 (replace-match ""))
11539 (if negative (insert " -"))
11540 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
11541 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
11542 (insert " " (format fh h m))))
11543 (if align (org-table-align))
11544 (message "Time difference inserted")))))
11546 (defun org-make-tdiff-string (y d h m)
11547 (let ((fmt "")
11548 (l nil))
11549 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
11550 l (push y l)))
11551 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
11552 l (push d l)))
11553 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
11554 l (push h l)))
11555 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
11556 l (push m l)))
11557 (apply 'format fmt (nreverse l))))
11559 (defun org-time-string-to-time (s)
11560 (apply 'encode-time (org-parse-time-string s)))
11562 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
11563 "Convert a time stamp to an absolute day number.
11564 If there is a specifyer for a cyclic time stamp, get the closest date to
11565 DAYNR.
11566 PREFER and SHOW-ALL are passed through to `org-closest-date'."
11567 (cond
11568 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
11569 (if (org-diary-sexp-entry (match-string 1 s) "" date)
11570 daynr
11571 (+ daynr 1000)))
11572 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
11573 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
11574 (time-to-days (current-time))) (match-string 0 s)
11575 prefer show-all))
11576 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
11578 (defun org-days-to-iso-week (days)
11579 "Return the iso week number."
11580 (require 'cal-iso)
11581 (car (calendar-iso-from-absolute days)))
11583 (defun org-small-year-to-year (year)
11584 "Convert 2-digit years into 4-digit years.
11585 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
11586 The year 2000 cannot be abbreviated. Any year larger than 99
11587 is returned unchanged."
11588 (if (< year 38)
11589 (setq year (+ 2000 year))
11590 (if (< year 100)
11591 (setq year (+ 1900 year))))
11592 year)
11594 (defun org-time-from-absolute (d)
11595 "Return the time corresponding to date D.
11596 D may be an absolute day number, or a calendar-type list (month day year)."
11597 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
11598 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
11600 (defun org-calendar-holiday ()
11601 "List of holidays, for Diary display in Org-mode."
11602 (require 'holidays)
11603 (let ((hl (funcall
11604 (if (fboundp 'calendar-check-holidays)
11605 'calendar-check-holidays 'check-calendar-holidays) date)))
11606 (if hl (mapconcat 'identity hl "; "))))
11608 (defun org-diary-sexp-entry (sexp entry date)
11609 "Process a SEXP diary ENTRY for DATE."
11610 (require 'diary-lib)
11611 (let ((result (if calendar-debug-sexp
11612 (let ((stack-trace-on-error t))
11613 (eval (car (read-from-string sexp))))
11614 (condition-case nil
11615 (eval (car (read-from-string sexp)))
11616 (error
11617 (beep)
11618 (message "Bad sexp at line %d in %s: %s"
11619 (org-current-line)
11620 (buffer-file-name) sexp)
11621 (sleep-for 2))))))
11622 (cond ((stringp result) result)
11623 ((and (consp result)
11624 (stringp (cdr result))) (cdr result))
11625 (result entry)
11626 (t nil))))
11628 (defun org-diary-to-ical-string (frombuf)
11629 "Get iCalendar entries from diary entries in buffer FROMBUF.
11630 This uses the icalendar.el library."
11631 (let* ((tmpdir (if (featurep 'xemacs)
11632 (temp-directory)
11633 temporary-file-directory))
11634 (tmpfile (make-temp-name
11635 (expand-file-name "orgics" tmpdir)))
11636 buf rtn b e)
11637 (save-excursion
11638 (set-buffer frombuf)
11639 (icalendar-export-region (point-min) (point-max) tmpfile)
11640 (setq buf (find-buffer-visiting tmpfile))
11641 (set-buffer buf)
11642 (goto-char (point-min))
11643 (if (re-search-forward "^BEGIN:VEVENT" nil t)
11644 (setq b (match-beginning 0)))
11645 (goto-char (point-max))
11646 (if (re-search-backward "^END:VEVENT" nil t)
11647 (setq e (match-end 0)))
11648 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
11649 (kill-buffer buf)
11650 (delete-file tmpfile)
11651 rtn))
11653 (defun org-closest-date (start current change prefer show-all)
11654 "Find the date closest to CURRENT that is consistent with START and CHANGE.
11655 When PREFER is `past' return a date that is either CURRENT or past.
11656 When PREFER is `future', return a date that is either CURRENT or future.
11657 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
11658 ;; Make the proper lists from the dates
11659 (catch 'exit
11660 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
11661 dn dw sday cday n1 n2 n0
11662 d m y y1 y2 date1 date2 nmonths nm ny m2)
11664 (setq start (org-date-to-gregorian start)
11665 current (org-date-to-gregorian
11666 (if show-all
11667 current
11668 (time-to-days (current-time))))
11669 sday (calendar-absolute-from-gregorian start)
11670 cday (calendar-absolute-from-gregorian current))
11672 (if (<= cday sday) (throw 'exit sday))
11674 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
11675 (setq dn (string-to-number (match-string 1 change))
11676 dw (cdr (assoc (match-string 2 change) a1)))
11677 (error "Invalid change specifyer: %s" change))
11678 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
11679 (cond
11680 ((eq dw 'day)
11681 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
11682 n2 (+ n1 dn)))
11683 ((eq dw 'year)
11684 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
11685 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
11686 (setq date1 (list m d y1)
11687 n1 (calendar-absolute-from-gregorian date1)
11688 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
11689 n2 (calendar-absolute-from-gregorian date2)))
11690 ((eq dw 'month)
11691 ;; approx number of month between the two dates
11692 (setq nmonths (floor (/ (- cday sday) 30.436875)))
11693 ;; How often does dn fit in there?
11694 (setq d (nth 1 start) m (car start) y (nth 2 start)
11695 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
11696 m (+ m nm)
11697 ny (floor (/ m 12))
11698 y (+ y ny)
11699 m (- m (* ny 12)))
11700 (while (> m 12) (setq m (- m 12) y (1+ y)))
11701 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
11702 (setq m2 (+ m dn) y2 y)
11703 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11704 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
11705 (while (<= n2 cday)
11706 (setq n1 n2 m m2 y y2)
11707 (setq m2 (+ m dn) y2 y)
11708 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11709 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
11710 ;; Make sure n1 is the earlier date
11711 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
11712 (if show-all
11713 (cond
11714 ((eq prefer 'past) n1)
11715 ((eq prefer 'future) (if (= cday n1) n1 n2))
11716 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
11717 (cond
11718 ((eq prefer 'past) n1)
11719 ((eq prefer 'future) (if (= cday n1) n1 n2))
11720 (t (if (= cday n1) n1 n2)))))))
11722 (defun org-date-to-gregorian (date)
11723 "Turn any specification of DATE into a gregorian date for the calendar."
11724 (cond ((integerp date) (calendar-gregorian-from-absolute date))
11725 ((and (listp date) (= (length date) 3)) date)
11726 ((stringp date)
11727 (setq date (org-parse-time-string date))
11728 (list (nth 4 date) (nth 3 date) (nth 5 date)))
11729 ((listp date)
11730 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
11732 (defun org-parse-time-string (s &optional nodefault)
11733 "Parse the standard Org-mode time string.
11734 This should be a lot faster than the normal `parse-time-string'.
11735 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
11736 hour and minute fields will be nil if not given."
11737 (if (string-match org-ts-regexp0 s)
11738 (list 0
11739 (if (or (match-beginning 8) (not nodefault))
11740 (string-to-number (or (match-string 8 s) "0")))
11741 (if (or (match-beginning 7) (not nodefault))
11742 (string-to-number (or (match-string 7 s) "0")))
11743 (string-to-number (match-string 4 s))
11744 (string-to-number (match-string 3 s))
11745 (string-to-number (match-string 2 s))
11746 nil nil nil)
11747 (make-list 9 0)))
11749 (defun org-timestamp-up (&optional arg)
11750 "Increase the date item at the cursor by one.
11751 If the cursor is on the year, change the year. If it is on the month or
11752 the day, change that.
11753 With prefix ARG, change by that many units."
11754 (interactive "p")
11755 (org-timestamp-change (prefix-numeric-value arg)))
11757 (defun org-timestamp-down (&optional arg)
11758 "Decrease the date item at the cursor by one.
11759 If the cursor is on the year, change the year. If it is on the month or
11760 the day, change that.
11761 With prefix ARG, change by that many units."
11762 (interactive "p")
11763 (org-timestamp-change (- (prefix-numeric-value arg))))
11765 (defun org-timestamp-up-day (&optional arg)
11766 "Increase the date in the time stamp by one day.
11767 With prefix ARG, change that many days."
11768 (interactive "p")
11769 (if (and (not (org-at-timestamp-p t))
11770 (org-on-heading-p))
11771 (org-todo 'up)
11772 (org-timestamp-change (prefix-numeric-value arg) 'day)))
11774 (defun org-timestamp-down-day (&optional arg)
11775 "Decrease the date in the time stamp by one day.
11776 With prefix ARG, change that many days."
11777 (interactive "p")
11778 (if (and (not (org-at-timestamp-p t))
11779 (org-on-heading-p))
11780 (org-todo 'down)
11781 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
11783 (defun org-at-timestamp-p (&optional inactive-ok)
11784 "Determine if the cursor is in or at a timestamp."
11785 (interactive)
11786 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
11787 (pos (point))
11788 (ans (or (looking-at tsr)
11789 (save-excursion
11790 (skip-chars-backward "^[<\n\r\t")
11791 (if (> (point) (point-min)) (backward-char 1))
11792 (and (looking-at tsr)
11793 (> (- (match-end 0) pos) -1))))))
11794 (and ans
11795 (boundp 'org-ts-what)
11796 (setq org-ts-what
11797 (cond
11798 ((= pos (match-beginning 0)) 'bracket)
11799 ((= pos (1- (match-end 0))) 'bracket)
11800 ((org-pos-in-match-range pos 2) 'year)
11801 ((org-pos-in-match-range pos 3) 'month)
11802 ((org-pos-in-match-range pos 7) 'hour)
11803 ((org-pos-in-match-range pos 8) 'minute)
11804 ((or (org-pos-in-match-range pos 4)
11805 (org-pos-in-match-range pos 5)) 'day)
11806 ((and (> pos (or (match-end 8) (match-end 5)))
11807 (< pos (match-end 0)))
11808 (- pos (or (match-end 8) (match-end 5))))
11809 (t 'day))))
11810 ans))
11812 (defun org-toggle-timestamp-type ()
11813 "Toggle the type (<active> or [inactive]) of a time stamp."
11814 (interactive)
11815 (when (org-at-timestamp-p t)
11816 (let ((beg (match-beginning 0)) (end (match-end 0))
11817 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
11818 (save-excursion
11819 (goto-char beg)
11820 (while (re-search-forward "[][<>]" end t)
11821 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
11822 t t)))
11823 (message "Timestamp is now %sactive"
11824 (if (equal (char-after beg) ?<) "" "in")))))
11826 (defun org-timestamp-change (n &optional what)
11827 "Change the date in the time stamp at point.
11828 The date will be changed by N times WHAT. WHAT can be `day', `month',
11829 `year', `minute', `second'. If WHAT is not given, the cursor position
11830 in the timestamp determines what will be changed."
11831 (let ((pos (point))
11832 with-hm inactive
11833 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
11834 org-ts-what
11835 extra rem
11836 ts time time0)
11837 (if (not (org-at-timestamp-p t))
11838 (error "Not at a timestamp"))
11839 (if (and (not what) (eq org-ts-what 'bracket))
11840 (org-toggle-timestamp-type)
11841 (if (and (not what) (not (eq org-ts-what 'day))
11842 org-display-custom-times
11843 (get-text-property (point) 'display)
11844 (not (get-text-property (1- (point)) 'display)))
11845 (setq org-ts-what 'day))
11846 (setq org-ts-what (or what org-ts-what)
11847 inactive (= (char-after (match-beginning 0)) ?\[)
11848 ts (match-string 0))
11849 (replace-match "")
11850 (if (string-match
11851 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
11853 (setq extra (match-string 1 ts)))
11854 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
11855 (setq with-hm t))
11856 (setq time0 (org-parse-time-string ts))
11857 (when (and (eq org-ts-what 'minute)
11858 (eq current-prefix-arg nil))
11859 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
11860 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
11861 (setcar (cdr time0) (+ (nth 1 time0)
11862 (if (> n 0) (- rem) (- dm rem))))))
11863 (setq time
11864 (encode-time (or (car time0) 0)
11865 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
11866 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
11867 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
11868 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
11869 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
11870 (nthcdr 6 time0)))
11871 (when (integerp org-ts-what)
11872 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
11873 (if (eq what 'calendar)
11874 (let ((cal-date (org-get-date-from-calendar)))
11875 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
11876 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
11877 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
11878 (setcar time0 (or (car time0) 0))
11879 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
11880 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
11881 (setq time (apply 'encode-time time0))))
11882 (setq org-last-changed-timestamp
11883 (org-insert-time-stamp time with-hm inactive nil nil extra))
11884 (org-clock-update-time-maybe)
11885 (goto-char pos)
11886 ;; Try to recenter the calendar window, if any
11887 (if (and org-calendar-follow-timestamp-change
11888 (get-buffer-window "*Calendar*" t)
11889 (memq org-ts-what '(day month year)))
11890 (org-recenter-calendar (time-to-days time))))))
11892 (defun org-modify-ts-extra (s pos n dm)
11893 "Change the different parts of the lead-time and repeat fields in timestamp."
11894 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
11895 ng h m new rem)
11896 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
11897 (cond
11898 ((or (org-pos-in-match-range pos 2)
11899 (org-pos-in-match-range pos 3))
11900 (setq m (string-to-number (match-string 3 s))
11901 h (string-to-number (match-string 2 s)))
11902 (if (org-pos-in-match-range pos 2)
11903 (setq h (+ h n))
11904 (setq n (* dm (org-no-warnings (signum n))))
11905 (when (not (= 0 (setq rem (% m dm))))
11906 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
11907 (setq m (+ m n)))
11908 (if (< m 0) (setq m (+ m 60) h (1- h)))
11909 (if (> m 59) (setq m (- m 60) h (1+ h)))
11910 (setq h (min 24 (max 0 h)))
11911 (setq ng 1 new (format "-%02d:%02d" h m)))
11912 ((org-pos-in-match-range pos 6)
11913 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
11914 ((org-pos-in-match-range pos 5)
11915 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
11917 ((org-pos-in-match-range pos 9)
11918 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
11919 ((org-pos-in-match-range pos 8)
11920 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
11922 (when ng
11923 (setq s (concat
11924 (substring s 0 (match-beginning ng))
11926 (substring s (match-end ng))))))
11929 (defun org-recenter-calendar (date)
11930 "If the calendar is visible, recenter it to DATE."
11931 (let* ((win (selected-window))
11932 (cwin (get-buffer-window "*Calendar*" t))
11933 (calendar-move-hook nil))
11934 (when cwin
11935 (select-window cwin)
11936 (calendar-goto-date (if (listp date) date
11937 (calendar-gregorian-from-absolute date)))
11938 (select-window win))))
11940 (defun org-goto-calendar (&optional arg)
11941 "Go to the Emacs calendar at the current date.
11942 If there is a time stamp in the current line, go to that date.
11943 A prefix ARG can be used to force the current date."
11944 (interactive "P")
11945 (let ((tsr org-ts-regexp) diff
11946 (calendar-move-hook nil)
11947 (calendar-view-holidays-initially-flag nil)
11948 (view-calendar-holidays-initially nil)
11949 (calendar-view-diary-initially-flag nil)
11950 (view-diary-entries-initially nil))
11951 (if (or (org-at-timestamp-p)
11952 (save-excursion
11953 (beginning-of-line 1)
11954 (looking-at (concat ".*" tsr))))
11955 (let ((d1 (time-to-days (current-time)))
11956 (d2 (time-to-days
11957 (org-time-string-to-time (match-string 1)))))
11958 (setq diff (- d2 d1))))
11959 (calendar)
11960 (calendar-goto-today)
11961 (if (and diff (not arg)) (calendar-forward-day diff))))
11963 (defun org-get-date-from-calendar ()
11964 "Return a list (month day year) of date at point in calendar."
11965 (with-current-buffer "*Calendar*"
11966 (save-match-data
11967 (calendar-cursor-to-date))))
11969 (defun org-date-from-calendar ()
11970 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
11971 If there is already a time stamp at the cursor position, update it."
11972 (interactive)
11973 (if (org-at-timestamp-p t)
11974 (org-timestamp-change 0 'calendar)
11975 (let ((cal-date (org-get-date-from-calendar)))
11976 (org-insert-time-stamp
11977 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
11979 (defun org-minutes-to-hh:mm-string (m)
11980 "Compute H:MM from a number of minutes."
11981 (let ((h (/ m 60)))
11982 (setq m (- m (* 60 h)))
11983 (format org-time-clocksum-format h m)))
11985 (defun org-hh:mm-string-to-minutes (s)
11986 "Convert a string H:MM to a number of minutes."
11987 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
11988 (+ (* (string-to-number (match-string 1 s)) 60)
11989 (string-to-number (match-string 2 s)))
11992 ;;;; Agenda files
11994 ;;;###autoload
11995 (defun org-iswitchb (&optional arg)
11996 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
11997 With a prefix argument, restrict available to files.
11998 With two prefix arguments, restrict available buffers to agenda files.
12000 Due to some yet unresolved reason, the global function
12001 `iswitchb-mode' needs to be active for this function to work."
12002 (interactive "P")
12003 (require 'iswitchb)
12004 (let ((enabled iswitchb-mode) blist)
12005 (or enabled (iswitchb-mode 1))
12006 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
12007 ((equal arg '(16)) (org-buffer-list 'agenda))
12008 (t (org-buffer-list))))
12009 (unwind-protect
12010 (let ((iswitchb-make-buflist-hook
12011 (lambda ()
12012 (setq iswitchb-temp-buflist
12013 (mapcar 'buffer-name blist)))))
12014 (switch-to-buffer
12015 (iswitchb-read-buffer
12016 "Switch-to: " nil t))
12017 (or enabled (iswitchb-mode -1))))))
12019 ;;;###autoload
12020 (defun org-ido-switchb (&optional arg)
12021 "Use `org-ido-completing-read' to prompt for an Org buffer to switch to.
12022 With a prefix argument, restrict available to files.
12023 With two prefix arguments, restrict available buffers to agenda files."
12024 (interactive "P")
12025 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
12026 ((equal arg '(16)) (org-buffer-list 'agenda))
12027 (t (org-buffer-list)))))
12028 (switch-to-buffer
12029 (org-ido-completing-read "Org buffer: "
12030 (mapcar 'buffer-name blist)
12031 nil t))))
12033 (defun org-buffer-list (&optional predicate exclude-tmp)
12034 "Return a list of Org buffers.
12035 PREDICATE can be `export', `files' or `agenda'.
12037 export restrict the list to Export buffers.
12038 files restrict the list to buffers visiting Org files.
12039 agenda restrict the list to buffers visiting agenda files.
12041 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
12042 (let* ((bfn nil)
12043 (agenda-files (and (eq predicate 'agenda)
12044 (mapcar 'file-truename (org-agenda-files t))))
12045 (filter
12046 (cond
12047 ((eq predicate 'files)
12048 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
12049 ((eq predicate 'export)
12050 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
12051 ((eq predicate 'agenda)
12052 (lambda (b)
12053 (with-current-buffer b
12054 (and (eq major-mode 'org-mode)
12055 (setq bfn (buffer-file-name b))
12056 (member (file-truename bfn) agenda-files)))))
12057 (t (lambda (b) (with-current-buffer b
12058 (or (eq major-mode 'org-mode)
12059 (string-match "\*Org .*Export"
12060 (buffer-name b)))))))))
12061 (delq nil
12062 (mapcar
12063 (lambda(b)
12064 (if (and (funcall filter b)
12065 (or (not exclude-tmp)
12066 (not (string-match "tmp" (buffer-name b)))))
12068 nil))
12069 (buffer-list)))))
12071 (defun org-agenda-files (&optional unrestricted archives)
12072 "Get the list of agenda files.
12073 Optional UNRESTRICTED means return the full list even if a restriction
12074 is currently in place.
12075 When ARCHIVES is t, include all archive files hat are really being
12076 used by the agenda files. If ARCHIVE is `ifmode', do this only if
12077 `org-agenda-archives-mode' is t."
12078 (let ((files
12079 (cond
12080 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
12081 ((stringp org-agenda-files) (org-read-agenda-file-list))
12082 ((listp org-agenda-files) org-agenda-files)
12083 (t (error "Invalid value of `org-agenda-files'")))))
12084 (setq files (apply 'append
12085 (mapcar (lambda (f)
12086 (if (file-directory-p f)
12087 (directory-files
12088 f t org-agenda-file-regexp)
12089 (list f)))
12090 files)))
12091 (when org-agenda-skip-unavailable-files
12092 (setq files (delq nil
12093 (mapcar (function
12094 (lambda (file)
12095 (and (file-readable-p file) file)))
12096 files))))
12097 (when (or (eq archives t)
12098 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
12099 (setq files (org-add-archive-files files)))
12100 files))
12102 (defun org-edit-agenda-file-list ()
12103 "Edit the list of agenda files.
12104 Depending on setup, this either uses customize to edit the variable
12105 `org-agenda-files', or it visits the file that is holding the list. In the
12106 latter case, the buffer is set up in a way that saving it automatically kills
12107 the buffer and restores the previous window configuration."
12108 (interactive)
12109 (if (stringp org-agenda-files)
12110 (let ((cw (current-window-configuration)))
12111 (find-file org-agenda-files)
12112 (org-set-local 'org-window-configuration cw)
12113 (org-add-hook 'after-save-hook
12114 (lambda ()
12115 (set-window-configuration
12116 (prog1 org-window-configuration
12117 (kill-buffer (current-buffer))))
12118 (org-install-agenda-files-menu)
12119 (message "New agenda file list installed"))
12120 nil 'local)
12121 (message "%s" (substitute-command-keys
12122 "Edit list and finish with \\[save-buffer]")))
12123 (customize-variable 'org-agenda-files)))
12125 (defun org-store-new-agenda-file-list (list)
12126 "Set new value for the agenda file list and save it correctly."
12127 (if (stringp org-agenda-files)
12128 (let ((f org-agenda-files) b)
12129 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
12130 (with-temp-file f
12131 (insert (mapconcat 'identity list "\n") "\n")))
12132 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
12133 (setq org-agenda-files list)
12134 (customize-save-variable 'org-agenda-files org-agenda-files))))
12136 (defun org-read-agenda-file-list ()
12137 "Read the list of agenda files from a file."
12138 (when (file-directory-p org-agenda-files)
12139 (error "`org-agenda-files' cannot be a single directory"))
12140 (when (stringp org-agenda-files)
12141 (with-temp-buffer
12142 (insert-file-contents org-agenda-files)
12143 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
12146 ;;;###autoload
12147 (defun org-cycle-agenda-files ()
12148 "Cycle through the files in `org-agenda-files'.
12149 If the current buffer visits an agenda file, find the next one in the list.
12150 If the current buffer does not, find the first agenda file."
12151 (interactive)
12152 (let* ((fs (org-agenda-files t))
12153 (files (append fs (list (car fs))))
12154 (tcf (if buffer-file-name (file-truename buffer-file-name)))
12155 file)
12156 (unless files (error "No agenda files"))
12157 (catch 'exit
12158 (while (setq file (pop files))
12159 (if (equal (file-truename file) tcf)
12160 (when (car files)
12161 (find-file (car files))
12162 (throw 'exit t))))
12163 (find-file (car fs)))
12164 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
12166 (defun org-agenda-file-to-front (&optional to-end)
12167 "Move/add the current file to the top of the agenda file list.
12168 If the file is not present in the list, it is added to the front. If it is
12169 present, it is moved there. With optional argument TO-END, add/move to the
12170 end of the list."
12171 (interactive "P")
12172 (let ((org-agenda-skip-unavailable-files nil)
12173 (file-alist (mapcar (lambda (x)
12174 (cons (file-truename x) x))
12175 (org-agenda-files t)))
12176 (ctf (file-truename buffer-file-name))
12177 x had)
12178 (setq x (assoc ctf file-alist) had x)
12180 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
12181 (if to-end
12182 (setq file-alist (append (delq x file-alist) (list x)))
12183 (setq file-alist (cons x (delq x file-alist))))
12184 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
12185 (org-install-agenda-files-menu)
12186 (message "File %s to %s of agenda file list"
12187 (if had "moved" "added") (if to-end "end" "front"))))
12189 (defun org-remove-file (&optional file)
12190 "Remove current file from the list of files in variable `org-agenda-files'.
12191 These are the files which are being checked for agenda entries.
12192 Optional argument FILE means, use this file instead of the current."
12193 (interactive)
12194 (let* ((org-agenda-skip-unavailable-files nil)
12195 (file (or file buffer-file-name))
12196 (true-file (file-truename file))
12197 (afile (abbreviate-file-name file))
12198 (files (delq nil (mapcar
12199 (lambda (x)
12200 (if (equal true-file
12201 (file-truename x))
12202 nil x))
12203 (org-agenda-files t)))))
12204 (if (not (= (length files) (length (org-agenda-files t))))
12205 (progn
12206 (org-store-new-agenda-file-list files)
12207 (org-install-agenda-files-menu)
12208 (message "Removed file: %s" afile))
12209 (message "File was not in list: %s (not removed)" afile))))
12211 (defun org-file-menu-entry (file)
12212 (vector file (list 'find-file file) t))
12214 (defun org-check-agenda-file (file)
12215 "Make sure FILE exists. If not, ask user what to do."
12216 (when (not (file-exists-p file))
12217 (message "non-existent file %s. [R]emove from list or [A]bort?"
12218 (abbreviate-file-name file))
12219 (let ((r (downcase (read-char-exclusive))))
12220 (cond
12221 ((equal r ?r)
12222 (org-remove-file file)
12223 (throw 'nextfile t))
12224 (t (error "Abort"))))))
12226 (defun org-get-agenda-file-buffer (file)
12227 "Get a buffer visiting FILE. If the buffer needs to be created, add
12228 it to the list of buffers which might be released later."
12229 (let ((buf (org-find-base-buffer-visiting file)))
12230 (if buf
12231 buf ; just return it
12232 ;; Make a new buffer and remember it
12233 (setq buf (find-file-noselect file))
12234 (if buf (push buf org-agenda-new-buffers))
12235 buf)))
12237 (defun org-release-buffers (blist)
12238 "Release all buffers in list, asking the user for confirmation when needed.
12239 When a buffer is unmodified, it is just killed. When modified, it is saved
12240 \(if the user agrees) and then killed."
12241 (let (buf file)
12242 (while (setq buf (pop blist))
12243 (setq file (buffer-file-name buf))
12244 (when (and (buffer-modified-p buf)
12245 file
12246 (y-or-n-p (format "Save file %s? " file)))
12247 (with-current-buffer buf (save-buffer)))
12248 (kill-buffer buf))))
12250 (defun org-prepare-agenda-buffers (files)
12251 "Create buffers for all agenda files, protect archived trees and comments."
12252 (interactive)
12253 (let ((pa '(:org-archived t))
12254 (pc '(:org-comment t))
12255 (pall '(:org-archived t :org-comment t))
12256 (inhibit-read-only t)
12257 (rea (concat ":" org-archive-tag ":"))
12258 bmp file re)
12259 (save-excursion
12260 (save-restriction
12261 (while (setq file (pop files))
12262 (if (bufferp file)
12263 (set-buffer file)
12264 (org-check-agenda-file file)
12265 (set-buffer (org-get-agenda-file-buffer file)))
12266 (widen)
12267 (setq bmp (buffer-modified-p))
12268 (org-refresh-category-properties)
12269 (setq org-todo-keywords-for-agenda
12270 (append org-todo-keywords-for-agenda org-todo-keywords-1))
12271 (setq org-done-keywords-for-agenda
12272 (append org-done-keywords-for-agenda org-done-keywords))
12273 (setq org-todo-keyword-alist-for-agenda
12274 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
12275 (setq org-tag-alist-for-agenda
12276 (append org-tag-alist-for-agenda org-tag-alist))
12278 (save-excursion
12279 (remove-text-properties (point-min) (point-max) pall)
12280 (when org-agenda-skip-archived-trees
12281 (goto-char (point-min))
12282 (while (re-search-forward rea nil t)
12283 (if (org-on-heading-p t)
12284 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
12285 (goto-char (point-min))
12286 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
12287 (while (re-search-forward re nil t)
12288 (add-text-properties
12289 (match-beginning 0) (org-end-of-subtree t) pc)))
12290 (set-buffer-modified-p bmp))))
12291 (setq org-todo-keyword-alist-for-agenda
12292 (org-uniquify org-todo-keyword-alist-for-agenda)
12293 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
12295 ;;;; Embedded LaTeX
12297 (defvar org-cdlatex-mode-map (make-sparse-keymap)
12298 "Keymap for the minor `org-cdlatex-mode'.")
12300 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
12301 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
12302 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
12303 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
12304 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
12306 (defvar org-cdlatex-texmathp-advice-is-done nil
12307 "Flag remembering if we have applied the advice to texmathp already.")
12309 (define-minor-mode org-cdlatex-mode
12310 "Toggle the minor `org-cdlatex-mode'.
12311 This mode supports entering LaTeX environment and math in LaTeX fragments
12312 in Org-mode.
12313 \\{org-cdlatex-mode-map}"
12314 nil " OCDL" nil
12315 (when org-cdlatex-mode (require 'cdlatex))
12316 (unless org-cdlatex-texmathp-advice-is-done
12317 (setq org-cdlatex-texmathp-advice-is-done t)
12318 (defadvice texmathp (around org-math-always-on activate)
12319 "Always return t in org-mode buffers.
12320 This is because we want to insert math symbols without dollars even outside
12321 the LaTeX math segments. If Orgmode thinks that point is actually inside
12322 an embedded LaTeX fragment, let texmathp do its job.
12323 \\[org-cdlatex-mode-map]"
12324 (interactive)
12325 (let (p)
12326 (cond
12327 ((not (org-mode-p)) ad-do-it)
12328 ((eq this-command 'cdlatex-math-symbol)
12329 (setq ad-return-value t
12330 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
12332 (let ((p (org-inside-LaTeX-fragment-p)))
12333 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
12334 (setq ad-return-value t
12335 texmathp-why '("Org-mode embedded math" . 0))
12336 (if p ad-do-it)))))))))
12338 (defun turn-on-org-cdlatex ()
12339 "Unconditionally turn on `org-cdlatex-mode'."
12340 (org-cdlatex-mode 1))
12342 (defun org-inside-LaTeX-fragment-p ()
12343 "Test if point is inside a LaTeX fragment.
12344 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
12345 sequence appearing also before point.
12346 Even though the matchers for math are configurable, this function assumes
12347 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
12348 delimiters are skipped when they have been removed by customization.
12349 The return value is nil, or a cons cell with the delimiter and
12350 and the position of this delimiter.
12352 This function does a reasonably good job, but can locally be fooled by
12353 for example currency specifications. For example it will assume being in
12354 inline math after \"$22.34\". The LaTeX fragment formatter will only format
12355 fragments that are properly closed, but during editing, we have to live
12356 with the uncertainty caused by missing closing delimiters. This function
12357 looks only before point, not after."
12358 (catch 'exit
12359 (let ((pos (point))
12360 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
12361 (lim (progn
12362 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
12363 (point)))
12364 dd-on str (start 0) m re)
12365 (goto-char pos)
12366 (when dodollar
12367 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
12368 re (nth 1 (assoc "$" org-latex-regexps)))
12369 (while (string-match re str start)
12370 (cond
12371 ((= (match-end 0) (length str))
12372 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
12373 ((= (match-end 0) (- (length str) 5))
12374 (throw 'exit nil))
12375 (t (setq start (match-end 0))))))
12376 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
12377 (goto-char pos)
12378 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
12379 (and (match-beginning 2) (throw 'exit nil))
12380 ;; count $$
12381 (while (re-search-backward "\\$\\$" lim t)
12382 (setq dd-on (not dd-on)))
12383 (goto-char pos)
12384 (if dd-on (cons "$$" m))))))
12387 (defun org-try-cdlatex-tab ()
12388 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
12389 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
12390 - inside a LaTeX fragment, or
12391 - after the first word in a line, where an abbreviation expansion could
12392 insert a LaTeX environment."
12393 (when org-cdlatex-mode
12394 (cond
12395 ((save-excursion
12396 (skip-chars-backward "a-zA-Z0-9*")
12397 (skip-chars-backward " \t")
12398 (bolp))
12399 (cdlatex-tab) t)
12400 ((org-inside-LaTeX-fragment-p)
12401 (cdlatex-tab) t)
12402 (t nil))))
12404 (defun org-cdlatex-underscore-caret (&optional arg)
12405 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
12406 Revert to the normal definition outside of these fragments."
12407 (interactive "P")
12408 (if (org-inside-LaTeX-fragment-p)
12409 (call-interactively 'cdlatex-sub-superscript)
12410 (let (org-cdlatex-mode)
12411 (call-interactively (key-binding (vector last-input-event))))))
12413 (defun org-cdlatex-math-modify (&optional arg)
12414 "Execute `cdlatex-math-modify' in LaTeX fragments.
12415 Revert to the normal definition outside of these fragments."
12416 (interactive "P")
12417 (if (org-inside-LaTeX-fragment-p)
12418 (call-interactively 'cdlatex-math-modify)
12419 (let (org-cdlatex-mode)
12420 (call-interactively (key-binding (vector last-input-event))))))
12422 (defvar org-latex-fragment-image-overlays nil
12423 "List of overlays carrying the images of latex fragments.")
12424 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
12426 (defun org-remove-latex-fragment-image-overlays ()
12427 "Remove all overlays with LaTeX fragment images in current buffer."
12428 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
12429 (setq org-latex-fragment-image-overlays nil))
12431 (defun org-preview-latex-fragment (&optional subtree)
12432 "Preview the LaTeX fragment at point, or all locally or globally.
12433 If the cursor is in a LaTeX fragment, create the image and overlay
12434 it over the source code. If there is no fragment at point, display
12435 all fragments in the current text, from one headline to the next. With
12436 prefix SUBTREE, display all fragments in the current subtree. With a
12437 double prefix `C-u C-u', or when the cursor is before the first headline,
12438 display all fragments in the buffer.
12439 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
12440 (interactive "P")
12441 (org-remove-latex-fragment-image-overlays)
12442 (save-excursion
12443 (save-restriction
12444 (let (beg end at msg)
12445 (cond
12446 ((or (equal subtree '(16))
12447 (not (save-excursion
12448 (re-search-backward (concat "^" outline-regexp) nil t))))
12449 (setq beg (point-min) end (point-max)
12450 msg "Creating images for buffer...%s"))
12451 ((equal subtree '(4))
12452 (org-back-to-heading)
12453 (setq beg (point) end (org-end-of-subtree t)
12454 msg "Creating images for subtree...%s"))
12456 (if (setq at (org-inside-LaTeX-fragment-p))
12457 (goto-char (max (point-min) (- (cdr at) 2)))
12458 (org-back-to-heading))
12459 (setq beg (point) end (progn (outline-next-heading) (point))
12460 msg (if at "Creating image...%s"
12461 "Creating images for entry...%s"))))
12462 (message msg "")
12463 (narrow-to-region beg end)
12464 (goto-char beg)
12465 (org-format-latex
12466 (concat "ltxpng/" (file-name-sans-extension
12467 (file-name-nondirectory
12468 buffer-file-name)))
12469 default-directory 'overlays msg at 'forbuffer)
12470 (message msg "done. Use `C-c C-c' to remove images.")))))
12472 (defvar org-latex-regexps
12473 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
12474 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
12475 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
12476 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
12477 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
12478 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
12479 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
12480 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
12481 "Regular expressions for matching embedded LaTeX.")
12483 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
12484 "Replace LaTeX fragments with links to an image, and produce images."
12485 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
12486 (let* ((prefixnodir (file-name-nondirectory prefix))
12487 (absprefix (expand-file-name prefix dir))
12488 (todir (file-name-directory absprefix))
12489 (opt org-format-latex-options)
12490 (matchers (plist-get opt :matchers))
12491 (re-list org-latex-regexps)
12492 (cnt 0) txt link beg end re e checkdir
12493 m n block linkfile movefile ov)
12494 ;; Check if there are old images files with this prefix, and remove them
12495 (when (file-directory-p todir)
12496 (mapc 'delete-file
12497 (directory-files
12498 todir 'full
12499 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
12500 ;; Check the different regular expressions
12501 (while (setq e (pop re-list))
12502 (setq m (car e) re (nth 1 e) n (nth 2 e)
12503 block (if (nth 3 e) "\n\n" ""))
12504 (when (member m matchers)
12505 (goto-char (point-min))
12506 (while (re-search-forward re nil t)
12507 (when (or (not at) (equal (cdr at) (match-beginning n)))
12508 (setq txt (match-string n)
12509 beg (match-beginning n) end (match-end n)
12510 cnt (1+ cnt)
12511 linkfile (format "%s_%04d.png" prefix cnt)
12512 movefile (format "%s_%04d.png" absprefix cnt)
12513 link (concat block "[[file:" linkfile "]]" block))
12514 (if msg (message msg cnt))
12515 (goto-char beg)
12516 (unless checkdir ; make sure the directory exists
12517 (setq checkdir t)
12518 (or (file-directory-p todir) (make-directory todir)))
12519 (org-create-formula-image
12520 txt movefile opt forbuffer)
12521 (if overlays
12522 (progn
12523 (setq ov (org-make-overlay beg end))
12524 (if (featurep 'xemacs)
12525 (progn
12526 (org-overlay-put ov 'invisible t)
12527 (org-overlay-put
12528 ov 'end-glyph
12529 (make-glyph (vector 'png :file movefile))))
12530 (org-overlay-put
12531 ov 'display
12532 (list 'image :type 'png :file movefile :ascent 'center)))
12533 (push ov org-latex-fragment-image-overlays)
12534 (goto-char end))
12535 (delete-region beg end)
12536 (insert link))))))))
12538 ;; This function borrows from Ganesh Swami's latex2png.el
12539 (defun org-create-formula-image (string tofile options buffer)
12540 (let* ((tmpdir (if (featurep 'xemacs)
12541 (temp-directory)
12542 temporary-file-directory))
12543 (texfilebase (make-temp-name
12544 (expand-file-name "orgtex" tmpdir)))
12545 (texfile (concat texfilebase ".tex"))
12546 (dvifile (concat texfilebase ".dvi"))
12547 (pngfile (concat texfilebase ".png"))
12548 (fnh (if (featurep 'xemacs)
12549 (font-height (get-face-font 'default))
12550 (face-attribute 'default :height nil)))
12551 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
12552 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
12553 (fg (or (plist-get options (if buffer :foreground :html-foreground))
12554 "Black"))
12555 (bg (or (plist-get options (if buffer :background :html-background))
12556 "Transparent")))
12557 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
12558 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
12559 (with-temp-file texfile
12560 (insert org-format-latex-header
12561 "\n\\begin{document}\n" string "\n\\end{document}\n"))
12562 (let ((dir default-directory))
12563 (condition-case nil
12564 (progn
12565 (cd tmpdir)
12566 (call-process "latex" nil nil nil texfile))
12567 (error nil))
12568 (cd dir))
12569 (if (not (file-exists-p dvifile))
12570 (progn (message "Failed to create dvi file from %s" texfile) nil)
12571 (condition-case nil
12572 (call-process "dvipng" nil nil nil
12573 "-E" "-fg" fg "-bg" bg
12574 "-D" dpi
12575 ;;"-x" scale "-y" scale
12576 "-T" "tight"
12577 "-o" pngfile
12578 dvifile)
12579 (error nil))
12580 (if (not (file-exists-p pngfile))
12581 (progn (message "Failed to create png file from %s" texfile) nil)
12582 ;; Use the requested file name and clean up
12583 (copy-file pngfile tofile 'replace)
12584 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
12585 (delete-file (concat texfilebase e)))
12586 pngfile))))
12588 (defun org-dvipng-color (attr)
12589 "Return an rgb color specification for dvipng."
12590 (apply 'format "rgb %s %s %s"
12591 (mapcar 'org-normalize-color
12592 (color-values (face-attribute 'default attr nil)))))
12594 (defun org-normalize-color (value)
12595 "Return string to be used as color value for an RGB component."
12596 (format "%g" (/ value 65535.0)))
12598 ;;;; Key bindings
12600 ;; Make `C-c C-x' a prefix key
12601 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
12603 ;; TAB key with modifiers
12604 (org-defkey org-mode-map "\C-i" 'org-cycle)
12605 (org-defkey org-mode-map [(tab)] 'org-cycle)
12606 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
12607 (org-defkey org-mode-map [(meta tab)] 'org-complete)
12608 (org-defkey org-mode-map "\M-\t" 'org-complete)
12609 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
12610 ;; The following line is necessary under Suse GNU/Linux
12611 (unless (featurep 'xemacs)
12612 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
12613 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
12614 (define-key org-mode-map [backtab] 'org-shifttab)
12616 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
12617 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
12618 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
12620 ;; Cursor keys with modifiers
12621 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
12622 (org-defkey org-mode-map [(meta right)] 'org-metaright)
12623 (org-defkey org-mode-map [(meta up)] 'org-metaup)
12624 (org-defkey org-mode-map [(meta down)] 'org-metadown)
12626 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
12627 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
12628 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
12629 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
12631 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
12632 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
12633 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
12634 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
12636 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
12637 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
12639 ;;; Extra keys for tty access.
12640 ;; We only set them when really needed because otherwise the
12641 ;; menus don't show the simple keys
12643 (when (or org-use-extra-keys
12644 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
12645 (not window-system))
12646 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
12647 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
12648 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
12649 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
12650 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
12651 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
12652 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
12653 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
12654 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
12655 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
12656 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
12657 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
12658 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
12659 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
12660 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
12661 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
12662 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
12663 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
12664 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
12665 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
12666 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
12667 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
12669 ;; All the other keys
12671 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
12672 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
12673 (if (boundp 'narrow-map)
12674 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
12675 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
12676 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
12677 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
12678 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
12679 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
12680 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
12681 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
12682 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
12683 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
12684 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
12685 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
12686 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
12687 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
12688 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
12689 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
12690 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
12691 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
12692 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
12693 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
12694 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
12695 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
12696 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
12697 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
12698 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
12699 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
12700 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
12701 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
12702 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
12703 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
12704 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
12705 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
12706 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
12707 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
12708 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
12709 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
12710 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
12711 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
12712 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
12713 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
12714 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
12715 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
12716 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
12717 (org-defkey org-mode-map "\C-c^" 'org-sort)
12718 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
12719 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
12720 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
12721 (org-defkey org-mode-map "\C-m" 'org-return)
12722 (org-defkey org-mode-map "\C-j" 'org-return-indent)
12723 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
12724 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
12725 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
12726 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
12727 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
12728 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
12729 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
12730 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
12731 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
12732 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
12733 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
12734 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
12735 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
12736 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
12737 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
12738 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
12740 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
12741 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
12742 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
12743 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
12745 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
12746 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
12747 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
12748 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
12749 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
12750 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
12751 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
12752 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
12753 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
12754 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
12755 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
12756 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
12758 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
12759 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
12760 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
12761 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
12763 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
12765 (when (featurep 'xemacs)
12766 (org-defkey org-mode-map 'button3 'popup-mode-menu))
12768 (defvar org-table-auto-blank-field) ; defined in org-table.el
12769 (defun org-self-insert-command (N)
12770 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
12771 If the cursor is in a table looking at whitespace, the whitespace is
12772 overwritten, and the table is not marked as requiring realignment."
12773 (interactive "p")
12774 (if (and (org-table-p)
12775 (progn
12776 ;; check if we blank the field, and if that triggers align
12777 (and (featurep 'org-table) org-table-auto-blank-field
12778 (member last-command
12779 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
12780 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
12781 ;; got extra space, this field does not determine column width
12782 (let (org-table-may-need-update) (org-table-blank-field))
12783 ;; no extra space, this field may determine column width
12784 (org-table-blank-field)))
12786 (eq N 1)
12787 (looking-at "[^|\n]* |"))
12788 (let (org-table-may-need-update)
12789 (goto-char (1- (match-end 0)))
12790 (delete-backward-char 1)
12791 (goto-char (match-beginning 0))
12792 (self-insert-command N))
12793 (setq org-table-may-need-update t)
12794 (self-insert-command N)
12795 (org-fix-tags-on-the-fly)))
12797 (defun org-fix-tags-on-the-fly ()
12798 (when (and (equal (char-after (point-at-bol)) ?*)
12799 (org-on-heading-p))
12800 (org-align-tags-here org-tags-column)))
12802 (defun org-delete-backward-char (N)
12803 "Like `delete-backward-char', insert whitespace at field end in tables.
12804 When deleting backwards, in tables this function will insert whitespace in
12805 front of the next \"|\" separator, to keep the table aligned. The table will
12806 still be marked for re-alignment if the field did fill the entire column,
12807 because, in this case the deletion might narrow the column."
12808 (interactive "p")
12809 (if (and (org-table-p)
12810 (eq N 1)
12811 (string-match "|" (buffer-substring (point-at-bol) (point)))
12812 (looking-at ".*?|"))
12813 (let ((pos (point))
12814 (noalign (looking-at "[^|\n\r]* |"))
12815 (c org-table-may-need-update))
12816 (backward-delete-char N)
12817 (skip-chars-forward "^|")
12818 (insert " ")
12819 (goto-char (1- pos))
12820 ;; noalign: if there were two spaces at the end, this field
12821 ;; does not determine the width of the column.
12822 (if noalign (setq org-table-may-need-update c)))
12823 (backward-delete-char N)
12824 (org-fix-tags-on-the-fly)))
12826 (defun org-delete-char (N)
12827 "Like `delete-char', but insert whitespace at field end in tables.
12828 When deleting characters, in tables this function will insert whitespace in
12829 front of the next \"|\" separator, to keep the table aligned. The table will
12830 still be marked for re-alignment if the field did fill the entire column,
12831 because, in this case the deletion might narrow the column."
12832 (interactive "p")
12833 (if (and (org-table-p)
12834 (not (bolp))
12835 (not (= (char-after) ?|))
12836 (eq N 1))
12837 (if (looking-at ".*?|")
12838 (let ((pos (point))
12839 (noalign (looking-at "[^|\n\r]* |"))
12840 (c org-table-may-need-update))
12841 (replace-match (concat
12842 (substring (match-string 0) 1 -1)
12843 " |"))
12844 (goto-char pos)
12845 ;; noalign: if there were two spaces at the end, this field
12846 ;; does not determine the width of the column.
12847 (if noalign (setq org-table-may-need-update c)))
12848 (delete-char N))
12849 (delete-char N)
12850 (org-fix-tags-on-the-fly)))
12852 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
12853 (put 'org-self-insert-command 'delete-selection t)
12854 (put 'orgtbl-self-insert-command 'delete-selection t)
12855 (put 'org-delete-char 'delete-selection 'supersede)
12856 (put 'org-delete-backward-char 'delete-selection 'supersede)
12858 ;; Make `flyspell-mode' delay after some commands
12859 (put 'org-self-insert-command 'flyspell-delayed t)
12860 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
12861 (put 'org-delete-char 'flyspell-delayed t)
12862 (put 'org-delete-backward-char 'flyspell-delayed t)
12864 ;; Make pabbrev-mode expand after org-mode commands
12865 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
12866 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
12868 ;; How to do this: Measure non-white length of current string
12869 ;; If equal to column width, we should realign.
12871 (defun org-remap (map &rest commands)
12872 "In MAP, remap the functions given in COMMANDS.
12873 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
12874 (let (new old)
12875 (while commands
12876 (setq old (pop commands) new (pop commands))
12877 (if (fboundp 'command-remapping)
12878 (org-defkey map (vector 'remap old) new)
12879 (substitute-key-definition old new map global-map)))))
12881 (when (eq org-enable-table-editor 'optimized)
12882 ;; If the user wants maximum table support, we need to hijack
12883 ;; some standard editing functions
12884 (org-remap org-mode-map
12885 'self-insert-command 'org-self-insert-command
12886 'delete-char 'org-delete-char
12887 'delete-backward-char 'org-delete-backward-char)
12888 (org-defkey org-mode-map "|" 'org-force-self-insert))
12890 (defun org-shiftcursor-error ()
12891 "Throw an error because Shift-Cursor command was applied in wrong context."
12892 (error "This command is active in special context like tables, headlines or timestamps"))
12894 (defun org-shifttab (&optional arg)
12895 "Global visibility cycling or move to previous table field.
12896 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
12897 on context.
12898 See the individual commands for more information."
12899 (interactive "P")
12900 (cond
12901 ((org-at-table-p) (call-interactively 'org-table-previous-field))
12902 ((integerp arg)
12903 (message "Content view to level: %d" arg)
12904 (org-content (prefix-numeric-value arg))
12905 (setq org-cycle-global-status 'overview))
12906 (t (call-interactively 'org-global-cycle))))
12908 (defun org-shiftmetaleft ()
12909 "Promote subtree or delete table column.
12910 Calls `org-promote-subtree', `org-outdent-item',
12911 or `org-table-delete-column', depending on context.
12912 See the individual commands for more information."
12913 (interactive)
12914 (cond
12915 ((org-at-table-p) (call-interactively 'org-table-delete-column))
12916 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
12917 ((org-at-item-p) (call-interactively 'org-outdent-item))
12918 (t (org-shiftcursor-error))))
12920 (defun org-shiftmetaright ()
12921 "Demote subtree or insert table column.
12922 Calls `org-demote-subtree', `org-indent-item',
12923 or `org-table-insert-column', depending on context.
12924 See the individual commands for more information."
12925 (interactive)
12926 (cond
12927 ((org-at-table-p) (call-interactively 'org-table-insert-column))
12928 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
12929 ((org-at-item-p) (call-interactively 'org-indent-item))
12930 (t (org-shiftcursor-error))))
12932 (defun org-shiftmetaup (&optional arg)
12933 "Move subtree up or kill table row.
12934 Calls `org-move-subtree-up' or `org-table-kill-row' or
12935 `org-move-item-up' depending on context. See the individual commands
12936 for more information."
12937 (interactive "P")
12938 (cond
12939 ((org-at-table-p) (call-interactively 'org-table-kill-row))
12940 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12941 ((org-at-item-p) (call-interactively 'org-move-item-up))
12942 (t (org-shiftcursor-error))))
12943 (defun org-shiftmetadown (&optional arg)
12944 "Move subtree down or insert table row.
12945 Calls `org-move-subtree-down' or `org-table-insert-row' or
12946 `org-move-item-down', depending on context. See the individual
12947 commands for more information."
12948 (interactive "P")
12949 (cond
12950 ((org-at-table-p) (call-interactively 'org-table-insert-row))
12951 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12952 ((org-at-item-p) (call-interactively 'org-move-item-down))
12953 (t (org-shiftcursor-error))))
12955 (defun org-metaleft (&optional arg)
12956 "Promote heading or move table column to left.
12957 Calls `org-do-promote' or `org-table-move-column', depending on context.
12958 With no specific context, calls the Emacs default `backward-word'.
12959 See the individual commands for more information."
12960 (interactive "P")
12961 (cond
12962 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
12963 ((or (org-on-heading-p) (org-region-active-p))
12964 (call-interactively 'org-do-promote))
12965 ((org-at-item-p) (call-interactively 'org-outdent-item))
12966 (t (call-interactively 'backward-word))))
12968 (defun org-metaright (&optional arg)
12969 "Demote subtree or move table column to right.
12970 Calls `org-do-demote' or `org-table-move-column', depending on context.
12971 With no specific context, calls the Emacs default `forward-word'.
12972 See the individual commands for more information."
12973 (interactive "P")
12974 (cond
12975 ((org-at-table-p) (call-interactively 'org-table-move-column))
12976 ((or (org-on-heading-p) (org-region-active-p))
12977 (call-interactively 'org-do-demote))
12978 ((org-at-item-p) (call-interactively 'org-indent-item))
12979 (t (call-interactively 'forward-word))))
12981 (defun org-metaup (&optional arg)
12982 "Move subtree up or move table row up.
12983 Calls `org-move-subtree-up' or `org-table-move-row' or
12984 `org-move-item-up', depending on context. See the individual commands
12985 for more information."
12986 (interactive "P")
12987 (cond
12988 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
12989 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12990 ((org-at-item-p) (call-interactively 'org-move-item-up))
12991 (t (transpose-lines 1) (beginning-of-line -1))))
12993 (defun org-metadown (&optional arg)
12994 "Move subtree down or move table row down.
12995 Calls `org-move-subtree-down' or `org-table-move-row' or
12996 `org-move-item-down', depending on context. See the individual
12997 commands for more information."
12998 (interactive "P")
12999 (cond
13000 ((org-at-table-p) (call-interactively 'org-table-move-row))
13001 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
13002 ((org-at-item-p) (call-interactively 'org-move-item-down))
13003 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
13005 (defun org-shiftup (&optional arg)
13006 "Increase item in timestamp or increase priority of current headline.
13007 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
13008 depending on context. See the individual commands for more information."
13009 (interactive "P")
13010 (cond
13011 ((org-at-timestamp-p t)
13012 (call-interactively (if org-edit-timestamp-down-means-later
13013 'org-timestamp-down 'org-timestamp-up)))
13014 ((org-on-heading-p) (call-interactively 'org-priority-up))
13015 ((org-at-item-p) (call-interactively 'org-previous-item))
13016 ((org-clocktable-try-shift 'up arg))
13017 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
13019 (defun org-shiftdown (&optional arg)
13020 "Decrease item in timestamp or decrease priority of current headline.
13021 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
13022 depending on context. See the individual commands for more information."
13023 (interactive "P")
13024 (cond
13025 ((org-at-timestamp-p t)
13026 (call-interactively (if org-edit-timestamp-down-means-later
13027 'org-timestamp-up 'org-timestamp-down)))
13028 ((org-on-heading-p) (call-interactively 'org-priority-down))
13029 ((org-clocktable-try-shift 'down arg))
13030 (t (call-interactively 'org-next-item))))
13032 (defun org-shiftright (&optional arg)
13033 "Cycle the thing at point or in the current line, depending on context.
13034 Depending on context, this does one of the following:
13036 - switch a timestamp at point one day into the future
13037 - on a headline, switch to the next TODO keyword.
13038 - on an item, switch entire list to the next bullet type
13039 - on a property line, switch to the next allowed value
13040 - on a clocktable definition line, move time block into the future"
13041 (interactive "P")
13042 (cond
13043 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
13044 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
13045 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
13046 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
13047 ((org-clocktable-try-shift 'right arg))
13048 (t (org-shiftcursor-error))))
13050 (defun org-shiftleft (&optional arg)
13051 "Cycle the thing at point or in the current line, depending on context.
13052 Depending on context, this does one of the following:
13054 - switch a timestamp at point one day into the past
13055 - on a headline, switch to the previous TODO keyword.
13056 - on an item, switch entire list to the previous bullet type
13057 - on a property line, switch to the previous allowed value
13058 - on a clocktable definition line, move time block into the past"
13059 (interactive "P")
13060 (cond
13061 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
13062 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
13063 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
13064 ((org-at-property-p)
13065 (call-interactively 'org-property-previous-allowed-value))
13066 ((org-clocktable-try-shift 'left arg))
13067 (t (org-shiftcursor-error))))
13069 (defun org-shiftcontrolright ()
13070 "Switch to next TODO set."
13071 (interactive)
13072 (cond
13073 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
13074 (t (org-shiftcursor-error))))
13076 (defun org-shiftcontrolleft ()
13077 "Switch to previous TODO set."
13078 (interactive)
13079 (cond
13080 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
13081 (t (org-shiftcursor-error))))
13083 (defun org-ctrl-c-ret ()
13084 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
13085 (interactive)
13086 (cond
13087 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
13088 (t (call-interactively 'org-insert-heading))))
13090 (defun org-copy-special ()
13091 "Copy region in table or copy current subtree.
13092 Calls `org-table-copy' or `org-copy-subtree', depending on context.
13093 See the individual commands for more information."
13094 (interactive)
13095 (call-interactively
13096 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
13098 (defun org-cut-special ()
13099 "Cut region in table or cut current subtree.
13100 Calls `org-table-copy' or `org-cut-subtree', depending on context.
13101 See the individual commands for more information."
13102 (interactive)
13103 (call-interactively
13104 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
13106 (defun org-paste-special (arg)
13107 "Paste rectangular region into table, or past subtree relative to level.
13108 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
13109 See the individual commands for more information."
13110 (interactive "P")
13111 (if (org-at-table-p)
13112 (org-table-paste-rectangle)
13113 (org-paste-subtree arg)))
13115 (defun org-edit-special ()
13116 "Call a special editor for the stuff at point.
13117 When at a table, call the formula editor with `org-table-edit-formulas'.
13118 When at the first line of an src example, call `org-edit-src-code'.
13119 When in an #+include line, visit the include file. Otherwise call
13120 `ffap' to visit the file at point."
13121 (interactive)
13122 (cond
13123 ((org-at-table-p)
13124 (call-interactively 'org-table-edit-formulas))
13125 ((save-excursion
13126 (beginning-of-line 1)
13127 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
13128 (find-file (org-trim (match-string 1))))
13129 ((org-edit-src-code))
13130 ((org-edit-fixed-width-region))
13131 (t (call-interactively 'ffap))))
13133 (defun org-ctrl-c-ctrl-c (&optional arg)
13134 "Set tags in headline, or update according to changed information at point.
13136 This command does many different things, depending on context:
13138 - If the cursor is in a headline, prompt for tags and insert them
13139 into the current line, aligned to `org-tags-column'. When called
13140 with prefix arg, realign all tags in the current buffer.
13142 - If the cursor is in one of the special #+KEYWORD lines, this
13143 triggers scanning the buffer for these lines and updating the
13144 information.
13146 - If the cursor is inside a table, realign the table. This command
13147 works even if the automatic table editor has been turned off.
13149 - If the cursor is on a #+TBLFM line, re-apply the formulas to
13150 the entire table.
13152 - If the cursor is at a footnote reference or definition, jump to
13153 the corresponding definition or references, respectively.
13155 - If the cursor is a the beginning of a dynamic block, update it.
13157 - If the cursor is inside a table created by the table.el package,
13158 activate that table.
13160 - If the current buffer is a remember buffer, close note and file
13161 it. A prefix argument of 1 files to the default location
13162 without further interaction. A prefix argument of 2 files to
13163 the currently clocking task.
13165 - If the cursor is on a <<<target>>>, update radio targets and corresponding
13166 links in this buffer.
13168 - If the cursor is on a numbered item in a plain list, renumber the
13169 ordered list.
13171 - If the cursor is on a checkbox, toggle it."
13172 (interactive "P")
13173 (let ((org-enable-table-editor t))
13174 (cond
13175 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
13176 org-occur-highlights
13177 org-latex-fragment-image-overlays)
13178 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
13179 (org-remove-occur-highlights)
13180 (org-remove-latex-fragment-image-overlays)
13181 (message "Temporary highlights/overlays removed from current buffer"))
13182 ((and (local-variable-p 'org-finish-function (current-buffer))
13183 (fboundp org-finish-function))
13184 (funcall org-finish-function))
13185 ((org-at-property-p)
13186 (call-interactively 'org-property-action))
13187 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
13188 ((org-on-heading-p) (call-interactively 'org-set-tags))
13189 ((org-at-table.el-p)
13190 (require 'table)
13191 (beginning-of-line 1)
13192 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
13193 (call-interactively 'table-recognize-table))
13194 ((org-at-table-p)
13195 (org-table-maybe-eval-formula)
13196 (if arg
13197 (call-interactively 'org-table-recalculate)
13198 (org-table-maybe-recalculate-line))
13199 (call-interactively 'org-table-align))
13200 ((or (org-footnote-at-reference-p)
13201 (org-footnote-at-definition-p))
13202 (call-interactively 'org-footnote-action))
13203 ((org-at-item-checkbox-p)
13204 (call-interactively 'org-toggle-checkbox))
13205 ((org-at-item-p)
13206 (call-interactively 'org-maybe-renumber-ordered-list))
13207 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
13208 ;; Dynamic block
13209 (beginning-of-line 1)
13210 (save-excursion (org-update-dblock)))
13211 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
13212 (cond
13213 ((equal (match-string 1) "TBLFM")
13214 ;; Recalculate the table before this line
13215 (save-excursion
13216 (beginning-of-line 1)
13217 (skip-chars-backward " \r\n\t")
13218 (if (org-at-table-p)
13219 (org-call-with-arg 'org-table-recalculate t))))
13221 ; (org-set-regexps-and-options)
13222 ; (org-restart-font-lock)
13223 (let ((org-inhibit-startup t)) (org-mode-restart))
13224 (message "Local setup has been refreshed"))))
13225 (t (error "C-c C-c can do nothing useful at this location.")))))
13227 (defun org-mode-restart ()
13228 "Restart Org-mode, to scan again for special lines.
13229 Also updates the keyword regular expressions."
13230 (interactive)
13231 (org-mode)
13232 (message "Org-mode restarted"))
13234 (defun org-kill-note-or-show-branches ()
13235 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
13236 (interactive)
13237 (if (not org-finish-function)
13238 (call-interactively 'show-branches)
13239 (let ((org-note-abort t))
13240 (funcall org-finish-function))))
13242 (defun org-return (&optional indent)
13243 "Goto next table row or insert a newline.
13244 Calls `org-table-next-row' or `newline', depending on context.
13245 See the individual commands for more information."
13246 (interactive)
13247 (cond
13248 ((bobp) (if indent (newline-and-indent) (newline)))
13249 ((and (org-at-heading-p)
13250 (looking-at
13251 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
13252 (org-show-entry)
13253 (end-of-line 1)
13254 (newline))
13255 ((org-at-table-p)
13256 (org-table-justify-field-maybe)
13257 (call-interactively 'org-table-next-row))
13258 (t (if indent (newline-and-indent) (newline)))))
13260 (defun org-return-indent ()
13261 "Goto next table row or insert a newline and indent.
13262 Calls `org-table-next-row' or `newline-and-indent', depending on
13263 context. See the individual commands for more information."
13264 (interactive)
13265 (org-return t))
13267 (defun org-ctrl-c-star ()
13268 "Compute table, or change heading status of lines.
13269 Calls `org-table-recalculate' or `org-toggle-region-headings',
13270 depending on context. This will also turn a plain list item or a normal
13271 line into a subheading."
13272 (interactive)
13273 (cond
13274 ((org-at-table-p)
13275 (call-interactively 'org-table-recalculate))
13276 ((org-region-active-p)
13277 ;; Convert all lines in region to list items
13278 (call-interactively 'org-toggle-region-headings))
13279 ((org-on-heading-p)
13280 (org-toggle-region-headings (point-at-bol)
13281 (min (1+ (point-at-eol)) (point-max))))
13282 ((org-at-item-p)
13283 ;; Convert to heading
13284 (let ((level (save-match-data
13285 (save-excursion
13286 (condition-case nil
13287 (progn
13288 (org-back-to-heading t)
13289 (funcall outline-level))
13290 (error 0))))))
13291 (replace-match
13292 (concat (make-string (org-get-valid-level level 1) ?*) " ") t t)))
13293 (t (org-toggle-region-headings (point-at-bol)
13294 (min (1+ (point-at-eol)) (point-max))))))
13296 (defun org-ctrl-c-minus ()
13297 "Insert separator line in table or modify bullet status of line.
13298 Also turns a plain line or a region of lines into list items.
13299 Calls `org-table-insert-hline', `org-toggle-region-items', or
13300 `org-cycle-list-bullet', depending on context."
13301 (interactive)
13302 (cond
13303 ((org-at-table-p)
13304 (call-interactively 'org-table-insert-hline))
13305 ((org-on-heading-p)
13306 ;; Convert to item
13307 (save-excursion
13308 (beginning-of-line 1)
13309 (if (looking-at "\\*+ ")
13310 (replace-match
13311 (concat (make-string
13312 (- (match-end 0) (point) (if org-odd-levels-only 2 1)) ?\ )
13313 "- ")))))
13314 ((org-region-active-p)
13315 ;; Convert all lines in region to list items
13316 (call-interactively 'org-toggle-region-items))
13317 ((org-in-item-p)
13318 (call-interactively 'org-cycle-list-bullet))
13319 (t (org-toggle-region-items (point-at-bol)
13320 (min (1+ (point-at-eol)) (point-max))))))
13322 (defun org-toggle-region-items (beg end)
13323 "Convert all lines in region to list items.
13324 If the first line is already an item, convert all list items in the region
13325 to normal lines."
13326 (interactive "r")
13327 (let (l2 l)
13328 (save-excursion
13329 (goto-char end)
13330 (setq l2 (org-current-line))
13331 (goto-char beg)
13332 (beginning-of-line 1)
13333 (setq l (1- (org-current-line)))
13334 (if (org-at-item-p)
13335 ;; We already have items, de-itemize
13336 (while (< (setq l (1+ l)) l2)
13337 (when (org-at-item-p)
13338 (goto-char (match-beginning 2))
13339 (delete-region (match-beginning 2) (match-end 2))
13340 (and (looking-at "[ \t]+") (replace-match "")))
13341 (beginning-of-line 2))
13342 (while (< (setq l (1+ l)) l2)
13343 (unless (org-at-item-p)
13344 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
13345 (replace-match "\\1- \\2")))
13346 (beginning-of-line 2))))))
13348 (defun org-toggle-region-headings (beg end)
13349 "Convert all lines in region to list items.
13350 If the first line is already an item, convert all list items in the region
13351 to normal lines."
13352 (interactive "r")
13353 (let (l2 l)
13354 (save-excursion
13355 (goto-char end)
13356 (setq l2 (org-current-line))
13357 (goto-char beg)
13358 (beginning-of-line 1)
13359 (setq l (1- (org-current-line)))
13360 (if (org-on-heading-p)
13361 ;; We already have headlines, de-star them
13362 (while (< (setq l (1+ l)) l2)
13363 (when (org-on-heading-p t)
13364 (and (looking-at outline-regexp) (replace-match "")))
13365 (beginning-of-line 2))
13366 (let* ((stars (save-excursion
13367 (re-search-backward org-complex-heading-regexp nil t)
13368 (or (match-string 1) "*")))
13369 (add-stars (if org-odd-levels-only "**" "*"))
13370 (rpl (concat stars add-stars " \\2")))
13371 (while (< (setq l (1+ l)) l2)
13372 (unless (org-on-heading-p)
13373 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
13374 (replace-match rpl)))
13375 (beginning-of-line 2)))))))
13377 (defun org-meta-return (&optional arg)
13378 "Insert a new heading or wrap a region in a table.
13379 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
13380 See the individual commands for more information."
13381 (interactive "P")
13382 (cond
13383 ((org-at-table-p)
13384 (call-interactively 'org-table-wrap-region))
13385 (t (call-interactively 'org-insert-heading))))
13387 ;;; Menu entries
13389 ;; Define the Org-mode menus
13390 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
13391 '("Tbl"
13392 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
13393 ["Next Field" org-cycle (org-at-table-p)]
13394 ["Previous Field" org-shifttab (org-at-table-p)]
13395 ["Next Row" org-return (org-at-table-p)]
13396 "--"
13397 ["Blank Field" org-table-blank-field (org-at-table-p)]
13398 ["Edit Field" org-table-edit-field (org-at-table-p)]
13399 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
13400 "--"
13401 ("Column"
13402 ["Move Column Left" org-metaleft (org-at-table-p)]
13403 ["Move Column Right" org-metaright (org-at-table-p)]
13404 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
13405 ["Insert Column" org-shiftmetaright (org-at-table-p)])
13406 ("Row"
13407 ["Move Row Up" org-metaup (org-at-table-p)]
13408 ["Move Row Down" org-metadown (org-at-table-p)]
13409 ["Delete Row" org-shiftmetaup (org-at-table-p)]
13410 ["Insert Row" org-shiftmetadown (org-at-table-p)]
13411 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
13412 "--"
13413 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
13414 ("Rectangle"
13415 ["Copy Rectangle" org-copy-special (org-at-table-p)]
13416 ["Cut Rectangle" org-cut-special (org-at-table-p)]
13417 ["Paste Rectangle" org-paste-special (org-at-table-p)]
13418 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
13419 "--"
13420 ("Calculate"
13421 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
13422 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
13423 ["Edit Formulas" org-edit-special (org-at-table-p)]
13424 "--"
13425 ["Recalculate line" org-table-recalculate (org-at-table-p)]
13426 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
13427 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
13428 "--"
13429 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
13430 "--"
13431 ["Sum Column/Rectangle" org-table-sum
13432 (or (org-at-table-p) (org-region-active-p))]
13433 ["Which Column?" org-table-current-column (org-at-table-p)])
13434 ["Debug Formulas"
13435 org-table-toggle-formula-debugger
13436 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
13437 ["Show Col/Row Numbers"
13438 org-table-toggle-coordinate-overlays
13439 :style toggle
13440 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
13441 "--"
13442 ["Create" org-table-create (and (not (org-at-table-p))
13443 org-enable-table-editor)]
13444 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
13445 ["Import from File" org-table-import (not (org-at-table-p))]
13446 ["Export to File" org-table-export (org-at-table-p)]
13447 "--"
13448 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
13450 (easy-menu-define org-org-menu org-mode-map "Org menu"
13451 '("Org"
13452 ("Show/Hide"
13453 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
13454 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
13455 ["Sparse Tree..." org-sparse-tree t]
13456 ["Reveal Context" org-reveal t]
13457 ["Show All" show-all t]
13458 "--"
13459 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
13460 "--"
13461 ["New Heading" org-insert-heading t]
13462 ("Navigate Headings"
13463 ["Up" outline-up-heading t]
13464 ["Next" outline-next-visible-heading t]
13465 ["Previous" outline-previous-visible-heading t]
13466 ["Next Same Level" outline-forward-same-level t]
13467 ["Previous Same Level" outline-backward-same-level t]
13468 "--"
13469 ["Jump" org-goto t])
13470 ("Edit Structure"
13471 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
13472 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
13473 "--"
13474 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
13475 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
13476 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
13477 "--"
13478 ["Promote Heading" org-metaleft (not (org-at-table-p))]
13479 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
13480 ["Demote Heading" org-metaright (not (org-at-table-p))]
13481 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
13482 "--"
13483 ["Sort Region/Children" org-sort (not (org-at-table-p))]
13484 "--"
13485 ["Convert to odd levels" org-convert-to-odd-levels t]
13486 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
13487 ("Editing"
13488 ["Emphasis..." org-emphasize t]
13489 ["Edit Source Example" org-edit-special t]
13490 "--"
13491 ["Footnote new/jump" org-footnote-action t]
13492 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
13493 ("Archive"
13494 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
13495 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
13496 ; :active t :keys "C-u C-c C-x C-a"]
13497 ["Sparse trees open ARCHIVE trees"
13498 (setq org-sparse-tree-open-archived-trees
13499 (not org-sparse-tree-open-archived-trees))
13500 :style toggle :selected org-sparse-tree-open-archived-trees]
13501 ["Cycling opens ARCHIVE trees"
13502 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
13503 :style toggle :selected org-cycle-open-archived-trees]
13504 "--"
13505 ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
13506 ["Move Subtree to Archive" org-advertized-archive-subtree t]
13507 ; ["Check and Move Children" (org-archive-subtree '(4))
13508 ; :active t :keys "C-u C-c C-x C-s"]
13510 "--"
13511 ("TODO Lists"
13512 ["TODO/DONE/-" org-todo t]
13513 ("Select keyword"
13514 ["Next keyword" org-shiftright (org-on-heading-p)]
13515 ["Previous keyword" org-shiftleft (org-on-heading-p)]
13516 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
13517 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
13518 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
13519 ["Show TODO Tree" org-show-todo-tree t]
13520 ["Global TODO list" org-todo-list t]
13521 "--"
13522 ["Set Priority" org-priority t]
13523 ["Priority Up" org-shiftup t]
13524 ["Priority Down" org-shiftdown t])
13525 ("TAGS and Properties"
13526 ["Set Tags" org-set-tags-command t]
13527 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
13528 "--"
13529 ["Set property" org-set-property t]
13530 ["Column view of properties" org-columns t]
13531 ["Insert Column View DBlock" org-insert-columns-dblock t])
13532 ("Dates and Scheduling"
13533 ["Timestamp" org-time-stamp t]
13534 ["Timestamp (inactive)" org-time-stamp-inactive t]
13535 ("Change Date"
13536 ["1 Day Later" org-shiftright t]
13537 ["1 Day Earlier" org-shiftleft t]
13538 ["1 ... Later" org-shiftup t]
13539 ["1 ... Earlier" org-shiftdown t])
13540 ["Compute Time Range" org-evaluate-time-range t]
13541 ["Schedule Item" org-schedule t]
13542 ["Deadline" org-deadline t]
13543 "--"
13544 ["Custom time format" org-toggle-time-stamp-overlays
13545 :style radio :selected org-display-custom-times]
13546 "--"
13547 ["Goto Calendar" org-goto-calendar t]
13548 ["Date from Calendar" org-date-from-calendar t]
13549 "--"
13550 ["Start/Restart Timer" org-timer-start t]
13551 ["Pause/Continue Timer" org-timer-pause-or-continue t]
13552 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
13553 ["Insert Timer String" org-timer t]
13554 ["Insert Timer Item" org-timer-item t])
13555 ("Logging work"
13556 ["Clock in" org-clock-in t]
13557 ["Clock out" org-clock-out t]
13558 ["Clock cancel" org-clock-cancel t]
13559 ["Goto running clock" org-clock-goto t]
13560 ["Display times" org-clock-display t]
13561 ["Create clock table" org-clock-report t]
13562 "--"
13563 ["Record DONE time"
13564 (progn (setq org-log-done (not org-log-done))
13565 (message "Switching to %s will %s record a timestamp"
13566 (car org-done-keywords)
13567 (if org-log-done "automatically" "not")))
13568 :style toggle :selected org-log-done])
13569 "--"
13570 ["Agenda Command..." org-agenda t]
13571 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
13572 ("File List for Agenda")
13573 ("Special views current file"
13574 ["TODO Tree" org-show-todo-tree t]
13575 ["Check Deadlines" org-check-deadlines t]
13576 ["Timeline" org-timeline t]
13577 ["Tags Tree" org-tags-sparse-tree t])
13578 "--"
13579 ("Hyperlinks"
13580 ["Store Link (Global)" org-store-link t]
13581 ["Insert Link" org-insert-link t]
13582 ["Follow Link" org-open-at-point t]
13583 "--"
13584 ["Next link" org-next-link t]
13585 ["Previous link" org-previous-link t]
13586 "--"
13587 ["Descriptive Links"
13588 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
13589 :style radio
13590 :selected (member '(org-link) buffer-invisibility-spec)]
13591 ["Literal Links"
13592 (progn
13593 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
13594 :style radio
13595 :selected (not (member '(org-link) buffer-invisibility-spec))])
13596 "--"
13597 ["Export/Publish..." org-export t]
13598 ("LaTeX"
13599 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
13600 :selected org-cdlatex-mode]
13601 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
13602 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
13603 ["Modify math symbol" org-cdlatex-math-modify
13604 (org-inside-LaTeX-fragment-p)]
13605 ["Export LaTeX fragments as images"
13606 (if (featurep 'org-exp)
13607 (setq org-export-with-LaTeX-fragments
13608 (not org-export-with-LaTeX-fragments))
13609 (require 'org-exp))
13610 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
13611 org-export-with-LaTeX-fragments)])
13612 "--"
13613 ("Documentation"
13614 ["Show Version" org-version t]
13615 ["Info Documentation" org-info t])
13616 ("Customize"
13617 ["Browse Org Group" org-customize t]
13618 "--"
13619 ["Expand This Menu" org-create-customize-menu
13620 (fboundp 'customize-menu-create)])
13621 "--"
13622 ["Refresh setup" org-mode-restart t]
13625 (defun org-info (&optional node)
13626 "Read documentation for Org-mode in the info system.
13627 With optional NODE, go directly to that node."
13628 (interactive)
13629 (info (format "(org)%s" (or node ""))))
13631 (defun org-install-agenda-files-menu ()
13632 (let ((bl (buffer-list)))
13633 (save-excursion
13634 (while bl
13635 (set-buffer (pop bl))
13636 (if (org-mode-p) (setq bl nil)))
13637 (when (org-mode-p)
13638 (easy-menu-change
13639 '("Org") "File List for Agenda"
13640 (append
13641 (list
13642 ["Edit File List" (org-edit-agenda-file-list) t]
13643 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
13644 ["Remove Current File from List" org-remove-file t]
13645 ["Cycle through agenda files" org-cycle-agenda-files t]
13646 ["Occur in all agenda files" org-occur-in-agenda-files t]
13647 "--")
13648 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
13650 ;;;; Documentation
13652 ;;;###autoload
13653 (defun org-require-autoloaded-modules ()
13654 (interactive)
13655 (mapc 'require
13656 '(org-agenda org-archive org-clock org-colview
13657 org-exp org-id org-export-latex org-publish
13658 org-remember org-table)))
13660 ;;;###autoload
13661 (defun org-customize ()
13662 "Call the customize function with org as argument."
13663 (interactive)
13664 (org-load-modules-maybe)
13665 (org-require-autoloaded-modules)
13666 (customize-browse 'org))
13668 (defun org-create-customize-menu ()
13669 "Create a full customization menu for Org-mode, insert it into the menu."
13670 (interactive)
13671 (org-load-modules-maybe)
13672 (org-require-autoloaded-modules)
13673 (if (fboundp 'customize-menu-create)
13674 (progn
13675 (easy-menu-change
13676 '("Org") "Customize"
13677 `(["Browse Org group" org-customize t]
13678 "--"
13679 ,(customize-menu-create 'org)
13680 ["Set" Custom-set t]
13681 ["Save" Custom-save t]
13682 ["Reset to Current" Custom-reset-current t]
13683 ["Reset to Saved" Custom-reset-saved t]
13684 ["Reset to Standard Settings" Custom-reset-standard t]))
13685 (message "\"Org\"-menu now contains full customization menu"))
13686 (error "Cannot expand menu (outdated version of cus-edit.el)")))
13688 ;;;; Miscellaneous stuff
13690 ;;; Generally useful functions
13692 (defun org-find-text-property-in-string (prop s)
13693 "Return the first non-nil value of property PROP in string S."
13694 (or (get-text-property 0 prop s)
13695 (get-text-property (or (next-single-property-change 0 prop s) 0)
13696 prop s)))
13698 (defun org-display-warning (message) ;; Copied from Emacs-Muse
13699 "Display the given MESSAGE as a warning."
13700 (if (fboundp 'display-warning)
13701 (display-warning 'org message
13702 (if (featurep 'xemacs)
13703 'warning
13704 :warning))
13705 (let ((buf (get-buffer-create "*Org warnings*")))
13706 (with-current-buffer buf
13707 (goto-char (point-max))
13708 (insert "Warning (Org): " message)
13709 (unless (bolp)
13710 (newline)))
13711 (display-buffer buf)
13712 (sit-for 0))))
13714 (defun org-goto-marker-or-bmk (marker &optional bookmark)
13715 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
13716 (if (and marker (marker-buffer marker)
13717 (buffer-live-p (marker-buffer marker)))
13718 (progn
13719 (switch-to-buffer (marker-buffer marker))
13720 (if (or (> marker (point-max)) (< marker (point-min)))
13721 (widen))
13722 (goto-char marker)
13723 (org-show-context 'org-goto))
13724 (if bookmark
13725 (bookmark-jump bookmark)
13726 (error "Cannot find location"))))
13728 (defun org-quote-csv-field (s)
13729 "Quote field for inclusion in CSV material."
13730 (if (string-match "[\",]" s)
13731 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
13734 (defun org-plist-delete (plist property)
13735 "Delete PROPERTY from PLIST.
13736 This is in contrast to merely setting it to 0."
13737 (let (p)
13738 (while plist
13739 (if (not (eq property (car plist)))
13740 (setq p (plist-put p (car plist) (nth 1 plist))))
13741 (setq plist (cddr plist)))
13744 (defun org-force-self-insert (N)
13745 "Needed to enforce self-insert under remapping."
13746 (interactive "p")
13747 (self-insert-command N))
13749 (defun org-string-width (s)
13750 "Compute width of string, ignoring invisible characters.
13751 This ignores character with invisibility property `org-link', and also
13752 characters with property `org-cwidth', because these will become invisible
13753 upon the next fontification round."
13754 (let (b l)
13755 (when (or (eq t buffer-invisibility-spec)
13756 (assq 'org-link buffer-invisibility-spec))
13757 (while (setq b (text-property-any 0 (length s)
13758 'invisible 'org-link s))
13759 (setq s (concat (substring s 0 b)
13760 (substring s (or (next-single-property-change
13761 b 'invisible s) (length s)))))))
13762 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
13763 (setq s (concat (substring s 0 b)
13764 (substring s (or (next-single-property-change
13765 b 'org-cwidth s) (length s))))))
13766 (setq l (string-width s) b -1)
13767 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
13768 (setq l (- l (get-text-property b 'org-dwidth-n s))))
13771 (defun org-get-indentation (&optional line)
13772 "Get the indentation of the current line, interpreting tabs.
13773 When LINE is given, assume it represents a line and compute its indentation."
13774 (if line
13775 (if (string-match "^ *" (org-remove-tabs line))
13776 (match-end 0))
13777 (save-excursion
13778 (beginning-of-line 1)
13779 (skip-chars-forward " \t")
13780 (current-column))))
13782 (defun org-remove-tabs (s &optional width)
13783 "Replace tabulators in S with spaces.
13784 Assumes that s is a single line, starting in column 0."
13785 (setq width (or width tab-width))
13786 (while (string-match "\t" s)
13787 (setq s (replace-match
13788 (make-string
13789 (- (* width (/ (+ (match-beginning 0) width) width))
13790 (match-beginning 0)) ?\ )
13791 t t s)))
13794 (defun org-fix-indentation (line ind)
13795 "Fix indentation in LINE.
13796 IND is a cons cell with target and minimum indentation.
13797 If the current indentation in LINE is smaller than the minimum,
13798 leave it alone. If it is larger than ind, set it to the target."
13799 (let* ((l (org-remove-tabs line))
13800 (i (org-get-indentation l))
13801 (i1 (car ind)) (i2 (cdr ind)))
13802 (if (>= i i2) (setq l (substring line i2)))
13803 (if (> i1 0)
13804 (concat (make-string i1 ?\ ) l)
13805 l)))
13807 (defun org-base-buffer (buffer)
13808 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
13809 (if (not buffer)
13810 buffer
13811 (or (buffer-base-buffer buffer)
13812 buffer)))
13814 (defun org-trim (s)
13815 "Remove whitespace at beginning and end of string."
13816 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
13817 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
13820 (defun org-wrap (string &optional width lines)
13821 "Wrap string to either a number of lines, or a width in characters.
13822 If WIDTH is non-nil, the string is wrapped to that width, however many lines
13823 that costs. If there is a word longer than WIDTH, the text is actually
13824 wrapped to the length of that word.
13825 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
13826 many lines, whatever width that takes.
13827 The return value is a list of lines, without newlines at the end."
13828 (let* ((words (org-split-string string "[ \t\n]+"))
13829 (maxword (apply 'max (mapcar 'org-string-width words)))
13830 w ll)
13831 (cond (width
13832 (org-do-wrap words (max maxword width)))
13833 (lines
13834 (setq w maxword)
13835 (setq ll (org-do-wrap words maxword))
13836 (if (<= (length ll) lines)
13838 (setq ll words)
13839 (while (> (length ll) lines)
13840 (setq w (1+ w))
13841 (setq ll (org-do-wrap words w)))
13842 ll))
13843 (t (error "Cannot wrap this")))))
13845 (defun org-do-wrap (words width)
13846 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
13847 (let (lines line)
13848 (while words
13849 (setq line (pop words))
13850 (while (and words (< (+ (length line) (length (car words))) width))
13851 (setq line (concat line " " (pop words))))
13852 (setq lines (push line lines)))
13853 (nreverse lines)))
13855 (defun org-split-string (string &optional separators)
13856 "Splits STRING into substrings at SEPARATORS.
13857 No empty strings are returned if there are matches at the beginning
13858 and end of string."
13859 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
13860 (start 0)
13861 notfirst
13862 (list nil))
13863 (while (and (string-match rexp string
13864 (if (and notfirst
13865 (= start (match-beginning 0))
13866 (< start (length string)))
13867 (1+ start) start))
13868 (< (match-beginning 0) (length string)))
13869 (setq notfirst t)
13870 (or (eq (match-beginning 0) 0)
13871 (and (eq (match-beginning 0) (match-end 0))
13872 (eq (match-beginning 0) start))
13873 (setq list
13874 (cons (substring string start (match-beginning 0))
13875 list)))
13876 (setq start (match-end 0)))
13877 (or (eq start (length string))
13878 (setq list
13879 (cons (substring string start)
13880 list)))
13881 (nreverse list)))
13883 (defun org-context ()
13884 "Return a list of contexts of the current cursor position.
13885 If several contexts apply, all are returned.
13886 Each context entry is a list with a symbol naming the context, and
13887 two positions indicating start and end of the context. Possible
13888 contexts are:
13890 :headline anywhere in a headline
13891 :headline-stars on the leading stars in a headline
13892 :todo-keyword on a TODO keyword (including DONE) in a headline
13893 :tags on the TAGS in a headline
13894 :priority on the priority cookie in a headline
13895 :item on the first line of a plain list item
13896 :item-bullet on the bullet/number of a plain list item
13897 :checkbox on the checkbox in a plain list item
13898 :table in an org-mode table
13899 :table-special on a special filed in a table
13900 :table-table in a table.el table
13901 :link on a hyperlink
13902 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
13903 :target on a <<target>>
13904 :radio-target on a <<<radio-target>>>
13905 :latex-fragment on a LaTeX fragment
13906 :latex-preview on a LaTeX fragment with overlayed preview image
13908 This function expects the position to be visible because it uses font-lock
13909 faces as a help to recognize the following contexts: :table-special, :link,
13910 and :keyword."
13911 (let* ((f (get-text-property (point) 'face))
13912 (faces (if (listp f) f (list f)))
13913 (p (point)) clist o)
13914 ;; First the large context
13915 (cond
13916 ((org-on-heading-p t)
13917 (push (list :headline (point-at-bol) (point-at-eol)) clist)
13918 (when (progn
13919 (beginning-of-line 1)
13920 (looking-at org-todo-line-tags-regexp))
13921 (push (org-point-in-group p 1 :headline-stars) clist)
13922 (push (org-point-in-group p 2 :todo-keyword) clist)
13923 (push (org-point-in-group p 4 :tags) clist))
13924 (goto-char p)
13925 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
13926 (if (looking-at "\\[#[A-Z0-9]\\]")
13927 (push (org-point-in-group p 0 :priority) clist)))
13929 ((org-at-item-p)
13930 (push (org-point-in-group p 2 :item-bullet) clist)
13931 (push (list :item (point-at-bol)
13932 (save-excursion (org-end-of-item) (point)))
13933 clist)
13934 (and (org-at-item-checkbox-p)
13935 (push (org-point-in-group p 0 :checkbox) clist)))
13937 ((org-at-table-p)
13938 (push (list :table (org-table-begin) (org-table-end)) clist)
13939 (if (memq 'org-formula faces)
13940 (push (list :table-special
13941 (previous-single-property-change p 'face)
13942 (next-single-property-change p 'face)) clist)))
13943 ((org-at-table-p 'any)
13944 (push (list :table-table) clist)))
13945 (goto-char p)
13947 ;; Now the small context
13948 (cond
13949 ((org-at-timestamp-p)
13950 (push (org-point-in-group p 0 :timestamp) clist))
13951 ((memq 'org-link faces)
13952 (push (list :link
13953 (previous-single-property-change p 'face)
13954 (next-single-property-change p 'face)) clist))
13955 ((memq 'org-special-keyword faces)
13956 (push (list :keyword
13957 (previous-single-property-change p 'face)
13958 (next-single-property-change p 'face)) clist))
13959 ((org-on-target-p)
13960 (push (org-point-in-group p 0 :target) clist)
13961 (goto-char (1- (match-beginning 0)))
13962 (if (looking-at org-radio-target-regexp)
13963 (push (org-point-in-group p 0 :radio-target) clist))
13964 (goto-char p))
13965 ((setq o (car (delq nil
13966 (mapcar
13967 (lambda (x)
13968 (if (memq x org-latex-fragment-image-overlays) x))
13969 (org-overlays-at (point))))))
13970 (push (list :latex-fragment
13971 (org-overlay-start o) (org-overlay-end o)) clist)
13972 (push (list :latex-preview
13973 (org-overlay-start o) (org-overlay-end o)) clist))
13974 ((org-inside-LaTeX-fragment-p)
13975 ;; FIXME: positions wrong.
13976 (push (list :latex-fragment (point) (point)) clist)))
13978 (setq clist (nreverse (delq nil clist)))
13979 clist))
13981 ;; FIXME: Compare with at-regexp-p Do we need both?
13982 (defun org-in-regexp (re &optional nlines visually)
13983 "Check if point is inside a match of regexp.
13984 Normally only the current line is checked, but you can include NLINES extra
13985 lines both before and after point into the search.
13986 If VISUALLY is set, require that the cursor is not after the match but
13987 really on, so that the block visually is on the match."
13988 (catch 'exit
13989 (let ((pos (point))
13990 (eol (point-at-eol (+ 1 (or nlines 0))))
13991 (inc (if visually 1 0)))
13992 (save-excursion
13993 (beginning-of-line (- 1 (or nlines 0)))
13994 (while (re-search-forward re eol t)
13995 (if (and (<= (match-beginning 0) pos)
13996 (>= (+ inc (match-end 0)) pos))
13997 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
13999 (defun org-at-regexp-p (regexp)
14000 "Is point inside a match of REGEXP in the current line?"
14001 (catch 'exit
14002 (save-excursion
14003 (let ((pos (point)) (end (point-at-eol)))
14004 (beginning-of-line 1)
14005 (while (re-search-forward regexp end t)
14006 (if (and (<= (match-beginning 0) pos)
14007 (>= (match-end 0) pos))
14008 (throw 'exit t)))
14009 nil))))
14011 (defun org-occur-in-agenda-files (regexp &optional nlines)
14012 "Call `multi-occur' with buffers for all agenda files."
14013 (interactive "sOrg-files matching: \np")
14014 (let* ((files (org-agenda-files))
14015 (tnames (mapcar 'file-truename files))
14016 (extra org-agenda-text-search-extra-files)
14018 (when (eq (car extra) 'agenda-archives)
14019 (setq extra (cdr extra))
14020 (setq files (org-add-archive-files files)))
14021 (while (setq f (pop extra))
14022 (unless (member (file-truename f) tnames)
14023 (add-to-list 'files f 'append)
14024 (add-to-list 'tnames (file-truename f) 'append)))
14025 (multi-occur
14026 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
14027 regexp)))
14029 (if (boundp 'occur-mode-find-occurrence-hook)
14030 ;; Emacs 23
14031 (add-hook 'occur-mode-find-occurrence-hook
14032 (lambda ()
14033 (when (org-mode-p)
14034 (org-reveal))))
14035 ;; Emacs 22
14036 (defadvice occur-mode-goto-occurrence
14037 (after org-occur-reveal activate)
14038 (and (org-mode-p) (org-reveal)))
14039 (defadvice occur-mode-goto-occurrence-other-window
14040 (after org-occur-reveal activate)
14041 (and (org-mode-p) (org-reveal)))
14042 (defadvice occur-mode-display-occurrence
14043 (after org-occur-reveal activate)
14044 (when (org-mode-p)
14045 (let ((pos (occur-mode-find-occurrence)))
14046 (with-current-buffer (marker-buffer pos)
14047 (save-excursion
14048 (goto-char pos)
14049 (org-reveal)))))))
14051 (defun org-uniquify (list)
14052 "Remove duplicate elements from LIST."
14053 (let (res)
14054 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
14055 res))
14057 (defun org-delete-all (elts list)
14058 "Remove all elements in ELTS from LIST."
14059 (while elts
14060 (setq list (delete (pop elts) list)))
14061 list)
14063 (defun org-back-over-empty-lines ()
14064 "Move backwards over whitespace, to the beginning of the first empty line.
14065 Returns the number of empty lines passed."
14066 (let ((pos (point)))
14067 (skip-chars-backward " \t\n\r")
14068 (beginning-of-line 2)
14069 (goto-char (min (point) pos))
14070 (count-lines (point) pos)))
14072 (defun org-skip-whitespace ()
14073 (skip-chars-forward " \t\n\r"))
14075 (defun org-point-in-group (point group &optional context)
14076 "Check if POINT is in match-group GROUP.
14077 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
14078 match. If the match group does ot exist or point is not inside it,
14079 return nil."
14080 (and (match-beginning group)
14081 (>= point (match-beginning group))
14082 (<= point (match-end group))
14083 (if context
14084 (list context (match-beginning group) (match-end group))
14085 t)))
14087 (defun org-switch-to-buffer-other-window (&rest args)
14088 "Switch to buffer in a second window on the current frame.
14089 In particular, do not allow pop-up frames."
14090 (let (pop-up-frames special-display-buffer-names special-display-regexps
14091 special-display-function)
14092 (apply 'switch-to-buffer-other-window args)))
14094 (defun org-combine-plists (&rest plists)
14095 "Create a single property list from all plists in PLISTS.
14096 The process starts by copying the first list, and then setting properties
14097 from the other lists. Settings in the last list are the most significant
14098 ones and overrule settings in the other lists."
14099 (let ((rtn (copy-sequence (pop plists)))
14100 p v ls)
14101 (while plists
14102 (setq ls (pop plists))
14103 (while ls
14104 (setq p (pop ls) v (pop ls))
14105 (setq rtn (plist-put rtn p v))))
14106 rtn))
14108 (defun org-move-line-down (arg)
14109 "Move the current line down. With prefix argument, move it past ARG lines."
14110 (interactive "p")
14111 (let ((col (current-column))
14112 beg end pos)
14113 (beginning-of-line 1) (setq beg (point))
14114 (beginning-of-line 2) (setq end (point))
14115 (beginning-of-line (+ 1 arg))
14116 (setq pos (move-marker (make-marker) (point)))
14117 (insert (delete-and-extract-region beg end))
14118 (goto-char pos)
14119 (org-move-to-column col)))
14121 (defun org-move-line-up (arg)
14122 "Move the current line up. With prefix argument, move it past ARG lines."
14123 (interactive "p")
14124 (let ((col (current-column))
14125 beg end pos)
14126 (beginning-of-line 1) (setq beg (point))
14127 (beginning-of-line 2) (setq end (point))
14128 (beginning-of-line (- arg))
14129 (setq pos (move-marker (make-marker) (point)))
14130 (insert (delete-and-extract-region beg end))
14131 (goto-char pos)
14132 (org-move-to-column col)))
14134 (defun org-replace-escapes (string table)
14135 "Replace %-escapes in STRING with values in TABLE.
14136 TABLE is an association list with keys like \"%a\" and string values.
14137 The sequences in STRING may contain normal field width and padding information,
14138 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
14139 so values can contain further %-escapes if they are define later in TABLE."
14140 (let ((case-fold-search nil)
14141 e re rpl)
14142 (while (setq e (pop table))
14143 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
14144 (while (string-match re string)
14145 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
14146 (cdr e)))
14147 (setq string (replace-match rpl t t string))))
14148 string))
14151 (defun org-sublist (list start end)
14152 "Return a section of LIST, from START to END.
14153 Counting starts at 1."
14154 (let (rtn (c start))
14155 (setq list (nthcdr (1- start) list))
14156 (while (and list (<= c end))
14157 (push (pop list) rtn)
14158 (setq c (1+ c)))
14159 (nreverse rtn)))
14161 (defun org-find-base-buffer-visiting (file)
14162 "Like `find-buffer-visiting' but alway return the base buffer and
14163 not an indirect buffer."
14164 (let ((buf (find-buffer-visiting file)))
14165 (if buf
14166 (or (buffer-base-buffer buf) buf)
14167 nil)))
14169 (defun org-image-file-name-regexp (&optional extensions)
14170 "Return regexp matching the file names of images.
14171 If EXTENSIONS is given, only match these."
14172 (if (and (not extensions) (fboundp 'image-file-name-regexp))
14173 (image-file-name-regexp)
14174 (let ((image-file-name-extensions
14175 (or extensions
14176 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
14177 "xbm" "xpm" "pbm" "pgm" "ppm"))))
14178 (concat "\\."
14179 (regexp-opt (nconc (mapcar 'upcase
14180 image-file-name-extensions)
14181 image-file-name-extensions)
14183 "\\'"))))
14185 (defun org-file-image-p (file &optional extensions)
14186 "Return non-nil if FILE is an image."
14187 (save-match-data
14188 (string-match (org-image-file-name-regexp extensions) file)))
14190 (defun org-get-cursor-date ()
14191 "Return the date at cursor in as a time.
14192 This works in the calendar and in the agenda, anywhere else it just
14193 returns the current time."
14194 (let (date day defd)
14195 (cond
14196 ((eq major-mode 'calendar-mode)
14197 (setq date (calendar-cursor-to-date)
14198 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14199 ((eq major-mode 'org-agenda-mode)
14200 (setq day (get-text-property (point) 'day))
14201 (if day
14202 (setq date (calendar-gregorian-from-absolute day)
14203 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
14204 (nth 2 date))))))
14205 (or defd (current-time))))
14207 (defvar org-agenda-action-marker (make-marker)
14208 "Marker pointing to the entry for the next agenda action.")
14210 (defun org-mark-entry-for-agenda-action ()
14211 "Mark the current entry as target of an agenda action.
14212 Agenda actions are actions executed from the agenda with the key `k',
14213 which make use of the date at the cursor."
14214 (interactive)
14215 (move-marker org-agenda-action-marker
14216 (save-excursion (org-back-to-heading t) (point))
14217 (current-buffer))
14218 (message
14219 "Entry marked for action; press `k' at desired date in agenda or calendar"))
14221 ;;; Paragraph filling stuff.
14222 ;; We want this to be just right, so use the full arsenal.
14224 (defun org-indent-line-function ()
14225 "Indent line like previous, but further if previous was headline or item."
14226 (interactive)
14227 (let* ((pos (point))
14228 (itemp (org-at-item-p))
14229 column bpos bcol tpos tcol bullet btype bullet-type)
14230 ;; Find the previous relevant line
14231 (beginning-of-line 1)
14232 (cond
14233 ((looking-at "#") (setq column 0))
14234 ((looking-at "\\*+ ") (setq column 0))
14236 (beginning-of-line 0)
14237 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
14238 (beginning-of-line 0))
14239 (cond
14240 ((looking-at "\\*+[ \t]+")
14241 (if (not org-adapt-indentation)
14242 (setq column 0)
14243 (goto-char (match-end 0))
14244 (setq column (current-column))))
14245 ((org-in-item-p)
14246 (org-beginning-of-item)
14247 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
14248 (setq bpos (match-beginning 1) tpos (match-end 0)
14249 bcol (progn (goto-char bpos) (current-column))
14250 tcol (progn (goto-char tpos) (current-column))
14251 bullet (match-string 1)
14252 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
14253 (if (> tcol (+ bcol org-description-max-indent))
14254 (setq tcol (+ bcol 5)))
14255 (if (not itemp)
14256 (setq column tcol)
14257 (goto-char pos)
14258 (beginning-of-line 1)
14259 (if (looking-at "\\S-")
14260 (progn
14261 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
14262 (setq bullet (match-string 1)
14263 btype (if (string-match "[0-9]" bullet) "n" bullet))
14264 (setq column (if (equal btype bullet-type) bcol tcol)))
14265 (setq column (org-get-indentation)))))
14266 (t (setq column (org-get-indentation))))))
14267 (goto-char pos)
14268 (if (<= (current-column) (current-indentation))
14269 (org-indent-line-to column)
14270 (save-excursion (org-indent-line-to column)))
14271 (setq column (current-column))
14272 (beginning-of-line 1)
14273 (if (looking-at
14274 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
14275 (replace-match (concat "\\1" (format org-property-format
14276 (match-string 2) (match-string 3)))
14277 t nil))
14278 (org-move-to-column column)))
14280 (defun org-set-autofill-regexps ()
14281 (interactive)
14282 ;; In the paragraph separator we include headlines, because filling
14283 ;; text in a line directly attached to a headline would otherwise
14284 ;; fill the headline as well.
14285 (org-set-local 'comment-start-skip "^#+[ \t]*")
14286 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
14287 ;; The paragraph starter includes hand-formatted lists.
14288 (org-set-local 'paragraph-start
14289 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
14290 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
14291 ;; But only if the user has not turned off tables or fixed-width regions
14292 (org-set-local
14293 'auto-fill-inhibit-regexp
14294 (concat "\\*+ \\|#\\+"
14295 "\\|[ \t]*" org-keyword-time-regexp
14296 (if (or org-enable-table-editor org-enable-fixed-width-editor)
14297 (concat
14298 "\\|[ \t]*["
14299 (if org-enable-table-editor "|" "")
14300 (if org-enable-fixed-width-editor ":" "")
14301 "]"))))
14302 ;; We use our own fill-paragraph function, to make sure that tables
14303 ;; and fixed-width regions are not wrapped. That function will pass
14304 ;; through to `fill-paragraph' when appropriate.
14305 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
14306 ; Adaptive filling: To get full control, first make sure that
14307 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
14308 (org-set-local 'adaptive-fill-regexp "\000")
14309 (org-set-local 'adaptive-fill-function
14310 'org-adaptive-fill-function)
14311 (org-set-local
14312 'align-mode-rules-list
14313 '((org-in-buffer-settings
14314 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
14315 (modes . '(org-mode))))))
14317 (defun org-fill-paragraph (&optional justify)
14318 "Re-align a table, pass through to fill-paragraph if no table."
14319 (let ((table-p (org-at-table-p))
14320 (table.el-p (org-at-table.el-p)))
14321 (cond ((and (equal (char-after (point-at-bol)) ?*)
14322 (save-excursion (goto-char (point-at-bol))
14323 (looking-at outline-regexp)))
14324 t) ; skip headlines
14325 (table.el-p t) ; skip table.el tables
14326 (table-p (org-table-align) t) ; align org-mode tables
14327 (t nil)))) ; call paragraph-fill
14329 ;; For reference, this is the default value of adaptive-fill-regexp
14330 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
14332 (defun org-adaptive-fill-function ()
14333 "Return a fill prefix for org-mode files.
14334 In particular, this makes sure hanging paragraphs for hand-formatted lists
14335 work correctly."
14336 (cond ((looking-at "#[ \t]+")
14337 (match-string 0))
14338 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
14339 (save-excursion
14340 (if (> (match-end 1) (+ (match-beginning 1)
14341 org-description-max-indent))
14342 (goto-char (+ (match-beginning 1) 5))
14343 (goto-char (match-end 0)))
14344 (make-string (current-column) ?\ )))
14345 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
14346 (save-excursion
14347 (goto-char (match-end 0))
14348 (make-string (current-column) ?\ )))
14349 (t nil)))
14351 ;;; Other stuff.
14353 (defun org-toggle-fixed-width-section (arg)
14354 "Toggle the fixed-width export.
14355 If there is no active region, the QUOTE keyword at the current headline is
14356 inserted or removed. When present, it causes the text between this headline
14357 and the next to be exported as fixed-width text, and unmodified.
14358 If there is an active region, this command adds or removes a colon as the
14359 first character of this line. If the first character of a line is a colon,
14360 this line is also exported in fixed-width font."
14361 (interactive "P")
14362 (let* ((cc 0)
14363 (regionp (org-region-active-p))
14364 (beg (if regionp (region-beginning) (point)))
14365 (end (if regionp (region-end)))
14366 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
14367 (case-fold-search nil)
14368 (re "[ \t]*\\(:\\)")
14369 off)
14370 (if regionp
14371 (save-excursion
14372 (goto-char beg)
14373 (setq cc (current-column))
14374 (beginning-of-line 1)
14375 (setq off (looking-at re))
14376 (while (> nlines 0)
14377 (setq nlines (1- nlines))
14378 (beginning-of-line 1)
14379 (cond
14380 (arg
14381 (org-move-to-column cc t)
14382 (insert ":\n")
14383 (forward-line -1))
14384 ((and off (looking-at re))
14385 (replace-match "" t t nil 1))
14386 ((not off) (org-move-to-column cc t) (insert ":")))
14387 (forward-line 1)))
14388 (save-excursion
14389 (org-back-to-heading)
14390 (if (looking-at (concat outline-regexp
14391 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
14392 (replace-match "" t t nil 1)
14393 (if (looking-at outline-regexp)
14394 (progn
14395 (goto-char (match-end 0))
14396 (insert org-quote-string " "))))))))
14398 ;;;; Functions extending outline functionality
14400 (defun org-beginning-of-line (&optional arg)
14401 "Go to the beginning of the current line. If that is invisible, continue
14402 to a visible line beginning. This makes the function of C-a more intuitive.
14403 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
14404 first attempt, and only move to after the tags when the cursor is already
14405 beyond the end of the headline."
14406 (interactive "P")
14407 (let ((pos (point)) refpos)
14408 (beginning-of-line 1)
14409 (if (bobp)
14411 (backward-char 1)
14412 (if (org-invisible-p)
14413 (while (and (not (bobp)) (org-invisible-p))
14414 (backward-char 1)
14415 (beginning-of-line 1))
14416 (forward-char 1)))
14417 (when org-special-ctrl-a/e
14418 (cond
14419 ((and (looking-at org-complex-heading-regexp)
14420 (= (char-after (match-end 1)) ?\ ))
14421 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
14422 (point-at-eol)))
14423 (goto-char
14424 (if (eq org-special-ctrl-a/e t)
14425 (cond ((> pos refpos) refpos)
14426 ((= pos (point)) refpos)
14427 (t (point)))
14428 (cond ((> pos (point)) (point))
14429 ((not (eq last-command this-command)) (point))
14430 (t refpos)))))
14431 ((org-at-item-p)
14432 (goto-char
14433 (if (eq org-special-ctrl-a/e t)
14434 (cond ((> pos (match-end 4)) (match-end 4))
14435 ((= pos (point)) (match-end 4))
14436 (t (point)))
14437 (cond ((> pos (point)) (point))
14438 ((not (eq last-command this-command)) (point))
14439 (t (match-end 4))))))))
14440 (org-no-warnings
14441 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
14443 (defun org-end-of-line (&optional arg)
14444 "Go to the end of the line.
14445 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
14446 first attempt, and only move to after the tags when the cursor is already
14447 beyond the end of the headline."
14448 (interactive "P")
14449 (if (or (not org-special-ctrl-a/e)
14450 (not (org-on-heading-p)))
14451 (end-of-line arg)
14452 (let ((pos (point)))
14453 (beginning-of-line 1)
14454 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
14455 (if (eq org-special-ctrl-a/e t)
14456 (if (or (< pos (match-beginning 1))
14457 (= pos (match-end 0)))
14458 (goto-char (match-beginning 1))
14459 (goto-char (match-end 0)))
14460 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
14461 (goto-char (match-end 0))
14462 (goto-char (match-beginning 1))))
14463 (end-of-line arg))))
14464 (org-no-warnings
14465 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
14468 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
14469 (define-key org-mode-map "\C-e" 'org-end-of-line)
14471 (defun org-kill-line (&optional arg)
14472 "Kill line, to tags or end of line."
14473 (interactive "P")
14474 (cond
14475 ((or (not org-special-ctrl-k)
14476 (bolp)
14477 (not (org-on-heading-p)))
14478 (call-interactively 'kill-line))
14479 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
14480 (kill-region (point) (match-beginning 1))
14481 (org-set-tags nil t))
14482 (t (kill-region (point) (point-at-eol)))))
14484 (define-key org-mode-map "\C-k" 'org-kill-line)
14486 (defun org-yank (&optional arg)
14487 "Yank. If the kill is a subtree, treat it specially.
14488 This command will look at the current kill and check if is a single
14489 subtree, or a series of subtrees[1]. If it passes the test, and if the
14490 cursor is at the beginning of a line or after the stars of a currently
14491 empty headline, then the yank is handled specially. How exactly depends
14492 on the value of the following variables, both set by default.
14494 org-yank-folded-subtrees
14495 When set, the subtree(s) will be folded after insertion, but only
14496 if doing so would now swallow text after the yanked text.
14498 org-yank-adjusted-subtrees
14499 When set, the subtree will be promoted or demoted in order to
14500 fit into the local outline tree structure, which means that the level
14501 will be adjusted so that it becomes the smaller one of the two
14502 *visible* surrounding headings.
14504 Any prefix to this command will cause `yank' to be called directly with
14505 no special treatment. In particular, a simple `C-u' prefix will just
14506 plainly yank the text as it is.
14508 \[1] Basically, the test checks if the first non-white line is a heading
14509 and if there are no other headings with fewer stars."
14510 (interactive "P")
14511 (setq this-command 'yank)
14512 (if arg
14513 (call-interactively 'yank)
14514 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
14515 (and (org-kill-is-subtree-p)
14516 (or (bolp)
14517 (and (looking-at "[ \t]*$")
14518 (string-match
14519 "\\`\\*+\\'"
14520 (buffer-substring (point-at-bol) (point)))))))
14521 swallowp)
14522 (cond
14523 ((and subtreep org-yank-folded-subtrees)
14524 (let ((beg (point))
14525 end)
14526 (if (and subtreep org-yank-adjusted-subtrees)
14527 (org-paste-subtree nil nil 'for-yank)
14528 (call-interactively 'yank))
14529 (setq end (point))
14530 (goto-char beg)
14531 (when (and (bolp) subtreep
14532 (not (setq swallowp
14533 (org-yank-folding-would-swallow-text beg end))))
14534 (or (looking-at outline-regexp)
14535 (re-search-forward (concat "^" outline-regexp) end t))
14536 (while (and (< (point) end) (looking-at outline-regexp))
14537 (hide-subtree)
14538 (org-cycle-show-empty-lines 'folded)
14539 (condition-case nil
14540 (outline-forward-same-level 1)
14541 (error (goto-char end)))))
14542 (when swallowp
14543 (message
14544 "Yanked text not folded because that would swallow text"))
14545 (goto-char end)
14546 (skip-chars-forward " \t\n\r")
14547 (beginning-of-line 1)
14548 (push-mark beg 'nomsg)))
14549 ((and subtreep org-yank-adjusted-subtrees)
14550 (let ((beg (point-at-bol)))
14551 (org-paste-subtree nil nil 'for-yank)
14552 (push-mark beg 'nomsg)))
14554 (call-interactively 'yank))))))
14556 (defun org-yank-folding-would-swallow-text (beg end)
14557 "Would hide-subtree at BEG swallow any text after END?"
14558 (let (level)
14559 (save-excursion
14560 (goto-char beg)
14561 (when (or (looking-at outline-regexp)
14562 (re-search-forward (concat "^" outline-regexp) end t))
14563 (setq level (org-outline-level)))
14564 (goto-char end)
14565 (skip-chars-forward " \t\r\n\v\f")
14566 (if (or (eobp)
14567 (and (bolp) (looking-at org-outline-regexp)
14568 (<= (org-outline-level) level)))
14569 nil ; Nothing would be swallowed
14570 t)))) ; something would swallow
14572 (define-key org-mode-map "\C-y" 'org-yank)
14574 (defun org-invisible-p ()
14575 "Check if point is at a character currently not visible."
14576 ;; Early versions of noutline don't have `outline-invisible-p'.
14577 (if (fboundp 'outline-invisible-p)
14578 (outline-invisible-p)
14579 (get-char-property (point) 'invisible)))
14581 (defun org-invisible-p2 ()
14582 "Check if point is at a character currently not visible."
14583 (save-excursion
14584 (if (and (eolp) (not (bobp))) (backward-char 1))
14585 ;; Early versions of noutline don't have `outline-invisible-p'.
14586 (if (fboundp 'outline-invisible-p)
14587 (outline-invisible-p)
14588 (get-char-property (point) 'invisible))))
14590 (defun org-back-to-heading (&optional invisible-ok)
14591 "Call `outline-back-to-heading', but provide a better error message."
14592 (condition-case nil
14593 (outline-back-to-heading invisible-ok)
14594 (error (error "Before first headline at position %d in buffer %s"
14595 (point) (current-buffer)))))
14597 (defun org-before-first-heading-p ()
14598 "Before first heading?"
14599 (save-excursion
14600 (null (re-search-backward "^\\*+ " nil t))))
14602 (defalias 'org-on-heading-p 'outline-on-heading-p)
14603 (defalias 'org-at-heading-p 'outline-on-heading-p)
14604 (defun org-at-heading-or-item-p ()
14605 (or (org-on-heading-p) (org-at-item-p)))
14607 (defun org-on-target-p ()
14608 (or (org-in-regexp org-radio-target-regexp)
14609 (org-in-regexp org-target-regexp)))
14611 (defun org-up-heading-all (arg)
14612 "Move to the heading line of which the present line is a subheading.
14613 This function considers both visible and invisible heading lines.
14614 With argument, move up ARG levels."
14615 (if (fboundp 'outline-up-heading-all)
14616 (outline-up-heading-all arg) ; emacs 21 version of outline.el
14617 (outline-up-heading arg t))) ; emacs 22 version of outline.el
14619 (defun org-up-heading-safe ()
14620 "Move to the heading line of which the present line is a subheading.
14621 This version will not throw an error. It will return the level of the
14622 headline found, or nil if no higher level is found."
14623 (let (start-level re)
14624 (org-back-to-heading t)
14625 (setq start-level (funcall outline-level))
14626 (if (equal start-level 1)
14628 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
14629 (if (re-search-backward re nil t)
14630 (funcall outline-level)))))
14632 (defun org-first-sibling-p ()
14633 "Is this heading the first child of its parents?"
14634 (interactive)
14635 (let ((re (concat "^" outline-regexp))
14636 level l)
14637 (unless (org-at-heading-p t)
14638 (error "Not at a heading"))
14639 (setq level (funcall outline-level))
14640 (save-excursion
14641 (if (not (re-search-backward re nil t))
14643 (setq l (funcall outline-level))
14644 (< l level)))))
14646 (defun org-goto-sibling (&optional previous)
14647 "Goto the next sibling, even if it is invisible.
14648 When PREVIOUS is set, go to the previous sibling instead. Returns t
14649 when a sibling was found. When none is found, return nil and don't
14650 move point."
14651 (let ((fun (if previous 're-search-backward 're-search-forward))
14652 (pos (point))
14653 (re (concat "^" outline-regexp))
14654 level l)
14655 (when (condition-case nil (org-back-to-heading t) (error nil))
14656 (setq level (funcall outline-level))
14657 (catch 'exit
14658 (or previous (forward-char 1))
14659 (while (funcall fun re nil t)
14660 (setq l (funcall outline-level))
14661 (when (< l level) (goto-char pos) (throw 'exit nil))
14662 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
14663 (goto-char pos)
14664 nil))))
14666 (defun org-show-siblings ()
14667 "Show all siblings of the current headline."
14668 (save-excursion
14669 (while (org-goto-sibling) (org-flag-heading nil)))
14670 (save-excursion
14671 (while (org-goto-sibling 'previous)
14672 (org-flag-heading nil))))
14674 (defun org-show-hidden-entry ()
14675 "Show an entry where even the heading is hidden."
14676 (save-excursion
14677 (org-show-entry)))
14679 (defun org-flag-heading (flag &optional entry)
14680 "Flag the current heading. FLAG non-nil means make invisible.
14681 When ENTRY is non-nil, show the entire entry."
14682 (save-excursion
14683 (org-back-to-heading t)
14684 ;; Check if we should show the entire entry
14685 (if entry
14686 (progn
14687 (org-show-entry)
14688 (save-excursion
14689 (and (outline-next-heading)
14690 (org-flag-heading nil))))
14691 (outline-flag-region (max (point-min) (1- (point)))
14692 (save-excursion (outline-end-of-heading) (point))
14693 flag))))
14695 (defun org-forward-same-level (arg)
14696 "Move forward to the ARG'th subheading at same level as this one.
14697 Stop at the first and last subheadings of a superior heading.
14698 This is like outline-forward-same-level, but invisible headings are ok."
14699 (interactive "p")
14700 (org-back-to-heading t)
14701 (while (> arg 0)
14702 (let ((point-to-move-to (save-excursion
14703 (org-get-next-sibling))))
14704 (if point-to-move-to
14705 (progn
14706 (goto-char point-to-move-to)
14707 (setq arg (1- arg)))
14708 (progn
14709 (setq arg 0)
14710 (error "No following same-level heading"))))))
14712 (defun org-get-next-sibling ()
14713 "Move to next heading of the same level, and return point.
14714 If there is no such heading, return nil.
14715 This is like outline-next-sibling, but invisible headings are ok."
14716 (let ((level (funcall outline-level)))
14717 (outline-next-heading)
14718 (while (and (not (eobp)) (> (funcall outline-level) level))
14719 (outline-next-heading))
14720 (if (or (eobp) (< (funcall outline-level) level))
14722 (point))))
14724 (defun org-end-of-subtree (&optional invisible-OK to-heading)
14725 ;; This is an exact copy of the original function, but it uses
14726 ;; `org-back-to-heading', to make it work also in invisible
14727 ;; trees. And is uses an invisible-OK argument.
14728 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
14729 (org-back-to-heading invisible-OK)
14730 (let ((first t)
14731 (level (funcall outline-level)))
14732 (while (and (not (eobp))
14733 (or first (> (funcall outline-level) level)))
14734 (setq first nil)
14735 (outline-next-heading))
14736 (unless to-heading
14737 (if (memq (preceding-char) '(?\n ?\^M))
14738 (progn
14739 ;; Go to end of line before heading
14740 (forward-char -1)
14741 (if (memq (preceding-char) '(?\n ?\^M))
14742 ;; leave blank line before heading
14743 (forward-char -1))))))
14744 (point))
14746 (defun org-show-subtree ()
14747 "Show everything after this heading at deeper levels."
14748 (outline-flag-region
14749 (point)
14750 (save-excursion
14751 (outline-end-of-subtree) (outline-next-heading) (point))
14752 nil))
14754 (defun org-show-entry ()
14755 "Show the body directly following this heading.
14756 Show the heading too, if it is currently invisible."
14757 (interactive)
14758 (save-excursion
14759 (condition-case nil
14760 (progn
14761 (org-back-to-heading t)
14762 (outline-flag-region
14763 (max (point-min) (1- (point)))
14764 (save-excursion
14765 (re-search-forward
14766 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
14767 (or (match-beginning 1) (point-max)))
14768 nil))
14769 (error nil))))
14771 (defun org-make-options-regexp (kwds)
14772 "Make a regular expression for keyword lines."
14773 (concat
14775 "#?[ \t]*\\+\\("
14776 (mapconcat 'regexp-quote kwds "\\|")
14777 "\\):[ \t]*"
14778 "\\(.+\\)"))
14780 ;; Make isearch reveal the necessary context
14781 (defun org-isearch-end ()
14782 "Reveal context after isearch exits."
14783 (when isearch-success ; only if search was successful
14784 (if (featurep 'xemacs)
14785 ;; Under XEmacs, the hook is run in the correct place,
14786 ;; we directly show the context.
14787 (org-show-context 'isearch)
14788 ;; In Emacs the hook runs *before* restoring the overlays.
14789 ;; So we have to use a one-time post-command-hook to do this.
14790 ;; (Emacs 22 has a special variable, see function `org-mode')
14791 (unless (and (boundp 'isearch-mode-end-hook-quit)
14792 isearch-mode-end-hook-quit)
14793 ;; Only when the isearch was not quitted.
14794 (org-add-hook 'post-command-hook 'org-isearch-post-command
14795 'append 'local)))))
14797 (defun org-isearch-post-command ()
14798 "Remove self from hook, and show context."
14799 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
14800 (org-show-context 'isearch))
14803 ;;;; Integration with and fixes for other packages
14805 ;;; Imenu support
14807 (defvar org-imenu-markers nil
14808 "All markers currently used by Imenu.")
14809 (make-variable-buffer-local 'org-imenu-markers)
14811 (defun org-imenu-new-marker (&optional pos)
14812 "Return a new marker for use by Imenu, and remember the marker."
14813 (let ((m (make-marker)))
14814 (move-marker m (or pos (point)))
14815 (push m org-imenu-markers)
14818 (defun org-imenu-get-tree ()
14819 "Produce the index for Imenu."
14820 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
14821 (setq org-imenu-markers nil)
14822 (let* ((n org-imenu-depth)
14823 (re (concat "^" outline-regexp))
14824 (subs (make-vector (1+ n) nil))
14825 (last-level 0)
14826 m tree level head)
14827 (save-excursion
14828 (save-restriction
14829 (widen)
14830 (goto-char (point-max))
14831 (while (re-search-backward re nil t)
14832 (setq level (org-reduced-level (funcall outline-level)))
14833 (when (<= level n)
14834 (looking-at org-complex-heading-regexp)
14835 (setq head (org-link-display-format
14836 (org-match-string-no-properties 4))
14837 m (org-imenu-new-marker))
14838 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
14839 (if (>= level last-level)
14840 (push (cons head m) (aref subs level))
14841 (push (cons head (aref subs (1+ level))) (aref subs level))
14842 (loop for i from (1+ level) to n do (aset subs i nil)))
14843 (setq last-level level)))))
14844 (aref subs 1)))
14846 (eval-after-load "imenu"
14847 '(progn
14848 (add-hook 'imenu-after-jump-hook
14849 (lambda ()
14850 (if (eq major-mode 'org-mode)
14851 (org-show-context 'org-goto))))))
14853 (defun org-link-display-format (link)
14854 "Replace a link with either the description, or the link target
14855 if no description is present"
14856 (save-match-data
14857 (if (string-match org-bracket-link-analytic-regexp link)
14858 (replace-match (or (match-string 5 link)
14859 (concat (match-string 1 link)
14860 (match-string 3 link)))
14861 nil nil link)
14862 link)))
14864 ;; Speedbar support
14866 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
14867 "Overlay marking the agenda restriction line in speedbar.")
14868 (org-overlay-put org-speedbar-restriction-lock-overlay
14869 'face 'org-agenda-restriction-lock)
14870 (org-overlay-put org-speedbar-restriction-lock-overlay
14871 'help-echo "Agendas are currently limited to this item.")
14872 (org-detach-overlay org-speedbar-restriction-lock-overlay)
14874 (defun org-speedbar-set-agenda-restriction ()
14875 "Restrict future agenda commands to the location at point in speedbar.
14876 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
14877 (interactive)
14878 (require 'org-agenda)
14879 (let (p m tp np dir txt w)
14880 (cond
14881 ((setq p (text-property-any (point-at-bol) (point-at-eol)
14882 'org-imenu t))
14883 (setq m (get-text-property p 'org-imenu-marker))
14884 (save-excursion
14885 (save-restriction
14886 (set-buffer (marker-buffer m))
14887 (goto-char m)
14888 (org-agenda-set-restriction-lock 'subtree))))
14889 ((setq p (text-property-any (point-at-bol) (point-at-eol)
14890 'speedbar-function 'speedbar-find-file))
14891 (setq tp (previous-single-property-change
14892 (1+ p) 'speedbar-function)
14893 np (next-single-property-change
14894 tp 'speedbar-function)
14895 dir (speedbar-line-directory)
14896 txt (buffer-substring-no-properties (or tp (point-min))
14897 (or np (point-max))))
14898 (save-excursion
14899 (save-restriction
14900 (set-buffer (find-file-noselect
14901 (let ((default-directory dir))
14902 (expand-file-name txt))))
14903 (unless (org-mode-p)
14904 (error "Cannot restrict to non-Org-mode file"))
14905 (org-agenda-set-restriction-lock 'file))))
14906 (t (error "Don't know how to restrict Org-mode's agenda")))
14907 (org-move-overlay org-speedbar-restriction-lock-overlay
14908 (point-at-bol) (point-at-eol))
14909 (setq current-prefix-arg nil)
14910 (org-agenda-maybe-redo)))
14912 (eval-after-load "speedbar"
14913 '(progn
14914 (speedbar-add-supported-extension ".org")
14915 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
14916 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
14917 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
14918 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
14919 (add-hook 'speedbar-visiting-tag-hook
14920 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
14923 ;;; Fixes and Hacks for problems with other packages
14925 ;; Make flyspell not check words in links, to not mess up our keymap
14926 (defun org-mode-flyspell-verify ()
14927 "Don't let flyspell put overlays at active buttons."
14928 (not (get-text-property (point) 'keymap)))
14930 ;; Make `bookmark-jump' show the jump location if it was hidden.
14931 (eval-after-load "bookmark"
14932 '(if (boundp 'bookmark-after-jump-hook)
14933 ;; We can use the hook
14934 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
14935 ;; Hook not available, use advice
14936 (defadvice bookmark-jump (after org-make-visible activate)
14937 "Make the position visible."
14938 (org-bookmark-jump-unhide))))
14940 ;; Make sure saveplace show the location if it was hidden
14941 (eval-after-load "saveplace"
14942 '(defadvice save-place-find-file-hook (after org-make-visible activate)
14943 "Make the position visible."
14944 (org-bookmark-jump-unhide)))
14946 (defun org-bookmark-jump-unhide ()
14947 "Unhide the current position, to show the bookmark location."
14948 (and (org-mode-p)
14949 (or (org-invisible-p)
14950 (save-excursion (goto-char (max (point-min) (1- (point))))
14951 (org-invisible-p)))
14952 (org-show-context 'bookmark-jump)))
14954 ;; Make session.el ignore our circular variable
14955 (eval-after-load "session"
14956 '(add-to-list 'session-globals-exclude 'org-mark-ring))
14958 ;;;; Experimental code
14960 (defun org-closed-in-range ()
14961 "Sparse tree of items closed in a certain time range.
14962 Still experimental, may disappear in the future."
14963 (interactive)
14964 ;; Get the time interval from the user.
14965 (let* ((time1 (time-to-seconds
14966 (org-read-date nil 'to-time nil "Starting date: ")))
14967 (time2 (time-to-seconds
14968 (org-read-date nil 'to-time nil "End date:")))
14969 ;; callback function
14970 (callback (lambda ()
14971 (let ((time
14972 (time-to-seconds
14973 (apply 'encode-time
14974 (org-parse-time-string
14975 (match-string 1))))))
14976 ;; check if time in interval
14977 (and (>= time time1) (<= time time2))))))
14978 ;; make tree, check each match with the callback
14979 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
14982 ;;;; Finish up
14984 (provide 'org)
14986 (run-hooks 'org-load-hook)
14988 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
14990 ;;; org.el ends here