Release 6.25f
[org-mode/org-tableheadings.git] / lisp / org.el
blobc92da54556a4b6850394ebc8d6bb19543166de82
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
4 ;; Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Keywords: outlines, hypermedia, calendar, wp
8 ;; Homepage: http://orgmode.org
9 ;; Version: 6.25f
11 ;; This file is part of GNU Emacs.
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;; Commentary:
29 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
30 ;; project planning with a fast and effective plain-text system.
32 ;; Org-mode develops organizational tasks around NOTES files that contain
33 ;; information about projects as plain text. Org-mode is implemented on
34 ;; top of outline-mode, which makes it possible to keep the content of
35 ;; large files well structured. Visibility cycling and structure editing
36 ;; help to work with the tree. Tables are easily created with a built-in
37 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
38 ;; and scheduling. It dynamically compiles entries into an agenda that
39 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
40 ;; Plain text URL-like links connect to websites, emails, Usenet
41 ;; messages, BBDB entries, and any files related to the projects. For
42 ;; printing and sharing of notes, an Org-mode file can be exported as a
43 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
44 ;; iCalendar file. It can also serve as a publishing tool for a set of
45 ;; linked webpages.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org-mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org-mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the etc/ directory of Emacs 22.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
64 ;;; Code:
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
69 (make-variable-buffer-local 'org-table-formula-constants-local)
71 ;;;; Require other packages
73 (eval-when-compile
74 (require 'cl)
75 (require 'gnus-sum)
76 (require 'calendar))
77 ;; For XEmacs, noutline is not yet provided by outline.el, so arrange for
78 ;; the file noutline.el being loaded.
79 (if (featurep 'xemacs) (condition-case nil (require 'noutline)))
80 ;; We require noutline, which might be provided in outline.el
81 (require 'outline) (require 'noutline)
82 ;; Other stuff we need.
83 (require 'time-date)
84 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
85 (require 'easymenu)
87 (require 'org-macs)
88 (require 'org-compat)
89 (require 'org-faces)
90 (require 'org-list)
91 (require 'org-footnote)
93 ;;;; Customization variables
95 ;;; Version
97 (defconst org-version "6.25f"
98 "The version number of the file org.el.")
100 (defun org-version (&optional here)
101 "Show the org-mode version in the echo area.
102 With prefix arg HERE, insert it at point."
103 (interactive "P")
104 (let ((version (format "Org-mode version %s" org-version)))
105 (message version)
106 (if here
107 (insert version))))
109 ;;; Compatibility constants
111 ;;; The custom variables
113 (defgroup org nil
114 "Outline-based notes management and organizer."
115 :tag "Org"
116 :group 'outlines
117 :group 'hypermedia
118 :group 'calendar)
120 (defcustom org-load-hook nil
121 "Hook that is run after org.el has been loaded."
122 :group 'org
123 :type 'hook)
125 (defvar org-modules) ; defined below
126 (defvar org-modules-loaded nil
127 "Have the modules been loaded already?")
129 (defun org-load-modules-maybe (&optional force)
130 "Load all extensions listed in `org-modules'."
131 (when (or force (not org-modules-loaded))
132 (mapc (lambda (ext)
133 (condition-case nil (require ext)
134 (error (message "Problems while trying to load feature `%s'" ext))))
135 org-modules)
136 (setq org-modules-loaded t)))
138 (defun org-set-modules (var value)
139 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
140 (set var value)
141 (when (featurep 'org)
142 (org-load-modules-maybe 'force)))
144 (when (org-bound-and-true-p org-modules)
145 (let ((a (member 'org-infojs org-modules)))
146 (and a (setcar a 'org-jsinfo))))
148 (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)
149 "Modules that should always be loaded together with org.el.
150 If a description starts with <C>, the file is not part of Emacs
151 and loading it will require that you have downloaded and properly installed
152 the org-mode distribution.
154 You can also use this system to load external packages (i.e. neither Org
155 core modules, not modules from the CONTRIB directory). Just add symbols
156 to the end of the list. If the package is called org-xyz.el, then you need
157 to add the symbol `xyz', and the package must have a call to
159 (provide 'org-xyz)"
160 :group 'org
161 :set 'org-set-modules
162 :type
163 '(set :greedy t
164 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
165 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
166 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
167 (const :tag " id: Global IDs for identifying entries" org-id)
168 (const :tag " info: Links to Info nodes" org-info)
169 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
170 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
171 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
172 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
173 (const :tag " mew Links to Mew folders/messages" org-mew)
174 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
175 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
176 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
177 (const :tag " vm: Links to VM folders/messages" org-vm)
178 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
179 (const :tag " w3m: Special cut/past from w3m to Org." org-w3m)
180 (const :tag " mouse: Additional mouse support" org-mouse)
182 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
183 (const :tag "C annotation-helper: Call Remember directly from Browser" org-annotation-helper)
184 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
185 (const :tag "C browser-url: Store link, directly from Browser" org-browser-url)
186 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
187 (const :tag "C collector: Collect properties into tables" org-collector)
188 (const :tag "C depend: TODO dependencies for Org-mode" org-depend)
189 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
190 (const :tag "C eval: Include command output as text" org-eval)
191 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
192 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
193 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
194 (const :tag "C exp-blocks: Pre-process blocks for export" org-exp-blocks)
195 (const :tag "C interactive-query: Interactive modification of tags query" org-interactive-query)
196 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
197 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
198 (const :tag "C mtags: Support for muse-like tags" org-mtags)
199 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
200 (const :tag "C R: Computation using the R language" org-R)
201 (const :tag "C registry: A registry for Org links" org-registry)
202 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
203 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
204 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
205 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
206 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
208 (defcustom org-support-shift-select nil
209 "Non-nil means, make shift-cursor commands select text when possible.
211 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys start
212 selecting a region, or enlarge thusly regions started in this way.
213 In Org-mode, in special contexts, these same keys are used for other
214 purposes, important enough to compete with shift selection. Org tries
215 to balance these needs by supporting `shift-select-mode' outside these
216 special contexts, under control of this variable.
218 The default of this variable is nil, to avoid confusing behavior. Shifted
219 cursor keys will then execute Org commands in the following contexts:
220 - on a headline, changing TODO state (left/right) and priority (up/down)
221 - on a time stamp, changing the time
222 - in a plain list item, changing the bullet type
223 - in a property definition line, switching between allowed values
224 - in the BEGIN line of a clock table (changing the time block).
225 Outside these contexts, the commands will throw an error.
227 When this variable is t and the cursor is not in a special context,
228 Org-mode will support shift-selection for making and enlarging regions.
229 To make this more effective, the bullet cycling will no longer happen
230 anywhere in an item line, but only if the cursor is exactly on the bullet.
232 If you set this variable to the symbol `always', then the keys
233 will not be special in headlines, property lines, and item lines, to make
234 shift selection work there as well. If this is what you want, you can
235 use the following alternative commands: `C-c C-t' and `C-c ,' to
236 change TODO state and priority, `C-u C-u C-c C-t' can be used to switch
237 TODO sets, `C-c -' to cycle item bullet types, and properties can be
238 edited by hand or in column view.
240 However, when the cursor is on a timestamp, shift-cursor commands
241 will still edit the time stamp - this is just too good to give up.
243 XEmacs user should have this variable set to nil, because shift-select-mode
244 is Emacs 23 only."
245 :group 'org
246 :type '(choice
247 (const :tag "Never" nil)
248 (const :tag "When outside special context" t)
249 (const :tag "Everywhere except timestamps" always)))
251 (defgroup org-startup nil
252 "Options concerning startup of Org-mode."
253 :tag "Org Startup"
254 :group 'org)
256 (defcustom org-startup-folded t
257 "Non-nil means, entering Org-mode will switch to OVERVIEW.
258 This can also be configured on a per-file basis by adding one of
259 the following lines anywhere in the buffer:
261 #+STARTUP: fold
262 #+STARTUP: nofold
263 #+STARTUP: content"
264 :group 'org-startup
265 :type '(choice
266 (const :tag "nofold: show all" nil)
267 (const :tag "fold: overview" t)
268 (const :tag "content: all headlines" content)))
270 (defcustom org-startup-truncated t
271 "Non-nil means, entering Org-mode will set `truncate-lines'.
272 This is useful since some lines containing links can be very long and
273 uninteresting. Also tables look terrible when wrapped."
274 :group 'org-startup
275 :type 'boolean)
277 (defcustom org-startup-align-all-tables nil
278 "Non-nil means, align all tables when visiting a file.
279 This is useful when the column width in tables is forced with <N> cookies
280 in table fields. Such tables will look correct only after the first re-align.
281 This can also be configured on a per-file basis by adding one of
282 the following lines anywhere in the buffer:
283 #+STARTUP: align
284 #+STARTUP: noalign"
285 :group 'org-startup
286 :type 'boolean)
288 (defcustom org-insert-mode-line-in-empty-file nil
289 "Non-nil means insert the first line setting Org-mode in empty files.
290 When the function `org-mode' is called interactively in an empty file, this
291 normally means that the file name does not automatically trigger Org-mode.
292 To ensure that the file will always be in Org-mode in the future, a
293 line enforcing Org-mode will be inserted into the buffer, if this option
294 has been set."
295 :group 'org-startup
296 :type 'boolean)
298 (defcustom org-replace-disputed-keys nil
299 "Non-nil means use alternative key bindings for some keys.
300 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
301 These keys are also used by other packages like shift-selection-mode'
302 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
303 If you want to use Org-mode together with one of these other modes,
304 or more generally if you would like to move some Org-mode commands to
305 other keys, set this variable and configure the keys with the variable
306 `org-disputed-keys'.
308 This option is only relevant at load-time of Org-mode, and must be set
309 *before* org.el is loaded. Changing it requires a restart of Emacs to
310 become effective."
311 :group 'org-startup
312 :type 'boolean)
314 (defcustom org-use-extra-keys nil
315 "Non-nil means use extra key sequence definitions for certain
316 commands. This happens automatically if you run XEmacs or if
317 window-system is nil. This variable lets you do the same
318 manually. You must set it before loading org.
320 Example: on Carbon Emacs 22 running graphically, with an external
321 keyboard on a Powerbook, the default way of setting M-left might
322 not work for either Alt or ESC. Setting this variable will make
323 it work for ESC."
324 :group 'org-startup
325 :type 'boolean)
327 (if (fboundp 'defvaralias)
328 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
330 (defcustom org-disputed-keys
331 '(([(shift up)] . [(meta p)])
332 ([(shift down)] . [(meta n)])
333 ([(shift left)] . [(meta -)])
334 ([(shift right)] . [(meta +)])
335 ([(control shift right)] . [(meta shift +)])
336 ([(control shift left)] . [(meta shift -)]))
337 "Keys for which Org-mode and other modes compete.
338 This is an alist, cars are the default keys, second element specifies
339 the alternative to use when `org-replace-disputed-keys' is t.
341 Keys can be specified in any syntax supported by `define-key'.
342 The value of this option takes effect only at Org-mode's startup,
343 therefore you'll have to restart Emacs to apply it after changing."
344 :group 'org-startup
345 :type 'alist)
347 (defun org-key (key)
348 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
349 Or return the original if not disputed."
350 (if org-replace-disputed-keys
351 (let* ((nkey (key-description key))
352 (x (org-find-if (lambda (x)
353 (equal (key-description (car x)) nkey))
354 org-disputed-keys)))
355 (if x (cdr x) key))
356 key))
358 (defun org-find-if (predicate seq)
359 (catch 'exit
360 (while seq
361 (if (funcall predicate (car seq))
362 (throw 'exit (car seq))
363 (pop seq)))))
365 (defun org-defkey (keymap key def)
366 "Define a key, possibly translated, as returned by `org-key'."
367 (define-key keymap (org-key key) def))
369 (defcustom org-ellipsis nil
370 "The ellipsis to use in the Org-mode outline.
371 When nil, just use the standard three dots. When a string, use that instead,
372 When a face, use the standard 3 dots, but with the specified face.
373 The change affects only Org-mode (which will then use its own display table).
374 Changing this requires executing `M-x org-mode' in a buffer to become
375 effective."
376 :group 'org-startup
377 :type '(choice (const :tag "Default" nil)
378 (face :tag "Face" :value org-warning)
379 (string :tag "String" :value "...#")))
381 (defvar org-display-table nil
382 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
384 (defgroup org-keywords nil
385 "Keywords in Org-mode."
386 :tag "Org Keywords"
387 :group 'org)
389 (defcustom org-deadline-string "DEADLINE:"
390 "String to mark deadline entries.
391 A deadline is this string, followed by a time stamp. Should be a word,
392 terminated by a colon. You can insert a schedule keyword and
393 a timestamp with \\[org-deadline].
394 Changes become only effective after restarting Emacs."
395 :group 'org-keywords
396 :type 'string)
398 (defcustom org-scheduled-string "SCHEDULED:"
399 "String to mark scheduled TODO entries.
400 A schedule is this string, followed by a time stamp. Should be a word,
401 terminated by a colon. You can insert a schedule keyword and
402 a timestamp with \\[org-schedule].
403 Changes become only effective after restarting Emacs."
404 :group 'org-keywords
405 :type 'string)
407 (defcustom org-closed-string "CLOSED:"
408 "String used as the prefix for timestamps logging closing a TODO entry."
409 :group 'org-keywords
410 :type 'string)
412 (defcustom org-clock-string "CLOCK:"
413 "String used as prefix for timestamps clocking work hours on an item."
414 :group 'org-keywords
415 :type 'string)
417 (defcustom org-comment-string "COMMENT"
418 "Entries starting with this keyword will never be exported.
419 An entry can be toggled between COMMENT and normal with
420 \\[org-toggle-comment].
421 Changes become only effective after restarting Emacs."
422 :group 'org-keywords
423 :type 'string)
425 (defcustom org-quote-string "QUOTE"
426 "Entries starting with this keyword will be exported in fixed-width font.
427 Quoting applies only to the text in the entry following the headline, and does
428 not extend beyond the next headline, even if that is lower level.
429 An entry can be toggled between QUOTE and normal with
430 \\[org-toggle-fixed-width-section]."
431 :group 'org-keywords
432 :type 'string)
434 (defconst org-repeat-re
435 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\([.+]?\\+[0-9]+[dwmy]\\)"
436 "Regular expression for specifying repeated events.
437 After a match, group 1 contains the repeat expression.")
439 (defgroup org-structure nil
440 "Options concerning the general structure of Org-mode files."
441 :tag "Org Structure"
442 :group 'org)
444 (defgroup org-reveal-location nil
445 "Options about how to make context of a location visible."
446 :tag "Org Reveal Location"
447 :group 'org-structure)
449 (defconst org-context-choice
450 '(choice
451 (const :tag "Always" t)
452 (const :tag "Never" nil)
453 (repeat :greedy t :tag "Individual contexts"
454 (cons
455 (choice :tag "Context"
456 (const agenda)
457 (const org-goto)
458 (const occur-tree)
459 (const tags-tree)
460 (const link-search)
461 (const mark-goto)
462 (const bookmark-jump)
463 (const isearch)
464 (const default))
465 (boolean))))
466 "Contexts for the reveal options.")
468 (defcustom org-show-hierarchy-above '((default . t))
469 "Non-nil means, show full hierarchy when revealing a location.
470 Org-mode often shows locations in an org-mode file which might have
471 been invisible before. When this is set, the hierarchy of headings
472 above the exposed location is shown.
473 Turning this off for example for sparse trees makes them very compact.
474 Instead of t, this can also be an alist specifying this option for different
475 contexts. Valid contexts are
476 agenda when exposing an entry from the agenda
477 org-goto when using the command `org-goto' on key C-c C-j
478 occur-tree when using the command `org-occur' on key C-c /
479 tags-tree when constructing a sparse tree based on tags matches
480 link-search when exposing search matches associated with a link
481 mark-goto when exposing the jump goal of a mark
482 bookmark-jump when exposing a bookmark location
483 isearch when exiting from an incremental search
484 default default for all contexts not set explicitly"
485 :group 'org-reveal-location
486 :type org-context-choice)
488 (defcustom org-show-following-heading '((default . nil))
489 "Non-nil means, show following heading when revealing a location.
490 Org-mode often shows locations in an org-mode file which might have
491 been invisible before. When this is set, the heading following the
492 match is shown.
493 Turning this off for example for sparse trees makes them very compact,
494 but makes it harder to edit the location of the match. In such a case,
495 use the command \\[org-reveal] to show more context.
496 Instead of t, this can also be an alist specifying this option for different
497 contexts. See `org-show-hierarchy-above' for valid contexts."
498 :group 'org-reveal-location
499 :type org-context-choice)
501 (defcustom org-show-siblings '((default . nil) (isearch t))
502 "Non-nil means, show all sibling heading when revealing a location.
503 Org-mode often shows locations in an org-mode file which might have
504 been invisible before. When this is set, the sibling of the current entry
505 heading are all made visible. If `org-show-hierarchy-above' is t,
506 the same happens on each level of the hierarchy above the current entry.
508 By default this is on for the isearch context, off for all other contexts.
509 Turning this off for example for sparse trees makes them very compact,
510 but makes it harder to edit the location of the match. In such a case,
511 use the command \\[org-reveal] to show more context.
512 Instead of t, this can also be an alist specifying this option for different
513 contexts. See `org-show-hierarchy-above' for valid contexts."
514 :group 'org-reveal-location
515 :type org-context-choice)
517 (defcustom org-show-entry-below '((default . nil))
518 "Non-nil means, show the entry below a headline when revealing a location.
519 Org-mode often shows locations in an org-mode file which might have
520 been invisible before. When this is set, the text below the headline that is
521 exposed is also shown.
523 By default this is off for all contexts.
524 Instead of t, this can also be an alist specifying this option for different
525 contexts. See `org-show-hierarchy-above' for valid contexts."
526 :group 'org-reveal-location
527 :type org-context-choice)
529 (defcustom org-indirect-buffer-display 'other-window
530 "How should indirect tree buffers be displayed?
531 This applies to indirect buffers created with the commands
532 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
533 Valid values are:
534 current-window Display in the current window
535 other-window Just display in another window.
536 dedicated-frame Create one new frame, and re-use it each time.
537 new-frame Make a new frame each time. Note that in this case
538 previously-made indirect buffers are kept, and you need to
539 kill these buffers yourself."
540 :group 'org-structure
541 :group 'org-agenda-windows
542 :type '(choice
543 (const :tag "In current window" current-window)
544 (const :tag "In current frame, other window" other-window)
545 (const :tag "Each time a new frame" new-frame)
546 (const :tag "One dedicated frame" dedicated-frame)))
548 (defgroup org-cycle nil
549 "Options concerning visibility cycling in Org-mode."
550 :tag "Org Cycle"
551 :group 'org-structure)
553 (defcustom org-cycle-max-level nil
554 "Maximum level which should still be subject to visibility cycling.
555 Levels higher than this will, for cycling, be treated as text, not a headline.
556 When `org-odd-levels-only' is set, a value of N in this variable actually
557 means 2N-1 stars as the limiting headline.
558 When nil, cycle all levels.
559 Note that the limiting level of cycling is also influenced by
560 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
561 `org-inlinetask-min-level' is, cycling will be limited to levels one less
562 than its value."
563 :group 'org-cycle
564 :type '(choice
565 (const :tag "No limit" nil)
566 (integer :tag "Maximum level")))
568 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK")
569 "Names of drawers. Drawers are not opened by cycling on the headline above.
570 Drawers only open with a TAB on the drawer line itself. A drawer looks like
571 this:
572 :DRAWERNAME:
573 .....
574 :END:
575 The drawer \"PROPERTIES\" is special for capturing properties through
576 the property API.
578 Drawers can be defined on the per-file basis with a line like:
580 #+DRAWERS: HIDDEN STATE PROPERTIES"
581 :group 'org-structure
582 :group 'org-cycle
583 :type '(repeat (string :tag "Drawer Name")))
585 (defcustom org-cycle-global-at-bob nil
586 "Cycle globally if cursor is at beginning of buffer and not at a headline.
587 This makes it possible to do global cycling without having to use S-TAB or
588 C-u TAB. For this special case to work, the first line of the buffer
589 must not be a headline - it may be empty or some other text. When used in
590 this way, `org-cycle-hook' is disables temporarily, to make sure the
591 cursor stays at the beginning of the buffer.
592 When this option is nil, don't do anything special at the beginning
593 of the buffer."
594 :group 'org-cycle
595 :type 'boolean)
597 (defcustom org-cycle-emulate-tab t
598 "Where should `org-cycle' emulate TAB.
599 nil Never
600 white Only in completely white lines
601 whitestart Only at the beginning of lines, before the first non-white char
602 t Everywhere except in headlines
603 exc-hl-bol Everywhere except at the start of a headline
604 If TAB is used in a place where it does not emulate TAB, the current subtree
605 visibility is cycled."
606 :group 'org-cycle
607 :type '(choice (const :tag "Never" nil)
608 (const :tag "Only in completely white lines" white)
609 (const :tag "Before first char in a line" whitestart)
610 (const :tag "Everywhere except in headlines" t)
611 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
614 (defcustom org-cycle-separator-lines 2
615 "Number of empty lines needed to keep an empty line between collapsed trees.
616 If you leave an empty line between the end of a subtree and the following
617 headline, this empty line is hidden when the subtree is folded.
618 Org-mode will leave (exactly) one empty line visible if the number of
619 empty lines is equal or larger to the number given in this variable.
620 So the default 2 means, at least 2 empty lines after the end of a subtree
621 are needed to produce free space between a collapsed subtree and the
622 following headline.
624 Special case: when 0, never leave empty lines in collapsed view."
625 :group 'org-cycle
626 :type 'integer)
627 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
629 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
630 org-cycle-hide-drawers
631 org-cycle-show-empty-lines
632 org-optimize-window-after-visibility-change)
633 "Hook that is run after `org-cycle' has changed the buffer visibility.
634 The function(s) in this hook must accept a single argument which indicates
635 the new state that was set by the most recent `org-cycle' command. The
636 argument is a symbol. After a global state change, it can have the values
637 `overview', `content', or `all'. After a local state change, it can have
638 the values `folded', `children', or `subtree'."
639 :group 'org-cycle
640 :type 'hook)
642 (defgroup org-edit-structure nil
643 "Options concerning structure editing in Org-mode."
644 :tag "Org Edit Structure"
645 :group 'org-structure)
647 (defcustom org-odd-levels-only nil
648 "Non-nil means, skip even levels and only use odd levels for the outline.
649 This has the effect that two stars are being added/taken away in
650 promotion/demotion commands. It also influences how levels are
651 handled by the exporters.
652 Changing it requires restart of `font-lock-mode' to become effective
653 for fontification also in regions already fontified.
654 You may also set this on a per-file basis by adding one of the following
655 lines to the buffer:
657 #+STARTUP: odd
658 #+STARTUP: oddeven"
659 :group 'org-edit-structure
660 :group 'org-font-lock
661 :type 'boolean)
663 (defcustom org-adapt-indentation t
664 "Non-nil means, adapt indentation when promoting and demoting.
665 When this is set and the *entire* text in an entry is indented, the
666 indentation is increased by one space in a demotion command, and
667 decreased by one in a promotion command. If any line in the entry
668 body starts at column 0, indentation is not changed at all."
669 :group 'org-edit-structure
670 :type 'boolean)
672 (defcustom org-special-ctrl-a/e nil
673 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
675 When t, `C-a' will bring back the cursor to the beginning of the
676 headline text, i.e. after the stars and after a possible TODO keyword.
677 In an item, this will be the position after the bullet.
678 When the cursor is already at that position, another `C-a' will bring
679 it to the beginning of the line.
681 `C-e' will jump to the end of the headline, ignoring the presence of tags
682 in the headline. A second `C-e' will then jump to the true end of the
683 line, after any tags.
685 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
686 and only a directly following, identical keypress will bring the cursor
687 to the special positions.
689 This may also be a cons cell where the behavior for `C-a' and `C-e' is
690 set separately."
691 :group 'org-edit-structure
692 :type '(choice
693 (const :tag "off" nil)
694 (const :tag "after stars/bullet and before tags first" t)
695 (const :tag "true line boundary first" reversed)
696 (cons :tag "Set C-a and C-e separately"
697 (choice :tag "Special C-a"
698 (const :tag "off" nil)
699 (const :tag "after stars/bullet first" t)
700 (const :tag "before stars/bullet first" reversed))
701 (choice :tag "Special C-e"
702 (const :tag "off" nil)
703 (const :tag "before tags first" t)
704 (const :tag "after tags first" reversed)))))
705 (if (fboundp 'defvaralias)
706 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
708 (defcustom org-special-ctrl-k nil
709 "Non-nil means `C-k' will behave specially in headlines.
710 When nil, `C-k' will call the default `kill-line' command.
711 When t, the following will happen while the cursor is in the headline:
713 - When the cursor is at the beginning of a headline, kill the entire
714 line and possible the folded subtree below the line.
715 - When in the middle of the headline text, kill the headline up to the tags.
716 - When after the headline text, kill the tags."
717 :group 'org-edit-structure
718 :type 'boolean)
720 (defcustom org-yank-folded-subtrees t
721 "Non-nil means, when yanking subtrees, fold them.
722 If the kill is a single subtree, or a sequence of subtrees, i.e. if
723 it starts with a heading and all other headings in it are either children
724 or siblings, then fold all the subtrees. However, do this only if no
725 text after the yank would be swallowed into a folded tree by this action."
726 :group 'org-edit-structure
727 :type 'boolean)
729 (defcustom org-yank-adjusted-subtrees nil
730 "Non-nil means, when yanking subtrees, adjust the level.
731 With this setting, `org-paste-subtree' is used to insert the subtree, see
732 this function for details."
733 :group 'org-edit-structure
734 :type 'boolean)
736 (defcustom org-M-RET-may-split-line '((default . t))
737 "Non-nil means, M-RET will split the line at the cursor position.
738 When nil, it will go to the end of the line before making a
739 new line.
740 You may also set this option in a different way for different
741 contexts. Valid contexts are:
743 headline when creating a new headline
744 item when creating a new item
745 table in a table field
746 default the value to be used for all contexts not explicitly
747 customized"
748 :group 'org-structure
749 :group 'org-table
750 :type '(choice
751 (const :tag "Always" t)
752 (const :tag "Never" nil)
753 (repeat :greedy t :tag "Individual contexts"
754 (cons
755 (choice :tag "Context"
756 (const headline)
757 (const item)
758 (const table)
759 (const default))
760 (boolean)))))
763 (defcustom org-insert-heading-respect-content nil
764 "Non-nil means, insert new headings after the current subtree.
765 When nil, the new heading is created directly after the current line.
766 The commands \\[org-insert-heading-respect-content] and
767 \\[org-insert-todo-heading-respect-content] turn this variable on
768 for the duration of the command."
769 :group 'org-structure
770 :type 'boolean)
772 (defcustom org-blank-before-new-entry '((heading . auto)
773 (plain-list-item . auto))
774 "Should `org-insert-heading' leave a blank line before new heading/item?
775 The value is an alist, with `heading' and `plain-list-item' as car,
776 and a boolean flag as cdr. For plain lists, if the variable
777 `org-empty-line-terminates-plain-lists' is set, the setting here
778 is ignored and no empty line is inserted, to keep the list in tact."
779 :group 'org-edit-structure
780 :type '(list
781 (cons (const heading)
782 (choice (const :tag "Never" nil)
783 (const :tag "Always" t)
784 (const :tag "Auto" auto)))
785 (cons (const plain-list-item)
786 (choice (const :tag "Never" nil)
787 (const :tag "Always" t)
788 (const :tag "Auto" auto)))))
790 (defcustom org-insert-heading-hook nil
791 "Hook being run after inserting a new heading."
792 :group 'org-edit-structure
793 :type 'hook)
795 (defcustom org-enable-fixed-width-editor t
796 "Non-nil means, lines starting with \":\" are treated as fixed-width.
797 This currently only means, they are never auto-wrapped.
798 When nil, such lines will be treated like ordinary lines.
799 See also the QUOTE keyword."
800 :group 'org-edit-structure
801 :type 'boolean)
803 (defcustom org-edit-src-region-extra nil
804 "Additional regexps to identify regions for editing with `org-edit-src-code'.
805 For examples see the function `org-edit-src-find-region-and-lang'.
806 The regular expression identifying the begin marker should end with a newline,
807 and the regexp marking the end line should start with a newline, to make sure
808 there are kept outside the narrowed region."
809 :group 'org-edit-structure
810 :type '(repeat
811 (list
812 (regexp :tag "begin regexp")
813 (regexp :tag "end regexp")
814 (choice :tag "language"
815 (string :tag "specify")
816 (integer :tag "from match group")
817 (const :tag "from `lang' element")
818 (const :tag "from `style' element")))))
820 (defcustom org-coderef-label-format "(ref:%s)"
821 "The default coderef format.
822 This format string will be used to search for coderef labels in literal
823 examples (EXAMPLE and SRC blocks). The format can be overwritten
824 an individual literal example with the -f option, like
826 #+BEGIN_SRC pascal +n -r -l \"((%s))\"
828 #+END_SRC
830 If you want to use this for HTML export, make sure that the format does
831 not introduce special font-locking, and avoid the HTML special
832 characters `<', `>', and `&'. The reason for this restriction is that
833 the labels are searched for only after htmlize has done its job."
834 :group 'org-edit-structure ; FIXME this is not in the right group
835 :type 'string)
837 (defcustom org-edit-fixed-width-region-mode 'artist-mode
838 "The mode that should be used to edit fixed-width regions.
839 These are the regions where each line starts with a colon."
840 :group 'org-edit-structure
841 :type '(choice
842 (const artist-mode)
843 (const picture-mode)
844 (const fundamental-mode)
845 (function :tag "Other (specify)")))
847 (defcustom org-goto-auto-isearch t
848 "Non-nil means, typing characters in org-goto starts incremental search."
849 :group 'org-edit-structure
850 :type 'boolean)
852 (defgroup org-sparse-trees nil
853 "Options concerning sparse trees in Org-mode."
854 :tag "Org Sparse Trees"
855 :group 'org-structure)
857 (defcustom org-highlight-sparse-tree-matches t
858 "Non-nil means, highlight all matches that define a sparse tree.
859 The highlights will automatically disappear the next time the buffer is
860 changed by an edit command."
861 :group 'org-sparse-trees
862 :type 'boolean)
864 (defcustom org-remove-highlights-with-change t
865 "Non-nil means, any change to the buffer will remove temporary highlights.
866 Such highlights are created by `org-occur' and `org-clock-display'.
867 When nil, `C-c C-c needs to be used to get rid of the highlights.
868 The highlights created by `org-preview-latex-fragment' always need
869 `C-c C-c' to be removed."
870 :group 'org-sparse-trees
871 :group 'org-time
872 :type 'boolean)
875 (defcustom org-occur-hook '(org-first-headline-recenter)
876 "Hook that is run after `org-occur' has constructed a sparse tree.
877 This can be used to recenter the window to show as much of the structure
878 as possible."
879 :group 'org-sparse-trees
880 :type 'hook)
882 (defgroup org-imenu-and-speedbar nil
883 "Options concerning imenu and speedbar in Org-mode."
884 :tag "Org Imenu and Speedbar"
885 :group 'org-structure)
887 (defcustom org-imenu-depth 2
888 "The maximum level for Imenu access to Org-mode headlines.
889 This also applied for speedbar access."
890 :group 'org-imenu-and-speedbar
891 :type 'integer)
893 (defgroup org-table nil
894 "Options concerning tables in Org-mode."
895 :tag "Org Table"
896 :group 'org)
898 (defcustom org-enable-table-editor 'optimized
899 "Non-nil means, lines starting with \"|\" are handled by the table editor.
900 When nil, such lines will be treated like ordinary lines.
902 When equal to the symbol `optimized', the table editor will be optimized to
903 do the following:
904 - Automatic overwrite mode in front of whitespace in table fields.
905 This makes the structure of the table stay in tact as long as the edited
906 field does not exceed the column width.
907 - Minimize the number of realigns. Normally, the table is aligned each time
908 TAB or RET are pressed to move to another field. With optimization this
909 happens only if changes to a field might have changed the column width.
910 Optimization requires replacing the functions `self-insert-command',
911 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
912 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
913 very good at guessing when a re-align will be necessary, but you can always
914 force one with \\[org-ctrl-c-ctrl-c].
916 If you would like to use the optimized version in Org-mode, but the
917 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
919 This variable can be used to turn on and off the table editor during a session,
920 but in order to toggle optimization, a restart is required.
922 See also the variable `org-table-auto-blank-field'."
923 :group 'org-table
924 :type '(choice
925 (const :tag "off" nil)
926 (const :tag "on" t)
927 (const :tag "on, optimized" optimized)))
929 (defcustom org-self-insert-cluster-for-undo t
930 "Non-nil means cluster self-insert commands for undo when possible.
931 If this is set, then, like in the Emacs command loop, 20 consequtive
932 characters will be undone together.
933 This is configurable, because there is some impact on typing performance."
934 :group 'org-table
935 :type 'boolean)
937 (defcustom org-table-tab-recognizes-table.el t
938 "Non-nil means, TAB will automatically notice a table.el table.
939 When it sees such a table, it moves point into it and - if necessary -
940 calls `table-recognize-table'."
941 :group 'org-table-editing
942 :type 'boolean)
944 (defgroup org-link nil
945 "Options concerning links in Org-mode."
946 :tag "Org Link"
947 :group 'org)
949 (defvar org-link-abbrev-alist-local nil
950 "Buffer-local version of `org-link-abbrev-alist', which see.
951 The value of this is taken from the #+LINK lines.")
952 (make-variable-buffer-local 'org-link-abbrev-alist-local)
954 (defcustom org-link-abbrev-alist nil
955 "Alist of link abbreviations.
956 The car of each element is a string, to be replaced at the start of a link.
957 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
958 links in Org-mode buffers can have an optional tag after a double colon, e.g.
960 [[linkkey:tag][description]]
962 The 'linkkey' must be a word word, starting with a letter, followed
963 by letters, numbers, '-' or '_'.
965 If REPLACE is a string, the tag will simply be appended to create the link.
966 If the string contains \"%s\", the tag will be inserted there. Alternatively,
967 the placeholder \"%h\" will cause a url-encoded version of the tag to
968 be inserted at that point (see the function `url-hexify-string').
970 REPLACE may also be a function that will be called with the tag as the
971 only argument to create the link, which should be returned as a string.
973 See the manual for examples."
974 :group 'org-link
975 :type '(repeat
976 (cons
977 (string :tag "Protocol")
978 (choice
979 (string :tag "Format")
980 (function)))))
982 (defcustom org-descriptive-links t
983 "Non-nil means, hide link part and only show description of bracket links.
984 Bracket links are like [[link][description]]. This variable sets the initial
985 state in new org-mode buffers. The setting can then be toggled on a
986 per-buffer basis from the Org->Hyperlinks menu."
987 :group 'org-link
988 :type 'boolean)
990 (defcustom org-link-file-path-type 'adaptive
991 "How the path name in file links should be stored.
992 Valid values are:
994 relative Relative to the current directory, i.e. the directory of the file
995 into which the link is being inserted.
996 absolute Absolute path, if possible with ~ for home directory.
997 noabbrev Absolute path, no abbreviation of home directory.
998 adaptive Use relative path for files in the current directory and sub-
999 directories of it. For other files, use an absolute path."
1000 :group 'org-link
1001 :type '(choice
1002 (const relative)
1003 (const absolute)
1004 (const noabbrev)
1005 (const adaptive)))
1007 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1008 "Types of links that should be activated in Org-mode files.
1009 This is a list of symbols, each leading to the activation of a certain link
1010 type. In principle, it does not hurt to turn on most link types - there may
1011 be a small gain when turning off unused link types. The types are:
1013 bracket The recommended [[link][description]] or [[link]] links with hiding.
1014 angular Links in angular brackets that may contain whitespace like
1015 <bbdb:Carsten Dominik>.
1016 plain Plain links in normal text, no whitespace, like http://google.com.
1017 radio Text that is matched by a radio target, see manual for details.
1018 tag Tag settings in a headline (link to tag search).
1019 date Time stamps (link to calendar).
1020 footnote Footnote labels.
1022 Changing this variable requires a restart of Emacs to become effective."
1023 :group 'org-link
1024 :type '(set :greedy t
1025 (const :tag "Double bracket links (new style)" bracket)
1026 (const :tag "Angular bracket links (old style)" angular)
1027 (const :tag "Plain text links" plain)
1028 (const :tag "Radio target matches" radio)
1029 (const :tag "Tags" tag)
1030 (const :tag "Timestamps" date)
1031 (const :tag "Footnotes" footnote)))
1033 (defcustom org-make-link-description-function nil
1034 "Function to use to generate link descriptions from links. If
1035 nil the link location will be used. This function must take two
1036 parameters; the first is the link and the second the description
1037 org-insert-link has generated, and should return the description
1038 to use."
1039 :group 'org-link
1040 :type 'function)
1042 (defgroup org-link-store nil
1043 "Options concerning storing links in Org-mode."
1044 :tag "Org Store Link"
1045 :group 'org-link)
1047 (defcustom org-email-link-description-format "Email %c: %.30s"
1048 "Format of the description part of a link to an email or usenet message.
1049 The following %-escapes will be replaced by corresponding information:
1051 %F full \"From\" field
1052 %f name, taken from \"From\" field, address if no name
1053 %T full \"To\" field
1054 %t first name in \"To\" field, address if no name
1055 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1056 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1057 %s subject
1058 %m message-id.
1060 You may use normal field width specification between the % and the letter.
1061 This is for example useful to limit the length of the subject.
1063 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1064 :group 'org-link-store
1065 :type 'string)
1067 (defcustom org-from-is-user-regexp
1068 (let (r1 r2)
1069 (when (and user-mail-address (not (string= user-mail-address "")))
1070 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1071 (when (and user-full-name (not (string= user-full-name "")))
1072 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1073 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1074 "Regexp matched against the \"From:\" header of an email or usenet message.
1075 It should match if the message is from the user him/herself."
1076 :group 'org-link-store
1077 :type 'regexp)
1079 (defcustom org-link-to-org-use-id 'create-if-interactive
1080 "Non-nil means, storing a link to an Org file will use entry IDs.
1082 Note that before this variable is even considered, org-id must be loaded,
1083 to please customize `org-modules' and turn it on.
1085 The variable can have the following values:
1087 t Create an ID if needed to make a link to the current entry.
1089 create-if-interactive
1090 If `org-store-link' is called directly (interactively, as a user
1091 command), do create an ID to support the link. But when doing the
1092 job for remember, only use the ID if it already exists. The
1093 purpose of this setting is to avoid proliferation of unwanted
1094 IDs, just because you happen to be in an Org file when you
1095 call `org-remember' that automatically and preemptively
1096 creates a link. If you do want to get an ID link in a remember
1097 template to an entry not having an ID, create it first by
1098 explicitly creating a link to it, using `C-c C-l' first.
1100 use-existing
1101 Use existing ID, do not create one.
1103 nil Never use an ID to make a link, instead link using a text search for
1104 the headline text."
1105 :group 'org-link-store
1106 :type '(choice
1107 (const :tag "Create ID to make link" t)
1108 (const :tag "Create if string link interactively"
1109 'create-if-interactive)
1110 (const :tag "Only use existing" 'use-existing)
1111 (const :tag "Do not use ID to create link" nil)))
1113 (defcustom org-context-in-file-links t
1114 "Non-nil means, file links from `org-store-link' contain context.
1115 A search string will be added to the file name with :: as separator and
1116 used to find the context when the link is activated by the command
1117 `org-open-at-point'.
1118 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1119 negates this setting for the duration of the command."
1120 :group 'org-link-store
1121 :type 'boolean)
1123 (defcustom org-keep-stored-link-after-insertion nil
1124 "Non-nil means, keep link in list for entire session.
1126 The command `org-store-link' adds a link pointing to the current
1127 location to an internal list. These links accumulate during a session.
1128 The command `org-insert-link' can be used to insert links into any
1129 Org-mode file (offering completion for all stored links). When this
1130 option is nil, every link which has been inserted once using \\[org-insert-link]
1131 will be removed from the list, to make completing the unused links
1132 more efficient."
1133 :group 'org-link-store
1134 :type 'boolean)
1136 (defgroup org-link-follow nil
1137 "Options concerning following links in Org-mode."
1138 :tag "Org Follow Link"
1139 :group 'org-link)
1141 (defcustom org-link-translation-function nil
1142 "Function to translate links with different syntax to Org syntax.
1143 This can be used to translate links created for example by the Planner
1144 or emacs-wiki packages to Org syntax.
1145 The function must accept two parameters, a TYPE containing the link
1146 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1147 which is everything after the link protocol. It should return a cons
1148 with possibly modified values of type and path.
1149 Org contains a function for this, so if you set this variable to
1150 `org-translate-link-from-planner', you should be able follow many
1151 links created by planner."
1152 :group 'org-link-follow
1153 :type 'function)
1155 (defcustom org-follow-link-hook nil
1156 "Hook that is run after a link has been followed."
1157 :group 'org-link-follow
1158 :type 'hook)
1160 (defcustom org-tab-follows-link nil
1161 "Non-nil means, on links TAB will follow the link.
1162 Needs to be set before org.el is loaded.
1163 This really should not be used, it does not make sense, and the
1164 implementation is bad."
1165 :group 'org-link-follow
1166 :type 'boolean)
1168 (defcustom org-return-follows-link nil
1169 "Non-nil means, on links RET will follow the link.
1170 Needs to be set before org.el is loaded."
1171 :group 'org-link-follow
1172 :type 'boolean)
1174 (defcustom org-mouse-1-follows-link
1175 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1176 "Non-nil means, mouse-1 on a link will follow the link.
1177 A longer mouse click will still set point. Does not work on XEmacs.
1178 Needs to be set before org.el is loaded."
1179 :group 'org-link-follow
1180 :type 'boolean)
1182 (defcustom org-mark-ring-length 4
1183 "Number of different positions to be recorded in the ring
1184 Changing this requires a restart of Emacs to work correctly."
1185 :group 'org-link-follow
1186 :type 'integer)
1188 (defcustom org-link-frame-setup
1189 '((vm . vm-visit-folder-other-frame)
1190 (gnus . gnus-other-frame)
1191 (file . find-file-other-window))
1192 "Setup the frame configuration for following links.
1193 When following a link with Emacs, it may often be useful to display
1194 this link in another window or frame. This variable can be used to
1195 set this up for the different types of links.
1196 For VM, use any of
1197 `vm-visit-folder'
1198 `vm-visit-folder-other-frame'
1199 For Gnus, use any of
1200 `gnus'
1201 `gnus-other-frame'
1202 `org-gnus-no-new-news'
1203 For FILE, use any of
1204 `find-file'
1205 `find-file-other-window'
1206 `find-file-other-frame'
1207 For the calendar, use the variable `calendar-setup'.
1208 For BBDB, it is currently only possible to display the matches in
1209 another window."
1210 :group 'org-link-follow
1211 :type '(list
1212 (cons (const vm)
1213 (choice
1214 (const vm-visit-folder)
1215 (const vm-visit-folder-other-window)
1216 (const vm-visit-folder-other-frame)))
1217 (cons (const gnus)
1218 (choice
1219 (const gnus)
1220 (const gnus-other-frame)
1221 (const org-gnus-no-new-news)))
1222 (cons (const file)
1223 (choice
1224 (const find-file)
1225 (const find-file-other-window)
1226 (const find-file-other-frame)))))
1228 (defcustom org-display-internal-link-with-indirect-buffer nil
1229 "Non-nil means, use indirect buffer to display infile links.
1230 Activating internal links (from one location in a file to another location
1231 in the same file) normally just jumps to the location. When the link is
1232 activated with a C-u prefix (or with mouse-3), the link is displayed in
1233 another window. When this option is set, the other window actually displays
1234 an indirect buffer clone of the current buffer, to avoid any visibility
1235 changes to the current buffer."
1236 :group 'org-link-follow
1237 :type 'boolean)
1239 (defcustom org-open-non-existing-files nil
1240 "Non-nil means, `org-open-file' will open non-existing files.
1241 When nil, an error will be generated."
1242 :group 'org-link-follow
1243 :type 'boolean)
1245 (defcustom org-open-directory-means-index-dot-org nil
1246 "Non-nil means, a link to a directory really means to index.org.
1247 When nil, following a directory link will run dired or open a finder/explorer
1248 window on that directory."
1249 :group 'org-link-follow
1250 :type 'boolean)
1252 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1253 "Function and arguments to call for following mailto links.
1254 This is a list with the first element being a lisp function, and the
1255 remaining elements being arguments to the function. In string arguments,
1256 %a will be replaced by the address, and %s will be replaced by the subject
1257 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1258 :group 'org-link-follow
1259 :type '(choice
1260 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1261 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1262 (const :tag "message-mail" (message-mail "%a" "%s"))
1263 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1265 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1266 "Non-nil means, ask for confirmation before executing shell links.
1267 Shell links can be dangerous: just think about a link
1269 [[shell:rm -rf ~/*][Google Search]]
1271 This link would show up in your Org-mode document as \"Google Search\",
1272 but really it would remove your entire home directory.
1273 Therefore we advise against setting this variable to nil.
1274 Just change it to `y-or-n-p' if you want to confirm with a
1275 single keystroke rather than having to type \"yes\"."
1276 :group 'org-link-follow
1277 :type '(choice
1278 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1279 (const :tag "with y-or-n (faster)" y-or-n-p)
1280 (const :tag "no confirmation (dangerous)" nil)))
1282 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1283 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1284 Elisp links can be dangerous: just think about a link
1286 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1288 This link would show up in your Org-mode document as \"Google Search\",
1289 but really it would remove your entire home directory.
1290 Therefore we advise against setting this variable to nil.
1291 Just change it to `y-or-n-p' if you want to confirm with a
1292 single keystroke rather than having to type \"yes\"."
1293 :group 'org-link-follow
1294 :type '(choice
1295 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1296 (const :tag "with y-or-n (faster)" y-or-n-p)
1297 (const :tag "no confirmation (dangerous)" nil)))
1299 (defconst org-file-apps-defaults-gnu
1300 '((remote . emacs)
1301 (system . mailcap)
1302 (t . mailcap))
1303 "Default file applications on a UNIX or GNU/Linux system.
1304 See `org-file-apps'.")
1306 (defconst org-file-apps-defaults-macosx
1307 '((remote . emacs)
1308 (t . "open %s")
1309 (system . "open %s")
1310 ("ps.gz" . "gv %s")
1311 ("eps.gz" . "gv %s")
1312 ("dvi" . "xdvi %s")
1313 ("fig" . "xfig %s"))
1314 "Default file applications on a MacOS X system.
1315 The system \"open\" is known as a default, but we use X11 applications
1316 for some files for which the OS does not have a good default.
1317 See `org-file-apps'.")
1319 (defconst org-file-apps-defaults-windowsnt
1320 (list
1321 '(remote . emacs)
1322 (cons t
1323 (list (if (featurep 'xemacs)
1324 'mswindows-shell-execute
1325 'w32-shell-execute)
1326 "open" 'file))
1327 (cons 'system
1328 (list (if (featurep 'xemacs)
1329 'mswindows-shell-execute
1330 'w32-shell-execute)
1331 "open" 'file)))
1332 "Default file applications on a Windows NT system.
1333 The system \"open\" is used for most files.
1334 See `org-file-apps'.")
1336 (defcustom org-file-apps
1338 (auto-mode . emacs)
1339 ("\\.x?html?\\'" . default)
1340 ("\\.pdf\\'" . default)
1342 "External applications for opening `file:path' items in a document.
1343 Org-mode uses system defaults for different file types, but
1344 you can use this variable to set the application for a given file
1345 extension. The entries in this list are cons cells where the car identifies
1346 files and the cdr the corresponding command. Possible values for the
1347 file identifier are
1348 \"regex\" Regular expression matched against the file name. For backward
1349 compatibility, this can also be a string with only alphanumeric
1350 characters, which is then interpreted as an extension.
1351 `directory' Matches a directory
1352 `remote' Matches a remote file, accessible through tramp or efs.
1353 Remote files most likely should be visited through Emacs
1354 because external applications cannot handle such paths.
1355 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1356 so all files Emacs knows how to handle. Using this with
1357 command `emacs' will open most files in Emacs. Beware that this
1358 will also open html files inside Emacs, unless you add
1359 (\"html\" . default) to the list as well.
1360 t Default for files not matched by any of the other options.
1361 `system' The system command to open files, like `open' on Windows
1362 and Mac OS X, and mailcap under GNU/Linux. This is the command
1363 that will be selected if you call `C-c C-o' with a double
1364 `C-u C-u' prefix.
1366 Possible values for the command are:
1367 `emacs' The file will be visited by the current Emacs process.
1368 `default' Use the default application for this file type, which is the
1369 association for t in the list, most likely in the system-specific
1370 part.
1371 This can be used to overrule an unwanted setting in the
1372 system-specific variable.
1373 `system' Use the system command for opening files, like \"open\".
1374 This command is specified by the entry whose car is `system'.
1375 Most likely, the system-specific version of this variable
1376 does define this command, but you can overrule/replace it
1377 here.
1378 string A command to be executed by a shell; %s will be replaced
1379 by the path to the file.
1380 sexp A Lisp form which will be evaluated. The file path will
1381 be available in the Lisp variable `file'.
1382 For more examples, see the system specific constants
1383 `org-file-apps-defaults-macosx'
1384 `org-file-apps-defaults-windowsnt'
1385 `org-file-apps-defaults-gnu'."
1386 :group 'org-link-follow
1387 :type '(repeat
1388 (cons (choice :value ""
1389 (string :tag "Extension")
1390 (const :tag "System command to open files" system)
1391 (const :tag "Default for unrecognized files" t)
1392 (const :tag "Remote file" remote)
1393 (const :tag "Links to a directory" directory)
1394 (const :tag "Any files that have Emacs modes"
1395 auto-mode))
1396 (choice :value ""
1397 (const :tag "Visit with Emacs" emacs)
1398 (const :tag "Use default" default)
1399 (const :tag "Use the system command" system)
1400 (string :tag "Command")
1401 (sexp :tag "Lisp form")))))
1403 (defgroup org-refile nil
1404 "Options concerning refiling entries in Org-mode."
1405 :tag "Org Refile"
1406 :group 'org)
1408 (defcustom org-directory "~/org"
1409 "Directory with org files.
1410 This is just a default location to look for Org files. There is no need
1411 at all to put your files into this directory. It is only used in the
1412 following situations:
1414 1. When a remember template specifies a target file that is not an
1415 absolute path. The path will then be interpreted relative to
1416 `org-directory'
1417 2. When a remember note is filed away in an interactive way (when exiting the
1418 note buffer with `C-1 C-c C-c'. The the user is prompted for an org file,
1419 with `org-directory' as the default path."
1420 :group 'org-refile
1421 :group 'org-remember
1422 :type 'directory)
1424 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1425 "Default target for storing notes.
1426 Used by the hooks for remember.el. This can be a string, or nil to mean
1427 the value of `remember-data-file'.
1428 You can set this on a per-template basis with the variable
1429 `org-remember-templates'."
1430 :group 'org-refile
1431 :group 'org-remember
1432 :type '(choice
1433 (const :tag "Default from remember-data-file" nil)
1434 file))
1436 (defcustom org-goto-interface 'outline
1437 "The default interface to be used for `org-goto'.
1438 Allowed values are:
1439 outline The interface shows an outline of the relevant file
1440 and the correct heading is found by moving through
1441 the outline or by searching with incremental search.
1442 outline-path-completion Headlines in the current buffer are offered via
1443 completion. This is the interface also used by
1444 the refile command."
1445 :group 'org-refile
1446 :type '(choice
1447 (const :tag "Outline" outline)
1448 (const :tag "Outline-path-completion" outline-path-completion)))
1450 (defcustom org-goto-max-level 5
1451 "Maximum level to be considered when running org-goto with refile interface."
1452 :group 'org-refile
1453 :type 'integer)
1455 (defcustom org-reverse-note-order nil
1456 "Non-nil means, store new notes at the beginning of a file or entry.
1457 When nil, new notes will be filed to the end of a file or entry.
1458 This can also be a list with cons cells of regular expressions that
1459 are matched against file names, and values."
1460 :group 'org-remember
1461 :group 'org-refile
1462 :type '(choice
1463 (const :tag "Reverse always" t)
1464 (const :tag "Reverse never" nil)
1465 (repeat :tag "By file name regexp"
1466 (cons regexp boolean))))
1468 (defcustom org-refile-targets nil
1469 "Targets for refiling entries with \\[org-refile].
1470 This is list of cons cells. Each cell contains:
1471 - a specification of the files to be considered, either a list of files,
1472 or a symbol whose function or variable value will be used to retrieve
1473 a file name or a list of file names. If you use `org-agenda-files' for
1474 that, all agenda files will be scanned for targets. Nil means, consider
1475 headings in the current buffer.
1476 - A specification of how to find candidate refile targets. This may be
1477 any of:
1478 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1479 This tag has to be present in all target headlines, inheritance will
1480 not be considered.
1481 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1482 todo keyword.
1483 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1484 headlines that are refiling targets.
1485 - a cons cell (:level . N). Any headline of level N is considered a target.
1486 Note that, when `org-odd-levels-only' is set, level corresponds to
1487 order in hierarchy, not to the number of stars.
1488 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1489 Note that, when `org-odd-levels-only' is set, level corresponds to
1490 order in hierarchy, not to the number of stars.
1492 When this variable is nil, all top-level headlines in the current buffer
1493 are used, equivalent to the value `((nil . (:level . 1))'."
1494 :group 'org-refile
1495 :type '(repeat
1496 (cons
1497 (choice :value org-agenda-files
1498 (const :tag "All agenda files" org-agenda-files)
1499 (const :tag "Current buffer" nil)
1500 (function) (variable) (file))
1501 (choice :tag "Identify target headline by"
1502 (cons :tag "Specific tag" (const :value :tag) (string))
1503 (cons :tag "TODO keyword" (const :value :todo) (string))
1504 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1505 (cons :tag "Level number" (const :value :level) (integer))
1506 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1508 (defcustom org-refile-use-outline-path nil
1509 "Non-nil means, provide refile targets as paths.
1510 So a level 3 headline will be available as level1/level2/level3.
1512 When the value is `file', also include the file name (without directory)
1513 into the path. In this case, you can also stop the completion after
1514 the file name, to get entries inserted as top level in the file.
1516 When `full-file-path', include the full file path."
1517 :group 'org-refile
1518 :type '(choice
1519 (const :tag "Not" nil)
1520 (const :tag "Yes" t)
1521 (const :tag "Start with file name" file)
1522 (const :tag "Start with full file path" full-file-path)))
1524 (defcustom org-outline-path-complete-in-steps t
1525 "Non-nil means, complete the outline path in hierarchical steps.
1526 When Org-mode uses the refile interface to select an outline path
1527 \(see variable `org-refile-use-outline-path'), the completion of
1528 the path can be done is a single go, or if can be done in steps down
1529 the headline hierarchy. Going in steps is probably the best if you
1530 do not use a special completion package like `ido' or `icicles'.
1531 However, when using these packages, going in one step can be very
1532 fast, while still showing the whole path to the entry."
1533 :group 'org-refile
1534 :type 'boolean)
1536 (defgroup org-todo nil
1537 "Options concerning TODO items in Org-mode."
1538 :tag "Org TODO"
1539 :group 'org)
1541 (defgroup org-progress nil
1542 "Options concerning Progress logging in Org-mode."
1543 :tag "Org Progress"
1544 :group 'org-time)
1546 (defvar org-todo-interpretation-widgets
1548 (:tag "Sequence (cycling hits every state)" sequence)
1549 (:tag "Type (cycling directly to DONE)" type))
1550 "The available interpretation symbols for customizing
1551 `org-todo-keywords'.
1552 Interested libraries should add to this list.")
1554 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1555 "List of TODO entry keyword sequences and their interpretation.
1556 \\<org-mode-map>This is a list of sequences.
1558 Each sequence starts with a symbol, either `sequence' or `type',
1559 indicating if the keywords should be interpreted as a sequence of
1560 action steps, or as different types of TODO items. The first
1561 keywords are states requiring action - these states will select a headline
1562 for inclusion into the global TODO list Org-mode produces. If one of
1563 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1564 signify that no further action is necessary. If \"|\" is not found,
1565 the last keyword is treated as the only DONE state of the sequence.
1567 The command \\[org-todo] cycles an entry through these states, and one
1568 additional state where no keyword is present. For details about this
1569 cycling, see the manual.
1571 TODO keywords and interpretation can also be set on a per-file basis with
1572 the special #+SEQ_TODO and #+TYP_TODO lines.
1574 Each keyword can optionally specify a character for fast state selection
1575 \(in combination with the variable `org-use-fast-todo-selection')
1576 and specifiers for state change logging, using the same syntax
1577 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1578 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1579 indicates to record a time stamp each time this state is selected.
1581 Each keyword may also specify if a timestamp or a note should be
1582 recorded when entering or leaving the state, by adding additional
1583 characters in the parenthesis after the keyword. This looks like this:
1584 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1585 record only the time of the state change. With X and Y being either
1586 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1587 Y when leaving the state if and only if the *target* state does not
1588 define X. You may omit any of the fast-selection key or X or /Y,
1589 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1591 For backward compatibility, this variable may also be just a list
1592 of keywords - in this case the interpretation (sequence or type) will be
1593 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1594 :group 'org-todo
1595 :group 'org-keywords
1596 :type '(choice
1597 (repeat :tag "Old syntax, just keywords"
1598 (string :tag "Keyword"))
1599 (repeat :tag "New syntax"
1600 (cons
1601 (choice
1602 :tag "Interpretation"
1603 ;;Quick and dirty way to see
1604 ;;`org-todo-interpretations'. This takes the
1605 ;;place of item arguments
1606 :convert-widget
1607 (lambda (widget)
1608 (widget-put widget
1609 :args (mapcar
1610 #'(lambda (x)
1611 (widget-convert
1612 (cons 'const x)))
1613 org-todo-interpretation-widgets))
1614 widget))
1615 (repeat
1616 (string :tag "Keyword"))))))
1618 (defvar org-todo-keywords-1 nil
1619 "All TODO and DONE keywords active in a buffer.")
1620 (make-variable-buffer-local 'org-todo-keywords-1)
1621 (defvar org-todo-keywords-for-agenda nil)
1622 (defvar org-done-keywords-for-agenda nil)
1623 (defvar org-todo-keyword-alist-for-agenda nil)
1624 (defvar org-tag-alist-for-agenda nil)
1625 (defvar org-agenda-contributing-files nil)
1626 (defvar org-not-done-keywords nil)
1627 (make-variable-buffer-local 'org-not-done-keywords)
1628 (defvar org-done-keywords nil)
1629 (make-variable-buffer-local 'org-done-keywords)
1630 (defvar org-todo-heads nil)
1631 (make-variable-buffer-local 'org-todo-heads)
1632 (defvar org-todo-sets nil)
1633 (make-variable-buffer-local 'org-todo-sets)
1634 (defvar org-todo-log-states nil)
1635 (make-variable-buffer-local 'org-todo-log-states)
1636 (defvar org-todo-kwd-alist nil)
1637 (make-variable-buffer-local 'org-todo-kwd-alist)
1638 (defvar org-todo-key-alist nil)
1639 (make-variable-buffer-local 'org-todo-key-alist)
1640 (defvar org-todo-key-trigger nil)
1641 (make-variable-buffer-local 'org-todo-key-trigger)
1643 (defcustom org-todo-interpretation 'sequence
1644 "Controls how TODO keywords are interpreted.
1645 This variable is in principle obsolete and is only used for
1646 backward compatibility, if the interpretation of todo keywords is
1647 not given already in `org-todo-keywords'. See that variable for
1648 more information."
1649 :group 'org-todo
1650 :group 'org-keywords
1651 :type '(choice (const sequence)
1652 (const type)))
1654 (defcustom org-use-fast-todo-selection t
1655 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1656 This variable describes if and under what circumstances the cycling
1657 mechanism for TODO keywords will be replaced by a single-key, direct
1658 selection scheme.
1660 When nil, fast selection is never used.
1662 When the symbol `prefix', it will be used when `org-todo' is called with
1663 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1664 in an agenda buffer.
1666 When t, fast selection is used by default. In this case, the prefix
1667 argument forces cycling instead.
1669 In all cases, the special interface is only used if access keys have actually
1670 been assigned by the user, i.e. if keywords in the configuration are followed
1671 by a letter in parenthesis, like TODO(t)."
1672 :group 'org-todo
1673 :type '(choice
1674 (const :tag "Never" nil)
1675 (const :tag "By default" t)
1676 (const :tag "Only with C-u C-c C-t" prefix)))
1678 (defcustom org-provide-todo-statistics t
1679 "Non-nil means, update todo statistics after insert and toggle.
1680 When this is set, todo statistics is updated in the parent of the current
1681 entry each time a todo state is changed."
1682 :group 'org-todo
1683 :type 'boolean)
1685 (defcustom org-after-todo-state-change-hook nil
1686 "Hook which is run after the state of a TODO item was changed.
1687 The new state (a string with a TODO keyword, or nil) is available in the
1688 Lisp variable `state'."
1689 :group 'org-todo
1690 :type 'hook)
1692 (defvar org-blocker-hook nil
1693 "Hook for functions that are allowed to block a state change.
1695 Each function gets as its single argument a property list, see
1696 `org-trigger-hook' for more information about this list.
1698 If any of the functions in this hook returns nil, the state change
1699 is blocked.")
1701 (defvar org-trigger-hook nil
1702 "Hook for functions that are triggered by a state change.
1704 Each function gets as its single argument a property list with at least
1705 the following elements:
1707 (:type type-of-change :position pos-at-entry-start
1708 :from old-state :to new-state)
1710 Depending on the type, more properties may be present.
1712 This mechanism is currently implemented for:
1714 TODO state changes
1715 ------------------
1716 :type todo-state-change
1717 :from previous state (keyword as a string), or nil, or a symbol
1718 'todo' or 'done', to indicate the general type of state.
1719 :to new state, like in :from")
1721 (defcustom org-enforce-todo-dependencies nil
1722 "Non-nil means, undone TODO entries will block switching the parent to DONE.
1723 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
1724 be blocked if any prior sibling is not yet done.
1725 Finally, if the parent is blocked because of ordered siblings of its own,
1726 the child will also be blocked.
1727 This variable needs to be set before org.el is loaded, and you need to
1728 restart Emacs after a change to make the change effective. The only way
1729 to change is while Emacs is running is through the customize interface."
1730 :set (lambda (var val)
1731 (set var val)
1732 (if val
1733 (add-hook 'org-blocker-hook
1734 'org-block-todo-from-children-or-siblings-or-parent)
1735 (remove-hook 'org-blocker-hook
1736 'org-block-todo-from-children-or-siblings-or-parent)))
1737 :group 'org-todo
1738 :type 'boolean)
1740 (defcustom org-enforce-todo-checkbox-dependencies nil
1741 "Non-nil means, unchecked boxes will block switching the parent to DONE.
1742 When this is nil, checkboxes have no influence on switching TODO states.
1743 When non-nil, you first need to check off all check boxes before the TODO
1744 entry can be switched to DONE.
1745 This variable needs to be set before org.el is loaded, and you need to
1746 restart Emacs after a change to make the change effective. The only way
1747 to change is while Emacs is running is through the customize interface."
1748 :set (lambda (var val)
1749 (set var val)
1750 (if val
1751 (add-hook 'org-blocker-hook
1752 'org-block-todo-from-checkboxes)
1753 (remove-hook 'org-blocker-hook
1754 'org-block-todo-from-checkboxes)))
1755 :group 'org-todo
1756 :type 'boolean)
1758 (defcustom org-todo-state-tags-triggers nil
1759 "Tag changes that should be triggered by TODO state changes.
1760 This is a list. Each entry is
1762 (state-change (tag . flag) .......)
1764 State-change can be a string with a state, and empty string to indicate the
1765 state that has no TODO keyword, or it can be one of the symbols `todo'
1766 or `done', meaning any not-done or done state, respectively."
1767 :group 'org-todo
1768 :group 'org-tags
1769 :type '(repeat
1770 (cons (choice :tag "When changing to"
1771 (const :tag "Not-done state" todo)
1772 (const :tag "Done state" done)
1773 (string :tag "State"))
1774 (repeat
1775 (cons :tag "Tag action"
1776 (string :tag "Tag")
1777 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1779 (defcustom org-log-done nil
1780 "Information to record when a task moves to the DONE state.
1782 Possible values are:
1784 nil Don't add anything, just change the keyword
1785 time Add a time stamp to the task
1786 note Prompt a closing note and add it with template `org-log-note-headings'
1788 This option can also be set with on a per-file-basis with
1790 #+STARTUP: nologdone
1791 #+STARTUP: logdone
1792 #+STARTUP: lognotedone
1794 You can have local logging settings for a subtree by setting the LOGGING
1795 property to one or more of these keywords."
1796 :group 'org-todo
1797 :group 'org-progress
1798 :type '(choice
1799 (const :tag "No logging" nil)
1800 (const :tag "Record CLOSED timestamp" time)
1801 (const :tag "Record CLOSED timestamp with closing note." note)))
1803 ;; Normalize old uses of org-log-done.
1804 (cond
1805 ((eq org-log-done t) (setq org-log-done 'time))
1806 ((and (listp org-log-done) (memq 'done org-log-done))
1807 (setq org-log-done 'note)))
1809 (defcustom org-log-note-clock-out nil
1810 "Non-nil means, record a note when clocking out of an item.
1811 This can also be configured on a per-file basis by adding one of
1812 the following lines anywhere in the buffer:
1814 #+STARTUP: lognoteclock-out
1815 #+STARTUP: nolognoteclock-out"
1816 :group 'org-todo
1817 :group 'org-progress
1818 :type 'boolean)
1820 (defcustom org-log-done-with-time t
1821 "Non-nil means, the CLOSED time stamp will contain date and time.
1822 When nil, only the date will be recorded."
1823 :group 'org-progress
1824 :type 'boolean)
1826 (defcustom org-log-note-headings
1827 '((done . "CLOSING NOTE %t")
1828 (state . "State %-12s from %-12S %t")
1829 (note . "Note taken on %t")
1830 (clock-out . ""))
1831 "Headings for notes added to entries.
1832 The value is an alist, with the car being a symbol indicating the note
1833 context, and the cdr is the heading to be used. The heading may also be the
1834 empty string.
1835 %t in the heading will be replaced by a time stamp.
1836 %s will be replaced by the new TODO state, in double quotes.
1837 %S will be replaced by the old TODO state, in double quotes.
1838 %u will be replaced by the user name.
1839 %U will be replaced by the full user name."
1840 :group 'org-todo
1841 :group 'org-progress
1842 :type '(list :greedy t
1843 (cons (const :tag "Heading when closing an item" done) string)
1844 (cons (const :tag
1845 "Heading when changing todo state (todo sequence only)"
1846 state) string)
1847 (cons (const :tag "Heading when just taking a note" note) string)
1848 (cons (const :tag "Heading when clocking out" clock-out) string)))
1850 (unless (assq 'note org-log-note-headings)
1851 (push '(note . "%t") org-log-note-headings))
1853 (defcustom org-log-into-drawer nil
1854 "Non-nil means, insert state change notes and time stamps into a drawer.
1855 When nil, state changes notes will be inserted after the headline and
1856 any scheduling and clock lines, but not inside a drawer.
1858 The value of this variable should be the name of the drawer to use.
1859 LOGBOOK is proposed at the default drawer for this purpose, you can
1860 also set this to a string to define the drawer of your choice.
1862 A value of t is also allowed, representing \"LOGBOOK\".
1864 If this variable is set, `org-log-state-notes-insert-after-drawers'
1865 will be ignored."
1866 :group 'org-todo
1867 :group 'org-progress
1868 :type '(choice
1869 (const :tag "Not into a drawer" nil)
1870 (const :tag "LOGBOOK" t)
1871 (string :tag "Other")))
1873 (if (fboundp 'defvaralias)
1874 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
1876 (defcustom org-log-state-notes-insert-after-drawers nil
1877 "Non-nil means, insert state change notes after any drawers in entry.
1878 Only the drawers that *immediately* follow the headline and the
1879 deadline/scheduled line are skipped.
1880 When nil, insert notes right after the heading and perhaps the line
1881 with deadline/scheduling if present.
1883 This variable will have no effect if `org-log-into-drawer' is
1884 set."
1885 :group 'org-todo
1886 :group 'org-progress
1887 :type 'boolean)
1889 (defcustom org-log-states-order-reversed t
1890 "Non-nil means, the latest state change note will be directly after heading.
1891 When nil, the notes will be orderer according to time."
1892 :group 'org-todo
1893 :group 'org-progress
1894 :type 'boolean)
1896 (defcustom org-log-repeat 'time
1897 "Non-nil means, record moving through the DONE state when triggering repeat.
1898 An auto-repeating tasks is immediately switched back to TODO when marked
1899 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1900 the TODO keyword definition, or recording a closing note by setting
1901 `org-log-done', there will be no record of the task moving through DONE.
1902 This variable forces taking a note anyway. Possible values are:
1904 nil Don't force a record
1905 time Record a time stamp
1906 note Record a note
1908 This option can also be set with on a per-file-basis with
1910 #+STARTUP: logrepeat
1911 #+STARTUP: lognoterepeat
1912 #+STARTUP: nologrepeat
1914 You can have local logging settings for a subtree by setting the LOGGING
1915 property to one or more of these keywords."
1916 :group 'org-todo
1917 :group 'org-progress
1918 :type '(choice
1919 (const :tag "Don't force a record" nil)
1920 (const :tag "Force recording the DONE state" time)
1921 (const :tag "Force recording a note with the DONE state" note)))
1924 (defgroup org-priorities nil
1925 "Priorities in Org-mode."
1926 :tag "Org Priorities"
1927 :group 'org-todo)
1929 (defcustom org-highest-priority ?A
1930 "The highest priority of TODO items. A character like ?A, ?B etc.
1931 Must have a smaller ASCII number than `org-lowest-priority'."
1932 :group 'org-priorities
1933 :type 'character)
1935 (defcustom org-lowest-priority ?C
1936 "The lowest priority of TODO items. A character like ?A, ?B etc.
1937 Must have a larger ASCII number than `org-highest-priority'."
1938 :group 'org-priorities
1939 :type 'character)
1941 (defcustom org-default-priority ?B
1942 "The default priority of TODO items.
1943 This is the priority an item get if no explicit priority is given."
1944 :group 'org-priorities
1945 :type 'character)
1947 (defcustom org-priority-start-cycle-with-default t
1948 "Non-nil means, start with default priority when starting to cycle.
1949 When this is nil, the first step in the cycle will be (depending on the
1950 command used) one higher or lower that the default priority."
1951 :group 'org-priorities
1952 :type 'boolean)
1954 (defgroup org-time nil
1955 "Options concerning time stamps and deadlines in Org-mode."
1956 :tag "Org Time"
1957 :group 'org)
1959 (defcustom org-insert-labeled-timestamps-at-point nil
1960 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1961 When nil, these labeled time stamps are forces into the second line of an
1962 entry, just after the headline. When scheduling from the global TODO list,
1963 the time stamp will always be forced into the second line."
1964 :group 'org-time
1965 :type 'boolean)
1967 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1968 "Formats for `format-time-string' which are used for time stamps.
1969 It is not recommended to change this constant.")
1971 (defcustom org-time-stamp-rounding-minutes '(0 5)
1972 "Number of minutes to round time stamps to.
1973 These are two values, the first applies when first creating a time stamp.
1974 The second applies when changing it with the commands `S-up' and `S-down'.
1975 When changing the time stamp, this means that it will change in steps
1976 of N minutes, as given by the second value.
1978 When a setting is 0 or 1, insert the time unmodified. Useful rounding
1979 numbers should be factors of 60, so for example 5, 10, 15.
1981 When this is larger than 1, you can still force an exact time-stamp by using
1982 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
1983 and by using a prefix arg to `S-up/down' to specify the exact number
1984 of minutes to shift."
1985 :group 'org-time
1986 :get '(lambda (var) ; Make sure all entries have 5 elements
1987 (if (integerp (default-value var))
1988 (list (default-value var) 5)
1989 (default-value var)))
1990 :type '(list
1991 (integer :tag "when inserting times")
1992 (integer :tag "when modifying times")))
1994 ;; Normalize old customizations of this variable.
1995 (when (integerp org-time-stamp-rounding-minutes)
1996 (setq org-time-stamp-rounding-minutes
1997 (list org-time-stamp-rounding-minutes
1998 org-time-stamp-rounding-minutes)))
2000 (defcustom org-display-custom-times nil
2001 "Non-nil means, overlay custom formats over all time stamps.
2002 The formats are defined through the variable `org-time-stamp-custom-formats'.
2003 To turn this on on a per-file basis, insert anywhere in the file:
2004 #+STARTUP: customtime"
2005 :group 'org-time
2006 :set 'set-default
2007 :type 'sexp)
2008 (make-variable-buffer-local 'org-display-custom-times)
2010 (defcustom org-time-stamp-custom-formats
2011 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2012 "Custom formats for time stamps. See `format-time-string' for the syntax.
2013 These are overlayed over the default ISO format if the variable
2014 `org-display-custom-times' is set. Time like %H:%M should be at the
2015 end of the second format."
2016 :group 'org-time
2017 :type 'sexp)
2019 (defun org-time-stamp-format (&optional long inactive)
2020 "Get the right format for a time string."
2021 (let ((f (if long (cdr org-time-stamp-formats)
2022 (car org-time-stamp-formats))))
2023 (if inactive
2024 (concat "[" (substring f 1 -1) "]")
2025 f)))
2027 (defcustom org-time-clocksum-format "%d:%02d"
2028 "The format string used when creating CLOCKSUM lines, or when
2029 org-mode generates a time duration."
2030 :group 'org-time
2031 :type 'string)
2033 (defcustom org-deadline-warning-days 14
2034 "No. of days before expiration during which a deadline becomes active.
2035 This variable governs the display in sparse trees and in the agenda.
2036 When 0 or negative, it means use this number (the absolute value of it)
2037 even if a deadline has a different individual lead time specified.
2039 Custom commands can set this variable in the options section."
2040 :group 'org-time
2041 :group 'org-agenda-daily/weekly
2042 :type 'integer)
2044 (defcustom org-read-date-prefer-future t
2045 "Non-nil means, assume future for incomplete date input from user.
2046 This affects the following situations:
2047 1. The user gives a day, but no month.
2048 For example, if today is the 15th, and you enter \"3\", Org-mode will
2049 read this as the third of *next* month. However, if you enter \"17\",
2050 it will be considered as *this* month.
2051 2. The user gives a month but not a year.
2052 For example, if it is april and you enter \"feb 2\", this will be read
2053 as feb 2, *next* year. \"May 5\", however, will be this year.
2055 Currently this does not work for ISO week specifications.
2057 When this option is nil, the current month and year will always be used
2058 as defaults."
2059 :group 'org-time
2060 :type 'boolean)
2062 (defcustom org-read-date-display-live t
2063 "Non-nil means, display current interpretation of date prompt live.
2064 This display will be in an overlay, in the minibuffer."
2065 :group 'org-time
2066 :type 'boolean)
2068 (defcustom org-read-date-popup-calendar t
2069 "Non-nil means, pop up a calendar when prompting for a date.
2070 In the calendar, the date can be selected with mouse-1. However, the
2071 minibuffer will also be active, and you can simply enter the date as well.
2072 When nil, only the minibuffer will be available."
2073 :group 'org-time
2074 :type 'boolean)
2075 (if (fboundp 'defvaralias)
2076 (defvaralias 'org-popup-calendar-for-date-prompt
2077 'org-read-date-popup-calendar))
2079 (defcustom org-read-date-minibuffer-setup-hook nil
2080 "Hook to be used to set up keys for the date/time interface.
2081 Add key definitions to `minibuffer-local-map', which will be a temporary
2082 copy."
2083 :group 'org-time
2084 :type 'hook)
2086 (defcustom org-extend-today-until 0
2087 "The hour when your day really ends. Must be an integer.
2088 This has influence for the following applications:
2089 - When switching the agenda to \"today\". It it is still earlier than
2090 the time given here, the day recognized as TODAY is actually yesterday.
2091 - When a date is read from the user and it is still before the time given
2092 here, the current date and time will be assumed to be yesterday, 23:59.
2093 Also, timestamps inserted in remember templates follow this rule.
2095 IMPORTANT: This is a feature whose implementation is and likely will
2096 remain incomplete. Really, it is only here because past midnight seems to
2097 be the favorite working time of John Wiegley :-)"
2098 :group 'org-time
2099 :type 'integer)
2101 (defcustom org-edit-timestamp-down-means-later nil
2102 "Non-nil means, S-down will increase the time in a time stamp.
2103 When nil, S-up will increase."
2104 :group 'org-time
2105 :type 'boolean)
2107 (defcustom org-calendar-follow-timestamp-change t
2108 "Non-nil means, make the calendar window follow timestamp changes.
2109 When a timestamp is modified and the calendar window is visible, it will be
2110 moved to the new date."
2111 :group 'org-time
2112 :type 'boolean)
2114 (defgroup org-tags nil
2115 "Options concerning tags in Org-mode."
2116 :tag "Org Tags"
2117 :group 'org)
2119 (defcustom org-tag-alist nil
2120 "List of tags allowed in Org-mode files.
2121 When this list is nil, Org-mode will base TAG input on what is already in the
2122 buffer.
2123 The value of this variable is an alist, the car of each entry must be a
2124 keyword as a string, the cdr may be a character that is used to select
2125 that tag through the fast-tag-selection interface.
2126 See the manual for details."
2127 :group 'org-tags
2128 :type '(repeat
2129 (choice
2130 (cons (string :tag "Tag name")
2131 (character :tag "Access char"))
2132 (const :tag "Start radio group" (:startgroup))
2133 (const :tag "End radio group" (:endgroup))
2134 (const :tag "New line" (:newline)))))
2136 (defcustom org-tag-persistent-alist nil
2137 "List of tags that will always appear in all Org-mode files.
2138 This is in addition to any in buffer settings or customizations
2139 of `org-tag-alist'.
2140 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2141 The value of this variable is an alist, the car of each entry must be a
2142 keyword as a string, the cdr may be a character that is used to select
2143 that tag through the fast-tag-selection interface.
2144 See the manual for details.
2145 To disable these tags on a per-file basis, insert anywhere in the file:
2146 #+STARTUP: noptag"
2147 :group 'org-tags
2148 :type '(repeat
2149 (choice
2150 (cons (string :tag "Tag name")
2151 (character :tag "Access char"))
2152 (const :tag "Start radio group" (:startgroup))
2153 (const :tag "End radio group" (:endgroup))
2154 (const :tag "New line" (:newline)))))
2156 (defvar org-file-tags nil
2157 "List of tags that can be inherited by all entries in the file.
2158 The tags will be inherited if the variable `org-use-tag-inheritance'
2159 says they should be.
2160 This variable is populated from #+TAG lines.")
2162 (defcustom org-use-fast-tag-selection 'auto
2163 "Non-nil means, use fast tag selection scheme.
2164 This is a special interface to select and deselect tags with single keys.
2165 When nil, fast selection is never used.
2166 When the symbol `auto', fast selection is used if and only if selection
2167 characters for tags have been configured, either through the variable
2168 `org-tag-alist' or through a #+TAGS line in the buffer.
2169 When t, fast selection is always used and selection keys are assigned
2170 automatically if necessary."
2171 :group 'org-tags
2172 :type '(choice
2173 (const :tag "Always" t)
2174 (const :tag "Never" nil)
2175 (const :tag "When selection characters are configured" 'auto)))
2177 (defcustom org-fast-tag-selection-single-key nil
2178 "Non-nil means, fast tag selection exits after first change.
2179 When nil, you have to press RET to exit it.
2180 During fast tag selection, you can toggle this flag with `C-c'.
2181 This variable can also have the value `expert'. In this case, the window
2182 displaying the tags menu is not even shown, until you press C-c again."
2183 :group 'org-tags
2184 :type '(choice
2185 (const :tag "No" nil)
2186 (const :tag "Yes" t)
2187 (const :tag "Expert" expert)))
2189 (defvar org-fast-tag-selection-include-todo nil
2190 "Non-nil means, fast tags selection interface will also offer TODO states.
2191 This is an undocumented feature, you should not rely on it.")
2193 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2194 "The column to which tags should be indented in a headline.
2195 If this number is positive, it specifies the column. If it is negative,
2196 it means that the tags should be flushright to that column. For example,
2197 -80 works well for a normal 80 character screen."
2198 :group 'org-tags
2199 :type 'integer)
2201 (defcustom org-auto-align-tags t
2202 "Non-nil means, realign tags after pro/demotion of TODO state change.
2203 These operations change the length of a headline and therefore shift
2204 the tags around. With this options turned on, after each such operation
2205 the tags are again aligned to `org-tags-column'."
2206 :group 'org-tags
2207 :type 'boolean)
2209 (defcustom org-use-tag-inheritance t
2210 "Non-nil means, tags in levels apply also for sublevels.
2211 When nil, only the tags directly given in a specific line apply there.
2212 This may also be a list of tags that should be inherited, or a regexp that
2213 matches tags that should be inherited. Additional control is possible
2214 with the variable `org-tags-exclude-from-inheritance' which gives an
2215 explicit list of tags to be excluded from inheritance., even if the value of
2216 `org-use-tag-inheritance' would select it for inheritance.
2218 If this option is t, a match early-on in a tree can lead to a large
2219 number of matches in the subtree when constructing the agenda or creating
2220 a sparse tree. If you only want to see the first match in a tree during
2221 a search, check out the variable `org-tags-match-list-sublevels'."
2222 :group 'org-tags
2223 :type '(choice
2224 (const :tag "Not" nil)
2225 (const :tag "Always" t)
2226 (repeat :tag "Specific tags" (string :tag "Tag"))
2227 (regexp :tag "Tags matched by regexp")))
2229 (defcustom org-tags-exclude-from-inheritance nil
2230 "List of tags that should never be inherited.
2231 This is a way to exclude a few tags from inheritance. For way to do
2232 the opposite, to actively allow inheritance for selected tags,
2233 see the variable `org-use-tag-inheritance'."
2234 :group 'org-tags
2235 :type '(repeat (string :tag "Tag")))
2237 (defun org-tag-inherit-p (tag)
2238 "Check if TAG is one that should be inherited."
2239 (cond
2240 ((member tag org-tags-exclude-from-inheritance) nil)
2241 ((eq org-use-tag-inheritance t) t)
2242 ((not org-use-tag-inheritance) nil)
2243 ((stringp org-use-tag-inheritance)
2244 (string-match org-use-tag-inheritance tag))
2245 ((listp org-use-tag-inheritance)
2246 (member tag org-use-tag-inheritance))
2247 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2249 (defcustom org-tags-match-list-sublevels t
2250 "Non-nil means list also sublevels of headlines matching a search.
2251 This variable applies to tags/property searches, and also to stuck
2252 projects because this search is based on a tags match as well.
2254 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2255 the sublevels of a headline matching a tag search often also match
2256 the same search. Listing all of them can create very long lists.
2257 Setting this variable to nil causes subtrees of a match to be skipped.
2259 As a special case, if the tag search is restricted to TODO items, the
2260 value of this variable is ignored and sublevels are always checked, to
2261 make sure all corresponding TODO items find their way into the list.
2263 This variable is semi-obsolete and probably should always be true. It
2264 is better to limit inheritance to certain tags using the variables
2265 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2266 :group 'org-tags
2267 :type '(choice
2268 (const :tag "No, don't list them" nil)
2269 (const :tag "Yes, do list them" t)
2270 (const :tag "List them, indented with leading dots" indented)))
2272 (defvar org-tags-history nil
2273 "History of minibuffer reads for tags.")
2274 (defvar org-last-tags-completion-table nil
2275 "The last used completion table for tags.")
2276 (defvar org-after-tags-change-hook nil
2277 "Hook that is run after the tags in a line have changed.")
2279 (defgroup org-properties nil
2280 "Options concerning properties in Org-mode."
2281 :tag "Org Properties"
2282 :group 'org)
2284 (defcustom org-property-format "%-10s %s"
2285 "How property key/value pairs should be formatted by `indent-line'.
2286 When `indent-line' hits a property definition, it will format the line
2287 according to this format, mainly to make sure that the values are
2288 lined-up with respect to each other."
2289 :group 'org-properties
2290 :type 'string)
2292 (defcustom org-use-property-inheritance nil
2293 "Non-nil means, properties apply also for sublevels.
2295 This setting is chiefly used during property searches. Turning it on can
2296 cause significant overhead when doing a search, which is why it is not
2297 on by default.
2299 When nil, only the properties directly given in the current entry count.
2300 When t, every property is inherited. The value may also be a list of
2301 properties that should have inheritance, or a regular expression matching
2302 properties that should be inherited.
2304 However, note that some special properties use inheritance under special
2305 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2306 and the properties ending in \"_ALL\" when they are used as descriptor
2307 for valid values of a property.
2309 Note for programmers:
2310 When querying an entry with `org-entry-get', you can control if inheritance
2311 should be used. By default, `org-entry-get' looks only at the local
2312 properties. You can request inheritance by setting the inherit argument
2313 to t (to force inheritance) or to `selective' (to respect the setting
2314 in this variable)."
2315 :group 'org-properties
2316 :type '(choice
2317 (const :tag "Not" nil)
2318 (const :tag "Always" t)
2319 (repeat :tag "Specific properties" (string :tag "Property"))
2320 (regexp :tag "Properties matched by regexp")))
2322 (defun org-property-inherit-p (property)
2323 "Check if PROPERTY is one that should be inherited."
2324 (cond
2325 ((eq org-use-property-inheritance t) t)
2326 ((not org-use-property-inheritance) nil)
2327 ((stringp org-use-property-inheritance)
2328 (string-match org-use-property-inheritance property))
2329 ((listp org-use-property-inheritance)
2330 (member property org-use-property-inheritance))
2331 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2333 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2334 "The default column format, if no other format has been defined.
2335 This variable can be set on the per-file basis by inserting a line
2337 #+COLUMNS: %25ITEM ....."
2338 :group 'org-properties
2339 :type 'string)
2341 (defcustom org-columns-ellipses ".."
2342 "The ellipses to be used when a field in column view is truncated.
2343 When this is the empty string, as many characters as possible are shown,
2344 but then there will be no visual indication that the field has been truncated.
2345 When this is a string of length N, the last N characters of a truncated
2346 field are replaced by this string. If the column is narrower than the
2347 ellipses string, only part of the ellipses string will be shown."
2348 :group 'org-properties
2349 :type 'string)
2351 (defcustom org-columns-modify-value-for-display-function nil
2352 "Function that modifies values for display in column view.
2353 For example, it can be used to cut out a certain part from a time stamp.
2354 The function must take 2 arguments:
2356 column-title The title of the column (*not* the property name)
2357 value The value that should be modified.
2359 The function should return the value that should be displayed,
2360 or nil if the normal value should be used."
2361 :group 'org-properties
2362 :type 'function)
2364 (defcustom org-effort-property "Effort"
2365 "The property that is being used to keep track of effort estimates.
2366 Effort estimates given in this property need to have the format H:MM."
2367 :group 'org-properties
2368 :group 'org-progress
2369 :type '(string :tag "Property"))
2371 (defconst org-global-properties-fixed
2372 '(("VISIBILITY_ALL" . "folded children content all"))
2373 "List of property/value pairs that can be inherited by any entry.
2375 These are fixed values, for the preset properties. The user variable
2376 that can be used to add to this list is `org-global-properties'.
2378 The entries in this list are cons cells where the car is a property
2379 name and cdr is a string with the value. If the value represents
2380 multiple items like an \"_ALL\" property, separate the items by
2381 spaces.")
2383 (defcustom org-global-properties nil
2384 "List of property/value pairs that can be inherited by any entry.
2386 This list will be combined with the constant `org-global-properties-fixed'.
2388 The entries in this list are cons cells where the car is a property
2389 name and cdr is a string with the value.
2391 You can set buffer-local values for the same purpose in the variable
2392 `org-file-properties' this by adding lines like
2394 #+PROPERTY: NAME VALUE"
2395 :group 'org-properties
2396 :type '(repeat
2397 (cons (string :tag "Property")
2398 (string :tag "Value"))))
2400 (defvar org-file-properties nil
2401 "List of property/value pairs that can be inherited by any entry.
2402 Valid for the current buffer.
2403 This variable is populated from #+PROPERTY lines.")
2404 (make-variable-buffer-local 'org-file-properties)
2406 (defgroup org-agenda nil
2407 "Options concerning agenda views in Org-mode."
2408 :tag "Org Agenda"
2409 :group 'org)
2411 (defvar org-category nil
2412 "Variable used by org files to set a category for agenda display.
2413 Such files should use a file variable to set it, for example
2415 # -*- mode: org; org-category: \"ELisp\"
2417 or contain a special line
2419 #+CATEGORY: ELisp
2421 If the file does not specify a category, then file's base name
2422 is used instead.")
2423 (make-variable-buffer-local 'org-category)
2424 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2426 (defcustom org-agenda-files nil
2427 "The files to be used for agenda display.
2428 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2429 \\[org-remove-file]. You can also use customize to edit the list.
2431 If an entry is a directory, all files in that directory that are matched by
2432 `org-agenda-file-regexp' will be part of the file list.
2434 If the value of the variable is not a list but a single file name, then
2435 the list of agenda files is actually stored and maintained in that file, one
2436 agenda file per line."
2437 :group 'org-agenda
2438 :type '(choice
2439 (repeat :tag "List of files and directories" file)
2440 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2442 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2443 "Regular expression to match files for `org-agenda-files'.
2444 If any element in the list in that variable contains a directory instead
2445 of a normal file, all files in that directory that are matched by this
2446 regular expression will be included."
2447 :group 'org-agenda
2448 :type 'regexp)
2450 (defcustom org-agenda-text-search-extra-files nil
2451 "List of extra files to be searched by text search commands.
2452 These files will be search in addition to the agenda files by the
2453 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2454 Note that these files will only be searched for text search commands,
2455 not for the other agenda views like todo lists, tag searches or the weekly
2456 agenda. This variable is intended to list notes and possibly archive files
2457 that should also be searched by these two commands.
2458 In fact, if the first element in the list is the symbol `agenda-archives',
2459 than all archive files of all agenda files will be added to the search
2460 scope."
2461 :group 'org-agenda
2462 :type '(set :greedy t
2463 (const :tag "Agenda Archives" agenda-archives)
2464 (repeat :inline t (file))))
2466 (if (fboundp 'defvaralias)
2467 (defvaralias 'org-agenda-multi-occur-extra-files
2468 'org-agenda-text-search-extra-files))
2470 (defcustom org-agenda-skip-unavailable-files nil
2471 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2472 A nil value means to remove them, after a query, from the list."
2473 :group 'org-agenda
2474 :type 'boolean)
2476 (defcustom org-calendar-to-agenda-key [?c]
2477 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2478 The command `org-calendar-goto-agenda' will be bound to this key. The
2479 default is the character `c' because then `c' can be used to switch back and
2480 forth between agenda and calendar."
2481 :group 'org-agenda
2482 :type 'sexp)
2484 (defcustom org-calendar-agenda-action-key [?k]
2485 "The key to be installed in `calendar-mode-map' for agenda-action.
2486 The command `org-agenda-action' will be bound to this key. The
2487 default is the character `k' because we use the same key in the agenda."
2488 :group 'org-agenda
2489 :type 'sexp)
2491 (eval-after-load "calendar"
2492 '(progn
2493 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2494 'org-calendar-goto-agenda)
2495 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2496 'org-agenda-action)))
2498 (defgroup org-latex nil
2499 "Options for embedding LaTeX code into Org-mode."
2500 :tag "Org LaTeX"
2501 :group 'org)
2503 (defcustom org-format-latex-options
2504 '(:foreground default :background default :scale 1.0
2505 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2506 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
2507 "Options for creating images from LaTeX fragments.
2508 This is a property list with the following properties:
2509 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2510 `default' means use the foreground of the default face.
2511 :background the background color, or \"Transparent\".
2512 `default' means use the background of the default face.
2513 :scale a scaling factor for the size of the images.
2514 :html-foreground, :html-background, :html-scale
2515 the same numbers for HTML export.
2516 :matchers a list indicating which matchers should be used to
2517 find LaTeX fragments. Valid members of this list are:
2518 \"begin\" find environments
2519 \"$1\" find single characters surrounded by $.$
2520 \"$\" find math expressions surrounded by $...$
2521 \"$$\" find math expressions surrounded by $$....$$
2522 \"\\(\" find math expressions surrounded by \\(...\\)
2523 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2524 :group 'org-latex
2525 :type 'plist)
2527 (defcustom org-format-latex-header "\\documentclass{article}
2528 \\usepackage{fullpage} % do not remove
2529 \\usepackage{amssymb}
2530 \\usepackage[usenames]{color}
2531 \\usepackage{amsmath}
2532 \\usepackage{latexsym}
2533 \\usepackage[mathscr]{eucal}
2534 \\pagestyle{empty} % do not remove"
2535 "The document header used for processing LaTeX fragments."
2536 :group 'org-latex
2537 :type 'string)
2540 (defgroup org-font-lock nil
2541 "Font-lock settings for highlighting in Org-mode."
2542 :tag "Org Font Lock"
2543 :group 'org)
2545 (defcustom org-level-color-stars-only nil
2546 "Non-nil means fontify only the stars in each headline.
2547 When nil, the entire headline is fontified.
2548 Changing it requires restart of `font-lock-mode' to become effective
2549 also in regions already fontified."
2550 :group 'org-font-lock
2551 :type 'boolean)
2553 (defcustom org-hide-leading-stars nil
2554 "Non-nil means, hide the first N-1 stars in a headline.
2555 This works by using the face `org-hide' for these stars. This
2556 face is white for a light background, and black for a dark
2557 background. You may have to customize the face `org-hide' to
2558 make this work.
2559 Changing it requires restart of `font-lock-mode' to become effective
2560 also in regions already fontified.
2561 You may also set this on a per-file basis by adding one of the following
2562 lines to the buffer:
2564 #+STARTUP: hidestars
2565 #+STARTUP: showstars"
2566 :group 'org-font-lock
2567 :type 'boolean)
2569 (defcustom org-fontify-done-headline nil
2570 "Non-nil means, change the face of a headline if it is marked DONE.
2571 Normally, only the TODO/DONE keyword indicates the state of a headline.
2572 When this is non-nil, the headline after the keyword is set to the
2573 `org-headline-done' as an additional indication."
2574 :group 'org-font-lock
2575 :type 'boolean)
2577 (defcustom org-fontify-emphasized-text t
2578 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2579 Changing this variable requires a restart of Emacs to take effect."
2580 :group 'org-font-lock
2581 :type 'boolean)
2583 (defcustom org-highlight-latex-fragments-and-specials nil
2584 "Non-nil means, fontify what is treated specially by the exporters."
2585 :group 'org-font-lock
2586 :type 'boolean)
2588 (defcustom org-hide-emphasis-markers nil
2589 "Non-nil mean font-lock should hide the emphasis marker characters."
2590 :group 'org-font-lock
2591 :type 'boolean)
2593 (defvar org-emph-re nil
2594 "Regular expression for matching emphasis.")
2595 (defvar org-verbatim-re nil
2596 "Regular expression for matching verbatim text.")
2597 (defvar org-emphasis-regexp-components) ; defined just below
2598 (defvar org-emphasis-alist) ; defined just below
2599 (defun org-set-emph-re (var val)
2600 "Set variable and compute the emphasis regular expression."
2601 (set var val)
2602 (when (and (boundp 'org-emphasis-alist)
2603 (boundp 'org-emphasis-regexp-components)
2604 org-emphasis-alist org-emphasis-regexp-components)
2605 (let* ((e org-emphasis-regexp-components)
2606 (pre (car e))
2607 (post (nth 1 e))
2608 (border (nth 2 e))
2609 (body (nth 3 e))
2610 (nl (nth 4 e))
2611 (body1 (concat body "*?"))
2612 (markers (mapconcat 'car org-emphasis-alist ""))
2613 (vmarkers (mapconcat
2614 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2615 org-emphasis-alist "")))
2616 ;; make sure special characters appear at the right position in the class
2617 (if (string-match "\\^" markers)
2618 (setq markers (concat (replace-match "" t t markers) "^")))
2619 (if (string-match "-" markers)
2620 (setq markers (concat (replace-match "" t t markers) "-")))
2621 (if (string-match "\\^" vmarkers)
2622 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2623 (if (string-match "-" vmarkers)
2624 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2625 (if (> nl 0)
2626 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2627 (int-to-string nl) "\\}")))
2628 ;; Make the regexp
2629 (setq org-emph-re
2630 (concat "\\([" pre "]\\|^\\)"
2631 "\\("
2632 "\\([" markers "]\\)"
2633 "\\("
2634 "[^" border "]\\|"
2635 "[^" border "]"
2636 body1
2637 "[^" border "]"
2638 "\\)"
2639 "\\3\\)"
2640 "\\([" post "]\\|$\\)"))
2641 (setq org-verbatim-re
2642 (concat "\\([" pre "]\\|^\\)"
2643 "\\("
2644 "\\([" vmarkers "]\\)"
2645 "\\("
2646 "[^" border "]\\|"
2647 "[^" border "]"
2648 body1
2649 "[^" border "]"
2650 "\\)"
2651 "\\3\\)"
2652 "\\([" post "]\\|$\\)")))))
2654 (defcustom org-emphasis-regexp-components
2655 '(" \t('\"{" "- \t.,:!?;'\")}" " \t\r\n,\"'" "." 1)
2656 "Components used to build the regular expression for emphasis.
2657 This is a list with 6 entries. Terminology: In an emphasis string
2658 like \" *strong word* \", we call the initial space PREMATCH, the final
2659 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2660 and \"trong wor\" is the body. The different components in this variable
2661 specify what is allowed/forbidden in each part:
2663 pre Chars allowed as prematch. Beginning of line will be allowed too.
2664 post Chars allowed as postmatch. End of line will be allowed too.
2665 border The chars *forbidden* as border characters.
2666 body-regexp A regexp like \".\" to match a body character. Don't use
2667 non-shy groups here, and don't allow newline here.
2668 newline The maximum number of newlines allowed in an emphasis exp.
2670 Use customize to modify this, or restart Emacs after changing it."
2671 :group 'org-font-lock
2672 :set 'org-set-emph-re
2673 :type '(list
2674 (sexp :tag "Allowed chars in pre ")
2675 (sexp :tag "Allowed chars in post ")
2676 (sexp :tag "Forbidden chars in border ")
2677 (sexp :tag "Regexp for body ")
2678 (integer :tag "number of newlines allowed")
2679 (option (boolean :tag "Please ignore this button"))))
2681 (defcustom org-emphasis-alist
2682 `(("*" bold "<b>" "</b>")
2683 ("/" italic "<i>" "</i>")
2684 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
2685 ("=" org-code "<code>" "</code>" verbatim)
2686 ("~" org-verbatim "<code>" "</code>" verbatim)
2687 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2688 "<del>" "</del>")
2690 "Special syntax for emphasized text.
2691 Text starting and ending with a special character will be emphasized, for
2692 example *bold*, _underlined_ and /italic/. This variable sets the marker
2693 characters, the face to be used by font-lock for highlighting in Org-mode
2694 Emacs buffers, and the HTML tags to be used for this.
2695 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
2696 Use customize to modify this, or restart Emacs after changing it."
2697 :group 'org-font-lock
2698 :set 'org-set-emph-re
2699 :type '(repeat
2700 (list
2701 (string :tag "Marker character")
2702 (choice
2703 (face :tag "Font-lock-face")
2704 (plist :tag "Face property list"))
2705 (string :tag "HTML start tag")
2706 (string :tag "HTML end tag")
2707 (option (const verbatim)))))
2709 ;;; Miscellaneous options
2711 (defgroup org-completion nil
2712 "Completion in Org-mode."
2713 :tag "Org Completion"
2714 :group 'org)
2716 (defcustom org-completion-use-ido nil
2717 "Non-nil means, use ido completion wherever possible.
2718 Note that `ido-mode' must be active for this variable to be relevant.
2719 If you decide to turn this variable on, you might well want to turn off
2720 `org-outline-path-complete-in-steps'."
2721 :group 'org-completion
2722 :type 'boolean)
2724 (defcustom org-completion-fallback-command 'hippie-expand
2725 "The expansion command called by \\[org-complete] in normal context.
2726 Normal means, no org-mode-specific context."
2727 :group 'org-completion
2728 :type 'function)
2730 ;;; Functions and variables from ther packages
2731 ;; Declared here to avoid compiler warnings
2733 ;; XEmacs only
2734 (defvar outline-mode-menu-heading)
2735 (defvar outline-mode-menu-show)
2736 (defvar outline-mode-menu-hide)
2737 (defvar zmacs-regions) ; XEmacs regions
2739 ;; Emacs only
2740 (defvar mark-active)
2742 ;; Various packages
2743 (declare-function find-library-name "find-func" (library))
2744 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2745 (declare-function calendar-forward-day "cal-move" (arg))
2746 (declare-function calendar-goto-date "cal-move" (date))
2747 (declare-function calendar-goto-today "cal-move" ())
2748 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2749 (defvar calc-embedded-close-formula)
2750 (defvar calc-embedded-open-formula)
2751 (declare-function cdlatex-tab "ext:cdlatex" ())
2752 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2753 (defvar font-lock-unfontify-region-function)
2754 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2755 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2756 (defvar iswitchb-temp-buflist)
2757 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2758 (defvar org-agenda-tags-todo-honor-ignore-options)
2759 (declare-function org-agenda-skip "org-agenda" ())
2760 (declare-function org-format-agenda-item "org-agenda"
2761 (extra txt &optional category tags dotime noprefix remove-re))
2762 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2763 (declare-function org-agenda-change-all-lines "org-agenda"
2764 (newhead hdmarker &optional fixface just-this))
2765 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2766 (declare-function org-agenda-maybe-redo "org-agenda" ())
2767 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2768 (beg end))
2769 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
2770 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
2771 "org-agenda" (&optional end))
2773 (declare-function parse-time-string "parse-time" (string))
2774 (declare-function remember "remember" (&optional initial))
2775 (declare-function remember-buffer-desc "remember" ())
2776 (declare-function remember-finalize "remember" ())
2777 (defvar remember-save-after-remembering)
2778 (defvar remember-data-file)
2779 (defvar remember-register)
2780 (defvar remember-buffer)
2781 (defvar remember-handler-functions)
2782 (defvar remember-annotation-functions)
2783 (defvar texmathp-why)
2784 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2785 (declare-function table--at-cell-p "table" (position &optional object at-column))
2787 (defvar w3m-current-url)
2788 (defvar w3m-current-title)
2790 (defvar org-latex-regexps)
2792 ;;; Autoload and prepare some org modules
2794 ;; Some table stuff that needs to be defined here, because it is used
2795 ;; by the functions setting up org-mode or checking for table context.
2797 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2798 "Detects an org-type or table-type table.")
2799 (defconst org-table-line-regexp "^[ \t]*|"
2800 "Detects an org-type table line.")
2801 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2802 "Detects an org-type table line.")
2803 (defconst org-table-hline-regexp "^[ \t]*|-"
2804 "Detects an org-type table hline.")
2805 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2806 "Detects a table-type table hline.")
2807 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2808 "Searching from within a table (any type) this finds the first line
2809 outside the table.")
2811 ;; Autoload the functions in org-table.el that are needed by functions here.
2813 (eval-and-compile
2814 (org-autoload "org-table"
2815 '(org-table-align org-table-begin org-table-blank-field
2816 org-table-convert org-table-convert-region org-table-copy-down
2817 org-table-copy-region org-table-create
2818 org-table-create-or-convert-from-region
2819 org-table-create-with-table.el org-table-current-dline
2820 org-table-cut-region org-table-delete-column org-table-edit-field
2821 org-table-edit-formulas org-table-end org-table-eval-formula
2822 org-table-export org-table-field-info
2823 org-table-get-stored-formulas org-table-goto-column
2824 org-table-hline-and-move org-table-import org-table-insert-column
2825 org-table-insert-hline org-table-insert-row org-table-iterate
2826 org-table-justify-field-maybe org-table-kill-row
2827 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2828 org-table-move-column org-table-move-column-left
2829 org-table-move-column-right org-table-move-row
2830 org-table-move-row-down org-table-move-row-up
2831 org-table-next-field org-table-next-row org-table-paste-rectangle
2832 org-table-previous-field org-table-recalculate
2833 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2834 org-table-toggle-coordinate-overlays
2835 org-table-toggle-formula-debugger org-table-wrap-region
2836 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
2838 (defun org-at-table-p (&optional table-type)
2839 "Return t if the cursor is inside an org-type table.
2840 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2841 (if org-enable-table-editor
2842 (save-excursion
2843 (beginning-of-line 1)
2844 (looking-at (if table-type org-table-any-line-regexp
2845 org-table-line-regexp)))
2846 nil))
2847 (defsubst org-table-p () (org-at-table-p))
2849 (defun org-at-table.el-p ()
2850 "Return t if and only if we are at a table.el table."
2851 (and (org-at-table-p 'any)
2852 (save-excursion
2853 (goto-char (org-table-begin 'any))
2854 (looking-at org-table1-hline-regexp))))
2855 (defun org-table-recognize-table.el ()
2856 "If there is a table.el table nearby, recognize it and move into it."
2857 (if org-table-tab-recognizes-table.el
2858 (if (org-at-table.el-p)
2859 (progn
2860 (beginning-of-line 1)
2861 (if (looking-at org-table-dataline-regexp)
2863 (if (looking-at org-table1-hline-regexp)
2864 (progn
2865 (beginning-of-line 2)
2866 (if (looking-at org-table-any-border-regexp)
2867 (beginning-of-line -1)))))
2868 (if (re-search-forward "|" (org-table-end t) t)
2869 (progn
2870 (require 'table)
2871 (if (table--at-cell-p (point))
2873 (message "recognizing table.el table...")
2874 (table-recognize-table)
2875 (message "recognizing table.el table...done")))
2876 (error "This should not happen..."))
2878 nil)
2879 nil))
2881 (defun org-at-table-hline-p ()
2882 "Return t if the cursor is inside a hline in a table."
2883 (if org-enable-table-editor
2884 (save-excursion
2885 (beginning-of-line 1)
2886 (looking-at org-table-hline-regexp))
2887 nil))
2889 (defvar org-table-clean-did-remove-column nil)
2891 (defun org-table-map-tables (function)
2892 "Apply FUNCTION to the start of all tables in the buffer."
2893 (save-excursion
2894 (save-restriction
2895 (widen)
2896 (goto-char (point-min))
2897 (while (re-search-forward org-table-any-line-regexp nil t)
2898 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2899 (beginning-of-line 1)
2900 (if (looking-at org-table-line-regexp)
2901 (save-excursion (funcall function)))
2902 (re-search-forward org-table-any-border-regexp nil 1))))
2903 (message "Mapping tables: done"))
2905 ;; Declare and autoload functions from org-exp.el
2907 (declare-function org-default-export-plist "org-exp")
2908 (declare-function org-infile-export-plist "org-exp")
2909 (declare-function org-get-current-options "org-exp")
2910 (eval-and-compile
2911 (org-autoload "org-exp"
2912 '(org-export org-export-as-ascii org-export-visible
2913 org-insert-export-options-template org-export-as-html-and-open
2914 org-export-as-html-batch org-export-as-html-to-buffer
2915 org-replace-region-by-html org-export-region-as-html
2916 org-export-as-html org-export-icalendar-this-file
2917 org-export-icalendar-all-agenda-files
2918 org-table-clean-before-export
2919 org-export-icalendar-combine-agenda-files org-export-as-xoxo)))
2921 ;; Declare and autoload functions from org-agenda.el
2923 (eval-and-compile
2924 (org-autoload "org-agenda"
2925 '(org-agenda org-agenda-list org-search-view
2926 org-todo-list org-tags-view org-agenda-list-stuck-projects
2927 org-diary org-agenda-to-appt
2928 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
2930 ;; Autoload org-remember
2932 (eval-and-compile
2933 (org-autoload "org-remember"
2934 '(org-remember-insinuate org-remember-annotation
2935 org-remember-apply-template org-remember org-remember-handler)))
2937 ;; Autoload org-clock.el
2940 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
2941 (beg end))
2942 (declare-function org-clock-update-mode-line "org-clock" ())
2943 (defvar org-clock-start-time)
2944 (defvar org-clock-marker (make-marker)
2945 "Marker recording the last clock-in.")
2947 (eval-and-compile
2948 (org-autoload
2949 "org-clock"
2950 '(org-clock-in org-clock-out org-clock-cancel
2951 org-clock-goto org-clock-sum org-clock-display
2952 org-clock-remove-overlays org-clock-report
2953 org-clocktable-shift org-dblock-write:clocktable
2954 org-get-clocktable)))
2956 (defun org-clock-update-time-maybe ()
2957 "If this is a CLOCK line, update it and return t.
2958 Otherwise, return nil."
2959 (interactive)
2960 (save-excursion
2961 (beginning-of-line 1)
2962 (skip-chars-forward " \t")
2963 (when (looking-at org-clock-string)
2964 (let ((re (concat "[ \t]*" org-clock-string
2965 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
2966 "\\([ \t]*=>.*\\)?\\)?"))
2967 ts te h m s neg)
2968 (cond
2969 ((not (looking-at re))
2970 nil)
2971 ((not (match-end 2))
2972 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2973 (> org-clock-marker (point))
2974 (<= org-clock-marker (point-at-eol)))
2975 ;; The clock is running here
2976 (setq org-clock-start-time
2977 (apply 'encode-time
2978 (org-parse-time-string (match-string 1))))
2979 (org-clock-update-mode-line)))
2981 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
2982 (end-of-line 1)
2983 (setq ts (match-string 1)
2984 te (match-string 3))
2985 (setq s (- (time-to-seconds
2986 (apply 'encode-time (org-parse-time-string te)))
2987 (time-to-seconds
2988 (apply 'encode-time (org-parse-time-string ts))))
2989 neg (< s 0)
2990 s (abs s)
2991 h (floor (/ s 3600))
2992 s (- s (* 3600 h))
2993 m (floor (/ s 60))
2994 s (- s (* 60 s)))
2995 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
2996 t))))))
2998 (defun org-check-running-clock ()
2999 "Check if the current buffer contains the running clock.
3000 If yes, offer to stop it and to save the buffer with the changes."
3001 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3002 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
3003 (buffer-name))))
3004 (org-clock-out)
3005 (when (y-or-n-p "Save changed buffer?")
3006 (save-buffer))))
3008 (defun org-clocktable-try-shift (dir n)
3009 "Check if this line starts a clock table, if yes, shift the time block."
3010 (when (org-match-line "#\\+BEGIN: clocktable\\>")
3011 (org-clocktable-shift dir n)))
3013 ;; Autoload org-timer.el
3015 (eval-and-compile
3016 (org-autoload
3017 "org-timer"
3018 '(org-timer-start org-timer org-timer-item
3019 org-timer-change-times-in-region)))
3021 ;; Autoload org-feed.el
3023 (eval-and-compile
3024 (org-autoload
3025 "org-feed"
3026 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
3029 ;; Autoload archiving code
3030 ;; The stuff that is needed for cycling and tags has to be defined here.
3032 (defgroup org-archive nil
3033 "Options concerning archiving in Org-mode."
3034 :tag "Org Archive"
3035 :group 'org-structure)
3037 (defcustom org-archive-location "%s_archive::"
3038 "The location where subtrees should be archived.
3040 The value of this variable is a string, consisting of two parts,
3041 separated by a double-colon. The first part is a filename and
3042 the second part is a headline.
3044 When the filename is omitted, archiving happens in the same file.
3045 %s in the filename will be replaced by the current file
3046 name (without the directory part). Archiving to a different file
3047 is useful to keep archived entries from contributing to the
3048 Org-mode Agenda.
3050 The archived entries will be filed as subtrees of the specified
3051 headline. When the headline is omitted, the subtrees are simply
3052 filed away at the end of the file, as top-level entries. Also in
3053 the heading you can use %s to represent the file name, this can be
3054 useful when using the same archive for a number of different files.
3056 Here are a few examples:
3057 \"%s_archive::\"
3058 If the current file is Projects.org, archive in file
3059 Projects.org_archive, as top-level trees. This is the default.
3061 \"::* Archived Tasks\"
3062 Archive in the current file, under the top-level headline
3063 \"* Archived Tasks\".
3065 \"~/org/archive.org::\"
3066 Archive in file ~/org/archive.org (absolute path), as top-level trees.
3068 \"~/org/archive.org::From %s\"
3069 Archive in file ~/org/archive.org (absolute path), und headlines
3070 \"From FILENAME\" where file name is the current file name.
3072 \"basement::** Finished Tasks\"
3073 Archive in file ./basement (relative path), as level 3 trees
3074 below the level 2 heading \"** Finished Tasks\".
3076 You may set this option on a per-file basis by adding to the buffer a
3077 line like
3079 #+ARCHIVE: basement::** Finished Tasks
3081 You may also define it locally for a subtree by setting an ARCHIVE property
3082 in the entry. If such a property is found in an entry, or anywhere up
3083 the hierarchy, it will be used."
3084 :group 'org-archive
3085 :type 'string)
3087 (defcustom org-archive-tag "ARCHIVE"
3088 "The tag that marks a subtree as archived.
3089 An archived subtree does not open during visibility cycling, and does
3090 not contribute to the agenda listings.
3091 After changing this, font-lock must be restarted in the relevant buffers to
3092 get the proper fontification."
3093 :group 'org-archive
3094 :group 'org-keywords
3095 :type 'string)
3097 (defcustom org-agenda-skip-archived-trees t
3098 "Non-nil means, the agenda will skip any items located in archived trees.
3099 An archived tree is a tree marked with the tag ARCHIVE. The use of this
3100 variable is no longer recommended, you should leave it at the value t.
3101 Instead, use the key `v' to cycle the archives-mode in the agenda."
3102 :group 'org-archive
3103 :group 'org-agenda-skip
3104 :type 'boolean)
3106 (defcustom org-columns-skip-arrchived-trees t
3107 "Non-nil means, irgnore archived trees when creating column view."
3108 :group 'org-archive
3109 :group 'org-properties
3110 :type 'boolean)
3112 (defcustom org-cycle-open-archived-trees nil
3113 "Non-nil means, `org-cycle' will open archived trees.
3114 An archived tree is a tree marked with the tag ARCHIVE.
3115 When nil, archived trees will stay folded. You can still open them with
3116 normal outline commands like `show-all', but not with the cycling commands."
3117 :group 'org-archive
3118 :group 'org-cycle
3119 :type 'boolean)
3121 (defcustom org-sparse-tree-open-archived-trees nil
3122 "Non-nil means sparse tree construction shows matches in archived trees.
3123 When nil, matches in these trees are highlighted, but the trees are kept in
3124 collapsed state."
3125 :group 'org-archive
3126 :group 'org-sparse-trees
3127 :type 'boolean)
3129 (defun org-cycle-hide-archived-subtrees (state)
3130 "Re-hide all archived subtrees after a visibility state change."
3131 (when (and (not org-cycle-open-archived-trees)
3132 (not (memq state '(overview folded))))
3133 (save-excursion
3134 (let* ((globalp (memq state '(contents all)))
3135 (beg (if globalp (point-min) (point)))
3136 (end (if globalp (point-max) (org-end-of-subtree t))))
3137 (org-hide-archived-subtrees beg end)
3138 (goto-char beg)
3139 (if (looking-at (concat ".*:" org-archive-tag ":"))
3140 (message "%s" (substitute-command-keys
3141 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
3143 (defun org-force-cycle-archived ()
3144 "Cycle subtree even if it is archived."
3145 (interactive)
3146 (setq this-command 'org-cycle)
3147 (let ((org-cycle-open-archived-trees t))
3148 (call-interactively 'org-cycle)))
3150 (defun org-hide-archived-subtrees (beg end)
3151 "Re-hide all archived subtrees after a visibility state change."
3152 (save-excursion
3153 (let* ((re (concat ":" org-archive-tag ":")))
3154 (goto-char beg)
3155 (while (re-search-forward re end t)
3156 (and (org-on-heading-p) (hide-subtree))
3157 (org-end-of-subtree t)))))
3159 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
3161 (eval-and-compile
3162 (org-autoload "org-archive"
3163 '(org-add-archive-files org-archive-subtree
3164 org-archive-to-archive-sibling org-toggle-archive-tag)))
3166 ;; Autoload Column View Code
3168 (declare-function org-columns-number-to-string "org-colview")
3169 (declare-function org-columns-get-format-and-top-level "org-colview")
3170 (declare-function org-columns-compute "org-colview")
3172 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
3173 '(org-columns-number-to-string org-columns-get-format-and-top-level
3174 org-columns-compute org-agenda-columns org-columns-remove-overlays
3175 org-columns org-insert-columns-dblock org-dblock-write:columnview))
3177 ;; Autoload ID code
3179 (declare-function org-id-store-link "org-id")
3180 (declare-function org-id-locations-load "org-id")
3181 (declare-function org-id-locations-save "org-id")
3182 (defvar org-id-track-globally)
3183 (org-autoload "org-id"
3184 '(org-id-get-create org-id-new org-id-copy org-id-get
3185 org-id-get-with-outline-path-completion
3186 org-id-get-with-outline-drilling
3187 org-id-goto org-id-find org-id-store-link))
3189 ;; Autoload Plotting Code
3191 (org-autoload "org-plot"
3192 '(org-plot/gnuplot))
3194 ;;; Variables for pre-computed regular expressions, all buffer local
3196 (defvar org-drawer-regexp nil
3197 "Matches first line of a hidden block.")
3198 (make-variable-buffer-local 'org-drawer-regexp)
3199 (defvar org-todo-regexp nil
3200 "Matches any of the TODO state keywords.")
3201 (make-variable-buffer-local 'org-todo-regexp)
3202 (defvar org-not-done-regexp nil
3203 "Matches any of the TODO state keywords except the last one.")
3204 (make-variable-buffer-local 'org-not-done-regexp)
3205 (defvar org-not-done-heading-regexp nil
3206 "Matches a TODO headline that is not done.")
3207 (make-variable-buffer-local 'org-not-done-regexp)
3208 (defvar org-todo-line-regexp nil
3209 "Matches a headline and puts TODO state into group 2 if present.")
3210 (make-variable-buffer-local 'org-todo-line-regexp)
3211 (defvar org-complex-heading-regexp nil
3212 "Matches a headline and puts everything into groups:
3213 group 1: the stars
3214 group 2: The todo keyword, maybe
3215 group 3: Priority cookie
3216 group 4: True headline
3217 group 5: Tags")
3218 (make-variable-buffer-local 'org-complex-heading-regexp)
3219 (defvar org-todo-line-tags-regexp nil
3220 "Matches a headline and puts TODO state into group 2 if present.
3221 Also put tags into group 4 if tags are present.")
3222 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3223 (defvar org-nl-done-regexp nil
3224 "Matches newline followed by a headline with the DONE keyword.")
3225 (make-variable-buffer-local 'org-nl-done-regexp)
3226 (defvar org-looking-at-done-regexp nil
3227 "Matches the DONE keyword a point.")
3228 (make-variable-buffer-local 'org-looking-at-done-regexp)
3229 (defvar org-ds-keyword-length 12
3230 "Maximum length of the Deadline and SCHEDULED keywords.")
3231 (make-variable-buffer-local 'org-ds-keyword-length)
3232 (defvar org-deadline-regexp nil
3233 "Matches the DEADLINE keyword.")
3234 (make-variable-buffer-local 'org-deadline-regexp)
3235 (defvar org-deadline-time-regexp nil
3236 "Matches the DEADLINE keyword together with a time stamp.")
3237 (make-variable-buffer-local 'org-deadline-time-regexp)
3238 (defvar org-deadline-line-regexp nil
3239 "Matches the DEADLINE keyword and the rest of the line.")
3240 (make-variable-buffer-local 'org-deadline-line-regexp)
3241 (defvar org-scheduled-regexp nil
3242 "Matches the SCHEDULED keyword.")
3243 (make-variable-buffer-local 'org-scheduled-regexp)
3244 (defvar org-scheduled-time-regexp nil
3245 "Matches the SCHEDULED keyword together with a time stamp.")
3246 (make-variable-buffer-local 'org-scheduled-time-regexp)
3247 (defvar org-closed-time-regexp nil
3248 "Matches the CLOSED keyword together with a time stamp.")
3249 (make-variable-buffer-local 'org-closed-time-regexp)
3251 (defvar org-keyword-time-regexp nil
3252 "Matches any of the 4 keywords, together with the time stamp.")
3253 (make-variable-buffer-local 'org-keyword-time-regexp)
3254 (defvar org-keyword-time-not-clock-regexp nil
3255 "Matches any of the 3 keywords, together with the time stamp.")
3256 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3257 (defvar org-maybe-keyword-time-regexp nil
3258 "Matches a timestamp, possibly preceeded by a keyword.")
3259 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3260 (defvar org-planning-or-clock-line-re nil
3261 "Matches a line with planning or clock info.")
3262 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3264 (defconst org-plain-time-of-day-regexp
3265 (concat
3266 "\\(\\<[012]?[0-9]"
3267 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3268 "\\(--?"
3269 "\\(\\<[012]?[0-9]"
3270 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3271 "\\)?")
3272 "Regular expression to match a plain time or time range.
3273 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3274 groups carry important information:
3275 0 the full match
3276 1 the first time, range or not
3277 8 the second time, if it is a range.")
3279 (defconst org-plain-time-extension-regexp
3280 (concat
3281 "\\(\\<[012]?[0-9]"
3282 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3283 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
3284 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
3285 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3286 groups carry important information:
3287 0 the full match
3288 7 hours of duration
3289 9 minutes of duration")
3291 (defconst org-stamp-time-of-day-regexp
3292 (concat
3293 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
3294 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
3295 "\\(--?"
3296 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
3297 "Regular expression to match a timestamp time or time range.
3298 After a match, the following groups carry important information:
3299 0 the full match
3300 1 date plus weekday, for backreferencing to make sure both times on same day
3301 2 the first time, range or not
3302 4 the second time, if it is a range.")
3304 (defconst org-startup-options
3305 '(("fold" org-startup-folded t)
3306 ("overview" org-startup-folded t)
3307 ("nofold" org-startup-folded nil)
3308 ("showall" org-startup-folded nil)
3309 ("content" org-startup-folded content)
3310 ("hidestars" org-hide-leading-stars t)
3311 ("showstars" org-hide-leading-stars nil)
3312 ("odd" org-odd-levels-only t)
3313 ("oddeven" org-odd-levels-only nil)
3314 ("align" org-startup-align-all-tables t)
3315 ("noalign" org-startup-align-all-tables nil)
3316 ("customtime" org-display-custom-times t)
3317 ("logdone" org-log-done time)
3318 ("lognotedone" org-log-done note)
3319 ("nologdone" org-log-done nil)
3320 ("lognoteclock-out" org-log-note-clock-out t)
3321 ("nolognoteclock-out" org-log-note-clock-out nil)
3322 ("logrepeat" org-log-repeat state)
3323 ("lognoterepeat" org-log-repeat note)
3324 ("nologrepeat" org-log-repeat nil)
3325 ("fninline" org-footnote-define-inline t)
3326 ("nofninline" org-footnote-define-inline nil)
3327 ("fnlocal" org-footnote-section nil)
3328 ("fnauto" org-footnote-auto-label t)
3329 ("fnprompt" org-footnote-auto-label nil)
3330 ("fnconfirm" org-footnote-auto-label confirm)
3331 ("fnplain" org-footnote-auto-label plain)
3332 ("constcgs" constants-unit-system cgs)
3333 ("constSI" constants-unit-system SI)
3334 ("noptag" org-tag-persistent-alist nil))
3335 "Variable associated with STARTUP options for org-mode.
3336 Each element is a list of three items: The startup options as written
3337 in the #+STARTUP line, the corresponding variable, and the value to
3338 set this variable to if the option is found. An optional forth element PUSH
3339 means to push this value onto the list in the variable.")
3341 (defun org-set-regexps-and-options ()
3342 "Precompute regular expressions for current buffer."
3343 (when (org-mode-p)
3344 (org-set-local 'org-todo-kwd-alist nil)
3345 (org-set-local 'org-todo-key-alist nil)
3346 (org-set-local 'org-todo-key-trigger nil)
3347 (org-set-local 'org-todo-keywords-1 nil)
3348 (org-set-local 'org-done-keywords nil)
3349 (org-set-local 'org-todo-heads nil)
3350 (org-set-local 'org-todo-sets nil)
3351 (org-set-local 'org-todo-log-states nil)
3352 (org-set-local 'org-file-properties nil)
3353 (org-set-local 'org-file-tags nil)
3354 (let ((re (org-make-options-regexp
3355 '("CATEGORY" "TODO" "COLUMNS"
3356 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3357 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")
3358 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
3359 (splitre "[ \t]+")
3360 kwds kws0 kwsa key log value cat arch tags const links hw dws
3361 tail sep kws1 prio props ftags drawers
3362 ext-setup-or-nil setup-contents (start 0))
3363 (save-excursion
3364 (save-restriction
3365 (widen)
3366 (goto-char (point-min))
3367 (while (or (and ext-setup-or-nil
3368 (string-match re ext-setup-or-nil start)
3369 (setq start (match-end 0)))
3370 (and (setq ext-setup-or-nil nil start 0)
3371 (re-search-forward re nil t)))
3372 (setq key (upcase (match-string 1 ext-setup-or-nil))
3373 value (org-match-string-no-properties 2 ext-setup-or-nil))
3374 (cond
3375 ((equal key "CATEGORY")
3376 (if (string-match "[ \t]+$" value)
3377 (setq value (replace-match "" t t value)))
3378 (setq cat value))
3379 ((member key '("SEQ_TODO" "TODO"))
3380 (push (cons 'sequence (org-split-string value splitre)) kwds))
3381 ((equal key "TYP_TODO")
3382 (push (cons 'type (org-split-string value splitre)) kwds))
3383 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
3384 ;; general TODO-like setup
3385 (push (cons (intern (downcase (match-string 1 key)))
3386 (org-split-string value splitre)) kwds))
3387 ((equal key "TAGS")
3388 (setq tags (append tags (if tags '("\\n") nil)
3389 (org-split-string value splitre))))
3390 ((equal key "COLUMNS")
3391 (org-set-local 'org-columns-default-format value))
3392 ((equal key "LINK")
3393 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3394 (push (cons (match-string 1 value)
3395 (org-trim (match-string 2 value)))
3396 links)))
3397 ((equal key "PRIORITIES")
3398 (setq prio (org-split-string value " +")))
3399 ((equal key "PROPERTY")
3400 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3401 (push (cons (match-string 1 value) (match-string 2 value))
3402 props)))
3403 ((equal key "FILETAGS")
3404 (when (string-match "\\S-" value)
3405 (setq ftags
3406 (append
3407 ftags
3408 (apply 'append
3409 (mapcar (lambda (x) (org-split-string x ":"))
3410 (org-split-string value)))))))
3411 ((equal key "DRAWERS")
3412 (setq drawers (org-split-string value splitre)))
3413 ((equal key "CONSTANTS")
3414 (setq const (append const (org-split-string value splitre))))
3415 ((equal key "STARTUP")
3416 (let ((opts (org-split-string value splitre))
3417 l var val)
3418 (while (setq l (pop opts))
3419 (when (setq l (assoc l org-startup-options))
3420 (setq var (nth 1 l) val (nth 2 l))
3421 (if (not (nth 3 l))
3422 (set (make-local-variable var) val)
3423 (if (not (listp (symbol-value var)))
3424 (set (make-local-variable var) nil))
3425 (set (make-local-variable var) (symbol-value var))
3426 (add-to-list var val))))))
3427 ((equal key "ARCHIVE")
3428 (string-match " *$" value)
3429 (setq arch (replace-match "" t t value))
3430 (remove-text-properties 0 (length arch)
3431 '(face t fontified t) arch))
3432 ((equal key "SETUPFILE")
3433 (setq setup-contents (org-file-contents
3434 (expand-file-name
3435 (org-remove-double-quotes value))
3436 'noerror))
3437 (if (not ext-setup-or-nil)
3438 (setq ext-setup-or-nil setup-contents start 0)
3439 (setq ext-setup-or-nil
3440 (concat (substring ext-setup-or-nil 0 start)
3441 "\n" setup-contents "\n"
3442 (substring ext-setup-or-nil start)))))
3443 ))))
3444 (when cat
3445 (org-set-local 'org-category (intern cat))
3446 (push (cons "CATEGORY" cat) props))
3447 (when prio
3448 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3449 (setq prio (mapcar 'string-to-char prio))
3450 (org-set-local 'org-highest-priority (nth 0 prio))
3451 (org-set-local 'org-lowest-priority (nth 1 prio))
3452 (org-set-local 'org-default-priority (nth 2 prio)))
3453 (and props (org-set-local 'org-file-properties (nreverse props)))
3454 (and ftags (org-set-local 'org-file-tags
3455 (mapcar 'org-add-prop-inherited ftags)))
3456 (and drawers (org-set-local 'org-drawers drawers))
3457 (and arch (org-set-local 'org-archive-location arch))
3458 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3459 ;; Process the TODO keywords
3460 (unless kwds
3461 ;; Use the global values as if they had been given locally.
3462 (setq kwds (default-value 'org-todo-keywords))
3463 (if (stringp (car kwds))
3464 (setq kwds (list (cons org-todo-interpretation
3465 (default-value 'org-todo-keywords)))))
3466 (setq kwds (reverse kwds)))
3467 (setq kwds (nreverse kwds))
3468 (let (inter kws kw)
3469 (while (setq kws (pop kwds))
3470 (let ((kws (or
3471 (run-hook-with-args-until-success
3472 'org-todo-setup-filter-hook kws)
3473 kws)))
3474 (setq inter (pop kws) sep (member "|" kws)
3475 kws0 (delete "|" (copy-sequence kws))
3476 kwsa nil
3477 kws1 (mapcar
3478 (lambda (x)
3479 ;; 1 2
3480 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3481 (progn
3482 (setq kw (match-string 1 x)
3483 key (and (match-end 2) (match-string 2 x))
3484 log (org-extract-log-state-settings x))
3485 (push (cons kw (and key (string-to-char key))) kwsa)
3486 (and log (push log org-todo-log-states))
3488 (error "Invalid TODO keyword %s" x)))
3489 kws0)
3490 kwsa (if kwsa (append '((:startgroup))
3491 (nreverse kwsa)
3492 '((:endgroup))))
3493 hw (car kws1)
3494 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3495 tail (list inter hw (car dws) (org-last dws))))
3496 (add-to-list 'org-todo-heads hw 'append)
3497 (push kws1 org-todo-sets)
3498 (setq org-done-keywords (append org-done-keywords dws nil))
3499 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3500 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3501 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3502 (setq org-todo-sets (nreverse org-todo-sets)
3503 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3504 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3505 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3506 ;; Process the constants
3507 (when const
3508 (let (e cst)
3509 (while (setq e (pop const))
3510 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3511 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3512 (setq org-table-formula-constants-local cst)))
3514 ;; Process the tags.
3515 (when tags
3516 (let (e tgs)
3517 (while (setq e (pop tags))
3518 (cond
3519 ((equal e "{") (push '(:startgroup) tgs))
3520 ((equal e "}") (push '(:endgroup) tgs))
3521 ((equal e "\\n") (push '(:newline) tgs))
3522 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3523 (push (cons (match-string 1 e)
3524 (string-to-char (match-string 2 e)))
3525 tgs))
3526 (t (push (list e) tgs))))
3527 (org-set-local 'org-tag-alist nil)
3528 (while (setq e (pop tgs))
3529 (or (and (stringp (car e))
3530 (assoc (car e) org-tag-alist))
3531 (push e org-tag-alist)))))
3533 ;; Compute the regular expressions and other local variables
3534 (if (not org-done-keywords)
3535 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
3536 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3537 (length org-scheduled-string)
3538 (length org-clock-string)
3539 (length org-closed-string)))
3540 org-drawer-regexp
3541 (concat "^[ \t]*:\\("
3542 (mapconcat 'regexp-quote org-drawers "\\|")
3543 "\\):[ \t]*$")
3544 org-not-done-keywords
3545 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3546 org-todo-regexp
3547 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3548 "\\|") "\\)\\>")
3549 org-not-done-regexp
3550 (concat "\\<\\("
3551 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3552 "\\)\\>")
3553 org-not-done-heading-regexp
3554 (concat "^\\(\\*+\\)[ \t]+\\("
3555 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3556 "\\)\\>")
3557 org-todo-line-regexp
3558 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3559 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3560 "\\)\\>\\)?[ \t]*\\(.*\\)")
3561 org-complex-heading-regexp
3562 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3563 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3564 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3565 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3566 org-nl-done-regexp
3567 (concat "\n\\*+[ \t]+"
3568 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3569 "\\)" "\\>")
3570 org-todo-line-tags-regexp
3571 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3572 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3573 (org-re
3574 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3575 org-looking-at-done-regexp
3576 (concat "^" "\\(?:"
3577 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3578 "\\>")
3579 org-deadline-regexp (concat "\\<" org-deadline-string)
3580 org-deadline-time-regexp
3581 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3582 org-deadline-line-regexp
3583 (concat "\\<\\(" org-deadline-string "\\).*")
3584 org-scheduled-regexp
3585 (concat "\\<" org-scheduled-string)
3586 org-scheduled-time-regexp
3587 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3588 org-closed-time-regexp
3589 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3590 org-keyword-time-regexp
3591 (concat "\\<\\(" org-scheduled-string
3592 "\\|" org-deadline-string
3593 "\\|" org-closed-string
3594 "\\|" org-clock-string "\\)"
3595 " *[[<]\\([^]>]+\\)[]>]")
3596 org-keyword-time-not-clock-regexp
3597 (concat "\\<\\(" org-scheduled-string
3598 "\\|" org-deadline-string
3599 "\\|" org-closed-string
3600 "\\)"
3601 " *[[<]\\([^]>]+\\)[]>]")
3602 org-maybe-keyword-time-regexp
3603 (concat "\\(\\<\\(" org-scheduled-string
3604 "\\|" org-deadline-string
3605 "\\|" org-closed-string
3606 "\\|" org-clock-string "\\)\\)?"
3607 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3608 org-planning-or-clock-line-re
3609 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3610 "\\|" org-deadline-string
3611 "\\|" org-closed-string "\\|" org-clock-string
3612 "\\)\\>\\)")
3614 (org-compute-latex-and-specials-regexp)
3615 (org-set-font-lock-defaults))))
3617 (defun org-file-contents (file &optional noerror)
3618 "Return the contents of FILE, as a string."
3619 (if (or (not file)
3620 (not (file-readable-p file)))
3621 (if noerror
3622 (progn
3623 (message "Cannot read file %s" file)
3624 (ding) (sit-for 2)
3626 (error "Cannot read file %s" file))
3627 (with-temp-buffer
3628 (insert-file-contents file)
3629 (buffer-string))))
3631 (defun org-extract-log-state-settings (x)
3632 "Extract the log state setting from a TODO keyword string.
3633 This will extract info from a string like \"WAIT(w@/!)\"."
3634 (let (kw key log1 log2)
3635 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3636 (setq kw (match-string 1 x)
3637 key (and (match-end 2) (match-string 2 x))
3638 log1 (and (match-end 3) (match-string 3 x))
3639 log2 (and (match-end 4) (match-string 4 x)))
3640 (and (or log1 log2)
3641 (list kw
3642 (and log1 (if (equal log1 "!") 'time 'note))
3643 (and log2 (if (equal log2 "!") 'time 'note)))))))
3645 (defun org-remove-keyword-keys (list)
3646 "Remove a pair of parenthesis at the end of each string in LIST."
3647 (mapcar (lambda (x)
3648 (if (string-match "(.*)$" x)
3649 (substring x 0 (match-beginning 0))
3651 list))
3653 ;; FIXME: this could be done much better, using second characters etc.
3654 (defun org-assign-fast-keys (alist)
3655 "Assign fast keys to a keyword-key alist.
3656 Respect keys that are already there."
3657 (let (new e k c c1 c2 (char ?a))
3658 (while (setq e (pop alist))
3659 (cond
3660 ((equal e '(:startgroup)) (push e new))
3661 ((equal e '(:endgroup)) (push e new))
3662 ((equal e '(:newline)) (push e new))
3664 (setq k (car e) c2 nil)
3665 (if (cdr e)
3666 (setq c (cdr e))
3667 ;; automatically assign a character.
3668 (setq c1 (string-to-char
3669 (downcase (substring
3670 k (if (= (string-to-char k) ?@) 1 0)))))
3671 (if (or (rassoc c1 new) (rassoc c1 alist))
3672 (while (or (rassoc char new) (rassoc char alist))
3673 (setq char (1+ char)))
3674 (setq c2 c1))
3675 (setq c (or c2 char)))
3676 (push (cons k c) new))))
3677 (nreverse new)))
3679 ;;; Some variables used in various places
3681 (defvar org-window-configuration nil
3682 "Used in various places to store a window configuration.")
3683 (defvar org-finish-function nil
3684 "Function to be called when `C-c C-c' is used.
3685 This is for getting out of special buffers like remember.")
3688 ;; FIXME: Occasionally check by commenting these, to make sure
3689 ;; no other functions uses these, forgetting to let-bind them.
3690 (defvar entry)
3691 (defvar state)
3692 (defvar last-state)
3693 (defvar date)
3694 (defvar description)
3696 ;; Defined somewhere in this file, but used before definition.
3697 (defvar org-html-entities)
3698 (defvar org-struct-menu)
3699 (defvar org-org-menu)
3700 (defvar org-tbl-menu)
3701 (defvar org-agenda-keymap)
3703 ;;;; Define the Org-mode
3705 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3706 (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."))
3709 ;; We use a before-change function to check if a table might need
3710 ;; an update.
3711 (defvar org-table-may-need-update t
3712 "Indicates that a table might need an update.
3713 This variable is set by `org-before-change-function'.
3714 `org-table-align' sets it back to nil.")
3715 (defun org-before-change-function (beg end)
3716 "Every change indicates that a table might need an update."
3717 (setq org-table-may-need-update t))
3718 (defvar org-mode-map)
3719 (defvar org-mode-hook nil
3720 "Mode hook for Org-mode, run after the mode was turned on.")
3721 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3722 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3723 (defvar org-table-buffer-is-an nil)
3724 (defconst org-outline-regexp "\\*+ ")
3726 ;;;###autoload
3727 (define-derived-mode org-mode outline-mode "Org"
3728 "Outline-based notes management and organizer, alias
3729 \"Carsten's outline-mode for keeping track of everything.\"
3731 Org-mode develops organizational tasks around a NOTES file which
3732 contains information about projects as plain text. Org-mode is
3733 implemented on top of outline-mode, which is ideal to keep the content
3734 of large files well structured. It supports ToDo items, deadlines and
3735 time stamps, which magically appear in the diary listing of the Emacs
3736 calendar. Tables are easily created with a built-in table editor.
3737 Plain text URL-like links connect to websites, emails (VM), Usenet
3738 messages (Gnus), BBDB entries, and any files related to the project.
3739 For printing and sharing of notes, an Org-mode file (or a part of it)
3740 can be exported as a structured ASCII or HTML file.
3742 The following commands are available:
3744 \\{org-mode-map}"
3746 ;; Get rid of Outline menus, they are not needed
3747 ;; Need to do this here because define-derived-mode sets up
3748 ;; the keymap so late. Still, it is a waste to call this each time
3749 ;; we switch another buffer into org-mode.
3750 (if (featurep 'xemacs)
3751 (when (boundp 'outline-mode-menu-heading)
3752 ;; Assume this is Greg's port, it used easymenu
3753 (easy-menu-remove outline-mode-menu-heading)
3754 (easy-menu-remove outline-mode-menu-show)
3755 (easy-menu-remove outline-mode-menu-hide))
3756 (define-key org-mode-map [menu-bar headings] 'undefined)
3757 (define-key org-mode-map [menu-bar hide] 'undefined)
3758 (define-key org-mode-map [menu-bar show] 'undefined))
3760 (org-load-modules-maybe)
3761 (easy-menu-add org-org-menu)
3762 (easy-menu-add org-tbl-menu)
3763 (org-install-agenda-files-menu)
3764 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3765 (org-add-to-invisibility-spec '(org-cwidth))
3766 (when (featurep 'xemacs)
3767 (org-set-local 'line-move-ignore-invisible t))
3768 (org-set-local 'outline-regexp org-outline-regexp)
3769 (org-set-local 'outline-level 'org-outline-level)
3770 (when (and org-ellipsis
3771 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3772 (fboundp 'make-glyph-code))
3773 (unless org-display-table
3774 (setq org-display-table (make-display-table)))
3775 (set-display-table-slot
3776 org-display-table 4
3777 (vconcat (mapcar
3778 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3779 org-ellipsis)))
3780 (if (stringp org-ellipsis) org-ellipsis "..."))))
3781 (setq buffer-display-table org-display-table))
3782 (org-set-regexps-and-options)
3783 (when (and org-tag-faces (not org-tags-special-faces-re))
3784 ;; tag faces set outside customize.... force initialization.
3785 (org-set-tag-faces 'org-tag-faces org-tag-faces))
3786 ;; Calc embedded
3787 (org-set-local 'calc-embedded-open-mode "# ")
3788 (modify-syntax-entry ?# "<")
3789 (modify-syntax-entry ?@ "w")
3790 (if org-startup-truncated (setq truncate-lines t))
3791 (org-set-local 'font-lock-unfontify-region-function
3792 'org-unfontify-region)
3793 ;; Activate before-change-function
3794 (org-set-local 'org-table-may-need-update t)
3795 (org-add-hook 'before-change-functions 'org-before-change-function nil
3796 'local)
3797 ;; Check for running clock before killing a buffer
3798 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3799 ;; Paragraphs and auto-filling
3800 (org-set-autofill-regexps)
3801 (setq indent-line-function 'org-indent-line-function)
3802 (org-update-radio-target-regexp)
3803 ;; Make sure dependence stuff works reliably, even for users who set it
3804 ;; too late :-(
3805 (if org-enforce-todo-dependencies
3806 (add-hook 'org-blocker-hook
3807 'org-block-todo-from-children-or-siblings-or-parent)
3808 (remove-hook 'org-blocker-hook
3809 'org-block-todo-from-children-or-siblings-or-parent))
3810 (if org-enforce-todo-checkbox-dependencies
3811 (add-hook 'org-blocker-hook
3812 'org-block-todo-from-checkboxes)
3813 (remove-hook 'org-blocker-hook
3814 'org-block-todo-from-checkboxes))
3816 ;; Comment characters
3817 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3818 (org-set-local 'comment-padding " ")
3820 ;; Align options lines
3821 (org-set-local
3822 'align-mode-rules-list
3823 '((org-in-buffer-settings
3824 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3825 (modes . '(org-mode)))))
3827 ;; Imenu
3828 (org-set-local 'imenu-create-index-function
3829 'org-imenu-get-tree)
3831 ;; Make isearch reveal context
3832 (if (or (featurep 'xemacs)
3833 (not (boundp 'outline-isearch-open-invisible-function)))
3834 ;; Emacs 21 and XEmacs make use of the hook
3835 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3836 ;; Emacs 22 deals with this through a special variable
3837 (org-set-local 'outline-isearch-open-invisible-function
3838 (lambda (&rest ignore) (org-show-context 'isearch))))
3840 ;; If empty file that did not turn on org-mode automatically, make it to.
3841 (if (and org-insert-mode-line-in-empty-file
3842 (interactive-p)
3843 (= (point-min) (point-max)))
3844 (insert "# -*- mode: org -*-\n\n"))
3846 (unless org-inhibit-startup
3847 (when org-startup-align-all-tables
3848 (let ((bmp (buffer-modified-p)))
3849 (org-table-map-tables 'org-table-align)
3850 (set-buffer-modified-p bmp)))
3851 (org-set-startup-visibility)))
3853 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3855 (defun org-current-time ()
3856 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3857 (if (> (car org-time-stamp-rounding-minutes) 1)
3858 (let ((r (car org-time-stamp-rounding-minutes))
3859 (time (decode-time)))
3860 (apply 'encode-time
3861 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3862 (nthcdr 2 time))))
3863 (current-time)))
3865 ;;;; Font-Lock stuff, including the activators
3867 (defvar org-mouse-map (make-sparse-keymap))
3868 (org-defkey org-mouse-map
3869 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3870 (org-defkey org-mouse-map
3871 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3872 (when org-mouse-1-follows-link
3873 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3874 (when org-tab-follows-link
3875 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3876 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3878 (require 'font-lock)
3880 (defconst org-non-link-chars "]\t\n\r<>")
3881 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3882 "shell" "elisp"))
3883 (defvar org-link-types-re nil
3884 "Matches a link that has a url-like prefix like \"http:\"")
3885 (defvar org-link-re-with-space nil
3886 "Matches a link with spaces, optional angular brackets around it.")
3887 (defvar org-link-re-with-space2 nil
3888 "Matches a link with spaces, optional angular brackets around it.")
3889 (defvar org-link-re-with-space3 nil
3890 "Matches a link with spaces, only for internal part in bracket links.")
3891 (defvar org-angle-link-re nil
3892 "Matches link with angular brackets, spaces are allowed.")
3893 (defvar org-plain-link-re nil
3894 "Matches plain link, without spaces.")
3895 (defvar org-bracket-link-regexp nil
3896 "Matches a link in double brackets.")
3897 (defvar org-bracket-link-analytic-regexp nil
3898 "Regular expression used to analyze links.
3899 Here is what the match groups contain after a match:
3900 1: http:
3901 2: http
3902 3: path
3903 4: [desc]
3904 5: desc")
3905 (defvar org-bracket-link-analytic-regexp++ nil
3906 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
3907 (defvar org-any-link-re nil
3908 "Regular expression matching any link.")
3910 (defun org-make-link-regexps ()
3911 "Update the link regular expressions.
3912 This should be called after the variable `org-link-types' has changed."
3913 (setq org-link-types-re
3914 (concat
3915 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3916 org-link-re-with-space
3917 (concat
3918 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3919 "\\([^" org-non-link-chars " ]"
3920 "[^" org-non-link-chars "]*"
3921 "[^" org-non-link-chars " ]\\)>?")
3922 org-link-re-with-space2
3923 (concat
3924 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3925 "\\([^" org-non-link-chars " ]"
3926 "[^\t\n\r]*"
3927 "[^" org-non-link-chars " ]\\)>?")
3928 org-link-re-with-space3
3929 (concat
3930 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3931 "\\([^" org-non-link-chars " ]"
3932 "[^\t\n\r]*\\)")
3933 org-angle-link-re
3934 (concat
3935 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3936 "\\([^" org-non-link-chars " ]"
3937 "[^" org-non-link-chars "]*"
3938 "\\)>")
3939 org-plain-link-re
3940 (concat
3941 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3942 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3943 org-bracket-link-regexp
3944 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3945 org-bracket-link-analytic-regexp
3946 (concat
3947 "\\[\\["
3948 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3949 "\\([^]]+\\)"
3950 "\\]"
3951 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3952 "\\]")
3953 org-bracket-link-analytic-regexp++
3954 (concat
3955 "\\[\\["
3956 "\\(\\(" (mapconcat 'identity (cons "coderef" org-link-types) "\\|") "\\):\\)?"
3957 "\\([^]]+\\)"
3958 "\\]"
3959 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3960 "\\]")
3961 org-any-link-re
3962 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3963 org-angle-link-re "\\)\\|\\("
3964 org-plain-link-re "\\)")))
3966 (org-make-link-regexps)
3968 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
3969 "Regular expression for fast time stamp matching.")
3970 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
3971 "Regular expression for fast time stamp matching.")
3972 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3973 "Regular expression matching time strings for analysis.
3974 This one does not require the space after the date, so it can be used
3975 on a string that terminates immediately after the date.")
3976 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3977 "Regular expression matching time strings for analysis.")
3978 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
3979 "Regular expression matching time stamps, with groups.")
3980 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
3981 "Regular expression matching time stamps (also [..]), with groups.")
3982 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3983 "Regular expression matching a time stamp range.")
3984 (defconst org-tr-regexp-both
3985 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3986 "Regular expression matching a time stamp range.")
3987 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3988 org-ts-regexp "\\)?")
3989 "Regular expression matching a time stamp or time stamp range.")
3990 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3991 org-ts-regexp-both "\\)?")
3992 "Regular expression matching a time stamp or time stamp range.
3993 The time stamps may be either active or inactive.")
3995 (defvar org-emph-face nil)
3997 (defun org-do-emphasis-faces (limit)
3998 "Run through the buffer and add overlays to links."
3999 (let (rtn)
4000 (while (and (not rtn) (re-search-forward org-emph-re limit t))
4001 (if (not (= (char-after (match-beginning 3))
4002 (char-after (match-beginning 4))))
4003 (progn
4004 (setq rtn t)
4005 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
4006 'face
4007 (nth 1 (assoc (match-string 3)
4008 org-emphasis-alist)))
4009 (add-text-properties (match-beginning 2) (match-end 2)
4010 '(font-lock-multiline t))
4011 (when org-hide-emphasis-markers
4012 (add-text-properties (match-end 4) (match-beginning 5)
4013 '(invisible org-link))
4014 (add-text-properties (match-beginning 3) (match-end 3)
4015 '(invisible org-link)))))
4016 (backward-char 1))
4017 rtn))
4019 (defun org-emphasize (&optional char)
4020 "Insert or change an emphasis, i.e. a font like bold or italic.
4021 If there is an active region, change that region to a new emphasis.
4022 If there is no region, just insert the marker characters and position
4023 the cursor between them.
4024 CHAR should be either the marker character, or the first character of the
4025 HTML tag associated with that emphasis. If CHAR is a space, the means
4026 to remove the emphasis of the selected region.
4027 If char is not given (for example in an interactive call) it
4028 will be prompted for."
4029 (interactive)
4030 (let ((eal org-emphasis-alist) e det
4031 (erc org-emphasis-regexp-components)
4032 (prompt "")
4033 (string "") beg end move tag c s)
4034 (if (org-region-active-p)
4035 (setq beg (region-beginning) end (region-end)
4036 string (buffer-substring beg end))
4037 (setq move t))
4039 (while (setq e (pop eal))
4040 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
4041 c (aref tag 0))
4042 (push (cons c (string-to-char (car e))) det)
4043 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
4044 (substring tag 1)))))
4045 (setq det (nreverse det))
4046 (unless char
4047 (message "%s" (concat "Emphasis marker or tag:" prompt))
4048 (setq char (read-char-exclusive)))
4049 (setq char (or (cdr (assoc char det)) char))
4050 (if (equal char ?\ )
4051 (setq s "" move nil)
4052 (unless (assoc (char-to-string char) org-emphasis-alist)
4053 (error "No such emphasis marker: \"%c\"" char))
4054 (setq s (char-to-string char)))
4055 (while (and (> (length string) 1)
4056 (equal (substring string 0 1) (substring string -1))
4057 (assoc (substring string 0 1) org-emphasis-alist))
4058 (setq string (substring string 1 -1)))
4059 (setq string (concat s string s))
4060 (if beg (delete-region beg end))
4061 (unless (or (bolp)
4062 (string-match (concat "[" (nth 0 erc) "\n]")
4063 (char-to-string (char-before (point)))))
4064 (insert " "))
4065 (unless (string-match (concat "[" (nth 1 erc) "\n]")
4066 (char-to-string (char-after (point))))
4067 (insert " ") (backward-char 1))
4068 (insert string)
4069 (and move (backward-char 1))))
4071 (defconst org-nonsticky-props
4072 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
4075 (defun org-activate-plain-links (limit)
4076 "Run through the buffer and add overlays to links."
4077 (catch 'exit
4078 (let (f)
4079 (while (re-search-forward org-plain-link-re limit t)
4080 (setq f (get-text-property (match-beginning 0) 'face))
4081 (if (or (eq f 'org-tag)
4082 (and (listp f) (memq 'org-tag f)))
4084 (add-text-properties (match-beginning 0) (match-end 0)
4085 (list 'mouse-face 'highlight
4086 'rear-nonsticky org-nonsticky-props
4087 'keymap org-mouse-map
4089 (throw 'exit t))))))
4091 (defun org-activate-code (limit)
4092 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
4093 (progn
4094 (remove-text-properties (match-beginning 0) (match-end 0)
4095 '(display t invisible t intangible t))
4096 t)))
4098 (defun org-activate-angle-links (limit)
4099 "Run through the buffer and add overlays to links."
4100 (if (re-search-forward org-angle-link-re limit t)
4101 (progn
4102 (add-text-properties (match-beginning 0) (match-end 0)
4103 (list 'mouse-face 'highlight
4104 'rear-nonsticky org-nonsticky-props
4105 'keymap org-mouse-map
4107 t)))
4109 (defun org-activate-footnote-links (limit)
4110 "Run through the buffer and add overlays to links."
4111 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
4112 limit t)
4113 (progn
4114 (add-text-properties (match-beginning 2) (match-end 2)
4115 (list 'mouse-face 'highlight
4116 'rear-nonsticky org-nonsticky-props
4117 'keymap org-mouse-map
4118 'help-echo
4119 (if (= (point-at-bol) (match-beginning 2))
4120 "Footnote definition"
4121 "Footnote reference")
4123 t)))
4125 (defun org-activate-bracket-links (limit)
4126 "Run through the buffer and add overlays to bracketed links."
4127 (if (re-search-forward org-bracket-link-regexp limit t)
4128 (let* ((help (concat "LINK: "
4129 (org-match-string-no-properties 1)))
4130 ;; FIXME: above we should remove the escapes.
4131 ;; but that requires another match, protecting match data,
4132 ;; a lot of overhead for font-lock.
4133 (ip (org-maybe-intangible
4134 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
4135 'keymap org-mouse-map 'mouse-face 'highlight
4136 'font-lock-multiline t 'help-echo help)))
4137 (vp (list 'rear-nonsticky org-nonsticky-props
4138 'keymap org-mouse-map 'mouse-face 'highlight
4139 'font-lock-multiline t 'help-echo help)))
4140 ;; We need to remove the invisible property here. Table narrowing
4141 ;; may have made some of this invisible.
4142 (remove-text-properties (match-beginning 0) (match-end 0)
4143 '(invisible nil))
4144 (if (match-end 3)
4145 (progn
4146 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
4147 (add-text-properties (match-beginning 3) (match-end 3) vp)
4148 (add-text-properties (match-end 3) (match-end 0) ip))
4149 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
4150 (add-text-properties (match-beginning 1) (match-end 1) vp)
4151 (add-text-properties (match-end 1) (match-end 0) ip))
4152 t)))
4154 (defun org-activate-dates (limit)
4155 "Run through the buffer and add overlays to dates."
4156 (if (re-search-forward org-tsr-regexp-both limit t)
4157 (progn
4158 (add-text-properties (match-beginning 0) (match-end 0)
4159 (list 'mouse-face 'highlight
4160 'rear-nonsticky org-nonsticky-props
4161 'keymap org-mouse-map))
4162 (when org-display-custom-times
4163 (if (match-end 3)
4164 (org-display-custom-time (match-beginning 3) (match-end 3)))
4165 (org-display-custom-time (match-beginning 1) (match-end 1)))
4166 t)))
4168 (defvar org-target-link-regexp nil
4169 "Regular expression matching radio targets in plain text.")
4170 (make-variable-buffer-local 'org-target-link-regexp)
4171 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
4172 "Regular expression matching a link target.")
4173 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
4174 "Regular expression matching a radio target.")
4175 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
4176 "Regular expression matching any target.")
4178 (defun org-activate-target-links (limit)
4179 "Run through the buffer and add overlays to target matches."
4180 (when org-target-link-regexp
4181 (let ((case-fold-search t))
4182 (if (re-search-forward org-target-link-regexp limit t)
4183 (progn
4184 (add-text-properties (match-beginning 0) (match-end 0)
4185 (list 'mouse-face 'highlight
4186 'rear-nonsticky org-nonsticky-props
4187 'keymap org-mouse-map
4188 'help-echo "Radio target link"
4189 'org-linked-text t))
4190 t)))))
4192 (defun org-update-radio-target-regexp ()
4193 "Find all radio targets in this file and update the regular expression."
4194 (interactive)
4195 (when (memq 'radio org-activate-links)
4196 (setq org-target-link-regexp
4197 (org-make-target-link-regexp (org-all-targets 'radio)))
4198 (org-restart-font-lock)))
4200 (defun org-hide-wide-columns (limit)
4201 (let (s e)
4202 (setq s (text-property-any (point) (or limit (point-max))
4203 'org-cwidth t))
4204 (when s
4205 (setq e (next-single-property-change s 'org-cwidth))
4206 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
4207 (goto-char e)
4208 t)))
4210 (defvar org-latex-and-specials-regexp nil
4211 "Regular expression for highlighting export special stuff.")
4212 (defvar org-match-substring-regexp)
4213 (defvar org-match-substring-with-braces-regexp)
4214 (defvar org-export-html-special-string-regexps)
4216 (defun org-compute-latex-and-specials-regexp ()
4217 "Compute regular expression for stuff treated specially by exporters."
4218 (if (not org-highlight-latex-fragments-and-specials)
4219 (org-set-local 'org-latex-and-specials-regexp nil)
4220 (require 'org-exp)
4221 (let*
4222 ((matchers (plist-get org-format-latex-options :matchers))
4223 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
4224 org-latex-regexps)))
4225 (options (org-combine-plists (org-default-export-plist)
4226 (org-infile-export-plist)))
4227 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
4228 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
4229 (org-export-with-TeX-macros (plist-get options :TeX-macros))
4230 (org-export-html-expand (plist-get options :expand-quoted-html))
4231 (org-export-with-special-strings (plist-get options :special-strings))
4232 (re-sub
4233 (cond
4234 ((equal org-export-with-sub-superscripts '{})
4235 (list org-match-substring-with-braces-regexp))
4236 (org-export-with-sub-superscripts
4237 (list org-match-substring-regexp))
4238 (t nil)))
4239 (re-latex
4240 (if org-export-with-LaTeX-fragments
4241 (mapcar (lambda (x) (nth 1 x)) latexs)))
4242 (re-macros
4243 (if org-export-with-TeX-macros
4244 (list (concat "\\\\"
4245 (regexp-opt
4246 (append (mapcar 'car org-html-entities)
4247 (if (boundp 'org-latex-entities)
4248 org-latex-entities nil))
4249 'words))) ; FIXME
4251 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
4252 (re-special (if org-export-with-special-strings
4253 (mapcar (lambda (x) (car x))
4254 org-export-html-special-string-regexps)))
4255 (re-rest
4256 (delq nil
4257 (list
4258 (if org-export-html-expand "@<[^>\n]+>")
4259 ))))
4260 (org-set-local
4261 'org-latex-and-specials-regexp
4262 (mapconcat 'identity (append re-latex re-sub re-macros re-special
4263 re-rest) "\\|")))))
4265 (defun org-do-latex-and-special-faces (limit)
4266 "Run through the buffer and add overlays to links."
4267 (when org-latex-and-specials-regexp
4268 (let (rtn d)
4269 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
4270 limit t))
4271 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
4272 'face))
4273 '(org-code org-verbatim underline)))
4274 (progn
4275 (setq rtn t
4276 d (cond ((member (char-after (1+ (match-beginning 0)))
4277 '(?_ ?^)) 1)
4278 (t 0)))
4279 (font-lock-prepend-text-property
4280 (+ d (match-beginning 0)) (match-end 0)
4281 'face 'org-latex-and-export-specials)
4282 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
4283 '(font-lock-multiline t)))))
4284 rtn)))
4286 (defun org-restart-font-lock ()
4287 "Restart font-lock-mode, to force refontification."
4288 (when (and (boundp 'font-lock-mode) font-lock-mode)
4289 (font-lock-mode -1)
4290 (font-lock-mode 1)))
4292 (defun org-all-targets (&optional radio)
4293 "Return a list of all targets in this file.
4294 With optional argument RADIO, only find radio targets."
4295 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4296 rtn)
4297 (save-excursion
4298 (goto-char (point-min))
4299 (while (re-search-forward re nil t)
4300 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4301 rtn)))
4303 (defun org-make-target-link-regexp (targets)
4304 "Make regular expression matching all strings in TARGETS.
4305 The regular expression finds the targets also if there is a line break
4306 between words."
4307 (and targets
4308 (concat
4309 "\\<\\("
4310 (mapconcat
4311 (lambda (x)
4312 (while (string-match " +" x)
4313 (setq x (replace-match "\\s-+" t t x)))
4315 targets
4316 "\\|")
4317 "\\)\\>")))
4319 (defun org-activate-tags (limit)
4320 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
4321 (progn
4322 (add-text-properties (match-beginning 1) (match-end 1)
4323 (list 'mouse-face 'highlight
4324 'rear-nonsticky org-nonsticky-props
4325 'keymap org-mouse-map))
4326 t)))
4328 (defun org-outline-level ()
4329 (save-excursion
4330 (looking-at outline-regexp)
4331 (if (match-beginning 1)
4332 (+ (org-get-string-indentation (match-string 1)) 1000)
4333 (1- (- (match-end 0) (match-beginning 0))))))
4335 (defvar org-font-lock-keywords nil)
4337 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
4338 "Regular expression matching a property line.")
4340 (defvar org-font-lock-hook nil
4341 "Functions to be called for special font lock stuff.")
4343 (defun org-font-lock-hook (limit)
4344 (run-hook-with-args 'org-font-lock-hook limit))
4346 (defun org-set-font-lock-defaults ()
4347 (let* ((em org-fontify-emphasized-text)
4348 (lk org-activate-links)
4349 (org-font-lock-extra-keywords
4350 (list
4351 ;; Call the hook
4352 '(org-font-lock-hook)
4353 ;; Headlines
4354 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
4355 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
4356 ;; Table lines
4357 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4358 (1 'org-table t))
4359 ;; Table internals
4360 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4361 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4362 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4363 ;; Drawers
4364 (list org-drawer-regexp '(0 'org-special-keyword t))
4365 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4366 ;; Properties
4367 (list org-property-re
4368 '(1 'org-special-keyword t)
4369 '(3 'org-property-value t))
4370 (if org-format-transports-properties-p
4371 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
4372 ;; Links
4373 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4374 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4375 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
4376 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4377 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4378 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4379 (if (memq 'footnote lk) '(org-activate-footnote-links
4380 (2 'org-footnote t)))
4381 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4382 '(org-hide-wide-columns (0 nil append))
4383 ;; TODO lines
4384 (list (concat "^\\*+[ \t]+" org-todo-regexp "\\([ \t]\\|$\\)")
4385 '(1 (org-get-todo-face 1) t))
4386 ;; DONE
4387 (if org-fontify-done-headline
4388 (list (concat "^[*]+ +\\<\\("
4389 (mapconcat 'regexp-quote org-done-keywords "\\|")
4390 "\\)\\(.*\\)")
4391 '(2 'org-headline-done t))
4392 nil)
4393 ;; Priorities
4394 '(org-font-lock-add-priority-faces)
4395 ;; Tags
4396 '(org-font-lock-add-tag-faces)
4397 ;; Special keywords
4398 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4399 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4400 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4401 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4402 ;; Emphasis
4403 (if em
4404 (if (featurep 'xemacs)
4405 '(org-do-emphasis-faces (0 nil append))
4406 '(org-do-emphasis-faces)))
4407 ;; Checkboxes
4408 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
4409 2 'org-checkbox prepend)
4410 (if org-provide-checkbox-statistics
4411 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4412 (0 (org-get-checkbox-statistics-face) t)))
4413 ;; Description list items
4414 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
4415 2 'bold prepend)
4416 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
4417 '(1 'org-archived prepend))
4418 ;; Specials
4419 '(org-do-latex-and-special-faces)
4420 ;; Code
4421 '(org-activate-code (1 'org-code t))
4422 ;; COMMENT
4423 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
4424 "\\|" org-quote-string "\\)\\>")
4425 '(1 'org-special-keyword t))
4426 '("^#.*" (0 'font-lock-comment-face t))
4428 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
4429 ;; Now set the full font-lock-keywords
4430 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
4431 (org-set-local 'font-lock-defaults
4432 '(org-font-lock-keywords t nil nil backward-paragraph))
4433 (kill-local-variable 'font-lock-keywords) nil))
4435 (defvar org-m nil)
4436 (defvar org-l nil)
4437 (defvar org-f nil)
4438 (defun org-get-level-face (n)
4439 "Get the right face for match N in font-lock matching of headlines."
4440 (setq org-l (- (match-end 2) (match-beginning 1) 1))
4441 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
4442 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
4443 (cond
4444 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
4445 ((eq n 2) org-f)
4446 (t (if org-level-color-stars-only nil org-f))))
4448 (defun org-get-todo-face (kwd)
4449 "Get the right face for a TODO keyword KWD.
4450 If KWD is a number, get the corresponding match group."
4451 (if (numberp kwd) (setq kwd (match-string kwd)))
4452 (or (cdr (assoc kwd org-todo-keyword-faces))
4453 (and (member kwd org-done-keywords) 'org-done)
4454 'org-todo))
4456 (defun org-font-lock-add-tag-faces (limit)
4457 "Add the special tag faces."
4458 (when (and org-tag-faces org-tags-special-faces-re)
4459 (while (re-search-forward org-tags-special-faces-re limit t)
4460 (add-text-properties (match-beginning 1) (match-end 1)
4461 (list 'face (org-get-tag-face 1)
4462 'font-lock-fontified t))
4463 (backward-char 1))))
4465 (defun org-font-lock-add-priority-faces (limit)
4466 "Add the special priority faces."
4467 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
4468 (add-text-properties
4469 (match-beginning 0) (match-end 0)
4470 (list 'face (or (cdr (assoc (char-after (match-beginning 1))
4471 org-priority-faces))
4472 'org-special-keyword)
4473 'font-lock-fontified t))))
4475 (defun org-get-tag-face (kwd)
4476 "Get the right face for a TODO keyword KWD.
4477 If KWD is a number, get the corresponding match group."
4478 (if (numberp kwd) (setq kwd (match-string kwd)))
4479 (or (cdr (assoc kwd org-tag-faces))
4480 'org-tag))
4482 (defun org-unfontify-region (beg end &optional maybe_loudly)
4483 "Remove fontification and activation overlays from links."
4484 (font-lock-default-unfontify-region beg end)
4485 (let* ((buffer-undo-list t)
4486 (inhibit-read-only t) (inhibit-point-motion-hooks t)
4487 (inhibit-modification-hooks t)
4488 deactivate-mark buffer-file-name buffer-file-truename)
4489 (remove-text-properties beg end
4490 '(mouse-face t keymap t org-linked-text t
4491 invisible t intangible t))))
4493 ;;;; Visibility cycling, including org-goto and indirect buffer
4495 ;;; Cycling
4497 (defvar org-cycle-global-status nil)
4498 (make-variable-buffer-local 'org-cycle-global-status)
4499 (defvar org-cycle-subtree-status nil)
4500 (make-variable-buffer-local 'org-cycle-subtree-status)
4502 ;;;###autoload
4504 (defvar org-inlinetask-min-level)
4505 (defun org-cycle (&optional arg)
4506 "Visibility cycling for Org-mode.
4508 - When this function is called with a prefix argument, rotate the entire
4509 buffer through 3 states (global cycling)
4510 1. OVERVIEW: Show only top-level headlines.
4511 2. CONTENTS: Show all headlines of all levels, but no body text.
4512 3. SHOW ALL: Show everything.
4513 When called with two C-u C-u prefixes, switch to the startup visibility,
4514 determined by the variable `org-startup-folded', and by any VISIBILITY
4515 properties in the buffer.
4516 When called with three C-u C-u C-u prefixed, show the entire buffer,
4517 including drawers.
4519 - When point is at the beginning of a headline, rotate the subtree started
4520 by this line through 3 different states (local cycling)
4521 1. FOLDED: Only the main headline is shown.
4522 2. CHILDREN: The main headline and the direct children are shown.
4523 From this state, you can move to one of the children
4524 and zoom in further.
4525 3. SUBTREE: Show the entire subtree, including body text.
4527 - When there is a numeric prefix, go up to a heading with level ARG, do
4528 a `show-subtree' and return to the previous cursor position. If ARG
4529 is negative, go up that many levels.
4531 - When point is not at the beginning of a headline, execute the global
4532 binding for TAB, which is re-indenting the line. See the option
4533 `org-cycle-emulate-tab' for details.
4535 - Special case: if point is at the beginning of the buffer and there is
4536 no headline in line 1, this function will act as if called with prefix arg.
4537 But only if also the variable `org-cycle-global-at-bob' is t."
4538 (interactive "P")
4539 (org-load-modules-maybe)
4540 (let* ((limit-level
4541 (or org-cycle-max-level
4542 (and (boundp 'org-inlinetask-min-level)
4543 org-inlinetask-min-level
4544 (1- org-inlinetask-min-level))))
4545 (nstars (and limit-level
4546 (if org-odd-levels-only
4547 (and limit-level (1- (* limit-level 2)))
4548 limit-level)))
4549 (outline-regexp
4550 (cond
4551 ((not (org-mode-p)) outline-regexp)
4552 (org-cycle-include-plain-lists
4553 (concat "\\(?:\\*"
4554 (if nstars (format "\\{1,%d\\} " nstars) "+")
4555 " \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"))
4556 (t (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))))
4557 (bob-special (and org-cycle-global-at-bob (bobp)
4558 (not (looking-at outline-regexp))))
4559 (org-cycle-hook
4560 (if bob-special
4561 (delq 'org-optimize-window-after-visibility-change
4562 (copy-sequence org-cycle-hook))
4563 org-cycle-hook))
4564 (pos (point)))
4566 (if (or bob-special (equal arg '(4)))
4567 ;; special case: use global cycling
4568 (setq arg t))
4570 (cond
4572 ((equal arg '(16))
4573 (org-set-startup-visibility)
4574 (message "Startup visibility, plus VISIBILITY properties"))
4576 ((equal arg '(64))
4577 (show-all)
4578 (message "Entire buffer visible, including drawers"))
4580 ((org-at-table-p 'any)
4581 ;; Enter the table or move to the next field in the table
4582 (or (org-table-recognize-table.el)
4583 (progn
4584 (if arg (org-table-edit-field t)
4585 (org-table-justify-field-maybe)
4586 (call-interactively 'org-table-next-field)))))
4588 ((eq arg t) ;; Global cycling
4590 (cond
4591 ((and (eq last-command this-command)
4592 (eq org-cycle-global-status 'overview))
4593 ;; We just created the overview - now do table of contents
4594 ;; This can be slow in very large buffers, so indicate action
4595 (message "CONTENTS...")
4596 (org-content)
4597 (message "CONTENTS...done")
4598 (setq org-cycle-global-status 'contents)
4599 (run-hook-with-args 'org-cycle-hook 'contents))
4601 ((and (eq last-command this-command)
4602 (eq org-cycle-global-status 'contents))
4603 ;; We just showed the table of contents - now show everything
4604 (show-all)
4605 (message "SHOW ALL")
4606 (setq org-cycle-global-status 'all)
4607 (run-hook-with-args 'org-cycle-hook 'all))
4610 ;; Default action: go to overview
4611 (org-overview)
4612 (message "OVERVIEW")
4613 (setq org-cycle-global-status 'overview)
4614 (run-hook-with-args 'org-cycle-hook 'overview))))
4616 ((and org-drawers org-drawer-regexp
4617 (save-excursion
4618 (beginning-of-line 1)
4619 (looking-at org-drawer-regexp)))
4620 ;; Toggle block visibility
4621 (org-flag-drawer
4622 (not (get-char-property (match-end 0) 'invisible))))
4624 ((integerp arg)
4625 ;; Show-subtree, ARG levels up from here.
4626 (save-excursion
4627 (org-back-to-heading)
4628 (outline-up-heading (if (< arg 0) (- arg)
4629 (- (funcall outline-level) arg)))
4630 (org-show-subtree)))
4632 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4633 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4634 ;; At a heading: rotate between three different views
4635 (org-back-to-heading)
4636 (let ((goal-column 0) eoh eol eos)
4637 ;; First, some boundaries
4638 (save-excursion
4639 (org-back-to-heading)
4640 (save-excursion
4641 (beginning-of-line 2)
4642 (while (and (not (eobp)) ;; this is like `next-line'
4643 (get-char-property (1- (point)) 'invisible))
4644 (beginning-of-line 2)) (setq eol (point)))
4645 (outline-end-of-heading) (setq eoh (point))
4646 (org-end-of-subtree t)
4647 (unless (eobp)
4648 (skip-chars-forward " \t\n")
4649 (beginning-of-line 1) ; in case this is an item
4651 (setq eos (1- (point))))
4652 ;; Find out what to do next and set `this-command'
4653 (cond
4654 ((= eos eoh)
4655 ;; Nothing is hidden behind this heading
4656 (message "EMPTY ENTRY")
4657 (setq org-cycle-subtree-status nil)
4658 (save-excursion
4659 (goto-char eos)
4660 (outline-next-heading)
4661 (if (org-invisible-p) (org-flag-heading nil))))
4662 ((or (>= eol eos)
4663 (not (string-match "\\S-" (buffer-substring eol eos))))
4664 ;; Entire subtree is hidden in one line: open it
4665 (org-show-entry)
4666 (show-children)
4667 (message "CHILDREN")
4668 (save-excursion
4669 (goto-char eos)
4670 (outline-next-heading)
4671 (if (org-invisible-p) (org-flag-heading nil)))
4672 (setq org-cycle-subtree-status 'children)
4673 (run-hook-with-args 'org-cycle-hook 'children))
4674 ((and (eq last-command this-command)
4675 (eq org-cycle-subtree-status 'children))
4676 ;; We just showed the children, now show everything.
4677 (org-show-subtree)
4678 (message "SUBTREE")
4679 (setq org-cycle-subtree-status 'subtree)
4680 (run-hook-with-args 'org-cycle-hook 'subtree))
4682 ;; Default action: hide the subtree.
4683 (hide-subtree)
4684 (message "FOLDED")
4685 (setq org-cycle-subtree-status 'folded)
4686 (run-hook-with-args 'org-cycle-hook 'folded)))))
4688 ;; TAB emulation and template completion
4689 (buffer-read-only (org-back-to-heading))
4691 ((org-try-structure-completion))
4693 ((org-try-cdlatex-tab))
4695 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4696 (or (not (bolp))
4697 (not (looking-at outline-regexp))))
4698 (call-interactively (global-key-binding "\t")))
4700 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4701 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4702 (or (and (eq org-cycle-emulate-tab 'white)
4703 (= (match-end 0) (point-at-eol)))
4704 (and (eq org-cycle-emulate-tab 'whitestart)
4705 (>= (match-end 0) pos))))
4707 (eq org-cycle-emulate-tab t))
4708 (call-interactively (global-key-binding "\t")))
4710 (t (save-excursion
4711 (org-back-to-heading)
4712 (org-cycle))))))
4714 ;;;###autoload
4715 (defun org-global-cycle (&optional arg)
4716 "Cycle the global visibility. For details see `org-cycle'.
4717 With C-u prefix arg, switch to startup visibility.
4718 With a numeric prefix, show all headlines up to that level."
4719 (interactive "P")
4720 (let ((org-cycle-include-plain-lists
4721 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4722 (cond
4723 ((integerp arg)
4724 (show-all)
4725 (hide-sublevels arg)
4726 (setq org-cycle-global-status 'contents))
4727 ((equal arg '(4))
4728 (org-set-startup-visibility)
4729 (message "Startup visibility, plus VISIBILITY properties."))
4731 (org-cycle '(4))))))
4733 (defun org-set-startup-visibility ()
4734 "Set the visibility required by startup options and properties."
4735 (cond
4736 ((eq org-startup-folded t)
4737 (org-cycle '(4)))
4738 ((eq org-startup-folded 'content)
4739 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4740 (org-cycle '(4)) (org-cycle '(4)))))
4741 (org-set-visibility-according-to-property 'no-cleanup)
4742 (org-cycle-hide-archived-subtrees 'all)
4743 (org-cycle-hide-drawers 'all)
4744 (org-cycle-show-empty-lines 'all))
4746 (defun org-set-visibility-according-to-property (&optional no-cleanup)
4747 "Switch subtree visibilities according to :VISIBILITY: property."
4748 (interactive)
4749 (let (org-show-entry-below state)
4750 (save-excursion
4751 (goto-char (point-min))
4752 (while (re-search-forward
4753 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
4754 nil t)
4755 (setq state (match-string 1))
4756 (save-excursion
4757 (org-back-to-heading t)
4758 (hide-subtree)
4759 (org-reveal)
4760 (cond
4761 ((equal state '("fold" "folded"))
4762 (hide-subtree))
4763 ((equal state "children")
4764 (org-show-hidden-entry)
4765 (show-children))
4766 ((equal state "content")
4767 (save-excursion
4768 (save-restriction
4769 (org-narrow-to-subtree)
4770 (org-content))))
4771 ((member state '("all" "showall"))
4772 (show-subtree)))))
4773 (unless no-cleanup
4774 (org-cycle-hide-archived-subtrees 'all)
4775 (org-cycle-hide-drawers 'all)
4776 (org-cycle-show-empty-lines 'all)))))
4778 (defun org-overview ()
4779 "Switch to overview mode, showing only top-level headlines.
4780 Really, this shows all headlines with level equal or greater than the level
4781 of the first headline in the buffer. This is important, because if the
4782 first headline is not level one, then (hide-sublevels 1) gives confusing
4783 results."
4784 (interactive)
4785 (let ((level (save-excursion
4786 (goto-char (point-min))
4787 (if (re-search-forward (concat "^" outline-regexp) nil t)
4788 (progn
4789 (goto-char (match-beginning 0))
4790 (funcall outline-level))))))
4791 (and level (hide-sublevels level))))
4793 (defun org-content (&optional arg)
4794 "Show all headlines in the buffer, like a table of contents.
4795 With numerical argument N, show content up to level N."
4796 (interactive "P")
4797 (save-excursion
4798 ;; Visit all headings and show their offspring
4799 (and (integerp arg) (org-overview))
4800 (goto-char (point-max))
4801 (catch 'exit
4802 (while (and (progn (condition-case nil
4803 (outline-previous-visible-heading 1)
4804 (error (goto-char (point-min))))
4806 (looking-at outline-regexp))
4807 (if (integerp arg)
4808 (show-children (1- arg))
4809 (show-branches))
4810 (if (bobp) (throw 'exit nil))))))
4813 (defun org-optimize-window-after-visibility-change (state)
4814 "Adjust the window after a change in outline visibility.
4815 This function is the default value of the hook `org-cycle-hook'."
4816 (when (get-buffer-window (current-buffer))
4817 (cond
4818 ((eq state 'content) nil)
4819 ((eq state 'all) nil)
4820 ((eq state 'folded) nil)
4821 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4822 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4824 (defun org-compact-display-after-subtree-move ()
4825 "Show a compacter version of the tree of the entry's parent."
4826 (save-excursion
4827 (if (org-up-heading-safe)
4828 (progn
4829 (hide-subtree)
4830 (show-entry)
4831 (show-children)
4832 (org-cycle-show-empty-lines 'children)
4833 (org-cycle-hide-drawers 'children))
4834 (org-overview))))
4836 (defun org-cycle-show-empty-lines (state)
4837 "Show empty lines above all visible headlines.
4838 The region to be covered depends on STATE when called through
4839 `org-cycle-hook'. Lisp program can use t for STATE to get the
4840 entire buffer covered. Note that an empty line is only shown if there
4841 are at least `org-cycle-separator-lines' empty lines before the headline."
4842 (when (> org-cycle-separator-lines 0)
4843 (save-excursion
4844 (let* ((n org-cycle-separator-lines)
4845 (re (cond
4846 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
4847 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
4848 (t (let ((ns (number-to-string (- n 2))))
4849 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
4850 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
4851 beg end)
4852 (cond
4853 ((memq state '(overview contents t))
4854 (setq beg (point-min) end (point-max)))
4855 ((memq state '(children folded))
4856 (setq beg (point) end (progn (org-end-of-subtree t t)
4857 (beginning-of-line 2)
4858 (point)))))
4859 (when beg
4860 (goto-char beg)
4861 (while (re-search-forward re end t)
4862 (if (not (get-char-property (match-end 1) 'invisible))
4863 (outline-flag-region
4864 (match-beginning 1) (match-end 1) nil)))))))
4865 ;; Never hide empty lines at the end of the file.
4866 (save-excursion
4867 (goto-char (point-max))
4868 (outline-previous-heading)
4869 (outline-end-of-heading)
4870 (if (and (looking-at "[ \t\n]+")
4871 (= (match-end 0) (point-max)))
4872 (outline-flag-region (point) (match-end 0) nil))))
4874 (defun org-show-empty-lines-in-parent ()
4875 "Move to the parent and re-show empty lines before visible headlines."
4876 (save-excursion
4877 (let ((context (if (org-up-heading-safe) 'children 'overview)))
4878 (org-cycle-show-empty-lines context))))
4880 (defun org-cycle-hide-drawers (state)
4881 "Re-hide all drawers after a visibility state change."
4882 (when (and (org-mode-p)
4883 (not (memq state '(overview folded))))
4884 (save-excursion
4885 (let* ((globalp (memq state '(contents all)))
4886 (beg (if globalp (point-min) (point)))
4887 (end (if globalp (point-max) (org-end-of-subtree t))))
4888 (goto-char beg)
4889 (while (re-search-forward org-drawer-regexp end t)
4890 (org-flag-drawer t))))))
4892 (defun org-flag-drawer (flag)
4893 (save-excursion
4894 (beginning-of-line 1)
4895 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
4896 (let ((b (match-end 0))
4897 (outline-regexp org-outline-regexp))
4898 (if (re-search-forward
4899 "^[ \t]*:END:"
4900 (save-excursion (outline-next-heading) (point)) t)
4901 (outline-flag-region b (point-at-eol) flag)
4902 (error ":END: line missing"))))))
4904 (defun org-subtree-end-visible-p ()
4905 "Is the end of the current subtree visible?"
4906 (pos-visible-in-window-p
4907 (save-excursion (org-end-of-subtree t) (point))))
4909 (defun org-first-headline-recenter (&optional N)
4910 "Move cursor to the first headline and recenter the headline.
4911 Optional argument N means, put the headline into the Nth line of the window."
4912 (goto-char (point-min))
4913 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4914 (beginning-of-line)
4915 (recenter (prefix-numeric-value N))))
4917 ;;; Org-goto
4919 (defvar org-goto-window-configuration nil)
4920 (defvar org-goto-marker nil)
4921 (defvar org-goto-map
4922 (let ((map (make-sparse-keymap)))
4923 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
4924 (while (setq cmd (pop cmds))
4925 (substitute-key-definition cmd cmd map global-map)))
4926 (suppress-keymap map)
4927 (org-defkey map "\C-m" 'org-goto-ret)
4928 (org-defkey map [(return)] 'org-goto-ret)
4929 (org-defkey map [(left)] 'org-goto-left)
4930 (org-defkey map [(right)] 'org-goto-right)
4931 (org-defkey map [(control ?g)] 'org-goto-quit)
4932 (org-defkey map "\C-i" 'org-cycle)
4933 (org-defkey map [(tab)] 'org-cycle)
4934 (org-defkey map [(down)] 'outline-next-visible-heading)
4935 (org-defkey map [(up)] 'outline-previous-visible-heading)
4936 (if org-goto-auto-isearch
4937 (if (fboundp 'define-key-after)
4938 (define-key-after map [t] 'org-goto-local-auto-isearch)
4939 nil)
4940 (org-defkey map "q" 'org-goto-quit)
4941 (org-defkey map "n" 'outline-next-visible-heading)
4942 (org-defkey map "p" 'outline-previous-visible-heading)
4943 (org-defkey map "f" 'outline-forward-same-level)
4944 (org-defkey map "b" 'outline-backward-same-level)
4945 (org-defkey map "u" 'outline-up-heading))
4946 (org-defkey map "/" 'org-occur)
4947 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4948 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4949 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
4950 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
4951 (org-defkey map "\C-c\C-u" 'outline-up-heading)
4952 map))
4954 (defconst org-goto-help
4955 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4956 RET=jump to location [Q]uit and return to previous location
4957 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4959 (defvar org-goto-start-pos) ; dynamically scoped parameter
4961 ;; FIXME: Docstring doe not mention both interfaces
4962 (defun org-goto (&optional alternative-interface)
4963 "Look up a different location in the current file, keeping current visibility.
4965 When you want look-up or go to a different location in a document, the
4966 fastest way is often to fold the entire buffer and then dive into the tree.
4967 This method has the disadvantage, that the previous location will be folded,
4968 which may not be what you want.
4970 This command works around this by showing a copy of the current buffer
4971 in an indirect buffer, in overview mode. You can dive into the tree in
4972 that copy, use org-occur and incremental search to find a location.
4973 When pressing RET or `Q', the command returns to the original buffer in
4974 which the visibility is still unchanged. After RET is will also jump to
4975 the location selected in the indirect buffer and expose the
4976 the headline hierarchy above."
4977 (interactive "P")
4978 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
4979 (org-refile-use-outline-path t)
4980 (interface
4981 (if (not alternative-interface)
4982 org-goto-interface
4983 (if (eq org-goto-interface 'outline)
4984 'outline-path-completion
4985 'outline)))
4986 (org-goto-start-pos (point))
4987 (selected-point
4988 (if (eq interface 'outline)
4989 (car (org-get-location (current-buffer) org-goto-help))
4990 (nth 3 (org-refile-get-location "Goto: ")))))
4991 (if selected-point
4992 (progn
4993 (org-mark-ring-push org-goto-start-pos)
4994 (goto-char selected-point)
4995 (if (or (org-invisible-p) (org-invisible-p2))
4996 (org-show-context 'org-goto)))
4997 (message "Quit"))))
4999 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
5000 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
5001 (defvar org-goto-local-auto-isearch-map) ; defined below
5003 (defun org-get-location (buf help)
5004 "Let the user select a location in the Org-mode buffer BUF.
5005 This function uses a recursive edit. It returns the selected position
5006 or nil."
5007 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
5008 (isearch-hide-immediately nil)
5009 (isearch-search-fun-function
5010 (lambda () 'org-goto-local-search-headings))
5011 (org-goto-selected-point org-goto-exit-command))
5012 (save-excursion
5013 (save-window-excursion
5014 (delete-other-windows)
5015 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
5016 (switch-to-buffer
5017 (condition-case nil
5018 (make-indirect-buffer (current-buffer) "*org-goto*")
5019 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
5020 (with-output-to-temp-buffer "*Help*"
5021 (princ help))
5022 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
5023 (setq buffer-read-only nil)
5024 (let ((org-startup-truncated t)
5025 (org-startup-folded nil)
5026 (org-startup-align-all-tables nil))
5027 (org-mode)
5028 (org-overview))
5029 (setq buffer-read-only t)
5030 (if (and (boundp 'org-goto-start-pos)
5031 (integer-or-marker-p org-goto-start-pos))
5032 (let ((org-show-hierarchy-above t)
5033 (org-show-siblings t)
5034 (org-show-following-heading t))
5035 (goto-char org-goto-start-pos)
5036 (and (org-invisible-p) (org-show-context)))
5037 (goto-char (point-min)))
5038 (let (org-special-ctrl-a/e) (org-beginning-of-line))
5039 (message "Select location and press RET")
5040 (use-local-map org-goto-map)
5041 (recursive-edit)
5043 (kill-buffer "*org-goto*")
5044 (cons org-goto-selected-point org-goto-exit-command)))
5046 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
5047 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
5048 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
5049 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
5051 (defun org-goto-local-search-headings (string bound noerror)
5052 "Search and make sure that any matches are in headlines."
5053 (catch 'return
5054 (while (if isearch-forward
5055 (search-forward string bound noerror)
5056 (search-backward string bound noerror))
5057 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
5058 (and (member :headline context)
5059 (not (member :tags context))))
5060 (throw 'return (point))))))
5062 (defun org-goto-local-auto-isearch ()
5063 "Start isearch."
5064 (interactive)
5065 (goto-char (point-min))
5066 (let ((keys (this-command-keys)))
5067 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
5068 (isearch-mode t)
5069 (isearch-process-search-char (string-to-char keys)))))
5071 (defun org-goto-ret (&optional arg)
5072 "Finish `org-goto' by going to the new location."
5073 (interactive "P")
5074 (setq org-goto-selected-point (point)
5075 org-goto-exit-command 'return)
5076 (throw 'exit nil))
5078 (defun org-goto-left ()
5079 "Finish `org-goto' by going to the new location."
5080 (interactive)
5081 (if (org-on-heading-p)
5082 (progn
5083 (beginning-of-line 1)
5084 (setq org-goto-selected-point (point)
5085 org-goto-exit-command 'left)
5086 (throw 'exit nil))
5087 (error "Not on a heading")))
5089 (defun org-goto-right ()
5090 "Finish `org-goto' by going to the new location."
5091 (interactive)
5092 (if (org-on-heading-p)
5093 (progn
5094 (setq org-goto-selected-point (point)
5095 org-goto-exit-command 'right)
5096 (throw 'exit nil))
5097 (error "Not on a heading")))
5099 (defun org-goto-quit ()
5100 "Finish `org-goto' without cursor motion."
5101 (interactive)
5102 (setq org-goto-selected-point nil)
5103 (setq org-goto-exit-command 'quit)
5104 (throw 'exit nil))
5106 ;;; Indirect buffer display of subtrees
5108 (defvar org-indirect-dedicated-frame nil
5109 "This is the frame being used for indirect tree display.")
5110 (defvar org-last-indirect-buffer nil)
5112 (defun org-tree-to-indirect-buffer (&optional arg)
5113 "Create indirect buffer and narrow it to current subtree.
5114 With numerical prefix ARG, go up to this level and then take that tree.
5115 If ARG is negative, go up that many levels.
5116 If `org-indirect-buffer-display' is not `new-frame', the command removes the
5117 indirect buffer previously made with this command, to avoid proliferation of
5118 indirect buffers. However, when you call the command with a `C-u' prefix, or
5119 when `org-indirect-buffer-display' is `new-frame', the last buffer
5120 is kept so that you can work with several indirect buffers at the same time.
5121 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
5122 requests that a new frame be made for the new buffer, so that the dedicated
5123 frame is not changed."
5124 (interactive "P")
5125 (let ((cbuf (current-buffer))
5126 (cwin (selected-window))
5127 (pos (point))
5128 beg end level heading ibuf)
5129 (save-excursion
5130 (org-back-to-heading t)
5131 (when (numberp arg)
5132 (setq level (org-outline-level))
5133 (if (< arg 0) (setq arg (+ level arg)))
5134 (while (> (setq level (org-outline-level)) arg)
5135 (outline-up-heading 1 t)))
5136 (setq beg (point)
5137 heading (org-get-heading))
5138 (org-end-of-subtree t) (setq end (point)))
5139 (if (and (buffer-live-p org-last-indirect-buffer)
5140 (not (eq org-indirect-buffer-display 'new-frame))
5141 (not arg))
5142 (kill-buffer org-last-indirect-buffer))
5143 (setq ibuf (org-get-indirect-buffer cbuf)
5144 org-last-indirect-buffer ibuf)
5145 (cond
5146 ((or (eq org-indirect-buffer-display 'new-frame)
5147 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
5148 (select-frame (make-frame))
5149 (delete-other-windows)
5150 (switch-to-buffer ibuf)
5151 (org-set-frame-title heading))
5152 ((eq org-indirect-buffer-display 'dedicated-frame)
5153 (raise-frame
5154 (select-frame (or (and org-indirect-dedicated-frame
5155 (frame-live-p org-indirect-dedicated-frame)
5156 org-indirect-dedicated-frame)
5157 (setq org-indirect-dedicated-frame (make-frame)))))
5158 (delete-other-windows)
5159 (switch-to-buffer ibuf)
5160 (org-set-frame-title (concat "Indirect: " heading)))
5161 ((eq org-indirect-buffer-display 'current-window)
5162 (switch-to-buffer ibuf))
5163 ((eq org-indirect-buffer-display 'other-window)
5164 (pop-to-buffer ibuf))
5165 (t (error "Invalid value.")))
5166 (if (featurep 'xemacs)
5167 (save-excursion (org-mode) (turn-on-font-lock)))
5168 (narrow-to-region beg end)
5169 (show-all)
5170 (goto-char pos)
5171 (and (window-live-p cwin) (select-window cwin))))
5173 (defun org-get-indirect-buffer (&optional buffer)
5174 (setq buffer (or buffer (current-buffer)))
5175 (let ((n 1) (base (buffer-name buffer)) bname)
5176 (while (buffer-live-p
5177 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
5178 (setq n (1+ n)))
5179 (condition-case nil
5180 (make-indirect-buffer buffer bname 'clone)
5181 (error (make-indirect-buffer buffer bname)))))
5183 (defun org-set-frame-title (title)
5184 "Set the title of the current frame to the string TITLE."
5185 ;; FIXME: how to name a single frame in XEmacs???
5186 (unless (featurep 'xemacs)
5187 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
5189 ;;;; Structure editing
5191 ;;; Inserting headlines
5193 (defun org-previous-line-empty-p ()
5194 (save-excursion
5195 (and (not (bobp))
5196 (or (beginning-of-line 0) t)
5197 (save-match-data
5198 (looking-at "[ \t]*$")))))
5200 (defun org-insert-heading (&optional force-heading)
5201 "Insert a new heading or item with same depth at point.
5202 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
5203 If point is at the beginning of a headline, insert a sibling before the
5204 current headline. If point is not at the beginning, do not split the line,
5205 but create the new headline after the current line."
5206 (interactive "P")
5207 (if (= (buffer-size) 0)
5208 (insert "\n* ")
5209 (when (or force-heading (not (org-insert-item)))
5210 (let* ((empty-line-p nil)
5211 (head (save-excursion
5212 (condition-case nil
5213 (progn
5214 (org-back-to-heading)
5215 (setq empty-line-p (org-previous-line-empty-p))
5216 (match-string 0))
5217 (error "*"))))
5218 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
5219 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
5220 pos hide-previous previous-pos)
5221 (cond
5222 ((and (org-on-heading-p) (bolp)
5223 (or (bobp)
5224 (save-excursion (backward-char 1) (not (org-invisible-p)))))
5225 ;; insert before the current line
5226 (open-line (if blank 2 1)))
5227 ((and (bolp)
5228 (or (bobp)
5229 (save-excursion
5230 (backward-char 1) (not (org-invisible-p)))))
5231 ;; insert right here
5232 nil)
5234 ;; somewhere in the line
5235 (save-excursion
5236 (setq previous-pos (point-at-bol))
5237 (end-of-line)
5238 (setq hide-previous (org-invisible-p)))
5239 (and org-insert-heading-respect-content (org-show-subtree))
5240 (let ((split
5241 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
5242 (save-excursion
5243 (let ((p (point)))
5244 (goto-char (point-at-bol))
5245 (and (looking-at org-complex-heading-regexp)
5246 (> p (match-beginning 4)))))))
5247 tags pos)
5248 (cond
5249 (org-insert-heading-respect-content
5250 (org-end-of-subtree nil t)
5251 (or (bolp) (newline))
5252 (or (org-previous-line-empty-p)
5253 (and blank (newline)))
5254 (open-line 1))
5255 ((org-on-heading-p)
5256 (when hide-previous
5257 (show-children)
5258 (org-show-entry))
5259 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
5260 (setq tags (and (match-end 2) (match-string 2)))
5261 (and (match-end 1)
5262 (delete-region (match-beginning 1) (match-end 1)))
5263 (setq pos (point-at-bol))
5264 (or split (end-of-line 1))
5265 (delete-horizontal-space)
5266 (newline (if blank 2 1))
5267 (when tags
5268 (save-excursion
5269 (goto-char pos)
5270 (end-of-line 1)
5271 (insert " " tags)
5272 (org-set-tags nil 'align))))
5274 (or split (end-of-line 1))
5275 (newline (if blank 2 1)))))))
5276 (insert head) (just-one-space)
5277 (setq pos (point))
5278 (end-of-line 1)
5279 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
5280 (when (and org-insert-heading-respect-content hide-previous)
5281 (save-excursion
5282 (goto-char previous-pos)
5283 (hide-subtree)))
5284 (run-hooks 'org-insert-heading-hook)))))
5286 (defun org-get-heading (&optional no-tags)
5287 "Return the heading of the current entry, without the stars."
5288 (save-excursion
5289 (org-back-to-heading t)
5290 (if (looking-at
5291 (if no-tags
5292 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
5293 "\\*+[ \t]+\\([^\r\n]*\\)"))
5294 (match-string 1) "")))
5296 (defun org-heading-components ()
5297 "Return the components of the current heading.
5298 This is a list with the following elements:
5299 - the level as an integer
5300 - the reduced level, different if `org-odd-levels-only' is set.
5301 - the TODO keyword, or nil
5302 - the priority character, like ?A, or nil if no priority is given
5303 - the headline text itself, or the tags string if no headline text
5304 - the tags string, or nil."
5305 (save-excursion
5306 (org-back-to-heading t)
5307 (if (looking-at org-complex-heading-regexp)
5308 (list (length (match-string 1))
5309 (org-reduced-level (length (match-string 1)))
5310 (org-match-string-no-properties 2)
5311 (and (match-end 3) (aref (match-string 3) 2))
5312 (org-match-string-no-properties 4)
5313 (org-match-string-no-properties 5)))))
5315 (defun org-insert-heading-after-current ()
5316 "Insert a new heading with same level as current, after current subtree."
5317 (interactive)
5318 (org-back-to-heading)
5319 (org-insert-heading)
5320 (org-move-subtree-down)
5321 (end-of-line 1))
5323 (defun org-insert-heading-respect-content ()
5324 (interactive)
5325 (let ((org-insert-heading-respect-content t))
5326 (org-insert-heading t)))
5328 (defun org-insert-todo-heading-respect-content (&optional force-state)
5329 (interactive "P")
5330 (let ((org-insert-heading-respect-content t))
5331 (org-insert-todo-heading force-state t)))
5333 (defun org-insert-todo-heading (arg &optional force-heading)
5334 "Insert a new heading with the same level and TODO state as current heading.
5335 If the heading has no TODO state, or if the state is DONE, use the first
5336 state (TODO by default). Also with prefix arg, force first state."
5337 (interactive "P")
5338 (when (or force-heading (not (org-insert-item 'checkbox)))
5339 (org-insert-heading force-heading)
5340 (save-excursion
5341 (org-back-to-heading)
5342 (outline-previous-heading)
5343 (looking-at org-todo-line-regexp))
5344 (let*
5345 ((new-mark-x
5346 (if (or arg
5347 (not (match-beginning 2))
5348 (member (match-string 2) org-done-keywords))
5349 (car org-todo-keywords-1)
5350 (match-string 2)))
5351 (new-mark
5353 (run-hook-with-args-until-success
5354 'org-todo-get-default-hook new-mark-x nil)
5355 new-mark-x)))
5356 (beginning-of-line 1)
5357 (and (looking-at "\\*+ ") (goto-char (match-end 0))
5358 (insert new-mark " ")))
5359 (when org-provide-todo-statistics
5360 (org-update-parent-todo-statistics))))
5362 (defun org-insert-subheading (arg)
5363 "Insert a new subheading and demote it.
5364 Works for outline headings and for plain lists alike."
5365 (interactive "P")
5366 (org-insert-heading arg)
5367 (cond
5368 ((org-on-heading-p) (org-do-demote))
5369 ((org-at-item-p) (org-indent-item 1))))
5371 (defun org-insert-todo-subheading (arg)
5372 "Insert a new subheading with TODO keyword or checkbox and demote it.
5373 Works for outline headings and for plain lists alike."
5374 (interactive "P")
5375 (org-insert-todo-heading arg)
5376 (cond
5377 ((org-on-heading-p) (org-do-demote))
5378 ((org-at-item-p) (org-indent-item 1))))
5380 ;;; Promotion and Demotion
5382 (defun org-promote-subtree ()
5383 "Promote the entire subtree.
5384 See also `org-promote'."
5385 (interactive)
5386 (save-excursion
5387 (org-map-tree 'org-promote))
5388 (org-fix-position-after-promote))
5390 (defun org-demote-subtree ()
5391 "Demote the entire subtree. See `org-demote'.
5392 See also `org-promote'."
5393 (interactive)
5394 (save-excursion
5395 (org-map-tree 'org-demote))
5396 (org-fix-position-after-promote))
5399 (defun org-do-promote ()
5400 "Promote the current heading higher up the tree.
5401 If the region is active in `transient-mark-mode', promote all headings
5402 in the region."
5403 (interactive)
5404 (save-excursion
5405 (if (org-region-active-p)
5406 (org-map-region 'org-promote (region-beginning) (region-end))
5407 (org-promote)))
5408 (org-fix-position-after-promote))
5410 (defun org-do-demote ()
5411 "Demote the current heading lower down the tree.
5412 If the region is active in `transient-mark-mode', demote all headings
5413 in the region."
5414 (interactive)
5415 (save-excursion
5416 (if (org-region-active-p)
5417 (org-map-region 'org-demote (region-beginning) (region-end))
5418 (org-demote)))
5419 (org-fix-position-after-promote))
5421 (defun org-fix-position-after-promote ()
5422 "Make sure that after pro/demotion cursor position is right."
5423 (let ((pos (point)))
5424 (when (save-excursion
5425 (beginning-of-line 1)
5426 (looking-at org-todo-line-regexp)
5427 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
5428 (cond ((eobp) (insert " "))
5429 ((eolp) (insert " "))
5430 ((equal (char-after) ?\ ) (forward-char 1))))))
5432 (defun org-reduced-level (l)
5433 "Compute the effective level of a heading.
5434 This takes into account the setting of `org-odd-levels-only'."
5435 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
5437 (defun org-get-valid-level (level &optional change)
5438 "Rectify a level change under the influence of `org-odd-levels-only'
5439 LEVEL is a current level, CHANGE is by how much the level should be
5440 modified. Even if CHANGE is nil, LEVEL may be returned modified because
5441 even level numbers will become the next higher odd number."
5442 (if org-odd-levels-only
5443 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
5444 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
5445 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
5446 (max 1 (+ level (or change 0)))))
5448 (if (boundp 'define-obsolete-function-alias)
5449 (if (or (featurep 'xemacs) (< emacs-major-version 23))
5450 (define-obsolete-function-alias 'org-get-legal-level
5451 'org-get-valid-level)
5452 (define-obsolete-function-alias 'org-get-legal-level
5453 'org-get-valid-level "23.1")))
5455 (defun org-promote ()
5456 "Promote the current heading higher up the tree.
5457 If the region is active in `transient-mark-mode', promote all headings
5458 in the region."
5459 (org-back-to-heading t)
5460 (let* ((level (save-match-data (funcall outline-level)))
5461 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
5462 (diff (abs (- level (length up-head) -1))))
5463 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
5464 (replace-match up-head nil t)
5465 ;; Fixup tag positioning
5466 (and org-auto-align-tags (org-set-tags nil t))
5467 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
5469 (defun org-demote ()
5470 "Demote the current heading lower down the tree.
5471 If the region is active in `transient-mark-mode', demote all headings
5472 in the region."
5473 (org-back-to-heading t)
5474 (let* ((level (save-match-data (funcall outline-level)))
5475 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
5476 (diff (abs (- level (length down-head) -1))))
5477 (replace-match down-head nil t)
5478 ;; Fixup tag positioning
5479 (and org-auto-align-tags (org-set-tags nil t))
5480 (if org-adapt-indentation (org-fixup-indentation diff))))
5482 (defun org-map-tree (fun)
5483 "Call FUN for every heading underneath the current one."
5484 (org-back-to-heading)
5485 (let ((level (funcall outline-level)))
5486 (save-excursion
5487 (funcall fun)
5488 (while (and (progn
5489 (outline-next-heading)
5490 (> (funcall outline-level) level))
5491 (not (eobp)))
5492 (funcall fun)))))
5494 (defun org-map-region (fun beg end)
5495 "Call FUN for every heading between BEG and END."
5496 (let ((org-ignore-region t))
5497 (save-excursion
5498 (setq end (copy-marker end))
5499 (goto-char beg)
5500 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
5501 (< (point) end))
5502 (funcall fun))
5503 (while (and (progn
5504 (outline-next-heading)
5505 (< (point) end))
5506 (not (eobp)))
5507 (funcall fun)))))
5509 (defun org-fixup-indentation (diff)
5510 "Change the indentation in the current entry by DIFF
5511 However, if any line in the current entry has no indentation, or if it
5512 would end up with no indentation after the change, nothing at all is done."
5513 (save-excursion
5514 (let ((end (save-excursion (outline-next-heading)
5515 (point-marker)))
5516 (prohibit (if (> diff 0)
5517 "^\\S-"
5518 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
5519 col)
5520 (unless (save-excursion (end-of-line 1)
5521 (re-search-forward prohibit end t))
5522 (while (and (< (point) end)
5523 (re-search-forward "^[ \t]+" end t))
5524 (goto-char (match-end 0))
5525 (setq col (current-column))
5526 (if (< diff 0) (replace-match ""))
5527 (org-indent-to-column (+ diff col))))
5528 (move-marker end nil))))
5530 (defun org-convert-to-odd-levels ()
5531 "Convert an org-mode file with all levels allowed to one with odd levels.
5532 This will leave level 1 alone, convert level 2 to level 3, level 3 to
5533 level 5 etc."
5534 (interactive)
5535 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
5536 (let ((org-odd-levels-only nil) n)
5537 (save-excursion
5538 (goto-char (point-min))
5539 (while (re-search-forward "^\\*\\*+ " nil t)
5540 (setq n (- (length (match-string 0)) 2))
5541 (while (>= (setq n (1- n)) 0)
5542 (org-demote))
5543 (end-of-line 1))))))
5546 (defun org-convert-to-oddeven-levels ()
5547 "Convert an org-mode file with only odd levels to one with odd and even levels.
5548 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
5549 section with an even level, conversion would destroy the structure of the file. An error
5550 is signaled in this case."
5551 (interactive)
5552 (goto-char (point-min))
5553 ;; First check if there are no even levels
5554 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
5555 (org-show-context t)
5556 (error "Not all levels are odd in this file. Conversion not possible."))
5557 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
5558 (let ((org-odd-levels-only nil) n)
5559 (save-excursion
5560 (goto-char (point-min))
5561 (while (re-search-forward "^\\*\\*+ " nil t)
5562 (setq n (/ (1- (length (match-string 0))) 2))
5563 (while (>= (setq n (1- n)) 0)
5564 (org-promote))
5565 (end-of-line 1))))))
5567 (defun org-tr-level (n)
5568 "Make N odd if required."
5569 (if org-odd-levels-only (1+ (/ n 2)) n))
5571 ;;; Vertical tree motion, cutting and pasting of subtrees
5573 (defun org-move-subtree-up (&optional arg)
5574 "Move the current subtree up past ARG headlines of the same level."
5575 (interactive "p")
5576 (org-move-subtree-down (- (prefix-numeric-value arg))))
5578 (defun org-move-subtree-down (&optional arg)
5579 "Move the current subtree down past ARG headlines of the same level."
5580 (interactive "p")
5581 (setq arg (prefix-numeric-value arg))
5582 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
5583 'outline-get-last-sibling))
5584 (ins-point (make-marker))
5585 (cnt (abs arg))
5586 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
5587 ;; Select the tree
5588 (org-back-to-heading)
5589 (setq beg0 (point))
5590 (save-excursion
5591 (setq ne-beg (org-back-over-empty-lines))
5592 (setq beg (point)))
5593 (save-match-data
5594 (save-excursion (outline-end-of-heading)
5595 (setq folded (org-invisible-p)))
5596 (outline-end-of-subtree))
5597 (outline-next-heading)
5598 (setq ne-end (org-back-over-empty-lines))
5599 (setq end (point))
5600 (goto-char beg0)
5601 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
5602 ;; include less whitespace
5603 (save-excursion
5604 (goto-char beg)
5605 (forward-line (- ne-beg ne-end))
5606 (setq beg (point))))
5607 ;; Find insertion point, with error handling
5608 (while (> cnt 0)
5609 (or (and (funcall movfunc) (looking-at outline-regexp))
5610 (progn (goto-char beg0)
5611 (error "Cannot move past superior level or buffer limit")))
5612 (setq cnt (1- cnt)))
5613 (if (> arg 0)
5614 ;; Moving forward - still need to move over subtree
5615 (progn (org-end-of-subtree t t)
5616 (save-excursion
5617 (org-back-over-empty-lines)
5618 (or (bolp) (newline)))))
5619 (setq ne-ins (org-back-over-empty-lines))
5620 (move-marker ins-point (point))
5621 (setq txt (buffer-substring beg end))
5622 (org-save-markers-in-region beg end)
5623 (delete-region beg end)
5624 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
5625 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
5626 (and (not (bolp)) (looking-at "\n") (forward-char 1))
5627 (let ((bbb (point)))
5628 (insert-before-markers txt)
5629 (org-reinstall-markers-in-region bbb)
5630 (move-marker ins-point bbb))
5631 (or (bolp) (insert "\n"))
5632 (setq ins-end (point))
5633 (goto-char ins-point)
5634 (org-skip-whitespace)
5635 (when (and (< arg 0)
5636 (org-first-sibling-p)
5637 (> ne-ins ne-beg))
5638 ;; Move whitespace back to beginning
5639 (save-excursion
5640 (goto-char ins-end)
5641 (let ((kill-whole-line t))
5642 (kill-line (- ne-ins ne-beg)) (point)))
5643 (insert (make-string (- ne-ins ne-beg) ?\n)))
5644 (move-marker ins-point nil)
5645 (org-compact-display-after-subtree-move)
5646 (org-show-empty-lines-in-parent)
5647 (unless folded
5648 (org-show-entry)
5649 (show-children)
5650 (org-cycle-hide-drawers 'children))))
5652 (defvar org-subtree-clip ""
5653 "Clipboard for cut and paste of subtrees.
5654 This is actually only a copy of the kill, because we use the normal kill
5655 ring. We need it to check if the kill was created by `org-copy-subtree'.")
5657 (defvar org-subtree-clip-folded nil
5658 "Was the last copied subtree folded?
5659 This is used to fold the tree back after pasting.")
5661 (defun org-cut-subtree (&optional n)
5662 "Cut the current subtree into the clipboard.
5663 With prefix arg N, cut this many sequential subtrees.
5664 This is a short-hand for marking the subtree and then cutting it."
5665 (interactive "p")
5666 (org-copy-subtree n 'cut))
5668 (defun org-copy-subtree (&optional n cut force-store-markers)
5669 "Cut the current subtree into the clipboard.
5670 With prefix arg N, cut this many sequential subtrees.
5671 This is a short-hand for marking the subtree and then copying it.
5672 If CUT is non-nil, actually cut the subtree.
5673 If FORCE-STORE-MARKERS is non-nil, store the relative locations
5674 of some markers in the region, even if CUT is non-nil. This is
5675 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
5676 (interactive "p")
5677 (let (beg end folded (beg0 (point)))
5678 (if (interactive-p)
5679 (org-back-to-heading nil) ; take what looks like a subtree
5680 (org-back-to-heading t)) ; take what is really there
5681 (org-back-over-empty-lines)
5682 (setq beg (point))
5683 (skip-chars-forward " \t\r\n")
5684 (save-match-data
5685 (save-excursion (outline-end-of-heading)
5686 (setq folded (org-invisible-p)))
5687 (condition-case nil
5688 (outline-forward-same-level (1- n))
5689 (error nil))
5690 (org-end-of-subtree t t))
5691 (org-back-over-empty-lines)
5692 (setq end (point))
5693 (goto-char beg0)
5694 (when (> end beg)
5695 (setq org-subtree-clip-folded folded)
5696 (when (or cut force-store-markers)
5697 (org-save-markers-in-region beg end))
5698 (if cut (kill-region beg end) (copy-region-as-kill beg end))
5699 (setq org-subtree-clip (current-kill 0))
5700 (message "%s: Subtree(s) with %d characters"
5701 (if cut "Cut" "Copied")
5702 (length org-subtree-clip)))))
5704 (defun org-paste-subtree (&optional level tree for-yank)
5705 "Paste the clipboard as a subtree, with modification of headline level.
5706 The entire subtree is promoted or demoted in order to match a new headline
5707 level.
5709 If the cursor is at the beginning of a headline, the same level as
5710 that headline is used to paste the tree
5712 If not, the new level is derived from the *visible* headings
5713 before and after the insertion point, and taken to be the inferior headline
5714 level of the two. So if the previous visible heading is level 3 and the
5715 next is level 4 (or vice versa), level 4 will be used for insertion.
5716 This makes sure that the subtree remains an independent subtree and does
5717 not swallow low level entries.
5719 You can also force a different level, either by using a numeric prefix
5720 argument, or by inserting the heading marker by hand. For example, if the
5721 cursor is after \"*****\", then the tree will be shifted to level 5.
5723 If optional TREE is given, use this text instead of the kill ring.
5725 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
5726 move back over whitespace before inserting, and move point to the end of
5727 the inserted text when done."
5728 (interactive "P")
5729 (unless (org-kill-is-subtree-p tree)
5730 (error "%s"
5731 (substitute-command-keys
5732 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
5733 (let* ((visp (not (org-invisible-p)))
5734 (txt (or tree (and kill-ring (current-kill 0))))
5735 (^re (concat "^\\(" outline-regexp "\\)"))
5736 (re (concat "\\(" outline-regexp "\\)"))
5737 (^re_ (concat "\\(\\*+\\)[ \t]*"))
5739 (old-level (if (string-match ^re txt)
5740 (- (match-end 0) (match-beginning 0) 1)
5741 -1))
5742 (force-level (cond (level (prefix-numeric-value level))
5743 ((and (looking-at "[ \t]*$")
5744 (string-match
5745 ^re_ (buffer-substring
5746 (point-at-bol) (point))))
5747 (- (match-end 1) (match-beginning 1)))
5748 ((and (bolp)
5749 (looking-at org-outline-regexp))
5750 (- (match-end 0) (point) 1))
5751 (t nil)))
5752 (previous-level (save-excursion
5753 (condition-case nil
5754 (progn
5755 (outline-previous-visible-heading 1)
5756 (if (looking-at re)
5757 (- (match-end 0) (match-beginning 0) 1)
5759 (error 1))))
5760 (next-level (save-excursion
5761 (condition-case nil
5762 (progn
5763 (or (looking-at outline-regexp)
5764 (outline-next-visible-heading 1))
5765 (if (looking-at re)
5766 (- (match-end 0) (match-beginning 0) 1)
5768 (error 1))))
5769 (new-level (or force-level (max previous-level next-level)))
5770 (shift (if (or (= old-level -1)
5771 (= new-level -1)
5772 (= old-level new-level))
5774 (- new-level old-level)))
5775 (delta (if (> shift 0) -1 1))
5776 (func (if (> shift 0) 'org-demote 'org-promote))
5777 (org-odd-levels-only nil)
5778 beg end newend)
5779 ;; Remove the forced level indicator
5780 (if force-level
5781 (delete-region (point-at-bol) (point)))
5782 ;; Paste
5783 (beginning-of-line 1)
5784 (unless for-yank (org-back-over-empty-lines))
5785 (setq beg (point))
5786 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
5787 (insert-before-markers txt)
5788 (unless (string-match "\n\\'" txt) (insert "\n"))
5789 (setq newend (point))
5790 (org-reinstall-markers-in-region beg)
5791 (setq end (point))
5792 (goto-char beg)
5793 (skip-chars-forward " \t\n\r")
5794 (setq beg (point))
5795 (if (and (org-invisible-p) visp)
5796 (save-excursion (outline-show-heading)))
5797 ;; Shift if necessary
5798 (unless (= shift 0)
5799 (save-restriction
5800 (narrow-to-region beg end)
5801 (while (not (= shift 0))
5802 (org-map-region func (point-min) (point-max))
5803 (setq shift (+ delta shift)))
5804 (goto-char (point-min))
5805 (setq newend (point-max))))
5806 (when (or (interactive-p) for-yank)
5807 (message "Clipboard pasted as level %d subtree" new-level))
5808 (if (and (not for-yank) ; in this case, org-yank will decide about folding
5809 kill-ring
5810 (eq org-subtree-clip (current-kill 0))
5811 org-subtree-clip-folded)
5812 ;; The tree was folded before it was killed/copied
5813 (hide-subtree))
5814 (and for-yank (goto-char newend))))
5816 (defun org-kill-is-subtree-p (&optional txt)
5817 "Check if the current kill is an outline subtree, or a set of trees.
5818 Returns nil if kill does not start with a headline, or if the first
5819 headline level is not the largest headline level in the tree.
5820 So this will actually accept several entries of equal levels as well,
5821 which is OK for `org-paste-subtree'.
5822 If optional TXT is given, check this string instead of the current kill."
5823 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
5824 (start-level (and kill
5825 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
5826 org-outline-regexp "\\)")
5827 kill)
5828 (- (match-end 2) (match-beginning 2) 1)))
5829 (re (concat "^" org-outline-regexp))
5830 (start (1+ (or (match-beginning 2) -1))))
5831 (if (not start-level)
5832 (progn
5833 nil) ;; does not even start with a heading
5834 (catch 'exit
5835 (while (setq start (string-match re kill (1+ start)))
5836 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
5837 (throw 'exit nil)))
5838 t))))
5840 (defvar org-markers-to-move nil
5841 "Markers that should be moved with a cut-and-paste operation.
5842 Those markers are stored together with their positions relative to
5843 the start of the region.")
5845 (defun org-save-markers-in-region (beg end)
5846 "Check markers in region.
5847 If these markers are between BEG and END, record their position relative
5848 to BEG, so that after moving the block of text, we can put the markers back
5849 into place.
5850 This function gets called just before an entry or tree gets cut from the
5851 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
5852 called immediately, to move the markers with the entries."
5853 (setq org-markers-to-move nil)
5854 (when (featurep 'org-clock)
5855 (org-clock-save-markers-for-cut-and-paste beg end))
5856 (when (featurep 'org-agenda)
5857 (org-agenda-save-markers-for-cut-and-paste beg end)))
5859 (defun org-check-and-save-marker (marker beg end)
5860 "Check if MARKER is between BEG and END.
5861 If yes, remember the marker and the distance to BEG."
5862 (when (and (marker-buffer marker)
5863 (equal (marker-buffer marker) (current-buffer)))
5864 (if (and (>= marker beg) (< marker end))
5865 (push (cons marker (- marker beg)) org-markers-to-move))))
5867 (defun org-reinstall-markers-in-region (beg)
5868 "Move all remembered markers to their position relative to BEG."
5869 (mapc (lambda (x)
5870 (move-marker (car x) (+ beg (cdr x))))
5871 org-markers-to-move)
5872 (setq org-markers-to-move nil))
5874 (defun org-narrow-to-subtree ()
5875 "Narrow buffer to the current subtree."
5876 (interactive)
5877 (save-excursion
5878 (save-match-data
5879 (narrow-to-region
5880 (progn (org-back-to-heading) (point))
5881 (progn (org-end-of-subtree t) (point))))))
5883 (defun org-clone-subtree-with-time-shift (n &optional shift)
5884 "Clone the task (subtree) at point N times.
5885 The clones will be inserted as siblings.
5887 In interactive use, the user will be prompted for the number of clones
5888 to be produced, and for a time SHIFT, which may be a repeater as used
5889 in time stamps, for example `+3d'.
5891 When a valid repeater is given and the entry contains any time stamps,
5892 the clones will become a sequence in time, with time stamps in the
5893 subtree shifted for each clone produced. If SHIFT is nil or the
5894 empty string, time stamps will be left alone.
5896 If the original subtree did contain time stamps with a repeater,
5897 the following will happen:
5898 - the repeater will be removed in each clone
5899 - an additional clone will be produced, with the current, unshifted
5900 date(s) in the entry.
5901 - the original entry will be placed *after* all the clones, with
5902 repeater intact.
5903 - the start days in the repeater in the original entry will be shifted
5904 to past the last clone.
5905 I this way you can spell out a number of instances of a repeating task,
5906 and still retain the repeater to cover future instances of the task."
5907 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
5908 (let (beg end template task
5909 shift-n shift-what doshift nmin nmax (n-no-remove -1))
5910 (if (not (and (integerp n) (> n 0)))
5911 (error "Invalid number of replications %s" n))
5912 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
5913 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
5914 shift)))
5915 (error "Invalid shift specification %s" shift))
5916 (when doshift
5917 (setq shift-n (string-to-number (match-string 1 shift))
5918 shift-what (cdr (assoc (match-string 2 shift)
5919 '(("d" . day) ("w" . week)
5920 ("m" . month) ("y" . year))))))
5921 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
5922 (setq nmin 1 nmax n)
5923 (org-back-to-heading t)
5924 (setq beg (point))
5925 (org-end-of-subtree t t)
5926 (setq end (point))
5927 (setq template (buffer-substring beg end))
5928 (when (and doshift
5929 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
5930 (delete-region beg end)
5931 (setq end beg)
5932 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
5933 (goto-char end)
5934 (loop for n from nmin to nmax do
5935 (if (not doshift)
5936 (setq task template)
5937 (with-temp-buffer
5938 (insert template)
5939 (org-mode)
5940 (goto-char (point-min))
5941 (while (re-search-forward org-ts-regexp nil t)
5942 (org-timestamp-change (* n shift-n) shift-what))
5943 (unless (= n n-no-remove)
5944 (goto-char (point-min))
5945 (while (re-search-forward org-ts-regexp nil t)
5946 (save-excursion
5947 (goto-char (match-beginning 0))
5948 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
5949 (delete-region (match-beginning 1) (match-end 1))))))
5950 (setq task (buffer-string))))
5951 (insert task))
5952 (goto-char beg)))
5954 ;;; Outline Sorting
5956 (defun org-sort (with-case)
5957 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
5958 Optional argument WITH-CASE means sort case-sensitively.
5959 With a double prefix argument, also remove duplicate entries."
5960 (interactive "P")
5961 (if (org-at-table-p)
5962 (org-call-with-arg 'org-table-sort-lines with-case)
5963 (org-call-with-arg 'org-sort-entries-or-items with-case)))
5965 (defun org-sort-remove-invisible (s)
5966 (remove-text-properties 0 (length s) org-rm-props s)
5967 (while (string-match org-bracket-link-regexp s)
5968 (setq s (replace-match (if (match-end 2)
5969 (match-string 3 s)
5970 (match-string 1 s)) t t s)))
5973 (defvar org-priority-regexp) ; defined later in the file
5975 (defun org-sort-entries-or-items
5976 (&optional with-case sorting-type getkey-func compare-func property)
5977 "Sort entries on a certain level of an outline tree.
5978 If there is an active region, the entries in the region are sorted.
5979 Else, if the cursor is before the first entry, sort the top-level items.
5980 Else, the children of the entry at point are sorted.
5982 Sorting can be alphabetically, numerically, and by date/time as given by
5983 the first time stamp in the entry. The command prompts for the sorting
5984 type unless it has been given to the function through the SORTING-TYPE
5985 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
5986 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
5987 called with point at the beginning of the record. It must return either
5988 a string or a number that should serve as the sorting key for that record.
5990 Comparing entries ignores case by default. However, with an optional argument
5991 WITH-CASE, the sorting considers case as well."
5992 (interactive "P")
5993 (let ((case-func (if with-case 'identity 'downcase))
5994 start beg end stars re re2
5995 txt what tmp plain-list-p)
5996 ;; Find beginning and end of region to sort
5997 (cond
5998 ((org-region-active-p)
5999 ;; we will sort the region
6000 (setq end (region-end)
6001 what "region")
6002 (goto-char (region-beginning))
6003 (if (not (org-on-heading-p)) (outline-next-heading))
6004 (setq start (point)))
6005 ((org-at-item-p)
6006 ;; we will sort this plain list
6007 (org-beginning-of-item-list) (setq start (point))
6008 (org-end-of-item-list) (setq end (point))
6009 (goto-char start)
6010 (setq plain-list-p t
6011 what "plain list"))
6012 ((or (org-on-heading-p)
6013 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6014 ;; we will sort the children of the current headline
6015 (org-back-to-heading)
6016 (setq start (point)
6017 end (progn (org-end-of-subtree t t)
6018 (org-back-over-empty-lines)
6019 (point))
6020 what "children")
6021 (goto-char start)
6022 (show-subtree)
6023 (outline-next-heading))
6025 ;; we will sort the top-level entries in this file
6026 (goto-char (point-min))
6027 (or (org-on-heading-p) (outline-next-heading))
6028 (setq start (point) end (point-max) what "top-level")
6029 (goto-char start)
6030 (show-all)))
6032 (setq beg (point))
6033 (if (>= beg end) (error "Nothing to sort"))
6035 (unless plain-list-p
6036 (looking-at "\\(\\*+\\)")
6037 (setq stars (match-string 1)
6038 re (concat "^" (regexp-quote stars) " +")
6039 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
6040 txt (buffer-substring beg end))
6041 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
6042 (if (and (not (equal stars "*")) (string-match re2 txt))
6043 (error "Region to sort contains a level above the first entry")))
6045 (unless sorting-type
6046 (message
6047 (if plain-list-p
6048 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
6049 "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:")
6050 what)
6051 (setq sorting-type (read-char-exclusive))
6053 (and (= (downcase sorting-type) ?f)
6054 (setq getkey-func
6055 (org-ido-completing-read "Sort using function: "
6056 obarray 'fboundp t nil nil))
6057 (setq getkey-func (intern getkey-func)))
6059 (and (= (downcase sorting-type) ?r)
6060 (setq property
6061 (org-ido-completing-read "Property: "
6062 (mapcar 'list (org-buffer-property-keys t))
6063 nil t))))
6065 (message "Sorting entries...")
6067 (save-restriction
6068 (narrow-to-region start end)
6070 (let ((dcst (downcase sorting-type))
6071 (now (current-time)))
6072 (sort-subr
6073 (/= dcst sorting-type)
6074 ;; This function moves to the beginning character of the "record" to
6075 ;; be sorted.
6076 (if plain-list-p
6077 (lambda nil
6078 (if (org-at-item-p) t (goto-char (point-max))))
6079 (lambda nil
6080 (if (re-search-forward re nil t)
6081 (goto-char (match-beginning 0))
6082 (goto-char (point-max)))))
6083 ;; This function moves to the last character of the "record" being
6084 ;; sorted.
6085 (if plain-list-p
6086 'org-end-of-item
6087 (lambda nil
6088 (save-match-data
6089 (condition-case nil
6090 (outline-forward-same-level 1)
6091 (error
6092 (goto-char (point-max)))))))
6094 ;; This function returns the value that gets sorted against.
6095 (if plain-list-p
6096 (lambda nil
6097 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
6098 (cond
6099 ((= dcst ?n)
6100 (string-to-number (buffer-substring (match-end 0)
6101 (point-at-eol))))
6102 ((= dcst ?a)
6103 (buffer-substring (match-end 0) (point-at-eol)))
6104 ((= dcst ?t)
6105 (if (re-search-forward org-ts-regexp
6106 (point-at-eol) t)
6107 (org-time-string-to-time (match-string 0))
6108 now))
6109 ((= dcst ?f)
6110 (if getkey-func
6111 (progn
6112 (setq tmp (funcall getkey-func))
6113 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6114 tmp)
6115 (error "Invalid key function `%s'" getkey-func)))
6116 (t (error "Invalid sorting type `%c'" sorting-type)))))
6117 (lambda nil
6118 (cond
6119 ((= dcst ?n)
6120 (if (looking-at org-complex-heading-regexp)
6121 (string-to-number (match-string 4))
6122 nil))
6123 ((= dcst ?a)
6124 (if (looking-at org-complex-heading-regexp)
6125 (funcall case-func (match-string 4))
6126 nil))
6127 ((= dcst ?t)
6128 (if (re-search-forward org-ts-regexp
6129 (save-excursion
6130 (forward-line 2)
6131 (point)) t)
6132 (org-time-string-to-time (match-string 0))
6133 now))
6134 ((= dcst ?p)
6135 (if (re-search-forward org-priority-regexp (point-at-eol) t)
6136 (string-to-char (match-string 2))
6137 org-default-priority))
6138 ((= dcst ?r)
6139 (or (org-entry-get nil property) ""))
6140 ((= dcst ?o)
6141 (if (looking-at org-complex-heading-regexp)
6142 (- 9999 (length (member (match-string 2)
6143 org-todo-keywords-1)))))
6144 ((= dcst ?f)
6145 (if getkey-func
6146 (progn
6147 (setq tmp (funcall getkey-func))
6148 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6149 tmp)
6150 (error "Invalid key function `%s'" getkey-func)))
6151 (t (error "Invalid sorting type `%c'" sorting-type)))))
6153 (cond
6154 ((= dcst ?a) 'string<)
6155 ((= dcst ?t) 'time-less-p)
6156 ((= dcst ?f) compare-func)
6157 (t nil)))))
6158 (message "Sorting entries...done")))
6160 (defun org-do-sort (table what &optional with-case sorting-type)
6161 "Sort TABLE of WHAT according to SORTING-TYPE.
6162 The user will be prompted for the SORTING-TYPE if the call to this
6163 function does not specify it. WHAT is only for the prompt, to indicate
6164 what is being sorted. The sorting key will be extracted from
6165 the car of the elements of the table.
6166 If WITH-CASE is non-nil, the sorting will be case-sensitive."
6167 (unless sorting-type
6168 (message
6169 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
6170 what)
6171 (setq sorting-type (read-char-exclusive)))
6172 (let ((dcst (downcase sorting-type))
6173 extractfun comparefun)
6174 ;; Define the appropriate functions
6175 (cond
6176 ((= dcst ?n)
6177 (setq extractfun 'string-to-number
6178 comparefun (if (= dcst sorting-type) '< '>)))
6179 ((= dcst ?a)
6180 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
6181 (lambda(x) (downcase (org-sort-remove-invisible x))))
6182 comparefun (if (= dcst sorting-type)
6183 'string<
6184 (lambda (a b) (and (not (string< a b))
6185 (not (string= a b)))))))
6186 ((= dcst ?t)
6187 (setq extractfun
6188 (lambda (x)
6189 (if (or (string-match org-ts-regexp x)
6190 (string-match org-ts-regexp-both x))
6191 (time-to-seconds
6192 (org-time-string-to-time (match-string 0 x)))
6194 comparefun (if (= dcst sorting-type) '< '>)))
6195 (t (error "Invalid sorting type `%c'" sorting-type)))
6197 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
6198 table)
6199 (lambda (a b) (funcall comparefun (car a) (car b))))))
6201 ;;; Editing source examples
6203 (defvar org-exit-edit-mode-map (make-sparse-keymap))
6204 (define-key org-exit-edit-mode-map "\C-c'" 'org-edit-src-exit)
6205 (defvar org-edit-src-force-single-line nil)
6206 (defvar org-edit-src-from-org-mode nil)
6207 (defvar org-edit-src-picture nil)
6209 (define-minor-mode org-exit-edit-mode
6210 "Minor mode installing a single key binding, \"C-c '\" to exit special edit.")
6212 (defun org-edit-src-code ()
6213 "Edit the source code example at point.
6214 An indirect buffer is created, and that buffer is then narrowed to the
6215 example at point and switched to the correct language mode. When done,
6216 exit by killing the buffer with \\[org-edit-src-exit]."
6217 (interactive)
6218 (let ((line (org-current-line))
6219 (case-fold-search t)
6220 (msg (substitute-command-keys
6221 "Edit, then exit with C-c ' (C-c and single quote)"))
6222 (info (org-edit-src-find-region-and-lang))
6223 (org-mode-p (eq major-mode 'org-mode))
6224 beg end lang lang-f single lfmt)
6225 (if (not info)
6227 (setq beg (nth 0 info)
6228 end (nth 1 info)
6229 lang (nth 2 info)
6230 single (nth 3 info)
6231 lfmt (nth 4 info)
6232 lang-f (intern (concat lang "-mode")))
6233 (unless (functionp lang-f)
6234 (error "No such language mode: %s" lang-f))
6235 (goto-line line)
6236 (if (get-buffer "*Org Edit Src Example*")
6237 (kill-buffer "*Org Edit Src Example*"))
6238 (switch-to-buffer (make-indirect-buffer (current-buffer)
6239 "*Org Edit Src Example*"))
6240 (narrow-to-region beg end)
6241 (remove-text-properties beg end '(display nil invisible nil
6242 intangible nil))
6243 (let ((org-inhibit-startup t))
6244 (funcall lang-f))
6245 (set (make-local-variable 'org-edit-src-force-single-line) single)
6246 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
6247 (when lfmt
6248 (set (make-local-variable 'org-coderef-label-format) lfmt))
6249 (when org-mode-p
6250 (goto-char (point-min))
6251 (while (re-search-forward "^," nil t)
6252 (replace-match "")))
6253 (goto-line line)
6254 (org-exit-edit-mode)
6255 (org-set-local 'header-line-format msg)
6256 (message "%s" msg)
6257 t)))
6259 (defun org-edit-fixed-width-region ()
6260 "Edit the fixed-width ascii drawing at point.
6261 This must be a region where each line starts with a colon followed by
6262 a space character.
6263 An indirect buffer is created, and that buffer is then narrowed to the
6264 example at point and switched to artist-mode. When done,
6265 exit by killing the buffer with \\[org-edit-src-exit]."
6266 (interactive)
6267 (let ((line (org-current-line))
6268 (case-fold-search t)
6269 (msg (substitute-command-keys
6270 "Edit, then exit with C-c ' (C-c and single quote)"))
6271 (org-mode-p (eq major-mode 'org-mode))
6272 beg end)
6273 (beginning-of-line 1)
6274 (if (looking-at "[ \t]*[^:\n \t]")
6276 (if (looking-at "[ \t]*\\(\n\\|\\'\\)")
6277 (setq beg (point) end beg)
6278 (save-excursion
6279 (if (re-search-backward "^[ \t]*[^:]" nil 'move)
6280 (setq beg (point-at-bol 2))
6281 (setq beg (point))))
6282 (save-excursion
6283 (if (re-search-forward "^[ \t]*[^:]" nil 'move)
6284 (setq end (1- (match-beginning 0)))
6285 (setq end (point))))
6286 (goto-line line))
6287 (if (get-buffer "*Org Edit Picture*")
6288 (kill-buffer "*Org Edit Picture*"))
6289 (switch-to-buffer (make-indirect-buffer (current-buffer)
6290 "*Org Edit Picture*"))
6291 (narrow-to-region beg end)
6292 (remove-text-properties beg end '(display nil invisible nil
6293 intangible nil))
6294 (when (fboundp 'font-lock-unfontify-region)
6295 (font-lock-unfontify-region (point-min) (point-max)))
6296 (cond
6297 ((eq org-edit-fixed-width-region-mode 'artist-mode)
6298 (fundamental-mode)
6299 (artist-mode 1))
6300 (t (funcall org-edit-fixed-width-region-mode)))
6301 (set (make-local-variable 'org-edit-src-force-single-line) nil)
6302 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
6303 (set (make-local-variable 'org-edit-src-picture) t)
6304 (goto-char (point-min))
6305 (while (re-search-forward "^[ \t]*: ?" nil t)
6306 (replace-match ""))
6307 (goto-line line)
6308 (org-exit-edit-mode)
6309 (org-set-local 'header-line-format msg)
6310 (message "%s" msg)
6311 t)))
6314 (defun org-edit-src-find-region-and-lang ()
6315 "Find the region and language for a local edit.
6316 Return a list with beginning and end of the region, a string representing
6317 the language, a switch telling of the content should be in a single line."
6318 (let ((re-list
6319 (append
6320 org-edit-src-region-extra
6322 ("<src\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</src>" lang)
6323 ("<literal\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</literal>" style)
6324 ("<example>[ \t]*\n?" "\n?[ \t]*</example>" "fundamental")
6325 ("<lisp>[ \t]*\n?" "\n?[ \t]*</lisp>" "emacs-lisp")
6326 ("<perl>[ \t]*\n?" "\n?[ \t]*</perl>" "perl")
6327 ("<python>[ \t]*\n?" "\n?[ \t]*</python>" "python")
6328 ("<ruby>[ \t]*\n?" "\n?[ \t]*</ruby>" "ruby")
6329 ("^#\\+begin_src\\( \\([^ \t\n]+\\)\\)?.*\n" "\n#\\+end_src" 2)
6330 ("^#\\+begin_example.*\n" "\n#\\+end_example" "fundamental")
6331 ("^#\\+html:" "\n" "html" single-line)
6332 ("^#\\+begin_html.*\n" "\n#\\+end_html" "html")
6333 ("^#\\+begin_latex.*\n" "\n#\\+end_latex" "latex")
6334 ("^#\\+latex:" "\n" "latex" single-line)
6335 ("^#\\+begin_ascii.*\n" "\n#\\+end_ascii" "fundamental")
6336 ("^#\\+ascii:" "\n" "ascii" single-line)
6338 (pos (point))
6339 re1 re2 single beg end lang lfmt match-re1)
6340 (catch 'exit
6341 (while (setq entry (pop re-list))
6342 (setq re1 (car entry) re2 (nth 1 entry) lang (nth 2 entry)
6343 single (nth 3 entry))
6344 (save-excursion
6345 (if (or (looking-at re1)
6346 (re-search-backward re1 nil t))
6347 (progn
6348 (setq match-re1 (match-string 0))
6349 (setq beg (match-end 0)
6350 lang (org-edit-src-get-lang lang)
6351 lfmt (org-edit-src-get-label-format match-re1))
6352 (if (and (re-search-forward re2 nil t)
6353 (>= (match-end 0) pos))
6354 (throw 'exit (list beg (match-beginning 0)
6355 lang single lfmt))))
6356 (if (or (looking-at re2)
6357 (re-search-forward re2 nil t))
6358 (progn
6359 (setq end (match-beginning 0))
6360 (if (and (re-search-backward re1 nil t)
6361 (<= (match-beginning 0) pos))
6362 (progn
6363 (setq lfmt (org-edit-src-get-label-format
6364 (match-string 0)))
6365 (throw 'exit
6366 (list (match-end 0) end
6367 (org-edit-src-get-lang lang)
6368 single lfmt))))))))))))
6370 (defun org-edit-src-get-lang (lang)
6371 "Extract the src language."
6372 (let ((m (match-string 0)))
6373 (cond
6374 ((stringp lang) lang)
6375 ((integerp lang) (match-string lang))
6376 ((and (eq lang 'lang)
6377 (string-match "\\<lang=\"\\([^ \t\n\"]+\\)\"" m))
6378 (match-string 1 m))
6379 ((and (eq lang 'style)
6380 (string-match "\\<style=\"\\([^ \t\n\"]+\\)\"" m))
6381 (match-string 1 m))
6382 (t "fundamental"))))
6384 (defun org-edit-src-get-label-format (s)
6385 "Extract the label format."
6386 (save-match-data
6387 (if (string-match "-l[ \t]+\\\\?\"\\([^\t\r\n\"]+\\)\\\\?\"" s)
6388 (match-string 1 s))))
6390 (defun org-edit-src-exit ()
6391 "Exit special edit and protect problematic lines."
6392 (interactive)
6393 (unless (buffer-base-buffer (current-buffer))
6394 (error "This is not an indirect buffer, something is wrong..."))
6395 (unless (> (point-min) 1)
6396 (error "This buffer is not narrowed, something is wrong..."))
6397 (goto-char (point-min))
6398 (if (looking-at "[ \t\n]*\n") (replace-match ""))
6399 (if (re-search-forward "\n[ \t\n]*\\'" nil t) (replace-match ""))
6400 (when (org-bound-and-true-p org-edit-src-force-single-line)
6401 (goto-char (point-min))
6402 (while (re-search-forward "\n" nil t)
6403 (replace-match " "))
6404 (goto-char (point-min))
6405 (if (looking-at "\\s-*") (replace-match " "))
6406 (if (re-search-forward "\\s-+\\'" nil t)
6407 (replace-match "")))
6408 (when (org-bound-and-true-p org-edit-src-from-org-mode)
6409 (goto-char (point-min))
6410 (while (re-search-forward (if (org-mode-p) "^\\(.\\)" "^\\([*#]\\)") nil t)
6411 (replace-match ",\\1"))
6412 (when font-lock-mode
6413 (font-lock-unfontify-region (point-min) (point-max)))
6414 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
6415 (when (org-bound-and-true-p org-edit-src-picture)
6416 (untabify (point-min) (point-max))
6417 (goto-char (point-min))
6418 (while (re-search-forward "^" nil t)
6419 (replace-match ": "))
6420 (when font-lock-mode
6421 (font-lock-unfontify-region (point-min) (point-max)))
6422 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
6423 (kill-buffer (current-buffer))
6424 (and (org-mode-p) (org-restart-font-lock)))
6427 ;;; The orgstruct minor mode
6429 ;; Define a minor mode which can be used in other modes in order to
6430 ;; integrate the org-mode structure editing commands.
6432 ;; This is really a hack, because the org-mode structure commands use
6433 ;; keys which normally belong to the major mode. Here is how it
6434 ;; works: The minor mode defines all the keys necessary to operate the
6435 ;; structure commands, but wraps the commands into a function which
6436 ;; tests if the cursor is currently at a headline or a plain list
6437 ;; item. If that is the case, the structure command is used,
6438 ;; temporarily setting many Org-mode variables like regular
6439 ;; expressions for filling etc. However, when any of those keys is
6440 ;; used at a different location, function uses `key-binding' to look
6441 ;; up if the key has an associated command in another currently active
6442 ;; keymap (minor modes, major mode, global), and executes that
6443 ;; command. There might be problems if any of the keys is otherwise
6444 ;; used as a prefix key.
6446 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
6447 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
6448 ;; addresses this by checking explicitly for both bindings.
6450 (defvar orgstruct-mode-map (make-sparse-keymap)
6451 "Keymap for the minor `orgstruct-mode'.")
6453 (defvar org-local-vars nil
6454 "List of local variables, for use by `orgstruct-mode'")
6456 ;;;###autoload
6457 (define-minor-mode orgstruct-mode
6458 "Toggle the minor more `orgstruct-mode'.
6459 This mode is for using Org-mode structure commands in other modes.
6460 The following key behave as if Org-mode was active, if the cursor
6461 is on a headline, or on a plain list item (both in the definition
6462 of Org-mode).
6464 M-up Move entry/item up
6465 M-down Move entry/item down
6466 M-left Promote
6467 M-right Demote
6468 M-S-up Move entry/item up
6469 M-S-down Move entry/item down
6470 M-S-left Promote subtree
6471 M-S-right Demote subtree
6472 M-q Fill paragraph and items like in Org-mode
6473 C-c ^ Sort entries
6474 C-c - Cycle list bullet
6475 TAB Cycle item visibility
6476 M-RET Insert new heading/item
6477 S-M-RET Insert new TODO heading / Checkbox item
6478 C-c C-c Set tags / toggle checkbox"
6479 nil " OrgStruct" nil
6480 (org-load-modules-maybe)
6481 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
6483 ;;;###autoload
6484 (defun turn-on-orgstruct ()
6485 "Unconditionally turn on `orgstruct-mode'."
6486 (orgstruct-mode 1))
6488 (defun orgstruct++-mode (&optional arg)
6489 "Toggle `orgstruct-mode', the enhanced version of it.
6490 In addition to setting orgstruct-mode, this also exports all indentation and
6491 autofilling variables from org-mode into the buffer. It will also
6492 recognize item context in multiline items.
6493 Note that turning off orgstruct-mode will *not* remove the
6494 indentation/paragraph settings. This can only be done by refreshing the
6495 major mode, for example with \[normal-mode]."
6496 (interactive "P")
6497 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
6498 (if (< arg 1)
6499 (orgstruct-mode -1)
6500 (orgstruct-mode 1)
6501 (let (var val)
6502 (mapc
6503 (lambda (x)
6504 (when (string-match
6505 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6506 (symbol-name (car x)))
6507 (setq var (car x) val (nth 1 x))
6508 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
6509 org-local-vars)
6510 (org-set-local 'orgstruct-is-++ t))))
6512 (defvar orgstruct-is-++ nil
6513 "Is orgstruct-mode in ++ version in the current-buffer?")
6514 (make-variable-buffer-local 'orgstruct-is-++)
6516 ;;;###autoload
6517 (defun turn-on-orgstruct++ ()
6518 "Unconditionally turn on `orgstruct++-mode'."
6519 (orgstruct++-mode 1))
6521 (defun orgstruct-error ()
6522 "Error when there is no default binding for a structure key."
6523 (interactive)
6524 (error "This key has no function outside structure elements"))
6526 (defun orgstruct-setup ()
6527 "Setup orgstruct keymaps."
6528 (let ((nfunc 0)
6529 (bindings
6530 (list
6531 '([(meta up)] org-metaup)
6532 '([(meta down)] org-metadown)
6533 '([(meta left)] org-metaleft)
6534 '([(meta right)] org-metaright)
6535 '([(meta shift up)] org-shiftmetaup)
6536 '([(meta shift down)] org-shiftmetadown)
6537 '([(meta shift left)] org-shiftmetaleft)
6538 '([(meta shift right)] org-shiftmetaright)
6539 '([(shift up)] org-shiftup)
6540 '([(shift down)] org-shiftdown)
6541 '([(shift left)] org-shiftleft)
6542 '([(shift right)] org-shiftright)
6543 '("\C-c\C-c" org-ctrl-c-ctrl-c)
6544 '("\M-q" fill-paragraph)
6545 '("\C-c^" org-sort)
6546 '("\C-c-" org-cycle-list-bullet)))
6547 elt key fun cmd)
6548 (while (setq elt (pop bindings))
6549 (setq nfunc (1+ nfunc))
6550 (setq key (org-key (car elt))
6551 fun (nth 1 elt)
6552 cmd (orgstruct-make-binding fun nfunc key))
6553 (org-defkey orgstruct-mode-map key cmd))
6555 ;; Special treatment needed for TAB and RET
6556 (org-defkey orgstruct-mode-map [(tab)]
6557 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
6558 (org-defkey orgstruct-mode-map "\C-i"
6559 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
6561 (org-defkey orgstruct-mode-map "\M-\C-m"
6562 (orgstruct-make-binding 'org-insert-heading 105
6563 "\M-\C-m" [(meta return)]))
6564 (org-defkey orgstruct-mode-map [(meta return)]
6565 (orgstruct-make-binding 'org-insert-heading 106
6566 [(meta return)] "\M-\C-m"))
6568 (org-defkey orgstruct-mode-map [(shift meta return)]
6569 (orgstruct-make-binding 'org-insert-todo-heading 107
6570 [(meta return)] "\M-\C-m"))
6572 (unless org-local-vars
6573 (setq org-local-vars (org-get-local-variables)))
6577 (defun orgstruct-make-binding (fun n &rest keys)
6578 "Create a function for binding in the structure minor mode.
6579 FUN is the command to call inside a table. N is used to create a unique
6580 command name. KEYS are keys that should be checked in for a command
6581 to execute outside of tables."
6582 (eval
6583 (list 'defun
6584 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6585 '(arg)
6586 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6587 "Outside of structure, run the binding of `"
6588 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6589 "'.")
6590 '(interactive "p")
6591 (list 'if
6592 `(org-context-p 'headline 'item
6593 (and orgstruct-is-++
6594 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
6595 'item-body))
6596 (list 'org-run-like-in-org-mode (list 'quote fun))
6597 (list 'let '(orgstruct-mode)
6598 (list 'call-interactively
6599 (append '(or)
6600 (mapcar (lambda (k)
6601 (list 'key-binding k))
6602 keys)
6603 '('orgstruct-error))))))))
6605 (defun org-context-p (&rest contexts)
6606 "Check if local context is any of CONTEXTS.
6607 Possible values in the list of contexts are `table', `headline', and `item'."
6608 (let ((pos (point)))
6609 (goto-char (point-at-bol))
6610 (prog1 (or (and (memq 'table contexts)
6611 (looking-at "[ \t]*|"))
6612 (and (memq 'headline contexts)
6613 ;;????????? (looking-at "\\*+"))
6614 (looking-at outline-regexp))
6615 (and (memq 'item contexts)
6616 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
6617 (and (memq 'item-body contexts)
6618 (org-in-item-p)))
6619 (goto-char pos))))
6621 (defun org-get-local-variables ()
6622 "Return a list of all local variables in an org-mode buffer."
6623 (let (varlist)
6624 (with-current-buffer (get-buffer-create "*Org tmp*")
6625 (erase-buffer)
6626 (org-mode)
6627 (setq varlist (buffer-local-variables)))
6628 (kill-buffer "*Org tmp*")
6629 (delq nil
6630 (mapcar
6631 (lambda (x)
6632 (setq x
6633 (if (symbolp x)
6634 (list x)
6635 (list (car x) (list 'quote (cdr x)))))
6636 (if (string-match
6637 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6638 (symbol-name (car x)))
6639 x nil))
6640 varlist))))
6642 ;;;###autoload
6643 (defun org-run-like-in-org-mode (cmd)
6644 "Run a command, pretending that the current buffer is in Org-mode.
6645 This will temporarily bind local variables that are typically bound in
6646 Org-mode to the values they have in Org-mode, and then interactively
6647 call CMD."
6648 (org-load-modules-maybe)
6649 (unless org-local-vars
6650 (setq org-local-vars (org-get-local-variables)))
6651 (eval (list 'let org-local-vars
6652 (list 'call-interactively (list 'quote cmd)))))
6654 ;;;; Archiving
6656 (defun org-get-category (&optional pos)
6657 "Get the category applying to position POS."
6658 (get-text-property (or pos (point)) 'org-category))
6660 (defun org-refresh-category-properties ()
6661 "Refresh category text properties in the buffer."
6662 (let ((def-cat (cond
6663 ((null org-category)
6664 (if buffer-file-name
6665 (file-name-sans-extension
6666 (file-name-nondirectory buffer-file-name))
6667 "???"))
6668 ((symbolp org-category) (symbol-name org-category))
6669 (t org-category)))
6670 beg end cat pos optionp)
6671 (org-unmodified
6672 (save-excursion
6673 (save-restriction
6674 (widen)
6675 (goto-char (point-min))
6676 (put-text-property (point) (point-max) 'org-category def-cat)
6677 (while (re-search-forward
6678 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6679 (setq pos (match-end 0)
6680 optionp (equal (char-after (match-beginning 0)) ?#)
6681 cat (org-trim (match-string 2)))
6682 (if optionp
6683 (setq beg (point-at-bol) end (point-max))
6684 (org-back-to-heading t)
6685 (setq beg (point) end (org-end-of-subtree t t)))
6686 (put-text-property beg end 'org-category cat)
6687 (goto-char pos)))))))
6690 ;;;; Link Stuff
6692 ;;; Link abbreviations
6694 (defun org-link-expand-abbrev (link)
6695 "Apply replacements as defined in `org-link-abbrev-alist."
6696 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6697 (let* ((key (match-string 1 link))
6698 (as (or (assoc key org-link-abbrev-alist-local)
6699 (assoc key org-link-abbrev-alist)))
6700 (tag (and (match-end 2) (match-string 3 link)))
6701 rpl)
6702 (if (not as)
6703 link
6704 (setq rpl (cdr as))
6705 (cond
6706 ((symbolp rpl) (funcall rpl tag))
6707 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
6708 ((string-match "%h" rpl)
6709 (replace-match (url-hexify-string (or tag "")) t t rpl))
6710 (t (concat rpl tag)))))
6711 link))
6713 ;;; Storing and inserting links
6715 (defvar org-insert-link-history nil
6716 "Minibuffer history for links inserted with `org-insert-link'.")
6718 (defvar org-stored-links nil
6719 "Contains the links stored with `org-store-link'.")
6721 (defvar org-store-link-plist nil
6722 "Plist with info about the most recently link created with `org-store-link'.")
6724 (defvar org-link-protocols nil
6725 "Link protocols added to Org-mode using `org-add-link-type'.")
6727 (defvar org-store-link-functions nil
6728 "List of functions that are called to create and store a link.
6729 Each function will be called in turn until one returns a non-nil
6730 value. Each function should check if it is responsible for creating
6731 this link (for example by looking at the major mode).
6732 If not, it must exit and return nil.
6733 If yes, it should return a non-nil value after a calling
6734 `org-store-link-props' with a list of properties and values.
6735 Special properties are:
6737 :type The link prefix. like \"http\". This must be given.
6738 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6739 This is obligatory as well.
6740 :description Optional default description for the second pair
6741 of brackets in an Org-mode link. The user can still change
6742 this when inserting this link into an Org-mode buffer.
6744 In addition to these, any additional properties can be specified
6745 and then used in remember templates.")
6747 (defun org-add-link-type (type &optional follow export)
6748 "Add TYPE to the list of `org-link-types'.
6749 Re-compute all regular expressions depending on `org-link-types'
6751 FOLLOW and EXPORT are two functions.
6753 FOLLOW should take the link path as the single argument and do whatever
6754 is necessary to follow the link, for example find a file or display
6755 a mail message.
6757 EXPORT should format the link path for export to one of the export formats.
6758 It should be a function accepting three arguments:
6760 path the path of the link, the text after the prefix (like \"http:\")
6761 desc the description of the link, if any, nil if there was no description
6762 format the export format, a symbol like `html' or `latex'.
6764 The function may use the FORMAT information to return different values
6765 depending on the format. The return value will be put literally into
6766 the exported file.
6767 Org-mode has a built-in default for exporting links. If you are happy with
6768 this default, there is no need to define an export function for the link
6769 type. For a simple example of an export function, see `org-bbdb.el'."
6770 (add-to-list 'org-link-types type t)
6771 (org-make-link-regexps)
6772 (if (assoc type org-link-protocols)
6773 (setcdr (assoc type org-link-protocols) (list follow export))
6774 (push (list type follow export) org-link-protocols)))
6776 ;;;###autoload
6777 (defun org-store-link (arg)
6778 "\\<org-mode-map>Store an org-link to the current location.
6779 This link is added to `org-stored-links' and can later be inserted
6780 into an org-buffer with \\[org-insert-link].
6782 For some link types, a prefix arg is interpreted:
6783 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
6784 For file links, arg negates `org-context-in-file-links'."
6785 (interactive "P")
6786 (org-load-modules-maybe)
6787 (setq org-store-link-plist nil) ; reset
6788 (let (link cpltxt desc description search txt)
6789 (cond
6791 ((run-hook-with-args-until-success 'org-store-link-functions)
6792 (setq link (plist-get org-store-link-plist :link)
6793 desc (or (plist-get org-store-link-plist :description) link)))
6795 ((equal (buffer-name) "*Org Edit Src Example*")
6796 (let (label gc)
6797 (while (or (not label)
6798 (save-excursion
6799 (save-restriction
6800 (widen)
6801 (goto-char (point-min))
6802 (re-search-forward
6803 (regexp-quote (format org-coderef-label-format label))
6804 nil t))))
6805 (when label (message "Label exists already") (sit-for 2))
6806 (setq label (read-string "Code line label: " label)))
6807 (end-of-line 1)
6808 (setq link (format org-coderef-label-format label))
6809 (setq gc (- 79 (length link)))
6810 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
6811 (insert link)
6812 (setq link (concat "(" label ")") desc nil)))
6814 ((eq major-mode 'calendar-mode)
6815 (let ((cd (calendar-cursor-to-date)))
6816 (setq link
6817 (format-time-string
6818 (car org-time-stamp-formats)
6819 (apply 'encode-time
6820 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6821 nil nil nil))))
6822 (org-store-link-props :type "calendar" :date cd)))
6824 ((eq major-mode 'w3-mode)
6825 (setq cpltxt (if (and (buffer-name)
6826 (not (string-match "Untitled" (buffer-name))))
6827 (buffer-name)
6828 (url-view-url t))
6829 link (org-make-link (url-view-url t)))
6830 (org-store-link-props :type "w3" :url (url-view-url t)))
6832 ((eq major-mode 'w3m-mode)
6833 (setq cpltxt (or w3m-current-title w3m-current-url)
6834 link (org-make-link w3m-current-url))
6835 (org-store-link-props :type "w3m" :url (url-view-url t)))
6837 ((setq search (run-hook-with-args-until-success
6838 'org-create-file-search-functions))
6839 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6840 "::" search))
6841 (setq cpltxt (or description link)))
6843 ((eq major-mode 'image-mode)
6844 (setq cpltxt (concat "file:"
6845 (abbreviate-file-name buffer-file-name))
6846 link (org-make-link cpltxt))
6847 (org-store-link-props :type "image" :file buffer-file-name))
6849 ((eq major-mode 'dired-mode)
6850 ;; link to the file in the current line
6851 (setq cpltxt (concat "file:"
6852 (abbreviate-file-name
6853 (expand-file-name
6854 (dired-get-filename nil t))))
6855 link (org-make-link cpltxt)))
6857 ((and buffer-file-name (org-mode-p))
6858 (cond
6859 ((org-in-regexp "<<\\(.*?\\)>>")
6860 (setq cpltxt
6861 (concat "file:"
6862 (abbreviate-file-name buffer-file-name)
6863 "::" (match-string 1))
6864 link (org-make-link cpltxt)))
6865 ((and (featurep 'org-id)
6866 (or (eq org-link-to-org-use-id t)
6867 (and (eq org-link-to-org-use-id 'create-if-interactive)
6868 (interactive-p))
6869 (and org-link-to-org-use-id
6870 (condition-case nil
6871 (org-entry-get nil "ID")
6872 (error nil)))))
6873 ;; We can make a link using the ID.
6874 (setq link (condition-case nil
6875 (prog1 (org-id-store-link)
6876 (setq desc (plist-get org-store-link-plist
6877 :description)))
6878 (error
6879 ;; probably before first headline, link to file only
6880 (concat "file:"
6881 (abbreviate-file-name buffer-file-name))))))
6883 ;; Just link to current headline
6884 (setq cpltxt (concat "file:"
6885 (abbreviate-file-name buffer-file-name)))
6886 ;; Add a context search string
6887 (when (org-xor org-context-in-file-links arg)
6888 (setq txt (cond
6889 ((org-on-heading-p) nil)
6890 ((org-region-active-p)
6891 (buffer-substring (region-beginning) (region-end)))
6892 (t nil)))
6893 (when (or (null txt) (string-match "\\S-" txt))
6894 (setq cpltxt
6895 (concat cpltxt "::"
6896 (condition-case nil
6897 (org-make-org-heading-search-string txt)
6898 (error "")))
6899 desc "NONE")))
6900 (if (string-match "::\\'" cpltxt)
6901 (setq cpltxt (substring cpltxt 0 -2)))
6902 (setq link (org-make-link cpltxt)))))
6904 ((buffer-file-name (buffer-base-buffer))
6905 ;; Just link to this file here.
6906 (setq cpltxt (concat "file:"
6907 (abbreviate-file-name
6908 (buffer-file-name (buffer-base-buffer)))))
6909 ;; Add a context string
6910 (when (org-xor org-context-in-file-links arg)
6911 (setq txt (if (org-region-active-p)
6912 (buffer-substring (region-beginning) (region-end))
6913 (buffer-substring (point-at-bol) (point-at-eol))))
6914 ;; Only use search option if there is some text.
6915 (when (string-match "\\S-" txt)
6916 (setq cpltxt
6917 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6918 desc "NONE")))
6919 (setq link (org-make-link cpltxt)))
6921 ((interactive-p)
6922 (error "Cannot link to a buffer which is not visiting a file"))
6924 (t (setq link nil)))
6926 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6927 (setq link (or link cpltxt)
6928 desc (or desc cpltxt))
6929 (if (equal desc "NONE") (setq desc nil))
6931 (if (and (interactive-p) link)
6932 (progn
6933 (setq org-stored-links
6934 (cons (list link desc) org-stored-links))
6935 (message "Stored: %s" (or desc link)))
6936 (and link (org-make-link-string link desc)))))
6938 (defun org-store-link-props (&rest plist)
6939 "Store link properties, extract names and addresses."
6940 (let (x adr)
6941 (when (setq x (plist-get plist :from))
6942 (setq adr (mail-extract-address-components x))
6943 (setq plist (plist-put plist :fromname (car adr)))
6944 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
6945 (when (setq x (plist-get plist :to))
6946 (setq adr (mail-extract-address-components x))
6947 (setq plist (plist-put plist :toname (car adr)))
6948 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
6949 (let ((from (plist-get plist :from))
6950 (to (plist-get plist :to)))
6951 (when (and from to org-from-is-user-regexp)
6952 (setq plist
6953 (plist-put plist :fromto
6954 (if (string-match org-from-is-user-regexp from)
6955 (concat "to %t")
6956 (concat "from %f"))))))
6957 (setq org-store-link-plist plist))
6959 (defun org-add-link-props (&rest plist)
6960 "Add these properties to the link property list."
6961 (let (key value)
6962 (while plist
6963 (setq key (pop plist) value (pop plist))
6964 (setq org-store-link-plist
6965 (plist-put org-store-link-plist key value)))))
6967 (defun org-email-link-description (&optional fmt)
6968 "Return the description part of an email link.
6969 This takes information from `org-store-link-plist' and formats it
6970 according to FMT (default from `org-email-link-description-format')."
6971 (setq fmt (or fmt org-email-link-description-format))
6972 (let* ((p org-store-link-plist)
6973 (to (plist-get p :toaddress))
6974 (from (plist-get p :fromaddress))
6975 (table
6976 (list
6977 (cons "%c" (plist-get p :fromto))
6978 (cons "%F" (plist-get p :from))
6979 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
6980 (cons "%T" (plist-get p :to))
6981 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
6982 (cons "%s" (plist-get p :subject))
6983 (cons "%m" (plist-get p :message-id)))))
6984 (when (string-match "%c" fmt)
6985 ;; Check if the user wrote this message
6986 (if (and org-from-is-user-regexp from to
6987 (save-match-data (string-match org-from-is-user-regexp from)))
6988 (setq fmt (replace-match "to %t" t t fmt))
6989 (setq fmt (replace-match "from %f" t t fmt))))
6990 (org-replace-escapes fmt table)))
6992 (defun org-make-org-heading-search-string (&optional string heading)
6993 "Make search string for STRING or current headline."
6994 (interactive)
6995 (let ((s (or string (org-get-heading))))
6996 (unless (and string (not heading))
6997 ;; We are using a headline, clean up garbage in there.
6998 (if (string-match org-todo-regexp s)
6999 (setq s (replace-match "" t t s)))
7000 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
7001 (setq s (replace-match "" t t s)))
7002 (setq s (org-trim s))
7003 (if (string-match (concat "^\\(" org-quote-string "\\|"
7004 org-comment-string "\\)") s)
7005 (setq s (replace-match "" t t s)))
7006 (while (string-match org-ts-regexp s)
7007 (setq s (replace-match "" t t s))))
7008 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
7009 (setq s (replace-match " " t t s)))
7010 (or string (setq s (concat "*" s))) ; Add * for headlines
7011 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
7013 (defun org-make-link (&rest strings)
7014 "Concatenate STRINGS."
7015 (apply 'concat strings))
7017 (defun org-make-link-string (link &optional description)
7018 "Make a link with brackets, consisting of LINK and DESCRIPTION."
7019 (unless (string-match "\\S-" link)
7020 (error "Empty link"))
7021 (when (stringp description)
7022 ;; Remove brackets from the description, they are fatal.
7023 (while (string-match "\\[" description)
7024 (setq description (replace-match "{" t t description)))
7025 (while (string-match "\\]" description)
7026 (setq description (replace-match "}" t t description))))
7027 (when (equal (org-link-escape link) description)
7028 ;; No description needed, it is identical
7029 (setq description nil))
7030 (when (and (not description)
7031 (not (equal link (org-link-escape link))))
7032 (setq description (org-extract-attributes link)))
7033 (concat "[[" (org-link-escape link) "]"
7034 (if description (concat "[" description "]") "")
7035 "]"))
7037 (defconst org-link-escape-chars
7038 '((?\ . "%20")
7039 (?\[ . "%5B")
7040 (?\] . "%5D")
7041 (?\340 . "%E0") ; `a
7042 (?\342 . "%E2") ; ^a
7043 (?\347 . "%E7") ; ,c
7044 (?\350 . "%E8") ; `e
7045 (?\351 . "%E9") ; 'e
7046 (?\352 . "%EA") ; ^e
7047 (?\356 . "%EE") ; ^i
7048 (?\364 . "%F4") ; ^o
7049 (?\371 . "%F9") ; `u
7050 (?\373 . "%FB") ; ^u
7051 (?\; . "%3B")
7052 (?? . "%3F")
7053 (?= . "%3D")
7054 (?+ . "%2B")
7056 "Association list of escapes for some characters problematic in links.
7057 This is the list that is used for internal purposes.")
7059 (defconst org-link-escape-chars-browser
7060 '((?\ . "%20")) ; 32 for the SPC char
7061 "Association list of escapes for some characters problematic in links.
7062 This is the list that is used before handing over to the browser.")
7064 (defun org-link-escape (text &optional table)
7065 "Escape characters in TEXT that are problematic for links."
7066 (setq table (or table org-link-escape-chars))
7067 (when text
7068 (let ((re (mapconcat (lambda (x) (regexp-quote
7069 (char-to-string (car x))))
7070 table "\\|")))
7071 (while (string-match re text)
7072 (setq text
7073 (replace-match
7074 (cdr (assoc (string-to-char (match-string 0 text))
7075 table))
7076 t t text)))
7077 text)))
7079 (defun org-link-unescape (text &optional table)
7080 "Reverse the action of `org-link-escape'."
7081 (setq table (or table org-link-escape-chars))
7082 (when text
7083 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
7084 table "\\|")))
7085 (while (string-match re text)
7086 (setq text
7087 (replace-match
7088 (char-to-string (car (rassoc (match-string 0 text) table)))
7089 t t text)))
7090 text)))
7092 (defun org-xor (a b)
7093 "Exclusive or."
7094 (if a (not b) b))
7096 (defun org-fixup-message-id-for-http (s)
7097 "Replace special characters in a message id, so it can be used in an http query."
7098 (while (string-match "<" s)
7099 (setq s (replace-match "%3C" t t s)))
7100 (while (string-match ">" s)
7101 (setq s (replace-match "%3E" t t s)))
7102 (while (string-match "@" s)
7103 (setq s (replace-match "%40" t t s)))
7106 ;;;###autoload
7107 (defun org-insert-link-global ()
7108 "Insert a link like Org-mode does.
7109 This command can be called in any mode to insert a link in Org-mode syntax."
7110 (interactive)
7111 (org-load-modules-maybe)
7112 (org-run-like-in-org-mode 'org-insert-link))
7114 (defun org-insert-link (&optional complete-file link-location)
7115 "Insert a link. At the prompt, enter the link.
7117 Completion can be used to insert any of the link protocol prefixes like
7118 http or ftp in use.
7120 The history can be used to select a link previously stored with
7121 `org-store-link'. When the empty string is entered (i.e. if you just
7122 press RET at the prompt), the link defaults to the most recently
7123 stored link. As SPC triggers completion in the minibuffer, you need to
7124 use M-SPC or C-q SPC to force the insertion of a space character.
7126 You will also be prompted for a description, and if one is given, it will
7127 be displayed in the buffer instead of the link.
7129 If there is already a link at point, this command will allow you to edit link
7130 and description parts.
7132 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
7133 be selected using completion. The path to the file will be relative to the
7134 current directory if the file is in the current directory or a subdirectory.
7135 Otherwise, the link will be the absolute path as completed in the minibuffer
7136 \(i.e. normally ~/path/to/file). You can configure this behavior using the
7137 option `org-link-file-path-type'.
7139 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
7140 the current directory or below.
7142 With three \\[universal-argument] prefixes, negate the meaning of
7143 `org-keep-stored-link-after-insertion'.
7145 If `org-make-link-description-function' is non-nil, this function will be
7146 called with the link target, and the result will be the default
7147 link description.
7149 If the LINK-LOCATION parameter is non-nil, this value will be
7150 used as the link location instead of reading one interactively."
7151 (interactive "P")
7152 (let* ((wcf (current-window-configuration))
7153 (region (if (org-region-active-p)
7154 (buffer-substring (region-beginning) (region-end))))
7155 (remove (and region (list (region-beginning) (region-end))))
7156 (desc region)
7157 tmphist ; byte-compile incorrectly complains about this
7158 (link link-location)
7159 entry file)
7160 (cond
7161 (link-location) ; specified by arg, just use it.
7162 ((org-in-regexp org-bracket-link-regexp 1)
7163 ;; We do have a link at point, and we are going to edit it.
7164 (setq remove (list (match-beginning 0) (match-end 0)))
7165 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
7166 (setq link (read-string "Link: "
7167 (org-link-unescape
7168 (org-match-string-no-properties 1)))))
7169 ((or (org-in-regexp org-angle-link-re)
7170 (org-in-regexp org-plain-link-re))
7171 ;; Convert to bracket link
7172 (setq remove (list (match-beginning 0) (match-end 0))
7173 link (read-string "Link: "
7174 (org-remove-angle-brackets (match-string 0)))))
7175 ((member complete-file '((4) (16)))
7176 ;; Completing read for file names.
7177 (setq file (read-file-name "File: "))
7178 (let ((pwd (file-name-as-directory (expand-file-name ".")))
7179 (pwd1 (file-name-as-directory (abbreviate-file-name
7180 (expand-file-name ".")))))
7181 (cond
7182 ((equal complete-file '(16))
7183 (setq link (org-make-link
7184 "file:"
7185 (abbreviate-file-name (expand-file-name file)))))
7186 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
7187 (setq link (org-make-link "file:" (match-string 1 file))))
7188 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
7189 (expand-file-name file))
7190 (setq link (org-make-link
7191 "file:" (match-string 1 (expand-file-name file)))))
7192 (t (setq link (org-make-link "file:" file))))))
7194 ;; Read link, with completion for stored links.
7195 (with-output-to-temp-buffer "*Org Links*"
7196 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
7197 (when org-stored-links
7198 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
7199 (princ (mapconcat
7200 (lambda (x)
7201 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
7202 (reverse org-stored-links) "\n"))))
7203 (let ((cw (selected-window)))
7204 (select-window (get-buffer-window "*Org Links*"))
7205 (setq truncate-lines t)
7206 (org-fit-window-to-buffer)
7207 (select-window cw))
7208 ;; Fake a link history, containing the stored links.
7209 (setq tmphist (append (mapcar 'car org-stored-links)
7210 org-insert-link-history))
7211 (unwind-protect
7212 (setq link
7213 (let ((org-completion-use-ido nil))
7214 (org-completing-read
7215 "Link: "
7216 (append
7217 (mapcar (lambda (x) (list (concat (car x) ":")))
7218 (append org-link-abbrev-alist-local org-link-abbrev-alist))
7219 (mapcar (lambda (x) (list (concat x ":")))
7220 org-link-types))
7221 nil nil nil
7222 'tmphist
7223 (or (car (car org-stored-links))))))
7224 (set-window-configuration wcf)
7225 (kill-buffer "*Org Links*"))
7226 (setq entry (assoc link org-stored-links))
7227 (or entry (push link org-insert-link-history))
7228 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
7229 (not org-keep-stored-link-after-insertion))
7230 (setq org-stored-links (delq (assoc link org-stored-links)
7231 org-stored-links)))
7232 (setq desc (or desc (nth 1 entry)))))
7234 (if (string-match org-plain-link-re link)
7235 ;; URL-like link, normalize the use of angular brackets.
7236 (setq link (org-make-link (org-remove-angle-brackets link))))
7238 ;; Check if we are linking to the current file with a search option
7239 ;; If yes, simplify the link by using only the search option.
7240 (when (and buffer-file-name
7241 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
7242 (let* ((path (match-string 1 link))
7243 (case-fold-search nil)
7244 (search (match-string 2 link)))
7245 (save-match-data
7246 (if (equal (file-truename buffer-file-name) (file-truename path))
7247 ;; We are linking to this same file, with a search option
7248 (setq link search)))))
7250 ;; Check if we can/should use a relative path. If yes, simplify the link
7251 (when (string-match "^file:\\(.*\\)" link)
7252 (let* ((path (match-string 1 link))
7253 (origpath path)
7254 (case-fold-search nil))
7255 (cond
7256 ((or (eq org-link-file-path-type 'absolute)
7257 (equal complete-file '(16)))
7258 (setq path (abbreviate-file-name (expand-file-name path))))
7259 ((eq org-link-file-path-type 'noabbrev)
7260 (setq path (expand-file-name path)))
7261 ((eq org-link-file-path-type 'relative)
7262 (setq path (file-relative-name path)))
7264 (save-match-data
7265 (if (string-match (concat "^" (regexp-quote
7266 (file-name-as-directory
7267 (expand-file-name "."))))
7268 (expand-file-name path))
7269 ;; We are linking a file with relative path name.
7270 (setq path (substring (expand-file-name path)
7271 (match-end 0)))
7272 (setq path (abbreviate-file-name (expand-file-name path)))))))
7273 (setq link (concat "file:" path))
7274 (if (equal desc origpath)
7275 (setq desc path))))
7277 (if org-make-link-description-function
7278 (setq desc (funcall org-make-link-description-function link desc)))
7280 (setq desc (read-string "Description: " desc))
7281 (unless (string-match "\\S-" desc) (setq desc nil))
7282 (if remove (apply 'delete-region remove))
7283 (insert (org-make-link-string link desc))))
7285 (defun org-completing-read (&rest args)
7286 "Completing-read with SPACE being a normal character."
7287 (let ((minibuffer-local-completion-map
7288 (copy-keymap minibuffer-local-completion-map)))
7289 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
7290 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
7291 (apply 'org-ido-completing-read args)))
7293 (defun org-completing-read-no-ido (&rest args)
7294 (let (org-completion-use-ido)
7295 (apply 'org-completing-read args)))
7297 (defun org-ido-completing-read (&rest args)
7298 "Completing-read using `ido-mode' speedups if available"
7299 (if (and org-completion-use-ido
7300 (fboundp 'ido-completing-read)
7301 (boundp 'ido-mode) ido-mode
7302 (listp (second args)))
7303 (let ((ido-enter-matching-directory nil))
7304 (apply 'ido-completing-read (concat (car args))
7305 (mapcar (lambda (x) (car x)) (nth 1 args))
7306 (cddr args)))
7307 (apply 'completing-read args)))
7309 (defun org-extract-attributes (s)
7310 "Extract the attributes cookie from a string and set as text property."
7311 (let (a attr (start 0) key value)
7312 (save-match-data
7313 (when (string-match "{{\\([^}]+\\)}}$" s)
7314 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
7315 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
7316 (setq key (match-string 1 a) value (match-string 2 a)
7317 start (match-end 0)
7318 attr (plist-put attr (intern key) value))))
7319 (org-add-props s nil 'org-attr attr))
7322 (defun org-extract-attributes-from-string (tag)
7323 (let (key value attr)
7324 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
7325 (setq key (match-string 1 tag) value (match-string 2 tag)
7326 tag (replace-match "" t t tag)
7327 attr (plist-put attr (intern key) value)))
7328 (cons tag attr)))
7330 (defun org-attributes-to-string (plist)
7331 "Format a property list into an HTML attribute list."
7332 (let ((s "") key value)
7333 (while plist
7334 (setq key (pop plist) value (pop plist))
7335 (and value
7336 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
7339 ;;; Opening/following a link
7341 (defvar org-link-search-failed nil)
7343 (defun org-next-link ()
7344 "Move forward to the next link.
7345 If the link is in hidden text, expose it."
7346 (interactive)
7347 (when (and org-link-search-failed (eq this-command last-command))
7348 (goto-char (point-min))
7349 (message "Link search wrapped back to beginning of buffer"))
7350 (setq org-link-search-failed nil)
7351 (let* ((pos (point))
7352 (ct (org-context))
7353 (a (assoc :link ct)))
7354 (if a (goto-char (nth 2 a)))
7355 (if (re-search-forward org-any-link-re nil t)
7356 (progn
7357 (goto-char (match-beginning 0))
7358 (if (org-invisible-p) (org-show-context)))
7359 (goto-char pos)
7360 (setq org-link-search-failed t)
7361 (error "No further link found"))))
7363 (defun org-previous-link ()
7364 "Move backward to the previous link.
7365 If the link is in hidden text, expose it."
7366 (interactive)
7367 (when (and org-link-search-failed (eq this-command last-command))
7368 (goto-char (point-max))
7369 (message "Link search wrapped back to end of buffer"))
7370 (setq org-link-search-failed nil)
7371 (let* ((pos (point))
7372 (ct (org-context))
7373 (a (assoc :link ct)))
7374 (if a (goto-char (nth 1 a)))
7375 (if (re-search-backward org-any-link-re nil t)
7376 (progn
7377 (goto-char (match-beginning 0))
7378 (if (org-invisible-p) (org-show-context)))
7379 (goto-char pos)
7380 (setq org-link-search-failed t)
7381 (error "No further link found"))))
7383 (defun org-translate-link (s)
7384 "Translate a link string if a translation function has been defined."
7385 (if (and org-link-translation-function
7386 (fboundp org-link-translation-function)
7387 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
7388 (progn
7389 (setq s (funcall org-link-translation-function
7390 (match-string 1) (match-string 2)))
7391 (concat (car s) ":" (cdr s)))
7394 (defun org-translate-link-from-planner (type path)
7395 "Translate a link from Emacs Planner syntax so that Org can follow it.
7396 This is still an experimental function, your mileage may vary."
7397 (cond
7398 ((member type '("http" "https" "news" "ftp"))
7399 ;; standard Internet links are the same.
7400 nil)
7401 ((and (equal type "irc") (string-match "^//" path))
7402 ;; Planner has two / at the beginning of an irc link, we have 1.
7403 ;; We should have zero, actually....
7404 (setq path (substring path 1)))
7405 ((and (equal type "lisp") (string-match "^/" path))
7406 ;; Planner has a slash, we do not.
7407 (setq type "elisp" path (substring path 1)))
7408 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
7409 ;; A typical message link. Planner has the id after the fina slash,
7410 ;; we separate it with a hash mark
7411 (setq path (concat (match-string 1 path) "#"
7412 (org-remove-angle-brackets (match-string 2 path)))))
7414 (cons type path))
7416 (defun org-find-file-at-mouse (ev)
7417 "Open file link or URL at mouse."
7418 (interactive "e")
7419 (mouse-set-point ev)
7420 (org-open-at-point 'in-emacs))
7422 (defun org-open-at-mouse (ev)
7423 "Open file link or URL at mouse."
7424 (interactive "e")
7425 (mouse-set-point ev)
7426 (if (eq major-mode 'org-agenda-mode)
7427 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
7428 (org-open-at-point))
7430 (defvar org-window-config-before-follow-link nil
7431 "The window configuration before following a link.
7432 This is saved in case the need arises to restore it.")
7434 (defvar org-open-link-marker (make-marker)
7435 "Marker pointing to the location where `org-open-at-point; was called.")
7437 ;;;###autoload
7438 (defun org-open-at-point-global ()
7439 "Follow a link like Org-mode does.
7440 This command can be called in any mode to follow a link that has
7441 Org-mode syntax."
7442 (interactive)
7443 (org-run-like-in-org-mode 'org-open-at-point))
7445 ;;;###autoload
7446 (defun org-open-link-from-string (s &optional arg)
7447 "Open a link in the string S, as if it was in Org-mode."
7448 (interactive "sLink: \nP")
7449 (let ((reference-buffer (current-buffer)))
7450 (with-temp-buffer
7451 (let ((org-inhibit-startup t))
7452 (org-mode)
7453 (insert s)
7454 (goto-char (point-min))
7455 (org-open-at-point arg reference-buffer)))))
7457 (defun org-open-at-point (&optional in-emacs reference-buffer)
7458 "Open link at or after point.
7459 If there is no link at point, this function will search forward up to
7460 the end of the current subtree.
7461 Normally, files will be opened by an appropriate application. If the
7462 optional argument IN-EMACS is non-nil, Emacs will visit the file.
7463 With a double prefix argument, try to open outside of Emacs, in the
7464 application the system uses for this file type."
7465 (interactive "P")
7466 (org-load-modules-maybe)
7467 (move-marker org-open-link-marker (point))
7468 (setq org-window-config-before-follow-link (current-window-configuration))
7469 (org-remove-occur-highlights nil nil t)
7470 (cond
7471 ((org-at-timestamp-p t) (org-follow-timestamp-link))
7472 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
7473 (org-footnote-action))
7475 (let (type path link line search (pos (point)))
7476 (catch 'match
7477 (save-excursion
7478 (skip-chars-forward "^]\n\r")
7479 (when (org-in-regexp org-bracket-link-regexp)
7480 (setq link (org-extract-attributes
7481 (org-link-unescape (org-match-string-no-properties 1))))
7482 (while (string-match " *\n *" link)
7483 (setq link (replace-match " " t t link)))
7484 (setq link (org-link-expand-abbrev link))
7485 (cond
7486 ((or (file-name-absolute-p link)
7487 (string-match "^\\.\\.?/" link))
7488 (setq type "file" path link))
7489 ((string-match org-link-re-with-space3 link)
7490 (setq type (match-string 1 link) path (match-string 2 link)))
7491 (t (setq type "thisfile" path link)))
7492 (throw 'match t)))
7494 (when (get-text-property (point) 'org-linked-text)
7495 (setq type "thisfile"
7496 pos (if (get-text-property (1+ (point)) 'org-linked-text)
7497 (1+ (point)) (point))
7498 path (buffer-substring
7499 (previous-single-property-change pos 'org-linked-text)
7500 (next-single-property-change pos 'org-linked-text)))
7501 (throw 'match t))
7503 (save-excursion
7504 (when (or (org-in-regexp org-angle-link-re)
7505 (org-in-regexp org-plain-link-re))
7506 (setq type (match-string 1) path (match-string 2))
7507 (throw 'match t)))
7508 (save-excursion
7509 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
7510 (setq type "tags"
7511 path (match-string 1))
7512 (while (string-match ":" path)
7513 (setq path (replace-match "+" t t path)))
7514 (throw 'match t)))
7515 (when (org-in-regexp "<\\([^><\n]+\\)>")
7516 (setq type "tree-match"
7517 path (match-string 1))
7518 (throw 'match t)))
7519 (unless path
7520 (error "No link found"))
7522 ;; switch back to reference buffer
7523 ;; needed when if called in a temporary buffer through
7524 ;; org-open-link-from-string
7525 (and reference-buffer (switch-to-buffer reference-buffer))
7527 ;; Remove any trailing spaces in path
7528 (if (string-match " +\\'" path)
7529 (setq path (replace-match "" t t path)))
7530 (if (and org-link-translation-function
7531 (fboundp org-link-translation-function))
7532 ;; Check if we need to translate the link
7533 (let ((tmp (funcall org-link-translation-function type path)))
7534 (setq type (car tmp) path (cdr tmp))))
7536 (cond
7538 ((assoc type org-link-protocols)
7539 (funcall (nth 1 (assoc type org-link-protocols)) path))
7541 ((equal type "mailto")
7542 (let ((cmd (car org-link-mailto-program))
7543 (args (cdr org-link-mailto-program)) args1
7544 (address path) (subject "") a)
7545 (if (string-match "\\(.*\\)::\\(.*\\)" path)
7546 (setq address (match-string 1 path)
7547 subject (org-link-escape (match-string 2 path))))
7548 (while args
7549 (cond
7550 ((not (stringp (car args))) (push (pop args) args1))
7551 (t (setq a (pop args))
7552 (if (string-match "%a" a)
7553 (setq a (replace-match address t t a)))
7554 (if (string-match "%s" a)
7555 (setq a (replace-match subject t t a)))
7556 (push a args1))))
7557 (apply cmd (nreverse args1))))
7559 ((member type '("http" "https" "ftp" "news"))
7560 (browse-url (concat type ":" (org-link-escape
7561 path org-link-escape-chars-browser))))
7563 ((member type '("message"))
7564 (browse-url (concat type ":" path)))
7566 ((string= type "tags")
7567 (org-tags-view in-emacs path))
7568 ((string= type "thisfile")
7569 (if in-emacs
7570 (switch-to-buffer-other-window
7571 (org-get-buffer-for-internal-link (current-buffer)))
7572 (org-mark-ring-push))
7573 (let ((cmd `(org-link-search
7574 ,path
7575 ,(cond ((equal in-emacs '(4)) 'occur)
7576 ((equal in-emacs '(16)) 'org-occur)
7577 (t nil))
7578 ,pos)))
7579 (condition-case nil (eval cmd)
7580 (error (progn (widen) (eval cmd))))))
7582 ((string= type "tree-match")
7583 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
7585 ((string= type "file")
7586 (if (string-match "::\\([0-9]+\\)\\'" path)
7587 (setq line (string-to-number (match-string 1 path))
7588 path (substring path 0 (match-beginning 0)))
7589 (if (string-match "::\\(.+\\)\\'" path)
7590 (setq search (match-string 1 path)
7591 path (substring path 0 (match-beginning 0)))))
7592 (if (string-match "[*?{]" (file-name-nondirectory path))
7593 (dired path)
7594 (org-open-file path in-emacs line search)))
7596 ((string= type "news")
7597 (require 'org-gnus)
7598 (org-gnus-follow-link path))
7600 ((string= type "shell")
7601 (let ((cmd path))
7602 (if (or (not org-confirm-shell-link-function)
7603 (funcall org-confirm-shell-link-function
7604 (format "Execute \"%s\" in shell? "
7605 (org-add-props cmd nil
7606 'face 'org-warning))))
7607 (progn
7608 (message "Executing %s" cmd)
7609 (shell-command cmd))
7610 (error "Abort"))))
7612 ((string= type "elisp")
7613 (let ((cmd path))
7614 (if (or (not org-confirm-elisp-link-function)
7615 (funcall org-confirm-elisp-link-function
7616 (format "Execute \"%s\" as elisp? "
7617 (org-add-props cmd nil
7618 'face 'org-warning))))
7619 (message "%s => %s" cmd
7620 (if (equal (string-to-char cmd) ?\()
7621 (eval (read cmd))
7622 (call-interactively (read cmd))))
7623 (error "Abort"))))
7626 (browse-url-at-point))))))
7627 (move-marker org-open-link-marker nil)
7628 (run-hook-with-args 'org-follow-link-hook))
7630 ;;;; Time estimates
7632 (defun org-get-effort (&optional pom)
7633 "Get the effort estimate for the current entry."
7634 (org-entry-get pom org-effort-property))
7636 ;;; File search
7638 (defvar org-create-file-search-functions nil
7639 "List of functions to construct the right search string for a file link.
7640 These functions are called in turn with point at the location to
7641 which the link should point.
7643 A function in the hook should first test if it would like to
7644 handle this file type, for example by checking the major-mode or
7645 the file extension. If it decides not to handle this file, it
7646 should just return nil to give other functions a chance. If it
7647 does handle the file, it must return the search string to be used
7648 when following the link. The search string will be part of the
7649 file link, given after a double colon, and `org-open-at-point'
7650 will automatically search for it. If special measures must be
7651 taken to make the search successful, another function should be
7652 added to the companion hook `org-execute-file-search-functions',
7653 which see.
7655 A function in this hook may also use `setq' to set the variable
7656 `description' to provide a suggestion for the descriptive text to
7657 be used for this link when it gets inserted into an Org-mode
7658 buffer with \\[org-insert-link].")
7660 (defvar org-execute-file-search-functions nil
7661 "List of functions to execute a file search triggered by a link.
7663 Functions added to this hook must accept a single argument, the
7664 search string that was part of the file link, the part after the
7665 double colon. The function must first check if it would like to
7666 handle this search, for example by checking the major-mode or the
7667 file extension. If it decides not to handle this search, it
7668 should just return nil to give other functions a chance. If it
7669 does handle the search, it must return a non-nil value to keep
7670 other functions from trying.
7672 Each function can access the current prefix argument through the
7673 variable `current-prefix-argument'. Note that a single prefix is
7674 used to force opening a link in Emacs, so it may be good to only
7675 use a numeric or double prefix to guide the search function.
7677 In case this is needed, a function in this hook can also restore
7678 the window configuration before `org-open-at-point' was called using:
7680 (set-window-configuration org-window-config-before-follow-link)")
7682 (defun org-link-search (s &optional type avoid-pos)
7683 "Search for a link search option.
7684 If S is surrounded by forward slashes, it is interpreted as a
7685 regular expression. In org-mode files, this will create an `org-occur'
7686 sparse tree. In ordinary files, `occur' will be used to list matches.
7687 If the current buffer is in `dired-mode', grep will be used to search
7688 in all files. If AVOID-POS is given, ignore matches near that position."
7689 (let ((case-fold-search t)
7690 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
7691 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
7692 (append '(("") (" ") ("\t") ("\n"))
7693 org-emphasis-alist)
7694 "\\|") "\\)"))
7695 (pos (point))
7696 (pre nil) (post nil)
7697 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
7698 (cond
7699 ;; First check if there are any special
7700 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
7701 ;; Now try the builtin stuff
7702 ((save-excursion
7703 (goto-char (point-min))
7704 (and
7705 (re-search-forward
7706 (concat "<<" (regexp-quote s0) ">>") nil t)
7707 (setq type 'dedicated
7708 pos (match-beginning 0))))
7709 ;; There is an exact target for this
7710 (goto-char pos))
7711 ((and (string-match "^(\\(.*\\))$" s0)
7712 (save-excursion
7713 (goto-char (point-min))
7714 (and
7715 (re-search-forward
7716 (concat "[^[]" (regexp-quote
7717 (format org-coderef-label-format
7718 (match-string 1 s0))))
7719 nil t)
7720 (setq type 'dedicated
7721 pos (1+ (match-beginning 0))))))
7722 ;; There is a coderef target for this
7723 (goto-char pos))
7724 ((string-match "^/\\(.*\\)/$" s)
7725 ;; A regular expression
7726 (cond
7727 ((org-mode-p)
7728 (org-occur (match-string 1 s)))
7729 ;;((eq major-mode 'dired-mode)
7730 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
7731 (t (org-do-occur (match-string 1 s)))))
7733 ;; A normal search strings
7734 (when (equal (string-to-char s) ?*)
7735 ;; Anchor on headlines, post may include tags.
7736 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
7737 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
7738 s (substring s 1)))
7739 (remove-text-properties
7740 0 (length s)
7741 '(face nil mouse-face nil keymap nil fontified nil) s)
7742 ;; Make a series of regular expressions to find a match
7743 (setq words (org-split-string s "[ \n\r\t]+")
7745 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
7746 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
7747 "\\)" markers)
7748 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
7749 re2a (concat "[ \t\r\n]" re2a_)
7750 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
7751 re4 (concat "[^a-zA-Z_]" re4_)
7753 re1 (concat pre re2 post)
7754 re3 (concat pre (if pre re4_ re4) post)
7755 re5 (concat pre ".*" re4)
7756 re2 (concat pre re2)
7757 re2a (concat pre (if pre re2a_ re2a))
7758 re4 (concat pre (if pre re4_ re4))
7759 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7760 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7761 re5 "\\)"
7763 (cond
7764 ((eq type 'org-occur) (org-occur reall))
7765 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7766 (t (goto-char (point-min))
7767 (setq type 'fuzzy)
7768 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
7769 (org-search-not-self 1 re1 nil t)
7770 (org-search-not-self 1 re2 nil t)
7771 (org-search-not-self 1 re2a nil t)
7772 (org-search-not-self 1 re3 nil t)
7773 (org-search-not-self 1 re4 nil t)
7774 (org-search-not-self 1 re5 nil t)
7776 (goto-char (match-beginning 1))
7777 (goto-char pos)
7778 (error "No match")))))
7780 ;; Normal string-search
7781 (goto-char (point-min))
7782 (if (search-forward s nil t)
7783 (goto-char (match-beginning 0))
7784 (error "No match"))))
7785 (and (org-mode-p) (org-show-context 'link-search))
7786 type))
7788 (defun org-search-not-self (group &rest args)
7789 "Execute `re-search-forward', but only accept matches that do not
7790 enclose the position of `org-open-link-marker'."
7791 (let ((m org-open-link-marker))
7792 (catch 'exit
7793 (while (apply 're-search-forward args)
7794 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
7795 (goto-char (match-end group))
7796 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
7797 (> (match-beginning 0) (marker-position m))
7798 (< (match-end 0) (marker-position m)))
7799 (save-match-data
7800 (or (not (org-in-regexp
7801 org-bracket-link-analytic-regexp 1))
7802 (not (match-end 4)) ; no description
7803 (and (<= (match-beginning 4) (point))
7804 (>= (match-end 4) (point))))))
7805 (throw 'exit (point))))))))
7807 (defun org-get-buffer-for-internal-link (buffer)
7808 "Return a buffer to be used for displaying the link target of internal links."
7809 (cond
7810 ((not org-display-internal-link-with-indirect-buffer)
7811 buffer)
7812 ((string-match "(Clone)$" (buffer-name buffer))
7813 (message "Buffer is already a clone, not making another one")
7814 ;; we also do not modify visibility in this case
7815 buffer)
7816 (t ; make a new indirect buffer for displaying the link
7817 (let* ((bn (buffer-name buffer))
7818 (ibn (concat bn "(Clone)"))
7819 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
7820 (with-current-buffer ib (org-overview))
7821 ib))))
7823 (defun org-do-occur (regexp &optional cleanup)
7824 "Call the Emacs command `occur'.
7825 If CLEANUP is non-nil, remove the printout of the regular expression
7826 in the *Occur* buffer. This is useful if the regex is long and not useful
7827 to read."
7828 (occur regexp)
7829 (when cleanup
7830 (let ((cwin (selected-window)) win beg end)
7831 (when (setq win (get-buffer-window "*Occur*"))
7832 (select-window win))
7833 (goto-char (point-min))
7834 (when (re-search-forward "match[a-z]+" nil t)
7835 (setq beg (match-end 0))
7836 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7837 (setq end (1- (match-beginning 0)))))
7838 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
7839 (goto-char (point-min))
7840 (select-window cwin))))
7842 ;;; The mark ring for links jumps
7844 (defvar org-mark-ring nil
7845 "Mark ring for positions before jumps in Org-mode.")
7846 (defvar org-mark-ring-last-goto nil
7847 "Last position in the mark ring used to go back.")
7848 ;; Fill and close the ring
7849 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7850 (loop for i from 1 to org-mark-ring-length do
7851 (push (make-marker) org-mark-ring))
7852 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7853 org-mark-ring)
7855 (defun org-mark-ring-push (&optional pos buffer)
7856 "Put the current position or POS into the mark ring and rotate it."
7857 (interactive)
7858 (setq pos (or pos (point)))
7859 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7860 (move-marker (car org-mark-ring)
7861 (or pos (point))
7862 (or buffer (current-buffer)))
7863 (message "%s"
7864 (substitute-command-keys
7865 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7867 (defun org-mark-ring-goto (&optional n)
7868 "Jump to the previous position in the mark ring.
7869 With prefix arg N, jump back that many stored positions. When
7870 called several times in succession, walk through the entire ring.
7871 Org-mode commands jumping to a different position in the current file,
7872 or to another Org-mode file, automatically push the old position
7873 onto the ring."
7874 (interactive "p")
7875 (let (p m)
7876 (if (eq last-command this-command)
7877 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7878 (setq p org-mark-ring))
7879 (setq org-mark-ring-last-goto p)
7880 (setq m (car p))
7881 (switch-to-buffer (marker-buffer m))
7882 (goto-char m)
7883 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
7885 (defun org-remove-angle-brackets (s)
7886 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7887 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7889 (defun org-add-angle-brackets (s)
7890 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7891 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7893 (defun org-remove-double-quotes (s)
7894 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
7895 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
7898 ;;; Following specific links
7900 (defun org-follow-timestamp-link ()
7901 (cond
7902 ((org-at-date-range-p t)
7903 (let ((org-agenda-start-on-weekday)
7904 (t1 (match-string 1))
7905 (t2 (match-string 2)))
7906 (setq t1 (time-to-days (org-time-string-to-time t1))
7907 t2 (time-to-days (org-time-string-to-time t2)))
7908 (org-agenda-list nil t1 (1+ (- t2 t1)))))
7909 ((org-at-timestamp-p t)
7910 (org-agenda-list nil (time-to-days (org-time-string-to-time
7911 (substring (match-string 1) 0 10)))
7913 (t (error "This should not happen"))))
7916 ;;; Following file links
7917 (defvar org-wait nil)
7918 (defun org-open-file (path &optional in-emacs line search)
7919 "Open the file at PATH.
7920 First, this expands any special file name abbreviations. Then the
7921 configuration variable `org-file-apps' is checked if it contains an
7922 entry for this file type, and if yes, the corresponding command is launched.
7924 If no application is found, Emacs simply visits the file.
7926 With optional prefix argument IN-EMACS, Emacs will visit the file.
7927 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
7928 and o use an external application to visit the file.
7930 Optional LINE specifies a line to go to, optional SEARCH a string to
7931 search for. If LINE or SEARCH is given, the file will always be
7932 opened in Emacs.
7933 If the file does not exist, an error is thrown."
7934 (setq in-emacs (or in-emacs line search))
7935 (let* ((file (if (equal path "")
7936 buffer-file-name
7937 (substitute-in-file-name (expand-file-name path))))
7938 (apps (append org-file-apps (org-default-apps)))
7939 (remp (and (assq 'remote apps) (org-file-remote-p file)))
7940 (dirp (if remp nil (file-directory-p file)))
7941 (file (if (and dirp org-open-directory-means-index-dot-org)
7942 (concat (file-name-as-directory file) "index.org")
7943 file))
7944 (a-m-a-p (assq 'auto-mode apps))
7945 (dfile (downcase file))
7946 (old-buffer (current-buffer))
7947 (old-pos (point))
7948 (old-mode major-mode)
7949 ext cmd)
7950 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7951 (setq ext (match-string 1 dfile))
7952 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7953 (setq ext (match-string 1 dfile))))
7954 (cond
7955 ((equal in-emacs '(16))
7956 (setq cmd (cdr (assoc 'system apps))))
7957 (in-emacs (setq cmd 'emacs))
7959 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
7960 (and dirp (cdr (assoc 'directory apps)))
7961 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
7962 'string-match)
7963 (cdr (assoc ext apps))
7964 (cdr (assoc t apps))))))
7965 (when (eq cmd 'system)
7966 (setq cmd (cdr (assoc 'system apps))))
7967 (when (eq cmd 'default)
7968 (setq cmd (cdr (assoc t apps))))
7969 (when (eq cmd 'mailcap)
7970 (require 'mailcap)
7971 (mailcap-parse-mailcaps)
7972 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7973 (command (mailcap-mime-info mime-type)))
7974 (if (stringp command)
7975 (setq cmd command)
7976 (setq cmd 'emacs))))
7977 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
7978 (not (file-exists-p file))
7979 (not org-open-non-existing-files))
7980 (error "No such file: %s" file))
7981 (cond
7982 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7983 ;; Remove quotes around the file name - we'll use shell-quote-argument.
7984 (while (string-match "['\"]%s['\"]" cmd)
7985 (setq cmd (replace-match "%s" t t cmd)))
7986 (while (string-match "%s" cmd)
7987 (setq cmd (replace-match
7988 (save-match-data
7989 (shell-quote-argument
7990 (convert-standard-filename file)))
7991 t t cmd)))
7992 (save-window-excursion
7993 (start-process-shell-command cmd nil cmd)
7994 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
7996 ((or (stringp cmd)
7997 (eq cmd 'emacs))
7998 (funcall (cdr (assq 'file org-link-frame-setup)) file)
7999 (widen)
8000 (if line (goto-line line)
8001 (if search (org-link-search search))))
8002 ((consp cmd)
8003 (let ((file (convert-standard-filename file)))
8004 (eval cmd)))
8005 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
8006 (and (org-mode-p) (eq old-mode 'org-mode)
8007 (or (not (equal old-buffer (current-buffer)))
8008 (not (equal old-pos (point))))
8009 (org-mark-ring-push old-pos old-buffer))))
8011 (defun org-default-apps ()
8012 "Return the default applications for this operating system."
8013 (cond
8014 ((eq system-type 'darwin)
8015 org-file-apps-defaults-macosx)
8016 ((eq system-type 'windows-nt)
8017 org-file-apps-defaults-windowsnt)
8018 (t org-file-apps-defaults-gnu)))
8020 (defun org-apps-regexp-alist (list &optional add-auto-mode)
8021 "Convert extensions to regular expressions in the cars of LIST.
8022 Also, weed out any non-string entries, because the return value is used
8023 only for regexp matching.
8024 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
8025 point to the symbol `emacs', indicating that the file should
8026 be opened in Emacs."
8027 (append
8028 (delq nil
8029 (mapcar (lambda (x)
8030 (if (not (stringp (car x)))
8032 (if (string-match "\\W" (car x))
8034 (cons (concat "\\." (car x) "\\'") (cdr x)))))
8035 list))
8036 (if add-auto-mode
8037 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
8039 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
8040 (defun org-file-remote-p (file)
8041 "Test whether FILE specifies a location on a remote system.
8042 Return non-nil if the location is indeed remote.
8044 For example, the filename \"/user@host:/foo\" specifies a location
8045 on the system \"/user@host:\"."
8046 (cond ((fboundp 'file-remote-p)
8047 (file-remote-p file))
8048 ((fboundp 'tramp-handle-file-remote-p)
8049 (tramp-handle-file-remote-p file))
8050 ((and (boundp 'ange-ftp-name-format)
8051 (string-match (car ange-ftp-name-format) file))
8053 (t nil)))
8056 ;;;; Refiling
8058 (defun org-get-org-file ()
8059 "Read a filename, with default directory `org-directory'."
8060 (let ((default (or org-default-notes-file remember-data-file)))
8061 (read-file-name (format "File name [%s]: " default)
8062 (file-name-as-directory org-directory)
8063 default)))
8065 (defun org-notes-order-reversed-p ()
8066 "Check if the current file should receive notes in reversed order."
8067 (cond
8068 ((not org-reverse-note-order) nil)
8069 ((eq t org-reverse-note-order) t)
8070 ((not (listp org-reverse-note-order)) nil)
8071 (t (catch 'exit
8072 (let ((all org-reverse-note-order)
8073 entry)
8074 (while (setq entry (pop all))
8075 (if (string-match (car entry) buffer-file-name)
8076 (throw 'exit (cdr entry))))
8077 nil)))))
8079 (defvar org-refile-target-table nil
8080 "The list of refile targets, created by `org-refile'.")
8082 (defvar org-agenda-new-buffers nil
8083 "Buffers created to visit agenda files.")
8085 (defun org-get-refile-targets (&optional default-buffer)
8086 "Produce a table with refile targets."
8087 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
8088 targets txt re files f desc descre fast-path-p level)
8089 (message "Getting targets...")
8090 (with-current-buffer (or default-buffer (current-buffer))
8091 (while (setq entry (pop entries))
8092 (setq files (car entry) desc (cdr entry))
8093 (setq fast-path-p nil)
8094 (cond
8095 ((null files) (setq files (list (current-buffer))))
8096 ((eq files 'org-agenda-files)
8097 (setq files (org-agenda-files 'unrestricted)))
8098 ((and (symbolp files) (fboundp files))
8099 (setq files (funcall files)))
8100 ((and (symbolp files) (boundp files))
8101 (setq files (symbol-value files))))
8102 (if (stringp files) (setq files (list files)))
8103 (cond
8104 ((eq (car desc) :tag)
8105 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
8106 ((eq (car desc) :todo)
8107 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
8108 ((eq (car desc) :regexp)
8109 (setq descre (cdr desc)))
8110 ((eq (car desc) :level)
8111 (setq descre (concat "^\\*\\{" (number-to-string
8112 (if org-odd-levels-only
8113 (1- (* 2 (cdr desc)))
8114 (cdr desc)))
8115 "\\}[ \t]")))
8116 ((eq (car desc) :maxlevel)
8117 (setq fast-path-p t)
8118 (setq descre (concat "^\\*\\{1," (number-to-string
8119 (if org-odd-levels-only
8120 (1- (* 2 (cdr desc)))
8121 (cdr desc)))
8122 "\\}[ \t]")))
8123 (t (error "Bad refiling target description %s" desc)))
8124 (while (setq f (pop files))
8125 (save-excursion
8126 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
8127 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
8128 (setq f (expand-file-name f))
8129 (if (eq org-refile-use-outline-path 'file)
8130 (push (list (file-name-nondirectory f) f nil nil) targets))
8131 (save-excursion
8132 (save-restriction
8133 (widen)
8134 (goto-char (point-min))
8135 (while (re-search-forward descre nil t)
8136 (goto-char (point-at-bol))
8137 (when (looking-at org-complex-heading-regexp)
8138 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
8139 txt (org-link-display-format (match-string 4))
8140 re (concat "^" (regexp-quote
8141 (buffer-substring (match-beginning 1)
8142 (match-end 4)))))
8143 (if (match-end 5) (setq re (concat re "[ \t]+"
8144 (regexp-quote
8145 (match-string 5)))))
8146 (setq re (concat re "[ \t]*$"))
8147 (when org-refile-use-outline-path
8148 (setq txt (mapconcat 'org-protect-slash
8149 (append
8150 (if (eq org-refile-use-outline-path 'file)
8151 (list (file-name-nondirectory
8152 (buffer-file-name (buffer-base-buffer))))
8153 (if (eq org-refile-use-outline-path 'full-file-path)
8154 (list (buffer-file-name (buffer-base-buffer)))))
8155 (org-get-outline-path fast-path-p level txt)
8156 (list txt))
8157 "/")))
8158 (push (list txt f re (point)) targets))
8159 (goto-char (point-at-eol))))))))
8160 (message "Getting targets...done")
8161 (nreverse targets))))
8163 (defun org-protect-slash (s)
8164 (while (string-match "/" s)
8165 (setq s (replace-match "\\" t t s)))
8168 (defvar org-olpa (make-vector 20 nil))
8170 (defun org-get-outline-path (&optional fastp level heading)
8171 "Return the outline path to the current entry, as a list."
8172 (if fastp
8173 (progn
8174 (if (> level 19)
8175 (error "Outline path failure, more than 19 levels."))
8176 (loop for i from level upto 19 do
8177 (aset org-olpa i nil))
8178 (prog1
8179 (delq nil (append org-olpa nil))
8180 (aset org-olpa level heading)))
8181 (let (rtn)
8182 (save-excursion
8183 (while (org-up-heading-safe)
8184 (when (looking-at org-complex-heading-regexp)
8185 (push (org-match-string-no-properties 4) rtn)))
8186 rtn))))
8188 (defvar org-refile-history nil
8189 "History for refiling operations.")
8191 (defun org-refile (&optional goto default-buffer)
8192 "Move the entry at point to another heading.
8193 The list of target headings is compiled using the information in
8194 `org-refile-targets', which see. This list is created before each use
8195 and will therefore always be up-to-date.
8197 At the target location, the entry is filed as a subitem of the target heading.
8198 Depending on `org-reverse-note-order', the new subitem will either be the
8199 first or the last subitem.
8201 If there is an active region, all entries in that region will be moved.
8202 However, the region must fulfil the requirement that the first heading
8203 is the first one sets the top-level of the moved text - at most siblings
8204 below it are allowed.
8206 With prefix arg GOTO, the command will only visit the target location,
8207 not actually move anything.
8208 With a double prefix `C-u C-u', go to the location where the last refiling
8209 operation has put the subtree."
8210 (interactive "P")
8211 (let* ((cbuf (current-buffer))
8212 (regionp (org-region-active-p))
8213 (region-start (and regionp (region-beginning)))
8214 (region-end (and regionp (region-end)))
8215 (region-length (and regionp (- region-end region-start)))
8216 (filename (buffer-file-name (buffer-base-buffer cbuf)))
8217 pos it nbuf file re level reversed)
8218 (when regionp (goto-char region-start)
8219 (unless (org-kill-is-subtree-p
8220 (buffer-substring region-start region-end))
8221 (error "The region is not a (sequence of) subtree(s)")))
8222 (if (equal goto '(16))
8223 (org-refile-goto-last-stored)
8224 (when (setq it (org-refile-get-location
8225 (if goto "Goto: " "Refile to: ") default-buffer))
8226 (setq file (nth 1 it)
8227 re (nth 2 it)
8228 pos (nth 3 it))
8229 (if (and (not goto)
8231 (equal (buffer-file-name) file)
8232 (if regionp
8233 (and (>= pos region-start)
8234 (<= pos region-end))
8235 (and (>= pos (point))
8236 (< pos (save-excursion
8237 (org-end-of-subtree t t))))))
8238 (error "Cannot refile to position inside the tree or region"))
8240 (setq nbuf (or (find-buffer-visiting file)
8241 (find-file-noselect file)))
8242 (if goto
8243 (progn
8244 (switch-to-buffer nbuf)
8245 (goto-char pos)
8246 (org-show-context 'org-goto))
8247 (if regionp
8248 (progn
8249 (kill-new (buffer-substring region-start region-end))
8250 (org-save-markers-in-region region-start region-end))
8251 (org-copy-subtree 1 nil t))
8252 (save-excursion
8253 (set-buffer (setq nbuf (or (find-buffer-visiting file)
8254 (find-file-noselect file))))
8255 (setq reversed (org-notes-order-reversed-p))
8256 (save-excursion
8257 (save-restriction
8258 (widen)
8259 (if pos
8260 (progn
8261 (goto-char pos)
8262 (looking-at outline-regexp)
8263 (setq level (org-get-valid-level (funcall outline-level) 1))
8264 (goto-char
8265 (if reversed
8266 (or (outline-next-heading) (point-max))
8267 (or (save-excursion (outline-get-next-sibling))
8268 (org-end-of-subtree t t)
8269 (point-max)))))
8270 (setq level 1)
8271 (if (not reversed)
8272 (goto-char (point-max))
8273 (goto-char (point-min))
8274 (or (outline-next-heading) (goto-char (point-max)))))
8275 (if (not (bolp)) (newline))
8276 (bookmark-set "org-refile-last-stored")
8277 (org-paste-subtree level))))
8278 (if regionp
8279 (delete-region (point) (+ (point) region-length))
8280 (org-cut-subtree))
8281 (setq org-markers-to-move nil)
8282 (message "Refiled to \"%s\"" (car it)))))))
8284 (defun org-refile-goto-last-stored ()
8285 "Go to the location where the last refile was stored."
8286 (interactive)
8287 (bookmark-jump "org-refile-last-stored")
8288 (message "This is the location of the last refile"))
8290 (defun org-refile-get-location (&optional prompt default-buffer)
8291 "Prompt the user for a refile location, using PROMPT."
8292 (let ((org-refile-targets org-refile-targets)
8293 (org-refile-use-outline-path org-refile-use-outline-path))
8294 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
8295 (unless org-refile-target-table
8296 (error "No refile targets"))
8297 (let* ((cbuf (current-buffer))
8298 (partial-completion-mode nil)
8299 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
8300 (cfunc (if (and org-refile-use-outline-path
8301 org-outline-path-complete-in-steps)
8302 'org-olpath-completing-read
8303 'org-ido-completing-read))
8304 (extra (if org-refile-use-outline-path "/" ""))
8305 (filename (and cfn (expand-file-name cfn)))
8306 (tbl (mapcar
8307 (lambda (x)
8308 (if (and (not (member org-refile-use-outline-path
8309 '(file full-file-path)))
8310 (not (equal filename (nth 1 x))))
8311 (cons (concat (car x) extra " ("
8312 (file-name-nondirectory (nth 1 x)) ")")
8313 (cdr x))
8314 (cons (concat (car x) extra) (cdr x))))
8315 org-refile-target-table))
8316 (completion-ignore-case t))
8317 (assoc (funcall cfunc prompt tbl nil t nil 'org-refile-history)
8318 tbl)))
8320 (defun org-olpath-completing-read (prompt collection &rest args)
8321 "Read an outline path like a file name."
8322 (let ((thetable collection)
8323 (org-completion-use-ido nil)) ; does not work with ido.
8324 (apply
8325 'org-ido-completing-read prompt
8326 (lambda (string predicate &optional flag)
8327 (let (rtn r f (l (length string)))
8328 (cond
8329 ((eq flag nil)
8330 ;; try completion
8331 (try-completion string thetable))
8332 ((eq flag t)
8333 ;; all-completions
8334 (setq rtn (all-completions string thetable predicate))
8335 (mapcar
8336 (lambda (x)
8337 (setq r (substring x l))
8338 (if (string-match " ([^)]*)$" x)
8339 (setq f (match-string 0 x))
8340 (setq f ""))
8341 (if (string-match "/" r)
8342 (concat string (substring r 0 (match-end 0)) f)
8344 rtn))
8345 ((eq flag 'lambda)
8346 ;; exact match?
8347 (assoc string thetable)))
8349 args)))
8351 ;;;; Dynamic blocks
8353 (defun org-find-dblock (name)
8354 "Find the first dynamic block with name NAME in the buffer.
8355 If not found, stay at current position and return nil."
8356 (let (pos)
8357 (save-excursion
8358 (goto-char (point-min))
8359 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
8360 nil t)
8361 (match-beginning 0))))
8362 (if pos (goto-char pos))
8363 pos))
8365 (defconst org-dblock-start-re
8366 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
8367 "Matches the startline of a dynamic block, with parameters.")
8369 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
8370 "Matches the end of a dynamic block.")
8372 (defun org-create-dblock (plist)
8373 "Create a dynamic block section, with parameters taken from PLIST.
8374 PLIST must contain a :name entry which is used as name of the block."
8375 (unless (bolp) (newline))
8376 (let ((name (plist-get plist :name)))
8377 (insert "#+BEGIN: " name)
8378 (while plist
8379 (if (eq (car plist) :name)
8380 (setq plist (cddr plist))
8381 (insert " " (prin1-to-string (pop plist)))))
8382 (insert "\n\n#+END:\n")
8383 (beginning-of-line -2)))
8385 (defun org-prepare-dblock ()
8386 "Prepare dynamic block for refresh.
8387 This empties the block, puts the cursor at the insert position and returns
8388 the property list including an extra property :name with the block name."
8389 (unless (looking-at org-dblock-start-re)
8390 (error "Not at a dynamic block"))
8391 (let* ((begdel (1+ (match-end 0)))
8392 (name (org-no-properties (match-string 1)))
8393 (params (append (list :name name)
8394 (read (concat "(" (match-string 3) ")")))))
8395 (unless (re-search-forward org-dblock-end-re nil t)
8396 (error "Dynamic block not terminated"))
8397 (setq params
8398 (append params
8399 (list :content (buffer-substring
8400 begdel (match-beginning 0)))))
8401 (delete-region begdel (match-beginning 0))
8402 (goto-char begdel)
8403 (open-line 1)
8404 params))
8406 (defun org-map-dblocks (&optional command)
8407 "Apply COMMAND to all dynamic blocks in the current buffer.
8408 If COMMAND is not given, use `org-update-dblock'."
8409 (let ((cmd (or command 'org-update-dblock))
8410 pos)
8411 (save-excursion
8412 (goto-char (point-min))
8413 (while (re-search-forward org-dblock-start-re nil t)
8414 (goto-char (setq pos (match-beginning 0)))
8415 (condition-case nil
8416 (funcall cmd)
8417 (error (message "Error during update of dynamic block")))
8418 (goto-char pos)
8419 (unless (re-search-forward org-dblock-end-re nil t)
8420 (error "Dynamic block not terminated"))))))
8422 (defun org-dblock-update (&optional arg)
8423 "User command for updating dynamic blocks.
8424 Update the dynamic block at point. With prefix ARG, update all dynamic
8425 blocks in the buffer."
8426 (interactive "P")
8427 (if arg
8428 (org-update-all-dblocks)
8429 (or (looking-at org-dblock-start-re)
8430 (org-beginning-of-dblock))
8431 (org-update-dblock)))
8433 (defun org-update-dblock ()
8434 "Update the dynamic block at point
8435 This means to empty the block, parse for parameters and then call
8436 the correct writing function."
8437 (save-window-excursion
8438 (let* ((pos (point))
8439 (line (org-current-line))
8440 (params (org-prepare-dblock))
8441 (name (plist-get params :name))
8442 (cmd (intern (concat "org-dblock-write:" name))))
8443 (message "Updating dynamic block `%s' at line %d..." name line)
8444 (funcall cmd params)
8445 (message "Updating dynamic block `%s' at line %d...done" name line)
8446 (goto-char pos))))
8448 (defun org-beginning-of-dblock ()
8449 "Find the beginning of the dynamic block at point.
8450 Error if there is no such block at point."
8451 (let ((pos (point))
8452 beg)
8453 (end-of-line 1)
8454 (if (and (re-search-backward org-dblock-start-re nil t)
8455 (setq beg (match-beginning 0))
8456 (re-search-forward org-dblock-end-re nil t)
8457 (> (match-end 0) pos))
8458 (goto-char beg)
8459 (goto-char pos)
8460 (error "Not in a dynamic block"))))
8462 (defun org-update-all-dblocks ()
8463 "Update all dynamic blocks in the buffer.
8464 This function can be used in a hook."
8465 (when (org-mode-p)
8466 (org-map-dblocks 'org-update-dblock)))
8469 ;;;; Completion
8471 (defconst org-additional-option-like-keywords
8472 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
8473 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
8474 "BEGIN_EXAMPLE" "END_EXAMPLE"
8475 "BEGIN_QUOTE" "END_QUOTE"
8476 "BEGIN_VERSE" "END_VERSE"
8477 "BEGIN_CENTER" "END_CENTER"
8478 "BEGIN_SRC" "END_SRC"
8479 "CATEGORY" "COLUMNS"
8480 "CAPTION" "LABEL" "ATTR_HTML" "ATTR_LaTeX"))
8482 (defcustom org-structure-template-alist
8484 ("s" "#+begin_src ?\n\n#+end_src"
8485 "<src lang=\"?\">\n\n</src>")
8486 ("e" "#+begin_example\n?\n#+end_example"
8487 "<example>\n?\n</example>")
8488 ("q" "#+begin_quote\n?\n#+end_quote"
8489 "<quote>\n?\n</quote>")
8490 ("v" "#+begin_verse\n?\n#+end_verse"
8491 "<verse>\n?\n/verse>")
8492 ("c" "#+begin_center\n?\n#+end_center"
8493 "<center>\n?\n/center>")
8494 ("l" "#+begin_latex\n?\n#+end_latex"
8495 "<literal style=\"latex\">\n?\n</literal>")
8496 ("L" "#+latex: "
8497 "<literal style=\"latex\">?</literal>")
8498 ("h" "#+begin_html\n?\n#+end_html"
8499 "<literal style=\"html\">\n?\n</literal>")
8500 ("H" "#+html: "
8501 "<literal style=\"html\">?</literal>")
8502 ("a" "#+begin_ascii\n?\n#+end_ascii")
8503 ("A" "#+ascii: ")
8504 ("i" "#+include %file ?"
8505 "<include file=%file markup=\"?\">")
8507 "Structure completion elements.
8508 This is a list of abbreviation keys and values. The value gets inserted
8509 it you type @samp{.} followed by the key and then the completion key,
8510 usually `M-TAB'. %file will be replaced by a file name after prompting
8511 for the file using completion.
8512 There are two templates for each key, the first uses the original Org syntax,
8513 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
8514 the default when the /org-mtags.el/ module has been loaded. See also the
8515 variable `org-mtags-prefer-muse-templates'.
8516 This is an experimental feature, it is undecided if it is going to stay in."
8517 :group 'org-completion
8518 :type '(repeat
8519 (string :tag "Key")
8520 (string :tag "Template")
8521 (string :tag "Muse Template")))
8523 (defun org-try-structure-completion ()
8524 "Try to complete a structure template before point.
8525 This looks for strings like \"<e\" on an otherwise empty line and
8526 expands them."
8527 (let ((l (buffer-substring (point-at-bol) (point)))
8529 (when (and (looking-at "[ \t]*$")
8530 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
8531 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
8532 (org-complete-expand-structure-template (+ -1 (point-at-bol)
8533 (match-beginning 1)) a)
8534 t)))
8536 (defun org-complete-expand-structure-template (start cell)
8537 "Expand a structure template."
8538 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
8539 (rpl (nth (if musep 2 1) cell)))
8540 (delete-region start (point))
8541 (when (string-match "\\`#\\+" rpl)
8542 (cond
8543 ((bolp))
8544 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
8545 (delete-region (point-at-bol) (point)))
8546 (t (newline))))
8547 (setq start (point))
8548 (if (string-match "%file" rpl)
8549 (setq rpl (replace-match
8550 (concat
8551 "\""
8552 (save-match-data
8553 (abbreviate-file-name (read-file-name "Include file: ")))
8554 "\"")
8555 t t rpl)))
8556 (insert rpl)
8557 (if (re-search-backward "\\?" start t) (delete-char 1))))
8560 (defun org-complete (&optional arg)
8561 "Perform completion on word at point.
8562 At the beginning of a headline, this completes TODO keywords as given in
8563 `org-todo-keywords'.
8564 If the current word is preceded by a backslash, completes the TeX symbols
8565 that are supported for HTML support.
8566 If the current word is preceded by \"#+\", completes special words for
8567 setting file options.
8568 In the line after \"#+STARTUP:, complete valid keywords.\"
8569 At all other locations, this simply calls the value of
8570 `org-completion-fallback-command'."
8571 (interactive "P")
8572 (org-without-partial-completion
8573 (catch 'exit
8574 (let* ((a nil)
8575 (end (point))
8576 (beg1 (save-excursion
8577 (skip-chars-backward (org-re "[:alnum:]_@"))
8578 (point)))
8579 (beg (save-excursion
8580 (skip-chars-backward "a-zA-Z0-9_:$")
8581 (point)))
8582 (confirm (lambda (x) (stringp (car x))))
8583 (searchhead (equal (char-before beg) ?*))
8584 (struct
8585 (when (and (member (char-before beg1) '(?. ?<))
8586 (setq a (assoc (buffer-substring beg1 (point))
8587 org-structure-template-alist)))
8588 (org-complete-expand-structure-template (1- beg1) a)
8589 (throw 'exit t)))
8590 (tag (and (equal (char-before beg1) ?:)
8591 (equal (char-after (point-at-bol)) ?*)))
8592 (prop (and (equal (char-before beg1) ?:)
8593 (not (equal (char-after (point-at-bol)) ?*))))
8594 (texp (equal (char-before beg) ?\\))
8595 (link (equal (char-before beg) ?\[))
8596 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
8597 beg)
8598 "#+"))
8599 (startup (string-match "^#\\+STARTUP:.*"
8600 (buffer-substring (point-at-bol) (point))))
8601 (completion-ignore-case opt)
8602 (type nil)
8603 (tbl nil)
8604 (table (cond
8605 (opt
8606 (setq type :opt)
8607 (require 'org-exp)
8608 (append
8609 (mapcar
8610 (lambda (x)
8611 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
8612 (cons (match-string 2 x) (match-string 1 x)))
8613 (org-split-string (org-get-current-options) "\n"))
8614 (mapcar 'list org-additional-option-like-keywords)))
8615 (startup
8616 (setq type :startup)
8617 org-startup-options)
8618 (link (append org-link-abbrev-alist-local
8619 org-link-abbrev-alist))
8620 (texp
8621 (setq type :tex)
8622 org-html-entities)
8623 ((string-match "\\`\\*+[ \t]+\\'"
8624 (buffer-substring (point-at-bol) beg))
8625 (setq type :todo)
8626 (mapcar 'list org-todo-keywords-1))
8627 (searchhead
8628 (setq type :searchhead)
8629 (save-excursion
8630 (goto-char (point-min))
8631 (while (re-search-forward org-todo-line-regexp nil t)
8632 (push (list
8633 (org-make-org-heading-search-string
8634 (match-string 3) t))
8635 tbl)))
8636 tbl)
8637 (tag (setq type :tag beg beg1)
8638 (or org-tag-alist (org-get-buffer-tags)))
8639 (prop (setq type :prop beg beg1)
8640 (mapcar 'list (org-buffer-property-keys nil t t)))
8641 (t (progn
8642 (call-interactively org-completion-fallback-command)
8643 (throw 'exit nil)))))
8644 (pattern (buffer-substring-no-properties beg end))
8645 (completion (try-completion pattern table confirm)))
8646 (cond ((eq completion t)
8647 (if (not (assoc (upcase pattern) table))
8648 (message "Already complete")
8649 (if (and (equal type :opt)
8650 (not (member (car (assoc (upcase pattern) table))
8651 org-additional-option-like-keywords)))
8652 (insert (substring (cdr (assoc (upcase pattern) table))
8653 (length pattern)))
8654 (if (memq type '(:tag :prop)) (insert ":")))))
8655 ((null completion)
8656 (message "Can't find completion for \"%s\"" pattern)
8657 (ding))
8658 ((not (string= pattern completion))
8659 (delete-region beg end)
8660 (if (string-match " +$" completion)
8661 (setq completion (replace-match "" t t completion)))
8662 (insert completion)
8663 (if (get-buffer-window "*Completions*")
8664 (delete-window (get-buffer-window "*Completions*")))
8665 (if (assoc completion table)
8666 (if (eq type :todo) (insert " ")
8667 (if (memq type '(:tag :prop)) (insert ":"))))
8668 (if (and (equal type :opt) (assoc completion table))
8669 (message "%s" (substitute-command-keys
8670 "Press \\[org-complete] again to insert example settings"))))
8672 (message "Making completion list...")
8673 (let ((list (sort (all-completions pattern table confirm)
8674 'string<)))
8675 (with-output-to-temp-buffer "*Completions*"
8676 (condition-case nil
8677 ;; Protection needed for XEmacs and emacs 21
8678 (display-completion-list list pattern)
8679 (error (display-completion-list list)))))
8680 (message "Making completion list...%s" "done")))))))
8682 ;;;; TODO, DEADLINE, Comments
8684 (defun org-toggle-comment ()
8685 "Change the COMMENT state of an entry."
8686 (interactive)
8687 (save-excursion
8688 (org-back-to-heading)
8689 (let (case-fold-search)
8690 (if (looking-at (concat outline-regexp
8691 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
8692 (replace-match "" t t nil 1)
8693 (if (looking-at outline-regexp)
8694 (progn
8695 (goto-char (match-end 0))
8696 (insert org-comment-string " ")))))))
8698 (defvar org-last-todo-state-is-todo nil
8699 "This is non-nil when the last TODO state change led to a TODO state.
8700 If the last change removed the TODO tag or switched to DONE, then
8701 this is nil.")
8703 (defvar org-setting-tags nil) ; dynamically skipped
8705 (defun org-parse-local-options (string var)
8706 "Parse STRING for startup setting relevant for variable VAR."
8707 (let ((rtn (symbol-value var))
8708 e opts)
8709 (save-match-data
8710 (if (or (not string) (not (string-match "\\S-" string)))
8712 (setq opts (delq nil (mapcar (lambda (x)
8713 (setq e (assoc x org-startup-options))
8714 (if (eq (nth 1 e) var) e nil))
8715 (org-split-string string "[ \t]+"))))
8716 (if (not opts)
8718 (setq rtn nil)
8719 (while (setq e (pop opts))
8720 (if (not (nth 3 e))
8721 (setq rtn (nth 2 e))
8722 (if (not (listp rtn)) (setq rtn nil))
8723 (push (nth 2 e) rtn)))
8724 rtn)))))
8726 (defvar org-todo-setup-filter-hook nil
8727 "Hook for functions that pre-filter todo specs.
8729 Each function takes a todo spec and returns either `nil' or the spec
8730 transformed into canonical form." )
8732 (defvar org-todo-get-default-hook nil
8733 "Hook for functions that get a default item for todo.
8735 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
8736 `nil' or a string to be used for the todo mark." )
8738 (defvar org-agenda-headline-snapshot-before-repeat)
8739 (defun org-todo (&optional arg)
8740 "Change the TODO state of an item.
8741 The state of an item is given by a keyword at the start of the heading,
8742 like
8743 *** TODO Write paper
8744 *** DONE Call mom
8746 The different keywords are specified in the variable `org-todo-keywords'.
8747 By default the available states are \"TODO\" and \"DONE\".
8748 So for this example: when the item starts with TODO, it is changed to DONE.
8749 When it starts with DONE, the DONE is removed. And when neither TODO nor
8750 DONE are present, add TODO at the beginning of the heading.
8752 With C-u prefix arg, use completion to determine the new state.
8753 With numeric prefix arg, switch to that state.
8754 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
8755 With a tripple C-u prefix, circumvent any state blocking.
8757 For calling through lisp, arg is also interpreted in the following way:
8758 'none -> empty state
8759 \"\"(empty string) -> switch to empty state
8760 'done -> switch to DONE
8761 'nextset -> switch to the next set of keywords
8762 'previousset -> switch to the previous set of keywords
8763 \"WAITING\" -> switch to the specified keyword, but only if it
8764 really is a member of `org-todo-keywords'."
8765 (interactive "P")
8766 (if (equal arg '(16)) (setq arg 'nextset))
8767 (let ((org-blocker-hook org-blocker-hook)
8768 (case-fold-search nil))
8769 (when (equal arg '(64))
8770 (setq arg nil org-blocker-hook nil))
8771 (save-excursion
8772 (catch 'exit
8773 (org-back-to-heading)
8774 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
8775 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|$\\)"))
8776 (looking-at " *"))
8777 (let* ((match-data (match-data))
8778 (startpos (point-at-bol))
8779 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
8780 (org-log-done org-log-done)
8781 (org-log-repeat org-log-repeat)
8782 (org-todo-log-states org-todo-log-states)
8783 (this (match-string 1))
8784 (hl-pos (match-beginning 0))
8785 (head (org-get-todo-sequence-head this))
8786 (ass (assoc head org-todo-kwd-alist))
8787 (interpret (nth 1 ass))
8788 (done-word (nth 3 ass))
8789 (final-done-word (nth 4 ass))
8790 (last-state (or this ""))
8791 (completion-ignore-case t)
8792 (member (member this org-todo-keywords-1))
8793 (tail (cdr member))
8794 (state (cond
8795 ((and org-todo-key-trigger
8796 (or (and (equal arg '(4))
8797 (eq org-use-fast-todo-selection 'prefix))
8798 (and (not arg) org-use-fast-todo-selection
8799 (not (eq org-use-fast-todo-selection
8800 'prefix)))))
8801 ;; Use fast selection
8802 (org-fast-todo-selection))
8803 ((and (equal arg '(4))
8804 (or (not org-use-fast-todo-selection)
8805 (not org-todo-key-trigger)))
8806 ;; Read a state with completion
8807 (org-ido-completing-read
8808 "State: " (mapcar (lambda(x) (list x))
8809 org-todo-keywords-1)
8810 nil t))
8811 ((eq arg 'right)
8812 (if this
8813 (if tail (car tail) nil)
8814 (car org-todo-keywords-1)))
8815 ((eq arg 'left)
8816 (if (equal member org-todo-keywords-1)
8818 (if this
8819 (nth (- (length org-todo-keywords-1)
8820 (length tail) 2)
8821 org-todo-keywords-1)
8822 (org-last org-todo-keywords-1))))
8823 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
8824 (setq arg nil))) ; hack to fall back to cycling
8825 (arg
8826 ;; user or caller requests a specific state
8827 (cond
8828 ((equal arg "") nil)
8829 ((eq arg 'none) nil)
8830 ((eq arg 'done) (or done-word (car org-done-keywords)))
8831 ((eq arg 'nextset)
8832 (or (car (cdr (member head org-todo-heads)))
8833 (car org-todo-heads)))
8834 ((eq arg 'previousset)
8835 (let ((org-todo-heads (reverse org-todo-heads)))
8836 (or (car (cdr (member head org-todo-heads)))
8837 (car org-todo-heads))))
8838 ((car (member arg org-todo-keywords-1)))
8839 ((nth (1- (prefix-numeric-value arg))
8840 org-todo-keywords-1))))
8841 ((null member) (or head (car org-todo-keywords-1)))
8842 ((equal this final-done-word) nil) ;; -> make empty
8843 ((null tail) nil) ;; -> first entry
8844 ((memq interpret '(type priority))
8845 (if (eq this-command last-command)
8846 (car tail)
8847 (if (> (length tail) 0)
8848 (or done-word (car org-done-keywords))
8849 nil)))
8851 (car tail))))
8852 (state (or
8853 (run-hook-with-args-until-success
8854 'org-todo-get-default-hook state last-state)
8855 state))
8856 (next (if state (concat " " state " ") " "))
8857 (change-plist (list :type 'todo-state-change :from this :to state
8858 :position startpos))
8859 dolog now-done-p)
8860 (when org-blocker-hook
8861 (setq org-last-todo-state-is-todo
8862 (not (member this org-done-keywords)))
8863 (unless (save-excursion
8864 (save-match-data
8865 (run-hook-with-args-until-failure
8866 'org-blocker-hook change-plist)))
8867 (if (interactive-p)
8868 (error "TODO state change from %s to %s blocked" this state)
8869 ;; fail silently
8870 (message "TODO state change from %s to %s blocked" this state)
8871 (throw 'exit nil))))
8872 (store-match-data match-data)
8873 (replace-match next t t)
8874 (unless (pos-visible-in-window-p hl-pos)
8875 (message "TODO state changed to %s" (org-trim next)))
8876 (unless head
8877 (setq head (org-get-todo-sequence-head state)
8878 ass (assoc head org-todo-kwd-alist)
8879 interpret (nth 1 ass)
8880 done-word (nth 3 ass)
8881 final-done-word (nth 4 ass)))
8882 (when (memq arg '(nextset previousset))
8883 (message "Keyword-Set %d/%d: %s"
8884 (- (length org-todo-sets) -1
8885 (length (memq (assoc state org-todo-sets) org-todo-sets)))
8886 (length org-todo-sets)
8887 (mapconcat 'identity (assoc state org-todo-sets) " ")))
8888 (setq org-last-todo-state-is-todo
8889 (not (member state org-done-keywords)))
8890 (setq now-done-p (and (member state org-done-keywords)
8891 (not (member this org-done-keywords))))
8892 (and logging (org-local-logging logging))
8893 (when (and (or org-todo-log-states org-log-done)
8894 (not (memq arg '(nextset previousset))))
8895 ;; we need to look at recording a time and note
8896 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
8897 (nth 2 (assoc this org-todo-log-states))))
8898 (when (and state
8899 (member state org-not-done-keywords)
8900 (not (member this org-not-done-keywords)))
8901 ;; This is now a todo state and was not one before
8902 ;; If there was a CLOSED time stamp, get rid of it.
8903 (org-add-planning-info nil nil 'closed))
8904 (when (and now-done-p org-log-done)
8905 ;; It is now done, and it was not done before
8906 (org-add-planning-info 'closed (org-current-time))
8907 (if (and (not dolog) (eq 'note org-log-done))
8908 (org-add-log-setup 'done state this 'findpos 'note)))
8909 (when (and state dolog)
8910 ;; This is a non-nil state, and we need to log it
8911 (org-add-log-setup 'state state this 'findpos dolog)))
8912 ;; Fixup tag positioning
8913 (org-todo-trigger-tag-changes state)
8914 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
8915 (when org-provide-todo-statistics
8916 (org-update-parent-todo-statistics))
8917 (run-hooks 'org-after-todo-state-change-hook)
8918 (if (and arg (not (member state org-done-keywords)))
8919 (setq head (org-get-todo-sequence-head state)))
8920 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
8921 ;; Do we need to trigger a repeat?
8922 (when now-done-p
8923 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
8924 ;; This is for the agenda, take a snapshot of the headline.
8925 (save-match-data
8926 (setq org-agenda-headline-snapshot-before-repeat
8927 (org-get-heading))))
8928 (org-auto-repeat-maybe state))
8929 ;; Fixup cursor location if close to the keyword
8930 (if (and (outline-on-heading-p)
8931 (not (bolp))
8932 (save-excursion (beginning-of-line 1)
8933 (looking-at org-todo-line-regexp))
8934 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
8935 (progn
8936 (goto-char (or (match-end 2) (match-end 1)))
8937 (and (looking-at " ") (just-one-space))))
8938 (when org-trigger-hook
8939 (save-excursion
8940 (run-hook-with-args 'org-trigger-hook change-plist))))))))
8942 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
8943 "Block turning an entry into a TODO, using the hierarchy.
8944 This checks whether the current task should be blocked from state
8945 changes. Such blocking occurs when:
8947 1. The task has children which are not all in a completed state.
8949 2. A task has a parent with the property :ORDERED:, and there
8950 are siblings prior to the current task with incomplete
8951 status.
8953 3. The parent of the task is blocked because it has siblings that should
8954 be done first, or is child of a block grandparent TODO entry."
8956 (catch 'dont-block
8957 ;; If this is not a todo state change, or if this entry is already DONE,
8958 ;; do not block
8959 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
8960 (member (plist-get change-plist :from)
8961 (cons 'done org-done-keywords))
8962 (member (plist-get change-plist :to)
8963 (cons 'todo org-not-done-keywords)))
8964 (throw 'dont-block t))
8965 ;; If this task has children, and any are undone, it's blocked
8966 (save-excursion
8967 (org-back-to-heading t)
8968 (let ((this-level (funcall outline-level)))
8969 (outline-next-heading)
8970 (let ((child-level (funcall outline-level)))
8971 (while (and (not (eobp))
8972 (> child-level this-level))
8973 ;; this todo has children, check whether they are all
8974 ;; completed
8975 (if (and (not (org-entry-is-done-p))
8976 (org-entry-is-todo-p))
8977 (throw 'dont-block nil))
8978 (outline-next-heading)
8979 (setq child-level (funcall outline-level))))))
8980 ;; Otherwise, if the task's parent has the :ORDERED: property, and
8981 ;; any previous siblings are undone, it's blocked
8982 (save-excursion
8983 (org-back-to-heading t)
8984 (let* ((pos (point))
8985 (parent-pos (and (org-up-heading-safe) (point))))
8986 (if (not parent-pos) (throw 'dont-block t)) ; no parent
8987 (when (and (org-entry-get (point) "ORDERED")
8988 (forward-line 1)
8989 (re-search-forward org-not-done-heading-regexp pos t))
8990 (throw 'dont-block nil)) ; block, there is an older sibling not done.
8991 ;; Search further up the hierarchy, to see if an anchestor is blocked
8992 (while t
8993 (goto-char parent-pos)
8994 (if (not (looking-at org-not-done-heading-regexp))
8995 (throw 'dont-block t)) ; do not block, parent is not a TODO
8996 (setq pos (point))
8997 (setq parent-pos (and (org-up-heading-safe) (point)))
8998 (if (not parent-pos) (throw 'dont-block t)) ; no parent
8999 (when (and (org-entry-get (point) "ORDERED")
9000 (forward-line 1)
9001 (re-search-forward org-not-done-heading-regexp pos t))
9002 (throw 'dont-block nil))))))) ; block, older sibling not done.
9004 (defcustom org-track-ordered-property-with-tag nil
9005 "Should the ORDERED property also be shown as a tag?
9006 The ORDERED property decides if an entry should require subtasks to be
9007 completed in sequence. Since a property is not very visible, setting
9008 this option means that toggling the ORDERED property with the command
9009 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
9010 not relevant for the behavior, but it makes things more visible.
9012 Note that toggling the tag with tags commands will not change the property
9013 and therefore not influence behavior!
9015 This can be t, meaning the tag ORDERED should be used, It can also be a
9016 string to select a different tag for this task."
9017 :group 'org-todo
9018 :type '(choice
9019 (const :tag "No tracking" nil)
9020 (const :tag "Track with ORDERED tag" t)
9021 (string :tag "Use other tag")))
9023 (defun org-toggle-ordered-property ()
9024 "Toggle the ORDERED property of the current entry.
9025 For better visibility, you can track the value of this property with a tag.
9026 See variable `org-track-ordered-property-with-tag'."
9027 (interactive)
9028 (let* ((t1 org-track-ordered-property-with-tag)
9029 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
9030 (save-excursion
9031 (org-back-to-heading)
9032 (if (org-entry-get nil "ORDERED")
9033 (progn
9034 (org-delete-property "ORDERED")
9035 (and tag (org-toggle-tag tag 'off))
9036 (message "Subtasks can be completed in arbitrary order"))
9037 (org-entry-put nil "ORDERED" "t")
9038 (and tag (org-toggle-tag tag 'on))
9039 (message "Subtasks must be completed in sequence")))))
9041 (defvar org-blocked-by-checkboxes) ; dynamically scoped
9042 (defun org-block-todo-from-checkboxes (change-plist)
9043 "Block turning an entry into a TODO, using checkboxes.
9044 This checks whether the current task should be blocked from state
9045 changes because there are uncheckd boxes in this entry."
9046 (catch 'dont-block
9047 ;; If this is not a todo state change, or if this entry is already DONE,
9048 ;; do not block
9049 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
9050 (member (plist-get change-plist :from)
9051 (cons 'done org-done-keywords))
9052 (member (plist-get change-plist :to)
9053 (cons 'todo org-not-done-keywords)))
9054 (throw 'dont-block t))
9055 ;; If this task has checkboxes that are not checked, it's blocked
9056 (save-excursion
9057 (org-back-to-heading t)
9058 (let ((beg (point)) end)
9059 (outline-next-heading)
9060 (setq end (point))
9061 (goto-char beg)
9062 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
9063 end t)
9064 (progn
9065 (if (boundp 'org-blocked-by-checkboxes)
9066 (setq org-blocked-by-checkboxes t))
9067 (throw 'dont-block nil)))))
9068 t)) ; do not block
9070 (defun org-update-parent-todo-statistics ()
9071 "Update any statistics cookie in the parent of the current headline."
9072 (interactive)
9073 (let ((box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
9074 level (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
9075 (catch 'exit
9076 (save-excursion
9077 (setq level (org-up-heading-safe))
9078 (unless level
9079 (throw 'exit nil))
9080 (while (re-search-forward box-re (point-at-eol) t)
9081 (setq cnt-all 0 cnt-done 0 cookie-present t)
9082 (setq is-percent (match-end 2))
9083 (save-match-data
9084 (unless (outline-next-heading) (throw 'exit nil))
9085 (while (looking-at org-todo-line-regexp)
9086 (setq kwd (match-string 2))
9087 (and kwd (setq cnt-all (1+ cnt-all)))
9088 (and (member kwd org-done-keywords)
9089 (setq cnt-done (1+ cnt-done)))
9090 (condition-case nil
9091 (org-forward-same-level 1)
9092 (error (end-of-line 1)))))
9093 (replace-match
9094 (if is-percent
9095 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
9096 (format "[%d/%d]" cnt-done cnt-all))))
9097 (when cookie-present
9098 (run-hook-with-args 'org-after-todo-statistics-hook
9099 cnt-done (- cnt-all cnt-done)))))))
9101 (defvar org-after-todo-statistics-hook nil
9102 "Hook that is called after a TODO statistics cookie has been updated.
9103 Each function is called with two arguments: the number of not-done entries
9104 and the number of done entries.
9106 For example, the following function, when added to this hook, will switch
9107 an entry to DONE when all children are done, and back to TODO when new
9108 entries are set to a TODO status. Note that this hook is only called
9109 when there is a statistics cookie in the headline!
9111 (defun org-summary-todo (n-done n-not-done)
9112 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
9113 (let (org-log-done org-log-states) ; turn off logging
9114 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
9117 (defun org-todo-trigger-tag-changes (state)
9118 "Apply the changes defined in `org-todo-state-tags-triggers'."
9119 (let ((l org-todo-state-tags-triggers)
9120 changes)
9121 (when (or (not state) (equal state ""))
9122 (setq changes (append changes (cdr (assoc "" l)))))
9123 (when (and (stringp state) (> (length state) 0))
9124 (setq changes (append changes (cdr (assoc state l)))))
9125 (when (member state org-not-done-keywords)
9126 (setq changes (append changes (cdr (assoc 'todo l)))))
9127 (when (member state org-done-keywords)
9128 (setq changes (append changes (cdr (assoc 'done l)))))
9129 (dolist (c changes)
9130 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
9132 (defun org-local-logging (value)
9133 "Get logging settings from a property VALUE."
9134 (let* (words w a)
9135 ;; directly set the variables, they are already local.
9136 (setq org-log-done nil
9137 org-log-repeat nil
9138 org-todo-log-states nil)
9139 (setq words (org-split-string value))
9140 (while (setq w (pop words))
9141 (cond
9142 ((setq a (assoc w org-startup-options))
9143 (and (member (nth 1 a) '(org-log-done org-log-repeat))
9144 (set (nth 1 a) (nth 2 a))))
9145 ((setq a (org-extract-log-state-settings w))
9146 (and (member (car a) org-todo-keywords-1)
9147 (push a org-todo-log-states)))))))
9149 (defun org-get-todo-sequence-head (kwd)
9150 "Return the head of the TODO sequence to which KWD belongs.
9151 If KWD is not set, check if there is a text property remembering the
9152 right sequence."
9153 (let (p)
9154 (cond
9155 ((not kwd)
9156 (or (get-text-property (point-at-bol) 'org-todo-head)
9157 (progn
9158 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
9159 nil (point-at-eol)))
9160 (get-text-property p 'org-todo-head))))
9161 ((not (member kwd org-todo-keywords-1))
9162 (car org-todo-keywords-1))
9163 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
9165 (defun org-fast-todo-selection ()
9166 "Fast TODO keyword selection with single keys.
9167 Returns the new TODO keyword, or nil if no state change should occur."
9168 (let* ((fulltable org-todo-key-alist)
9169 (done-keywords org-done-keywords) ;; needed for the faces.
9170 (maxlen (apply 'max (mapcar
9171 (lambda (x)
9172 (if (stringp (car x)) (string-width (car x)) 0))
9173 fulltable)))
9174 (expert nil)
9175 (fwidth (+ maxlen 3 1 3))
9176 (ncol (/ (- (window-width) 4) fwidth))
9177 tg cnt e c tbl
9178 groups ingroup)
9179 (save-excursion
9180 (save-window-excursion
9181 (if expert
9182 (set-buffer (get-buffer-create " *Org todo*"))
9183 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
9184 (erase-buffer)
9185 (org-set-local 'org-done-keywords done-keywords)
9186 (setq tbl fulltable cnt 0)
9187 (while (setq e (pop tbl))
9188 (cond
9189 ((equal e '(:startgroup))
9190 (push '() groups) (setq ingroup t)
9191 (when (not (= cnt 0))
9192 (setq cnt 0)
9193 (insert "\n"))
9194 (insert "{ "))
9195 ((equal e '(:endgroup))
9196 (setq ingroup nil cnt 0)
9197 (insert "}\n"))
9198 ((equal e '(:newline))
9199 (when (not (= cnt 0))
9200 (setq cnt 0)
9201 (insert "\n")
9202 (setq e (car tbl))
9203 (while (equal (car tbl) '(:newline))
9204 (insert "\n")
9205 (setq tbl (cdr tbl)))))
9207 (setq tg (car e) c (cdr e))
9208 (if ingroup (push tg (car groups)))
9209 (setq tg (org-add-props tg nil 'face
9210 (org-get-todo-face tg)))
9211 (if (and (= cnt 0) (not ingroup)) (insert " "))
9212 (insert "[" c "] " tg (make-string
9213 (- fwidth 4 (length tg)) ?\ ))
9214 (when (= (setq cnt (1+ cnt)) ncol)
9215 (insert "\n")
9216 (if ingroup (insert " "))
9217 (setq cnt 0)))))
9218 (insert "\n")
9219 (goto-char (point-min))
9220 (if (not expert) (org-fit-window-to-buffer))
9221 (message "[a-z..]:Set [SPC]:clear")
9222 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9223 (cond
9224 ((or (= c ?\C-g)
9225 (and (= c ?q) (not (rassoc c fulltable))))
9226 (setq quit-flag t))
9227 ((= c ?\ ) nil)
9228 ((setq e (rassoc c fulltable) tg (car e))
9230 (t (setq quit-flag t)))))))
9232 (defun org-entry-is-todo-p ()
9233 (member (org-get-todo-state) org-not-done-keywords))
9235 (defun org-entry-is-done-p ()
9236 (member (org-get-todo-state) org-done-keywords))
9238 (defun org-get-todo-state ()
9239 (save-excursion
9240 (org-back-to-heading t)
9241 (and (looking-at org-todo-line-regexp)
9242 (match-end 2)
9243 (match-string 2))))
9245 (defun org-at-date-range-p (&optional inactive-ok)
9246 "Is the cursor inside a date range?"
9247 (interactive)
9248 (save-excursion
9249 (catch 'exit
9250 (let ((pos (point)))
9251 (skip-chars-backward "^[<\r\n")
9252 (skip-chars-backward "<[")
9253 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
9254 (>= (match-end 0) pos)
9255 (throw 'exit t))
9256 (skip-chars-backward "^<[\r\n")
9257 (skip-chars-backward "<[")
9258 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
9259 (>= (match-end 0) pos)
9260 (throw 'exit t)))
9261 nil)))
9263 (defun org-get-repeat ()
9264 "Check if there is a deadline/schedule with repeater in this entry."
9265 (save-match-data
9266 (save-excursion
9267 (org-back-to-heading t)
9268 (if (re-search-forward
9269 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
9270 (match-string 1)))))
9272 (defvar org-last-changed-timestamp)
9273 (defvar org-last-inserted-timestamp)
9274 (defvar org-log-post-message)
9275 (defvar org-log-note-purpose)
9276 (defvar org-log-note-how)
9277 (defvar org-log-note-extra)
9278 (defun org-auto-repeat-maybe (done-word)
9279 "Check if the current headline contains a repeated deadline/schedule.
9280 If yes, set TODO state back to what it was and change the base date
9281 of repeating deadline/scheduled time stamps to new date.
9282 This function is run automatically after each state change to a DONE state."
9283 ;; last-state is dynamically scoped into this function
9284 (let* ((repeat (org-get-repeat))
9285 (aa (assoc last-state org-todo-kwd-alist))
9286 (interpret (nth 1 aa))
9287 (head (nth 2 aa))
9288 (whata '(("d" . day) ("m" . month) ("y" . year)))
9289 (msg "Entry repeats: ")
9290 (org-log-done nil)
9291 (org-todo-log-states nil)
9292 (nshiftmax 10) (nshift 0)
9293 re type n what ts time)
9294 (when repeat
9295 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
9296 (org-todo (if (eq interpret 'type) last-state head))
9297 (when org-log-repeat
9298 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
9299 (memq 'org-add-log-note post-command-hook))
9300 ;; OK, we are already setup for some record
9301 (if (eq org-log-repeat 'note)
9302 ;; make sure we take a note, not only a time stamp
9303 (setq org-log-note-how 'note))
9304 ;; Set up for taking a record
9305 (org-add-log-setup 'state (or done-word (car org-done-keywords))
9306 last-state
9307 'findpos org-log-repeat)))
9308 (org-back-to-heading t)
9309 (org-add-planning-info nil nil 'closed)
9310 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
9311 org-deadline-time-regexp "\\)\\|\\("
9312 org-ts-regexp "\\)"))
9313 (while (re-search-forward
9314 re (save-excursion (outline-next-heading) (point)) t)
9315 (setq type (if (match-end 1) org-scheduled-string
9316 (if (match-end 3) org-deadline-string "Plain:"))
9317 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
9318 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
9319 (setq n (string-to-number (match-string 2 ts))
9320 what (match-string 3 ts))
9321 (if (equal what "w") (setq n (* n 7) what "d"))
9322 ;; Preparation, see if we need to modify the start date for the change
9323 (when (match-end 1)
9324 (setq time (save-match-data (org-time-string-to-time ts)))
9325 (cond
9326 ((equal (match-string 1 ts) ".")
9327 ;; Shift starting date to today
9328 (org-timestamp-change
9329 (- (time-to-days (current-time)) (time-to-days time))
9330 'day))
9331 ((equal (match-string 1 ts) "+")
9332 (while (or (= nshift 0)
9333 (<= (time-to-days time) (time-to-days (current-time))))
9334 (when (= (incf nshift) nshiftmax)
9335 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
9336 (error "Abort")))
9337 (org-timestamp-change n (cdr (assoc what whata)))
9338 (org-at-timestamp-p t)
9339 (setq ts (match-string 1))
9340 (setq time (save-match-data (org-time-string-to-time ts))))
9341 (org-timestamp-change (- n) (cdr (assoc what whata)))
9342 ;; rematch, so that we have everything in place for the real shift
9343 (org-at-timestamp-p t)
9344 (setq ts (match-string 1))
9345 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
9346 (org-timestamp-change n (cdr (assoc what whata)))
9347 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
9348 (setq org-log-post-message msg)
9349 (message "%s" msg))))
9351 (defun org-show-todo-tree (arg)
9352 "Make a compact tree which shows all headlines marked with TODO.
9353 The tree will show the lines where the regexp matches, and all higher
9354 headlines above the match.
9355 With a \\[universal-argument] prefix, also show the DONE entries.
9356 With a numeric prefix N, construct a sparse tree for the Nth element
9357 of `org-todo-keywords-1'."
9358 (interactive "P")
9359 (let ((case-fold-search nil)
9360 (kwd-re
9361 (cond ((null arg) org-not-done-regexp)
9362 ((equal arg '(4))
9363 (let ((kwd (org-ido-completing-read "Keyword (or KWD1|KWD2|...): "
9364 (mapcar 'list org-todo-keywords-1))))
9365 (concat "\\("
9366 (mapconcat 'identity (org-split-string kwd "|") "\\|")
9367 "\\)\\>")))
9368 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
9369 (regexp-quote (nth (1- (prefix-numeric-value arg))
9370 org-todo-keywords-1)))
9371 (t (error "Invalid prefix argument: %s" arg)))))
9372 (message "%d TODO entries found"
9373 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
9375 (defun org-deadline (&optional remove time)
9376 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
9377 With argument REMOVE, remove any deadline from the item.
9378 When TIME is set, it should be an internal time specification, and the
9379 scheduling will use the corresponding date."
9380 (interactive "P")
9381 (if remove
9382 (progn
9383 (org-remove-timestamp-with-keyword org-deadline-string)
9384 (message "Item no longer has a deadline."))
9385 (if (org-get-repeat)
9386 (error "Cannot change deadline on task with repeater, please do that by hand")
9387 (org-add-planning-info 'deadline time 'closed)
9388 (message "Deadline on %s" org-last-inserted-timestamp))))
9390 (defun org-schedule (&optional remove time)
9391 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
9392 With argument REMOVE, remove any scheduling date from the item.
9393 When TIME is set, it should be an internal time specification, and the
9394 scheduling will use the corresponding date."
9395 (interactive "P")
9396 (if remove
9397 (progn
9398 (org-remove-timestamp-with-keyword org-scheduled-string)
9399 (message "Item is no longer scheduled."))
9400 (if (org-get-repeat)
9401 (error "Cannot reschedule task with repeater, please do that by hand")
9402 (org-add-planning-info 'scheduled time 'closed)
9403 (message "Scheduled to %s" org-last-inserted-timestamp))))
9405 (defun org-get-scheduled-time (pom &optional inherit)
9406 "Get the scheduled time as a time tuple, of a format suitable
9407 for calling org-schedule with, or if there is no scheduling,
9408 returns nil."
9409 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
9410 (when time
9411 (apply 'encode-time (org-parse-time-string time)))))
9413 (defun org-get-deadline-time (pom &optional inherit)
9414 "Get the deadine as a time tuple, of a format suitable for
9415 calling org-deadlin with, or if there is no scheduling, returns
9416 nil."
9417 (let ((time (org-entry-get pom "DEADLINE" inherit)))
9418 (when time
9419 (apply 'encode-time (org-parse-time-string time)))))
9421 (defun org-remove-timestamp-with-keyword (keyword)
9422 "Remove all time stamps with KEYWORD in the current entry."
9423 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
9424 beg)
9425 (save-excursion
9426 (org-back-to-heading t)
9427 (setq beg (point))
9428 (org-end-of-subtree t t)
9429 (while (re-search-backward re beg t)
9430 (replace-match "")
9431 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
9432 (equal (char-before) ?\ ))
9433 (backward-delete-char 1)
9434 (if (string-match "^[ \t]*$" (buffer-substring
9435 (point-at-bol) (point-at-eol)))
9436 (delete-region (point-at-bol)
9437 (min (point-max) (1+ (point-at-eol))))))))))
9439 (defun org-add-planning-info (what &optional time &rest remove)
9440 "Insert new timestamp with keyword in the line directly after the headline.
9441 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
9442 If non is given, the user is prompted for a date.
9443 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
9444 be removed."
9445 (interactive)
9446 (let (org-time-was-given org-end-time-was-given ts
9447 end default-time default-input)
9449 (catch 'exit
9450 (when (and (not time) (memq what '(scheduled deadline)))
9451 ;; Try to get a default date/time from existing timestamp
9452 (save-excursion
9453 (org-back-to-heading t)
9454 (setq end (save-excursion (outline-next-heading) (point)))
9455 (when (re-search-forward (if (eq what 'scheduled)
9456 org-scheduled-time-regexp
9457 org-deadline-time-regexp)
9458 end t)
9459 (setq ts (match-string 1)
9460 default-time
9461 (apply 'encode-time (org-parse-time-string ts))
9462 default-input (and ts (org-get-compact-tod ts))))))
9463 (when what
9464 ;; If necessary, get the time from the user
9465 (setq time (or time (org-read-date nil 'to-time nil nil
9466 default-time default-input))))
9468 (when (and org-insert-labeled-timestamps-at-point
9469 (member what '(scheduled deadline)))
9470 (insert
9471 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
9472 (org-insert-time-stamp time org-time-was-given
9473 nil nil nil (list org-end-time-was-given))
9474 (setq what nil))
9475 (save-excursion
9476 (save-restriction
9477 (let (col list elt ts buffer-invisibility-spec)
9478 (org-back-to-heading t)
9479 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
9480 (goto-char (match-end 1))
9481 (setq col (current-column))
9482 (goto-char (match-end 0))
9483 (if (eobp) (insert "\n") (forward-char 1))
9484 (when (and (not what)
9485 (not (looking-at
9486 (concat "[ \t]*"
9487 org-keyword-time-not-clock-regexp))))
9488 ;; Nothing to add, nothing to remove...... :-)
9489 (throw 'exit nil))
9490 (if (and (not (looking-at outline-regexp))
9491 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
9492 "[^\r\n]*"))
9493 (not (equal (match-string 1) org-clock-string)))
9494 (narrow-to-region (match-beginning 0) (match-end 0))
9495 (insert-before-markers "\n")
9496 (backward-char 1)
9497 (narrow-to-region (point) (point))
9498 (and org-adapt-indentation (org-indent-to-column col)))
9499 ;; Check if we have to remove something.
9500 (setq list (cons what remove))
9501 (while list
9502 (setq elt (pop list))
9503 (goto-char (point-min))
9504 (when (or (and (eq elt 'scheduled)
9505 (re-search-forward org-scheduled-time-regexp nil t))
9506 (and (eq elt 'deadline)
9507 (re-search-forward org-deadline-time-regexp nil t))
9508 (and (eq elt 'closed)
9509 (re-search-forward org-closed-time-regexp nil t)))
9510 (replace-match "")
9511 (if (looking-at "--+<[^>]+>") (replace-match ""))
9512 (if (looking-at " +") (replace-match ""))))
9513 (goto-char (point-max))
9514 (when what
9515 (insert
9516 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
9517 (cond ((eq what 'scheduled) org-scheduled-string)
9518 ((eq what 'deadline) org-deadline-string)
9519 ((eq what 'closed) org-closed-string))
9520 " ")
9521 (setq ts (org-insert-time-stamp
9522 time
9523 (or org-time-was-given
9524 (and (eq what 'closed) org-log-done-with-time))
9525 (eq what 'closed)
9526 nil nil (list org-end-time-was-given)))
9527 (end-of-line 1))
9528 (goto-char (point-min))
9529 (widen)
9530 (if (and (looking-at "[ \t]+\n")
9531 (equal (char-before) ?\n))
9532 (delete-region (1- (point)) (point-at-eol)))
9533 ts))))))
9535 (defvar org-log-note-marker (make-marker))
9536 (defvar org-log-note-purpose nil)
9537 (defvar org-log-note-state nil)
9538 (defvar org-log-note-previous-state nil)
9539 (defvar org-log-note-how nil)
9540 (defvar org-log-note-extra nil)
9541 (defvar org-log-note-window-configuration nil)
9542 (defvar org-log-note-return-to (make-marker))
9543 (defvar org-log-post-message nil
9544 "Message to be displayed after a log note has been stored.
9545 The auto-repeater uses this.")
9547 (defun org-add-note ()
9548 "Add a note to the current entry.
9549 This is done in the same way as adding a state change note."
9550 (interactive)
9551 (org-add-log-setup 'note nil nil 'findpos nil))
9553 (defvar org-property-end-re)
9554 (defun org-add-log-setup (&optional purpose state prev-state
9555 findpos how &optional extra)
9556 "Set up the post command hook to take a note.
9557 If this is about to TODO state change, the new state is expected in STATE.
9558 When FINDPOS is non-nil, find the correct position for the note in
9559 the current entry. If not, assume that it can be inserted at point.
9560 HOW is an indicator what kind of note should be created.
9561 EXTRA is additional text that will be inserted into the notes buffer."
9562 (let ((drawer (cond ((stringp org-log-into-drawer)
9563 org-log-into-drawer)
9564 (org-log-into-drawer "LOGBOOK")
9565 (t nil))))
9566 (save-restriction
9567 (save-excursion
9568 (when findpos
9569 (org-back-to-heading t)
9570 (narrow-to-region (point) (save-excursion
9571 (outline-next-heading) (point)))
9572 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
9573 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
9574 "[^\r\n]*\\)?"))
9575 (goto-char (match-end 0))
9576 (cond
9577 (drawer
9578 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
9579 nil t)
9580 (progn
9581 (goto-char (match-end 0))
9582 (or org-log-states-order-reversed
9583 (and (re-search-forward org-property-end-re nil t)
9584 (goto-char (1- (match-beginning 0))))))
9585 (insert "\n:" drawer ":\n:END:")
9586 (beginning-of-line 0)
9587 (org-indent-line-function)
9588 (beginning-of-line 2)
9589 (org-indent-line-function)
9590 (end-of-line 0)))
9591 ((and org-log-state-notes-insert-after-drawers
9592 (save-excursion
9593 (forward-line) (looking-at org-drawer-regexp)))
9594 (forward-line)
9595 (while (looking-at org-drawer-regexp)
9596 (goto-char (match-end 0))
9597 (re-search-forward org-property-end-re (point-max) t)
9598 (forward-line))
9599 (forward-line -1)))
9600 (unless org-log-states-order-reversed
9601 (and (= (char-after) ?\n) (forward-char 1))
9602 (org-skip-over-state-notes)
9603 (skip-chars-backward " \t\n\r")))
9604 (move-marker org-log-note-marker (point))
9605 (setq org-log-note-purpose purpose
9606 org-log-note-state state
9607 org-log-note-previous-state prev-state
9608 org-log-note-how how
9609 org-log-note-extra extra)
9610 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
9612 (defun org-skip-over-state-notes ()
9613 "Skip past the list of State notes in an entry."
9614 (if (looking-at "\n[ \t]*- State") (forward-char 1))
9615 (while (looking-at "[ \t]*- State")
9616 (condition-case nil
9617 (org-next-item)
9618 (error (org-end-of-item)))))
9620 (defun org-add-log-note (&optional purpose)
9621 "Pop up a window for taking a note, and add this note later at point."
9622 (remove-hook 'post-command-hook 'org-add-log-note)
9623 (setq org-log-note-window-configuration (current-window-configuration))
9624 (delete-other-windows)
9625 (move-marker org-log-note-return-to (point))
9626 (switch-to-buffer (marker-buffer org-log-note-marker))
9627 (goto-char org-log-note-marker)
9628 (org-switch-to-buffer-other-window "*Org Note*")
9629 (erase-buffer)
9630 (if (memq org-log-note-how '(time state))
9631 (let (current-prefix-arg) (org-store-log-note))
9632 (let ((org-inhibit-startup t)) (org-mode))
9633 (insert (format "# Insert note for %s.
9634 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
9635 (cond
9636 ((eq org-log-note-purpose 'clock-out) "stopped clock")
9637 ((eq org-log-note-purpose 'done) "closed todo item")
9638 ((eq org-log-note-purpose 'state)
9639 (format "state change from \"%s\" to \"%s\""
9640 (or org-log-note-previous-state "")
9641 (or org-log-note-state "")))
9642 ((eq org-log-note-purpose 'note)
9643 "this entry")
9644 (t (error "This should not happen")))))
9645 (if org-log-note-extra (insert org-log-note-extra))
9646 (org-set-local 'org-finish-function 'org-store-log-note)))
9648 (defvar org-note-abort nil) ; dynamically scoped
9649 (defun org-store-log-note ()
9650 "Finish taking a log note, and insert it to where it belongs."
9651 (let ((txt (buffer-string))
9652 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
9653 lines ind)
9654 (kill-buffer (current-buffer))
9655 (while (string-match "\\`#.*\n[ \t\n]*" txt)
9656 (setq txt (replace-match "" t t txt)))
9657 (if (string-match "\\s-+\\'" txt)
9658 (setq txt (replace-match "" t t txt)))
9659 (setq lines (org-split-string txt "\n"))
9660 (when (and note (string-match "\\S-" note))
9661 (setq note
9662 (org-replace-escapes
9663 note
9664 (list (cons "%u" (user-login-name))
9665 (cons "%U" user-full-name)
9666 (cons "%t" (format-time-string
9667 (org-time-stamp-format 'long 'inactive)
9668 (current-time)))
9669 (cons "%s" (if org-log-note-state
9670 (concat "\"" org-log-note-state "\"")
9671 ""))
9672 (cons "%S" (if org-log-note-previous-state
9673 (concat "\"" org-log-note-previous-state "\"")
9674 "\"\"")))))
9675 (if lines (setq note (concat note " \\\\")))
9676 (push note lines))
9677 (when (or current-prefix-arg org-note-abort)
9678 (when org-log-into-drawer
9679 (org-remove-empty-drawer-at
9680 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
9681 org-log-note-marker))
9682 (setq lines nil))
9683 (when lines
9684 (save-excursion
9685 (set-buffer (marker-buffer org-log-note-marker))
9686 (save-excursion
9687 (goto-char org-log-note-marker)
9688 (move-marker org-log-note-marker nil)
9689 (end-of-line 1)
9690 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
9691 (insert "- " (pop lines))
9692 (org-indent-line-function)
9693 (beginning-of-line 1)
9694 (looking-at "[ \t]*")
9695 (setq ind (concat (match-string 0) " "))
9696 (end-of-line 1)
9697 (while lines (insert "\n" ind (pop lines)))
9698 (message "Note stored")
9699 (org-back-to-heading t)
9700 (org-cycle-hide-drawers 'children)))))
9701 (set-window-configuration org-log-note-window-configuration)
9702 (with-current-buffer (marker-buffer org-log-note-return-to)
9703 (goto-char org-log-note-return-to))
9704 (move-marker org-log-note-return-to nil)
9705 (and org-log-post-message (message "%s" org-log-post-message)))
9707 (defun org-remove-empty-drawer-at (drawer pos)
9708 "Remove an emptyr DARWER drawer at position POS.
9709 POS may also be a marker."
9710 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
9711 (save-excursion
9712 (save-restriction
9713 (widen)
9714 (goto-char pos)
9715 (if (org-in-regexp
9716 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
9717 (replace-match ""))))))
9719 (defun org-sparse-tree (&optional arg)
9720 "Create a sparse tree, prompt for the details.
9721 This command can create sparse trees. You first need to select the type
9722 of match used to create the tree:
9724 t Show entries with a specific TODO keyword.
9725 m Show entries selected by a tags/property match.
9726 p Enter a property name and its value (both with completion on existing
9727 names/values) and show entries with that property.
9728 r Show entries matching a regular expression.
9729 d Show deadlines due within `org-deadline-warning-days'.
9730 b Show deadlines and scheduled items before a date.
9731 a Show deadlines and scheduled items after a date."
9732 (interactive "P")
9733 (let (ans kwd value)
9734 (message "Sparse tree: [/]regexp [t]odo-kwd [m]atch [p]roperty [d]eadlines [b]efore-date [a]fter-date")
9735 (setq ans (read-char-exclusive))
9736 (cond
9737 ((equal ans ?d)
9738 (call-interactively 'org-check-deadlines))
9739 ((equal ans ?b)
9740 (call-interactively 'org-check-before-date))
9741 ((equal ans ?a)
9742 (call-interactively 'org-check-after-date))
9743 ((equal ans ?t)
9744 (org-show-todo-tree '(4)))
9745 ((member ans '(?T ?m))
9746 (call-interactively 'org-match-sparse-tree))
9747 ((member ans '(?p ?P))
9748 (setq kwd (org-ido-completing-read "Property: "
9749 (mapcar 'list (org-buffer-property-keys))))
9750 (setq value (org-ido-completing-read "Value: "
9751 (mapcar 'list (org-property-values kwd))))
9752 (unless (string-match "\\`{.*}\\'" value)
9753 (setq value (concat "\"" value "\"")))
9754 (org-match-sparse-tree arg (concat kwd "=" value)))
9755 ((member ans '(?r ?R ?/))
9756 (call-interactively 'org-occur))
9757 (t (error "No such sparse tree command \"%c\"" ans)))))
9759 (defvar org-occur-highlights nil
9760 "List of overlays used for occur matches.")
9761 (make-variable-buffer-local 'org-occur-highlights)
9762 (defvar org-occur-parameters nil
9763 "Parameters of the active org-occur calls.
9764 This is a list, each call to org-occur pushes as cons cell,
9765 containing the regular expression and the callback, onto the list.
9766 The list can contain several entries if `org-occur' has been called
9767 several time with the KEEP-PREVIOUS argument. Otherwise, this list
9768 will only contain one set of parameters. When the highlights are
9769 removed (for example with `C-c C-c', or with the next edit (depending
9770 on `org-remove-highlights-with-change'), this variable is emptied
9771 as well.")
9772 (make-variable-buffer-local 'org-occur-parameters)
9774 (defun org-occur (regexp &optional keep-previous callback)
9775 "Make a compact tree which shows all matches of REGEXP.
9776 The tree will show the lines where the regexp matches, and all higher
9777 headlines above the match. It will also show the heading after the match,
9778 to make sure editing the matching entry is easy.
9779 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
9780 call to `org-occur' will be kept, to allow stacking of calls to this
9781 command.
9782 If CALLBACK is non-nil, it is a function which is called to confirm
9783 that the match should indeed be shown."
9784 (interactive "sRegexp: \nP")
9785 (unless keep-previous
9786 (org-remove-occur-highlights nil nil t))
9787 (push (cons regexp callback) org-occur-parameters)
9788 (let ((cnt 0))
9789 (save-excursion
9790 (goto-char (point-min))
9791 (if (or (not keep-previous) ; do not want to keep
9792 (not org-occur-highlights)) ; no previous matches
9793 ;; hide everything
9794 (org-overview))
9795 (while (re-search-forward regexp nil t)
9796 (when (or (not callback)
9797 (save-match-data (funcall callback)))
9798 (setq cnt (1+ cnt))
9799 (when org-highlight-sparse-tree-matches
9800 (org-highlight-new-match (match-beginning 0) (match-end 0)))
9801 (org-show-context 'occur-tree))))
9802 (when org-remove-highlights-with-change
9803 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
9804 nil 'local))
9805 (unless org-sparse-tree-open-archived-trees
9806 (org-hide-archived-subtrees (point-min) (point-max)))
9807 (run-hooks 'org-occur-hook)
9808 (if (interactive-p)
9809 (message "%d match(es) for regexp %s" cnt regexp))
9810 cnt))
9812 (defun org-show-context (&optional key)
9813 "Make sure point and context and visible.
9814 How much context is shown depends upon the variables
9815 `org-show-hierarchy-above', `org-show-following-heading'. and
9816 `org-show-siblings'."
9817 (let ((heading-p (org-on-heading-p t))
9818 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
9819 (following-p (org-get-alist-option org-show-following-heading key))
9820 (entry-p (org-get-alist-option org-show-entry-below key))
9821 (siblings-p (org-get-alist-option org-show-siblings key)))
9822 (catch 'exit
9823 ;; Show heading or entry text
9824 (if (and heading-p (not entry-p))
9825 (org-flag-heading nil) ; only show the heading
9826 (and (or entry-p (org-invisible-p) (org-invisible-p2))
9827 (org-show-hidden-entry))) ; show entire entry
9828 (when following-p
9829 ;; Show next sibling, or heading below text
9830 (save-excursion
9831 (and (if heading-p (org-goto-sibling) (outline-next-heading))
9832 (org-flag-heading nil))))
9833 (when siblings-p (org-show-siblings))
9834 (when hierarchy-p
9835 ;; show all higher headings, possibly with siblings
9836 (save-excursion
9837 (while (and (condition-case nil
9838 (progn (org-up-heading-all 1) t)
9839 (error nil))
9840 (not (bobp)))
9841 (org-flag-heading nil)
9842 (when siblings-p (org-show-siblings))))))))
9844 (defun org-reveal (&optional siblings)
9845 "Show current entry, hierarchy above it, and the following headline.
9846 This can be used to show a consistent set of context around locations
9847 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
9848 not t for the search context.
9850 With optional argument SIBLINGS, on each level of the hierarchy all
9851 siblings are shown. This repairs the tree structure to what it would
9852 look like when opened with hierarchical calls to `org-cycle'."
9853 (interactive "P")
9854 (let ((org-show-hierarchy-above t)
9855 (org-show-following-heading t)
9856 (org-show-siblings (if siblings t org-show-siblings)))
9857 (org-show-context nil)))
9859 (defun org-highlight-new-match (beg end)
9860 "Highlight from BEG to END and mark the highlight is an occur headline."
9861 (let ((ov (org-make-overlay beg end)))
9862 (org-overlay-put ov 'face 'secondary-selection)
9863 (push ov org-occur-highlights)))
9865 (defun org-remove-occur-highlights (&optional beg end noremove)
9866 "Remove the occur highlights from the buffer.
9867 BEG and END are ignored. If NOREMOVE is nil, remove this function
9868 from the `before-change-functions' in the current buffer."
9869 (interactive)
9870 (unless org-inhibit-highlight-removal
9871 (mapc 'org-delete-overlay org-occur-highlights)
9872 (setq org-occur-highlights nil)
9873 (setq org-occur-parameters nil)
9874 (unless noremove
9875 (remove-hook 'before-change-functions
9876 'org-remove-occur-highlights 'local))))
9878 ;;;; Priorities
9880 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
9881 "Regular expression matching the priority indicator.")
9883 (defvar org-remove-priority-next-time nil)
9885 (defun org-priority-up ()
9886 "Increase the priority of the current item."
9887 (interactive)
9888 (org-priority 'up))
9890 (defun org-priority-down ()
9891 "Decrease the priority of the current item."
9892 (interactive)
9893 (org-priority 'down))
9895 (defun org-priority (&optional action)
9896 "Change the priority of an item by ARG.
9897 ACTION can be `set', `up', `down', or a character."
9898 (interactive)
9899 (setq action (or action 'set))
9900 (let (current new news have remove)
9901 (save-excursion
9902 (org-back-to-heading t)
9903 (if (looking-at org-priority-regexp)
9904 (setq current (string-to-char (match-string 2))
9905 have t)
9906 (setq current org-default-priority))
9907 (cond
9908 ((or (eq action 'set)
9909 (if (featurep 'xemacs) (characterp action) (integerp action)))
9910 (if (not (eq action 'set))
9911 (setq new action)
9912 (message "Priority %c-%c, SPC to remove: "
9913 org-highest-priority org-lowest-priority)
9914 (setq new (read-char-exclusive)))
9915 (if (and (= (upcase org-highest-priority) org-highest-priority)
9916 (= (upcase org-lowest-priority) org-lowest-priority))
9917 (setq new (upcase new)))
9918 (cond ((equal new ?\ ) (setq remove t))
9919 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
9920 (error "Priority must be between `%c' and `%c'"
9921 org-highest-priority org-lowest-priority))))
9922 ((eq action 'up)
9923 (if (and (not have) (eq last-command this-command))
9924 (setq new org-lowest-priority)
9925 (setq new (if (and org-priority-start-cycle-with-default (not have))
9926 org-default-priority (1- current)))))
9927 ((eq action 'down)
9928 (if (and (not have) (eq last-command this-command))
9929 (setq new org-highest-priority)
9930 (setq new (if (and org-priority-start-cycle-with-default (not have))
9931 org-default-priority (1+ current)))))
9932 (t (error "Invalid action")))
9933 (if (or (< (upcase new) org-highest-priority)
9934 (> (upcase new) org-lowest-priority))
9935 (setq remove t))
9936 (setq news (format "%c" new))
9937 (if have
9938 (if remove
9939 (replace-match "" t t nil 1)
9940 (replace-match news t t nil 2))
9941 (if remove
9942 (error "No priority cookie found in line")
9943 (looking-at org-todo-line-regexp)
9944 (if (match-end 2)
9945 (progn
9946 (goto-char (match-end 2))
9947 (insert " [#" news "]"))
9948 (goto-char (match-beginning 3))
9949 (insert "[#" news "] ")))))
9950 (org-preserve-lc (org-set-tags nil 'align))
9951 (if remove
9952 (message "Priority removed")
9953 (message "Priority of current item set to %s" news))))
9956 (defun org-get-priority (s)
9957 "Find priority cookie and return priority."
9958 (save-match-data
9959 (if (not (string-match org-priority-regexp s))
9960 (* 1000 (- org-lowest-priority org-default-priority))
9961 (* 1000 (- org-lowest-priority
9962 (string-to-char (match-string 2 s)))))))
9964 ;;;; Tags
9966 (defvar org-agenda-archives-mode)
9967 (defvar org-map-continue-from nil
9968 "Position from where mapping should continue.
9969 Can be set byt the action argument to `org-scan-tag's and `org-map-entries'.")
9971 (defvar org-scanner-tags nil
9972 "The current tag list while the tags scanner is running.")
9973 (defvar org-trust-scanner-tags nil
9974 "Should `org-get-tags-at' use the tags fro the scanner.
9975 This is for internal dynamical scoping only.
9976 When this is non-nil, the function `org-get-tags-at' will return the value
9977 of `org-scanner-tags' instead of building the list by itself. This
9978 can lead to large speed-ups when the tags scanner is used in a file with
9979 many entries, and when the list of tags is retrieved, for example to
9980 obtain a list of properties. Building the tags list for each entry in such
9981 a file becomes an N^2 operation - but with this variable set, it scales
9982 as N.")
9984 (defun org-scan-tags (action matcher &optional todo-only)
9985 "Scan headline tags with inheritance and produce output ACTION.
9987 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
9988 or `agenda' to produce an entry list for an agenda view. It can also be
9989 a Lisp form or a function that should be called at each matched headline, in
9990 this case the return value is a list of all return values from these calls.
9992 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
9993 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
9994 only lines with a TODO keyword are included in the output."
9995 (require 'org-agenda)
9996 (let* ((re (concat "^" outline-regexp " *\\(\\<\\("
9997 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
9998 (org-re
9999 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
10000 (props (list 'face 'default
10001 'done-face 'org-agenda-done
10002 'undone-face 'default
10003 'mouse-face 'highlight
10004 'org-not-done-regexp org-not-done-regexp
10005 'org-todo-regexp org-todo-regexp
10006 'keymap org-agenda-keymap
10007 'help-echo
10008 (format "mouse-2 or RET jump to org file %s"
10009 (abbreviate-file-name
10010 (or (buffer-file-name (buffer-base-buffer))
10011 (buffer-name (buffer-base-buffer)))))))
10012 (case-fold-search nil)
10013 (org-map-continue-from nil)
10014 lspos tags tags-list
10015 (tags-alist (list (cons 0 org-file-tags)))
10016 (llast 0) rtn rtn1 level category i txt
10017 todo marker entry priority)
10018 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
10019 (setq action (list 'lambda nil action)))
10020 (save-excursion
10021 (goto-char (point-min))
10022 (when (eq action 'sparse-tree)
10023 (org-overview)
10024 (org-remove-occur-highlights))
10025 (while (re-search-forward re nil t)
10026 (catch :skip
10027 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
10028 tags (if (match-end 4) (org-match-string-no-properties 4)))
10029 (goto-char (setq lspos (match-beginning 0)))
10030 (setq level (org-reduced-level (funcall outline-level))
10031 category (org-get-category))
10032 (setq i llast llast level)
10033 ;; remove tag lists from same and sublevels
10034 (while (>= i level)
10035 (when (setq entry (assoc i tags-alist))
10036 (setq tags-alist (delete entry tags-alist)))
10037 (setq i (1- i)))
10038 ;; add the next tags
10039 (when tags
10040 (setq tags (org-split-string tags ":")
10041 tags-alist
10042 (cons (cons level tags) tags-alist)))
10043 ;; compile tags for current headline
10044 (setq tags-list
10045 (if org-use-tag-inheritance
10046 (apply 'append (mapcar 'cdr (reverse tags-alist)))
10047 tags)
10048 org-scanner-tags tags-list)
10049 (when org-use-tag-inheritance
10050 (setcdr (car tags-alist)
10051 (mapcar (lambda (x)
10052 (setq x (copy-sequence x))
10053 (org-add-prop-inherited x))
10054 (cdar tags-alist))))
10055 (when (and tags org-use-tag-inheritance
10056 (or (not (eq t org-use-tag-inheritance))
10057 org-tags-exclude-from-inheritance))
10058 ;; selective inheritance, remove uninherited ones
10059 (setcdr (car tags-alist)
10060 (org-remove-uniherited-tags (cdar tags-alist))))
10061 (when (and (or (not todo-only)
10062 (and (member todo org-not-done-keywords)
10063 (or (not org-agenda-tags-todo-honor-ignore-options)
10064 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
10065 (let ((case-fold-search t)) (eval matcher))
10067 (not (member org-archive-tag tags-list))
10068 ;; we have an archive tag, should we use this anyway?
10069 (or (not org-agenda-skip-archived-trees)
10070 (and (eq action 'agenda) org-agenda-archives-mode))))
10071 (unless (eq action 'sparse-tree) (org-agenda-skip))
10073 ;; select this headline
10075 (cond
10076 ((eq action 'sparse-tree)
10077 (and org-highlight-sparse-tree-matches
10078 (org-get-heading) (match-end 0)
10079 (org-highlight-new-match
10080 (match-beginning 0) (match-beginning 1)))
10081 (org-show-context 'tags-tree))
10082 ((eq action 'agenda)
10083 (setq txt (org-format-agenda-item
10085 (concat
10086 (if (eq org-tags-match-list-sublevels 'indented)
10087 (make-string (1- level) ?.) "")
10088 (org-get-heading))
10089 category
10090 tags-list
10092 priority (org-get-priority txt))
10093 (goto-char lspos)
10094 (setq marker (org-agenda-new-marker))
10095 (org-add-props txt props
10096 'org-marker marker 'org-hd-marker marker 'org-category category
10097 'todo-state todo
10098 'priority priority 'type "tagsmatch")
10099 (push txt rtn))
10100 ((functionp action)
10101 (setq org-map-continue-from nil)
10102 (save-excursion
10103 (setq rtn1 (funcall action))
10104 (push rtn1 rtn)))
10105 (t (error "Invalid action")))
10107 ;; if we are to skip sublevels, jump to end of subtree
10108 (unless org-tags-match-list-sublevels
10109 (org-end-of-subtree t)
10110 (backward-char 1))))
10111 ;; Get the correct position from where to continue
10112 (if org-map-continue-from
10113 (goto-char org-map-continue-from)
10114 (and (= (point) lspos) (end-of-line 1)))))
10115 (when (and (eq action 'sparse-tree)
10116 (not org-sparse-tree-open-archived-trees))
10117 (org-hide-archived-subtrees (point-min) (point-max)))
10118 (nreverse rtn)))
10120 (defun org-remove-uniherited-tags (tags)
10121 "Remove all tags that are not inherited from the list TAGS."
10122 (cond
10123 ((eq org-use-tag-inheritance t)
10124 (if org-tags-exclude-from-inheritance
10125 (org-delete-all org-tags-exclude-from-inheritance tags)
10126 tags))
10127 ((not org-use-tag-inheritance) nil)
10128 ((stringp org-use-tag-inheritance)
10129 (delq nil (mapcar
10130 (lambda (x)
10131 (if (and (string-match org-use-tag-inheritance x)
10132 (not (member x org-tags-exclude-from-inheritance)))
10133 x nil))
10134 tags)))
10135 ((listp org-use-tag-inheritance)
10136 (delq nil (mapcar
10137 (lambda (x)
10138 (if (member x org-use-tag-inheritance) x nil))
10139 tags)))))
10141 (defvar todo-only) ;; dynamically scoped
10143 (defun org-match-sparse-tree (&optional todo-only match)
10144 "Create a sparse tree according to tags string MATCH.
10145 MATCH can contain positive and negative selection of tags, like
10146 \"+WORK+URGENT-WITHBOSS\".
10147 If optional argument TODO-ONLY is non-nil, only select lines that are
10148 also TODO lines."
10149 (interactive "P")
10150 (org-prepare-agenda-buffers (list (current-buffer)))
10151 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
10153 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
10155 (defvar org-cached-props nil)
10156 (defun org-cached-entry-get (pom property)
10157 (if (or (eq t org-use-property-inheritance)
10158 (and (stringp org-use-property-inheritance)
10159 (string-match org-use-property-inheritance property))
10160 (and (listp org-use-property-inheritance)
10161 (member property org-use-property-inheritance)))
10162 ;; Caching is not possible, check it directly
10163 (org-entry-get pom property 'inherit)
10164 ;; Get all properties, so that we can do complicated checks easily
10165 (cdr (assoc property (or org-cached-props
10166 (setq org-cached-props
10167 (org-entry-properties pom)))))))
10169 (defun org-global-tags-completion-table (&optional files)
10170 "Return the list of all tags in all agenda buffer/files."
10171 (save-excursion
10172 (org-uniquify
10173 (delq nil
10174 (apply 'append
10175 (mapcar
10176 (lambda (file)
10177 (set-buffer (find-file-noselect file))
10178 (append (org-get-buffer-tags)
10179 (mapcar (lambda (x) (if (stringp (car-safe x))
10180 (list (car-safe x)) nil))
10181 org-tag-alist)))
10182 (if (and files (car files))
10183 files
10184 (org-agenda-files))))))))
10186 (defun org-make-tags-matcher (match)
10187 "Create the TAGS//TODO matcher form for the selection string MATCH."
10188 ;; todo-only is scoped dynamically into this function, and the function
10189 ;; may change it if the matcher asks for it.
10190 (unless match
10191 ;; Get a new match request, with completion
10192 (let ((org-last-tags-completion-table
10193 (org-global-tags-completion-table)))
10194 (setq match (org-completing-read-no-ido
10195 "Match: " 'org-tags-completion-function nil nil nil
10196 'org-tags-history))))
10198 ;; Parse the string and create a lisp form
10199 (let ((match0 match)
10200 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
10201 minus tag mm
10202 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
10203 orterms term orlist re-p str-p level-p level-op time-p
10204 prop-p pn pv po cat-p gv rest)
10205 (if (string-match "/+" match)
10206 ;; match contains also a todo-matching request
10207 (progn
10208 (setq tagsmatch (substring match 0 (match-beginning 0))
10209 todomatch (substring match (match-end 0)))
10210 (if (string-match "^!" todomatch)
10211 (setq todo-only t todomatch (substring todomatch 1)))
10212 (if (string-match "^\\s-*$" todomatch)
10213 (setq todomatch nil)))
10214 ;; only matching tags
10215 (setq tagsmatch match todomatch nil))
10217 ;; Make the tags matcher
10218 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
10219 (setq tagsmatcher t)
10220 (setq orterms (org-split-string tagsmatch "|") orlist nil)
10221 (while (setq term (pop orterms))
10222 (while (and (equal (substring term -1) "\\") orterms)
10223 (setq term (concat term "|" (pop orterms)))) ; repair bad split
10224 (while (string-match re term)
10225 (setq rest (substring term (match-end 0))
10226 minus (and (match-end 1)
10227 (equal (match-string 1 term) "-"))
10228 tag (match-string 2 term)
10229 re-p (equal (string-to-char tag) ?{)
10230 level-p (match-end 4)
10231 prop-p (match-end 5)
10232 mm (cond
10233 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
10234 (level-p
10235 (setq level-op (org-op-to-function (match-string 3 term)))
10236 `(,level-op level ,(string-to-number
10237 (match-string 4 term))))
10238 (prop-p
10239 (setq pn (match-string 5 term)
10240 po (match-string 6 term)
10241 pv (match-string 7 term)
10242 cat-p (equal pn "CATEGORY")
10243 re-p (equal (string-to-char pv) ?{)
10244 str-p (equal (string-to-char pv) ?\")
10245 time-p (save-match-data
10246 (string-match "^\"[[<].*[]>]\"$" pv))
10247 pv (if (or re-p str-p) (substring pv 1 -1) pv))
10248 (if time-p (setq pv (org-matcher-time pv)))
10249 (setq po (org-op-to-function po (if time-p 'time str-p)))
10250 (cond
10251 ((equal pn "CATEGORY")
10252 (setq gv '(get-text-property (point) 'org-category)))
10253 ((equal pn "TODO")
10254 (setq gv 'todo))
10256 (setq gv `(org-cached-entry-get nil ,pn))))
10257 (if re-p
10258 (if (eq po 'org<>)
10259 `(not (string-match ,pv (or ,gv "")))
10260 `(string-match ,pv (or ,gv "")))
10261 (if str-p
10262 `(,po (or ,gv "") ,pv)
10263 `(,po (string-to-number (or ,gv ""))
10264 ,(string-to-number pv) ))))
10265 (t `(member ,tag tags-list)))
10266 mm (if minus (list 'not mm) mm)
10267 term rest)
10268 (push mm tagsmatcher))
10269 (push (if (> (length tagsmatcher) 1)
10270 (cons 'and tagsmatcher)
10271 (car tagsmatcher))
10272 orlist)
10273 (setq tagsmatcher nil))
10274 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
10275 (setq tagsmatcher
10276 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
10277 ;; Make the todo matcher
10278 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
10279 (setq todomatcher t)
10280 (setq orterms (org-split-string todomatch "|") orlist nil)
10281 (while (setq term (pop orterms))
10282 (while (string-match re term)
10283 (setq minus (and (match-end 1)
10284 (equal (match-string 1 term) "-"))
10285 kwd (match-string 2 term)
10286 re-p (equal (string-to-char kwd) ?{)
10287 term (substring term (match-end 0))
10288 mm (if re-p
10289 `(string-match ,(substring kwd 1 -1) todo)
10290 (list 'equal 'todo kwd))
10291 mm (if minus (list 'not mm) mm))
10292 (push mm todomatcher))
10293 (push (if (> (length todomatcher) 1)
10294 (cons 'and todomatcher)
10295 (car todomatcher))
10296 orlist)
10297 (setq todomatcher nil))
10298 (setq todomatcher (if (> (length orlist) 1)
10299 (cons 'or orlist) (car orlist))))
10301 ;; Return the string and lisp forms of the matcher
10302 (setq matcher (if todomatcher
10303 (list 'and tagsmatcher todomatcher)
10304 tagsmatcher))
10305 (cons match0 matcher)))
10307 (defun org-op-to-function (op &optional stringp)
10308 "Turn an operator into the appropriate function."
10309 (setq op
10310 (cond
10311 ((equal op "<" ) '(< string< org-time<))
10312 ((equal op ">" ) '(> org-string> org-time>))
10313 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
10314 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
10315 ((member op '("=" "==")) '(= string= org-time=))
10316 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
10317 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
10319 (defun org<> (a b) (not (= a b)))
10320 (defun org-string<= (a b) (or (string= a b) (string< a b)))
10321 (defun org-string>= (a b) (not (string< a b)))
10322 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
10323 (defun org-string<> (a b) (not (string= a b)))
10324 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
10325 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
10326 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
10327 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
10328 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
10329 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
10330 (defun org-2ft (s)
10331 "Convert S to a floating point time.
10332 If S is already a number, just return it. If it is a string, parse
10333 it as a time string and apply `float-time' to it. If S is nil, just return 0."
10334 (cond
10335 ((numberp s) s)
10336 ((stringp s)
10337 (condition-case nil
10338 (float-time (apply 'encode-time (org-parse-time-string s)))
10339 (error 0.)))
10340 (t 0.)))
10342 (defun org-time-today ()
10343 "Time in seconds today at 0:00.
10344 Returns the float number of seconds since the beginning of the
10345 epoch to the beginning of today (00:00)."
10346 (float-time (apply 'encode-time
10347 (append '(0 0 0) (nthcdr 3 (decode-time))))))
10349 (defun org-matcher-time (s)
10350 "Interpret a time comparison value."
10351 (save-match-data
10352 (cond
10353 ((string= s "<now>") (float-time))
10354 ((string= s "<today>") (org-time-today))
10355 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
10356 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
10357 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
10358 (+ (org-time-today)
10359 (* (string-to-number (match-string 1 s))
10360 (cdr (assoc (match-string 2 s)
10361 '(("d" . 86400.0) ("w" . 604800.0)
10362 ("m" . 2678400.0) ("y" . 31557600.0)))))))
10363 (t (org-2ft s)))))
10365 (defun org-match-any-p (re list)
10366 "Does re match any element of list?"
10367 (setq list (mapcar (lambda (x) (string-match re x)) list))
10368 (delq nil list))
10370 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
10371 (defvar org-tags-overlay (org-make-overlay 1 1))
10372 (org-detach-overlay org-tags-overlay)
10374 (defun org-get-local-tags-at (&optional pos)
10375 "Get a list of tags defined in the current headline."
10376 (org-get-tags-at pos 'local))
10378 (defun org-get-local-tags ()
10379 "Get a list of tags defined in the current headline."
10380 (org-get-tags-at nil 'local))
10382 (defun org-get-tags-at (&optional pos local)
10383 "Get a list of all headline tags applicable at POS.
10384 POS defaults to point. If tags are inherited, the list contains
10385 the targets in the same sequence as the headlines appear, i.e.
10386 the tags of the current headline come last.
10387 When LOCAL is non-nil, only return tags from the current headline,
10388 ignore inherited ones."
10389 (interactive)
10390 (if (and org-trust-scanner-tags
10391 (or (not pos) (equal pos (point)))
10392 (not local))
10393 org-scanner-tags
10394 (let (tags ltags lastpos parent)
10395 (save-excursion
10396 (save-restriction
10397 (widen)
10398 (goto-char (or pos (point)))
10399 (save-match-data
10400 (catch 'done
10401 (condition-case nil
10402 (progn
10403 (org-back-to-heading t)
10404 (while (not (equal lastpos (point)))
10405 (setq lastpos (point))
10406 (when (looking-at
10407 (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
10408 (setq ltags (org-split-string
10409 (org-match-string-no-properties 1) ":"))
10410 (when parent
10411 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
10412 (setq tags (append
10413 (if parent
10414 (org-remove-uniherited-tags ltags)
10415 ltags)
10416 tags)))
10417 (or org-use-tag-inheritance (throw 'done t))
10418 (if local (throw 'done t))
10419 (org-up-heading-all 1)
10420 (setq parent t)))
10421 (error nil)))))
10422 (append (org-remove-uniherited-tags org-file-tags) tags)))))
10424 (defun org-add-prop-inherited (s)
10425 (add-text-properties 0 (length s) '(inherited t) s)
10428 (defun org-toggle-tag (tag &optional onoff)
10429 "Toggle the tag TAG for the current line.
10430 If ONOFF is `on' or `off', don't toggle but set to this state."
10431 (let (res current)
10432 (save-excursion
10433 (org-back-to-heading t)
10434 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
10435 (point-at-eol) t)
10436 (progn
10437 (setq current (match-string 1))
10438 (replace-match ""))
10439 (setq current ""))
10440 (setq current (nreverse (org-split-string current ":")))
10441 (cond
10442 ((eq onoff 'on)
10443 (setq res t)
10444 (or (member tag current) (push tag current)))
10445 ((eq onoff 'off)
10446 (or (not (member tag current)) (setq current (delete tag current))))
10447 (t (if (member tag current)
10448 (setq current (delete tag current))
10449 (setq res t)
10450 (push tag current))))
10451 (end-of-line 1)
10452 (if current
10453 (progn
10454 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
10455 (org-set-tags nil t))
10456 (delete-horizontal-space))
10457 (run-hooks 'org-after-tags-change-hook))
10458 res))
10460 (defun org-align-tags-here (to-col)
10461 ;; Assumes that this is a headline
10462 (let ((pos (point)) (col (current-column)) ncol tags-l p)
10463 (beginning-of-line 1)
10464 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10465 (< pos (match-beginning 2)))
10466 (progn
10467 (setq tags-l (- (match-end 2) (match-beginning 2)))
10468 (goto-char (match-beginning 1))
10469 (insert " ")
10470 (delete-region (point) (1+ (match-beginning 2)))
10471 (setq ncol (max (1+ (current-column))
10472 (1+ col)
10473 (if (> to-col 0)
10474 to-col
10475 (- (abs to-col) tags-l))))
10476 (setq p (point))
10477 (insert (make-string (- ncol (current-column)) ?\ ))
10478 (setq ncol (current-column))
10479 (when indent-tabs-mode (tabify p (point-at-eol)))
10480 (org-move-to-column (min ncol col) t))
10481 (goto-char pos))))
10483 (defun org-set-tags-command (&optional arg just-align)
10484 "Call the set-tags command for the current entry."
10485 (interactive "P")
10486 (if (org-on-heading-p)
10487 (org-set-tags arg just-align)
10488 (save-excursion
10489 (org-back-to-heading t)
10490 (org-set-tags arg just-align))))
10492 (defun org-set-tags (&optional arg just-align)
10493 "Set the tags for the current headline.
10494 With prefix ARG, realign all tags in headings in the current buffer."
10495 (interactive "P")
10496 (let* ((re (concat "^" outline-regexp))
10497 (current (org-get-tags-string))
10498 (col (current-column))
10499 (org-setting-tags t)
10500 table current-tags inherited-tags ; computed below when needed
10501 tags p0 c0 c1 rpl)
10502 (if arg
10503 (save-excursion
10504 (goto-char (point-min))
10505 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
10506 (while (re-search-forward re nil t)
10507 (org-set-tags nil t)
10508 (end-of-line 1)))
10509 (message "All tags realigned to column %d" org-tags-column))
10510 (if just-align
10511 (setq tags current)
10512 ;; Get a new set of tags from the user
10513 (save-excursion
10514 (setq table (append org-tag-persistent-alist
10515 (or org-tag-alist (org-get-buffer-tags)))
10516 org-last-tags-completion-table table
10517 current-tags (org-split-string current ":")
10518 inherited-tags (nreverse
10519 (nthcdr (length current-tags)
10520 (nreverse (org-get-tags-at))))
10521 tags
10522 (if (or (eq t org-use-fast-tag-selection)
10523 (and org-use-fast-tag-selection
10524 (delq nil (mapcar 'cdr table))))
10525 (org-fast-tag-selection
10526 current-tags inherited-tags table
10527 (if org-fast-tag-selection-include-todo org-todo-key-alist))
10528 (let ((org-add-colon-after-tag-completion t))
10529 (org-trim
10530 (org-without-partial-completion
10531 (org-ido-completing-read "Tags: " 'org-tags-completion-function
10532 nil nil current 'org-tags-history)))))))
10533 (while (string-match "[-+&]+" tags)
10534 ;; No boolean logic, just a list
10535 (setq tags (replace-match ":" t t tags))))
10537 (if (string-match "\\`[\t ]*\\'" tags)
10538 (setq tags "")
10539 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
10540 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
10542 ;; Insert new tags at the correct column
10543 (beginning-of-line 1)
10544 (cond
10545 ((and (equal current "") (equal tags "")))
10546 ((re-search-forward
10547 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
10548 (point-at-eol) t)
10549 (if (equal tags "")
10550 (setq rpl "")
10551 (goto-char (match-beginning 0))
10552 (setq c0 (current-column) p0 (point)
10553 c1 (max (1+ c0) (if (> org-tags-column 0)
10554 org-tags-column
10555 (- (- org-tags-column) (length tags))))
10556 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
10557 (replace-match rpl t t)
10558 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
10559 tags)
10560 (t (error "Tags alignment failed")))
10561 (org-move-to-column col)
10562 (unless just-align
10563 (run-hooks 'org-after-tags-change-hook)))))
10565 (defun org-change-tag-in-region (beg end tag off)
10566 "Add or remove TAG for each entry in the region.
10567 This works in the agenda, and also in an org-mode buffer."
10568 (interactive
10569 (list (region-beginning) (region-end)
10570 (let ((org-last-tags-completion-table
10571 (if (org-mode-p)
10572 (org-get-buffer-tags)
10573 (org-global-tags-completion-table))))
10574 (org-ido-completing-read
10575 "Tag: " 'org-tags-completion-function nil nil nil
10576 'org-tags-history))
10577 (progn
10578 (message "[s]et or [r]emove? ")
10579 (equal (read-char-exclusive) ?r))))
10580 (if (fboundp 'deactivate-mark) (deactivate-mark))
10581 (let ((agendap (equal major-mode 'org-agenda-mode))
10582 l1 l2 m buf pos newhead (cnt 0))
10583 (goto-char end)
10584 (setq l2 (1- (org-current-line)))
10585 (goto-char beg)
10586 (setq l1 (org-current-line))
10587 (loop for l from l1 to l2 do
10588 (goto-line l)
10589 (setq m (get-text-property (point) 'org-hd-marker))
10590 (when (or (and (org-mode-p) (org-on-heading-p))
10591 (and agendap m))
10592 (setq buf (if agendap (marker-buffer m) (current-buffer))
10593 pos (if agendap m (point)))
10594 (with-current-buffer buf
10595 (save-excursion
10596 (save-restriction
10597 (goto-char pos)
10598 (setq cnt (1+ cnt))
10599 (org-toggle-tag tag (if off 'off 'on))
10600 (setq newhead (org-get-heading)))))
10601 (and agendap (org-agenda-change-all-lines newhead m))))
10602 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
10604 (defun org-tags-completion-function (string predicate &optional flag)
10605 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
10606 (confirm (lambda (x) (stringp (car x)))))
10607 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
10608 (setq s1 (match-string 1 string)
10609 s2 (match-string 2 string))
10610 (setq s1 "" s2 string))
10611 (cond
10612 ((eq flag nil)
10613 ;; try completion
10614 (setq rtn (try-completion s2 ctable confirm))
10615 (if (stringp rtn)
10616 (setq rtn
10617 (concat s1 s2 (substring rtn (length s2))
10618 (if (and org-add-colon-after-tag-completion
10619 (assoc rtn ctable))
10620 ":" ""))))
10621 rtn)
10622 ((eq flag t)
10623 ;; all-completions
10624 (all-completions s2 ctable confirm)
10626 ((eq flag 'lambda)
10627 ;; exact match?
10628 (assoc s2 ctable)))
10631 (defun org-fast-tag-insert (kwd tags face &optional end)
10632 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
10633 (insert (format "%-12s" (concat kwd ":"))
10634 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
10635 (or end "")))
10637 (defun org-fast-tag-show-exit (flag)
10638 (save-excursion
10639 (goto-line 3)
10640 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
10641 (replace-match ""))
10642 (when flag
10643 (end-of-line 1)
10644 (org-move-to-column (- (window-width) 19) t)
10645 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
10647 (defun org-set-current-tags-overlay (current prefix)
10648 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
10649 (if (featurep 'xemacs)
10650 (org-overlay-display org-tags-overlay (concat prefix s)
10651 'secondary-selection)
10652 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
10653 (org-overlay-display org-tags-overlay (concat prefix s)))))
10655 (defun org-fast-tag-selection (current inherited table &optional todo-table)
10656 "Fast tag selection with single keys.
10657 CURRENT is the current list of tags in the headline, INHERITED is the
10658 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
10659 possibly with grouping information. TODO-TABLE is a similar table with
10660 TODO keywords, should these have keys assigned to them.
10661 If the keys are nil, a-z are automatically assigned.
10662 Returns the new tags string, or nil to not change the current settings."
10663 (let* ((fulltable (append table todo-table))
10664 (maxlen (apply 'max (mapcar
10665 (lambda (x)
10666 (if (stringp (car x)) (string-width (car x)) 0))
10667 fulltable)))
10668 (buf (current-buffer))
10669 (expert (eq org-fast-tag-selection-single-key 'expert))
10670 (buffer-tags nil)
10671 (fwidth (+ maxlen 3 1 3))
10672 (ncol (/ (- (window-width) 4) fwidth))
10673 (i-face 'org-done)
10674 (c-face 'org-todo)
10675 tg cnt e c char c1 c2 ntable tbl rtn
10676 ov-start ov-end ov-prefix
10677 (exit-after-next org-fast-tag-selection-single-key)
10678 (done-keywords org-done-keywords)
10679 groups ingroup)
10680 (save-excursion
10681 (beginning-of-line 1)
10682 (if (looking-at
10683 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10684 (setq ov-start (match-beginning 1)
10685 ov-end (match-end 1)
10686 ov-prefix "")
10687 (setq ov-start (1- (point-at-eol))
10688 ov-end (1+ ov-start))
10689 (skip-chars-forward "^\n\r")
10690 (setq ov-prefix
10691 (concat
10692 (buffer-substring (1- (point)) (point))
10693 (if (> (current-column) org-tags-column)
10695 (make-string (- org-tags-column (current-column)) ?\ ))))))
10696 (org-move-overlay org-tags-overlay ov-start ov-end)
10697 (save-window-excursion
10698 (if expert
10699 (set-buffer (get-buffer-create " *Org tags*"))
10700 (delete-other-windows)
10701 (split-window-vertically)
10702 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
10703 (erase-buffer)
10704 (org-set-local 'org-done-keywords done-keywords)
10705 (org-fast-tag-insert "Inherited" inherited i-face "\n")
10706 (org-fast-tag-insert "Current" current c-face "\n\n")
10707 (org-fast-tag-show-exit exit-after-next)
10708 (org-set-current-tags-overlay current ov-prefix)
10709 (setq tbl fulltable char ?a cnt 0)
10710 (while (setq e (pop tbl))
10711 (cond
10712 ((equal e '(:startgroup))
10713 (push '() groups) (setq ingroup t)
10714 (when (not (= cnt 0))
10715 (setq cnt 0)
10716 (insert "\n"))
10717 (insert "{ "))
10718 ((equal e '(:endgroup))
10719 (setq ingroup nil cnt 0)
10720 (insert "}\n"))
10721 ((equal e '(:newline))
10722 (when (not (= cnt 0))
10723 (setq cnt 0)
10724 (insert "\n")
10725 (setq e (car tbl))
10726 (while (equal (car tbl) '(:newline))
10727 (insert "\n")
10728 (setq tbl (cdr tbl)))))
10730 (setq tg (car e) c2 nil)
10731 (if (cdr e)
10732 (setq c (cdr e))
10733 ;; automatically assign a character.
10734 (setq c1 (string-to-char
10735 (downcase (substring
10736 tg (if (= (string-to-char tg) ?@) 1 0)))))
10737 (if (or (rassoc c1 ntable) (rassoc c1 table))
10738 (while (or (rassoc char ntable) (rassoc char table))
10739 (setq char (1+ char)))
10740 (setq c2 c1))
10741 (setq c (or c2 char)))
10742 (if ingroup (push tg (car groups)))
10743 (setq tg (org-add-props tg nil 'face
10744 (cond
10745 ((not (assoc tg table))
10746 (org-get-todo-face tg))
10747 ((member tg current) c-face)
10748 ((member tg inherited) i-face)
10749 (t nil))))
10750 (if (and (= cnt 0) (not ingroup)) (insert " "))
10751 (insert "[" c "] " tg (make-string
10752 (- fwidth 4 (length tg)) ?\ ))
10753 (push (cons tg c) ntable)
10754 (when (= (setq cnt (1+ cnt)) ncol)
10755 (insert "\n")
10756 (if ingroup (insert " "))
10757 (setq cnt 0)))))
10758 (setq ntable (nreverse ntable))
10759 (insert "\n")
10760 (goto-char (point-min))
10761 (if (not expert) (org-fit-window-to-buffer))
10762 (setq rtn
10763 (catch 'exit
10764 (while t
10765 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
10766 (if groups " [!] no groups" " [!]groups")
10767 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
10768 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
10769 (cond
10770 ((= c ?\r) (throw 'exit t))
10771 ((= c ?!)
10772 (setq groups (not groups))
10773 (goto-char (point-min))
10774 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
10775 ((= c ?\C-c)
10776 (if (not expert)
10777 (org-fast-tag-show-exit
10778 (setq exit-after-next (not exit-after-next)))
10779 (setq expert nil)
10780 (delete-other-windows)
10781 (split-window-vertically)
10782 (org-switch-to-buffer-other-window " *Org tags*")
10783 (org-fit-window-to-buffer)))
10784 ((or (= c ?\C-g)
10785 (and (= c ?q) (not (rassoc c ntable))))
10786 (org-detach-overlay org-tags-overlay)
10787 (setq quit-flag t))
10788 ((= c ?\ )
10789 (setq current nil)
10790 (if exit-after-next (setq exit-after-next 'now)))
10791 ((= c ?\t)
10792 (condition-case nil
10793 (setq tg (org-ido-completing-read
10794 "Tag: "
10795 (or buffer-tags
10796 (with-current-buffer buf
10797 (org-get-buffer-tags)))))
10798 (quit (setq tg "")))
10799 (when (string-match "\\S-" tg)
10800 (add-to-list 'buffer-tags (list tg))
10801 (if (member tg current)
10802 (setq current (delete tg current))
10803 (push tg current)))
10804 (if exit-after-next (setq exit-after-next 'now)))
10805 ((setq e (rassoc c todo-table) tg (car e))
10806 (with-current-buffer buf
10807 (save-excursion (org-todo tg)))
10808 (if exit-after-next (setq exit-after-next 'now)))
10809 ((setq e (rassoc c ntable) tg (car e))
10810 (if (member tg current)
10811 (setq current (delete tg current))
10812 (loop for g in groups do
10813 (if (member tg g)
10814 (mapc (lambda (x)
10815 (setq current (delete x current)))
10816 g)))
10817 (push tg current))
10818 (if exit-after-next (setq exit-after-next 'now))))
10820 ;; Create a sorted list
10821 (setq current
10822 (sort current
10823 (lambda (a b)
10824 (assoc b (cdr (memq (assoc a ntable) ntable))))))
10825 (if (eq exit-after-next 'now) (throw 'exit t))
10826 (goto-char (point-min))
10827 (beginning-of-line 2)
10828 (delete-region (point) (point-at-eol))
10829 (org-fast-tag-insert "Current" current c-face)
10830 (org-set-current-tags-overlay current ov-prefix)
10831 (while (re-search-forward
10832 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
10833 (setq tg (match-string 1))
10834 (add-text-properties
10835 (match-beginning 1) (match-end 1)
10836 (list 'face
10837 (cond
10838 ((member tg current) c-face)
10839 ((member tg inherited) i-face)
10840 (t (get-text-property (match-beginning 1) 'face))))))
10841 (goto-char (point-min)))))
10842 (org-detach-overlay org-tags-overlay)
10843 (if rtn
10844 (mapconcat 'identity current ":")
10845 nil))))
10847 (defun org-get-tags-string ()
10848 "Get the TAGS string in the current headline."
10849 (unless (org-on-heading-p t)
10850 (error "Not on a heading"))
10851 (save-excursion
10852 (beginning-of-line 1)
10853 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10854 (org-match-string-no-properties 1)
10855 "")))
10857 (defun org-get-tags ()
10858 "Get the list of tags specified in the current headline."
10859 (org-split-string (org-get-tags-string) ":"))
10861 (defun org-get-buffer-tags ()
10862 "Get a table of all tags used in the buffer, for completion."
10863 (let (tags)
10864 (save-excursion
10865 (goto-char (point-min))
10866 (while (re-search-forward
10867 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
10868 (when (equal (char-after (point-at-bol 0)) ?*)
10869 (mapc (lambda (x) (add-to-list 'tags x))
10870 (org-split-string (org-match-string-no-properties 1) ":")))))
10871 (mapcar 'list tags)))
10873 ;;;; The mapping API
10875 ;;;###autoload
10876 (defun org-map-entries (func &optional match scope &rest skip)
10877 "Call FUNC at each headline selected by MATCH in SCOPE.
10879 FUNC is a function or a lisp form. The function will be called without
10880 arguments, with the cursor positioned at the beginning of the headline.
10881 The return values of all calls to the function will be collected and
10882 returned as a list.
10884 The call to FUNC will be wrapped into a save-excursion form, so FUNC
10885 does not need to preserve point. After evaluaton, the cursor will be
10886 moved to the end of the line (presumably of the headline of the
10887 processed entry) and search continues from there. Under some
10888 circumstances, this may not produce the wanted results. For example,
10889 if you have removed (e.g. archived) the current (sub)tree it could
10890 mean that the next entry will be skipped entirely. In such cases, you
10891 can specify the position from where search should continue by making
10892 FUNC set the variable `org-map-continue-from' to the desired buffer
10893 position.
10895 MATCH is a tags/property/todo match as it is used in the agenda tags view.
10896 Only headlines that are matched by this query will be considered during
10897 the iteration. When MATCH is nil or t, all headlines will be
10898 visited by the iteration.
10900 SCOPE determines the scope of this command. It can be any of:
10902 nil The current buffer, respecting the restriction if any
10903 tree The subtree started with the entry at point
10904 file The current buffer, without restriction
10905 file-with-archives
10906 The current buffer, and any archives associated with it
10907 agenda All agenda files
10908 agenda-with-archives
10909 All agenda files with any archive files associated with them
10910 \(file1 file2 ...)
10911 If this is a list, all files in the list will be scanned
10913 The remaining args are treated as settings for the skipping facilities of
10914 the scanner. The following items can be given here:
10916 archive skip trees with the archive tag.
10917 comment skip trees with the COMMENT keyword
10918 function or Emacs Lisp form:
10919 will be used as value for `org-agenda-skip-function', so whenever
10920 the the function returns t, FUNC will not be called for that
10921 entry and search will continue from the point where the
10922 function leaves it.
10924 If your function needs to retrieve the tags including inherited tags
10925 at the *current* entry, you can use the value of the variable
10926 `org-scanner-tags' which will be much faster than getting the value
10927 with `org-get-tags-at'. If your function gets properties with
10928 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
10929 to t around the call to `org-entry-properties' to get the same speedup.
10930 Note that if your function moves around to retrieve tags and properties at
10931 a *different* entry, you cannot use these techniques."
10932 (let* ((org-agenda-archives-mode nil) ; just to make sure
10933 (org-agenda-skip-archived-trees (memq 'archive skip))
10934 (org-agenda-skip-comment-trees (memq 'comment skip))
10935 (org-agenda-skip-function
10936 (car (org-delete-all '(comment archive) skip)))
10937 (org-tags-match-list-sublevels t)
10938 matcher file res
10939 org-todo-keywords-for-agenda
10940 org-done-keywords-for-agenda
10941 org-todo-keyword-alist-for-agenda
10942 org-tag-alist-for-agenda)
10944 (cond
10945 ((eq match t) (setq matcher t))
10946 ((eq match nil) (setq matcher t))
10947 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
10949 (save-excursion
10950 (save-restriction
10951 (when (eq scope 'tree)
10952 (org-back-to-heading t)
10953 (org-narrow-to-subtree)
10954 (setq scope nil))
10956 (if (not scope)
10957 (progn
10958 (org-prepare-agenda-buffers
10959 (list (buffer-file-name (current-buffer))))
10960 (setq res (org-scan-tags func matcher)))
10961 ;; Get the right scope
10962 (cond
10963 ((and scope (listp scope) (symbolp (car scope)))
10964 (setq scope (eval scope)))
10965 ((eq scope 'agenda)
10966 (setq scope (org-agenda-files t)))
10967 ((eq scope 'agenda-with-archives)
10968 (setq scope (org-agenda-files t))
10969 (setq scope (org-add-archive-files scope)))
10970 ((eq scope 'file)
10971 (setq scope (list (buffer-file-name))))
10972 ((eq scope 'file-with-archives)
10973 (setq scope (org-add-archive-files (list (buffer-file-name))))))
10974 (org-prepare-agenda-buffers scope)
10975 (while (setq file (pop scope))
10976 (with-current-buffer (org-find-base-buffer-visiting file)
10977 (save-excursion
10978 (save-restriction
10979 (widen)
10980 (goto-char (point-min))
10981 (setq res (append res (org-scan-tags func matcher))))))))))
10982 res))
10984 ;;;; Properties
10986 ;;; Setting and retrieving properties
10988 (defconst org-special-properties
10989 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
10990 "TIMESTAMP" "TIMESTAMP_IA")
10991 "The special properties valid in Org-mode.
10993 These are properties that are not defined in the property drawer,
10994 but in some other way.")
10996 (defconst org-default-properties
10997 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
10998 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
10999 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
11000 "EXPORT_FILE_NAME" "EXPORT_TITLE" "ORDERED")
11001 "Some properties that are used by Org-mode for various purposes.
11002 Being in this list makes sure that they are offered for completion.")
11004 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
11005 "Regular expression matching the first line of a property drawer.")
11007 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
11008 "Regular expression matching the first line of a property drawer.")
11010 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
11011 "Regular expression matching the first line of a property drawer.")
11013 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
11014 "Regular expression matching the first line of a property drawer.")
11016 (defconst org-property-drawer-re
11017 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
11018 org-property-end-re "\\)\n?")
11019 "Matches an entire property drawer.")
11021 (defconst org-clock-drawer-re
11022 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
11023 org-property-end-re "\\)\n?")
11024 "Matches an entire clock drawer.")
11026 (defun org-property-action ()
11027 "Do an action on properties."
11028 (interactive)
11029 (let (c)
11030 (org-at-property-p)
11031 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
11032 (setq c (read-char-exclusive))
11033 (cond
11034 ((equal c ?s)
11035 (call-interactively 'org-set-property))
11036 ((equal c ?d)
11037 (call-interactively 'org-delete-property))
11038 ((equal c ?D)
11039 (call-interactively 'org-delete-property-globally))
11040 ((equal c ?c)
11041 (call-interactively 'org-compute-property-at-point))
11042 (t (error "No such property action %c" c)))))
11044 (defun org-at-property-p ()
11045 "Is the cursor in a property line?"
11046 ;; FIXME: Does not check if we are actually in the drawer.
11047 ;; FIXME: also returns true on any drawers.....
11048 ;; This is used by C-c C-c for property action.
11049 (save-excursion
11050 (beginning-of-line 1)
11051 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
11053 (defun org-get-property-block (&optional beg end force)
11054 "Return the (beg . end) range of the body of the property drawer.
11055 BEG and END can be beginning and end of subtree, if not given
11056 they will be found.
11057 If the drawer does not exist and FORCE is non-nil, create the drawer."
11058 (catch 'exit
11059 (save-excursion
11060 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
11061 (end (or end (progn (outline-next-heading) (point)))))
11062 (goto-char beg)
11063 (if (re-search-forward org-property-start-re end t)
11064 (setq beg (1+ (match-end 0)))
11065 (if force
11066 (save-excursion
11067 (org-insert-property-drawer)
11068 (setq end (progn (outline-next-heading) (point))))
11069 (throw 'exit nil))
11070 (goto-char beg)
11071 (if (re-search-forward org-property-start-re end t)
11072 (setq beg (1+ (match-end 0)))))
11073 (if (re-search-forward org-property-end-re end t)
11074 (setq end (match-beginning 0))
11075 (or force (throw 'exit nil))
11076 (goto-char beg)
11077 (setq end beg)
11078 (org-indent-line-function)
11079 (insert ":END:\n"))
11080 (cons beg end)))))
11082 (defun org-entry-properties (&optional pom which)
11083 "Get all properties of the entry at point-or-marker POM.
11084 This includes the TODO keyword, the tags, time strings for deadline,
11085 scheduled, and clocking, and any additional properties defined in the
11086 entry. The return value is an alist, keys may occur multiple times
11087 if the property key was used several times.
11088 POM may also be nil, in which case the current entry is used.
11089 If WHICH is nil or `all', get all properties. If WHICH is
11090 `special' or `standard', only get that subclass."
11091 (setq which (or which 'all))
11092 (org-with-point-at pom
11093 (let ((clockstr (substring org-clock-string 0 -1))
11094 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
11095 beg end range props sum-props key value string clocksum)
11096 (save-excursion
11097 (when (condition-case nil
11098 (and (org-mode-p) (org-back-to-heading t))
11099 (error nil))
11100 (setq beg (point))
11101 (setq sum-props (get-text-property (point) 'org-summaries))
11102 (setq clocksum (get-text-property (point) :org-clock-minutes))
11103 (outline-next-heading)
11104 (setq end (point))
11105 (when (memq which '(all special))
11106 ;; Get the special properties, like TODO and tags
11107 (goto-char beg)
11108 (when (and (looking-at org-todo-line-regexp) (match-end 2))
11109 (push (cons "TODO" (org-match-string-no-properties 2)) props))
11110 (when (looking-at org-priority-regexp)
11111 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
11112 (when (and (setq value (org-get-tags-string))
11113 (string-match "\\S-" value))
11114 (push (cons "TAGS" value) props))
11115 (when (setq value (org-get-tags-at))
11116 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
11117 props))
11118 (while (re-search-forward org-maybe-keyword-time-regexp end t)
11119 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
11120 string (if (equal key clockstr)
11121 (org-no-properties
11122 (org-trim
11123 (buffer-substring
11124 (match-beginning 3) (goto-char (point-at-eol)))))
11125 (substring (org-match-string-no-properties 3) 1 -1)))
11126 (unless key
11127 (if (= (char-after (match-beginning 3)) ?\[)
11128 (setq key "TIMESTAMP_IA")
11129 (setq key "TIMESTAMP")))
11130 (when (or (equal key clockstr) (not (assoc key props)))
11131 (push (cons key string) props)))
11135 (when (memq which '(all standard))
11136 ;; Get the standard properties, like :PROP: ...
11137 (setq range (org-get-property-block beg end))
11138 (when range
11139 (goto-char (car range))
11140 (while (re-search-forward
11141 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
11142 (cdr range) t)
11143 (setq key (org-match-string-no-properties 1)
11144 value (org-trim (or (org-match-string-no-properties 2) "")))
11145 (unless (member key excluded)
11146 (push (cons key (or value "")) props)))))
11147 (if clocksum
11148 (push (cons "CLOCKSUM"
11149 (org-columns-number-to-string (/ (float clocksum) 60.)
11150 'add_times))
11151 props))
11152 (unless (assoc "CATEGORY" props)
11153 (setq value (or (org-get-category)
11154 (progn (org-refresh-category-properties)
11155 (org-get-category))))
11156 (push (cons "CATEGORY" value) props))
11157 (append sum-props (nreverse props)))))))
11159 (defun org-entry-get (pom property &optional inherit)
11160 "Get value of PROPERTY for entry at point-or-marker POM.
11161 If INHERIT is non-nil and the entry does not have the property,
11162 then also check higher levels of the hierarchy.
11163 If INHERIT is the symbol `selective', use inheritance only if the setting
11164 in `org-use-property-inheritance' selects PROPERTY for inheritance.
11165 If the property is present but empty, the return value is the empty string.
11166 If the property is not present at all, nil is returned."
11167 (org-with-point-at pom
11168 (if (and inherit (if (eq inherit 'selective)
11169 (org-property-inherit-p property)
11171 (org-entry-get-with-inheritance property)
11172 (if (member property org-special-properties)
11173 ;; We need a special property. Use brute force, get all properties.
11174 (cdr (assoc property (org-entry-properties nil 'special)))
11175 (let ((range (org-get-property-block)))
11176 (if (and range
11177 (goto-char (car range))
11178 (re-search-forward
11179 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
11180 (cdr range) t))
11181 ;; Found the property, return it.
11182 (if (match-end 1)
11183 (org-match-string-no-properties 1)
11184 "")))))))
11186 (defun org-property-or-variable-value (var &optional inherit)
11187 "Check if there is a property fixing the value of VAR.
11188 If yes, return this value. If not, return the current value of the variable."
11189 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
11190 (if (and prop (stringp prop) (string-match "\\S-" prop))
11191 (read prop)
11192 (symbol-value var))))
11194 (defun org-entry-delete (pom property)
11195 "Delete the property PROPERTY from entry at point-or-marker POM."
11196 (org-with-point-at pom
11197 (if (member property org-special-properties)
11198 nil ; cannot delete these properties.
11199 (let ((range (org-get-property-block)))
11200 (if (and range
11201 (goto-char (car range))
11202 (re-search-forward
11203 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
11204 (cdr range) t))
11205 (progn
11206 (delete-region (match-beginning 0) (1+ (point-at-eol)))
11208 nil)))))
11210 ;; Multi-values properties are properties that contain multiple values
11211 ;; These values are assumed to be single words, separated by whitespace.
11212 (defun org-entry-add-to-multivalued-property (pom property value)
11213 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
11214 (let* ((old (org-entry-get pom property))
11215 (values (and old (org-split-string old "[ \t]"))))
11216 (setq value (org-entry-protect-space value))
11217 (unless (member value values)
11218 (setq values (cons value values))
11219 (org-entry-put pom property
11220 (mapconcat 'identity values " ")))))
11222 (defun org-entry-remove-from-multivalued-property (pom property value)
11223 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
11224 (let* ((old (org-entry-get pom property))
11225 (values (and old (org-split-string old "[ \t]"))))
11226 (setq value (org-entry-protect-space value))
11227 (when (member value values)
11228 (setq values (delete value values))
11229 (org-entry-put pom property
11230 (mapconcat 'identity values " ")))))
11232 (defun org-entry-member-in-multivalued-property (pom property value)
11233 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
11234 (let* ((old (org-entry-get pom property))
11235 (values (and old (org-split-string old "[ \t]"))))
11236 (setq value (org-entry-protect-space value))
11237 (member value values)))
11239 (defun org-entry-get-multivalued-property (pom property)
11240 "Return a list of values in a multivalued property."
11241 (let* ((value (org-entry-get pom property))
11242 (values (and value (org-split-string value "[ \t]"))))
11243 (mapcar 'org-entry-restore-space values)))
11245 (defun org-entry-put-multivalued-property (pom property &rest values)
11246 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
11247 VALUES should be a list of strings. Spaces will be protected."
11248 (org-entry-put pom property
11249 (mapconcat 'org-entry-protect-space values " "))
11250 (let* ((value (org-entry-get pom property))
11251 (values (and value (org-split-string value "[ \t]"))))
11252 (mapcar 'org-entry-restore-space values)))
11254 (defun org-entry-protect-space (s)
11255 "Protect spaces and newline in string S."
11256 (while (string-match " " s)
11257 (setq s (replace-match "%20" t t s)))
11258 (while (string-match "\n" s)
11259 (setq s (replace-match "%0A" t t s)))
11262 (defun org-entry-restore-space (s)
11263 "Restore spaces and newline in string S."
11264 (while (string-match "%20" s)
11265 (setq s (replace-match " " t t s)))
11266 (while (string-match "%0A" s)
11267 (setq s (replace-match "\n" t t s)))
11270 (defvar org-entry-property-inherited-from (make-marker)
11271 "Marker pointing to the entry from where a property was inherited.
11272 Each call to `org-entry-get-with-inheritance' will set this marker to the
11273 location of the entry where the inheritance search matched. If there was
11274 no match, the marker will point nowhere.
11275 Note that also `org-entry-get' calls this function, if the INHERIT flag
11276 is set.")
11278 (defun org-entry-get-with-inheritance (property)
11279 "Get entry property, and search higher levels if not present."
11280 (move-marker org-entry-property-inherited-from nil)
11281 (let (tmp)
11282 (save-excursion
11283 (save-restriction
11284 (widen)
11285 (catch 'ex
11286 (while t
11287 (when (setq tmp (org-entry-get nil property))
11288 (org-back-to-heading t)
11289 (move-marker org-entry-property-inherited-from (point))
11290 (throw 'ex tmp))
11291 (or (org-up-heading-safe) (throw 'ex nil)))))
11292 (or tmp
11293 (cdr (assoc property org-file-properties))
11294 (cdr (assoc property org-global-properties))
11295 (cdr (assoc property org-global-properties-fixed))))))
11297 (defun org-entry-put (pom property value)
11298 "Set PROPERTY to VALUE for entry at point-or-marker POM."
11299 (org-with-point-at pom
11300 (org-back-to-heading t)
11301 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
11302 range)
11303 (cond
11304 ((equal property "TODO")
11305 (when (and (stringp value) (string-match "\\S-" value)
11306 (not (member value org-todo-keywords-1)))
11307 (error "\"%s\" is not a valid TODO state" value))
11308 (if (or (not value)
11309 (not (string-match "\\S-" value)))
11310 (setq value 'none))
11311 (org-todo value)
11312 (org-set-tags nil 'align))
11313 ((equal property "PRIORITY")
11314 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
11315 (string-to-char value) ?\ ))
11316 (org-set-tags nil 'align))
11317 ((equal property "SCHEDULED")
11318 (if (re-search-forward org-scheduled-time-regexp end t)
11319 (cond
11320 ((eq value 'earlier) (org-timestamp-change -1 'day))
11321 ((eq value 'later) (org-timestamp-change 1 'day))
11322 (t (call-interactively 'org-schedule)))
11323 (call-interactively 'org-schedule)))
11324 ((equal property "DEADLINE")
11325 (if (re-search-forward org-deadline-time-regexp end t)
11326 (cond
11327 ((eq value 'earlier) (org-timestamp-change -1 'day))
11328 ((eq value 'later) (org-timestamp-change 1 'day))
11329 (t (call-interactively 'org-deadline)))
11330 (call-interactively 'org-deadline)))
11331 ((member property org-special-properties)
11332 (error "The %s property can not yet be set with `org-entry-put'"
11333 property))
11334 (t ; a non-special property
11335 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
11336 (setq range (org-get-property-block beg end 'force))
11337 (goto-char (car range))
11338 (if (re-search-forward
11339 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
11340 (progn
11341 (delete-region (match-beginning 1) (match-end 1))
11342 (goto-char (match-beginning 1)))
11343 (goto-char (cdr range))
11344 (insert "\n")
11345 (backward-char 1)
11346 (org-indent-line-function)
11347 (insert ":" property ":"))
11348 (and value (insert " " value))
11349 (org-indent-line-function)))))))
11351 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
11352 "Get all property keys in the current buffer.
11353 With INCLUDE-SPECIALS, also list the special properties that reflect things
11354 like tags and TODO state.
11355 With INCLUDE-DEFAULTS, also include properties that has special meaning
11356 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
11357 With INCLUDE-COLUMNS, also include property names given in COLUMN
11358 formats in the current buffer."
11359 (let (rtn range cfmt s p)
11360 (save-excursion
11361 (save-restriction
11362 (widen)
11363 (goto-char (point-min))
11364 (while (re-search-forward org-property-start-re nil t)
11365 (setq range (org-get-property-block))
11366 (goto-char (car range))
11367 (while (re-search-forward
11368 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
11369 (cdr range) t)
11370 (add-to-list 'rtn (org-match-string-no-properties 1)))
11371 (outline-next-heading))))
11373 (when include-specials
11374 (setq rtn (append org-special-properties rtn)))
11376 (when include-defaults
11377 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
11379 (when include-columns
11380 (save-excursion
11381 (save-restriction
11382 (widen)
11383 (goto-char (point-min))
11384 (while (re-search-forward
11385 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
11386 nil t)
11387 (setq cfmt (match-string 2) s 0)
11388 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
11389 cfmt s)
11390 (setq s (match-end 0)
11391 p (match-string 1 cfmt))
11392 (unless (or (equal p "ITEM")
11393 (member p org-special-properties))
11394 (add-to-list 'rtn (match-string 1 cfmt))))))))
11396 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
11398 (defun org-property-values (key)
11399 "Return a list of all values of property KEY."
11400 (save-excursion
11401 (save-restriction
11402 (widen)
11403 (goto-char (point-min))
11404 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
11405 values)
11406 (while (re-search-forward re nil t)
11407 (add-to-list 'values (org-trim (match-string 1))))
11408 (delete "" values)))))
11410 (defun org-insert-property-drawer ()
11411 "Insert a property drawer into the current entry."
11412 (interactive)
11413 (org-back-to-heading t)
11414 (looking-at outline-regexp)
11415 (let ((indent (- (match-end 0)(match-beginning 0)))
11416 (beg (point))
11417 (re (concat "^[ \t]*" org-keyword-time-regexp))
11418 end hiddenp)
11419 (outline-next-heading)
11420 (setq end (point))
11421 (goto-char beg)
11422 (while (re-search-forward re end t))
11423 (setq hiddenp (org-invisible-p))
11424 (end-of-line 1)
11425 (and (equal (char-after) ?\n) (forward-char 1))
11426 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
11427 (if (member (match-string 1) '("CLOCK:" ":END:"))
11428 ;; just skip this line
11429 (beginning-of-line 2)
11430 ;; Drawer start, find the end
11431 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
11432 (beginning-of-line 1)))
11433 (org-skip-over-state-notes)
11434 (skip-chars-backward " \t\n\r")
11435 (if (eq (char-before) ?*) (forward-char 1))
11436 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
11437 (beginning-of-line 0)
11438 (org-indent-to-column indent)
11439 (beginning-of-line 2)
11440 (org-indent-to-column indent)
11441 (beginning-of-line 0)
11442 (if hiddenp
11443 (save-excursion
11444 (org-back-to-heading t)
11445 (hide-entry))
11446 (org-flag-drawer t))))
11448 (defun org-set-property (property value)
11449 "In the current entry, set PROPERTY to VALUE.
11450 When called interactively, this will prompt for a property name, offering
11451 completion on existing and default properties. And then it will prompt
11452 for a value, offering completion either on allowed values (via an inherited
11453 xxx_ALL property) or on existing values in other instances of this property
11454 in the current file."
11455 (interactive
11456 (let* ((completion-ignore-case t)
11457 (keys (org-buffer-property-keys nil t t))
11458 (prop0 (org-ido-completing-read "Property: " (mapcar 'list keys)))
11459 (prop (if (member prop0 keys)
11460 prop0
11461 (or (cdr (assoc (downcase prop0)
11462 (mapcar (lambda (x) (cons (downcase x) x))
11463 keys)))
11464 prop0)))
11465 (cur (org-entry-get nil prop))
11466 (allowed (org-property-get-allowed-values nil prop 'table))
11467 (existing (mapcar 'list (org-property-values prop)))
11468 (val (if allowed
11469 (org-completing-read "Value: " allowed nil 'req-match)
11470 (let (org-completion-use-ido)
11471 (org-completing-read
11472 (concat "Value" (if (and cur (string-match "\\S-" cur))
11473 (concat "[" cur "]") "")
11474 ": ")
11475 existing nil nil "" nil cur)))))
11476 (list prop (if (equal val "") cur val))))
11477 (unless (equal (org-entry-get nil property) value)
11478 (org-entry-put nil property value)))
11480 (defun org-delete-property (property)
11481 "In the current entry, delete PROPERTY."
11482 (interactive
11483 (let* ((completion-ignore-case t)
11484 (prop (org-ido-completing-read
11485 "Property: " (org-entry-properties nil 'standard))))
11486 (list prop)))
11487 (message "Property %s %s" property
11488 (if (org-entry-delete nil property)
11489 "deleted"
11490 "was not present in the entry")))
11492 (defun org-delete-property-globally (property)
11493 "Remove PROPERTY globally, from all entries."
11494 (interactive
11495 (let* ((completion-ignore-case t)
11496 (prop (org-ido-completing-read
11497 "Globally remove property: "
11498 (mapcar 'list (org-buffer-property-keys)))))
11499 (list prop)))
11500 (save-excursion
11501 (save-restriction
11502 (widen)
11503 (goto-char (point-min))
11504 (let ((cnt 0))
11505 (while (re-search-forward
11506 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
11507 nil t)
11508 (setq cnt (1+ cnt))
11509 (replace-match ""))
11510 (message "Property \"%s\" removed from %d entries" property cnt)))))
11512 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
11514 (defun org-compute-property-at-point ()
11515 "Compute the property at point.
11516 This looks for an enclosing column format, extracts the operator and
11517 then applies it to the property in the column format's scope."
11518 (interactive)
11519 (unless (org-at-property-p)
11520 (error "Not at a property"))
11521 (let ((prop (org-match-string-no-properties 2)))
11522 (org-columns-get-format-and-top-level)
11523 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
11524 (error "No operator defined for property %s" prop))
11525 (org-columns-compute prop)))
11527 (defun org-property-get-allowed-values (pom property &optional table)
11528 "Get allowed values for the property PROPERTY.
11529 When TABLE is non-nil, return an alist that can directly be used for
11530 completion."
11531 (let (vals)
11532 (cond
11533 ((equal property "TODO")
11534 (setq vals (org-with-point-at pom
11535 (append org-todo-keywords-1 '("")))))
11536 ((equal property "PRIORITY")
11537 (let ((n org-lowest-priority))
11538 (while (>= n org-highest-priority)
11539 (push (char-to-string n) vals)
11540 (setq n (1- n)))))
11541 ((member property org-special-properties))
11543 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
11545 (when (and vals (string-match "\\S-" vals))
11546 (setq vals (car (read-from-string (concat "(" vals ")"))))
11547 (setq vals (mapcar (lambda (x)
11548 (cond ((stringp x) x)
11549 ((numberp x) (number-to-string x))
11550 ((symbolp x) (symbol-name x))
11551 (t "???")))
11552 vals)))))
11553 (if table (mapcar 'list vals) vals)))
11555 (defun org-property-previous-allowed-value (&optional previous)
11556 "Switch to the next allowed value for this property."
11557 (interactive)
11558 (org-property-next-allowed-value t))
11560 (defun org-property-next-allowed-value (&optional previous)
11561 "Switch to the next allowed value for this property."
11562 (interactive)
11563 (unless (org-at-property-p)
11564 (error "Not at a property"))
11565 (let* ((key (match-string 2))
11566 (value (match-string 3))
11567 (allowed (or (org-property-get-allowed-values (point) key)
11568 (and (member value '("[ ]" "[-]" "[X]"))
11569 '("[ ]" "[X]"))))
11570 nval)
11571 (unless allowed
11572 (error "Allowed values for this property have not been defined"))
11573 (if previous (setq allowed (reverse allowed)))
11574 (if (member value allowed)
11575 (setq nval (car (cdr (member value allowed)))))
11576 (setq nval (or nval (car allowed)))
11577 (if (equal nval value)
11578 (error "Only one allowed value for this property"))
11579 (org-at-property-p)
11580 (replace-match (concat " :" key ": " nval) t t)
11581 (org-indent-line-function)
11582 (beginning-of-line 1)
11583 (skip-chars-forward " \t")))
11585 (defun org-find-entry-with-id (ident)
11586 "Locate the entry that contains the ID property with exact value IDENT.
11587 IDENT can be a string, a symbol or a number, this function will search for
11588 the string representation of it.
11589 Return the position where this entry starts, or nil if there is no such entry."
11590 (interactive "sID: ")
11591 (let ((id (cond
11592 ((stringp ident) ident)
11593 ((symbol-name ident) (symbol-name ident))
11594 ((numberp ident) (number-to-string ident))
11595 (t (error "IDENT %s must be a string, symbol or number" ident))))
11596 (case-fold-search nil))
11597 (save-excursion
11598 (save-restriction
11599 (widen)
11600 (goto-char (point-min))
11601 (when (re-search-forward
11602 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
11603 nil t)
11604 (org-back-to-heading)
11605 (point))))))
11607 ;;;; Timestamps
11609 (defvar org-last-changed-timestamp nil)
11610 (defvar org-last-inserted-timestamp nil
11611 "The last time stamp inserted with `org-insert-time-stamp'.")
11612 (defvar org-time-was-given) ; dynamically scoped parameter
11613 (defvar org-end-time-was-given) ; dynamically scoped parameter
11614 (defvar org-ts-what) ; dynamically scoped parameter
11616 (defun org-time-stamp (arg &optional inactive)
11617 "Prompt for a date/time and insert a time stamp.
11618 If the user specifies a time like HH:MM, or if this command is called
11619 with a prefix argument, the time stamp will contain date and time.
11620 Otherwise, only the date will be included. All parts of a date not
11621 specified by the user will be filled in from the current date/time.
11622 So if you press just return without typing anything, the time stamp
11623 will represent the current date/time. If there is already a timestamp
11624 at the cursor, it will be modified."
11625 (interactive "P")
11626 (let* ((ts nil)
11627 (default-time
11628 ;; Default time is either today, or, when entering a range,
11629 ;; the range start.
11630 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
11631 (save-excursion
11632 (re-search-backward
11633 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
11634 (- (point) 20) t)))
11635 (apply 'encode-time (org-parse-time-string (match-string 1)))
11636 (current-time)))
11637 (default-input (and ts (org-get-compact-tod ts)))
11638 org-time-was-given org-end-time-was-given time)
11639 (cond
11640 ((and (org-at-timestamp-p t)
11641 (memq last-command '(org-time-stamp org-time-stamp-inactive))
11642 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
11643 (insert "--")
11644 (setq time (let ((this-command this-command))
11645 (org-read-date arg 'totime nil nil
11646 default-time default-input)))
11647 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
11648 ((org-at-timestamp-p t)
11649 (setq time (let ((this-command this-command))
11650 (org-read-date arg 'totime nil nil default-time default-input)))
11651 (when (org-at-timestamp-p t) ; just to get the match data
11652 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
11653 (replace-match "")
11654 (setq org-last-changed-timestamp
11655 (org-insert-time-stamp
11656 time (or org-time-was-given arg)
11657 inactive nil nil (list org-end-time-was-given))))
11658 (message "Timestamp updated"))
11660 (setq time (let ((this-command this-command))
11661 (org-read-date arg 'totime nil nil default-time default-input)))
11662 (org-insert-time-stamp time (or org-time-was-given arg) inactive
11663 nil nil (list org-end-time-was-given))))))
11665 ;; FIXME: can we use this for something else, like computing time differences?
11666 (defun org-get-compact-tod (s)
11667 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
11668 (let* ((t1 (match-string 1 s))
11669 (h1 (string-to-number (match-string 2 s)))
11670 (m1 (string-to-number (match-string 3 s)))
11671 (t2 (and (match-end 4) (match-string 5 s)))
11672 (h2 (and t2 (string-to-number (match-string 6 s))))
11673 (m2 (and t2 (string-to-number (match-string 7 s))))
11674 dh dm)
11675 (if (not t2)
11677 (setq dh (- h2 h1) dm (- m2 m1))
11678 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
11679 (concat t1 "+" (number-to-string dh)
11680 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
11682 (defun org-time-stamp-inactive (&optional arg)
11683 "Insert an inactive time stamp.
11684 An inactive time stamp is enclosed in square brackets instead of angle
11685 brackets. It is inactive in the sense that it does not trigger agenda entries,
11686 does not link to the calendar and cannot be changed with the S-cursor keys.
11687 So these are more for recording a certain time/date."
11688 (interactive "P")
11689 (org-time-stamp arg 'inactive))
11691 (defvar org-date-ovl (org-make-overlay 1 1))
11692 (org-overlay-put org-date-ovl 'face 'org-warning)
11693 (org-detach-overlay org-date-ovl)
11695 (defvar org-ans1) ; dynamically scoped parameter
11696 (defvar org-ans2) ; dynamically scoped parameter
11698 (defvar org-plain-time-of-day-regexp) ; defined below
11700 (defvar org-overriding-default-time nil) ; dynamically scoped
11701 (defvar org-read-date-overlay nil)
11702 (defvar org-dcst nil) ; dynamically scoped
11703 (defvar org-read-date-history nil)
11705 (defun org-read-date (&optional with-time to-time from-string prompt
11706 default-time default-input)
11707 "Read a date, possibly a time, and make things smooth for the user.
11708 The prompt will suggest to enter an ISO date, but you can also enter anything
11709 which will at least partially be understood by `parse-time-string'.
11710 Unrecognized parts of the date will default to the current day, month, year,
11711 hour and minute. If this command is called to replace a timestamp at point,
11712 of to enter the second timestamp of a range, the default time is taken from the
11713 existing stamp. For example,
11714 3-2-5 --> 2003-02-05
11715 feb 15 --> currentyear-02-15
11716 sep 12 9 --> 2009-09-12
11717 12:45 --> today 12:45
11718 22 sept 0:34 --> currentyear-09-22 0:34
11719 12 --> currentyear-currentmonth-12
11720 Fri --> nearest Friday (today or later)
11721 etc.
11723 Furthermore you can specify a relative date by giving, as the *first* thing
11724 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
11725 change in days weeks, months, years.
11726 With a single plus or minus, the date is relative to today. With a double
11727 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
11728 +4d --> four days from today
11729 +4 --> same as above
11730 +2w --> two weeks from today
11731 ++5 --> five days from default date
11733 The function understands only English month and weekday abbreviations,
11734 but this can be configured with the variables `parse-time-months' and
11735 `parse-time-weekdays'.
11737 While prompting, a calendar is popped up - you can also select the
11738 date with the mouse (button 1). The calendar shows a period of three
11739 months. To scroll it to other months, use the keys `>' and `<'.
11740 If you don't like the calendar, turn it off with
11741 \(setq org-read-date-popup-calendar nil)
11743 With optional argument TO-TIME, the date will immediately be converted
11744 to an internal time.
11745 With an optional argument WITH-TIME, the prompt will suggest to also
11746 insert a time. Note that when WITH-TIME is not set, you can still
11747 enter a time, and this function will inform the calling routine about
11748 this change. The calling routine may then choose to change the format
11749 used to insert the time stamp into the buffer to include the time.
11750 With optional argument FROM-STRING, read from this string instead from
11751 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
11752 the time/date that is used for everything that is not specified by the
11753 user."
11754 (require 'parse-time)
11755 (let* ((org-time-stamp-rounding-minutes
11756 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
11757 (org-dcst org-display-custom-times)
11758 (ct (org-current-time))
11759 (def (or org-overriding-default-time default-time ct))
11760 (defdecode (decode-time def))
11761 (dummy (progn
11762 (when (< (nth 2 defdecode) org-extend-today-until)
11763 (setcar (nthcdr 2 defdecode) -1)
11764 (setcar (nthcdr 1 defdecode) 59)
11765 (setq def (apply 'encode-time defdecode)
11766 defdecode (decode-time def)))))
11767 (calendar-move-hook nil)
11768 (calendar-view-diary-initially-flag nil)
11769 (view-diary-entries-initially nil)
11770 (calendar-view-holidays-initially-flag nil)
11771 (view-calendar-holidays-initially nil)
11772 (timestr (format-time-string
11773 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
11774 (prompt (concat (if prompt (concat prompt " ") "")
11775 (format "Date+time [%s]: " timestr)))
11776 ans (org-ans0 "") org-ans1 org-ans2 final)
11778 (cond
11779 (from-string (setq ans from-string))
11780 (org-read-date-popup-calendar
11781 (save-excursion
11782 (save-window-excursion
11783 (calendar)
11784 (calendar-forward-day (- (time-to-days def)
11785 (calendar-absolute-from-gregorian
11786 (calendar-current-date))))
11787 (org-eval-in-calendar nil t)
11788 (let* ((old-map (current-local-map))
11789 (map (copy-keymap calendar-mode-map))
11790 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
11791 (org-defkey map (kbd "RET") 'org-calendar-select)
11792 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
11793 'org-calendar-select-mouse)
11794 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
11795 'org-calendar-select-mouse)
11796 (org-defkey minibuffer-local-map [(meta shift left)]
11797 (lambda () (interactive)
11798 (org-eval-in-calendar '(calendar-backward-month 1))))
11799 (org-defkey minibuffer-local-map [(meta shift right)]
11800 (lambda () (interactive)
11801 (org-eval-in-calendar '(calendar-forward-month 1))))
11802 (org-defkey minibuffer-local-map [(meta shift up)]
11803 (lambda () (interactive)
11804 (org-eval-in-calendar '(calendar-backward-year 1))))
11805 (org-defkey minibuffer-local-map [(meta shift down)]
11806 (lambda () (interactive)
11807 (org-eval-in-calendar '(calendar-forward-year 1))))
11808 (org-defkey minibuffer-local-map [(shift up)]
11809 (lambda () (interactive)
11810 (org-eval-in-calendar '(calendar-backward-week 1))))
11811 (org-defkey minibuffer-local-map [(shift down)]
11812 (lambda () (interactive)
11813 (org-eval-in-calendar '(calendar-forward-week 1))))
11814 (org-defkey minibuffer-local-map [(shift left)]
11815 (lambda () (interactive)
11816 (org-eval-in-calendar '(calendar-backward-day 1))))
11817 (org-defkey minibuffer-local-map [(shift right)]
11818 (lambda () (interactive)
11819 (org-eval-in-calendar '(calendar-forward-day 1))))
11820 (org-defkey minibuffer-local-map ">"
11821 (lambda () (interactive)
11822 (org-eval-in-calendar '(scroll-calendar-left 1))))
11823 (org-defkey minibuffer-local-map "<"
11824 (lambda () (interactive)
11825 (org-eval-in-calendar '(scroll-calendar-right 1))))
11826 (run-hooks 'org-read-date-minibuffer-setup-hook)
11827 (unwind-protect
11828 (progn
11829 (use-local-map map)
11830 (add-hook 'post-command-hook 'org-read-date-display)
11831 (setq org-ans0 (read-string prompt default-input
11832 'org-read-date-history nil))
11833 ;; org-ans0: from prompt
11834 ;; org-ans1: from mouse click
11835 ;; org-ans2: from calendar motion
11836 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
11837 (remove-hook 'post-command-hook 'org-read-date-display)
11838 (use-local-map old-map)
11839 (when org-read-date-overlay
11840 (org-delete-overlay org-read-date-overlay)
11841 (setq org-read-date-overlay nil)))))))
11843 (t ; Naked prompt only
11844 (unwind-protect
11845 (setq ans (read-string prompt default-input
11846 'org-read-date-history timestr))
11847 (when org-read-date-overlay
11848 (org-delete-overlay org-read-date-overlay)
11849 (setq org-read-date-overlay nil)))))
11851 (setq final (org-read-date-analyze ans def defdecode))
11853 (if to-time
11854 (apply 'encode-time final)
11855 (if (and (boundp 'org-time-was-given) org-time-was-given)
11856 (format "%04d-%02d-%02d %02d:%02d"
11857 (nth 5 final) (nth 4 final) (nth 3 final)
11858 (nth 2 final) (nth 1 final))
11859 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
11860 (defvar def)
11861 (defvar defdecode)
11862 (defvar with-time)
11863 (defun org-read-date-display ()
11864 "Display the current date prompt interpretation in the minibuffer."
11865 (when org-read-date-display-live
11866 (when org-read-date-overlay
11867 (org-delete-overlay org-read-date-overlay))
11868 (let ((p (point)))
11869 (end-of-line 1)
11870 (while (not (equal (buffer-substring
11871 (max (point-min) (- (point) 4)) (point))
11872 " "))
11873 (insert " "))
11874 (goto-char p))
11875 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
11876 " " (or org-ans1 org-ans2)))
11877 (org-end-time-was-given nil)
11878 (f (org-read-date-analyze ans def defdecode))
11879 (fmts (if org-dcst
11880 org-time-stamp-custom-formats
11881 org-time-stamp-formats))
11882 (fmt (if (or with-time
11883 (and (boundp 'org-time-was-given) org-time-was-given))
11884 (cdr fmts)
11885 (car fmts)))
11886 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
11887 (when (and org-end-time-was-given
11888 (string-match org-plain-time-of-day-regexp txt))
11889 (setq txt (concat (substring txt 0 (match-end 0)) "-"
11890 org-end-time-was-given
11891 (substring txt (match-end 0)))))
11892 (setq org-read-date-overlay
11893 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
11894 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
11896 (defun org-read-date-analyze (ans def defdecode)
11897 "Analyse the combined answer of the date prompt."
11898 ;; FIXME: cleanup and comment
11899 (let (delta deltan deltaw deltadef year month day
11900 hour minute second wday pm h2 m2 tl wday1
11901 iso-year iso-weekday iso-week iso-year iso-date)
11903 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
11904 (setq ans "+0"))
11906 (when (setq delta (org-read-date-get-relative ans (current-time) def))
11907 (setq ans (replace-match "" t t ans)
11908 deltan (car delta)
11909 deltaw (nth 1 delta)
11910 deltadef (nth 2 delta)))
11912 ;; Check if there is an iso week date in there
11913 ;; If yes, sore the info and postpone interpreting it until the rest
11914 ;; of the parsing is done
11915 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
11916 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
11917 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
11918 iso-week (string-to-number (match-string 2 ans)))
11919 (setq ans (replace-match "" t t ans)))
11921 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
11922 (when (string-match
11923 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
11924 (setq year (if (match-end 2)
11925 (string-to-number (match-string 2 ans))
11926 (string-to-number (format-time-string "%Y")))
11927 month (string-to-number (match-string 3 ans))
11928 day (string-to-number (match-string 4 ans)))
11929 (if (< year 100) (setq year (+ 2000 year)))
11930 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
11931 t nil ans)))
11932 ;; Help matching am/pm times, because `parse-time-string' does not do that.
11933 ;; If there is a time with am/pm, and *no* time without it, we convert
11934 ;; so that matching will be successful.
11935 (loop for i from 1 to 2 do ; twice, for end time as well
11936 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
11937 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
11938 (setq hour (string-to-number (match-string 1 ans))
11939 minute (if (match-end 3)
11940 (string-to-number (match-string 3 ans))
11942 pm (equal ?p
11943 (string-to-char (downcase (match-string 4 ans)))))
11944 (if (and (= hour 12) (not pm))
11945 (setq hour 0)
11946 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
11947 (setq ans (replace-match (format "%02d:%02d" hour minute)
11948 t t ans))))
11950 ;; Check if a time range is given as a duration
11951 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
11952 (setq hour (string-to-number (match-string 1 ans))
11953 h2 (+ hour (string-to-number (match-string 3 ans)))
11954 minute (string-to-number (match-string 2 ans))
11955 m2 (+ minute (if (match-end 5) (string-to-number
11956 (match-string 5 ans))0)))
11957 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
11958 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
11959 t t ans)))
11961 ;; Check if there is a time range
11962 (when (boundp 'org-end-time-was-given)
11963 (setq org-time-was-given nil)
11964 (when (and (string-match org-plain-time-of-day-regexp ans)
11965 (match-end 8))
11966 (setq org-end-time-was-given (match-string 8 ans))
11967 (setq ans (concat (substring ans 0 (match-beginning 7))
11968 (substring ans (match-end 7))))))
11970 (setq tl (parse-time-string ans)
11971 day (or (nth 3 tl) (nth 3 defdecode))
11972 month (or (nth 4 tl)
11973 (if (and org-read-date-prefer-future
11974 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
11975 (1+ (nth 4 defdecode))
11976 (nth 4 defdecode)))
11977 year (or (nth 5 tl)
11978 (if (and org-read-date-prefer-future
11979 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
11980 (1+ (nth 5 defdecode))
11981 (nth 5 defdecode)))
11982 hour (or (nth 2 tl) (nth 2 defdecode))
11983 minute (or (nth 1 tl) (nth 1 defdecode))
11984 second (or (nth 0 tl) 0)
11985 wday (nth 6 tl))
11987 ;; Special date definitions below
11988 (cond
11989 (iso-week
11990 ;; There was an iso week
11991 (setq year (or iso-year year)
11992 day (or iso-weekday wday 1)
11993 wday nil ; to make sure that the trigger below does not match
11994 iso-date (calendar-gregorian-from-absolute
11995 (calendar-absolute-from-iso
11996 (list iso-week day year))))
11997 ; FIXME: Should we also push ISO weeks into the future?
11998 ; (when (and org-read-date-prefer-future
11999 ; (not iso-year)
12000 ; (< (calendar-absolute-from-gregorian iso-date)
12001 ; (time-to-days (current-time))))
12002 ; (setq year (1+ year)
12003 ; iso-date (calendar-gregorian-from-absolute
12004 ; (calendar-absolute-from-iso
12005 ; (list iso-week day year)))))
12006 (setq month (car iso-date)
12007 year (nth 2 iso-date)
12008 day (nth 1 iso-date)))
12009 (deltan
12010 (unless deltadef
12011 (let ((now (decode-time (current-time))))
12012 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
12013 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
12014 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
12015 ((equal deltaw "m") (setq month (+ month deltan)))
12016 ((equal deltaw "y") (setq year (+ year deltan)))))
12017 ((and wday (not (nth 3 tl)))
12018 ;; Weekday was given, but no day, so pick that day in the week
12019 ;; on or after the derived date.
12020 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
12021 (unless (equal wday wday1)
12022 (setq day (+ day (% (- wday wday1 -7) 7))))))
12023 (if (and (boundp 'org-time-was-given)
12024 (nth 2 tl))
12025 (setq org-time-was-given t))
12026 (if (< year 100) (setq year (+ 2000 year)))
12027 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
12028 (list second minute hour day month year)))
12030 (defvar parse-time-weekdays)
12032 (defun org-read-date-get-relative (s today default)
12033 "Check string S for special relative date string.
12034 TODAY and DEFAULT are internal times, for today and for a default.
12035 Return shift list (N what def-flag)
12036 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
12037 N is the number of WHATs to shift.
12038 DEF-FLAG is t when a double ++ or -- indicates shift relative to
12039 the DEFAULT date rather than TODAY."
12040 (when (and
12041 (string-match
12042 (concat
12043 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
12044 "\\([0-9]+\\)?"
12045 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
12046 "\\([ \t]\\|$\\)") s)
12047 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
12048 (let* ((dir (if (> (match-end 1) (match-beginning 1))
12049 (string-to-char (substring (match-string 1 s) -1))
12050 ?+))
12051 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
12052 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
12053 (what (if (match-end 3) (match-string 3 s) "d"))
12054 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
12055 (date (if rel default today))
12056 (wday (nth 6 (decode-time date)))
12057 delta)
12058 (if wday1
12059 (progn
12060 (setq delta (mod (+ 7 (- wday1 wday)) 7))
12061 (if (= dir ?-) (setq delta (- delta 7)))
12062 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
12063 (list delta "d" rel))
12064 (list (* n (if (= dir ?-) -1 1)) what rel)))))
12066 (defun org-eval-in-calendar (form &optional keepdate)
12067 "Eval FORM in the calendar window and return to current window.
12068 Also, store the cursor date in variable org-ans2."
12069 (let ((sw (selected-window)))
12070 (select-window (get-buffer-window "*Calendar*"))
12071 (eval form)
12072 (when (and (not keepdate) (calendar-cursor-to-date))
12073 (let* ((date (calendar-cursor-to-date))
12074 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12075 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
12076 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
12077 (select-window sw)))
12079 (defun org-calendar-select ()
12080 "Return to `org-read-date' with the date currently selected.
12081 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
12082 (interactive)
12083 (when (calendar-cursor-to-date)
12084 (let* ((date (calendar-cursor-to-date))
12085 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12086 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
12087 (if (active-minibuffer-window) (exit-minibuffer))))
12089 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
12090 "Insert a date stamp for the date given by the internal TIME.
12091 WITH-HM means, use the stamp format that includes the time of the day.
12092 INACTIVE means use square brackets instead of angular ones, so that the
12093 stamp will not contribute to the agenda.
12094 PRE and POST are optional strings to be inserted before and after the
12095 stamp.
12096 The command returns the inserted time stamp."
12097 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
12098 stamp)
12099 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
12100 (insert-before-markers (or pre ""))
12101 (insert-before-markers (setq stamp (format-time-string fmt time)))
12102 (when (listp extra)
12103 (setq extra (car extra))
12104 (if (and (stringp extra)
12105 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
12106 (setq extra (format "-%02d:%02d"
12107 (string-to-number (match-string 1 extra))
12108 (string-to-number (match-string 2 extra))))
12109 (setq extra nil)))
12110 (when extra
12111 (backward-char 1)
12112 (insert-before-markers extra)
12113 (forward-char 1))
12114 (insert-before-markers (or post ""))
12115 (setq org-last-inserted-timestamp stamp)))
12117 (defun org-toggle-time-stamp-overlays ()
12118 "Toggle the use of custom time stamp formats."
12119 (interactive)
12120 (setq org-display-custom-times (not org-display-custom-times))
12121 (unless org-display-custom-times
12122 (let ((p (point-min)) (bmp (buffer-modified-p)))
12123 (while (setq p (next-single-property-change p 'display))
12124 (if (and (get-text-property p 'display)
12125 (eq (get-text-property p 'face) 'org-date))
12126 (remove-text-properties
12127 p (setq p (next-single-property-change p 'display))
12128 '(display t))))
12129 (set-buffer-modified-p bmp)))
12130 (if (featurep 'xemacs)
12131 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
12132 (org-restart-font-lock)
12133 (setq org-table-may-need-update t)
12134 (if org-display-custom-times
12135 (message "Time stamps are overlayed with custom format")
12136 (message "Time stamp overlays removed")))
12138 (defun org-display-custom-time (beg end)
12139 "Overlay modified time stamp format over timestamp between BEG and END."
12140 (let* ((ts (buffer-substring beg end))
12141 t1 w1 with-hm tf time str w2 (off 0))
12142 (save-match-data
12143 (setq t1 (org-parse-time-string ts t))
12144 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
12145 (setq off (- (match-end 0) (match-beginning 0)))))
12146 (setq end (- end off))
12147 (setq w1 (- end beg)
12148 with-hm (and (nth 1 t1) (nth 2 t1))
12149 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
12150 time (org-fix-decoded-time t1)
12151 str (org-add-props
12152 (format-time-string
12153 (substring tf 1 -1) (apply 'encode-time time))
12154 nil 'mouse-face 'highlight)
12155 w2 (length str))
12156 (if (not (= w2 w1))
12157 (add-text-properties (1+ beg) (+ 2 beg)
12158 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
12159 (if (featurep 'xemacs)
12160 (progn
12161 (put-text-property beg end 'invisible t)
12162 (put-text-property beg end 'end-glyph (make-glyph str)))
12163 (put-text-property beg end 'display str))))
12165 (defun org-translate-time (string)
12166 "Translate all timestamps in STRING to custom format.
12167 But do this only if the variable `org-display-custom-times' is set."
12168 (when org-display-custom-times
12169 (save-match-data
12170 (let* ((start 0)
12171 (re org-ts-regexp-both)
12172 t1 with-hm inactive tf time str beg end)
12173 (while (setq start (string-match re string start))
12174 (setq beg (match-beginning 0)
12175 end (match-end 0)
12176 t1 (save-match-data
12177 (org-parse-time-string (substring string beg end) t))
12178 with-hm (and (nth 1 t1) (nth 2 t1))
12179 inactive (equal (substring string beg (1+ beg)) "[")
12180 tf (funcall (if with-hm 'cdr 'car)
12181 org-time-stamp-custom-formats)
12182 time (org-fix-decoded-time t1)
12183 str (format-time-string
12184 (concat
12185 (if inactive "[" "<") (substring tf 1 -1)
12186 (if inactive "]" ">"))
12187 (apply 'encode-time time))
12188 string (replace-match str t t string)
12189 start (+ start (length str)))))))
12190 string)
12192 (defun org-fix-decoded-time (time)
12193 "Set 0 instead of nil for the first 6 elements of time.
12194 Don't touch the rest."
12195 (let ((n 0))
12196 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
12198 (defun org-days-to-time (timestamp-string)
12199 "Difference between TIMESTAMP-STRING and now in days."
12200 (- (time-to-days (org-time-string-to-time timestamp-string))
12201 (time-to-days (current-time))))
12203 (defun org-deadline-close (timestamp-string &optional ndays)
12204 "Is the time in TIMESTAMP-STRING close to the current date?"
12205 (setq ndays (or ndays (org-get-wdays timestamp-string)))
12206 (and (< (org-days-to-time timestamp-string) ndays)
12207 (not (org-entry-is-done-p))))
12209 (defun org-get-wdays (ts)
12210 "Get the deadline lead time appropriate for timestring TS."
12211 (cond
12212 ((<= org-deadline-warning-days 0)
12213 ;; 0 or negative, enforce this value no matter what
12214 (- org-deadline-warning-days))
12215 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
12216 ;; lead time is specified.
12217 (floor (* (string-to-number (match-string 1 ts))
12218 (cdr (assoc (match-string 2 ts)
12219 '(("d" . 1) ("w" . 7)
12220 ("m" . 30.4) ("y" . 365.25)))))))
12221 ;; go for the default.
12222 (t org-deadline-warning-days)))
12224 (defun org-calendar-select-mouse (ev)
12225 "Return to `org-read-date' with the date currently selected.
12226 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
12227 (interactive "e")
12228 (mouse-set-point ev)
12229 (when (calendar-cursor-to-date)
12230 (let* ((date (calendar-cursor-to-date))
12231 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12232 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
12233 (if (active-minibuffer-window) (exit-minibuffer))))
12235 (defun org-check-deadlines (ndays)
12236 "Check if there are any deadlines due or past due.
12237 A deadline is considered due if it happens within `org-deadline-warning-days'
12238 days from today's date. If the deadline appears in an entry marked DONE,
12239 it is not shown. The prefix arg NDAYS can be used to test that many
12240 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
12241 (interactive "P")
12242 (let* ((org-warn-days
12243 (cond
12244 ((equal ndays '(4)) 100000)
12245 (ndays (prefix-numeric-value ndays))
12246 (t (abs org-deadline-warning-days))))
12247 (case-fold-search nil)
12248 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
12249 (callback
12250 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
12252 (message "%d deadlines past-due or due within %d days"
12253 (org-occur regexp nil callback)
12254 org-warn-days)))
12256 (defun org-check-before-date (date)
12257 "Check if there are deadlines or scheduled entries before DATE."
12258 (interactive (list (org-read-date)))
12259 (let ((case-fold-search nil)
12260 (regexp (concat "\\<\\(" org-deadline-string
12261 "\\|" org-scheduled-string
12262 "\\) *<\\([^>]+\\)>"))
12263 (callback
12264 (lambda () (time-less-p
12265 (org-time-string-to-time (match-string 2))
12266 (org-time-string-to-time date)))))
12267 (message "%d entries before %s"
12268 (org-occur regexp nil callback) date)))
12270 (defun org-check-after-date (date)
12271 "Check if there are deadlines or scheduled entries after DATE."
12272 (interactive (list (org-read-date)))
12273 (let ((case-fold-search nil)
12274 (regexp (concat "\\<\\(" org-deadline-string
12275 "\\|" org-scheduled-string
12276 "\\) *<\\([^>]+\\)>"))
12277 (callback
12278 (lambda () (not
12279 (time-less-p
12280 (org-time-string-to-time (match-string 2))
12281 (org-time-string-to-time date))))))
12282 (message "%d entries after %s"
12283 (org-occur regexp nil callback) date)))
12285 (defun org-evaluate-time-range (&optional to-buffer)
12286 "Evaluate a time range by computing the difference between start and end.
12287 Normally the result is just printed in the echo area, but with prefix arg
12288 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
12289 If the time range is actually in a table, the result is inserted into the
12290 next column.
12291 For time difference computation, a year is assumed to be exactly 365
12292 days in order to avoid rounding problems."
12293 (interactive "P")
12295 (org-clock-update-time-maybe)
12296 (save-excursion
12297 (unless (org-at-date-range-p t)
12298 (goto-char (point-at-bol))
12299 (re-search-forward org-tr-regexp-both (point-at-eol) t))
12300 (if (not (org-at-date-range-p t))
12301 (error "Not at a time-stamp range, and none found in current line")))
12302 (let* ((ts1 (match-string 1))
12303 (ts2 (match-string 2))
12304 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
12305 (match-end (match-end 0))
12306 (time1 (org-time-string-to-time ts1))
12307 (time2 (org-time-string-to-time ts2))
12308 (t1 (time-to-seconds time1))
12309 (t2 (time-to-seconds time2))
12310 (diff (abs (- t2 t1)))
12311 (negative (< (- t2 t1) 0))
12312 ;; (ys (floor (* 365 24 60 60)))
12313 (ds (* 24 60 60))
12314 (hs (* 60 60))
12315 (fy "%dy %dd %02d:%02d")
12316 (fy1 "%dy %dd")
12317 (fd "%dd %02d:%02d")
12318 (fd1 "%dd")
12319 (fh "%02d:%02d")
12320 y d h m align)
12321 (if havetime
12322 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
12324 d (floor (/ diff ds)) diff (mod diff ds)
12325 h (floor (/ diff hs)) diff (mod diff hs)
12326 m (floor (/ diff 60)))
12327 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
12329 d (floor (+ (/ diff ds) 0.5))
12330 h 0 m 0))
12331 (if (not to-buffer)
12332 (message "%s" (org-make-tdiff-string y d h m))
12333 (if (org-at-table-p)
12334 (progn
12335 (goto-char match-end)
12336 (setq align t)
12337 (and (looking-at " *|") (goto-char (match-end 0))))
12338 (goto-char match-end))
12339 (if (looking-at
12340 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
12341 (replace-match ""))
12342 (if negative (insert " -"))
12343 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
12344 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
12345 (insert " " (format fh h m))))
12346 (if align (org-table-align))
12347 (message "Time difference inserted")))))
12349 (defun org-make-tdiff-string (y d h m)
12350 (let ((fmt "")
12351 (l nil))
12352 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
12353 l (push y l)))
12354 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
12355 l (push d l)))
12356 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
12357 l (push h l)))
12358 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
12359 l (push m l)))
12360 (apply 'format fmt (nreverse l))))
12362 (defun org-time-string-to-time (s)
12363 (apply 'encode-time (org-parse-time-string s)))
12365 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
12366 "Convert a time stamp to an absolute day number.
12367 If there is a specifyer for a cyclic time stamp, get the closest date to
12368 DAYNR.
12369 PREFER and SHOW-ALL are passed through to `org-closest-date'."
12370 (cond
12371 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
12372 (if (org-diary-sexp-entry (match-string 1 s) "" date)
12373 daynr
12374 (+ daynr 1000)))
12375 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
12376 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
12377 (time-to-days (current-time))) (match-string 0 s)
12378 prefer show-all))
12379 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
12381 (defun org-days-to-iso-week (days)
12382 "Return the iso week number."
12383 (require 'cal-iso)
12384 (car (calendar-iso-from-absolute days)))
12386 (defun org-small-year-to-year (year)
12387 "Convert 2-digit years into 4-digit years.
12388 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
12389 The year 2000 cannot be abbreviated. Any year larger than 99
12390 is returned unchanged."
12391 (if (< year 38)
12392 (setq year (+ 2000 year))
12393 (if (< year 100)
12394 (setq year (+ 1900 year))))
12395 year)
12397 (defun org-time-from-absolute (d)
12398 "Return the time corresponding to date D.
12399 D may be an absolute day number, or a calendar-type list (month day year)."
12400 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
12401 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
12403 (defun org-calendar-holiday ()
12404 "List of holidays, for Diary display in Org-mode."
12405 (require 'holidays)
12406 (let ((hl (funcall
12407 (if (fboundp 'calendar-check-holidays)
12408 'calendar-check-holidays 'check-calendar-holidays) date)))
12409 (if hl (mapconcat 'identity hl "; "))))
12411 (defun org-diary-sexp-entry (sexp entry date)
12412 "Process a SEXP diary ENTRY for DATE."
12413 (require 'diary-lib)
12414 (let ((result (if calendar-debug-sexp
12415 (let ((stack-trace-on-error t))
12416 (eval (car (read-from-string sexp))))
12417 (condition-case nil
12418 (eval (car (read-from-string sexp)))
12419 (error
12420 (beep)
12421 (message "Bad sexp at line %d in %s: %s"
12422 (org-current-line)
12423 (buffer-file-name) sexp)
12424 (sleep-for 2))))))
12425 (cond ((stringp result) result)
12426 ((and (consp result)
12427 (stringp (cdr result))) (cdr result))
12428 (result entry)
12429 (t nil))))
12431 (defun org-diary-to-ical-string (frombuf)
12432 "Get iCalendar entries from diary entries in buffer FROMBUF.
12433 This uses the icalendar.el library."
12434 (let* ((tmpdir (if (featurep 'xemacs)
12435 (temp-directory)
12436 temporary-file-directory))
12437 (tmpfile (make-temp-name
12438 (expand-file-name "orgics" tmpdir)))
12439 buf rtn b e)
12440 (save-excursion
12441 (set-buffer frombuf)
12442 (icalendar-export-region (point-min) (point-max) tmpfile)
12443 (setq buf (find-buffer-visiting tmpfile))
12444 (set-buffer buf)
12445 (goto-char (point-min))
12446 (if (re-search-forward "^BEGIN:VEVENT" nil t)
12447 (setq b (match-beginning 0)))
12448 (goto-char (point-max))
12449 (if (re-search-backward "^END:VEVENT" nil t)
12450 (setq e (match-end 0)))
12451 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
12452 (kill-buffer buf)
12453 (delete-file tmpfile)
12454 rtn))
12456 (defun org-closest-date (start current change prefer show-all)
12457 "Find the date closest to CURRENT that is consistent with START and CHANGE.
12458 When PREFER is `past' return a date that is either CURRENT or past.
12459 When PREFER is `future', return a date that is either CURRENT or future.
12460 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
12461 ;; Make the proper lists from the dates
12462 (catch 'exit
12463 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
12464 dn dw sday cday n1 n2 n0
12465 d m y y1 y2 date1 date2 nmonths nm ny m2)
12467 (setq start (org-date-to-gregorian start)
12468 current (org-date-to-gregorian
12469 (if show-all
12470 current
12471 (time-to-days (current-time))))
12472 sday (calendar-absolute-from-gregorian start)
12473 cday (calendar-absolute-from-gregorian current))
12475 (if (<= cday sday) (throw 'exit sday))
12477 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
12478 (setq dn (string-to-number (match-string 1 change))
12479 dw (cdr (assoc (match-string 2 change) a1)))
12480 (error "Invalid change specifyer: %s" change))
12481 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
12482 (cond
12483 ((eq dw 'day)
12484 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
12485 n2 (+ n1 dn)))
12486 ((eq dw 'year)
12487 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
12488 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
12489 (setq date1 (list m d y1)
12490 n1 (calendar-absolute-from-gregorian date1)
12491 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
12492 n2 (calendar-absolute-from-gregorian date2)))
12493 ((eq dw 'month)
12494 ;; approx number of month between the two dates
12495 (setq nmonths (floor (/ (- cday sday) 30.436875)))
12496 ;; How often does dn fit in there?
12497 (setq d (nth 1 start) m (car start) y (nth 2 start)
12498 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
12499 m (+ m nm)
12500 ny (floor (/ m 12))
12501 y (+ y ny)
12502 m (- m (* ny 12)))
12503 (while (> m 12) (setq m (- m 12) y (1+ y)))
12504 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
12505 (setq m2 (+ m dn) y2 y)
12506 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
12507 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
12508 (while (<= n2 cday)
12509 (setq n1 n2 m m2 y y2)
12510 (setq m2 (+ m dn) y2 y)
12511 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
12512 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
12513 ;; Make sure n1 is the earlier date
12514 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
12515 (if show-all
12516 (cond
12517 ((eq prefer 'past) n1)
12518 ((eq prefer 'future) (if (= cday n1) n1 n2))
12519 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
12520 (cond
12521 ((eq prefer 'past) n1)
12522 ((eq prefer 'future) (if (= cday n1) n1 n2))
12523 (t (if (= cday n1) n1 n2)))))))
12525 (defun org-date-to-gregorian (date)
12526 "Turn any specification of DATE into a gregorian date for the calendar."
12527 (cond ((integerp date) (calendar-gregorian-from-absolute date))
12528 ((and (listp date) (= (length date) 3)) date)
12529 ((stringp date)
12530 (setq date (org-parse-time-string date))
12531 (list (nth 4 date) (nth 3 date) (nth 5 date)))
12532 ((listp date)
12533 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
12535 (defun org-parse-time-string (s &optional nodefault)
12536 "Parse the standard Org-mode time string.
12537 This should be a lot faster than the normal `parse-time-string'.
12538 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
12539 hour and minute fields will be nil if not given."
12540 (if (string-match org-ts-regexp0 s)
12541 (list 0
12542 (if (or (match-beginning 8) (not nodefault))
12543 (string-to-number (or (match-string 8 s) "0")))
12544 (if (or (match-beginning 7) (not nodefault))
12545 (string-to-number (or (match-string 7 s) "0")))
12546 (string-to-number (match-string 4 s))
12547 (string-to-number (match-string 3 s))
12548 (string-to-number (match-string 2 s))
12549 nil nil nil)
12550 (make-list 9 0)))
12552 (defun org-timestamp-up (&optional arg)
12553 "Increase the date item at the cursor by one.
12554 If the cursor is on the year, change the year. If it is on the month or
12555 the day, change that.
12556 With prefix ARG, change by that many units."
12557 (interactive "p")
12558 (org-timestamp-change (prefix-numeric-value arg)))
12560 (defun org-timestamp-down (&optional arg)
12561 "Decrease the date item at the cursor by one.
12562 If the cursor is on the year, change the year. If it is on the month or
12563 the day, change that.
12564 With prefix ARG, change by that many units."
12565 (interactive "p")
12566 (org-timestamp-change (- (prefix-numeric-value arg))))
12568 (defun org-timestamp-up-day (&optional arg)
12569 "Increase the date in the time stamp by one day.
12570 With prefix ARG, change that many days."
12571 (interactive "p")
12572 (if (and (not (org-at-timestamp-p t))
12573 (org-on-heading-p))
12574 (org-todo 'up)
12575 (org-timestamp-change (prefix-numeric-value arg) 'day)))
12577 (defun org-timestamp-down-day (&optional arg)
12578 "Decrease the date in the time stamp by one day.
12579 With prefix ARG, change that many days."
12580 (interactive "p")
12581 (if (and (not (org-at-timestamp-p t))
12582 (org-on-heading-p))
12583 (org-todo 'down)
12584 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
12586 (defun org-at-timestamp-p (&optional inactive-ok)
12587 "Determine if the cursor is in or at a timestamp."
12588 (interactive)
12589 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
12590 (pos (point))
12591 (ans (or (looking-at tsr)
12592 (save-excursion
12593 (skip-chars-backward "^[<\n\r\t")
12594 (if (> (point) (point-min)) (backward-char 1))
12595 (and (looking-at tsr)
12596 (> (- (match-end 0) pos) -1))))))
12597 (and ans
12598 (boundp 'org-ts-what)
12599 (setq org-ts-what
12600 (cond
12601 ((= pos (match-beginning 0)) 'bracket)
12602 ((= pos (1- (match-end 0))) 'bracket)
12603 ((org-pos-in-match-range pos 2) 'year)
12604 ((org-pos-in-match-range pos 3) 'month)
12605 ((org-pos-in-match-range pos 7) 'hour)
12606 ((org-pos-in-match-range pos 8) 'minute)
12607 ((or (org-pos-in-match-range pos 4)
12608 (org-pos-in-match-range pos 5)) 'day)
12609 ((and (> pos (or (match-end 8) (match-end 5)))
12610 (< pos (match-end 0)))
12611 (- pos (or (match-end 8) (match-end 5))))
12612 (t 'day))))
12613 ans))
12615 (defun org-toggle-timestamp-type ()
12616 "Toggle the type (<active> or [inactive]) of a time stamp."
12617 (interactive)
12618 (when (org-at-timestamp-p t)
12619 (let ((beg (match-beginning 0)) (end (match-end 0))
12620 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
12621 (save-excursion
12622 (goto-char beg)
12623 (while (re-search-forward "[][<>]" end t)
12624 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
12625 t t)))
12626 (message "Timestamp is now %sactive"
12627 (if (equal (char-after beg) ?<) "" "in")))))
12629 (defun org-timestamp-change (n &optional what)
12630 "Change the date in the time stamp at point.
12631 The date will be changed by N times WHAT. WHAT can be `day', `month',
12632 `year', `minute', `second'. If WHAT is not given, the cursor position
12633 in the timestamp determines what will be changed."
12634 (let ((pos (point))
12635 with-hm inactive
12636 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
12637 org-ts-what
12638 extra rem
12639 ts time time0)
12640 (if (not (org-at-timestamp-p t))
12641 (error "Not at a timestamp"))
12642 (if (and (not what) (eq org-ts-what 'bracket))
12643 (org-toggle-timestamp-type)
12644 (if (and (not what) (not (eq org-ts-what 'day))
12645 org-display-custom-times
12646 (get-text-property (point) 'display)
12647 (not (get-text-property (1- (point)) 'display)))
12648 (setq org-ts-what 'day))
12649 (setq org-ts-what (or what org-ts-what)
12650 inactive (= (char-after (match-beginning 0)) ?\[)
12651 ts (match-string 0))
12652 (replace-match "")
12653 (if (string-match
12654 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
12656 (setq extra (match-string 1 ts)))
12657 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
12658 (setq with-hm t))
12659 (setq time0 (org-parse-time-string ts))
12660 (when (and (eq org-ts-what 'minute)
12661 (eq current-prefix-arg nil))
12662 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
12663 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
12664 (setcar (cdr time0) (+ (nth 1 time0)
12665 (if (> n 0) (- rem) (- dm rem))))))
12666 (setq time
12667 (encode-time (or (car time0) 0)
12668 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
12669 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
12670 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
12671 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
12672 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
12673 (nthcdr 6 time0)))
12674 (when (and (member org-ts-what '(hour minute))
12675 extra
12676 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
12677 (setq extra (org-modify-ts-extra
12678 extra
12679 (if (eq org-ts-what 'hour) 2 5)
12680 n dm)))
12681 (when (integerp org-ts-what)
12682 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
12683 (if (eq what 'calendar)
12684 (let ((cal-date (org-get-date-from-calendar)))
12685 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
12686 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
12687 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
12688 (setcar time0 (or (car time0) 0))
12689 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
12690 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
12691 (setq time (apply 'encode-time time0))))
12692 (setq org-last-changed-timestamp
12693 (org-insert-time-stamp time with-hm inactive nil nil extra))
12694 (org-clock-update-time-maybe)
12695 (goto-char pos)
12696 ;; Try to recenter the calendar window, if any
12697 (if (and org-calendar-follow-timestamp-change
12698 (get-buffer-window "*Calendar*" t)
12699 (memq org-ts-what '(day month year)))
12700 (org-recenter-calendar (time-to-days time))))))
12702 (defun org-modify-ts-extra (s pos n dm)
12703 "Change the different parts of the lead-time and repeat fields in timestamp."
12704 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
12705 ng h m new rem)
12706 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
12707 (cond
12708 ((or (org-pos-in-match-range pos 2)
12709 (org-pos-in-match-range pos 3))
12710 (setq m (string-to-number (match-string 3 s))
12711 h (string-to-number (match-string 2 s)))
12712 (if (org-pos-in-match-range pos 2)
12713 (setq h (+ h n))
12714 (setq n (* dm (org-no-warnings (signum n))))
12715 (when (not (= 0 (setq rem (% m dm))))
12716 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
12717 (setq m (+ m n)))
12718 (if (< m 0) (setq m (+ m 60) h (1- h)))
12719 (if (> m 59) (setq m (- m 60) h (1+ h)))
12720 (setq h (min 24 (max 0 h)))
12721 (setq ng 1 new (format "-%02d:%02d" h m)))
12722 ((org-pos-in-match-range pos 6)
12723 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
12724 ((org-pos-in-match-range pos 5)
12725 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
12727 ((org-pos-in-match-range pos 9)
12728 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
12729 ((org-pos-in-match-range pos 8)
12730 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
12732 (when ng
12733 (setq s (concat
12734 (substring s 0 (match-beginning ng))
12736 (substring s (match-end ng))))))
12739 (defun org-recenter-calendar (date)
12740 "If the calendar is visible, recenter it to DATE."
12741 (let* ((win (selected-window))
12742 (cwin (get-buffer-window "*Calendar*" t))
12743 (calendar-move-hook nil))
12744 (when cwin
12745 (select-window cwin)
12746 (calendar-goto-date (if (listp date) date
12747 (calendar-gregorian-from-absolute date)))
12748 (select-window win))))
12750 (defun org-goto-calendar (&optional arg)
12751 "Go to the Emacs calendar at the current date.
12752 If there is a time stamp in the current line, go to that date.
12753 A prefix ARG can be used to force the current date."
12754 (interactive "P")
12755 (let ((tsr org-ts-regexp) diff
12756 (calendar-move-hook nil)
12757 (calendar-view-holidays-initially-flag nil)
12758 (view-calendar-holidays-initially nil)
12759 (calendar-view-diary-initially-flag nil)
12760 (view-diary-entries-initially nil))
12761 (if (or (org-at-timestamp-p)
12762 (save-excursion
12763 (beginning-of-line 1)
12764 (looking-at (concat ".*" tsr))))
12765 (let ((d1 (time-to-days (current-time)))
12766 (d2 (time-to-days
12767 (org-time-string-to-time (match-string 1)))))
12768 (setq diff (- d2 d1))))
12769 (calendar)
12770 (calendar-goto-today)
12771 (if (and diff (not arg)) (calendar-forward-day diff))))
12773 (defun org-get-date-from-calendar ()
12774 "Return a list (month day year) of date at point in calendar."
12775 (with-current-buffer "*Calendar*"
12776 (save-match-data
12777 (calendar-cursor-to-date))))
12779 (defun org-date-from-calendar ()
12780 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
12781 If there is already a time stamp at the cursor position, update it."
12782 (interactive)
12783 (if (org-at-timestamp-p t)
12784 (org-timestamp-change 0 'calendar)
12785 (let ((cal-date (org-get-date-from-calendar)))
12786 (org-insert-time-stamp
12787 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
12789 (defun org-minutes-to-hh:mm-string (m)
12790 "Compute H:MM from a number of minutes."
12791 (let ((h (/ m 60)))
12792 (setq m (- m (* 60 h)))
12793 (format org-time-clocksum-format h m)))
12795 (defun org-hh:mm-string-to-minutes (s)
12796 "Convert a string H:MM to a number of minutes."
12797 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
12798 (+ (* (string-to-number (match-string 1 s)) 60)
12799 (string-to-number (match-string 2 s)))
12802 ;;;; Files
12804 (defun org-save-all-org-buffers ()
12805 "Save all Org-mode buffers without user confirmation."
12806 (interactive)
12807 (message "Saving all Org-mode buffers...")
12808 (save-some-buffers t 'org-mode-p)
12809 (when (featurep 'org-id) (org-id-locations-save))
12810 (message "Saving all Org-mode buffers... done"))
12812 (defun org-revert-all-org-buffers ()
12813 "Revert all Org-mode buffers.
12814 Prompt for confirmation when there are unsaved changes.
12815 Be sure you know what you are doing before letting this function
12816 overwrite your changes.
12818 This function is useful in a setup where one tracks org files
12819 with a version control system, to revert on one machine after pulling
12820 changes from another. I believe the procedure must be like this:
12822 1. M-x org-save-all-org-buffers
12823 2. Pull changes from the other machine, resolve conflicts
12824 3. M-x org-revert-all-org-buffers"
12825 (interactive)
12826 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
12827 (error "Abort"))
12828 (save-excursion
12829 (save-window-excursion
12830 (mapc
12831 (lambda (b)
12832 (when (and (with-current-buffer b (org-mode-p))
12833 (with-current-buffer b buffer-file-name))
12834 (switch-to-buffer b)
12835 (revert-buffer t 'no-confirm)))
12836 (buffer-list))
12837 (when (and (featurep 'org-id) org-id-track-globally)
12838 (org-id-locations-load)))))
12840 ;;;; Agenda files
12842 ;;;###autoload
12843 (defun org-iswitchb (&optional arg)
12844 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
12845 With a prefix argument, restrict available to files.
12846 With two prefix arguments, restrict available buffers to agenda files.
12848 Due to some yet unresolved reason, the global function
12849 `iswitchb-mode' needs to be active for this function to work."
12850 (interactive "P")
12851 (require 'iswitchb)
12852 (let ((enabled iswitchb-mode) blist)
12853 (or enabled (iswitchb-mode 1))
12854 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
12855 ((equal arg '(16)) (org-buffer-list 'agenda))
12856 (t (org-buffer-list))))
12857 (unwind-protect
12858 (let ((iswitchb-make-buflist-hook
12859 (lambda ()
12860 (setq iswitchb-temp-buflist
12861 (mapcar 'buffer-name blist)))))
12862 (switch-to-buffer
12863 (iswitchb-read-buffer
12864 "Switch-to: " nil t))
12865 (or enabled (iswitchb-mode -1))))))
12867 ;;;###autoload
12868 (defun org-ido-switchb (&optional arg)
12869 "Use `org-ido-completing-read' to prompt for an Org buffer to switch to.
12870 With a prefix argument, restrict available to files.
12871 With two prefix arguments, restrict available buffers to agenda files."
12872 (interactive "P")
12873 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
12874 ((equal arg '(16)) (org-buffer-list 'agenda))
12875 (t (org-buffer-list)))))
12876 (switch-to-buffer
12877 (org-ido-completing-read "Org buffer: "
12878 (mapcar 'list (mapcar 'buffer-name blist))
12879 nil t))))
12881 (defun org-buffer-list (&optional predicate exclude-tmp)
12882 "Return a list of Org buffers.
12883 PREDICATE can be `export', `files' or `agenda'.
12885 export restrict the list to Export buffers.
12886 files restrict the list to buffers visiting Org files.
12887 agenda restrict the list to buffers visiting agenda files.
12889 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
12890 (let* ((bfn nil)
12891 (agenda-files (and (eq predicate 'agenda)
12892 (mapcar 'file-truename (org-agenda-files t))))
12893 (filter
12894 (cond
12895 ((eq predicate 'files)
12896 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
12897 ((eq predicate 'export)
12898 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
12899 ((eq predicate 'agenda)
12900 (lambda (b)
12901 (with-current-buffer b
12902 (and (eq major-mode 'org-mode)
12903 (setq bfn (buffer-file-name b))
12904 (member (file-truename bfn) agenda-files)))))
12905 (t (lambda (b) (with-current-buffer b
12906 (or (eq major-mode 'org-mode)
12907 (string-match "\*Org .*Export"
12908 (buffer-name b)))))))))
12909 (delq nil
12910 (mapcar
12911 (lambda(b)
12912 (if (and (funcall filter b)
12913 (or (not exclude-tmp)
12914 (not (string-match "tmp" (buffer-name b)))))
12916 nil))
12917 (buffer-list)))))
12919 (defun org-agenda-files (&optional unrestricted archives)
12920 "Get the list of agenda files.
12921 Optional UNRESTRICTED means return the full list even if a restriction
12922 is currently in place.
12923 When ARCHIVES is t, include all archive files hat are really being
12924 used by the agenda files. If ARCHIVE is `ifmode', do this only if
12925 `org-agenda-archives-mode' is t."
12926 (let ((files
12927 (cond
12928 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
12929 ((stringp org-agenda-files) (org-read-agenda-file-list))
12930 ((listp org-agenda-files) org-agenda-files)
12931 (t (error "Invalid value of `org-agenda-files'")))))
12932 (setq files (apply 'append
12933 (mapcar (lambda (f)
12934 (if (file-directory-p f)
12935 (directory-files
12936 f t org-agenda-file-regexp)
12937 (list f)))
12938 files)))
12939 (when org-agenda-skip-unavailable-files
12940 (setq files (delq nil
12941 (mapcar (function
12942 (lambda (file)
12943 (and (file-readable-p file) file)))
12944 files))))
12945 (when (or (eq archives t)
12946 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
12947 (setq files (org-add-archive-files files)))
12948 files))
12950 (defun org-edit-agenda-file-list ()
12951 "Edit the list of agenda files.
12952 Depending on setup, this either uses customize to edit the variable
12953 `org-agenda-files', or it visits the file that is holding the list. In the
12954 latter case, the buffer is set up in a way that saving it automatically kills
12955 the buffer and restores the previous window configuration."
12956 (interactive)
12957 (if (stringp org-agenda-files)
12958 (let ((cw (current-window-configuration)))
12959 (find-file org-agenda-files)
12960 (org-set-local 'org-window-configuration cw)
12961 (org-add-hook 'after-save-hook
12962 (lambda ()
12963 (set-window-configuration
12964 (prog1 org-window-configuration
12965 (kill-buffer (current-buffer))))
12966 (org-install-agenda-files-menu)
12967 (message "New agenda file list installed"))
12968 nil 'local)
12969 (message "%s" (substitute-command-keys
12970 "Edit list and finish with \\[save-buffer]")))
12971 (customize-variable 'org-agenda-files)))
12973 (defun org-store-new-agenda-file-list (list)
12974 "Set new value for the agenda file list and save it correctly."
12975 (if (stringp org-agenda-files)
12976 (let ((f org-agenda-files) b)
12977 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
12978 (with-temp-file f
12979 (insert (mapconcat 'identity list "\n") "\n")))
12980 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
12981 (setq org-agenda-files list)
12982 (customize-save-variable 'org-agenda-files org-agenda-files))))
12984 (defun org-read-agenda-file-list ()
12985 "Read the list of agenda files from a file."
12986 (when (file-directory-p org-agenda-files)
12987 (error "`org-agenda-files' cannot be a single directory"))
12988 (when (stringp org-agenda-files)
12989 (with-temp-buffer
12990 (insert-file-contents org-agenda-files)
12991 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
12994 ;;;###autoload
12995 (defun org-cycle-agenda-files ()
12996 "Cycle through the files in `org-agenda-files'.
12997 If the current buffer visits an agenda file, find the next one in the list.
12998 If the current buffer does not, find the first agenda file."
12999 (interactive)
13000 (let* ((fs (org-agenda-files t))
13001 (files (append fs (list (car fs))))
13002 (tcf (if buffer-file-name (file-truename buffer-file-name)))
13003 file)
13004 (unless files (error "No agenda files"))
13005 (catch 'exit
13006 (while (setq file (pop files))
13007 (if (equal (file-truename file) tcf)
13008 (when (car files)
13009 (find-file (car files))
13010 (throw 'exit t))))
13011 (find-file (car fs)))
13012 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
13014 (defun org-agenda-file-to-front (&optional to-end)
13015 "Move/add the current file to the top of the agenda file list.
13016 If the file is not present in the list, it is added to the front. If it is
13017 present, it is moved there. With optional argument TO-END, add/move to the
13018 end of the list."
13019 (interactive "P")
13020 (let ((org-agenda-skip-unavailable-files nil)
13021 (file-alist (mapcar (lambda (x)
13022 (cons (file-truename x) x))
13023 (org-agenda-files t)))
13024 (ctf (file-truename buffer-file-name))
13025 x had)
13026 (setq x (assoc ctf file-alist) had x)
13028 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
13029 (if to-end
13030 (setq file-alist (append (delq x file-alist) (list x)))
13031 (setq file-alist (cons x (delq x file-alist))))
13032 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
13033 (org-install-agenda-files-menu)
13034 (message "File %s to %s of agenda file list"
13035 (if had "moved" "added") (if to-end "end" "front"))))
13037 (defun org-remove-file (&optional file)
13038 "Remove current file from the list of files in variable `org-agenda-files'.
13039 These are the files which are being checked for agenda entries.
13040 Optional argument FILE means, use this file instead of the current."
13041 (interactive)
13042 (let* ((org-agenda-skip-unavailable-files nil)
13043 (file (or file buffer-file-name))
13044 (true-file (file-truename file))
13045 (afile (abbreviate-file-name file))
13046 (files (delq nil (mapcar
13047 (lambda (x)
13048 (if (equal true-file
13049 (file-truename x))
13050 nil x))
13051 (org-agenda-files t)))))
13052 (if (not (= (length files) (length (org-agenda-files t))))
13053 (progn
13054 (org-store-new-agenda-file-list files)
13055 (org-install-agenda-files-menu)
13056 (message "Removed file: %s" afile))
13057 (message "File was not in list: %s (not removed)" afile))))
13059 (defun org-file-menu-entry (file)
13060 (vector file (list 'find-file file) t))
13062 (defun org-check-agenda-file (file)
13063 "Make sure FILE exists. If not, ask user what to do."
13064 (when (not (file-exists-p file))
13065 (message "non-existent file %s. [R]emove from list or [A]bort?"
13066 (abbreviate-file-name file))
13067 (let ((r (downcase (read-char-exclusive))))
13068 (cond
13069 ((equal r ?r)
13070 (org-remove-file file)
13071 (throw 'nextfile t))
13072 (t (error "Abort"))))))
13074 (defun org-get-agenda-file-buffer (file)
13075 "Get a buffer visiting FILE. If the buffer needs to be created, add
13076 it to the list of buffers which might be released later."
13077 (let ((buf (org-find-base-buffer-visiting file)))
13078 (if buf
13079 buf ; just return it
13080 ;; Make a new buffer and remember it
13081 (setq buf (find-file-noselect file))
13082 (if buf (push buf org-agenda-new-buffers))
13083 buf)))
13085 (defun org-release-buffers (blist)
13086 "Release all buffers in list, asking the user for confirmation when needed.
13087 When a buffer is unmodified, it is just killed. When modified, it is saved
13088 \(if the user agrees) and then killed."
13089 (let (buf file)
13090 (while (setq buf (pop blist))
13091 (setq file (buffer-file-name buf))
13092 (when (and (buffer-modified-p buf)
13093 file
13094 (y-or-n-p (format "Save file %s? " file)))
13095 (with-current-buffer buf (save-buffer)))
13096 (kill-buffer buf))))
13098 (defun org-prepare-agenda-buffers (files)
13099 "Create buffers for all agenda files, protect archived trees and comments."
13100 (interactive)
13101 (let ((pa '(:org-archived t))
13102 (pc '(:org-comment t))
13103 (pall '(:org-archived t :org-comment t))
13104 (inhibit-read-only t)
13105 (rea (concat ":" org-archive-tag ":"))
13106 bmp file re)
13107 (save-excursion
13108 (save-restriction
13109 (while (setq file (pop files))
13110 (if (bufferp file)
13111 (set-buffer file)
13112 (org-check-agenda-file file)
13113 (set-buffer (org-get-agenda-file-buffer file)))
13114 (widen)
13115 (setq bmp (buffer-modified-p))
13116 (org-refresh-category-properties)
13117 (setq org-todo-keywords-for-agenda
13118 (append org-todo-keywords-for-agenda org-todo-keywords-1))
13119 (setq org-done-keywords-for-agenda
13120 (append org-done-keywords-for-agenda org-done-keywords))
13121 (setq org-todo-keyword-alist-for-agenda
13122 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
13123 (setq org-tag-alist-for-agenda
13124 (append org-tag-alist-for-agenda org-tag-alist))
13126 (save-excursion
13127 (remove-text-properties (point-min) (point-max) pall)
13128 (when org-agenda-skip-archived-trees
13129 (goto-char (point-min))
13130 (while (re-search-forward rea nil t)
13131 (if (org-on-heading-p t)
13132 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
13133 (goto-char (point-min))
13134 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
13135 (while (re-search-forward re nil t)
13136 (add-text-properties
13137 (match-beginning 0) (org-end-of-subtree t) pc)))
13138 (set-buffer-modified-p bmp))))
13139 (setq org-todo-keyword-alist-for-agenda
13140 (org-uniquify org-todo-keyword-alist-for-agenda)
13141 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
13143 ;;;; Embedded LaTeX
13145 (defvar org-cdlatex-mode-map (make-sparse-keymap)
13146 "Keymap for the minor `org-cdlatex-mode'.")
13148 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
13149 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
13150 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
13151 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
13152 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
13154 (defvar org-cdlatex-texmathp-advice-is-done nil
13155 "Flag remembering if we have applied the advice to texmathp already.")
13157 (define-minor-mode org-cdlatex-mode
13158 "Toggle the minor `org-cdlatex-mode'.
13159 This mode supports entering LaTeX environment and math in LaTeX fragments
13160 in Org-mode.
13161 \\{org-cdlatex-mode-map}"
13162 nil " OCDL" nil
13163 (when org-cdlatex-mode (require 'cdlatex))
13164 (unless org-cdlatex-texmathp-advice-is-done
13165 (setq org-cdlatex-texmathp-advice-is-done t)
13166 (defadvice texmathp (around org-math-always-on activate)
13167 "Always return t in org-mode buffers.
13168 This is because we want to insert math symbols without dollars even outside
13169 the LaTeX math segments. If Orgmode thinks that point is actually inside
13170 an embedded LaTeX fragment, let texmathp do its job.
13171 \\[org-cdlatex-mode-map]"
13172 (interactive)
13173 (let (p)
13174 (cond
13175 ((not (org-mode-p)) ad-do-it)
13176 ((eq this-command 'cdlatex-math-symbol)
13177 (setq ad-return-value t
13178 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
13180 (let ((p (org-inside-LaTeX-fragment-p)))
13181 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
13182 (setq ad-return-value t
13183 texmathp-why '("Org-mode embedded math" . 0))
13184 (if p ad-do-it)))))))))
13186 (defun turn-on-org-cdlatex ()
13187 "Unconditionally turn on `org-cdlatex-mode'."
13188 (org-cdlatex-mode 1))
13190 (defun org-inside-LaTeX-fragment-p ()
13191 "Test if point is inside a LaTeX fragment.
13192 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
13193 sequence appearing also before point.
13194 Even though the matchers for math are configurable, this function assumes
13195 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
13196 delimiters are skipped when they have been removed by customization.
13197 The return value is nil, or a cons cell with the delimiter and
13198 and the position of this delimiter.
13200 This function does a reasonably good job, but can locally be fooled by
13201 for example currency specifications. For example it will assume being in
13202 inline math after \"$22.34\". The LaTeX fragment formatter will only format
13203 fragments that are properly closed, but during editing, we have to live
13204 with the uncertainty caused by missing closing delimiters. This function
13205 looks only before point, not after."
13206 (catch 'exit
13207 (let ((pos (point))
13208 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
13209 (lim (progn
13210 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
13211 (point)))
13212 dd-on str (start 0) m re)
13213 (goto-char pos)
13214 (when dodollar
13215 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
13216 re (nth 1 (assoc "$" org-latex-regexps)))
13217 (while (string-match re str start)
13218 (cond
13219 ((= (match-end 0) (length str))
13220 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
13221 ((= (match-end 0) (- (length str) 5))
13222 (throw 'exit nil))
13223 (t (setq start (match-end 0))))))
13224 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
13225 (goto-char pos)
13226 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
13227 (and (match-beginning 2) (throw 'exit nil))
13228 ;; count $$
13229 (while (re-search-backward "\\$\\$" lim t)
13230 (setq dd-on (not dd-on)))
13231 (goto-char pos)
13232 (if dd-on (cons "$$" m))))))
13235 (defun org-try-cdlatex-tab ()
13236 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
13237 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
13238 - inside a LaTeX fragment, or
13239 - after the first word in a line, where an abbreviation expansion could
13240 insert a LaTeX environment."
13241 (when org-cdlatex-mode
13242 (cond
13243 ((save-excursion
13244 (skip-chars-backward "a-zA-Z0-9*")
13245 (skip-chars-backward " \t")
13246 (bolp))
13247 (cdlatex-tab) t)
13248 ((org-inside-LaTeX-fragment-p)
13249 (cdlatex-tab) t)
13250 (t nil))))
13252 (defun org-cdlatex-underscore-caret (&optional arg)
13253 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
13254 Revert to the normal definition outside of these fragments."
13255 (interactive "P")
13256 (if (org-inside-LaTeX-fragment-p)
13257 (call-interactively 'cdlatex-sub-superscript)
13258 (let (org-cdlatex-mode)
13259 (call-interactively (key-binding (vector last-input-event))))))
13261 (defun org-cdlatex-math-modify (&optional arg)
13262 "Execute `cdlatex-math-modify' in LaTeX fragments.
13263 Revert to the normal definition outside of these fragments."
13264 (interactive "P")
13265 (if (org-inside-LaTeX-fragment-p)
13266 (call-interactively 'cdlatex-math-modify)
13267 (let (org-cdlatex-mode)
13268 (call-interactively (key-binding (vector last-input-event))))))
13270 (defvar org-latex-fragment-image-overlays nil
13271 "List of overlays carrying the images of latex fragments.")
13272 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
13274 (defun org-remove-latex-fragment-image-overlays ()
13275 "Remove all overlays with LaTeX fragment images in current buffer."
13276 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
13277 (setq org-latex-fragment-image-overlays nil))
13279 (defun org-preview-latex-fragment (&optional subtree)
13280 "Preview the LaTeX fragment at point, or all locally or globally.
13281 If the cursor is in a LaTeX fragment, create the image and overlay
13282 it over the source code. If there is no fragment at point, display
13283 all fragments in the current text, from one headline to the next. With
13284 prefix SUBTREE, display all fragments in the current subtree. With a
13285 double prefix `C-u C-u', or when the cursor is before the first headline,
13286 display all fragments in the buffer.
13287 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
13288 (interactive "P")
13289 (org-remove-latex-fragment-image-overlays)
13290 (save-excursion
13291 (save-restriction
13292 (let (beg end at msg)
13293 (cond
13294 ((or (equal subtree '(16))
13295 (not (save-excursion
13296 (re-search-backward (concat "^" outline-regexp) nil t))))
13297 (setq beg (point-min) end (point-max)
13298 msg "Creating images for buffer...%s"))
13299 ((equal subtree '(4))
13300 (org-back-to-heading)
13301 (setq beg (point) end (org-end-of-subtree t)
13302 msg "Creating images for subtree...%s"))
13304 (if (setq at (org-inside-LaTeX-fragment-p))
13305 (goto-char (max (point-min) (- (cdr at) 2)))
13306 (org-back-to-heading))
13307 (setq beg (point) end (progn (outline-next-heading) (point))
13308 msg (if at "Creating image...%s"
13309 "Creating images for entry...%s"))))
13310 (message msg "")
13311 (narrow-to-region beg end)
13312 (goto-char beg)
13313 (org-format-latex
13314 (concat "ltxpng/" (file-name-sans-extension
13315 (file-name-nondirectory
13316 buffer-file-name)))
13317 default-directory 'overlays msg at 'forbuffer)
13318 (message msg "done. Use `C-c C-c' to remove images.")))))
13320 (defvar org-latex-regexps
13321 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
13322 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
13323 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
13324 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
13325 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
13326 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
13327 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
13328 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
13329 "Regular expressions for matching embedded LaTeX.")
13331 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
13332 "Replace LaTeX fragments with links to an image, and produce images."
13333 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
13334 (let* ((prefixnodir (file-name-nondirectory prefix))
13335 (absprefix (expand-file-name prefix dir))
13336 (todir (file-name-directory absprefix))
13337 (opt org-format-latex-options)
13338 (matchers (plist-get opt :matchers))
13339 (re-list org-latex-regexps)
13340 (cnt 0) txt link beg end re e checkdir
13341 m n block linkfile movefile ov)
13342 ;; Check if there are old images files with this prefix, and remove them
13343 (when (file-directory-p todir)
13344 (mapc 'delete-file
13345 (directory-files
13346 todir 'full
13347 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
13348 ;; Check the different regular expressions
13349 (while (setq e (pop re-list))
13350 (setq m (car e) re (nth 1 e) n (nth 2 e)
13351 block (if (nth 3 e) "\n\n" ""))
13352 (when (member m matchers)
13353 (goto-char (point-min))
13354 (while (re-search-forward re nil t)
13355 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
13356 (not (get-text-property (match-beginning n)
13357 'org-protected)))
13358 (setq txt (match-string n)
13359 beg (match-beginning n) end (match-end n)
13360 cnt (1+ cnt)
13361 linkfile (format "%s_%04d.png" prefix cnt)
13362 movefile (format "%s_%04d.png" absprefix cnt)
13363 link (concat block "[[file:" linkfile "]]" block))
13364 (if msg (message msg cnt))
13365 (goto-char beg)
13366 (unless checkdir ; make sure the directory exists
13367 (setq checkdir t)
13368 (or (file-directory-p todir) (make-directory todir)))
13369 (org-create-formula-image
13370 txt movefile opt forbuffer)
13371 (if overlays
13372 (progn
13373 (setq ov (org-make-overlay beg end))
13374 (if (featurep 'xemacs)
13375 (progn
13376 (org-overlay-put ov 'invisible t)
13377 (org-overlay-put
13378 ov 'end-glyph
13379 (make-glyph (vector 'png :file movefile))))
13380 (org-overlay-put
13381 ov 'display
13382 (list 'image :type 'png :file movefile :ascent 'center)))
13383 (push ov org-latex-fragment-image-overlays)
13384 (goto-char end))
13385 (delete-region beg end)
13386 (insert link))))))))
13388 ;; This function borrows from Ganesh Swami's latex2png.el
13389 (defun org-create-formula-image (string tofile options buffer)
13390 (let* ((tmpdir (if (featurep 'xemacs)
13391 (temp-directory)
13392 temporary-file-directory))
13393 (texfilebase (make-temp-name
13394 (expand-file-name "orgtex" tmpdir)))
13395 (texfile (concat texfilebase ".tex"))
13396 (dvifile (concat texfilebase ".dvi"))
13397 (pngfile (concat texfilebase ".png"))
13398 (fnh (if (featurep 'xemacs)
13399 (font-height (get-face-font 'default))
13400 (face-attribute 'default :height nil)))
13401 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
13402 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
13403 (fg (or (plist-get options (if buffer :foreground :html-foreground))
13404 "Black"))
13405 (bg (or (plist-get options (if buffer :background :html-background))
13406 "Transparent")))
13407 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
13408 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
13409 (with-temp-file texfile
13410 (insert org-format-latex-header
13411 "\n\\begin{document}\n" string "\n\\end{document}\n"))
13412 (let ((dir default-directory))
13413 (condition-case nil
13414 (progn
13415 (cd tmpdir)
13416 (call-process "latex" nil nil nil texfile))
13417 (error nil))
13418 (cd dir))
13419 (if (not (file-exists-p dvifile))
13420 (progn (message "Failed to create dvi file from %s" texfile) nil)
13421 (condition-case nil
13422 (call-process "dvipng" nil nil nil
13423 "-E" "-fg" fg "-bg" bg
13424 "-D" dpi
13425 ;;"-x" scale "-y" scale
13426 "-T" "tight"
13427 "-o" pngfile
13428 dvifile)
13429 (error nil))
13430 (if (not (file-exists-p pngfile))
13431 (progn (message "Failed to create png file from %s" texfile) nil)
13432 ;; Use the requested file name and clean up
13433 (copy-file pngfile tofile 'replace)
13434 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
13435 (delete-file (concat texfilebase e)))
13436 pngfile))))
13438 (defun org-dvipng-color (attr)
13439 "Return an rgb color specification for dvipng."
13440 (apply 'format "rgb %s %s %s"
13441 (mapcar 'org-normalize-color
13442 (color-values (face-attribute 'default attr nil)))))
13444 (defun org-normalize-color (value)
13445 "Return string to be used as color value for an RGB component."
13446 (format "%g" (/ value 65535.0)))
13448 ;;;; Key bindings
13450 ;; Make `C-c C-x' a prefix key
13451 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
13453 ;; TAB key with modifiers
13454 (org-defkey org-mode-map "\C-i" 'org-cycle)
13455 (org-defkey org-mode-map [(tab)] 'org-cycle)
13456 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
13457 (org-defkey org-mode-map [(meta tab)] 'org-complete)
13458 (org-defkey org-mode-map "\M-\t" 'org-complete)
13459 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
13460 ;; The following line is necessary under Suse GNU/Linux
13461 (unless (featurep 'xemacs)
13462 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
13463 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
13464 (define-key org-mode-map [backtab] 'org-shifttab)
13466 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
13467 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
13468 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
13470 ;; Cursor keys with modifiers
13471 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
13472 (org-defkey org-mode-map [(meta right)] 'org-metaright)
13473 (org-defkey org-mode-map [(meta up)] 'org-metaup)
13474 (org-defkey org-mode-map [(meta down)] 'org-metadown)
13476 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
13477 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
13478 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
13479 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
13481 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
13482 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
13483 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
13484 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
13486 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
13487 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
13489 ;;; Extra keys for tty access.
13490 ;; We only set them when really needed because otherwise the
13491 ;; menus don't show the simple keys
13493 (when (or org-use-extra-keys
13494 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
13495 (not window-system))
13496 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
13497 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
13498 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
13499 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
13500 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
13501 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
13502 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
13503 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
13504 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
13505 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
13506 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
13507 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
13508 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
13509 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
13510 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
13511 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
13512 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
13513 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
13514 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
13515 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
13516 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
13517 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
13519 ;; All the other keys
13521 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
13522 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
13523 (if (boundp 'narrow-map)
13524 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
13525 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
13526 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
13527 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
13528 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
13529 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
13530 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
13531 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
13532 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
13533 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
13534 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
13535 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
13536 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
13537 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
13538 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
13539 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
13540 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
13541 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
13542 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
13543 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
13544 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
13545 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
13546 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
13547 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
13548 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
13549 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
13550 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
13551 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
13552 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
13553 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
13554 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
13555 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
13556 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
13557 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
13558 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
13559 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
13560 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
13561 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
13562 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
13563 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
13564 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
13565 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
13566 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
13567 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
13568 (org-defkey org-mode-map "\C-c^" 'org-sort)
13569 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
13570 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
13571 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
13572 (org-defkey org-mode-map "\C-m" 'org-return)
13573 (org-defkey org-mode-map "\C-j" 'org-return-indent)
13574 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
13575 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
13576 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
13577 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
13578 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
13579 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
13580 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
13581 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
13582 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
13583 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
13584 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
13585 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
13586 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
13587 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
13588 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
13589 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
13591 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
13592 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
13593 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
13594 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
13596 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
13597 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
13598 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
13599 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
13600 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
13601 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
13602 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
13603 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
13604 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
13605 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
13606 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
13607 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
13608 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
13610 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
13611 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
13612 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
13613 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
13615 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
13617 (define-key org-mode-map "\C-c\C-xr" 'org-reload)
13619 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
13620 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
13622 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
13625 (when (featurep 'xemacs)
13626 (org-defkey org-mode-map 'button3 'popup-mode-menu))
13629 (defvar org-self-insert-command-undo-counter 0)
13631 (defvar org-table-auto-blank-field) ; defined in org-table.el
13632 (defun org-self-insert-command (N)
13633 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
13634 If the cursor is in a table looking at whitespace, the whitespace is
13635 overwritten, and the table is not marked as requiring realignment."
13636 (interactive "p")
13637 (if (and
13638 (org-table-p)
13639 (progn
13640 ;; check if we blank the field, and if that triggers align
13641 (and (featurep 'org-table) org-table-auto-blank-field
13642 (member last-command
13643 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
13644 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
13645 ;; got extra space, this field does not determine column width
13646 (let (org-table-may-need-update) (org-table-blank-field))
13647 ;; no extra space, this field may determine column width
13648 (org-table-blank-field)))
13650 (eq N 1)
13651 (looking-at "[^|\n]* |"))
13652 (let (org-table-may-need-update)
13653 (goto-char (1- (match-end 0)))
13654 (delete-backward-char 1)
13655 (goto-char (match-beginning 0))
13656 (self-insert-command N))
13657 (setq org-table-may-need-update t)
13658 (self-insert-command N)
13659 (org-fix-tags-on-the-fly)
13660 (if org-self-insert-cluster-for-undo
13661 (if (not (eq last-command 'org-self-insert-command))
13662 (setq org-self-insert-command-undo-counter 1)
13663 (if (>= org-self-insert-command-undo-counter 20)
13664 (setq org-self-insert-command-undo-counter 1)
13665 (and (> org-self-insert-command-undo-counter 0)
13666 buffer-undo-list
13667 (not (cadr buffer-undo-list)) ; remove nil entry
13668 (setcdr buffer-undo-list (cddr buffer-undo-list)))
13669 (setq org-self-insert-command-undo-counter
13670 (1+ org-self-insert-command-undo-counter)))))))
13672 (defun org-fix-tags-on-the-fly ()
13673 (when (and (equal (char-after (point-at-bol)) ?*)
13674 (org-on-heading-p))
13675 (org-align-tags-here org-tags-column)))
13677 (defun org-delete-backward-char (N)
13678 "Like `delete-backward-char', insert whitespace at field end in tables.
13679 When deleting backwards, in tables this function will insert whitespace in
13680 front of the next \"|\" separator, to keep the table aligned. The table will
13681 still be marked for re-alignment if the field did fill the entire column,
13682 because, in this case the deletion might narrow the column."
13683 (interactive "p")
13684 (if (and (org-table-p)
13685 (eq N 1)
13686 (string-match "|" (buffer-substring (point-at-bol) (point)))
13687 (looking-at ".*?|"))
13688 (let ((pos (point))
13689 (noalign (looking-at "[^|\n\r]* |"))
13690 (c org-table-may-need-update))
13691 (backward-delete-char N)
13692 (skip-chars-forward "^|")
13693 (insert " ")
13694 (goto-char (1- pos))
13695 ;; noalign: if there were two spaces at the end, this field
13696 ;; does not determine the width of the column.
13697 (if noalign (setq org-table-may-need-update c)))
13698 (backward-delete-char N)
13699 (org-fix-tags-on-the-fly)))
13701 (defun org-delete-char (N)
13702 "Like `delete-char', but insert whitespace at field end in tables.
13703 When deleting characters, in tables this function will insert whitespace in
13704 front of the next \"|\" separator, to keep the table aligned. The table will
13705 still be marked for re-alignment if the field did fill the entire column,
13706 because, in this case the deletion might narrow the column."
13707 (interactive "p")
13708 (if (and (org-table-p)
13709 (not (bolp))
13710 (not (= (char-after) ?|))
13711 (eq N 1))
13712 (if (looking-at ".*?|")
13713 (let ((pos (point))
13714 (noalign (looking-at "[^|\n\r]* |"))
13715 (c org-table-may-need-update))
13716 (replace-match (concat
13717 (substring (match-string 0) 1 -1)
13718 " |"))
13719 (goto-char pos)
13720 ;; noalign: if there were two spaces at the end, this field
13721 ;; does not determine the width of the column.
13722 (if noalign (setq org-table-may-need-update c)))
13723 (delete-char N))
13724 (delete-char N)
13725 (org-fix-tags-on-the-fly)))
13727 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
13728 (put 'org-self-insert-command 'delete-selection t)
13729 (put 'orgtbl-self-insert-command 'delete-selection t)
13730 (put 'org-delete-char 'delete-selection 'supersede)
13731 (put 'org-delete-backward-char 'delete-selection 'supersede)
13732 (put 'org-yank 'delete-selection 'yank)
13734 ;; Make `flyspell-mode' delay after some commands
13735 (put 'org-self-insert-command 'flyspell-delayed t)
13736 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
13737 (put 'org-delete-char 'flyspell-delayed t)
13738 (put 'org-delete-backward-char 'flyspell-delayed t)
13740 ;; Make pabbrev-mode expand after org-mode commands
13741 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
13742 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
13744 ;; How to do this: Measure non-white length of current string
13745 ;; If equal to column width, we should realign.
13747 (defun org-remap (map &rest commands)
13748 "In MAP, remap the functions given in COMMANDS.
13749 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
13750 (let (new old)
13751 (while commands
13752 (setq old (pop commands) new (pop commands))
13753 (if (fboundp 'command-remapping)
13754 (org-defkey map (vector 'remap old) new)
13755 (substitute-key-definition old new map global-map)))))
13757 (when (eq org-enable-table-editor 'optimized)
13758 ;; If the user wants maximum table support, we need to hijack
13759 ;; some standard editing functions
13760 (org-remap org-mode-map
13761 'self-insert-command 'org-self-insert-command
13762 'delete-char 'org-delete-char
13763 'delete-backward-char 'org-delete-backward-char)
13764 (org-defkey org-mode-map "|" 'org-force-self-insert))
13766 (defvar org-ctrl-c-ctrl-c-hook nil
13767 "Hook for functions attaching themselves to `C-c C-c'.
13768 This can be used to add additional functionality to the C-c C-c key which
13769 executes context-dependent commands.
13770 Each function will be called with no arguments. The function must check
13771 if the context is appropriate for it to act. If yes, it should do its
13772 thing and then return a non-nil value. If the context is wrong,
13773 just do nothing.")
13775 (defvar org-metaleft-hook nil
13776 "Hook for functions attaching themselves to `M-left'.
13777 See `org-ctrl-c-ctrl-c-hook' for more information.")
13778 (defvar org-metaright-hook nil
13779 "Hook for functions attaching themselves to `M-right'.
13780 See `org-ctrl-c-ctrl-c-hook' for more information.")
13781 (defvar org-metaup-hook nil
13782 "Hook for functions attaching themselves to `M-up'.
13783 See `org-ctrl-c-ctrl-c-hook' for more information.")
13784 (defvar org-metadown-hook nil
13785 "Hook for functions attaching themselves to `M-down'.
13786 See `org-ctrl-c-ctrl-c-hook' for more information.")
13787 (defvar org-shiftmetaleft-hook nil
13788 "Hook for functions attaching themselves to `M-S-left'.
13789 See `org-ctrl-c-ctrl-c-hook' for more information.")
13790 (defvar org-shiftmetaright-hook nil
13791 "Hook for functions attaching themselves to `M-S-right'.
13792 See `org-ctrl-c-ctrl-c-hook' for more information.")
13793 (defvar org-shiftmetaup-hook nil
13794 "Hook for functions attaching themselves to `M-S-up'.
13795 See `org-ctrl-c-ctrl-c-hook' for more information.")
13796 (defvar org-shiftmetadown-hook nil
13797 "Hook for functions attaching themselves to `M-S-down'.
13798 See `org-ctrl-c-ctrl-c-hook' for more information.")
13799 (defvar org-metareturn-hook nil
13800 "Hook for functions attaching themselves to `M-RET'.
13801 See `org-ctrl-c-ctrl-c-hook' for more information.")
13803 (defun org-modifier-cursor-error ()
13804 "Throw an error, a modified cursor command was applied in wrong context."
13805 (error "This command is active in special context like tables, headlines or items"))
13807 (defun org-shiftselect-error ()
13808 "Throw an error because Shift-Cursor command was applied in wrong context."
13809 (if (and (boundp 'shift-select-mode) shift-select-mode)
13810 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'.")
13811 (error "This command works only in special context like headlines or timestamps.")))
13813 (defun org-call-for-shift-select (cmd)
13814 (let ((this-command-keys-shift-translated t))
13815 (call-interactively cmd)))
13817 (defun org-shifttab (&optional arg)
13818 "Global visibility cycling or move to previous table field.
13819 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
13820 on context.
13821 See the individual commands for more information."
13822 (interactive "P")
13823 (cond
13824 ((org-at-table-p) (call-interactively 'org-table-previous-field))
13825 ((integerp arg)
13826 (message "Content view to level: %d" arg)
13827 (org-content (prefix-numeric-value arg))
13828 (setq org-cycle-global-status 'overview))
13829 (t (call-interactively 'org-global-cycle))))
13831 (defun org-shiftmetaleft ()
13832 "Promote subtree or delete table column.
13833 Calls `org-promote-subtree', `org-outdent-item',
13834 or `org-table-delete-column', depending on context.
13835 See the individual commands for more information."
13836 (interactive)
13837 (cond
13838 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
13839 ((org-at-table-p) (call-interactively 'org-table-delete-column))
13840 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
13841 ((org-at-item-p) (call-interactively 'org-outdent-item))
13842 (t (org-modifier-cursor-error))))
13844 (defun org-shiftmetaright ()
13845 "Demote subtree or insert table column.
13846 Calls `org-demote-subtree', `org-indent-item',
13847 or `org-table-insert-column', depending on context.
13848 See the individual commands for more information."
13849 (interactive)
13850 (cond
13851 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
13852 ((org-at-table-p) (call-interactively 'org-table-insert-column))
13853 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
13854 ((org-at-item-p) (call-interactively 'org-indent-item))
13855 (t (org-modifier-cursor-error))))
13857 (defun org-shiftmetaup (&optional arg)
13858 "Move subtree up or kill table row.
13859 Calls `org-move-subtree-up' or `org-table-kill-row' or
13860 `org-move-item-up' depending on context. See the individual commands
13861 for more information."
13862 (interactive "P")
13863 (cond
13864 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
13865 ((org-at-table-p) (call-interactively 'org-table-kill-row))
13866 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
13867 ((org-at-item-p) (call-interactively 'org-move-item-up))
13868 (t (org-modifier-cursor-error))))
13870 (defun org-shiftmetadown (&optional arg)
13871 "Move subtree down or insert table row.
13872 Calls `org-move-subtree-down' or `org-table-insert-row' or
13873 `org-move-item-down', depending on context. See the individual
13874 commands for more information."
13875 (interactive "P")
13876 (cond
13877 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
13878 ((org-at-table-p) (call-interactively 'org-table-insert-row))
13879 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
13880 ((org-at-item-p) (call-interactively 'org-move-item-down))
13881 (t (org-modifier-cursor-error))))
13883 (defun org-metaleft (&optional arg)
13884 "Promote heading or move table column to left.
13885 Calls `org-do-promote' or `org-table-move-column', depending on context.
13886 With no specific context, calls the Emacs default `backward-word'.
13887 See the individual commands for more information."
13888 (interactive "P")
13889 (cond
13890 ((run-hook-with-args-until-success 'org-metaleft-hook))
13891 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
13892 ((or (org-on-heading-p)
13893 (and (org-region-active-p)
13894 (save-excursion
13895 (goto-char (region-beginning))
13896 (org-on-heading-p))))
13897 (call-interactively 'org-do-promote))
13898 ((or (org-at-item-p)
13899 (and (org-region-active-p)
13900 (save-excursion
13901 (goto-char (region-beginning))
13902 (org-at-item-p))))
13903 (call-interactively 'org-outdent-item))
13904 (t (call-interactively 'backward-word))))
13906 (defun org-metaright (&optional arg)
13907 "Demote subtree or move table column to right.
13908 Calls `org-do-demote' or `org-table-move-column', depending on context.
13909 With no specific context, calls the Emacs default `forward-word'.
13910 See the individual commands for more information."
13911 (interactive "P")
13912 (cond
13913 ((run-hook-with-args-until-success 'org-metaright-hook))
13914 ((org-at-table-p) (call-interactively 'org-table-move-column))
13915 ((or (org-on-heading-p)
13916 (and (org-region-active-p)
13917 (save-excursion
13918 (goto-char (region-beginning))
13919 (org-on-heading-p))))
13920 (call-interactively 'org-do-demote))
13921 ((or (org-at-item-p)
13922 (and (org-region-active-p)
13923 (save-excursion
13924 (goto-char (region-beginning))
13925 (org-at-item-p))))
13926 (call-interactively 'org-indent-item))
13927 (t (call-interactively 'forward-word))))
13929 (defun org-metaup (&optional arg)
13930 "Move subtree up or move table row up.
13931 Calls `org-move-subtree-up' or `org-table-move-row' or
13932 `org-move-item-up', depending on context. See the individual commands
13933 for more information."
13934 (interactive "P")
13935 (cond
13936 ((run-hook-with-args-until-success 'org-metaup-hook))
13937 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
13938 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
13939 ((org-at-item-p) (call-interactively 'org-move-item-up))
13940 (t (transpose-lines 1) (beginning-of-line -1))))
13942 (defun org-metadown (&optional arg)
13943 "Move subtree down or move table row down.
13944 Calls `org-move-subtree-down' or `org-table-move-row' or
13945 `org-move-item-down', depending on context. See the individual
13946 commands for more information."
13947 (interactive "P")
13948 (cond
13949 ((run-hook-with-args-until-success 'org-metadown-hook))
13950 ((org-at-table-p) (call-interactively 'org-table-move-row))
13951 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
13952 ((org-at-item-p) (call-interactively 'org-move-item-down))
13953 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
13955 (defun org-shiftup (&optional arg)
13956 "Increase item in timestamp or increase priority of current headline.
13957 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
13958 depending on context. See the individual commands for more information."
13959 (interactive "P")
13960 (cond
13961 ((and org-support-shift-select (org-region-active-p))
13962 (org-call-for-shift-select 'previous-line))
13963 ((org-at-timestamp-p t)
13964 (call-interactively (if org-edit-timestamp-down-means-later
13965 'org-timestamp-down 'org-timestamp-up)))
13966 ((and (not (eq org-support-shift-select 'always))
13967 (org-on-heading-p))
13968 (call-interactively 'org-priority-up))
13969 ((and (not org-support-shift-select) (org-at-item-p))
13970 (call-interactively 'org-previous-item))
13971 ((org-clocktable-try-shift 'up arg))
13972 (org-support-shift-select
13973 (org-call-for-shift-select 'previous-line))
13974 (t (org-shiftselect-error))))
13976 (defun org-shiftdown (&optional arg)
13977 "Decrease item in timestamp or decrease priority of current headline.
13978 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
13979 depending on context. See the individual commands for more information."
13980 (interactive "P")
13981 (cond
13982 ((and org-support-shift-select (org-region-active-p))
13983 (org-call-for-shift-select 'next-line))
13984 ((org-at-timestamp-p t)
13985 (call-interactively (if org-edit-timestamp-down-means-later
13986 'org-timestamp-up 'org-timestamp-down)))
13987 ((and (not (eq org-support-shift-select 'always))
13988 (org-on-heading-p))
13989 (call-interactively 'org-priority-down))
13990 ((and (not org-support-shift-select) (org-at-item-p))
13991 (call-interactively 'org-next-item))
13992 ((org-clocktable-try-shift 'down arg))
13993 (org-support-shift-select
13994 (org-call-for-shift-select 'next-line))
13995 (t (org-shiftselect-error))))
13997 (defun org-shiftright (&optional arg)
13998 "Cycle the thing at point or in the current line, depending on context.
13999 Depending on context, this does one of the following:
14001 - switch a timestamp at point one day into the future
14002 - on a headline, switch to the next TODO keyword.
14003 - on an item, switch entire list to the next bullet type
14004 - on a property line, switch to the next allowed value
14005 - on a clocktable definition line, move time block into the future"
14006 (interactive "P")
14007 (cond
14008 ((and org-support-shift-select (org-region-active-p))
14009 (org-call-for-shift-select 'forward-char))
14010 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
14011 ((and (not (eq org-support-shift-select 'always))
14012 (org-on-heading-p))
14013 (org-call-with-arg 'org-todo 'right))
14014 ((or (and org-support-shift-select
14015 (not (eq org-support-shift-select 'always))
14016 (org-at-item-bullet-p))
14017 (and (not org-support-shift-select) (org-at-item-p)))
14018 (org-call-with-arg 'org-cycle-list-bullet nil))
14019 ((and (not (eq org-support-shift-select 'always))
14020 (org-at-property-p))
14021 (call-interactively 'org-property-next-allowed-value))
14022 ((org-clocktable-try-shift 'right arg))
14023 (org-support-shift-select
14024 (org-call-for-shift-select 'forward-char))
14025 (t (org-shiftselect-error))))
14027 (defun org-shiftleft (&optional arg)
14028 "Cycle the thing at point or in the current line, depending on context.
14029 Depending on context, this does one of the following:
14031 - switch a timestamp at point one day into the past
14032 - on a headline, switch to the previous TODO keyword.
14033 - on an item, switch entire list to the previous bullet type
14034 - on a property line, switch to the previous allowed value
14035 - on a clocktable definition line, move time block into the past"
14036 (interactive "P")
14037 (cond
14038 ((and org-support-shift-select (org-region-active-p))
14039 (org-call-for-shift-select 'backward-char))
14040 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
14041 ((and (not (eq org-support-shift-select 'always))
14042 (org-on-heading-p))
14043 (org-call-with-arg 'org-todo 'left))
14044 ((or (and org-support-shift-select
14045 (not (eq org-support-shift-select 'always))
14046 (org-at-item-bullet-p))
14047 (and (not org-support-shift-select) (org-at-item-p)))
14048 (org-call-with-arg 'org-cycle-list-bullet 'previous))
14049 ((and (not (eq org-support-shift-select 'always))
14050 (org-at-property-p))
14051 (call-interactively 'org-property-previous-allowed-value))
14052 ((org-clocktable-try-shift 'left arg))
14053 (org-support-shift-select
14054 (org-call-for-shift-select 'backward-char))
14055 (t (org-shiftselect-error))))
14057 (defun org-shiftcontrolright ()
14058 "Switch to next TODO set."
14059 (interactive)
14060 (cond
14061 ((and org-support-shift-select (org-region-active-p))
14062 (org-call-for-shift-select 'forward-word))
14063 ((and (not (eq org-support-shift-select 'always))
14064 (org-on-heading-p))
14065 (org-call-with-arg 'org-todo 'nextset))
14066 (org-support-shift-select
14067 (org-call-for-shift-select 'forward-word))
14068 (t (org-shiftselect-error))))
14070 (defun org-shiftcontrolleft ()
14071 "Switch to previous TODO set."
14072 (interactive)
14073 (cond
14074 ((and org-support-shift-select (org-region-active-p))
14075 (org-call-for-shift-select 'backward-word))
14076 ((and (not (eq org-support-shift-select 'always))
14077 (org-on-heading-p))
14078 (org-call-with-arg 'org-todo 'previousset))
14079 (org-support-shift-select
14080 (org-call-for-shift-select 'backward-word))
14081 (t (org-shiftselect-error))))
14083 (defun org-ctrl-c-ret ()
14084 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
14085 (interactive)
14086 (cond
14087 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
14088 (t (call-interactively 'org-insert-heading))))
14090 (defun org-copy-special ()
14091 "Copy region in table or copy current subtree.
14092 Calls `org-table-copy' or `org-copy-subtree', depending on context.
14093 See the individual commands for more information."
14094 (interactive)
14095 (call-interactively
14096 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
14098 (defun org-cut-special ()
14099 "Cut region in table or cut current subtree.
14100 Calls `org-table-copy' or `org-cut-subtree', depending on context.
14101 See the individual commands for more information."
14102 (interactive)
14103 (call-interactively
14104 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
14106 (defun org-paste-special (arg)
14107 "Paste rectangular region into table, or past subtree relative to level.
14108 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
14109 See the individual commands for more information."
14110 (interactive "P")
14111 (if (org-at-table-p)
14112 (org-table-paste-rectangle)
14113 (org-paste-subtree arg)))
14115 (defun org-edit-special ()
14116 "Call a special editor for the stuff at point.
14117 When at a table, call the formula editor with `org-table-edit-formulas'.
14118 When at the first line of an src example, call `org-edit-src-code'.
14119 When in an #+include line, visit the include file. Otherwise call
14120 `ffap' to visit the file at point."
14121 (interactive)
14122 (cond
14123 ((org-at-table-p)
14124 (call-interactively 'org-table-edit-formulas))
14125 ((save-excursion
14126 (beginning-of-line 1)
14127 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
14128 (find-file (org-trim (match-string 1))))
14129 ((org-edit-src-code))
14130 ((org-edit-fixed-width-region))
14131 (t (call-interactively 'ffap))))
14134 (defun org-ctrl-c-ctrl-c (&optional arg)
14135 "Set tags in headline, or update according to changed information at point.
14137 This command does many different things, depending on context:
14139 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
14140 this is what we do.
14142 - If the cursor is in a headline, prompt for tags and insert them
14143 into the current line, aligned to `org-tags-column'. When called
14144 with prefix arg, realign all tags in the current buffer.
14146 - If the cursor is in one of the special #+KEYWORD lines, this
14147 triggers scanning the buffer for these lines and updating the
14148 information.
14150 - If the cursor is inside a table, realign the table. This command
14151 works even if the automatic table editor has been turned off.
14153 - If the cursor is on a #+TBLFM line, re-apply the formulas to
14154 the entire table.
14156 - If the cursor is at a footnote reference or definition, jump to
14157 the corresponding definition or references, respectively.
14159 - If the cursor is a the beginning of a dynamic block, update it.
14161 - If the cursor is inside a table created by the table.el package,
14162 activate that table.
14164 - If the current buffer is a remember buffer, close note and file
14165 it. A prefix argument of 1 files to the default location
14166 without further interaction. A prefix argument of 2 files to
14167 the currently clocking task.
14169 - If the cursor is on a <<<target>>>, update radio targets and corresponding
14170 links in this buffer.
14172 - If the cursor is on a numbered item in a plain list, renumber the
14173 ordered list.
14175 - If the cursor is on a checkbox, toggle it."
14176 (interactive "P")
14177 (let ((org-enable-table-editor t))
14178 (cond
14179 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
14180 org-occur-highlights
14181 org-latex-fragment-image-overlays)
14182 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
14183 (org-remove-occur-highlights)
14184 (org-remove-latex-fragment-image-overlays)
14185 (message "Temporary highlights/overlays removed from current buffer"))
14186 ((and (local-variable-p 'org-finish-function (current-buffer))
14187 (fboundp org-finish-function))
14188 (funcall org-finish-function))
14189 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
14190 ((org-at-property-p)
14191 (call-interactively 'org-property-action))
14192 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
14193 ((org-on-heading-p) (call-interactively 'org-set-tags))
14194 ((org-at-table.el-p)
14195 (require 'table)
14196 (beginning-of-line 1)
14197 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
14198 (call-interactively 'table-recognize-table))
14199 ((org-at-table-p)
14200 (org-table-maybe-eval-formula)
14201 (if arg
14202 (call-interactively 'org-table-recalculate)
14203 (org-table-maybe-recalculate-line))
14204 (call-interactively 'org-table-align))
14205 ((or (org-footnote-at-reference-p)
14206 (org-footnote-at-definition-p))
14207 (call-interactively 'org-footnote-action))
14208 ((org-at-item-checkbox-p)
14209 (call-interactively 'org-toggle-checkbox))
14210 ((org-at-item-p)
14211 (if arg
14212 (call-interactively 'org-toggle-checkbox)
14213 (call-interactively 'org-maybe-renumber-ordered-list)))
14214 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
14215 ;; Dynamic block
14216 (beginning-of-line 1)
14217 (save-excursion (org-update-dblock)))
14218 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
14219 (cond
14220 ((equal (match-string 1) "TBLFM")
14221 ;; Recalculate the table before this line
14222 (save-excursion
14223 (beginning-of-line 1)
14224 (skip-chars-backward " \r\n\t")
14225 (if (org-at-table-p)
14226 (org-call-with-arg 'org-table-recalculate t))))
14228 ; (org-set-regexps-and-options)
14229 ; (org-restart-font-lock)
14230 (let ((org-inhibit-startup t)) (org-mode-restart))
14231 (message "Local setup has been refreshed"))))
14232 (t (error "C-c C-c can do nothing useful at this location.")))))
14234 (defun org-mode-restart ()
14235 "Restart Org-mode, to scan again for special lines.
14236 Also updates the keyword regular expressions."
14237 (interactive)
14238 (org-mode)
14239 (message "Org-mode restarted"))
14241 (defun org-kill-note-or-show-branches ()
14242 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
14243 (interactive)
14244 (if (not org-finish-function)
14245 (call-interactively 'show-branches)
14246 (let ((org-note-abort t))
14247 (funcall org-finish-function))))
14249 (defun org-return (&optional indent)
14250 "Goto next table row or insert a newline.
14251 Calls `org-table-next-row' or `newline', depending on context.
14252 See the individual commands for more information."
14253 (interactive)
14254 (cond
14255 ((bobp) (if indent (newline-and-indent) (newline)))
14256 ((org-at-table-p)
14257 (org-table-justify-field-maybe)
14258 (call-interactively 'org-table-next-row))
14259 ((and org-return-follows-link
14260 (eq (get-text-property (point) 'face) 'org-link))
14261 (call-interactively 'org-open-at-point))
14262 ((and (org-at-heading-p)
14263 (looking-at
14264 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
14265 (org-show-entry)
14266 (end-of-line 1)
14267 (newline))
14268 (t (if indent (newline-and-indent) (newline)))))
14270 (defun org-return-indent ()
14271 "Goto next table row or insert a newline and indent.
14272 Calls `org-table-next-row' or `newline-and-indent', depending on
14273 context. See the individual commands for more information."
14274 (interactive)
14275 (org-return t))
14277 (defun org-ctrl-c-star ()
14278 "Compute table, or change heading status of lines.
14279 Calls `org-table-recalculate' or `org-toggle-heading',
14280 depending on context."
14281 (interactive)
14282 (cond
14283 ((org-at-table-p)
14284 (call-interactively 'org-table-recalculate))
14286 ;; Convert all lines in region to list items
14287 (call-interactively 'org-toggle-heading))))
14289 (defun org-ctrl-c-minus ()
14290 "Insert separator line in table or modify bullet status of line.
14291 Also turns a plain line or a region of lines into list items.
14292 Calls `org-table-insert-hline', `org-toggle-item', or
14293 `org-cycle-list-bullet', depending on context."
14294 (interactive)
14295 (cond
14296 ((org-at-table-p)
14297 (call-interactively 'org-table-insert-hline))
14298 ((org-region-active-p)
14299 (call-interactively 'org-toggle-item))
14300 ((org-in-item-p)
14301 (call-interactively 'org-cycle-list-bullet))
14303 (call-interactively 'org-toggle-item))))
14305 (defun org-toggle-item ()
14306 "Convert headings or normal lines to items, items to normal lines.
14307 If there is no active region, only the current line is considered.
14309 If the first line in the region is a headline, convert all headlines to items.
14311 If the first line in the region is an item, convert all items to normal lines.
14313 If the first line is normal text, add an item bullet to each line."
14314 (interactive)
14315 (let (l2 l beg end)
14316 (if (org-region-active-p)
14317 (setq beg (region-beginning) end (region-end))
14318 (setq beg (point-at-bol)
14319 end (min (1+ (point-at-eol)) (point-max))))
14320 (save-excursion
14321 (goto-char end)
14322 (setq l2 (org-current-line))
14323 (goto-char beg)
14324 (beginning-of-line 1)
14325 (setq l (1- (org-current-line)))
14326 (if (org-at-item-p)
14327 ;; We already have items, de-itemize
14328 (while (< (setq l (1+ l)) l2)
14329 (when (org-at-item-p)
14330 (goto-char (match-beginning 2))
14331 (delete-region (match-beginning 2) (match-end 2))
14332 (and (looking-at "[ \t]+") (replace-match "")))
14333 (beginning-of-line 2))
14334 (if (org-on-heading-p)
14335 ;; Headings, convert to items
14336 (while (< (setq l (1+ l)) l2)
14337 (if (looking-at org-outline-regexp)
14338 (replace-match "- " t t))
14339 (beginning-of-line 2))
14340 ;; normal lines, turn them into items
14341 (while (< (setq l (1+ l)) l2)
14342 (unless (org-at-item-p)
14343 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
14344 (replace-match "\\1- \\2")))
14345 (beginning-of-line 2)))))))
14347 (defun org-toggle-heading (&optional nstars)
14348 "Convert headings to normal text, or items or text to headings.
14349 If there is no active region, only the current line is considered.
14351 If the first line is a heading, remove the stars from all headlines
14352 in the region.
14354 If the first line is a plain list item, turn all plain list items into
14355 headings.
14357 If the first line is a normal line, turn each and every line in the region
14358 into a heading.
14360 When converting a line into a heading, the number of stars is chosen
14361 such that the lines become children of the current entry. However, when
14362 a prefix argument is given, its value determines the number of stars to add."
14363 (interactive "P")
14364 (let (l2 l itemp beg end)
14365 (if (org-region-active-p)
14366 (setq beg (region-beginning) end (region-end))
14367 (setq beg (point-at-bol)
14368 end (min (1+ (point-at-eol)) (point-max))))
14369 (save-excursion
14370 (goto-char end)
14371 (setq l2 (org-current-line))
14372 (goto-char beg)
14373 (beginning-of-line 1)
14374 (setq l (1- (org-current-line)))
14375 (if (org-on-heading-p)
14376 ;; We already have headlines, de-star them
14377 (while (< (setq l (1+ l)) l2)
14378 (when (org-on-heading-p t)
14379 (and (looking-at outline-regexp) (replace-match "")))
14380 (beginning-of-line 2))
14381 (setq itemp (org-at-item-p))
14382 (let* ((stars
14383 (if nstars
14384 (make-string (prefix-numeric-value current-prefix-arg)
14386 (save-excursion
14387 (re-search-backward org-complex-heading-regexp nil t)
14388 (or (match-string 1) ""))))
14389 (add-stars (cond (nstars "")
14390 ((equal stars "") "*")
14391 (org-odd-levels-only "**")
14392 (t "*")))
14393 (rpl (concat stars add-stars " ")))
14394 (while (< (setq l (1+ l)) l2)
14395 (if itemp
14396 (and (org-at-item-p) (replace-match rpl t t))
14397 (unless (org-on-heading-p)
14398 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
14399 (replace-match (concat rpl (match-string 2))))))
14400 (beginning-of-line 2)))))))
14402 (defun org-meta-return (&optional arg)
14403 "Insert a new heading or wrap a region in a table.
14404 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
14405 See the individual commands for more information."
14406 (interactive "P")
14407 (cond
14408 ((run-hook-with-args-until-success 'org-metareturn-hook))
14409 ((org-at-table-p)
14410 (call-interactively 'org-table-wrap-region))
14411 (t (call-interactively 'org-insert-heading))))
14413 ;;; Menu entries
14415 ;; Define the Org-mode menus
14416 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
14417 '("Tbl"
14418 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
14419 ["Next Field" org-cycle (org-at-table-p)]
14420 ["Previous Field" org-shifttab (org-at-table-p)]
14421 ["Next Row" org-return (org-at-table-p)]
14422 "--"
14423 ["Blank Field" org-table-blank-field (org-at-table-p)]
14424 ["Edit Field" org-table-edit-field (org-at-table-p)]
14425 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
14426 "--"
14427 ("Column"
14428 ["Move Column Left" org-metaleft (org-at-table-p)]
14429 ["Move Column Right" org-metaright (org-at-table-p)]
14430 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
14431 ["Insert Column" org-shiftmetaright (org-at-table-p)])
14432 ("Row"
14433 ["Move Row Up" org-metaup (org-at-table-p)]
14434 ["Move Row Down" org-metadown (org-at-table-p)]
14435 ["Delete Row" org-shiftmetaup (org-at-table-p)]
14436 ["Insert Row" org-shiftmetadown (org-at-table-p)]
14437 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
14438 "--"
14439 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
14440 ("Rectangle"
14441 ["Copy Rectangle" org-copy-special (org-at-table-p)]
14442 ["Cut Rectangle" org-cut-special (org-at-table-p)]
14443 ["Paste Rectangle" org-paste-special (org-at-table-p)]
14444 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
14445 "--"
14446 ("Calculate"
14447 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
14448 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
14449 ["Edit Formulas" org-edit-special (org-at-table-p)]
14450 "--"
14451 ["Recalculate line" org-table-recalculate (org-at-table-p)]
14452 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
14453 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
14454 "--"
14455 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
14456 "--"
14457 ["Sum Column/Rectangle" org-table-sum
14458 (or (org-at-table-p) (org-region-active-p))]
14459 ["Which Column?" org-table-current-column (org-at-table-p)])
14460 ["Debug Formulas"
14461 org-table-toggle-formula-debugger
14462 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
14463 ["Show Col/Row Numbers"
14464 org-table-toggle-coordinate-overlays
14465 :style toggle
14466 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
14467 "--"
14468 ["Create" org-table-create (and (not (org-at-table-p))
14469 org-enable-table-editor)]
14470 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
14471 ["Import from File" org-table-import (not (org-at-table-p))]
14472 ["Export to File" org-table-export (org-at-table-p)]
14473 "--"
14474 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
14476 (easy-menu-define org-org-menu org-mode-map "Org menu"
14477 '("Org"
14478 ("Show/Hide"
14479 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
14480 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
14481 ["Sparse Tree..." org-sparse-tree t]
14482 ["Reveal Context" org-reveal t]
14483 ["Show All" show-all t]
14484 "--"
14485 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
14486 "--"
14487 ["New Heading" org-insert-heading t]
14488 ("Navigate Headings"
14489 ["Up" outline-up-heading t]
14490 ["Next" outline-next-visible-heading t]
14491 ["Previous" outline-previous-visible-heading t]
14492 ["Next Same Level" outline-forward-same-level t]
14493 ["Previous Same Level" outline-backward-same-level t]
14494 "--"
14495 ["Jump" org-goto t])
14496 ("Edit Structure"
14497 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
14498 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
14499 "--"
14500 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
14501 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
14502 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
14503 "--"
14504 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
14505 "--"
14506 ["Promote Heading" org-metaleft (not (org-at-table-p))]
14507 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
14508 ["Demote Heading" org-metaright (not (org-at-table-p))]
14509 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
14510 "--"
14511 ["Sort Region/Children" org-sort (not (org-at-table-p))]
14512 "--"
14513 ["Convert to odd levels" org-convert-to-odd-levels t]
14514 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
14515 ("Editing"
14516 ["Emphasis..." org-emphasize t]
14517 ["Edit Source Example" org-edit-special t]
14518 "--"
14519 ["Footnote new/jump" org-footnote-action t]
14520 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
14521 ("Archive"
14522 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
14523 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
14524 ; :active t :keys "C-u C-c C-x C-a"]
14525 ["Sparse trees open ARCHIVE trees"
14526 (setq org-sparse-tree-open-archived-trees
14527 (not org-sparse-tree-open-archived-trees))
14528 :style toggle :selected org-sparse-tree-open-archived-trees]
14529 ["Cycling opens ARCHIVE trees"
14530 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
14531 :style toggle :selected org-cycle-open-archived-trees]
14532 "--"
14533 ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
14534 ["Move Subtree to Archive" org-advertized-archive-subtree t]
14535 ; ["Check and Move Children" (org-archive-subtree '(4))
14536 ; :active t :keys "C-u C-c C-x C-s"]
14538 "--"
14539 ("Hyperlinks"
14540 ["Store Link (Global)" org-store-link t]
14541 ["Insert Link" org-insert-link t]
14542 ["Follow Link" org-open-at-point t]
14543 "--"
14544 ["Next link" org-next-link t]
14545 ["Previous link" org-previous-link t]
14546 "--"
14547 ["Descriptive Links"
14548 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
14549 :style radio
14550 :selected (member '(org-link) buffer-invisibility-spec)]
14551 ["Literal Links"
14552 (progn
14553 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
14554 :style radio
14555 :selected (not (member '(org-link) buffer-invisibility-spec))])
14556 "--"
14557 ("TODO Lists"
14558 ["TODO/DONE/-" org-todo t]
14559 ("Select keyword"
14560 ["Next keyword" org-shiftright (org-on-heading-p)]
14561 ["Previous keyword" org-shiftleft (org-on-heading-p)]
14562 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
14563 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
14564 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
14565 ["Show TODO Tree" org-show-todo-tree t]
14566 ["Global TODO list" org-todo-list t]
14567 "--"
14568 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
14569 :selected org-enforce-todo-dependencies :style toggle :active t]
14570 "Settings for tree at point"
14571 ["Do Children sequentially" org-toggle-ordered-property :style radio
14572 :selected (ignore-errors (org-entry-get nil "ORDERED"))
14573 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
14574 ["Do Children parallel" org-toggle-ordered-property :style radio
14575 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
14576 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
14577 "--"
14578 ["Set Priority" org-priority t]
14579 ["Priority Up" org-shiftup t]
14580 ["Priority Down" org-shiftdown t]
14581 "--"
14582 ["Get news from all feeds" org-feed-update-all t]
14583 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
14584 ["Customize feeds" (customize-variable 'org-feed-alist) t])
14585 ("TAGS and Properties"
14586 ["Set Tags" org-set-tags-command t]
14587 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
14588 "--"
14589 ["Set property" org-set-property t]
14590 ["Column view of properties" org-columns t]
14591 ["Insert Column View DBlock" org-insert-columns-dblock t])
14592 ("Dates and Scheduling"
14593 ["Timestamp" org-time-stamp t]
14594 ["Timestamp (inactive)" org-time-stamp-inactive t]
14595 ("Change Date"
14596 ["1 Day Later" org-shiftright t]
14597 ["1 Day Earlier" org-shiftleft t]
14598 ["1 ... Later" org-shiftup t]
14599 ["1 ... Earlier" org-shiftdown t])
14600 ["Compute Time Range" org-evaluate-time-range t]
14601 ["Schedule Item" org-schedule t]
14602 ["Deadline" org-deadline t]
14603 "--"
14604 ["Custom time format" org-toggle-time-stamp-overlays
14605 :style radio :selected org-display-custom-times]
14606 "--"
14607 ["Goto Calendar" org-goto-calendar t]
14608 ["Date from Calendar" org-date-from-calendar t]
14609 "--"
14610 ["Start/Restart Timer" org-timer-start t]
14611 ["Pause/Continue Timer" org-timer-pause-or-continue t]
14612 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
14613 ["Insert Timer String" org-timer t]
14614 ["Insert Timer Item" org-timer-item t])
14615 ("Logging work"
14616 ["Clock in" org-clock-in t]
14617 ["Clock out" org-clock-out t]
14618 ["Clock cancel" org-clock-cancel t]
14619 ["Goto running clock" org-clock-goto t]
14620 ["Display times" org-clock-display t]
14621 ["Create clock table" org-clock-report t]
14622 "--"
14623 ["Record DONE time"
14624 (progn (setq org-log-done (not org-log-done))
14625 (message "Switching to %s will %s record a timestamp"
14626 (car org-done-keywords)
14627 (if org-log-done "automatically" "not")))
14628 :style toggle :selected org-log-done])
14629 "--"
14630 ["Agenda Command..." org-agenda t]
14631 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
14632 ("File List for Agenda")
14633 ("Special views current file"
14634 ["TODO Tree" org-show-todo-tree t]
14635 ["Check Deadlines" org-check-deadlines t]
14636 ["Timeline" org-timeline t]
14637 ["Tags/Property tree" org-match-sparse-tree t])
14638 "--"
14639 ["Export/Publish..." org-export t]
14640 ("LaTeX"
14641 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
14642 :selected org-cdlatex-mode]
14643 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
14644 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
14645 ["Modify math symbol" org-cdlatex-math-modify
14646 (org-inside-LaTeX-fragment-p)]
14647 ["Insert citation" org-reftex-citation t]
14648 "--"
14649 ["Export LaTeX fragments as images"
14650 (if (featurep 'org-exp)
14651 (setq org-export-with-LaTeX-fragments
14652 (not org-export-with-LaTeX-fragments))
14653 (require 'org-exp))
14654 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
14655 org-export-with-LaTeX-fragments)])
14656 "--"
14657 ("Documentation"
14658 ["Show Version" org-version t]
14659 ["Info Documentation" org-info t])
14660 ("Customize"
14661 ["Browse Org Group" org-customize t]
14662 "--"
14663 ["Expand This Menu" org-create-customize-menu
14664 (fboundp 'customize-menu-create)])
14665 "--"
14666 ("Refresh/Reload"
14667 ["Refresh setup current buffer" org-mode-restart t]
14668 ["Reload Org (after update)" org-reload t]
14669 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
14672 (defun org-info (&optional node)
14673 "Read documentation for Org-mode in the info system.
14674 With optional NODE, go directly to that node."
14675 (interactive)
14676 (info (format "(org)%s" (or node ""))))
14678 (defun org-install-agenda-files-menu ()
14679 (let ((bl (buffer-list)))
14680 (save-excursion
14681 (while bl
14682 (set-buffer (pop bl))
14683 (if (org-mode-p) (setq bl nil)))
14684 (when (org-mode-p)
14685 (easy-menu-change
14686 '("Org") "File List for Agenda"
14687 (append
14688 (list
14689 ["Edit File List" (org-edit-agenda-file-list) t]
14690 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
14691 ["Remove Current File from List" org-remove-file t]
14692 ["Cycle through agenda files" org-cycle-agenda-files t]
14693 ["Occur in all agenda files" org-occur-in-agenda-files t]
14694 "--")
14695 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
14697 ;;;; Documentation
14699 ;;;###autoload
14700 (defun org-require-autoloaded-modules ()
14701 (interactive)
14702 (mapc 'require
14703 '(org-agenda org-archive org-attach org-clock org-colview
14704 org-exp org-id org-export-latex org-docbook
14705 org-publish org-remember org-table org-timer)))
14707 ;;;###autoload
14708 (defun org-reload (&optional uncompiled)
14709 "Reload all org lisp files.
14710 With prefix arg UNCOMPILED, load the uncompiled versions."
14711 (interactive "P")
14712 (require 'find-func)
14713 (let* ((dir
14714 (if (fboundp 'find-library-name)
14715 (file-name-directory (find-library-name "org"))
14716 (flet ((find-library-name-helper (filename ignored-codesys)
14717 filename)
14718 (find-library-name
14719 (library)
14720 (find-library library nil 'find-library-name-helper)))
14721 (file-name-directory (find-library-name "org")))))
14722 (files (directory-files dir t "\\.el\\'"))
14723 (remove-re (concat (if (featurep 'xemacs)
14724 "org-colview" "org-colview-xemacs")
14725 "\\'")))
14726 (setq files (mapcar 'file-name-sans-extension files))
14727 (setq files (mapcar
14728 (lambda (x) (if (string-match remove-re x) nil x))
14729 files))
14730 (setq files (delq nil files))
14731 (mapc
14732 (lambda (f)
14733 (if (and (not uncompiled)
14734 (file-exists-p (concat f ".elc")))
14735 (load (concat f ".elc") nil nil t)
14736 (load (concat f ".el") nil nil t)))
14737 files)))
14739 ;;;###autoload
14740 (defun org-customize ()
14741 "Call the customize function with org as argument."
14742 (interactive)
14743 (org-load-modules-maybe)
14744 (org-require-autoloaded-modules)
14745 (customize-browse 'org))
14747 (defun org-create-customize-menu ()
14748 "Create a full customization menu for Org-mode, insert it into the menu."
14749 (interactive)
14750 (org-load-modules-maybe)
14751 (org-require-autoloaded-modules)
14752 (if (fboundp 'customize-menu-create)
14753 (progn
14754 (easy-menu-change
14755 '("Org") "Customize"
14756 `(["Browse Org group" org-customize t]
14757 "--"
14758 ,(customize-menu-create 'org)
14759 ["Set" Custom-set t]
14760 ["Save" Custom-save t]
14761 ["Reset to Current" Custom-reset-current t]
14762 ["Reset to Saved" Custom-reset-saved t]
14763 ["Reset to Standard Settings" Custom-reset-standard t]))
14764 (message "\"Org\"-menu now contains full customization menu"))
14765 (error "Cannot expand menu (outdated version of cus-edit.el)")))
14767 ;;;; Miscellaneous stuff
14769 ;;; Generally useful functions
14771 (defun org-find-text-property-in-string (prop s)
14772 "Return the first non-nil value of property PROP in string S."
14773 (or (get-text-property 0 prop s)
14774 (get-text-property (or (next-single-property-change 0 prop s) 0)
14775 prop s)))
14777 (defun org-display-warning (message) ;; Copied from Emacs-Muse
14778 "Display the given MESSAGE as a warning."
14779 (if (fboundp 'display-warning)
14780 (display-warning 'org message
14781 (if (featurep 'xemacs)
14782 'warning
14783 :warning))
14784 (let ((buf (get-buffer-create "*Org warnings*")))
14785 (with-current-buffer buf
14786 (goto-char (point-max))
14787 (insert "Warning (Org): " message)
14788 (unless (bolp)
14789 (newline)))
14790 (display-buffer buf)
14791 (sit-for 0))))
14793 (defun org-goto-marker-or-bmk (marker &optional bookmark)
14794 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
14795 (if (and marker (marker-buffer marker)
14796 (buffer-live-p (marker-buffer marker)))
14797 (progn
14798 (switch-to-buffer (marker-buffer marker))
14799 (if (or (> marker (point-max)) (< marker (point-min)))
14800 (widen))
14801 (goto-char marker)
14802 (org-show-context 'org-goto))
14803 (if bookmark
14804 (bookmark-jump bookmark)
14805 (error "Cannot find location"))))
14807 (defun org-quote-csv-field (s)
14808 "Quote field for inclusion in CSV material."
14809 (if (string-match "[\",]" s)
14810 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
14813 (defun org-plist-delete (plist property)
14814 "Delete PROPERTY from PLIST.
14815 This is in contrast to merely setting it to 0."
14816 (let (p)
14817 (while plist
14818 (if (not (eq property (car plist)))
14819 (setq p (plist-put p (car plist) (nth 1 plist))))
14820 (setq plist (cddr plist)))
14823 (defun org-force-self-insert (N)
14824 "Needed to enforce self-insert under remapping."
14825 (interactive "p")
14826 (self-insert-command N))
14828 (defun org-string-width (s)
14829 "Compute width of string, ignoring invisible characters.
14830 This ignores character with invisibility property `org-link', and also
14831 characters with property `org-cwidth', because these will become invisible
14832 upon the next fontification round."
14833 (let (b l)
14834 (when (or (eq t buffer-invisibility-spec)
14835 (assq 'org-link buffer-invisibility-spec))
14836 (while (setq b (text-property-any 0 (length s)
14837 'invisible 'org-link s))
14838 (setq s (concat (substring s 0 b)
14839 (substring s (or (next-single-property-change
14840 b 'invisible s) (length s)))))))
14841 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
14842 (setq s (concat (substring s 0 b)
14843 (substring s (or (next-single-property-change
14844 b 'org-cwidth s) (length s))))))
14845 (setq l (string-width s) b -1)
14846 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
14847 (setq l (- l (get-text-property b 'org-dwidth-n s))))
14850 (defun org-get-indentation (&optional line)
14851 "Get the indentation of the current line, interpreting tabs.
14852 When LINE is given, assume it represents a line and compute its indentation."
14853 (if line
14854 (if (string-match "^ *" (org-remove-tabs line))
14855 (match-end 0))
14856 (save-excursion
14857 (beginning-of-line 1)
14858 (skip-chars-forward " \t")
14859 (current-column))))
14861 (defun org-remove-tabs (s &optional width)
14862 "Replace tabulators in S with spaces.
14863 Assumes that s is a single line, starting in column 0."
14864 (setq width (or width tab-width))
14865 (while (string-match "\t" s)
14866 (setq s (replace-match
14867 (make-string
14868 (- (* width (/ (+ (match-beginning 0) width) width))
14869 (match-beginning 0)) ?\ )
14870 t t s)))
14873 (defun org-fix-indentation (line ind)
14874 "Fix indentation in LINE.
14875 IND is a cons cell with target and minimum indentation.
14876 If the current indentation in LINE is smaller than the minimum,
14877 leave it alone. If it is larger than ind, set it to the target."
14878 (let* ((l (org-remove-tabs line))
14879 (i (org-get-indentation l))
14880 (i1 (car ind)) (i2 (cdr ind)))
14881 (if (>= i i2) (setq l (substring line i2)))
14882 (if (> i1 0)
14883 (concat (make-string i1 ?\ ) l)
14884 l)))
14886 (defun org-base-buffer (buffer)
14887 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
14888 (if (not buffer)
14889 buffer
14890 (or (buffer-base-buffer buffer)
14891 buffer)))
14893 (defun org-trim (s)
14894 "Remove whitespace at beginning and end of string."
14895 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
14896 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
14899 (defun org-wrap (string &optional width lines)
14900 "Wrap string to either a number of lines, or a width in characters.
14901 If WIDTH is non-nil, the string is wrapped to that width, however many lines
14902 that costs. If there is a word longer than WIDTH, the text is actually
14903 wrapped to the length of that word.
14904 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
14905 many lines, whatever width that takes.
14906 The return value is a list of lines, without newlines at the end."
14907 (let* ((words (org-split-string string "[ \t\n]+"))
14908 (maxword (apply 'max (mapcar 'org-string-width words)))
14909 w ll)
14910 (cond (width
14911 (org-do-wrap words (max maxword width)))
14912 (lines
14913 (setq w maxword)
14914 (setq ll (org-do-wrap words maxword))
14915 (if (<= (length ll) lines)
14917 (setq ll words)
14918 (while (> (length ll) lines)
14919 (setq w (1+ w))
14920 (setq ll (org-do-wrap words w)))
14921 ll))
14922 (t (error "Cannot wrap this")))))
14924 (defun org-do-wrap (words width)
14925 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
14926 (let (lines line)
14927 (while words
14928 (setq line (pop words))
14929 (while (and words (< (+ (length line) (length (car words))) width))
14930 (setq line (concat line " " (pop words))))
14931 (setq lines (push line lines)))
14932 (nreverse lines)))
14934 (defun org-split-string (string &optional separators)
14935 "Splits STRING into substrings at SEPARATORS.
14936 No empty strings are returned if there are matches at the beginning
14937 and end of string."
14938 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
14939 (start 0)
14940 notfirst
14941 (list nil))
14942 (while (and (string-match rexp string
14943 (if (and notfirst
14944 (= start (match-beginning 0))
14945 (< start (length string)))
14946 (1+ start) start))
14947 (< (match-beginning 0) (length string)))
14948 (setq notfirst t)
14949 (or (eq (match-beginning 0) 0)
14950 (and (eq (match-beginning 0) (match-end 0))
14951 (eq (match-beginning 0) start))
14952 (setq list
14953 (cons (substring string start (match-beginning 0))
14954 list)))
14955 (setq start (match-end 0)))
14956 (or (eq start (length string))
14957 (setq list
14958 (cons (substring string start)
14959 list)))
14960 (nreverse list)))
14962 (defun org-uuidgen-p (s)
14963 "Is S an ID created by UUIDGEN?"
14964 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
14966 (defun org-context ()
14967 "Return a list of contexts of the current cursor position.
14968 If several contexts apply, all are returned.
14969 Each context entry is a list with a symbol naming the context, and
14970 two positions indicating start and end of the context. Possible
14971 contexts are:
14973 :headline anywhere in a headline
14974 :headline-stars on the leading stars in a headline
14975 :todo-keyword on a TODO keyword (including DONE) in a headline
14976 :tags on the TAGS in a headline
14977 :priority on the priority cookie in a headline
14978 :item on the first line of a plain list item
14979 :item-bullet on the bullet/number of a plain list item
14980 :checkbox on the checkbox in a plain list item
14981 :table in an org-mode table
14982 :table-special on a special filed in a table
14983 :table-table in a table.el table
14984 :link on a hyperlink
14985 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
14986 :target on a <<target>>
14987 :radio-target on a <<<radio-target>>>
14988 :latex-fragment on a LaTeX fragment
14989 :latex-preview on a LaTeX fragment with overlayed preview image
14991 This function expects the position to be visible because it uses font-lock
14992 faces as a help to recognize the following contexts: :table-special, :link,
14993 and :keyword."
14994 (let* ((f (get-text-property (point) 'face))
14995 (faces (if (listp f) f (list f)))
14996 (p (point)) clist o)
14997 ;; First the large context
14998 (cond
14999 ((org-on-heading-p t)
15000 (push (list :headline (point-at-bol) (point-at-eol)) clist)
15001 (when (progn
15002 (beginning-of-line 1)
15003 (looking-at org-todo-line-tags-regexp))
15004 (push (org-point-in-group p 1 :headline-stars) clist)
15005 (push (org-point-in-group p 2 :todo-keyword) clist)
15006 (push (org-point-in-group p 4 :tags) clist))
15007 (goto-char p)
15008 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
15009 (if (looking-at "\\[#[A-Z0-9]\\]")
15010 (push (org-point-in-group p 0 :priority) clist)))
15012 ((org-at-item-p)
15013 (push (org-point-in-group p 2 :item-bullet) clist)
15014 (push (list :item (point-at-bol)
15015 (save-excursion (org-end-of-item) (point)))
15016 clist)
15017 (and (org-at-item-checkbox-p)
15018 (push (org-point-in-group p 0 :checkbox) clist)))
15020 ((org-at-table-p)
15021 (push (list :table (org-table-begin) (org-table-end)) clist)
15022 (if (memq 'org-formula faces)
15023 (push (list :table-special
15024 (previous-single-property-change p 'face)
15025 (next-single-property-change p 'face)) clist)))
15026 ((org-at-table-p 'any)
15027 (push (list :table-table) clist)))
15028 (goto-char p)
15030 ;; Now the small context
15031 (cond
15032 ((org-at-timestamp-p)
15033 (push (org-point-in-group p 0 :timestamp) clist))
15034 ((memq 'org-link faces)
15035 (push (list :link
15036 (previous-single-property-change p 'face)
15037 (next-single-property-change p 'face)) clist))
15038 ((memq 'org-special-keyword faces)
15039 (push (list :keyword
15040 (previous-single-property-change p 'face)
15041 (next-single-property-change p 'face)) clist))
15042 ((org-on-target-p)
15043 (push (org-point-in-group p 0 :target) clist)
15044 (goto-char (1- (match-beginning 0)))
15045 (if (looking-at org-radio-target-regexp)
15046 (push (org-point-in-group p 0 :radio-target) clist))
15047 (goto-char p))
15048 ((setq o (car (delq nil
15049 (mapcar
15050 (lambda (x)
15051 (if (memq x org-latex-fragment-image-overlays) x))
15052 (org-overlays-at (point))))))
15053 (push (list :latex-fragment
15054 (org-overlay-start o) (org-overlay-end o)) clist)
15055 (push (list :latex-preview
15056 (org-overlay-start o) (org-overlay-end o)) clist))
15057 ((org-inside-LaTeX-fragment-p)
15058 ;; FIXME: positions wrong.
15059 (push (list :latex-fragment (point) (point)) clist)))
15061 (setq clist (nreverse (delq nil clist)))
15062 clist))
15064 ;; FIXME: Compare with at-regexp-p Do we need both?
15065 (defun org-in-regexp (re &optional nlines visually)
15066 "Check if point is inside a match of regexp.
15067 Normally only the current line is checked, but you can include NLINES extra
15068 lines both before and after point into the search.
15069 If VISUALLY is set, require that the cursor is not after the match but
15070 really on, so that the block visually is on the match."
15071 (catch 'exit
15072 (let ((pos (point))
15073 (eol (point-at-eol (+ 1 (or nlines 0))))
15074 (inc (if visually 1 0)))
15075 (save-excursion
15076 (beginning-of-line (- 1 (or nlines 0)))
15077 (while (re-search-forward re eol t)
15078 (if (and (<= (match-beginning 0) pos)
15079 (>= (+ inc (match-end 0)) pos))
15080 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
15082 (defun org-at-regexp-p (regexp)
15083 "Is point inside a match of REGEXP in the current line?"
15084 (catch 'exit
15085 (save-excursion
15086 (let ((pos (point)) (end (point-at-eol)))
15087 (beginning-of-line 1)
15088 (while (re-search-forward regexp end t)
15089 (if (and (<= (match-beginning 0) pos)
15090 (>= (match-end 0) pos))
15091 (throw 'exit t)))
15092 nil))))
15094 (defun org-occur-in-agenda-files (regexp &optional nlines)
15095 "Call `multi-occur' with buffers for all agenda files."
15096 (interactive "sOrg-files matching: \np")
15097 (let* ((files (org-agenda-files))
15098 (tnames (mapcar 'file-truename files))
15099 (extra org-agenda-text-search-extra-files)
15101 (when (eq (car extra) 'agenda-archives)
15102 (setq extra (cdr extra))
15103 (setq files (org-add-archive-files files)))
15104 (while (setq f (pop extra))
15105 (unless (member (file-truename f) tnames)
15106 (add-to-list 'files f 'append)
15107 (add-to-list 'tnames (file-truename f) 'append)))
15108 (multi-occur
15109 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
15110 regexp)))
15112 (if (boundp 'occur-mode-find-occurrence-hook)
15113 ;; Emacs 23
15114 (add-hook 'occur-mode-find-occurrence-hook
15115 (lambda ()
15116 (when (org-mode-p)
15117 (org-reveal))))
15118 ;; Emacs 22
15119 (defadvice occur-mode-goto-occurrence
15120 (after org-occur-reveal activate)
15121 (and (org-mode-p) (org-reveal)))
15122 (defadvice occur-mode-goto-occurrence-other-window
15123 (after org-occur-reveal activate)
15124 (and (org-mode-p) (org-reveal)))
15125 (defadvice occur-mode-display-occurrence
15126 (after org-occur-reveal activate)
15127 (when (org-mode-p)
15128 (let ((pos (occur-mode-find-occurrence)))
15129 (with-current-buffer (marker-buffer pos)
15130 (save-excursion
15131 (goto-char pos)
15132 (org-reveal)))))))
15134 (defun org-uniquify (list)
15135 "Remove duplicate elements from LIST."
15136 (let (res)
15137 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
15138 res))
15140 (defun org-delete-all (elts list)
15141 "Remove all elements in ELTS from LIST."
15142 (while elts
15143 (setq list (delete (pop elts) list)))
15144 list)
15146 (defun org-back-over-empty-lines ()
15147 "Move backwards over whitespace, to the beginning of the first empty line.
15148 Returns the number of empty lines passed."
15149 (let ((pos (point)))
15150 (skip-chars-backward " \t\n\r")
15151 (beginning-of-line 2)
15152 (goto-char (min (point) pos))
15153 (count-lines (point) pos)))
15155 (defun org-skip-whitespace ()
15156 (skip-chars-forward " \t\n\r"))
15158 (defun org-point-in-group (point group &optional context)
15159 "Check if POINT is in match-group GROUP.
15160 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
15161 match. If the match group does ot exist or point is not inside it,
15162 return nil."
15163 (and (match-beginning group)
15164 (>= point (match-beginning group))
15165 (<= point (match-end group))
15166 (if context
15167 (list context (match-beginning group) (match-end group))
15168 t)))
15170 (defun org-switch-to-buffer-other-window (&rest args)
15171 "Switch to buffer in a second window on the current frame.
15172 In particular, do not allow pop-up frames."
15173 (let (pop-up-frames special-display-buffer-names special-display-regexps
15174 special-display-function)
15175 (apply 'switch-to-buffer-other-window args)))
15177 (defun org-combine-plists (&rest plists)
15178 "Create a single property list from all plists in PLISTS.
15179 The process starts by copying the first list, and then setting properties
15180 from the other lists. Settings in the last list are the most significant
15181 ones and overrule settings in the other lists."
15182 (let ((rtn (copy-sequence (pop plists)))
15183 p v ls)
15184 (while plists
15185 (setq ls (pop plists))
15186 (while ls
15187 (setq p (pop ls) v (pop ls))
15188 (setq rtn (plist-put rtn p v))))
15189 rtn))
15191 (defun org-move-line-down (arg)
15192 "Move the current line down. With prefix argument, move it past ARG lines."
15193 (interactive "p")
15194 (let ((col (current-column))
15195 beg end pos)
15196 (beginning-of-line 1) (setq beg (point))
15197 (beginning-of-line 2) (setq end (point))
15198 (beginning-of-line (+ 1 arg))
15199 (setq pos (move-marker (make-marker) (point)))
15200 (insert (delete-and-extract-region beg end))
15201 (goto-char pos)
15202 (org-move-to-column col)))
15204 (defun org-move-line-up (arg)
15205 "Move the current line up. With prefix argument, move it past ARG lines."
15206 (interactive "p")
15207 (let ((col (current-column))
15208 beg end pos)
15209 (beginning-of-line 1) (setq beg (point))
15210 (beginning-of-line 2) (setq end (point))
15211 (beginning-of-line (- arg))
15212 (setq pos (move-marker (make-marker) (point)))
15213 (insert (delete-and-extract-region beg end))
15214 (goto-char pos)
15215 (org-move-to-column col)))
15217 (defun org-replace-escapes (string table)
15218 "Replace %-escapes in STRING with values in TABLE.
15219 TABLE is an association list with keys like \"%a\" and string values.
15220 The sequences in STRING may contain normal field width and padding information,
15221 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
15222 so values can contain further %-escapes if they are define later in TABLE."
15223 (let ((case-fold-search nil)
15224 e re rpl)
15225 (while (setq e (pop table))
15226 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
15227 (while (string-match re string)
15228 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
15229 (cdr e)))
15230 (setq string (replace-match rpl t t string))))
15231 string))
15234 (defun org-sublist (list start end)
15235 "Return a section of LIST, from START to END.
15236 Counting starts at 1."
15237 (let (rtn (c start))
15238 (setq list (nthcdr (1- start) list))
15239 (while (and list (<= c end))
15240 (push (pop list) rtn)
15241 (setq c (1+ c)))
15242 (nreverse rtn)))
15244 (defun org-find-base-buffer-visiting (file)
15245 "Like `find-buffer-visiting' but alway return the base buffer and
15246 not an indirect buffer."
15247 (let ((buf (find-buffer-visiting file)))
15248 (if buf
15249 (or (buffer-base-buffer buf) buf)
15250 nil)))
15252 (defun org-image-file-name-regexp (&optional extensions)
15253 "Return regexp matching the file names of images.
15254 If EXTENSIONS is given, only match these."
15255 (if (and (not extensions) (fboundp 'image-file-name-regexp))
15256 (image-file-name-regexp)
15257 (let ((image-file-name-extensions
15258 (or extensions
15259 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
15260 "xbm" "xpm" "pbm" "pgm" "ppm"))))
15261 (concat "\\."
15262 (regexp-opt (nconc (mapcar 'upcase
15263 image-file-name-extensions)
15264 image-file-name-extensions)
15266 "\\'"))))
15268 (defun org-file-image-p (file &optional extensions)
15269 "Return non-nil if FILE is an image."
15270 (save-match-data
15271 (string-match (org-image-file-name-regexp extensions) file)))
15273 (defun org-get-cursor-date ()
15274 "Return the date at cursor in as a time.
15275 This works in the calendar and in the agenda, anywhere else it just
15276 returns the current time."
15277 (let (date day defd)
15278 (cond
15279 ((eq major-mode 'calendar-mode)
15280 (setq date (calendar-cursor-to-date)
15281 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15282 ((eq major-mode 'org-agenda-mode)
15283 (setq day (get-text-property (point) 'day))
15284 (if day
15285 (setq date (calendar-gregorian-from-absolute day)
15286 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
15287 (nth 2 date))))))
15288 (or defd (current-time))))
15290 (defvar org-agenda-action-marker (make-marker)
15291 "Marker pointing to the entry for the next agenda action.")
15293 (defun org-mark-entry-for-agenda-action ()
15294 "Mark the current entry as target of an agenda action.
15295 Agenda actions are actions executed from the agenda with the key `k',
15296 which make use of the date at the cursor."
15297 (interactive)
15298 (move-marker org-agenda-action-marker
15299 (save-excursion (org-back-to-heading t) (point))
15300 (current-buffer))
15301 (message
15302 "Entry marked for action; press `k' at desired date in agenda or calendar"))
15304 ;;; Paragraph filling stuff.
15305 ;; We want this to be just right, so use the full arsenal.
15307 (defun org-indent-line-function ()
15308 "Indent line like previous, but further if previous was headline or item."
15309 (interactive)
15310 (let* ((pos (point))
15311 (itemp (org-at-item-p))
15312 (org-drawer-regexp (or org-drawer-regexp "\000"))
15313 column bpos bcol tpos tcol bullet btype bullet-type)
15314 ;; Find the previous relevant line
15315 (beginning-of-line 1)
15316 (cond
15317 ((looking-at "#") (setq column 0))
15318 ((looking-at "\\*+ ") (setq column 0))
15319 ((and (looking-at "[ \t]*:END:")
15320 (save-excursion (re-search-backward org-drawer-regexp nil t)))
15321 (save-excursion
15322 (goto-char (1- (match-beginning 1)))
15323 (setq column (current-column))))
15325 (beginning-of-line 0)
15326 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]")
15327 (not (looking-at "[ \t]*:END:"))
15328 (not (looking-at org-drawer-regexp)))
15329 (beginning-of-line 0))
15330 (cond
15331 ((looking-at "\\*+[ \t]+")
15332 (if (not org-adapt-indentation)
15333 (setq column 0)
15334 (goto-char (match-end 0))
15335 (setq column (current-column))))
15336 ((looking-at org-drawer-regexp)
15337 (goto-char (1- (match-beginning 1)))
15338 (setq column (current-column)))
15339 ((looking-at "\\([ \t]*\\):END:")
15340 (goto-char (match-end 1))
15341 (setq column (current-column)))
15342 ((org-in-item-p)
15343 (org-beginning-of-item)
15344 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
15345 (setq bpos (match-beginning 1) tpos (match-end 0)
15346 bcol (progn (goto-char bpos) (current-column))
15347 tcol (progn (goto-char tpos) (current-column))
15348 bullet (match-string 1)
15349 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
15350 (if (> tcol (+ bcol org-description-max-indent))
15351 (setq tcol (+ bcol 5)))
15352 (if (not itemp)
15353 (setq column tcol)
15354 (goto-char pos)
15355 (beginning-of-line 1)
15356 (if (looking-at "\\S-")
15357 (progn
15358 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
15359 (setq bullet (match-string 1)
15360 btype (if (string-match "[0-9]" bullet) "n" bullet))
15361 (setq column (if (equal btype bullet-type) bcol tcol)))
15362 (setq column (org-get-indentation)))))
15363 (t (setq column (org-get-indentation))))))
15364 (goto-char pos)
15365 (if (<= (current-column) (current-indentation))
15366 (org-indent-line-to column)
15367 (save-excursion (org-indent-line-to column)))
15368 (setq column (current-column))
15369 (beginning-of-line 1)
15370 (if (looking-at
15371 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
15372 (replace-match (concat "\\1" (format org-property-format
15373 (match-string 2) (match-string 3)))
15374 t nil))
15375 (org-move-to-column column)))
15377 (defun org-set-autofill-regexps ()
15378 (interactive)
15379 ;; In the paragraph separator we include headlines, because filling
15380 ;; text in a line directly attached to a headline would otherwise
15381 ;; fill the headline as well.
15382 (org-set-local 'comment-start-skip "^#+[ \t]*")
15383 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
15384 ;; The paragraph starter includes hand-formatted lists.
15385 (org-set-local 'paragraph-start
15386 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
15387 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
15388 ;; But only if the user has not turned off tables or fixed-width regions
15389 (org-set-local
15390 'auto-fill-inhibit-regexp
15391 (concat "\\*+ \\|#\\+"
15392 "\\|[ \t]*" org-keyword-time-regexp
15393 (if (or org-enable-table-editor org-enable-fixed-width-editor)
15394 (concat
15395 "\\|[ \t]*["
15396 (if org-enable-table-editor "|" "")
15397 (if org-enable-fixed-width-editor ":" "")
15398 "]"))))
15399 ;; We use our own fill-paragraph function, to make sure that tables
15400 ;; and fixed-width regions are not wrapped. That function will pass
15401 ;; through to `fill-paragraph' when appropriate.
15402 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
15403 ; Adaptive filling: To get full control, first make sure that
15404 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
15405 (org-set-local 'adaptive-fill-regexp "\000")
15406 (org-set-local 'adaptive-fill-function
15407 'org-adaptive-fill-function)
15408 (org-set-local
15409 'align-mode-rules-list
15410 '((org-in-buffer-settings
15411 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
15412 (modes . '(org-mode))))))
15414 (defun org-fill-paragraph (&optional justify)
15415 "Re-align a table, pass through to fill-paragraph if no table."
15416 (let ((table-p (org-at-table-p))
15417 (table.el-p (org-at-table.el-p)))
15418 (cond ((and (equal (char-after (point-at-bol)) ?*)
15419 (save-excursion (goto-char (point-at-bol))
15420 (looking-at outline-regexp)))
15421 t) ; skip headlines
15422 (table.el-p t) ; skip table.el tables
15423 (table-p (org-table-align) t) ; align org-mode tables
15424 (t nil)))) ; call paragraph-fill
15426 ;; For reference, this is the default value of adaptive-fill-regexp
15427 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
15429 (defun org-adaptive-fill-function ()
15430 "Return a fill prefix for org-mode files.
15431 In particular, this makes sure hanging paragraphs for hand-formatted lists
15432 work correctly."
15433 (cond ((looking-at "#[ \t]+")
15434 (match-string 0))
15435 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
15436 (save-excursion
15437 (if (> (match-end 1) (+ (match-beginning 1)
15438 org-description-max-indent))
15439 (goto-char (+ (match-beginning 1) 5))
15440 (goto-char (match-end 0)))
15441 (make-string (current-column) ?\ )))
15442 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
15443 (save-excursion
15444 (goto-char (match-end 0))
15445 (make-string (current-column) ?\ )))
15446 (t nil)))
15448 ;;; Other stuff.
15450 (defun org-toggle-fixed-width-section (arg)
15451 "Toggle the fixed-width export.
15452 If there is no active region, the QUOTE keyword at the current headline is
15453 inserted or removed. When present, it causes the text between this headline
15454 and the next to be exported as fixed-width text, and unmodified.
15455 If there is an active region, this command adds or removes a colon as the
15456 first character of this line. If the first character of a line is a colon,
15457 this line is also exported in fixed-width font."
15458 (interactive "P")
15459 (let* ((cc 0)
15460 (regionp (org-region-active-p))
15461 (beg (if regionp (region-beginning) (point)))
15462 (end (if regionp (region-end)))
15463 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
15464 (case-fold-search nil)
15465 (re "[ \t]*\\(: \\)")
15466 off)
15467 (if regionp
15468 (save-excursion
15469 (goto-char beg)
15470 (setq cc (current-column))
15471 (beginning-of-line 1)
15472 (setq off (looking-at re))
15473 (while (> nlines 0)
15474 (setq nlines (1- nlines))
15475 (beginning-of-line 1)
15476 (cond
15477 (arg
15478 (org-move-to-column cc t)
15479 (insert ": \n")
15480 (forward-line -1))
15481 ((and off (looking-at re))
15482 (replace-match "" t t nil 1))
15483 ((not off) (org-move-to-column cc t) (insert ": ")))
15484 (forward-line 1)))
15485 (save-excursion
15486 (org-back-to-heading)
15487 (if (looking-at (concat outline-regexp
15488 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
15489 (replace-match "" t t nil 1)
15490 (if (looking-at outline-regexp)
15491 (progn
15492 (goto-char (match-end 0))
15493 (insert org-quote-string " "))))))))
15495 (defun org-reftex-citation ()
15496 "Use reftex-citation to insert a citation into the buffer.
15497 This looks for a line like
15499 #+BIBLIOGRAPHY: foo plain option:-d
15501 and derives from it that foo.bib is the bbliography file relevant
15502 for this document. It then installs the necessary environment for RefTeX
15503 to work in this buffer and calls `reftex-citation' to insert a citation
15504 into the buffer.
15506 Export of such citations to both LaTeX and HTML is handled by the contributed
15507 package org-exp-bibtex by Taru Karttunen."
15508 (interactive)
15509 (let ((reftex-docstruct-symbol 'rds)
15510 (reftex-cite-format "\\cite{%l}")
15511 rds bib)
15512 (save-excursion
15513 (save-restriction
15514 (widen)
15515 (let ((case-fold-search t)
15516 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
15517 (if (not (save-excursion
15518 (or (re-search-forward re nil t)
15519 (re-search-backward re nil t))))
15520 (error "No bibliography defined in file")
15521 (setq bib (concat (match-string 1) ".bib")
15522 rds (list (list 'bib bib)))))))
15523 (call-interactively 'reftex-citation)))
15525 ;;;; Functions extending outline functionality
15527 (defun org-beginning-of-line (&optional arg)
15528 "Go to the beginning of the current line. If that is invisible, continue
15529 to a visible line beginning. This makes the function of C-a more intuitive.
15530 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
15531 first attempt, and only move to after the tags when the cursor is already
15532 beyond the end of the headline."
15533 (interactive "P")
15534 (let ((pos (point))
15535 (special (if (consp org-special-ctrl-a/e)
15536 (car org-special-ctrl-a/e)
15537 org-special-ctrl-a/e))
15538 refpos)
15539 (beginning-of-line 1)
15540 (if (and arg (fboundp 'move-beginning-of-line))
15541 (call-interactively 'move-beginning-of-line)
15542 (if (bobp)
15544 (backward-char 1)
15545 (if (org-invisible-p)
15546 (while (and (not (bobp)) (org-invisible-p))
15547 (backward-char 1)
15548 (beginning-of-line 1))
15549 (forward-char 1))))
15550 (when special
15551 (cond
15552 ((and (looking-at org-complex-heading-regexp)
15553 (= (char-after (match-end 1)) ?\ ))
15554 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
15555 (point-at-eol)))
15556 (goto-char
15557 (if (eq special t)
15558 (cond ((> pos refpos) refpos)
15559 ((= pos (point)) refpos)
15560 (t (point)))
15561 (cond ((> pos (point)) (point))
15562 ((not (eq last-command this-command)) (point))
15563 (t refpos)))))
15564 ((org-at-item-p)
15565 (goto-char
15566 (if (eq special t)
15567 (cond ((> pos (match-end 4)) (match-end 4))
15568 ((= pos (point)) (match-end 4))
15569 (t (point)))
15570 (cond ((> pos (point)) (point))
15571 ((not (eq last-command this-command)) (point))
15572 (t (match-end 4))))))))
15573 (org-no-warnings
15574 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
15576 (defun org-end-of-line (&optional arg)
15577 "Go to the end of the line.
15578 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
15579 first attempt, and only move to after the tags when the cursor is already
15580 beyond the end of the headline."
15581 (interactive "P")
15582 (let ((special (if (consp org-special-ctrl-a/e)
15583 (cdr org-special-ctrl-a/e)
15584 org-special-ctrl-a/e)))
15585 (if (or (not special)
15586 (not (org-on-heading-p))
15587 arg)
15588 (call-interactively (if (fboundp 'move-end-of-line)
15589 'move-end-of-line
15590 'end-of-line))
15591 (let ((pos (point)))
15592 (beginning-of-line 1)
15593 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15594 (if (eq special t)
15595 (if (or (< pos (match-beginning 1))
15596 (= pos (match-end 0)))
15597 (goto-char (match-beginning 1))
15598 (goto-char (match-end 0)))
15599 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
15600 (goto-char (match-end 0))
15601 (goto-char (match-beginning 1))))
15602 (call-interactively (if (fboundp 'move-end-of-line)
15603 'move-end-of-line
15604 'end-of-line)))))
15605 (org-no-warnings
15606 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
15608 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
15609 (define-key org-mode-map "\C-e" 'org-end-of-line)
15611 (defun org-backward-sentence (&optional arg)
15612 "Go to beginning of sentence, or beginning of table field.
15613 This will call `backward-sentence' or `org-table-beginning-of-field',
15614 depending on context."
15615 (interactive "P")
15616 (cond
15617 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
15618 (t (call-interactively 'backward-sentence))))
15620 (defun org-forward-sentence (&optional arg)
15621 "Go to end of sentence, or end of table field.
15622 This will call `forward-sentence' or `org-table-end-of-field',
15623 depending on context."
15624 (interactive "P")
15625 (cond
15626 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
15627 (t (call-interactively 'forward-sentence))))
15629 (define-key org-mode-map "\M-a" 'org-backward-sentence)
15630 (define-key org-mode-map "\M-e" 'org-forward-sentence)
15632 (defun org-kill-line (&optional arg)
15633 "Kill line, to tags or end of line."
15634 (interactive "P")
15635 (cond
15636 ((or (not org-special-ctrl-k)
15637 (bolp)
15638 (not (org-on-heading-p)))
15639 (call-interactively 'kill-line))
15640 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
15641 (kill-region (point) (match-beginning 1))
15642 (org-set-tags nil t))
15643 (t (kill-region (point) (point-at-eol)))))
15645 (define-key org-mode-map "\C-k" 'org-kill-line)
15647 (defun org-yank (&optional arg)
15648 "Yank. If the kill is a subtree, treat it specially.
15649 This command will look at the current kill and check if is a single
15650 subtree, or a series of subtrees[1]. If it passes the test, and if the
15651 cursor is at the beginning of a line or after the stars of a currently
15652 empty headline, then the yank is handled specially. How exactly depends
15653 on the value of the following variables, both set by default.
15655 org-yank-folded-subtrees
15656 When set, the subtree(s) will be folded after insertion, but only
15657 if doing so would now swallow text after the yanked text.
15659 org-yank-adjusted-subtrees
15660 When set, the subtree will be promoted or demoted in order to
15661 fit into the local outline tree structure, which means that the level
15662 will be adjusted so that it becomes the smaller one of the two
15663 *visible* surrounding headings.
15665 Any prefix to this command will cause `yank' to be called directly with
15666 no special treatment. In particular, a simple `C-u' prefix will just
15667 plainly yank the text as it is.
15669 \[1] Basically, the test checks if the first non-white line is a heading
15670 and if there are no other headings with fewer stars."
15671 (interactive "P")
15672 (setq this-command 'yank)
15673 (if arg
15674 (call-interactively 'yank)
15675 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
15676 (and (org-kill-is-subtree-p)
15677 (or (bolp)
15678 (and (looking-at "[ \t]*$")
15679 (string-match
15680 "\\`\\*+\\'"
15681 (buffer-substring (point-at-bol) (point)))))))
15682 swallowp)
15683 (cond
15684 ((and subtreep org-yank-folded-subtrees)
15685 (let ((beg (point))
15686 end)
15687 (if (and subtreep org-yank-adjusted-subtrees)
15688 (org-paste-subtree nil nil 'for-yank)
15689 (call-interactively 'yank))
15690 (setq end (point))
15691 (goto-char beg)
15692 (when (and (bolp) subtreep
15693 (not (setq swallowp
15694 (org-yank-folding-would-swallow-text beg end))))
15695 (or (looking-at outline-regexp)
15696 (re-search-forward (concat "^" outline-regexp) end t))
15697 (while (and (< (point) end) (looking-at outline-regexp))
15698 (hide-subtree)
15699 (org-cycle-show-empty-lines 'folded)
15700 (condition-case nil
15701 (outline-forward-same-level 1)
15702 (error (goto-char end)))))
15703 (when swallowp
15704 (message
15705 "Yanked text not folded because that would swallow text"))
15706 (goto-char end)
15707 (skip-chars-forward " \t\n\r")
15708 (beginning-of-line 1)
15709 (push-mark beg 'nomsg)))
15710 ((and subtreep org-yank-adjusted-subtrees)
15711 (let ((beg (point-at-bol)))
15712 (org-paste-subtree nil nil 'for-yank)
15713 (push-mark beg 'nomsg)))
15715 (call-interactively 'yank))))))
15717 (defun org-yank-folding-would-swallow-text (beg end)
15718 "Would hide-subtree at BEG swallow any text after END?"
15719 (let (level)
15720 (save-excursion
15721 (goto-char beg)
15722 (when (or (looking-at outline-regexp)
15723 (re-search-forward (concat "^" outline-regexp) end t))
15724 (setq level (org-outline-level)))
15725 (goto-char end)
15726 (skip-chars-forward " \t\r\n\v\f")
15727 (if (or (eobp)
15728 (and (bolp) (looking-at org-outline-regexp)
15729 (<= (org-outline-level) level)))
15730 nil ; Nothing would be swallowed
15731 t)))) ; something would swallow
15733 (define-key org-mode-map "\C-y" 'org-yank)
15735 (defun org-invisible-p ()
15736 "Check if point is at a character currently not visible."
15737 ;; Early versions of noutline don't have `outline-invisible-p'.
15738 (if (fboundp 'outline-invisible-p)
15739 (outline-invisible-p)
15740 (get-char-property (point) 'invisible)))
15742 (defun org-invisible-p2 ()
15743 "Check if point is at a character currently not visible."
15744 (save-excursion
15745 (if (and (eolp) (not (bobp))) (backward-char 1))
15746 ;; Early versions of noutline don't have `outline-invisible-p'.
15747 (if (fboundp 'outline-invisible-p)
15748 (outline-invisible-p)
15749 (get-char-property (point) 'invisible))))
15751 (defun org-back-to-heading (&optional invisible-ok)
15752 "Call `outline-back-to-heading', but provide a better error message."
15753 (condition-case nil
15754 (outline-back-to-heading invisible-ok)
15755 (error (error "Before first headline at position %d in buffer %s"
15756 (point) (current-buffer)))))
15758 (defun org-before-first-heading-p ()
15759 "Before first heading?"
15760 (save-excursion
15761 (null (re-search-backward "^\\*+ " nil t))))
15763 (defalias 'org-on-heading-p 'outline-on-heading-p)
15764 (defalias 'org-at-heading-p 'outline-on-heading-p)
15765 (defun org-at-heading-or-item-p ()
15766 (or (org-on-heading-p) (org-at-item-p)))
15768 (defun org-on-target-p ()
15769 (or (org-in-regexp org-radio-target-regexp)
15770 (org-in-regexp org-target-regexp)))
15772 (defun org-up-heading-all (arg)
15773 "Move to the heading line of which the present line is a subheading.
15774 This function considers both visible and invisible heading lines.
15775 With argument, move up ARG levels."
15776 (if (fboundp 'outline-up-heading-all)
15777 (outline-up-heading-all arg) ; emacs 21 version of outline.el
15778 (outline-up-heading arg t))) ; emacs 22 version of outline.el
15780 (defun org-up-heading-safe ()
15781 "Move to the heading line of which the present line is a subheading.
15782 This version will not throw an error. It will return the level of the
15783 headline found, or nil if no higher level is found.
15785 Also, this function will be a lot faster than `outline-up-heading',
15786 because it relies on stars being the outline starters. This can really
15787 make a significant difference in outlines with very many siblings."
15788 (let (start-level re)
15789 (org-back-to-heading t)
15790 (setq start-level (funcall outline-level))
15791 (if (equal start-level 1)
15793 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
15794 (if (re-search-backward re nil t)
15795 (funcall outline-level)))))
15797 (defun org-first-sibling-p ()
15798 "Is this heading the first child of its parents?"
15799 (interactive)
15800 (let ((re (concat "^" outline-regexp))
15801 level l)
15802 (unless (org-at-heading-p t)
15803 (error "Not at a heading"))
15804 (setq level (funcall outline-level))
15805 (save-excursion
15806 (if (not (re-search-backward re nil t))
15808 (setq l (funcall outline-level))
15809 (< l level)))))
15811 (defun org-goto-sibling (&optional previous)
15812 "Goto the next sibling, even if it is invisible.
15813 When PREVIOUS is set, go to the previous sibling instead. Returns t
15814 when a sibling was found. When none is found, return nil and don't
15815 move point."
15816 (let ((fun (if previous 're-search-backward 're-search-forward))
15817 (pos (point))
15818 (re (concat "^" outline-regexp))
15819 level l)
15820 (when (condition-case nil (org-back-to-heading t) (error nil))
15821 (setq level (funcall outline-level))
15822 (catch 'exit
15823 (or previous (forward-char 1))
15824 (while (funcall fun re nil t)
15825 (setq l (funcall outline-level))
15826 (when (< l level) (goto-char pos) (throw 'exit nil))
15827 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
15828 (goto-char pos)
15829 nil))))
15831 (defun org-show-siblings ()
15832 "Show all siblings of the current headline."
15833 (save-excursion
15834 (while (org-goto-sibling) (org-flag-heading nil)))
15835 (save-excursion
15836 (while (org-goto-sibling 'previous)
15837 (org-flag-heading nil))))
15839 (defun org-show-hidden-entry ()
15840 "Show an entry where even the heading is hidden."
15841 (save-excursion
15842 (org-show-entry)))
15844 (defun org-flag-heading (flag &optional entry)
15845 "Flag the current heading. FLAG non-nil means make invisible.
15846 When ENTRY is non-nil, show the entire entry."
15847 (save-excursion
15848 (org-back-to-heading t)
15849 ;; Check if we should show the entire entry
15850 (if entry
15851 (progn
15852 (org-show-entry)
15853 (save-excursion
15854 (and (outline-next-heading)
15855 (org-flag-heading nil))))
15856 (outline-flag-region (max (point-min) (1- (point)))
15857 (save-excursion (outline-end-of-heading) (point))
15858 flag))))
15860 (defun org-forward-same-level (arg)
15861 "Move forward to the ARG'th subheading at same level as this one.
15862 Stop at the first and last subheadings of a superior heading.
15863 This is like outline-forward-same-level, but invisible headings are ok."
15864 (interactive "p")
15865 (org-back-to-heading t)
15866 (while (> arg 0)
15867 (let ((point-to-move-to (save-excursion
15868 (org-get-next-sibling))))
15869 (if point-to-move-to
15870 (progn
15871 (goto-char point-to-move-to)
15872 (setq arg (1- arg)))
15873 (progn
15874 (setq arg 0)
15875 (error "No following same-level heading"))))))
15877 (defun org-get-next-sibling ()
15878 "Move to next heading of the same level, and return point.
15879 If there is no such heading, return nil.
15880 This is like outline-next-sibling, but invisible headings are ok."
15881 (let ((level (funcall outline-level)))
15882 (outline-next-heading)
15883 (while (and (not (eobp)) (> (funcall outline-level) level))
15884 (outline-next-heading))
15885 (if (or (eobp) (< (funcall outline-level) level))
15887 (point))))
15889 (defun org-end-of-subtree (&optional invisible-OK to-heading)
15890 ;; This is an exact copy of the original function, but it uses
15891 ;; `org-back-to-heading', to make it work also in invisible
15892 ;; trees. And is uses an invisible-OK argument.
15893 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
15894 (org-back-to-heading invisible-OK)
15895 (let ((first t)
15896 (level (funcall outline-level)))
15897 (while (and (not (eobp))
15898 (or first (> (funcall outline-level) level)))
15899 (setq first nil)
15900 (outline-next-heading))
15901 (unless to-heading
15902 (if (memq (preceding-char) '(?\n ?\^M))
15903 (progn
15904 ;; Go to end of line before heading
15905 (forward-char -1)
15906 (if (memq (preceding-char) '(?\n ?\^M))
15907 ;; leave blank line before heading
15908 (forward-char -1))))))
15909 (point))
15911 (defun org-show-subtree ()
15912 "Show everything after this heading at deeper levels."
15913 (outline-flag-region
15914 (point)
15915 (save-excursion
15916 (outline-end-of-subtree) (outline-next-heading) (point))
15917 nil))
15919 (defun org-show-entry ()
15920 "Show the body directly following this heading.
15921 Show the heading too, if it is currently invisible."
15922 (interactive)
15923 (save-excursion
15924 (condition-case nil
15925 (progn
15926 (org-back-to-heading t)
15927 (outline-flag-region
15928 (max (point-min) (1- (point)))
15929 (save-excursion
15930 (if (re-search-forward
15931 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
15932 (match-beginning 1)
15933 (point-max)))
15934 nil))
15935 (error nil))))
15937 (defun org-make-options-regexp (kwds &optional extra)
15938 "Make a regular expression for keyword lines."
15939 (concat
15941 "#?[ \t]*\\+\\("
15942 (mapconcat 'regexp-quote kwds "\\|")
15943 (if extra (concat "\\|" extra))
15944 "\\):[ \t]*"
15945 "\\(.+\\)"))
15947 ;; Make isearch reveal the necessary context
15948 (defun org-isearch-end ()
15949 "Reveal context after isearch exits."
15950 (when isearch-success ; only if search was successful
15951 (if (featurep 'xemacs)
15952 ;; Under XEmacs, the hook is run in the correct place,
15953 ;; we directly show the context.
15954 (org-show-context 'isearch)
15955 ;; In Emacs the hook runs *before* restoring the overlays.
15956 ;; So we have to use a one-time post-command-hook to do this.
15957 ;; (Emacs 22 has a special variable, see function `org-mode')
15958 (unless (and (boundp 'isearch-mode-end-hook-quit)
15959 isearch-mode-end-hook-quit)
15960 ;; Only when the isearch was not quitted.
15961 (org-add-hook 'post-command-hook 'org-isearch-post-command
15962 'append 'local)))))
15964 (defun org-isearch-post-command ()
15965 "Remove self from hook, and show context."
15966 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
15967 (org-show-context 'isearch))
15970 ;;;; Integration with and fixes for other packages
15972 ;;; Imenu support
15974 (defvar org-imenu-markers nil
15975 "All markers currently used by Imenu.")
15976 (make-variable-buffer-local 'org-imenu-markers)
15978 (defun org-imenu-new-marker (&optional pos)
15979 "Return a new marker for use by Imenu, and remember the marker."
15980 (let ((m (make-marker)))
15981 (move-marker m (or pos (point)))
15982 (push m org-imenu-markers)
15985 (defun org-imenu-get-tree ()
15986 "Produce the index for Imenu."
15987 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
15988 (setq org-imenu-markers nil)
15989 (let* ((n org-imenu-depth)
15990 (re (concat "^" outline-regexp))
15991 (subs (make-vector (1+ n) nil))
15992 (last-level 0)
15993 m level head)
15994 (save-excursion
15995 (save-restriction
15996 (widen)
15997 (goto-char (point-max))
15998 (while (re-search-backward re nil t)
15999 (setq level (org-reduced-level (funcall outline-level)))
16000 (when (<= level n)
16001 (looking-at org-complex-heading-regexp)
16002 (setq head (org-link-display-format
16003 (org-match-string-no-properties 4))
16004 m (org-imenu-new-marker))
16005 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
16006 (if (>= level last-level)
16007 (push (cons head m) (aref subs level))
16008 (push (cons head (aref subs (1+ level))) (aref subs level))
16009 (loop for i from (1+ level) to n do (aset subs i nil)))
16010 (setq last-level level)))))
16011 (aref subs 1)))
16013 (eval-after-load "imenu"
16014 '(progn
16015 (add-hook 'imenu-after-jump-hook
16016 (lambda ()
16017 (if (eq major-mode 'org-mode)
16018 (org-show-context 'org-goto))))))
16020 (defun org-link-display-format (link)
16021 "Replace a link with either the description, or the link target
16022 if no description is present"
16023 (save-match-data
16024 (if (string-match org-bracket-link-analytic-regexp link)
16025 (replace-match (or (match-string 5 link)
16026 (concat (match-string 1 link)
16027 (match-string 3 link)))
16028 nil nil link)
16029 link)))
16031 ;; Speedbar support
16033 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
16034 "Overlay marking the agenda restriction line in speedbar.")
16035 (org-overlay-put org-speedbar-restriction-lock-overlay
16036 'face 'org-agenda-restriction-lock)
16037 (org-overlay-put org-speedbar-restriction-lock-overlay
16038 'help-echo "Agendas are currently limited to this item.")
16039 (org-detach-overlay org-speedbar-restriction-lock-overlay)
16041 (defun org-speedbar-set-agenda-restriction ()
16042 "Restrict future agenda commands to the location at point in speedbar.
16043 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
16044 (interactive)
16045 (require 'org-agenda)
16046 (let (p m tp np dir txt)
16047 (cond
16048 ((setq p (text-property-any (point-at-bol) (point-at-eol)
16049 'org-imenu t))
16050 (setq m (get-text-property p 'org-imenu-marker))
16051 (save-excursion
16052 (save-restriction
16053 (set-buffer (marker-buffer m))
16054 (goto-char m)
16055 (org-agenda-set-restriction-lock 'subtree))))
16056 ((setq p (text-property-any (point-at-bol) (point-at-eol)
16057 'speedbar-function 'speedbar-find-file))
16058 (setq tp (previous-single-property-change
16059 (1+ p) 'speedbar-function)
16060 np (next-single-property-change
16061 tp 'speedbar-function)
16062 dir (speedbar-line-directory)
16063 txt (buffer-substring-no-properties (or tp (point-min))
16064 (or np (point-max))))
16065 (save-excursion
16066 (save-restriction
16067 (set-buffer (find-file-noselect
16068 (let ((default-directory dir))
16069 (expand-file-name txt))))
16070 (unless (org-mode-p)
16071 (error "Cannot restrict to non-Org-mode file"))
16072 (org-agenda-set-restriction-lock 'file))))
16073 (t (error "Don't know how to restrict Org-mode's agenda")))
16074 (org-move-overlay org-speedbar-restriction-lock-overlay
16075 (point-at-bol) (point-at-eol))
16076 (setq current-prefix-arg nil)
16077 (org-agenda-maybe-redo)))
16079 (eval-after-load "speedbar"
16080 '(progn
16081 (speedbar-add-supported-extension ".org")
16082 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
16083 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
16084 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
16085 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
16086 (add-hook 'speedbar-visiting-tag-hook
16087 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
16090 ;;; Fixes and Hacks for problems with other packages
16092 ;; Make flyspell not check words in links, to not mess up our keymap
16093 (defun org-mode-flyspell-verify ()
16094 "Don't let flyspell put overlays at active buttons."
16095 (not (get-text-property (point) 'keymap)))
16097 ;; Make `bookmark-jump' show the jump location if it was hidden.
16098 (eval-after-load "bookmark"
16099 '(if (boundp 'bookmark-after-jump-hook)
16100 ;; We can use the hook
16101 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
16102 ;; Hook not available, use advice
16103 (defadvice bookmark-jump (after org-make-visible activate)
16104 "Make the position visible."
16105 (org-bookmark-jump-unhide))))
16107 ;; Make sure saveplace show the location if it was hidden
16108 (eval-after-load "saveplace"
16109 '(defadvice save-place-find-file-hook (after org-make-visible activate)
16110 "Make the position visible."
16111 (org-bookmark-jump-unhide)))
16113 (defun org-bookmark-jump-unhide ()
16114 "Unhide the current position, to show the bookmark location."
16115 (and (org-mode-p)
16116 (or (org-invisible-p)
16117 (save-excursion (goto-char (max (point-min) (1- (point))))
16118 (org-invisible-p)))
16119 (org-show-context 'bookmark-jump)))
16121 ;; Make session.el ignore our circular variable
16122 (eval-after-load "session"
16123 '(add-to-list 'session-globals-exclude 'org-mark-ring))
16125 ;;;; Experimental code
16127 (defun org-closed-in-range ()
16128 "Sparse tree of items closed in a certain time range.
16129 Still experimental, may disappear in the future."
16130 (interactive)
16131 ;; Get the time interval from the user.
16132 (let* ((time1 (time-to-seconds
16133 (org-read-date nil 'to-time nil "Starting date: ")))
16134 (time2 (time-to-seconds
16135 (org-read-date nil 'to-time nil "End date:")))
16136 ;; callback function
16137 (callback (lambda ()
16138 (let ((time
16139 (time-to-seconds
16140 (apply 'encode-time
16141 (org-parse-time-string
16142 (match-string 1))))))
16143 ;; check if time in interval
16144 (and (>= time time1) (<= time time2))))))
16145 ;; make tree, check each match with the callback
16146 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
16148 ;;;; Finish up
16150 (provide 'org)
16152 (run-hooks 'org-load-hook)
16154 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
16156 ;;; org.el ends here