Custom links in the list of changes, testing
[org-mode.git] / lisp / org.el
blob31d26866515ec508bec5cc3949e4e8d14ad87dcf
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.26b
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.26b"
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/paste 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 (OBSOLETE, use org-protocol)" 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 (OBSOLETE, use org-protocol)" 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 (PARTIALLY OBSOLETE, see built-in dependency support))" 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 (PARTIALLY OBSOLETE, see secondary filtering)" 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-pre-cycle-hook nil
630 "Hook that is run before visibility cycling is happening.
631 The function(s) in this hook must accept a single argument which indicates
632 the new state that will be set right after running this hook. The
633 argument is a symbol. Before a global state change, it can have the values
634 `overview', `content', or `all'. Before a local state change, it can have
635 the values `folded', `children', or `subtree'."
636 :group 'org-cycle
637 :type 'hook)
639 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
640 org-cycle-hide-drawers
641 org-cycle-show-empty-lines
642 org-optimize-window-after-visibility-change)
643 "Hook that is run after `org-cycle' has changed the buffer visibility.
644 The function(s) in this hook must accept a single argument which indicates
645 the new state that was set by the most recent `org-cycle' command. The
646 argument is a symbol. After a global state change, it can have the values
647 `overview', `content', or `all'. After a local state change, it can have
648 the values `folded', `children', or `subtree'."
649 :group 'org-cycle
650 :type 'hook)
652 (defgroup org-edit-structure nil
653 "Options concerning structure editing in Org-mode."
654 :tag "Org Edit Structure"
655 :group 'org-structure)
657 (defcustom org-odd-levels-only nil
658 "Non-nil means, skip even levels and only use odd levels for the outline.
659 This has the effect that two stars are being added/taken away in
660 promotion/demotion commands. It also influences how levels are
661 handled by the exporters.
662 Changing it requires restart of `font-lock-mode' to become effective
663 for fontification also in regions already fontified.
664 You may also set this on a per-file basis by adding one of the following
665 lines to the buffer:
667 #+STARTUP: odd
668 #+STARTUP: oddeven"
669 :group 'org-edit-structure
670 :group 'org-font-lock
671 :type 'boolean)
673 (defcustom org-adapt-indentation t
674 "Non-nil means, adapt indentation when promoting and demoting.
675 When this is set and the *entire* text in an entry is indented, the
676 indentation is increased by one space in a demotion command, and
677 decreased by one in a promotion command. If any line in the entry
678 body starts at column 0, indentation is not changed at all."
679 :group 'org-edit-structure
680 :type 'boolean)
682 (defcustom org-special-ctrl-a/e nil
683 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
685 When t, `C-a' will bring back the cursor to the beginning of the
686 headline text, i.e. after the stars and after a possible TODO keyword.
687 In an item, this will be the position after the bullet.
688 When the cursor is already at that position, another `C-a' will bring
689 it to the beginning of the line.
691 `C-e' will jump to the end of the headline, ignoring the presence of tags
692 in the headline. A second `C-e' will then jump to the true end of the
693 line, after any tags.
695 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
696 and only a directly following, identical keypress will bring the cursor
697 to the special positions.
699 This may also be a cons cell where the behavior for `C-a' and `C-e' is
700 set separately."
701 :group 'org-edit-structure
702 :type '(choice
703 (const :tag "off" nil)
704 (const :tag "after stars/bullet and before tags first" t)
705 (const :tag "true line boundary first" reversed)
706 (cons :tag "Set C-a and C-e separately"
707 (choice :tag "Special C-a"
708 (const :tag "off" nil)
709 (const :tag "after stars/bullet first" t)
710 (const :tag "before stars/bullet first" reversed))
711 (choice :tag "Special C-e"
712 (const :tag "off" nil)
713 (const :tag "before tags first" t)
714 (const :tag "after tags first" reversed)))))
715 (if (fboundp 'defvaralias)
716 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
718 (defcustom org-special-ctrl-k nil
719 "Non-nil means `C-k' will behave specially in headlines.
720 When nil, `C-k' will call the default `kill-line' command.
721 When t, the following will happen while the cursor is in the headline:
723 - When the cursor is at the beginning of a headline, kill the entire
724 line and possible the folded subtree below the line.
725 - When in the middle of the headline text, kill the headline up to the tags.
726 - When after the headline text, kill the tags."
727 :group 'org-edit-structure
728 :type 'boolean)
730 (defcustom org-yank-folded-subtrees t
731 "Non-nil means, when yanking subtrees, fold them.
732 If the kill is a single subtree, or a sequence of subtrees, i.e. if
733 it starts with a heading and all other headings in it are either children
734 or siblings, then fold all the subtrees. However, do this only if no
735 text after the yank would be swallowed into a folded tree by this action."
736 :group 'org-edit-structure
737 :type 'boolean)
739 (defcustom org-yank-adjusted-subtrees nil
740 "Non-nil means, when yanking subtrees, adjust the level.
741 With this setting, `org-paste-subtree' is used to insert the subtree, see
742 this function for details."
743 :group 'org-edit-structure
744 :type 'boolean)
746 (defcustom org-M-RET-may-split-line '((default . t))
747 "Non-nil means, M-RET will split the line at the cursor position.
748 When nil, it will go to the end of the line before making a
749 new line.
750 You may also set this option in a different way for different
751 contexts. Valid contexts are:
753 headline when creating a new headline
754 item when creating a new item
755 table in a table field
756 default the value to be used for all contexts not explicitly
757 customized"
758 :group 'org-structure
759 :group 'org-table
760 :type '(choice
761 (const :tag "Always" t)
762 (const :tag "Never" nil)
763 (repeat :greedy t :tag "Individual contexts"
764 (cons
765 (choice :tag "Context"
766 (const headline)
767 (const item)
768 (const table)
769 (const default))
770 (boolean)))))
773 (defcustom org-insert-heading-respect-content nil
774 "Non-nil means, insert new headings after the current subtree.
775 When nil, the new heading is created directly after the current line.
776 The commands \\[org-insert-heading-respect-content] and
777 \\[org-insert-todo-heading-respect-content] turn this variable on
778 for the duration of the command."
779 :group 'org-structure
780 :type 'boolean)
782 (defcustom org-blank-before-new-entry '((heading . auto)
783 (plain-list-item . auto))
784 "Should `org-insert-heading' leave a blank line before new heading/item?
785 The value is an alist, with `heading' and `plain-list-item' as car,
786 and a boolean flag as cdr. For plain lists, if the variable
787 `org-empty-line-terminates-plain-lists' is set, the setting here
788 is ignored and no empty line is inserted, to keep the list in tact."
789 :group 'org-edit-structure
790 :type '(list
791 (cons (const heading)
792 (choice (const :tag "Never" nil)
793 (const :tag "Always" t)
794 (const :tag "Auto" auto)))
795 (cons (const plain-list-item)
796 (choice (const :tag "Never" nil)
797 (const :tag "Always" t)
798 (const :tag "Auto" auto)))))
800 (defcustom org-insert-heading-hook nil
801 "Hook being run after inserting a new heading."
802 :group 'org-edit-structure
803 :type 'hook)
805 (defcustom org-enable-fixed-width-editor t
806 "Non-nil means, lines starting with \":\" are treated as fixed-width.
807 This currently only means, they are never auto-wrapped.
808 When nil, such lines will be treated like ordinary lines.
809 See also the QUOTE keyword."
810 :group 'org-edit-structure
811 :type 'boolean)
813 (defcustom org-edit-src-region-extra nil
814 "Additional regexps to identify regions for editing with `org-edit-src-code'.
815 For examples see the function `org-edit-src-find-region-and-lang'.
816 The regular expression identifying the begin marker should end with a newline,
817 and the regexp marking the end line should start with a newline, to make sure
818 there are kept outside the narrowed region."
819 :group 'org-edit-structure
820 :type '(repeat
821 (list
822 (regexp :tag "begin regexp")
823 (regexp :tag "end regexp")
824 (choice :tag "language"
825 (string :tag "specify")
826 (integer :tag "from match group")
827 (const :tag "from `lang' element")
828 (const :tag "from `style' element")))))
830 (defcustom org-coderef-label-format "(ref:%s)"
831 "The default coderef format.
832 This format string will be used to search for coderef labels in literal
833 examples (EXAMPLE and SRC blocks). The format can be overwritten
834 an individual literal example with the -f option, like
836 #+BEGIN_SRC pascal +n -r -l \"((%s))\"
838 #+END_SRC
840 If you want to use this for HTML export, make sure that the format does
841 not introduce special font-locking, and avoid the HTML special
842 characters `<', `>', and `&'. The reason for this restriction is that
843 the labels are searched for only after htmlize has done its job."
844 :group 'org-edit-structure ; FIXME this is not in the right group
845 :type 'string)
847 (defcustom org-edit-fixed-width-region-mode 'artist-mode
848 "The mode that should be used to edit fixed-width regions.
849 These are the regions where each line starts with a colon."
850 :group 'org-edit-structure
851 :type '(choice
852 (const artist-mode)
853 (const picture-mode)
854 (const fundamental-mode)
855 (function :tag "Other (specify)")))
857 (defcustom org-goto-auto-isearch t
858 "Non-nil means, typing characters in org-goto starts incremental search."
859 :group 'org-edit-structure
860 :type 'boolean)
862 (defgroup org-sparse-trees nil
863 "Options concerning sparse trees in Org-mode."
864 :tag "Org Sparse Trees"
865 :group 'org-structure)
867 (defcustom org-highlight-sparse-tree-matches t
868 "Non-nil means, highlight all matches that define a sparse tree.
869 The highlights will automatically disappear the next time the buffer is
870 changed by an edit command."
871 :group 'org-sparse-trees
872 :type 'boolean)
874 (defcustom org-remove-highlights-with-change t
875 "Non-nil means, any change to the buffer will remove temporary highlights.
876 Such highlights are created by `org-occur' and `org-clock-display'.
877 When nil, `C-c C-c needs to be used to get rid of the highlights.
878 The highlights created by `org-preview-latex-fragment' always need
879 `C-c C-c' to be removed."
880 :group 'org-sparse-trees
881 :group 'org-time
882 :type 'boolean)
885 (defcustom org-occur-hook '(org-first-headline-recenter)
886 "Hook that is run after `org-occur' has constructed a sparse tree.
887 This can be used to recenter the window to show as much of the structure
888 as possible."
889 :group 'org-sparse-trees
890 :type 'hook)
892 (defgroup org-imenu-and-speedbar nil
893 "Options concerning imenu and speedbar in Org-mode."
894 :tag "Org Imenu and Speedbar"
895 :group 'org-structure)
897 (defcustom org-imenu-depth 2
898 "The maximum level for Imenu access to Org-mode headlines.
899 This also applied for speedbar access."
900 :group 'org-imenu-and-speedbar
901 :type 'integer)
903 (defgroup org-table nil
904 "Options concerning tables in Org-mode."
905 :tag "Org Table"
906 :group 'org)
908 (defcustom org-enable-table-editor 'optimized
909 "Non-nil means, lines starting with \"|\" are handled by the table editor.
910 When nil, such lines will be treated like ordinary lines.
912 When equal to the symbol `optimized', the table editor will be optimized to
913 do the following:
914 - Automatic overwrite mode in front of whitespace in table fields.
915 This makes the structure of the table stay in tact as long as the edited
916 field does not exceed the column width.
917 - Minimize the number of realigns. Normally, the table is aligned each time
918 TAB or RET are pressed to move to another field. With optimization this
919 happens only if changes to a field might have changed the column width.
920 Optimization requires replacing the functions `self-insert-command',
921 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
922 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
923 very good at guessing when a re-align will be necessary, but you can always
924 force one with \\[org-ctrl-c-ctrl-c].
926 If you would like to use the optimized version in Org-mode, but the
927 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
929 This variable can be used to turn on and off the table editor during a session,
930 but in order to toggle optimization, a restart is required.
932 See also the variable `org-table-auto-blank-field'."
933 :group 'org-table
934 :type '(choice
935 (const :tag "off" nil)
936 (const :tag "on" t)
937 (const :tag "on, optimized" optimized)))
939 (defcustom org-self-insert-cluster-for-undo t
940 "Non-nil means cluster self-insert commands for undo when possible.
941 If this is set, then, like in the Emacs command loop, 20 consequtive
942 characters will be undone together.
943 This is configurable, because there is some impact on typing performance."
944 :group 'org-table
945 :type 'boolean)
947 (defcustom org-table-tab-recognizes-table.el t
948 "Non-nil means, TAB will automatically notice a table.el table.
949 When it sees such a table, it moves point into it and - if necessary -
950 calls `table-recognize-table'."
951 :group 'org-table-editing
952 :type 'boolean)
954 (defgroup org-link nil
955 "Options concerning links in Org-mode."
956 :tag "Org Link"
957 :group 'org)
959 (defvar org-link-abbrev-alist-local nil
960 "Buffer-local version of `org-link-abbrev-alist', which see.
961 The value of this is taken from the #+LINK lines.")
962 (make-variable-buffer-local 'org-link-abbrev-alist-local)
964 (defcustom org-link-abbrev-alist nil
965 "Alist of link abbreviations.
966 The car of each element is a string, to be replaced at the start of a link.
967 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
968 links in Org-mode buffers can have an optional tag after a double colon, e.g.
970 [[linkkey:tag][description]]
972 The 'linkkey' must be a word word, starting with a letter, followed
973 by letters, numbers, '-' or '_'.
975 If REPLACE is a string, the tag will simply be appended to create the link.
976 If the string contains \"%s\", the tag will be inserted there. Alternatively,
977 the placeholder \"%h\" will cause a url-encoded version of the tag to
978 be inserted at that point (see the function `url-hexify-string').
980 REPLACE may also be a function that will be called with the tag as the
981 only argument to create the link, which should be returned as a string.
983 See the manual for examples."
984 :group 'org-link
985 :type '(repeat
986 (cons
987 (string :tag "Protocol")
988 (choice
989 (string :tag "Format")
990 (function)))))
992 (defcustom org-descriptive-links t
993 "Non-nil means, hide link part and only show description of bracket links.
994 Bracket links are like [[link][description]]. This variable sets the initial
995 state in new org-mode buffers. The setting can then be toggled on a
996 per-buffer basis from the Org->Hyperlinks menu."
997 :group 'org-link
998 :type 'boolean)
1000 (defcustom org-link-file-path-type 'adaptive
1001 "How the path name in file links should be stored.
1002 Valid values are:
1004 relative Relative to the current directory, i.e. the directory of the file
1005 into which the link is being inserted.
1006 absolute Absolute path, if possible with ~ for home directory.
1007 noabbrev Absolute path, no abbreviation of home directory.
1008 adaptive Use relative path for files in the current directory and sub-
1009 directories of it. For other files, use an absolute path."
1010 :group 'org-link
1011 :type '(choice
1012 (const relative)
1013 (const absolute)
1014 (const noabbrev)
1015 (const adaptive)))
1017 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1018 "Types of links that should be activated in Org-mode files.
1019 This is a list of symbols, each leading to the activation of a certain link
1020 type. In principle, it does not hurt to turn on most link types - there may
1021 be a small gain when turning off unused link types. The types are:
1023 bracket The recommended [[link][description]] or [[link]] links with hiding.
1024 angular Links in angular brackets that may contain whitespace like
1025 <bbdb:Carsten Dominik>.
1026 plain Plain links in normal text, no whitespace, like http://google.com.
1027 radio Text that is matched by a radio target, see manual for details.
1028 tag Tag settings in a headline (link to tag search).
1029 date Time stamps (link to calendar).
1030 footnote Footnote labels.
1032 Changing this variable requires a restart of Emacs to become effective."
1033 :group 'org-link
1034 :type '(set :greedy t
1035 (const :tag "Double bracket links (new style)" bracket)
1036 (const :tag "Angular bracket links (old style)" angular)
1037 (const :tag "Plain text links" plain)
1038 (const :tag "Radio target matches" radio)
1039 (const :tag "Tags" tag)
1040 (const :tag "Timestamps" date)
1041 (const :tag "Footnotes" footnote)))
1043 (defcustom org-make-link-description-function nil
1044 "Function to use to generate link descriptions from links. If
1045 nil the link location will be used. This function must take two
1046 parameters; the first is the link and the second the description
1047 org-insert-link has generated, and should return the description
1048 to use."
1049 :group 'org-link
1050 :type 'function)
1052 (defgroup org-link-store nil
1053 "Options concerning storing links in Org-mode."
1054 :tag "Org Store Link"
1055 :group 'org-link)
1057 (defcustom org-email-link-description-format "Email %c: %.30s"
1058 "Format of the description part of a link to an email or usenet message.
1059 The following %-escapes will be replaced by corresponding information:
1061 %F full \"From\" field
1062 %f name, taken from \"From\" field, address if no name
1063 %T full \"To\" field
1064 %t first name in \"To\" field, address if no name
1065 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1066 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1067 %s subject
1068 %m message-id.
1070 You may use normal field width specification between the % and the letter.
1071 This is for example useful to limit the length of the subject.
1073 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1074 :group 'org-link-store
1075 :type 'string)
1077 (defcustom org-from-is-user-regexp
1078 (let (r1 r2)
1079 (when (and user-mail-address (not (string= user-mail-address "")))
1080 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1081 (when (and user-full-name (not (string= user-full-name "")))
1082 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1083 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1084 "Regexp matched against the \"From:\" header of an email or usenet message.
1085 It should match if the message is from the user him/herself."
1086 :group 'org-link-store
1087 :type 'regexp)
1089 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1090 "Non-nil means, storing a link to an Org file will use entry IDs.
1092 Note that before this variable is even considered, org-id must be loaded,
1093 to please customize `org-modules' and turn it on.
1095 The variable can have the following values:
1097 t Create an ID if needed to make a link to the current entry.
1099 create-if-interactive
1100 If `org-store-link' is called directly (interactively, as a user
1101 command), do create an ID to support the link. But when doing the
1102 job for remember, only use the ID if it already exists. The
1103 purpose of this setting is to avoid proliferation of unwanted
1104 IDs, just because you happen to be in an Org file when you
1105 call `org-remember' that automatically and preemptively
1106 creates a link. If you do want to get an ID link in a remember
1107 template to an entry not having an ID, create it first by
1108 explicitly creating a link to it, using `C-c C-l' first.
1110 use-existing
1111 Use existing ID, do not create one.
1113 nil Never use an ID to make a link, instead link using a text search for
1114 the headline text."
1115 :group 'org-link-store
1116 :type '(choice
1117 (const :tag "Create ID to make link" t)
1118 (const :tag "Create if storing link interactively"
1119 create-if-interactive)
1120 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1121 create-if-interactive-and-no-custom-id)
1122 (const :tag "Only use existing" use-existing)
1123 (const :tag "Do not use ID to create link" nil)))
1125 (defcustom org-context-in-file-links t
1126 "Non-nil means, file links from `org-store-link' contain context.
1127 A search string will be added to the file name with :: as separator and
1128 used to find the context when the link is activated by the command
1129 `org-open-at-point'.
1130 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1131 negates this setting for the duration of the command."
1132 :group 'org-link-store
1133 :type 'boolean)
1135 (defcustom org-keep-stored-link-after-insertion nil
1136 "Non-nil means, keep link in list for entire session.
1138 The command `org-store-link' adds a link pointing to the current
1139 location to an internal list. These links accumulate during a session.
1140 The command `org-insert-link' can be used to insert links into any
1141 Org-mode file (offering completion for all stored links). When this
1142 option is nil, every link which has been inserted once using \\[org-insert-link]
1143 will be removed from the list, to make completing the unused links
1144 more efficient."
1145 :group 'org-link-store
1146 :type 'boolean)
1148 (defgroup org-link-follow nil
1149 "Options concerning following links in Org-mode."
1150 :tag "Org Follow Link"
1151 :group 'org-link)
1153 (defcustom org-link-translation-function nil
1154 "Function to translate links with different syntax to Org syntax.
1155 This can be used to translate links created for example by the Planner
1156 or emacs-wiki packages to Org syntax.
1157 The function must accept two parameters, a TYPE containing the link
1158 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1159 which is everything after the link protocol. It should return a cons
1160 with possibly modified values of type and path.
1161 Org contains a function for this, so if you set this variable to
1162 `org-translate-link-from-planner', you should be able follow many
1163 links created by planner."
1164 :group 'org-link-follow
1165 :type 'function)
1167 (defcustom org-follow-link-hook nil
1168 "Hook that is run after a link has been followed."
1169 :group 'org-link-follow
1170 :type 'hook)
1172 (defcustom org-tab-follows-link nil
1173 "Non-nil means, on links TAB will follow the link.
1174 Needs to be set before org.el is loaded.
1175 This really should not be used, it does not make sense, and the
1176 implementation is bad."
1177 :group 'org-link-follow
1178 :type 'boolean)
1180 (defcustom org-return-follows-link nil
1181 "Non-nil means, on links RET will follow the link.
1182 Needs to be set before org.el is loaded."
1183 :group 'org-link-follow
1184 :type 'boolean)
1186 (defcustom org-mouse-1-follows-link
1187 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1188 "Non-nil means, mouse-1 on a link will follow the link.
1189 A longer mouse click will still set point. Does not work on XEmacs.
1190 Needs to be set before org.el is loaded."
1191 :group 'org-link-follow
1192 :type 'boolean)
1194 (defcustom org-mark-ring-length 4
1195 "Number of different positions to be recorded in the ring
1196 Changing this requires a restart of Emacs to work correctly."
1197 :group 'org-link-follow
1198 :type 'integer)
1200 (defcustom org-link-frame-setup
1201 '((vm . vm-visit-folder-other-frame)
1202 (gnus . gnus-other-frame)
1203 (file . find-file-other-window))
1204 "Setup the frame configuration for following links.
1205 When following a link with Emacs, it may often be useful to display
1206 this link in another window or frame. This variable can be used to
1207 set this up for the different types of links.
1208 For VM, use any of
1209 `vm-visit-folder'
1210 `vm-visit-folder-other-frame'
1211 For Gnus, use any of
1212 `gnus'
1213 `gnus-other-frame'
1214 `org-gnus-no-new-news'
1215 For FILE, use any of
1216 `find-file'
1217 `find-file-other-window'
1218 `find-file-other-frame'
1219 For the calendar, use the variable `calendar-setup'.
1220 For BBDB, it is currently only possible to display the matches in
1221 another window."
1222 :group 'org-link-follow
1223 :type '(list
1224 (cons (const vm)
1225 (choice
1226 (const vm-visit-folder)
1227 (const vm-visit-folder-other-window)
1228 (const vm-visit-folder-other-frame)))
1229 (cons (const gnus)
1230 (choice
1231 (const gnus)
1232 (const gnus-other-frame)
1233 (const org-gnus-no-new-news)))
1234 (cons (const file)
1235 (choice
1236 (const find-file)
1237 (const find-file-other-window)
1238 (const find-file-other-frame)))))
1240 (defcustom org-display-internal-link-with-indirect-buffer nil
1241 "Non-nil means, use indirect buffer to display infile links.
1242 Activating internal links (from one location in a file to another location
1243 in the same file) normally just jumps to the location. When the link is
1244 activated with a C-u prefix (or with mouse-3), the link is displayed in
1245 another window. When this option is set, the other window actually displays
1246 an indirect buffer clone of the current buffer, to avoid any visibility
1247 changes to the current buffer."
1248 :group 'org-link-follow
1249 :type 'boolean)
1251 (defcustom org-open-non-existing-files nil
1252 "Non-nil means, `org-open-file' will open non-existing files.
1253 When nil, an error will be generated."
1254 :group 'org-link-follow
1255 :type 'boolean)
1257 (defcustom org-open-directory-means-index-dot-org nil
1258 "Non-nil means, a link to a directory really means to index.org.
1259 When nil, following a directory link will run dired or open a finder/explorer
1260 window on that directory."
1261 :group 'org-link-follow
1262 :type 'boolean)
1264 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1265 "Function and arguments to call for following mailto links.
1266 This is a list with the first element being a lisp function, and the
1267 remaining elements being arguments to the function. In string arguments,
1268 %a will be replaced by the address, and %s will be replaced by the subject
1269 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1270 :group 'org-link-follow
1271 :type '(choice
1272 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1273 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1274 (const :tag "message-mail" (message-mail "%a" "%s"))
1275 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1277 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1278 "Non-nil means, ask for confirmation before executing shell links.
1279 Shell links can be dangerous: just think about a link
1281 [[shell:rm -rf ~/*][Google Search]]
1283 This link would show up in your Org-mode document as \"Google Search\",
1284 but really it would remove your entire home directory.
1285 Therefore we advise against setting this variable to nil.
1286 Just change it to `y-or-n-p' if you want to confirm with a
1287 single keystroke rather than having to type \"yes\"."
1288 :group 'org-link-follow
1289 :type '(choice
1290 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1291 (const :tag "with y-or-n (faster)" y-or-n-p)
1292 (const :tag "no confirmation (dangerous)" nil)))
1294 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1295 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1296 Elisp links can be dangerous: just think about a link
1298 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1300 This link would show up in your Org-mode document as \"Google Search\",
1301 but really it would remove your entire home directory.
1302 Therefore we advise against setting this variable to nil.
1303 Just change it to `y-or-n-p' if you want to confirm with a
1304 single keystroke rather than having to type \"yes\"."
1305 :group 'org-link-follow
1306 :type '(choice
1307 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1308 (const :tag "with y-or-n (faster)" y-or-n-p)
1309 (const :tag "no confirmation (dangerous)" nil)))
1311 (defconst org-file-apps-defaults-gnu
1312 '((remote . emacs)
1313 (system . mailcap)
1314 (t . mailcap))
1315 "Default file applications on a UNIX or GNU/Linux system.
1316 See `org-file-apps'.")
1318 (defconst org-file-apps-defaults-macosx
1319 '((remote . emacs)
1320 (t . "open %s")
1321 (system . "open %s")
1322 ("ps.gz" . "gv %s")
1323 ("eps.gz" . "gv %s")
1324 ("dvi" . "xdvi %s")
1325 ("fig" . "xfig %s"))
1326 "Default file applications on a MacOS X system.
1327 The system \"open\" is known as a default, but we use X11 applications
1328 for some files for which the OS does not have a good default.
1329 See `org-file-apps'.")
1331 (defconst org-file-apps-defaults-windowsnt
1332 (list
1333 '(remote . emacs)
1334 (cons t
1335 (list (if (featurep 'xemacs)
1336 'mswindows-shell-execute
1337 'w32-shell-execute)
1338 "open" 'file))
1339 (cons 'system
1340 (list (if (featurep 'xemacs)
1341 'mswindows-shell-execute
1342 'w32-shell-execute)
1343 "open" 'file)))
1344 "Default file applications on a Windows NT system.
1345 The system \"open\" is used for most files.
1346 See `org-file-apps'.")
1348 (defcustom org-file-apps
1350 (auto-mode . emacs)
1351 ("\\.x?html?\\'" . default)
1352 ("\\.pdf\\'" . default)
1354 "External applications for opening `file:path' items in a document.
1355 Org-mode uses system defaults for different file types, but
1356 you can use this variable to set the application for a given file
1357 extension. The entries in this list are cons cells where the car identifies
1358 files and the cdr the corresponding command. Possible values for the
1359 file identifier are
1360 \"regex\" Regular expression matched against the file name. For backward
1361 compatibility, this can also be a string with only alphanumeric
1362 characters, which is then interpreted as an extension.
1363 `directory' Matches a directory
1364 `remote' Matches a remote file, accessible through tramp or efs.
1365 Remote files most likely should be visited through Emacs
1366 because external applications cannot handle such paths.
1367 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1368 so all files Emacs knows how to handle. Using this with
1369 command `emacs' will open most files in Emacs. Beware that this
1370 will also open html files inside Emacs, unless you add
1371 (\"html\" . default) to the list as well.
1372 t Default for files not matched by any of the other options.
1373 `system' The system command to open files, like `open' on Windows
1374 and Mac OS X, and mailcap under GNU/Linux. This is the command
1375 that will be selected if you call `C-c C-o' with a double
1376 `C-u C-u' prefix.
1378 Possible values for the command are:
1379 `emacs' The file will be visited by the current Emacs process.
1380 `default' Use the default application for this file type, which is the
1381 association for t in the list, most likely in the system-specific
1382 part.
1383 This can be used to overrule an unwanted setting in the
1384 system-specific variable.
1385 `system' Use the system command for opening files, like \"open\".
1386 This command is specified by the entry whose car is `system'.
1387 Most likely, the system-specific version of this variable
1388 does define this command, but you can overrule/replace it
1389 here.
1390 string A command to be executed by a shell; %s will be replaced
1391 by the path to the file.
1392 sexp A Lisp form which will be evaluated. The file path will
1393 be available in the Lisp variable `file'.
1394 For more examples, see the system specific constants
1395 `org-file-apps-defaults-macosx'
1396 `org-file-apps-defaults-windowsnt'
1397 `org-file-apps-defaults-gnu'."
1398 :group 'org-link-follow
1399 :type '(repeat
1400 (cons (choice :value ""
1401 (string :tag "Extension")
1402 (const :tag "System command to open files" system)
1403 (const :tag "Default for unrecognized files" t)
1404 (const :tag "Remote file" remote)
1405 (const :tag "Links to a directory" directory)
1406 (const :tag "Any files that have Emacs modes"
1407 auto-mode))
1408 (choice :value ""
1409 (const :tag "Visit with Emacs" emacs)
1410 (const :tag "Use default" default)
1411 (const :tag "Use the system command" system)
1412 (string :tag "Command")
1413 (sexp :tag "Lisp form")))))
1415 (defgroup org-refile nil
1416 "Options concerning refiling entries in Org-mode."
1417 :tag "Org Refile"
1418 :group 'org)
1420 (defcustom org-directory "~/org"
1421 "Directory with org files.
1422 This is just a default location to look for Org files. There is no need
1423 at all to put your files into this directory. It is only used in the
1424 following situations:
1426 1. When a remember template specifies a target file that is not an
1427 absolute path. The path will then be interpreted relative to
1428 `org-directory'
1429 2. When a remember note is filed away in an interactive way (when exiting the
1430 note buffer with `C-1 C-c C-c'. The the user is prompted for an org file,
1431 with `org-directory' as the default path."
1432 :group 'org-refile
1433 :group 'org-remember
1434 :type 'directory)
1436 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1437 "Default target for storing notes.
1438 Used by the hooks for remember.el. This can be a string, or nil to mean
1439 the value of `remember-data-file'.
1440 You can set this on a per-template basis with the variable
1441 `org-remember-templates'."
1442 :group 'org-refile
1443 :group 'org-remember
1444 :type '(choice
1445 (const :tag "Default from remember-data-file" nil)
1446 file))
1448 (defcustom org-goto-interface 'outline
1449 "The default interface to be used for `org-goto'.
1450 Allowed values are:
1451 outline The interface shows an outline of the relevant file
1452 and the correct heading is found by moving through
1453 the outline or by searching with incremental search.
1454 outline-path-completion Headlines in the current buffer are offered via
1455 completion. This is the interface also used by
1456 the refile command."
1457 :group 'org-refile
1458 :type '(choice
1459 (const :tag "Outline" outline)
1460 (const :tag "Outline-path-completion" outline-path-completion)))
1462 (defcustom org-goto-max-level 5
1463 "Maximum level to be considered when running org-goto with refile interface."
1464 :group 'org-refile
1465 :type 'integer)
1467 (defcustom org-reverse-note-order nil
1468 "Non-nil means, store new notes at the beginning of a file or entry.
1469 When nil, new notes will be filed to the end of a file or entry.
1470 This can also be a list with cons cells of regular expressions that
1471 are matched against file names, and values."
1472 :group 'org-remember
1473 :group 'org-refile
1474 :type '(choice
1475 (const :tag "Reverse always" t)
1476 (const :tag "Reverse never" nil)
1477 (repeat :tag "By file name regexp"
1478 (cons regexp boolean))))
1480 (defcustom org-refile-targets nil
1481 "Targets for refiling entries with \\[org-refile].
1482 This is list of cons cells. Each cell contains:
1483 - a specification of the files to be considered, either a list of files,
1484 or a symbol whose function or variable value will be used to retrieve
1485 a file name or a list of file names. If you use `org-agenda-files' for
1486 that, all agenda files will be scanned for targets. Nil means, consider
1487 headings in the current buffer.
1488 - A specification of how to find candidate refile targets. This may be
1489 any of:
1490 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1491 This tag has to be present in all target headlines, inheritance will
1492 not be considered.
1493 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1494 todo keyword.
1495 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1496 headlines that are refiling targets.
1497 - a cons cell (:level . N). Any headline of level N is considered a target.
1498 Note that, when `org-odd-levels-only' is set, level corresponds to
1499 order in hierarchy, not to the number of stars.
1500 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1501 Note that, when `org-odd-levels-only' is set, level corresponds to
1502 order in hierarchy, not to the number of stars.
1504 You can set the variable `org-refile-target-verify-function' to a function
1505 to verify each headline found by the simple critery above.
1507 When this variable is nil, all top-level headlines in the current buffer
1508 are used, equivalent to the value `((nil . (:level . 1))'."
1509 :group 'org-refile
1510 :type '(repeat
1511 (cons
1512 (choice :value org-agenda-files
1513 (const :tag "All agenda files" org-agenda-files)
1514 (const :tag "Current buffer" nil)
1515 (function) (variable) (file))
1516 (choice :tag "Identify target headline by"
1517 (cons :tag "Specific tag" (const :value :tag) (string))
1518 (cons :tag "TODO keyword" (const :value :todo) (string))
1519 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1520 (cons :tag "Level number" (const :value :level) (integer))
1521 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1523 (defcustom org-refile-target-verify-function nil
1524 "Function to verify if the headline at point should be a refile target.
1525 The function will be called without arguments, with point at the
1526 beginning of the headline. It should return t and leave point
1527 where it is if the headline is a valid target for refiling.
1529 If the target should not be selected, the function must return nil.
1530 In addition to this, it may move point to a place from where the search
1531 should be continued. For example, the function may decide that the entire
1532 subtree of the current entry should be excluded and move point to the end
1533 of the subtree."
1534 :group 'org-refile
1535 :type 'function)
1537 (defcustom org-refile-use-outline-path nil
1538 "Non-nil means, provide refile targets as paths.
1539 So a level 3 headline will be available as level1/level2/level3.
1541 When the value is `file', also include the file name (without directory)
1542 into the path. In this case, you can also stop the completion after
1543 the file name, to get entries inserted as top level in the file.
1545 When `full-file-path', include the full file path."
1546 :group 'org-refile
1547 :type '(choice
1548 (const :tag "Not" nil)
1549 (const :tag "Yes" t)
1550 (const :tag "Start with file name" file)
1551 (const :tag "Start with full file path" full-file-path)))
1553 (defcustom org-outline-path-complete-in-steps t
1554 "Non-nil means, complete the outline path in hierarchical steps.
1555 When Org-mode uses the refile interface to select an outline path
1556 \(see variable `org-refile-use-outline-path'), the completion of
1557 the path can be done is a single go, or if can be done in steps down
1558 the headline hierarchy. Going in steps is probably the best if you
1559 do not use a special completion package like `ido' or `icicles'.
1560 However, when using these packages, going in one step can be very
1561 fast, while still showing the whole path to the entry."
1562 :group 'org-refile
1563 :type 'boolean)
1565 (defcustom org-refile-allow-creating-parent-nodes nil
1566 "Non-nil means, allow to create new nodes as refile targets.
1567 New nodes are then created by adding \"/new node name\" to the completion
1568 of an existing node. When the value of this variable is `confirm',
1569 new node creation must be confirmed by the user (recommended)
1570 When nil, the completion must match an existing entry.
1572 Note that, if the new heading is not seen by the criteria
1573 listed in `org-refile-targets', multiple instances of the same
1574 heading would be created by trying again to file under the new
1575 heading."
1576 :group 'org-refile
1577 :type '(choice
1578 (const :tag "Never" nil)
1579 (const :tag "Always" t)
1580 (const :tag "Prompt for confirmation" confirm)))
1582 (defgroup org-todo nil
1583 "Options concerning TODO items in Org-mode."
1584 :tag "Org TODO"
1585 :group 'org)
1587 (defgroup org-progress nil
1588 "Options concerning Progress logging in Org-mode."
1589 :tag "Org Progress"
1590 :group 'org-time)
1592 (defvar org-todo-interpretation-widgets
1594 (:tag "Sequence (cycling hits every state)" sequence)
1595 (:tag "Type (cycling directly to DONE)" type))
1596 "The available interpretation symbols for customizing
1597 `org-todo-keywords'.
1598 Interested libraries should add to this list.")
1600 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1601 "List of TODO entry keyword sequences and their interpretation.
1602 \\<org-mode-map>This is a list of sequences.
1604 Each sequence starts with a symbol, either `sequence' or `type',
1605 indicating if the keywords should be interpreted as a sequence of
1606 action steps, or as different types of TODO items. The first
1607 keywords are states requiring action - these states will select a headline
1608 for inclusion into the global TODO list Org-mode produces. If one of
1609 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1610 signify that no further action is necessary. If \"|\" is not found,
1611 the last keyword is treated as the only DONE state of the sequence.
1613 The command \\[org-todo] cycles an entry through these states, and one
1614 additional state where no keyword is present. For details about this
1615 cycling, see the manual.
1617 TODO keywords and interpretation can also be set on a per-file basis with
1618 the special #+SEQ_TODO and #+TYP_TODO lines.
1620 Each keyword can optionally specify a character for fast state selection
1621 \(in combination with the variable `org-use-fast-todo-selection')
1622 and specifiers for state change logging, using the same syntax
1623 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1624 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1625 indicates to record a time stamp each time this state is selected.
1627 Each keyword may also specify if a timestamp or a note should be
1628 recorded when entering or leaving the state, by adding additional
1629 characters in the parenthesis after the keyword. This looks like this:
1630 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1631 record only the time of the state change. With X and Y being either
1632 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1633 Y when leaving the state if and only if the *target* state does not
1634 define X. You may omit any of the fast-selection key or X or /Y,
1635 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1637 For backward compatibility, this variable may also be just a list
1638 of keywords - in this case the interpretation (sequence or type) will be
1639 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1640 :group 'org-todo
1641 :group 'org-keywords
1642 :type '(choice
1643 (repeat :tag "Old syntax, just keywords"
1644 (string :tag "Keyword"))
1645 (repeat :tag "New syntax"
1646 (cons
1647 (choice
1648 :tag "Interpretation"
1649 ;;Quick and dirty way to see
1650 ;;`org-todo-interpretations'. This takes the
1651 ;;place of item arguments
1652 :convert-widget
1653 (lambda (widget)
1654 (widget-put widget
1655 :args (mapcar
1656 #'(lambda (x)
1657 (widget-convert
1658 (cons 'const x)))
1659 org-todo-interpretation-widgets))
1660 widget))
1661 (repeat
1662 (string :tag "Keyword"))))))
1664 (defvar org-todo-keywords-1 nil
1665 "All TODO and DONE keywords active in a buffer.")
1666 (make-variable-buffer-local 'org-todo-keywords-1)
1667 (defvar org-todo-keywords-for-agenda nil)
1668 (defvar org-done-keywords-for-agenda nil)
1669 (defvar org-todo-keyword-alist-for-agenda nil)
1670 (defvar org-tag-alist-for-agenda nil)
1671 (defvar org-agenda-contributing-files nil)
1672 (defvar org-not-done-keywords nil)
1673 (make-variable-buffer-local 'org-not-done-keywords)
1674 (defvar org-done-keywords nil)
1675 (make-variable-buffer-local 'org-done-keywords)
1676 (defvar org-todo-heads nil)
1677 (make-variable-buffer-local 'org-todo-heads)
1678 (defvar org-todo-sets nil)
1679 (make-variable-buffer-local 'org-todo-sets)
1680 (defvar org-todo-log-states nil)
1681 (make-variable-buffer-local 'org-todo-log-states)
1682 (defvar org-todo-kwd-alist nil)
1683 (make-variable-buffer-local 'org-todo-kwd-alist)
1684 (defvar org-todo-key-alist nil)
1685 (make-variable-buffer-local 'org-todo-key-alist)
1686 (defvar org-todo-key-trigger nil)
1687 (make-variable-buffer-local 'org-todo-key-trigger)
1689 (defcustom org-todo-interpretation 'sequence
1690 "Controls how TODO keywords are interpreted.
1691 This variable is in principle obsolete and is only used for
1692 backward compatibility, if the interpretation of todo keywords is
1693 not given already in `org-todo-keywords'. See that variable for
1694 more information."
1695 :group 'org-todo
1696 :group 'org-keywords
1697 :type '(choice (const sequence)
1698 (const type)))
1700 (defcustom org-use-fast-todo-selection t
1701 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1702 This variable describes if and under what circumstances the cycling
1703 mechanism for TODO keywords will be replaced by a single-key, direct
1704 selection scheme.
1706 When nil, fast selection is never used.
1708 When the symbol `prefix', it will be used when `org-todo' is called with
1709 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1710 in an agenda buffer.
1712 When t, fast selection is used by default. In this case, the prefix
1713 argument forces cycling instead.
1715 In all cases, the special interface is only used if access keys have actually
1716 been assigned by the user, i.e. if keywords in the configuration are followed
1717 by a letter in parenthesis, like TODO(t)."
1718 :group 'org-todo
1719 :type '(choice
1720 (const :tag "Never" nil)
1721 (const :tag "By default" t)
1722 (const :tag "Only with C-u C-c C-t" prefix)))
1724 (defcustom org-provide-todo-statistics t
1725 "Non-nil means, update todo statistics after insert and toggle.
1726 When this is set, todo statistics is updated in the parent of the current
1727 entry each time a todo state is changed."
1728 :group 'org-todo
1729 :type 'boolean)
1731 (defcustom org-after-todo-state-change-hook nil
1732 "Hook which is run after the state of a TODO item was changed.
1733 The new state (a string with a TODO keyword, or nil) is available in the
1734 Lisp variable `state'."
1735 :group 'org-todo
1736 :type 'hook)
1738 (defvar org-blocker-hook nil
1739 "Hook for functions that are allowed to block a state change.
1741 Each function gets as its single argument a property list, see
1742 `org-trigger-hook' for more information about this list.
1744 If any of the functions in this hook returns nil, the state change
1745 is blocked.")
1747 (defvar org-trigger-hook nil
1748 "Hook for functions that are triggered by a state change.
1750 Each function gets as its single argument a property list with at least
1751 the following elements:
1753 (:type type-of-change :position pos-at-entry-start
1754 :from old-state :to new-state)
1756 Depending on the type, more properties may be present.
1758 This mechanism is currently implemented for:
1760 TODO state changes
1761 ------------------
1762 :type todo-state-change
1763 :from previous state (keyword as a string), or nil, or a symbol
1764 'todo' or 'done', to indicate the general type of state.
1765 :to new state, like in :from")
1767 (defcustom org-enforce-todo-dependencies nil
1768 "Non-nil means, undone TODO entries will block switching the parent to DONE.
1769 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
1770 be blocked if any prior sibling is not yet done.
1771 Finally, if the parent is blocked because of ordered siblings of its own,
1772 the child will also be blocked.
1773 This variable needs to be set before org.el is loaded, and you need to
1774 restart Emacs after a change to make the change effective. The only way
1775 to change is while Emacs is running is through the customize interface."
1776 :set (lambda (var val)
1777 (set var val)
1778 (if val
1779 (add-hook 'org-blocker-hook
1780 'org-block-todo-from-children-or-siblings-or-parent)
1781 (remove-hook 'org-blocker-hook
1782 'org-block-todo-from-children-or-siblings-or-parent)))
1783 :group 'org-todo
1784 :type 'boolean)
1786 (defcustom org-enforce-todo-checkbox-dependencies nil
1787 "Non-nil means, unchecked boxes will block switching the parent to DONE.
1788 When this is nil, checkboxes have no influence on switching TODO states.
1789 When non-nil, you first need to check off all check boxes before the TODO
1790 entry can be switched to DONE.
1791 This variable needs to be set before org.el is loaded, and you need to
1792 restart Emacs after a change to make the change effective. The only way
1793 to change is while Emacs is running is through the customize interface."
1794 :set (lambda (var val)
1795 (set var val)
1796 (if val
1797 (add-hook 'org-blocker-hook
1798 'org-block-todo-from-checkboxes)
1799 (remove-hook 'org-blocker-hook
1800 'org-block-todo-from-checkboxes)))
1801 :group 'org-todo
1802 :type 'boolean)
1804 (defcustom org-todo-state-tags-triggers nil
1805 "Tag changes that should be triggered by TODO state changes.
1806 This is a list. Each entry is
1808 (state-change (tag . flag) .......)
1810 State-change can be a string with a state, and empty string to indicate the
1811 state that has no TODO keyword, or it can be one of the symbols `todo'
1812 or `done', meaning any not-done or done state, respectively."
1813 :group 'org-todo
1814 :group 'org-tags
1815 :type '(repeat
1816 (cons (choice :tag "When changing to"
1817 (const :tag "Not-done state" todo)
1818 (const :tag "Done state" done)
1819 (string :tag "State"))
1820 (repeat
1821 (cons :tag "Tag action"
1822 (string :tag "Tag")
1823 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1825 (defcustom org-log-done nil
1826 "Information to record when a task moves to the DONE state.
1828 Possible values are:
1830 nil Don't add anything, just change the keyword
1831 time Add a time stamp to the task
1832 note Prompt a closing note and add it with template `org-log-note-headings'
1834 This option can also be set with on a per-file-basis with
1836 #+STARTUP: nologdone
1837 #+STARTUP: logdone
1838 #+STARTUP: lognotedone
1840 You can have local logging settings for a subtree by setting the LOGGING
1841 property to one or more of these keywords."
1842 :group 'org-todo
1843 :group 'org-progress
1844 :type '(choice
1845 (const :tag "No logging" nil)
1846 (const :tag "Record CLOSED timestamp" time)
1847 (const :tag "Record CLOSED timestamp with closing note." note)))
1849 ;; Normalize old uses of org-log-done.
1850 (cond
1851 ((eq org-log-done t) (setq org-log-done 'time))
1852 ((and (listp org-log-done) (memq 'done org-log-done))
1853 (setq org-log-done 'note)))
1855 (defcustom org-log-note-clock-out nil
1856 "Non-nil means, record a note when clocking out of an item.
1857 This can also be configured on a per-file basis by adding one of
1858 the following lines anywhere in the buffer:
1860 #+STARTUP: lognoteclock-out
1861 #+STARTUP: nolognoteclock-out"
1862 :group 'org-todo
1863 :group 'org-progress
1864 :type 'boolean)
1866 (defcustom org-log-done-with-time t
1867 "Non-nil means, the CLOSED time stamp will contain date and time.
1868 When nil, only the date will be recorded."
1869 :group 'org-progress
1870 :type 'boolean)
1872 (defcustom org-log-note-headings
1873 '((done . "CLOSING NOTE %t")
1874 (state . "State %-12s from %-12S %t")
1875 (note . "Note taken on %t")
1876 (clock-out . ""))
1877 "Headings for notes added to entries.
1878 The value is an alist, with the car being a symbol indicating the note
1879 context, and the cdr is the heading to be used. The heading may also be the
1880 empty string.
1881 %t in the heading will be replaced by a time stamp.
1882 %s will be replaced by the new TODO state, in double quotes.
1883 %S will be replaced by the old TODO state, in double quotes.
1884 %u will be replaced by the user name.
1885 %U will be replaced by the full user name."
1886 :group 'org-todo
1887 :group 'org-progress
1888 :type '(list :greedy t
1889 (cons (const :tag "Heading when closing an item" done) string)
1890 (cons (const :tag
1891 "Heading when changing todo state (todo sequence only)"
1892 state) string)
1893 (cons (const :tag "Heading when just taking a note" note) string)
1894 (cons (const :tag "Heading when clocking out" clock-out) string)))
1896 (unless (assq 'note org-log-note-headings)
1897 (push '(note . "%t") org-log-note-headings))
1899 (defcustom org-log-into-drawer nil
1900 "Non-nil means, insert state change notes and time stamps into a drawer.
1901 When nil, state changes notes will be inserted after the headline and
1902 any scheduling and clock lines, but not inside a drawer.
1904 The value of this variable should be the name of the drawer to use.
1905 LOGBOOK is proposed at the default drawer for this purpose, you can
1906 also set this to a string to define the drawer of your choice.
1908 A value of t is also allowed, representing \"LOGBOOK\".
1910 If this variable is set, `org-log-state-notes-insert-after-drawers'
1911 will be ignored."
1912 :group 'org-todo
1913 :group 'org-progress
1914 :type '(choice
1915 (const :tag "Not into a drawer" nil)
1916 (const :tag "LOGBOOK" t)
1917 (string :tag "Other")))
1919 (if (fboundp 'defvaralias)
1920 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
1922 (defcustom org-log-state-notes-insert-after-drawers nil
1923 "Non-nil means, insert state change notes after any drawers in entry.
1924 Only the drawers that *immediately* follow the headline and the
1925 deadline/scheduled line are skipped.
1926 When nil, insert notes right after the heading and perhaps the line
1927 with deadline/scheduling if present.
1929 This variable will have no effect if `org-log-into-drawer' is
1930 set."
1931 :group 'org-todo
1932 :group 'org-progress
1933 :type 'boolean)
1935 (defcustom org-log-states-order-reversed t
1936 "Non-nil means, the latest state change note will be directly after heading.
1937 When nil, the notes will be orderer according to time."
1938 :group 'org-todo
1939 :group 'org-progress
1940 :type 'boolean)
1942 (defcustom org-log-repeat 'time
1943 "Non-nil means, record moving through the DONE state when triggering repeat.
1944 An auto-repeating tasks is immediately switched back to TODO when marked
1945 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1946 the TODO keyword definition, or recording a closing note by setting
1947 `org-log-done', there will be no record of the task moving through DONE.
1948 This variable forces taking a note anyway. Possible values are:
1950 nil Don't force a record
1951 time Record a time stamp
1952 note Record a note
1954 This option can also be set with on a per-file-basis with
1956 #+STARTUP: logrepeat
1957 #+STARTUP: lognoterepeat
1958 #+STARTUP: nologrepeat
1960 You can have local logging settings for a subtree by setting the LOGGING
1961 property to one or more of these keywords."
1962 :group 'org-todo
1963 :group 'org-progress
1964 :type '(choice
1965 (const :tag "Don't force a record" nil)
1966 (const :tag "Force recording the DONE state" time)
1967 (const :tag "Force recording a note with the DONE state" note)))
1970 (defgroup org-priorities nil
1971 "Priorities in Org-mode."
1972 :tag "Org Priorities"
1973 :group 'org-todo)
1975 (defcustom org-highest-priority ?A
1976 "The highest priority of TODO items. A character like ?A, ?B etc.
1977 Must have a smaller ASCII number than `org-lowest-priority'."
1978 :group 'org-priorities
1979 :type 'character)
1981 (defcustom org-lowest-priority ?C
1982 "The lowest priority of TODO items. A character like ?A, ?B etc.
1983 Must have a larger ASCII number than `org-highest-priority'."
1984 :group 'org-priorities
1985 :type 'character)
1987 (defcustom org-default-priority ?B
1988 "The default priority of TODO items.
1989 This is the priority an item get if no explicit priority is given."
1990 :group 'org-priorities
1991 :type 'character)
1993 (defcustom org-priority-start-cycle-with-default t
1994 "Non-nil means, start with default priority when starting to cycle.
1995 When this is nil, the first step in the cycle will be (depending on the
1996 command used) one higher or lower that the default priority."
1997 :group 'org-priorities
1998 :type 'boolean)
2000 (defgroup org-time nil
2001 "Options concerning time stamps and deadlines in Org-mode."
2002 :tag "Org Time"
2003 :group 'org)
2005 (defcustom org-insert-labeled-timestamps-at-point nil
2006 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
2007 When nil, these labeled time stamps are forces into the second line of an
2008 entry, just after the headline. When scheduling from the global TODO list,
2009 the time stamp will always be forced into the second line."
2010 :group 'org-time
2011 :type 'boolean)
2013 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2014 "Formats for `format-time-string' which are used for time stamps.
2015 It is not recommended to change this constant.")
2017 (defcustom org-time-stamp-rounding-minutes '(0 5)
2018 "Number of minutes to round time stamps to.
2019 These are two values, the first applies when first creating a time stamp.
2020 The second applies when changing it with the commands `S-up' and `S-down'.
2021 When changing the time stamp, this means that it will change in steps
2022 of N minutes, as given by the second value.
2024 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2025 numbers should be factors of 60, so for example 5, 10, 15.
2027 When this is larger than 1, you can still force an exact time-stamp by using
2028 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
2029 and by using a prefix arg to `S-up/down' to specify the exact number
2030 of minutes to shift."
2031 :group 'org-time
2032 :get '(lambda (var) ; Make sure all entries have 5 elements
2033 (if (integerp (default-value var))
2034 (list (default-value var) 5)
2035 (default-value var)))
2036 :type '(list
2037 (integer :tag "when inserting times")
2038 (integer :tag "when modifying times")))
2040 ;; Normalize old customizations of this variable.
2041 (when (integerp org-time-stamp-rounding-minutes)
2042 (setq org-time-stamp-rounding-minutes
2043 (list org-time-stamp-rounding-minutes
2044 org-time-stamp-rounding-minutes)))
2046 (defcustom org-display-custom-times nil
2047 "Non-nil means, overlay custom formats over all time stamps.
2048 The formats are defined through the variable `org-time-stamp-custom-formats'.
2049 To turn this on on a per-file basis, insert anywhere in the file:
2050 #+STARTUP: customtime"
2051 :group 'org-time
2052 :set 'set-default
2053 :type 'sexp)
2054 (make-variable-buffer-local 'org-display-custom-times)
2056 (defcustom org-time-stamp-custom-formats
2057 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2058 "Custom formats for time stamps. See `format-time-string' for the syntax.
2059 These are overlayed over the default ISO format if the variable
2060 `org-display-custom-times' is set. Time like %H:%M should be at the
2061 end of the second format. The custom formats are also honored by export
2062 commands, if custom time display is turned on at the time of export."
2063 :group 'org-time
2064 :type 'sexp)
2066 (defun org-time-stamp-format (&optional long inactive)
2067 "Get the right format for a time string."
2068 (let ((f (if long (cdr org-time-stamp-formats)
2069 (car org-time-stamp-formats))))
2070 (if inactive
2071 (concat "[" (substring f 1 -1) "]")
2072 f)))
2074 (defcustom org-time-clocksum-format "%d:%02d"
2075 "The format string used when creating CLOCKSUM lines, or when
2076 org-mode generates a time duration."
2077 :group 'org-time
2078 :type 'string)
2080 (defcustom org-deadline-warning-days 14
2081 "No. of days before expiration during which a deadline becomes active.
2082 This variable governs the display in sparse trees and in the agenda.
2083 When 0 or negative, it means use this number (the absolute value of it)
2084 even if a deadline has a different individual lead time specified.
2086 Custom commands can set this variable in the options section."
2087 :group 'org-time
2088 :group 'org-agenda-daily/weekly
2089 :type 'integer)
2091 (defcustom org-read-date-prefer-future t
2092 "Non-nil means, assume future for incomplete date input from user.
2093 This affects the following situations:
2094 1. The user gives a day, but no month.
2095 For example, if today is the 15th, and you enter \"3\", Org-mode will
2096 read this as the third of *next* month. However, if you enter \"17\",
2097 it will be considered as *this* month.
2098 2. The user gives a month but not a year.
2099 For example, if it is april and you enter \"feb 2\", this will be read
2100 as feb 2, *next* year. \"May 5\", however, will be this year.
2102 Currently this does not work for ISO week specifications.
2104 When this option is nil, the current month and year will always be used
2105 as defaults."
2106 :group 'org-time
2107 :type 'boolean)
2109 (defcustom org-read-date-display-live t
2110 "Non-nil means, display current interpretation of date prompt live.
2111 This display will be in an overlay, in the minibuffer."
2112 :group 'org-time
2113 :type 'boolean)
2115 (defcustom org-read-date-popup-calendar t
2116 "Non-nil means, pop up a calendar when prompting for a date.
2117 In the calendar, the date can be selected with mouse-1. However, the
2118 minibuffer will also be active, and you can simply enter the date as well.
2119 When nil, only the minibuffer will be available."
2120 :group 'org-time
2121 :type 'boolean)
2122 (if (fboundp 'defvaralias)
2123 (defvaralias 'org-popup-calendar-for-date-prompt
2124 'org-read-date-popup-calendar))
2126 (defcustom org-read-date-minibuffer-setup-hook nil
2127 "Hook to be used to set up keys for the date/time interface.
2128 Add key definitions to `minibuffer-local-map', which will be a temporary
2129 copy."
2130 :group 'org-time
2131 :type 'hook)
2133 (defcustom org-extend-today-until 0
2134 "The hour when your day really ends. Must be an integer.
2135 This has influence for the following applications:
2136 - When switching the agenda to \"today\". It it is still earlier than
2137 the time given here, the day recognized as TODAY is actually yesterday.
2138 - When a date is read from the user and it is still before the time given
2139 here, the current date and time will be assumed to be yesterday, 23:59.
2140 Also, timestamps inserted in remember templates follow this rule.
2142 IMPORTANT: This is a feature whose implementation is and likely will
2143 remain incomplete. Really, it is only here because past midnight seems to
2144 be the favorite working time of John Wiegley :-)"
2145 :group 'org-time
2146 :type 'integer)
2148 (defcustom org-edit-timestamp-down-means-later nil
2149 "Non-nil means, S-down will increase the time in a time stamp.
2150 When nil, S-up will increase."
2151 :group 'org-time
2152 :type 'boolean)
2154 (defcustom org-calendar-follow-timestamp-change t
2155 "Non-nil means, make the calendar window follow timestamp changes.
2156 When a timestamp is modified and the calendar window is visible, it will be
2157 moved to the new date."
2158 :group 'org-time
2159 :type 'boolean)
2161 (defgroup org-tags nil
2162 "Options concerning tags in Org-mode."
2163 :tag "Org Tags"
2164 :group 'org)
2166 (defcustom org-tag-alist nil
2167 "List of tags allowed in Org-mode files.
2168 When this list is nil, Org-mode will base TAG input on what is already in the
2169 buffer.
2170 The value of this variable is an alist, the car of each entry must be a
2171 keyword as a string, the cdr may be a character that is used to select
2172 that tag through the fast-tag-selection interface.
2173 See the manual for details."
2174 :group 'org-tags
2175 :type '(repeat
2176 (choice
2177 (cons (string :tag "Tag name")
2178 (character :tag "Access char"))
2179 (const :tag "Start radio group" (:startgroup))
2180 (const :tag "End radio group" (:endgroup))
2181 (const :tag "New line" (:newline)))))
2183 (defcustom org-tag-persistent-alist nil
2184 "List of tags that will always appear in all Org-mode files.
2185 This is in addition to any in buffer settings or customizations
2186 of `org-tag-alist'.
2187 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2188 The value of this variable is an alist, the car of each entry must be a
2189 keyword as a string, the cdr may be a character that is used to select
2190 that tag through the fast-tag-selection interface.
2191 See the manual for details.
2192 To disable these tags on a per-file basis, insert anywhere in the file:
2193 #+STARTUP: noptag"
2194 :group 'org-tags
2195 :type '(repeat
2196 (choice
2197 (cons (string :tag "Tag name")
2198 (character :tag "Access char"))
2199 (const :tag "Start radio group" (:startgroup))
2200 (const :tag "End radio group" (:endgroup))
2201 (const :tag "New line" (:newline)))))
2203 (defvar org-file-tags nil
2204 "List of tags that can be inherited by all entries in the file.
2205 The tags will be inherited if the variable `org-use-tag-inheritance'
2206 says they should be.
2207 This variable is populated from #+TAG lines.")
2209 (defcustom org-use-fast-tag-selection 'auto
2210 "Non-nil means, use fast tag selection scheme.
2211 This is a special interface to select and deselect tags with single keys.
2212 When nil, fast selection is never used.
2213 When the symbol `auto', fast selection is used if and only if selection
2214 characters for tags have been configured, either through the variable
2215 `org-tag-alist' or through a #+TAGS line in the buffer.
2216 When t, fast selection is always used and selection keys are assigned
2217 automatically if necessary."
2218 :group 'org-tags
2219 :type '(choice
2220 (const :tag "Always" t)
2221 (const :tag "Never" nil)
2222 (const :tag "When selection characters are configured" 'auto)))
2224 (defcustom org-fast-tag-selection-single-key nil
2225 "Non-nil means, fast tag selection exits after first change.
2226 When nil, you have to press RET to exit it.
2227 During fast tag selection, you can toggle this flag with `C-c'.
2228 This variable can also have the value `expert'. In this case, the window
2229 displaying the tags menu is not even shown, until you press C-c again."
2230 :group 'org-tags
2231 :type '(choice
2232 (const :tag "No" nil)
2233 (const :tag "Yes" t)
2234 (const :tag "Expert" expert)))
2236 (defvar org-fast-tag-selection-include-todo nil
2237 "Non-nil means, fast tags selection interface will also offer TODO states.
2238 This is an undocumented feature, you should not rely on it.")
2240 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2241 "The column to which tags should be indented in a headline.
2242 If this number is positive, it specifies the column. If it is negative,
2243 it means that the tags should be flushright to that column. For example,
2244 -80 works well for a normal 80 character screen."
2245 :group 'org-tags
2246 :type 'integer)
2248 (defcustom org-auto-align-tags t
2249 "Non-nil means, realign tags after pro/demotion of TODO state change.
2250 These operations change the length of a headline and therefore shift
2251 the tags around. With this options turned on, after each such operation
2252 the tags are again aligned to `org-tags-column'."
2253 :group 'org-tags
2254 :type 'boolean)
2256 (defcustom org-use-tag-inheritance t
2257 "Non-nil means, tags in levels apply also for sublevels.
2258 When nil, only the tags directly given in a specific line apply there.
2259 This may also be a list of tags that should be inherited, or a regexp that
2260 matches tags that should be inherited. Additional control is possible
2261 with the variable `org-tags-exclude-from-inheritance' which gives an
2262 explicit list of tags to be excluded from inheritance., even if the value of
2263 `org-use-tag-inheritance' would select it for inheritance.
2265 If this option is t, a match early-on in a tree can lead to a large
2266 number of matches in the subtree when constructing the agenda or creating
2267 a sparse tree. If you only want to see the first match in a tree during
2268 a search, check out the variable `org-tags-match-list-sublevels'."
2269 :group 'org-tags
2270 :type '(choice
2271 (const :tag "Not" nil)
2272 (const :tag "Always" t)
2273 (repeat :tag "Specific tags" (string :tag "Tag"))
2274 (regexp :tag "Tags matched by regexp")))
2276 (defcustom org-tags-exclude-from-inheritance nil
2277 "List of tags that should never be inherited.
2278 This is a way to exclude a few tags from inheritance. For way to do
2279 the opposite, to actively allow inheritance for selected tags,
2280 see the variable `org-use-tag-inheritance'."
2281 :group 'org-tags
2282 :type '(repeat (string :tag "Tag")))
2284 (defun org-tag-inherit-p (tag)
2285 "Check if TAG is one that should be inherited."
2286 (cond
2287 ((member tag org-tags-exclude-from-inheritance) nil)
2288 ((eq org-use-tag-inheritance t) t)
2289 ((not org-use-tag-inheritance) nil)
2290 ((stringp org-use-tag-inheritance)
2291 (string-match org-use-tag-inheritance tag))
2292 ((listp org-use-tag-inheritance)
2293 (member tag org-use-tag-inheritance))
2294 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2296 (defcustom org-tags-match-list-sublevels t
2297 "Non-nil means list also sublevels of headlines matching a search.
2298 This variable applies to tags/property searches, and also to stuck
2299 projects because this search is based on a tags match as well.
2301 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2302 the sublevels of a headline matching a tag search often also match
2303 the same search. Listing all of them can create very long lists.
2304 Setting this variable to nil causes subtrees of a match to be skipped.
2306 As a special case, if the tag search is restricted to TODO items, the
2307 value of this variable is ignored and sublevels are always checked, to
2308 make sure all corresponding TODO items find their way into the list.
2310 This variable is semi-obsolete and probably should always be true. It
2311 is better to limit inheritance to certain tags using the variables
2312 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2313 :group 'org-tags
2314 :type '(choice
2315 (const :tag "No, don't list them" nil)
2316 (const :tag "Yes, do list them" t)
2317 (const :tag "List them, indented with leading dots" indented)))
2319 (defvar org-tags-history nil
2320 "History of minibuffer reads for tags.")
2321 (defvar org-last-tags-completion-table nil
2322 "The last used completion table for tags.")
2323 (defvar org-after-tags-change-hook nil
2324 "Hook that is run after the tags in a line have changed.")
2326 (defgroup org-properties nil
2327 "Options concerning properties in Org-mode."
2328 :tag "Org Properties"
2329 :group 'org)
2331 (defcustom org-property-format "%-10s %s"
2332 "How property key/value pairs should be formatted by `indent-line'.
2333 When `indent-line' hits a property definition, it will format the line
2334 according to this format, mainly to make sure that the values are
2335 lined-up with respect to each other."
2336 :group 'org-properties
2337 :type 'string)
2339 (defcustom org-use-property-inheritance nil
2340 "Non-nil means, properties apply also for sublevels.
2342 This setting is chiefly used during property searches. Turning it on can
2343 cause significant overhead when doing a search, which is why it is not
2344 on by default.
2346 When nil, only the properties directly given in the current entry count.
2347 When t, every property is inherited. The value may also be a list of
2348 properties that should have inheritance, or a regular expression matching
2349 properties that should be inherited.
2351 However, note that some special properties use inheritance under special
2352 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2353 and the properties ending in \"_ALL\" when they are used as descriptor
2354 for valid values of a property.
2356 Note for programmers:
2357 When querying an entry with `org-entry-get', you can control if inheritance
2358 should be used. By default, `org-entry-get' looks only at the local
2359 properties. You can request inheritance by setting the inherit argument
2360 to t (to force inheritance) or to `selective' (to respect the setting
2361 in this variable)."
2362 :group 'org-properties
2363 :type '(choice
2364 (const :tag "Not" nil)
2365 (const :tag "Always" t)
2366 (repeat :tag "Specific properties" (string :tag "Property"))
2367 (regexp :tag "Properties matched by regexp")))
2369 (defun org-property-inherit-p (property)
2370 "Check if PROPERTY is one that should be inherited."
2371 (cond
2372 ((eq org-use-property-inheritance t) t)
2373 ((not org-use-property-inheritance) nil)
2374 ((stringp org-use-property-inheritance)
2375 (string-match org-use-property-inheritance property))
2376 ((listp org-use-property-inheritance)
2377 (member property org-use-property-inheritance))
2378 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2380 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2381 "The default column format, if no other format has been defined.
2382 This variable can be set on the per-file basis by inserting a line
2384 #+COLUMNS: %25ITEM ....."
2385 :group 'org-properties
2386 :type 'string)
2388 (defcustom org-columns-ellipses ".."
2389 "The ellipses to be used when a field in column view is truncated.
2390 When this is the empty string, as many characters as possible are shown,
2391 but then there will be no visual indication that the field has been truncated.
2392 When this is a string of length N, the last N characters of a truncated
2393 field are replaced by this string. If the column is narrower than the
2394 ellipses string, only part of the ellipses string will be shown."
2395 :group 'org-properties
2396 :type 'string)
2398 (defcustom org-columns-modify-value-for-display-function nil
2399 "Function that modifies values for display in column view.
2400 For example, it can be used to cut out a certain part from a time stamp.
2401 The function must take 2 arguments:
2403 column-title The title of the column (*not* the property name)
2404 value The value that should be modified.
2406 The function should return the value that should be displayed,
2407 or nil if the normal value should be used."
2408 :group 'org-properties
2409 :type 'function)
2411 (defcustom org-effort-property "Effort"
2412 "The property that is being used to keep track of effort estimates.
2413 Effort estimates given in this property need to have the format H:MM."
2414 :group 'org-properties
2415 :group 'org-progress
2416 :type '(string :tag "Property"))
2418 (defconst org-global-properties-fixed
2419 '(("VISIBILITY_ALL" . "folded children content all"))
2420 "List of property/value pairs that can be inherited by any entry.
2422 These are fixed values, for the preset properties. The user variable
2423 that can be used to add to this list is `org-global-properties'.
2425 The entries in this list are cons cells where the car is a property
2426 name and cdr is a string with the value. If the value represents
2427 multiple items like an \"_ALL\" property, separate the items by
2428 spaces.")
2430 (defcustom org-global-properties nil
2431 "List of property/value pairs that can be inherited by any entry.
2433 This list will be combined with the constant `org-global-properties-fixed'.
2435 The entries in this list are cons cells where the car is a property
2436 name and cdr is a string with the value.
2438 You can set buffer-local values for the same purpose in the variable
2439 `org-file-properties' this by adding lines like
2441 #+PROPERTY: NAME VALUE"
2442 :group 'org-properties
2443 :type '(repeat
2444 (cons (string :tag "Property")
2445 (string :tag "Value"))))
2447 (defvar org-file-properties nil
2448 "List of property/value pairs that can be inherited by any entry.
2449 Valid for the current buffer.
2450 This variable is populated from #+PROPERTY lines.")
2451 (make-variable-buffer-local 'org-file-properties)
2453 (defgroup org-agenda nil
2454 "Options concerning agenda views in Org-mode."
2455 :tag "Org Agenda"
2456 :group 'org)
2458 (defvar org-category nil
2459 "Variable used by org files to set a category for agenda display.
2460 Such files should use a file variable to set it, for example
2462 # -*- mode: org; org-category: \"ELisp\"
2464 or contain a special line
2466 #+CATEGORY: ELisp
2468 If the file does not specify a category, then file's base name
2469 is used instead.")
2470 (make-variable-buffer-local 'org-category)
2471 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2473 (defcustom org-agenda-files nil
2474 "The files to be used for agenda display.
2475 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2476 \\[org-remove-file]. You can also use customize to edit the list.
2478 If an entry is a directory, all files in that directory that are matched by
2479 `org-agenda-file-regexp' will be part of the file list.
2481 If the value of the variable is not a list but a single file name, then
2482 the list of agenda files is actually stored and maintained in that file, one
2483 agenda file per line."
2484 :group 'org-agenda
2485 :type '(choice
2486 (repeat :tag "List of files and directories" file)
2487 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2489 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2490 "Regular expression to match files for `org-agenda-files'.
2491 If any element in the list in that variable contains a directory instead
2492 of a normal file, all files in that directory that are matched by this
2493 regular expression will be included."
2494 :group 'org-agenda
2495 :type 'regexp)
2497 (defcustom org-agenda-text-search-extra-files nil
2498 "List of extra files to be searched by text search commands.
2499 These files will be search in addition to the agenda files by the
2500 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2501 Note that these files will only be searched for text search commands,
2502 not for the other agenda views like todo lists, tag searches or the weekly
2503 agenda. This variable is intended to list notes and possibly archive files
2504 that should also be searched by these two commands.
2505 In fact, if the first element in the list is the symbol `agenda-archives',
2506 than all archive files of all agenda files will be added to the search
2507 scope."
2508 :group 'org-agenda
2509 :type '(set :greedy t
2510 (const :tag "Agenda Archives" agenda-archives)
2511 (repeat :inline t (file))))
2513 (if (fboundp 'defvaralias)
2514 (defvaralias 'org-agenda-multi-occur-extra-files
2515 'org-agenda-text-search-extra-files))
2517 (defcustom org-agenda-skip-unavailable-files nil
2518 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2519 A nil value means to remove them, after a query, from the list."
2520 :group 'org-agenda
2521 :type 'boolean)
2523 (defcustom org-calendar-to-agenda-key [?c]
2524 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2525 The command `org-calendar-goto-agenda' will be bound to this key. The
2526 default is the character `c' because then `c' can be used to switch back and
2527 forth between agenda and calendar."
2528 :group 'org-agenda
2529 :type 'sexp)
2531 (defcustom org-calendar-agenda-action-key [?k]
2532 "The key to be installed in `calendar-mode-map' for agenda-action.
2533 The command `org-agenda-action' will be bound to this key. The
2534 default is the character `k' because we use the same key in the agenda."
2535 :group 'org-agenda
2536 :type 'sexp)
2538 (eval-after-load "calendar"
2539 '(progn
2540 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2541 'org-calendar-goto-agenda)
2542 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2543 'org-agenda-action)))
2545 (defgroup org-latex nil
2546 "Options for embedding LaTeX code into Org-mode."
2547 :tag "Org LaTeX"
2548 :group 'org)
2550 (defcustom org-format-latex-options
2551 '(:foreground default :background default :scale 1.0
2552 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2553 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
2554 "Options for creating images from LaTeX fragments.
2555 This is a property list with the following properties:
2556 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2557 `default' means use the foreground of the default face.
2558 :background the background color, or \"Transparent\".
2559 `default' means use the background of the default face.
2560 :scale a scaling factor for the size of the images.
2561 :html-foreground, :html-background, :html-scale
2562 the same numbers for HTML export.
2563 :matchers a list indicating which matchers should be used to
2564 find LaTeX fragments. Valid members of this list are:
2565 \"begin\" find environments
2566 \"$1\" find single characters surrounded by $.$
2567 \"$\" find math expressions surrounded by $...$
2568 \"$$\" find math expressions surrounded by $$....$$
2569 \"\\(\" find math expressions surrounded by \\(...\\)
2570 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2571 :group 'org-latex
2572 :type 'plist)
2574 (defcustom org-format-latex-header "\\documentclass{article}
2575 \\usepackage{fullpage} % do not remove
2576 \\usepackage{amssymb}
2577 \\usepackage[usenames]{color}
2578 \\usepackage{amsmath}
2579 \\usepackage{latexsym}
2580 \\usepackage[mathscr]{eucal}
2581 \\pagestyle{empty} % do not remove"
2582 "The document header used for processing LaTeX fragments."
2583 :group 'org-latex
2584 :type 'string)
2587 (defgroup org-font-lock nil
2588 "Font-lock settings for highlighting in Org-mode."
2589 :tag "Org Font Lock"
2590 :group 'org)
2592 (defcustom org-level-color-stars-only nil
2593 "Non-nil means fontify only the stars in each headline.
2594 When nil, the entire headline is fontified.
2595 Changing it requires restart of `font-lock-mode' to become effective
2596 also in regions already fontified."
2597 :group 'org-font-lock
2598 :type 'boolean)
2600 (defcustom org-hide-leading-stars nil
2601 "Non-nil means, hide the first N-1 stars in a headline.
2602 This works by using the face `org-hide' for these stars. This
2603 face is white for a light background, and black for a dark
2604 background. You may have to customize the face `org-hide' to
2605 make this work.
2606 Changing it requires restart of `font-lock-mode' to become effective
2607 also in regions already fontified.
2608 You may also set this on a per-file basis by adding one of the following
2609 lines to the buffer:
2611 #+STARTUP: hidestars
2612 #+STARTUP: showstars"
2613 :group 'org-font-lock
2614 :type 'boolean)
2616 (defcustom org-fontify-done-headline nil
2617 "Non-nil means, change the face of a headline if it is marked DONE.
2618 Normally, only the TODO/DONE keyword indicates the state of a headline.
2619 When this is non-nil, the headline after the keyword is set to the
2620 `org-headline-done' as an additional indication."
2621 :group 'org-font-lock
2622 :type 'boolean)
2624 (defcustom org-fontify-emphasized-text t
2625 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2626 Changing this variable requires a restart of Emacs to take effect."
2627 :group 'org-font-lock
2628 :type 'boolean)
2630 (defcustom org-highlight-latex-fragments-and-specials nil
2631 "Non-nil means, fontify what is treated specially by the exporters."
2632 :group 'org-font-lock
2633 :type 'boolean)
2635 (defcustom org-hide-emphasis-markers nil
2636 "Non-nil mean font-lock should hide the emphasis marker characters."
2637 :group 'org-font-lock
2638 :type 'boolean)
2640 (defvar org-emph-re nil
2641 "Regular expression for matching emphasis.")
2642 (defvar org-verbatim-re nil
2643 "Regular expression for matching verbatim text.")
2644 (defvar org-emphasis-regexp-components) ; defined just below
2645 (defvar org-emphasis-alist) ; defined just below
2646 (defun org-set-emph-re (var val)
2647 "Set variable and compute the emphasis regular expression."
2648 (set var val)
2649 (when (and (boundp 'org-emphasis-alist)
2650 (boundp 'org-emphasis-regexp-components)
2651 org-emphasis-alist org-emphasis-regexp-components)
2652 (let* ((e org-emphasis-regexp-components)
2653 (pre (car e))
2654 (post (nth 1 e))
2655 (border (nth 2 e))
2656 (body (nth 3 e))
2657 (nl (nth 4 e))
2658 (body1 (concat body "*?"))
2659 (markers (mapconcat 'car org-emphasis-alist ""))
2660 (vmarkers (mapconcat
2661 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2662 org-emphasis-alist "")))
2663 ;; make sure special characters appear at the right position in the class
2664 (if (string-match "\\^" markers)
2665 (setq markers (concat (replace-match "" t t markers) "^")))
2666 (if (string-match "-" markers)
2667 (setq markers (concat (replace-match "" t t markers) "-")))
2668 (if (string-match "\\^" vmarkers)
2669 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2670 (if (string-match "-" vmarkers)
2671 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2672 (if (> nl 0)
2673 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2674 (int-to-string nl) "\\}")))
2675 ;; Make the regexp
2676 (setq org-emph-re
2677 (concat "\\([" pre "]\\|^\\)"
2678 "\\("
2679 "\\([" markers "]\\)"
2680 "\\("
2681 "[^" border "]\\|"
2682 "[^" border "]"
2683 body1
2684 "[^" border "]"
2685 "\\)"
2686 "\\3\\)"
2687 "\\([" post "]\\|$\\)"))
2688 (setq org-verbatim-re
2689 (concat "\\([" pre "]\\|^\\)"
2690 "\\("
2691 "\\([" vmarkers "]\\)"
2692 "\\("
2693 "[^" border "]\\|"
2694 "[^" border "]"
2695 body1
2696 "[^" border "]"
2697 "\\)"
2698 "\\3\\)"
2699 "\\([" post "]\\|$\\)")))))
2701 (defcustom org-emphasis-regexp-components
2702 '(" \t('\"{" "- \t.,:!?;'\")}" " \t\r\n,\"'" "." 1)
2703 "Components used to build the regular expression for emphasis.
2704 This is a list with 6 entries. Terminology: In an emphasis string
2705 like \" *strong word* \", we call the initial space PREMATCH, the final
2706 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2707 and \"trong wor\" is the body. The different components in this variable
2708 specify what is allowed/forbidden in each part:
2710 pre Chars allowed as prematch. Beginning of line will be allowed too.
2711 post Chars allowed as postmatch. End of line will be allowed too.
2712 border The chars *forbidden* as border characters.
2713 body-regexp A regexp like \".\" to match a body character. Don't use
2714 non-shy groups here, and don't allow newline here.
2715 newline The maximum number of newlines allowed in an emphasis exp.
2717 Use customize to modify this, or restart Emacs after changing it."
2718 :group 'org-font-lock
2719 :set 'org-set-emph-re
2720 :type '(list
2721 (sexp :tag "Allowed chars in pre ")
2722 (sexp :tag "Allowed chars in post ")
2723 (sexp :tag "Forbidden chars in border ")
2724 (sexp :tag "Regexp for body ")
2725 (integer :tag "number of newlines allowed")
2726 (option (boolean :tag "Please ignore this button"))))
2728 (defcustom org-emphasis-alist
2729 `(("*" bold "<b>" "</b>")
2730 ("/" italic "<i>" "</i>")
2731 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
2732 ("=" org-code "<code>" "</code>" verbatim)
2733 ("~" org-verbatim "<code>" "</code>" verbatim)
2734 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2735 "<del>" "</del>")
2737 "Special syntax for emphasized text.
2738 Text starting and ending with a special character will be emphasized, for
2739 example *bold*, _underlined_ and /italic/. This variable sets the marker
2740 characters, the face to be used by font-lock for highlighting in Org-mode
2741 Emacs buffers, and the HTML tags to be used for this.
2742 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
2743 Use customize to modify this, or restart Emacs after changing it."
2744 :group 'org-font-lock
2745 :set 'org-set-emph-re
2746 :type '(repeat
2747 (list
2748 (string :tag "Marker character")
2749 (choice
2750 (face :tag "Font-lock-face")
2751 (plist :tag "Face property list"))
2752 (string :tag "HTML start tag")
2753 (string :tag "HTML end tag")
2754 (option (const verbatim)))))
2756 ;;; Miscellaneous options
2758 (defgroup org-completion nil
2759 "Completion in Org-mode."
2760 :tag "Org Completion"
2761 :group 'org)
2763 (defcustom org-completion-use-ido nil
2764 "Non-nil means, use ido completion wherever possible.
2765 Note that `ido-mode' must be active for this variable to be relevant.
2766 If you decide to turn this variable on, you might well want to turn off
2767 `org-outline-path-complete-in-steps'."
2768 :group 'org-completion
2769 :type 'boolean)
2771 (defcustom org-completion-fallback-command 'hippie-expand
2772 "The expansion command called by \\[org-complete] in normal context.
2773 Normal means, no org-mode-specific context."
2774 :group 'org-completion
2775 :type 'function)
2777 ;;; Functions and variables from ther packages
2778 ;; Declared here to avoid compiler warnings
2780 ;; XEmacs only
2781 (defvar outline-mode-menu-heading)
2782 (defvar outline-mode-menu-show)
2783 (defvar outline-mode-menu-hide)
2784 (defvar zmacs-regions) ; XEmacs regions
2786 ;; Emacs only
2787 (defvar mark-active)
2789 ;; Various packages
2790 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2791 (declare-function calendar-forward-day "cal-move" (arg))
2792 (declare-function calendar-goto-date "cal-move" (date))
2793 (declare-function calendar-goto-today "cal-move" ())
2794 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2795 (defvar calc-embedded-close-formula)
2796 (defvar calc-embedded-open-formula)
2797 (declare-function cdlatex-tab "ext:cdlatex" ())
2798 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2799 (defvar font-lock-unfontify-region-function)
2800 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2801 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2802 (defvar iswitchb-temp-buflist)
2803 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2804 (defvar org-agenda-tags-todo-honor-ignore-options)
2805 (declare-function org-agenda-skip "org-agenda" ())
2806 (declare-function org-format-agenda-item "org-agenda"
2807 (extra txt &optional category tags dotime noprefix remove-re))
2808 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2809 (declare-function org-agenda-change-all-lines "org-agenda"
2810 (newhead hdmarker &optional fixface just-this))
2811 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2812 (declare-function org-agenda-maybe-redo "org-agenda" ())
2813 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2814 (beg end))
2815 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
2816 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
2817 "org-agenda" (&optional end))
2819 (declare-function parse-time-string "parse-time" (string))
2820 (declare-function remember "remember" (&optional initial))
2821 (declare-function remember-buffer-desc "remember" ())
2822 (declare-function remember-finalize "remember" ())
2823 (defvar remember-save-after-remembering)
2824 (defvar remember-data-file)
2825 (defvar remember-register)
2826 (defvar remember-buffer)
2827 (defvar remember-handler-functions)
2828 (defvar remember-annotation-functions)
2829 (defvar texmathp-why)
2830 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2831 (declare-function table--at-cell-p "table" (position &optional object at-column))
2833 (defvar w3m-current-url)
2834 (defvar w3m-current-title)
2836 (defvar org-latex-regexps)
2838 ;;; Autoload and prepare some org modules
2840 ;; Some table stuff that needs to be defined here, because it is used
2841 ;; by the functions setting up org-mode or checking for table context.
2843 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2844 "Detects an org-type or table-type table.")
2845 (defconst org-table-line-regexp "^[ \t]*|"
2846 "Detects an org-type table line.")
2847 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2848 "Detects an org-type table line.")
2849 (defconst org-table-hline-regexp "^[ \t]*|-"
2850 "Detects an org-type table hline.")
2851 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2852 "Detects a table-type table hline.")
2853 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2854 "Searching from within a table (any type) this finds the first line
2855 outside the table.")
2857 ;; Autoload the functions in org-table.el that are needed by functions here.
2859 (eval-and-compile
2860 (org-autoload "org-table"
2861 '(org-table-align org-table-begin org-table-blank-field
2862 org-table-convert org-table-convert-region org-table-copy-down
2863 org-table-copy-region org-table-create
2864 org-table-create-or-convert-from-region
2865 org-table-create-with-table.el org-table-current-dline
2866 org-table-cut-region org-table-delete-column org-table-edit-field
2867 org-table-edit-formulas org-table-end org-table-eval-formula
2868 org-table-export org-table-field-info
2869 org-table-get-stored-formulas org-table-goto-column
2870 org-table-hline-and-move org-table-import org-table-insert-column
2871 org-table-insert-hline org-table-insert-row org-table-iterate
2872 org-table-justify-field-maybe org-table-kill-row
2873 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2874 org-table-move-column org-table-move-column-left
2875 org-table-move-column-right org-table-move-row
2876 org-table-move-row-down org-table-move-row-up
2877 org-table-next-field org-table-next-row org-table-paste-rectangle
2878 org-table-previous-field org-table-recalculate
2879 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2880 org-table-toggle-coordinate-overlays
2881 org-table-toggle-formula-debugger org-table-wrap-region
2882 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
2884 (defun org-at-table-p (&optional table-type)
2885 "Return t if the cursor is inside an org-type table.
2886 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2887 (if org-enable-table-editor
2888 (save-excursion
2889 (beginning-of-line 1)
2890 (looking-at (if table-type org-table-any-line-regexp
2891 org-table-line-regexp)))
2892 nil))
2893 (defsubst org-table-p () (org-at-table-p))
2895 (defun org-at-table.el-p ()
2896 "Return t if and only if we are at a table.el table."
2897 (and (org-at-table-p 'any)
2898 (save-excursion
2899 (goto-char (org-table-begin 'any))
2900 (looking-at org-table1-hline-regexp))))
2901 (defun org-table-recognize-table.el ()
2902 "If there is a table.el table nearby, recognize it and move into it."
2903 (if org-table-tab-recognizes-table.el
2904 (if (org-at-table.el-p)
2905 (progn
2906 (beginning-of-line 1)
2907 (if (looking-at org-table-dataline-regexp)
2909 (if (looking-at org-table1-hline-regexp)
2910 (progn
2911 (beginning-of-line 2)
2912 (if (looking-at org-table-any-border-regexp)
2913 (beginning-of-line -1)))))
2914 (if (re-search-forward "|" (org-table-end t) t)
2915 (progn
2916 (require 'table)
2917 (if (table--at-cell-p (point))
2919 (message "recognizing table.el table...")
2920 (table-recognize-table)
2921 (message "recognizing table.el table...done")))
2922 (error "This should not happen..."))
2924 nil)
2925 nil))
2927 (defun org-at-table-hline-p ()
2928 "Return t if the cursor is inside a hline in a table."
2929 (if org-enable-table-editor
2930 (save-excursion
2931 (beginning-of-line 1)
2932 (looking-at org-table-hline-regexp))
2933 nil))
2935 (defvar org-table-clean-did-remove-column nil)
2937 (defun org-table-map-tables (function)
2938 "Apply FUNCTION to the start of all tables in the buffer."
2939 (save-excursion
2940 (save-restriction
2941 (widen)
2942 (goto-char (point-min))
2943 (while (re-search-forward org-table-any-line-regexp nil t)
2944 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2945 (beginning-of-line 1)
2946 (if (looking-at org-table-line-regexp)
2947 (save-excursion (funcall function)))
2948 (re-search-forward org-table-any-border-regexp nil 1))))
2949 (message "Mapping tables: done"))
2951 ;; Declare and autoload functions from org-exp.el & Co
2953 (declare-function org-default-export-plist "org-exp")
2954 (declare-function org-infile-export-plist "org-exp")
2955 (declare-function org-get-current-options "org-exp")
2956 (eval-and-compile
2957 (org-autoload "org-exp"
2958 '(org-export org-export-visible
2959 org-insert-export-options-template
2960 org-table-clean-before-export))
2961 (org-autoload "org-ascii"
2962 '(org-export-as-ascii org-export-ascii-preprocess))
2963 (org-autoload "org-html"
2964 '(org-export-as-html-and-open
2965 org-export-as-html-batch org-export-as-html-to-buffer
2966 org-replace-region-by-html org-export-region-as-html
2967 org-export-as-html))
2968 (org-autoload "org-icalendar"
2969 '(org-export-icalendar-this-file
2970 org-export-icalendar-all-agenda-files
2971 org-export-icalendar-combine-agenda-files))
2972 (org-autoload "org-xoxo" '(org-export-as-xoxo)))
2974 ;; Declare and autoload functions from org-agenda.el
2976 (eval-and-compile
2977 (org-autoload "org-agenda"
2978 '(org-agenda org-agenda-list org-search-view
2979 org-todo-list org-tags-view org-agenda-list-stuck-projects
2980 org-diary org-agenda-to-appt
2981 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
2983 ;; Autoload org-remember
2985 (eval-and-compile
2986 (org-autoload "org-remember"
2987 '(org-remember-insinuate org-remember-annotation
2988 org-remember-apply-template org-remember org-remember-handler)))
2990 ;; Autoload org-clock.el
2993 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
2994 (beg end))
2995 (declare-function org-clock-update-mode-line "org-clock" ())
2996 (defvar org-clock-start-time)
2997 (defvar org-clock-marker (make-marker)
2998 "Marker recording the last clock-in.")
3000 (eval-and-compile
3001 (org-autoload
3002 "org-clock"
3003 '(org-clock-in org-clock-out org-clock-cancel
3004 org-clock-goto org-clock-sum org-clock-display
3005 org-clock-remove-overlays org-clock-report
3006 org-clocktable-shift org-dblock-write:clocktable
3007 org-get-clocktable)))
3009 (defun org-clock-update-time-maybe ()
3010 "If this is a CLOCK line, update it and return t.
3011 Otherwise, return nil."
3012 (interactive)
3013 (save-excursion
3014 (beginning-of-line 1)
3015 (skip-chars-forward " \t")
3016 (when (looking-at org-clock-string)
3017 (let ((re (concat "[ \t]*" org-clock-string
3018 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
3019 "\\([ \t]*=>.*\\)?\\)?"))
3020 ts te h m s neg)
3021 (cond
3022 ((not (looking-at re))
3023 nil)
3024 ((not (match-end 2))
3025 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3026 (> org-clock-marker (point))
3027 (<= org-clock-marker (point-at-eol)))
3028 ;; The clock is running here
3029 (setq org-clock-start-time
3030 (apply 'encode-time
3031 (org-parse-time-string (match-string 1))))
3032 (org-clock-update-mode-line)))
3034 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
3035 (end-of-line 1)
3036 (setq ts (match-string 1)
3037 te (match-string 3))
3038 (setq s (- (time-to-seconds
3039 (apply 'encode-time (org-parse-time-string te)))
3040 (time-to-seconds
3041 (apply 'encode-time (org-parse-time-string ts))))
3042 neg (< s 0)
3043 s (abs s)
3044 h (floor (/ s 3600))
3045 s (- s (* 3600 h))
3046 m (floor (/ s 60))
3047 s (- s (* 60 s)))
3048 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
3049 t))))))
3051 (defun org-check-running-clock ()
3052 "Check if the current buffer contains the running clock.
3053 If yes, offer to stop it and to save the buffer with the changes."
3054 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3055 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
3056 (buffer-name))))
3057 (org-clock-out)
3058 (when (y-or-n-p "Save changed buffer?")
3059 (save-buffer))))
3061 (defun org-clocktable-try-shift (dir n)
3062 "Check if this line starts a clock table, if yes, shift the time block."
3063 (when (org-match-line "#\\+BEGIN: clocktable\\>")
3064 (org-clocktable-shift dir n)))
3066 ;; Autoload org-timer.el
3068 (eval-and-compile
3069 (org-autoload
3070 "org-timer"
3071 '(org-timer-start org-timer org-timer-item
3072 org-timer-change-times-in-region)))
3074 ;; Autoload org-feed.el
3076 (eval-and-compile
3077 (org-autoload
3078 "org-feed"
3079 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
3082 ;; Autoload archiving code
3083 ;; The stuff that is needed for cycling and tags has to be defined here.
3085 (defgroup org-archive nil
3086 "Options concerning archiving in Org-mode."
3087 :tag "Org Archive"
3088 :group 'org-structure)
3090 (defcustom org-archive-location "%s_archive::"
3091 "The location where subtrees should be archived.
3093 The value of this variable is a string, consisting of two parts,
3094 separated by a double-colon. The first part is a filename and
3095 the second part is a headline.
3097 When the filename is omitted, archiving happens in the same file.
3098 %s in the filename will be replaced by the current file
3099 name (without the directory part). Archiving to a different file
3100 is useful to keep archived entries from contributing to the
3101 Org-mode Agenda.
3103 The archived entries will be filed as subtrees of the specified
3104 headline. When the headline is omitted, the subtrees are simply
3105 filed away at the end of the file, as top-level entries. Also in
3106 the heading you can use %s to represent the file name, this can be
3107 useful when using the same archive for a number of different files.
3109 Here are a few examples:
3110 \"%s_archive::\"
3111 If the current file is Projects.org, archive in file
3112 Projects.org_archive, as top-level trees. This is the default.
3114 \"::* Archived Tasks\"
3115 Archive in the current file, under the top-level headline
3116 \"* Archived Tasks\".
3118 \"~/org/archive.org::\"
3119 Archive in file ~/org/archive.org (absolute path), as top-level trees.
3121 \"~/org/archive.org::From %s\"
3122 Archive in file ~/org/archive.org (absolute path), und headlines
3123 \"From FILENAME\" where file name is the current file name.
3125 \"basement::** Finished Tasks\"
3126 Archive in file ./basement (relative path), as level 3 trees
3127 below the level 2 heading \"** Finished Tasks\".
3129 You may set this option on a per-file basis by adding to the buffer a
3130 line like
3132 #+ARCHIVE: basement::** Finished Tasks
3134 You may also define it locally for a subtree by setting an ARCHIVE property
3135 in the entry. If such a property is found in an entry, or anywhere up
3136 the hierarchy, it will be used."
3137 :group 'org-archive
3138 :type 'string)
3140 (defcustom org-archive-tag "ARCHIVE"
3141 "The tag that marks a subtree as archived.
3142 An archived subtree does not open during visibility cycling, and does
3143 not contribute to the agenda listings.
3144 After changing this, font-lock must be restarted in the relevant buffers to
3145 get the proper fontification."
3146 :group 'org-archive
3147 :group 'org-keywords
3148 :type 'string)
3150 (defcustom org-agenda-skip-archived-trees t
3151 "Non-nil means, the agenda will skip any items located in archived trees.
3152 An archived tree is a tree marked with the tag ARCHIVE. The use of this
3153 variable is no longer recommended, you should leave it at the value t.
3154 Instead, use the key `v' to cycle the archives-mode in the agenda."
3155 :group 'org-archive
3156 :group 'org-agenda-skip
3157 :type 'boolean)
3159 (defcustom org-columns-skip-arrchived-trees t
3160 "Non-nil means, irgnore archived trees when creating column view."
3161 :group 'org-archive
3162 :group 'org-properties
3163 :type 'boolean)
3165 (defcustom org-cycle-open-archived-trees nil
3166 "Non-nil means, `org-cycle' will open archived trees.
3167 An archived tree is a tree marked with the tag ARCHIVE.
3168 When nil, archived trees will stay folded. You can still open them with
3169 normal outline commands like `show-all', but not with the cycling commands."
3170 :group 'org-archive
3171 :group 'org-cycle
3172 :type 'boolean)
3174 (defcustom org-sparse-tree-open-archived-trees nil
3175 "Non-nil means sparse tree construction shows matches in archived trees.
3176 When nil, matches in these trees are highlighted, but the trees are kept in
3177 collapsed state."
3178 :group 'org-archive
3179 :group 'org-sparse-trees
3180 :type 'boolean)
3182 (defun org-cycle-hide-archived-subtrees (state)
3183 "Re-hide all archived subtrees after a visibility state change."
3184 (when (and (not org-cycle-open-archived-trees)
3185 (not (memq state '(overview folded))))
3186 (save-excursion
3187 (let* ((globalp (memq state '(contents all)))
3188 (beg (if globalp (point-min) (point)))
3189 (end (if globalp (point-max) (org-end-of-subtree t))))
3190 (org-hide-archived-subtrees beg end)
3191 (goto-char beg)
3192 (if (looking-at (concat ".*:" org-archive-tag ":"))
3193 (message "%s" (substitute-command-keys
3194 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
3196 (defun org-force-cycle-archived ()
3197 "Cycle subtree even if it is archived."
3198 (interactive)
3199 (setq this-command 'org-cycle)
3200 (let ((org-cycle-open-archived-trees t))
3201 (call-interactively 'org-cycle)))
3203 (defun org-hide-archived-subtrees (beg end)
3204 "Re-hide all archived subtrees after a visibility state change."
3205 (save-excursion
3206 (let* ((re (concat ":" org-archive-tag ":")))
3207 (goto-char beg)
3208 (while (re-search-forward re end t)
3209 (and (org-on-heading-p) (hide-subtree))
3210 (org-end-of-subtree t)))))
3212 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
3214 (eval-and-compile
3215 (org-autoload "org-archive"
3216 '(org-add-archive-files org-archive-subtree
3217 org-archive-to-archive-sibling org-toggle-archive-tag)))
3219 ;; Autoload Column View Code
3221 (declare-function org-columns-number-to-string "org-colview")
3222 (declare-function org-columns-get-format-and-top-level "org-colview")
3223 (declare-function org-columns-compute "org-colview")
3225 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
3226 '(org-columns-number-to-string org-columns-get-format-and-top-level
3227 org-columns-compute org-agenda-columns org-columns-remove-overlays
3228 org-columns org-insert-columns-dblock org-dblock-write:columnview))
3230 ;; Autoload ID code
3232 (declare-function org-id-store-link "org-id")
3233 (declare-function org-id-locations-load "org-id")
3234 (declare-function org-id-locations-save "org-id")
3235 (defvar org-id-track-globally)
3236 (org-autoload "org-id"
3237 '(org-id-get-create org-id-new org-id-copy org-id-get
3238 org-id-get-with-outline-path-completion
3239 org-id-get-with-outline-drilling
3240 org-id-goto org-id-find org-id-store-link))
3242 ;; Autoload Plotting Code
3244 (org-autoload "org-plot"
3245 '(org-plot/gnuplot))
3247 ;;; Variables for pre-computed regular expressions, all buffer local
3249 (defvar org-drawer-regexp nil
3250 "Matches first line of a hidden block.")
3251 (make-variable-buffer-local 'org-drawer-regexp)
3252 (defvar org-todo-regexp nil
3253 "Matches any of the TODO state keywords.")
3254 (make-variable-buffer-local 'org-todo-regexp)
3255 (defvar org-not-done-regexp nil
3256 "Matches any of the TODO state keywords except the last one.")
3257 (make-variable-buffer-local 'org-not-done-regexp)
3258 (defvar org-not-done-heading-regexp nil
3259 "Matches a TODO headline that is not done.")
3260 (make-variable-buffer-local 'org-not-done-regexp)
3261 (defvar org-todo-line-regexp nil
3262 "Matches a headline and puts TODO state into group 2 if present.")
3263 (make-variable-buffer-local 'org-todo-line-regexp)
3264 (defvar org-complex-heading-regexp nil
3265 "Matches a headline and puts everything into groups:
3266 group 1: the stars
3267 group 2: The todo keyword, maybe
3268 group 3: Priority cookie
3269 group 4: True headline
3270 group 5: Tags")
3271 (make-variable-buffer-local 'org-complex-heading-regexp)
3272 (defvar org-todo-line-tags-regexp nil
3273 "Matches a headline and puts TODO state into group 2 if present.
3274 Also put tags into group 4 if tags are present.")
3275 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3276 (defvar org-nl-done-regexp nil
3277 "Matches newline followed by a headline with the DONE keyword.")
3278 (make-variable-buffer-local 'org-nl-done-regexp)
3279 (defvar org-looking-at-done-regexp nil
3280 "Matches the DONE keyword a point.")
3281 (make-variable-buffer-local 'org-looking-at-done-regexp)
3282 (defvar org-ds-keyword-length 12
3283 "Maximum length of the Deadline and SCHEDULED keywords.")
3284 (make-variable-buffer-local 'org-ds-keyword-length)
3285 (defvar org-deadline-regexp nil
3286 "Matches the DEADLINE keyword.")
3287 (make-variable-buffer-local 'org-deadline-regexp)
3288 (defvar org-deadline-time-regexp nil
3289 "Matches the DEADLINE keyword together with a time stamp.")
3290 (make-variable-buffer-local 'org-deadline-time-regexp)
3291 (defvar org-deadline-line-regexp nil
3292 "Matches the DEADLINE keyword and the rest of the line.")
3293 (make-variable-buffer-local 'org-deadline-line-regexp)
3294 (defvar org-scheduled-regexp nil
3295 "Matches the SCHEDULED keyword.")
3296 (make-variable-buffer-local 'org-scheduled-regexp)
3297 (defvar org-scheduled-time-regexp nil
3298 "Matches the SCHEDULED keyword together with a time stamp.")
3299 (make-variable-buffer-local 'org-scheduled-time-regexp)
3300 (defvar org-closed-time-regexp nil
3301 "Matches the CLOSED keyword together with a time stamp.")
3302 (make-variable-buffer-local 'org-closed-time-regexp)
3304 (defvar org-keyword-time-regexp nil
3305 "Matches any of the 4 keywords, together with the time stamp.")
3306 (make-variable-buffer-local 'org-keyword-time-regexp)
3307 (defvar org-keyword-time-not-clock-regexp nil
3308 "Matches any of the 3 keywords, together with the time stamp.")
3309 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3310 (defvar org-maybe-keyword-time-regexp nil
3311 "Matches a timestamp, possibly preceeded by a keyword.")
3312 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3313 (defvar org-planning-or-clock-line-re nil
3314 "Matches a line with planning or clock info.")
3315 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3317 (defconst org-plain-time-of-day-regexp
3318 (concat
3319 "\\(\\<[012]?[0-9]"
3320 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3321 "\\(--?"
3322 "\\(\\<[012]?[0-9]"
3323 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3324 "\\)?")
3325 "Regular expression to match a plain time or time range.
3326 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3327 groups carry important information:
3328 0 the full match
3329 1 the first time, range or not
3330 8 the second time, if it is a range.")
3332 (defconst org-plain-time-extension-regexp
3333 (concat
3334 "\\(\\<[012]?[0-9]"
3335 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3336 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
3337 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
3338 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3339 groups carry important information:
3340 0 the full match
3341 7 hours of duration
3342 9 minutes of duration")
3344 (defconst org-stamp-time-of-day-regexp
3345 (concat
3346 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
3347 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
3348 "\\(--?"
3349 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
3350 "Regular expression to match a timestamp time or time range.
3351 After a match, the following groups carry important information:
3352 0 the full match
3353 1 date plus weekday, for backreferencing to make sure both times on same day
3354 2 the first time, range or not
3355 4 the second time, if it is a range.")
3357 (defconst org-startup-options
3358 '(("fold" org-startup-folded t)
3359 ("overview" org-startup-folded t)
3360 ("nofold" org-startup-folded nil)
3361 ("showall" org-startup-folded nil)
3362 ("content" org-startup-folded content)
3363 ("hidestars" org-hide-leading-stars t)
3364 ("showstars" org-hide-leading-stars nil)
3365 ("odd" org-odd-levels-only t)
3366 ("oddeven" org-odd-levels-only nil)
3367 ("align" org-startup-align-all-tables t)
3368 ("noalign" org-startup-align-all-tables nil)
3369 ("customtime" org-display-custom-times t)
3370 ("logdone" org-log-done time)
3371 ("lognotedone" org-log-done note)
3372 ("nologdone" org-log-done nil)
3373 ("lognoteclock-out" org-log-note-clock-out t)
3374 ("nolognoteclock-out" org-log-note-clock-out nil)
3375 ("logrepeat" org-log-repeat state)
3376 ("lognoterepeat" org-log-repeat note)
3377 ("nologrepeat" org-log-repeat nil)
3378 ("fninline" org-footnote-define-inline t)
3379 ("nofninline" org-footnote-define-inline nil)
3380 ("fnlocal" org-footnote-section nil)
3381 ("fnauto" org-footnote-auto-label t)
3382 ("fnprompt" org-footnote-auto-label nil)
3383 ("fnconfirm" org-footnote-auto-label confirm)
3384 ("fnplain" org-footnote-auto-label plain)
3385 ("constcgs" constants-unit-system cgs)
3386 ("constSI" constants-unit-system SI)
3387 ("noptag" org-tag-persistent-alist nil))
3388 "Variable associated with STARTUP options for org-mode.
3389 Each element is a list of three items: The startup options as written
3390 in the #+STARTUP line, the corresponding variable, and the value to
3391 set this variable to if the option is found. An optional forth element PUSH
3392 means to push this value onto the list in the variable.")
3394 (defun org-set-regexps-and-options ()
3395 "Precompute regular expressions for current buffer."
3396 (when (org-mode-p)
3397 (org-set-local 'org-todo-kwd-alist nil)
3398 (org-set-local 'org-todo-key-alist nil)
3399 (org-set-local 'org-todo-key-trigger nil)
3400 (org-set-local 'org-todo-keywords-1 nil)
3401 (org-set-local 'org-done-keywords nil)
3402 (org-set-local 'org-todo-heads nil)
3403 (org-set-local 'org-todo-sets nil)
3404 (org-set-local 'org-todo-log-states nil)
3405 (org-set-local 'org-file-properties nil)
3406 (org-set-local 'org-file-tags nil)
3407 (let ((re (org-make-options-regexp
3408 '("CATEGORY" "TODO" "COLUMNS"
3409 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3410 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")
3411 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
3412 (splitre "[ \t]+")
3413 kwds kws0 kwsa key log value cat arch tags const links hw dws
3414 tail sep kws1 prio props ftags drawers
3415 ext-setup-or-nil setup-contents (start 0))
3416 (save-excursion
3417 (save-restriction
3418 (widen)
3419 (goto-char (point-min))
3420 (while (or (and ext-setup-or-nil
3421 (string-match re ext-setup-or-nil start)
3422 (setq start (match-end 0)))
3423 (and (setq ext-setup-or-nil nil start 0)
3424 (re-search-forward re nil t)))
3425 (setq key (upcase (match-string 1 ext-setup-or-nil))
3426 value (org-match-string-no-properties 2 ext-setup-or-nil))
3427 (cond
3428 ((equal key "CATEGORY")
3429 (if (string-match "[ \t]+$" value)
3430 (setq value (replace-match "" t t value)))
3431 (setq cat value))
3432 ((member key '("SEQ_TODO" "TODO"))
3433 (push (cons 'sequence (org-split-string value splitre)) kwds))
3434 ((equal key "TYP_TODO")
3435 (push (cons 'type (org-split-string value splitre)) kwds))
3436 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
3437 ;; general TODO-like setup
3438 (push (cons (intern (downcase (match-string 1 key)))
3439 (org-split-string value splitre)) kwds))
3440 ((equal key "TAGS")
3441 (setq tags (append tags (if tags '("\\n") nil)
3442 (org-split-string value splitre))))
3443 ((equal key "COLUMNS")
3444 (org-set-local 'org-columns-default-format value))
3445 ((equal key "LINK")
3446 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3447 (push (cons (match-string 1 value)
3448 (org-trim (match-string 2 value)))
3449 links)))
3450 ((equal key "PRIORITIES")
3451 (setq prio (org-split-string value " +")))
3452 ((equal key "PROPERTY")
3453 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3454 (push (cons (match-string 1 value) (match-string 2 value))
3455 props)))
3456 ((equal key "FILETAGS")
3457 (when (string-match "\\S-" value)
3458 (setq ftags
3459 (append
3460 ftags
3461 (apply 'append
3462 (mapcar (lambda (x) (org-split-string x ":"))
3463 (org-split-string value)))))))
3464 ((equal key "DRAWERS")
3465 (setq drawers (org-split-string value splitre)))
3466 ((equal key "CONSTANTS")
3467 (setq const (append const (org-split-string value splitre))))
3468 ((equal key "STARTUP")
3469 (let ((opts (org-split-string value splitre))
3470 l var val)
3471 (while (setq l (pop opts))
3472 (when (setq l (assoc l org-startup-options))
3473 (setq var (nth 1 l) val (nth 2 l))
3474 (if (not (nth 3 l))
3475 (set (make-local-variable var) val)
3476 (if (not (listp (symbol-value var)))
3477 (set (make-local-variable var) nil))
3478 (set (make-local-variable var) (symbol-value var))
3479 (add-to-list var val))))))
3480 ((equal key "ARCHIVE")
3481 (string-match " *$" value)
3482 (setq arch (replace-match "" t t value))
3483 (remove-text-properties 0 (length arch)
3484 '(face t fontified t) arch))
3485 ((equal key "SETUPFILE")
3486 (setq setup-contents (org-file-contents
3487 (expand-file-name
3488 (org-remove-double-quotes value))
3489 'noerror))
3490 (if (not ext-setup-or-nil)
3491 (setq ext-setup-or-nil setup-contents start 0)
3492 (setq ext-setup-or-nil
3493 (concat (substring ext-setup-or-nil 0 start)
3494 "\n" setup-contents "\n"
3495 (substring ext-setup-or-nil start)))))
3496 ))))
3497 (when cat
3498 (org-set-local 'org-category (intern cat))
3499 (push (cons "CATEGORY" cat) props))
3500 (when prio
3501 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3502 (setq prio (mapcar 'string-to-char prio))
3503 (org-set-local 'org-highest-priority (nth 0 prio))
3504 (org-set-local 'org-lowest-priority (nth 1 prio))
3505 (org-set-local 'org-default-priority (nth 2 prio)))
3506 (and props (org-set-local 'org-file-properties (nreverse props)))
3507 (and ftags (org-set-local 'org-file-tags
3508 (mapcar 'org-add-prop-inherited ftags)))
3509 (and drawers (org-set-local 'org-drawers drawers))
3510 (and arch (org-set-local 'org-archive-location arch))
3511 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3512 ;; Process the TODO keywords
3513 (unless kwds
3514 ;; Use the global values as if they had been given locally.
3515 (setq kwds (default-value 'org-todo-keywords))
3516 (if (stringp (car kwds))
3517 (setq kwds (list (cons org-todo-interpretation
3518 (default-value 'org-todo-keywords)))))
3519 (setq kwds (reverse kwds)))
3520 (setq kwds (nreverse kwds))
3521 (let (inter kws kw)
3522 (while (setq kws (pop kwds))
3523 (let ((kws (or
3524 (run-hook-with-args-until-success
3525 'org-todo-setup-filter-hook kws)
3526 kws)))
3527 (setq inter (pop kws) sep (member "|" kws)
3528 kws0 (delete "|" (copy-sequence kws))
3529 kwsa nil
3530 kws1 (mapcar
3531 (lambda (x)
3532 ;; 1 2
3533 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3534 (progn
3535 (setq kw (match-string 1 x)
3536 key (and (match-end 2) (match-string 2 x))
3537 log (org-extract-log-state-settings x))
3538 (push (cons kw (and key (string-to-char key))) kwsa)
3539 (and log (push log org-todo-log-states))
3541 (error "Invalid TODO keyword %s" x)))
3542 kws0)
3543 kwsa (if kwsa (append '((:startgroup))
3544 (nreverse kwsa)
3545 '((:endgroup))))
3546 hw (car kws1)
3547 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3548 tail (list inter hw (car dws) (org-last dws))))
3549 (add-to-list 'org-todo-heads hw 'append)
3550 (push kws1 org-todo-sets)
3551 (setq org-done-keywords (append org-done-keywords dws nil))
3552 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3553 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3554 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3555 (setq org-todo-sets (nreverse org-todo-sets)
3556 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3557 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3558 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3559 ;; Process the constants
3560 (when const
3561 (let (e cst)
3562 (while (setq e (pop const))
3563 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3564 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3565 (setq org-table-formula-constants-local cst)))
3567 ;; Process the tags.
3568 (when tags
3569 (let (e tgs)
3570 (while (setq e (pop tags))
3571 (cond
3572 ((equal e "{") (push '(:startgroup) tgs))
3573 ((equal e "}") (push '(:endgroup) tgs))
3574 ((equal e "\\n") (push '(:newline) tgs))
3575 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3576 (push (cons (match-string 1 e)
3577 (string-to-char (match-string 2 e)))
3578 tgs))
3579 (t (push (list e) tgs))))
3580 (org-set-local 'org-tag-alist nil)
3581 (while (setq e (pop tgs))
3582 (or (and (stringp (car e))
3583 (assoc (car e) org-tag-alist))
3584 (push e org-tag-alist)))))
3586 ;; Compute the regular expressions and other local variables
3587 (if (not org-done-keywords)
3588 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
3589 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3590 (length org-scheduled-string)
3591 (length org-clock-string)
3592 (length org-closed-string)))
3593 org-drawer-regexp
3594 (concat "^[ \t]*:\\("
3595 (mapconcat 'regexp-quote org-drawers "\\|")
3596 "\\):[ \t]*$")
3597 org-not-done-keywords
3598 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3599 org-todo-regexp
3600 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3601 "\\|") "\\)\\>")
3602 org-not-done-regexp
3603 (concat "\\<\\("
3604 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3605 "\\)\\>")
3606 org-not-done-heading-regexp
3607 (concat "^\\(\\*+\\)[ \t]+\\("
3608 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3609 "\\)\\>")
3610 org-todo-line-regexp
3611 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3612 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3613 "\\)\\>\\)?[ \t]*\\(.*\\)")
3614 org-complex-heading-regexp
3615 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3616 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3617 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3618 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3619 org-nl-done-regexp
3620 (concat "\n\\*+[ \t]+"
3621 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3622 "\\)" "\\>")
3623 org-todo-line-tags-regexp
3624 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3625 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3626 (org-re
3627 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3628 org-looking-at-done-regexp
3629 (concat "^" "\\(?:"
3630 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3631 "\\>")
3632 org-deadline-regexp (concat "\\<" org-deadline-string)
3633 org-deadline-time-regexp
3634 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3635 org-deadline-line-regexp
3636 (concat "\\<\\(" org-deadline-string "\\).*")
3637 org-scheduled-regexp
3638 (concat "\\<" org-scheduled-string)
3639 org-scheduled-time-regexp
3640 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3641 org-closed-time-regexp
3642 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3643 org-keyword-time-regexp
3644 (concat "\\<\\(" org-scheduled-string
3645 "\\|" org-deadline-string
3646 "\\|" org-closed-string
3647 "\\|" org-clock-string "\\)"
3648 " *[[<]\\([^]>]+\\)[]>]")
3649 org-keyword-time-not-clock-regexp
3650 (concat "\\<\\(" org-scheduled-string
3651 "\\|" org-deadline-string
3652 "\\|" org-closed-string
3653 "\\)"
3654 " *[[<]\\([^]>]+\\)[]>]")
3655 org-maybe-keyword-time-regexp
3656 (concat "\\(\\<\\(" org-scheduled-string
3657 "\\|" org-deadline-string
3658 "\\|" org-closed-string
3659 "\\|" org-clock-string "\\)\\)?"
3660 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3661 org-planning-or-clock-line-re
3662 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3663 "\\|" org-deadline-string
3664 "\\|" org-closed-string "\\|" org-clock-string
3665 "\\)\\>\\)")
3667 (org-compute-latex-and-specials-regexp)
3668 (org-set-font-lock-defaults))))
3670 (defun org-file-contents (file &optional noerror)
3671 "Return the contents of FILE, as a string."
3672 (if (or (not file)
3673 (not (file-readable-p file)))
3674 (if noerror
3675 (progn
3676 (message "Cannot read file %s" file)
3677 (ding) (sit-for 2)
3679 (error "Cannot read file %s" file))
3680 (with-temp-buffer
3681 (insert-file-contents file)
3682 (buffer-string))))
3684 (defun org-extract-log-state-settings (x)
3685 "Extract the log state setting from a TODO keyword string.
3686 This will extract info from a string like \"WAIT(w@/!)\"."
3687 (let (kw key log1 log2)
3688 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3689 (setq kw (match-string 1 x)
3690 key (and (match-end 2) (match-string 2 x))
3691 log1 (and (match-end 3) (match-string 3 x))
3692 log2 (and (match-end 4) (match-string 4 x)))
3693 (and (or log1 log2)
3694 (list kw
3695 (and log1 (if (equal log1 "!") 'time 'note))
3696 (and log2 (if (equal log2 "!") 'time 'note)))))))
3698 (defun org-remove-keyword-keys (list)
3699 "Remove a pair of parenthesis at the end of each string in LIST."
3700 (mapcar (lambda (x)
3701 (if (string-match "(.*)$" x)
3702 (substring x 0 (match-beginning 0))
3704 list))
3706 ;; FIXME: this could be done much better, using second characters etc.
3707 (defun org-assign-fast-keys (alist)
3708 "Assign fast keys to a keyword-key alist.
3709 Respect keys that are already there."
3710 (let (new e k c c1 c2 (char ?a))
3711 (while (setq e (pop alist))
3712 (cond
3713 ((equal e '(:startgroup)) (push e new))
3714 ((equal e '(:endgroup)) (push e new))
3715 ((equal e '(:newline)) (push e new))
3717 (setq k (car e) c2 nil)
3718 (if (cdr e)
3719 (setq c (cdr e))
3720 ;; automatically assign a character.
3721 (setq c1 (string-to-char
3722 (downcase (substring
3723 k (if (= (string-to-char k) ?@) 1 0)))))
3724 (if (or (rassoc c1 new) (rassoc c1 alist))
3725 (while (or (rassoc char new) (rassoc char alist))
3726 (setq char (1+ char)))
3727 (setq c2 c1))
3728 (setq c (or c2 char)))
3729 (push (cons k c) new))))
3730 (nreverse new)))
3732 ;;; Some variables used in various places
3734 (defvar org-window-configuration nil
3735 "Used in various places to store a window configuration.")
3736 (defvar org-finish-function nil
3737 "Function to be called when `C-c C-c' is used.
3738 This is for getting out of special buffers like remember.")
3741 ;; FIXME: Occasionally check by commenting these, to make sure
3742 ;; no other functions uses these, forgetting to let-bind them.
3743 (defvar entry)
3744 (defvar state)
3745 (defvar last-state)
3746 (defvar date)
3747 (defvar description)
3749 ;; Defined somewhere in this file, but used before definition.
3750 (defvar org-html-entities)
3751 (defvar org-struct-menu)
3752 (defvar org-org-menu)
3753 (defvar org-tbl-menu)
3754 (defvar org-agenda-keymap)
3756 ;;;; Define the Org-mode
3758 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3759 (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."))
3762 ;; We use a before-change function to check if a table might need
3763 ;; an update.
3764 (defvar org-table-may-need-update t
3765 "Indicates that a table might need an update.
3766 This variable is set by `org-before-change-function'.
3767 `org-table-align' sets it back to nil.")
3768 (defun org-before-change-function (beg end)
3769 "Every change indicates that a table might need an update."
3770 (setq org-table-may-need-update t))
3771 (defvar org-mode-map)
3772 (defvar org-mode-hook nil
3773 "Mode hook for Org-mode, run after the mode was turned on.")
3774 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3775 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3776 (defvar org-table-buffer-is-an nil)
3777 (defconst org-outline-regexp "\\*+ ")
3779 ;;;###autoload
3780 (define-derived-mode org-mode outline-mode "Org"
3781 "Outline-based notes management and organizer, alias
3782 \"Carsten's outline-mode for keeping track of everything.\"
3784 Org-mode develops organizational tasks around a NOTES file which
3785 contains information about projects as plain text. Org-mode is
3786 implemented on top of outline-mode, which is ideal to keep the content
3787 of large files well structured. It supports ToDo items, deadlines and
3788 time stamps, which magically appear in the diary listing of the Emacs
3789 calendar. Tables are easily created with a built-in table editor.
3790 Plain text URL-like links connect to websites, emails (VM), Usenet
3791 messages (Gnus), BBDB entries, and any files related to the project.
3792 For printing and sharing of notes, an Org-mode file (or a part of it)
3793 can be exported as a structured ASCII or HTML file.
3795 The following commands are available:
3797 \\{org-mode-map}"
3799 ;; Get rid of Outline menus, they are not needed
3800 ;; Need to do this here because define-derived-mode sets up
3801 ;; the keymap so late. Still, it is a waste to call this each time
3802 ;; we switch another buffer into org-mode.
3803 (if (featurep 'xemacs)
3804 (when (boundp 'outline-mode-menu-heading)
3805 ;; Assume this is Greg's port, it used easymenu
3806 (easy-menu-remove outline-mode-menu-heading)
3807 (easy-menu-remove outline-mode-menu-show)
3808 (easy-menu-remove outline-mode-menu-hide))
3809 (define-key org-mode-map [menu-bar headings] 'undefined)
3810 (define-key org-mode-map [menu-bar hide] 'undefined)
3811 (define-key org-mode-map [menu-bar show] 'undefined))
3813 (org-load-modules-maybe)
3814 (easy-menu-add org-org-menu)
3815 (easy-menu-add org-tbl-menu)
3816 (org-install-agenda-files-menu)
3817 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3818 (org-add-to-invisibility-spec '(org-cwidth))
3819 (when (featurep 'xemacs)
3820 (org-set-local 'line-move-ignore-invisible t))
3821 (org-set-local 'outline-regexp org-outline-regexp)
3822 (org-set-local 'outline-level 'org-outline-level)
3823 (when (and org-ellipsis
3824 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3825 (fboundp 'make-glyph-code))
3826 (unless org-display-table
3827 (setq org-display-table (make-display-table)))
3828 (set-display-table-slot
3829 org-display-table 4
3830 (vconcat (mapcar
3831 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3832 org-ellipsis)))
3833 (if (stringp org-ellipsis) org-ellipsis "..."))))
3834 (setq buffer-display-table org-display-table))
3835 (org-set-regexps-and-options)
3836 (when (and org-tag-faces (not org-tags-special-faces-re))
3837 ;; tag faces set outside customize.... force initialization.
3838 (org-set-tag-faces 'org-tag-faces org-tag-faces))
3839 ;; Calc embedded
3840 (org-set-local 'calc-embedded-open-mode "# ")
3841 (modify-syntax-entry ?# "<")
3842 (modify-syntax-entry ?@ "w")
3843 (if org-startup-truncated (setq truncate-lines t))
3844 (org-set-local 'font-lock-unfontify-region-function
3845 'org-unfontify-region)
3846 ;; Activate before-change-function
3847 (org-set-local 'org-table-may-need-update t)
3848 (org-add-hook 'before-change-functions 'org-before-change-function nil
3849 'local)
3850 ;; Check for running clock before killing a buffer
3851 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3852 ;; Paragraphs and auto-filling
3853 (org-set-autofill-regexps)
3854 (setq indent-line-function 'org-indent-line-function)
3855 (org-update-radio-target-regexp)
3856 ;; Make sure dependence stuff works reliably, even for users who set it
3857 ;; too late :-(
3858 (if org-enforce-todo-dependencies
3859 (add-hook 'org-blocker-hook
3860 'org-block-todo-from-children-or-siblings-or-parent)
3861 (remove-hook 'org-blocker-hook
3862 'org-block-todo-from-children-or-siblings-or-parent))
3863 (if org-enforce-todo-checkbox-dependencies
3864 (add-hook 'org-blocker-hook
3865 'org-block-todo-from-checkboxes)
3866 (remove-hook 'org-blocker-hook
3867 'org-block-todo-from-checkboxes))
3869 ;; Comment characters
3870 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3871 (org-set-local 'comment-padding " ")
3873 ;; Align options lines
3874 (org-set-local
3875 'align-mode-rules-list
3876 '((org-in-buffer-settings
3877 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3878 (modes . '(org-mode)))))
3880 ;; Imenu
3881 (org-set-local 'imenu-create-index-function
3882 'org-imenu-get-tree)
3884 ;; Make isearch reveal context
3885 (if (or (featurep 'xemacs)
3886 (not (boundp 'outline-isearch-open-invisible-function)))
3887 ;; Emacs 21 and XEmacs make use of the hook
3888 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3889 ;; Emacs 22 deals with this through a special variable
3890 (org-set-local 'outline-isearch-open-invisible-function
3891 (lambda (&rest ignore) (org-show-context 'isearch))))
3893 ;; If empty file that did not turn on org-mode automatically, make it to.
3894 (if (and org-insert-mode-line-in-empty-file
3895 (interactive-p)
3896 (= (point-min) (point-max)))
3897 (insert "# -*- mode: org -*-\n\n"))
3899 (unless org-inhibit-startup
3900 (when org-startup-align-all-tables
3901 (let ((bmp (buffer-modified-p)))
3902 (org-table-map-tables 'org-table-align)
3903 (set-buffer-modified-p bmp)))
3904 (org-set-startup-visibility)))
3906 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3908 (defun org-current-time ()
3909 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3910 (if (> (car org-time-stamp-rounding-minutes) 1)
3911 (let ((r (car org-time-stamp-rounding-minutes))
3912 (time (decode-time)))
3913 (apply 'encode-time
3914 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3915 (nthcdr 2 time))))
3916 (current-time)))
3918 ;;;; Font-Lock stuff, including the activators
3920 (defvar org-mouse-map (make-sparse-keymap))
3921 (org-defkey org-mouse-map
3922 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3923 (org-defkey org-mouse-map
3924 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3925 (when org-mouse-1-follows-link
3926 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3927 (when org-tab-follows-link
3928 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3929 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3931 (require 'font-lock)
3933 (defconst org-non-link-chars "]\t\n\r<>")
3934 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3935 "shell" "elisp"))
3936 (defvar org-link-types-re nil
3937 "Matches a link that has a url-like prefix like \"http:\"")
3938 (defvar org-link-re-with-space nil
3939 "Matches a link with spaces, optional angular brackets around it.")
3940 (defvar org-link-re-with-space2 nil
3941 "Matches a link with spaces, optional angular brackets around it.")
3942 (defvar org-link-re-with-space3 nil
3943 "Matches a link with spaces, only for internal part in bracket links.")
3944 (defvar org-angle-link-re nil
3945 "Matches link with angular brackets, spaces are allowed.")
3946 (defvar org-plain-link-re nil
3947 "Matches plain link, without spaces.")
3948 (defvar org-bracket-link-regexp nil
3949 "Matches a link in double brackets.")
3950 (defvar org-bracket-link-analytic-regexp nil
3951 "Regular expression used to analyze links.
3952 Here is what the match groups contain after a match:
3953 1: http:
3954 2: http
3955 3: path
3956 4: [desc]
3957 5: desc")
3958 (defvar org-bracket-link-analytic-regexp++ nil
3959 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
3960 (defvar org-any-link-re nil
3961 "Regular expression matching any link.")
3963 (defun org-make-link-regexps ()
3964 "Update the link regular expressions.
3965 This should be called after the variable `org-link-types' has changed."
3966 (setq org-link-types-re
3967 (concat
3968 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3969 org-link-re-with-space
3970 (concat
3971 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3972 "\\([^" org-non-link-chars " ]"
3973 "[^" org-non-link-chars "]*"
3974 "[^" org-non-link-chars " ]\\)>?")
3975 org-link-re-with-space2
3976 (concat
3977 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3978 "\\([^" org-non-link-chars " ]"
3979 "[^\t\n\r]*"
3980 "[^" org-non-link-chars " ]\\)>?")
3981 org-link-re-with-space3
3982 (concat
3983 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3984 "\\([^" org-non-link-chars " ]"
3985 "[^\t\n\r]*\\)")
3986 org-angle-link-re
3987 (concat
3988 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3989 "\\([^" org-non-link-chars " ]"
3990 "[^" org-non-link-chars "]*"
3991 "\\)>")
3992 org-plain-link-re
3993 (concat
3994 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3995 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3996 org-bracket-link-regexp
3997 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3998 org-bracket-link-analytic-regexp
3999 (concat
4000 "\\[\\["
4001 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
4002 "\\([^]]+\\)"
4003 "\\]"
4004 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4005 "\\]")
4006 org-bracket-link-analytic-regexp++
4007 (concat
4008 "\\[\\["
4009 "\\(\\(" (mapconcat 'identity (cons "coderef" org-link-types) "\\|") "\\):\\)?"
4010 "\\([^]]+\\)"
4011 "\\]"
4012 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4013 "\\]")
4014 org-any-link-re
4015 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
4016 org-angle-link-re "\\)\\|\\("
4017 org-plain-link-re "\\)")))
4019 (org-make-link-regexps)
4021 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
4022 "Regular expression for fast time stamp matching.")
4023 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
4024 "Regular expression for fast time stamp matching.")
4025 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4026 "Regular expression matching time strings for analysis.
4027 This one does not require the space after the date, so it can be used
4028 on a string that terminates immediately after the date.")
4029 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4030 "Regular expression matching time strings for analysis.")
4031 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
4032 "Regular expression matching time stamps, with groups.")
4033 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
4034 "Regular expression matching time stamps (also [..]), with groups.")
4035 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
4036 "Regular expression matching a time stamp range.")
4037 (defconst org-tr-regexp-both
4038 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
4039 "Regular expression matching a time stamp range.")
4040 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
4041 org-ts-regexp "\\)?")
4042 "Regular expression matching a time stamp or time stamp range.")
4043 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
4044 org-ts-regexp-both "\\)?")
4045 "Regular expression matching a time stamp or time stamp range.
4046 The time stamps may be either active or inactive.")
4048 (defvar org-emph-face nil)
4050 (defun org-do-emphasis-faces (limit)
4051 "Run through the buffer and add overlays to links."
4052 (let (rtn)
4053 (while (and (not rtn) (re-search-forward org-emph-re limit t))
4054 (if (not (= (char-after (match-beginning 3))
4055 (char-after (match-beginning 4))))
4056 (progn
4057 (setq rtn t)
4058 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
4059 'face
4060 (nth 1 (assoc (match-string 3)
4061 org-emphasis-alist)))
4062 (add-text-properties (match-beginning 2) (match-end 2)
4063 '(font-lock-multiline t))
4064 (when org-hide-emphasis-markers
4065 (add-text-properties (match-end 4) (match-beginning 5)
4066 '(invisible org-link))
4067 (add-text-properties (match-beginning 3) (match-end 3)
4068 '(invisible org-link)))))
4069 (backward-char 1))
4070 rtn))
4072 (defun org-emphasize (&optional char)
4073 "Insert or change an emphasis, i.e. a font like bold or italic.
4074 If there is an active region, change that region to a new emphasis.
4075 If there is no region, just insert the marker characters and position
4076 the cursor between them.
4077 CHAR should be either the marker character, or the first character of the
4078 HTML tag associated with that emphasis. If CHAR is a space, the means
4079 to remove the emphasis of the selected region.
4080 If char is not given (for example in an interactive call) it
4081 will be prompted for."
4082 (interactive)
4083 (let ((eal org-emphasis-alist) e det
4084 (erc org-emphasis-regexp-components)
4085 (prompt "")
4086 (string "") beg end move tag c s)
4087 (if (org-region-active-p)
4088 (setq beg (region-beginning) end (region-end)
4089 string (buffer-substring beg end))
4090 (setq move t))
4092 (while (setq e (pop eal))
4093 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
4094 c (aref tag 0))
4095 (push (cons c (string-to-char (car e))) det)
4096 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
4097 (substring tag 1)))))
4098 (setq det (nreverse det))
4099 (unless char
4100 (message "%s" (concat "Emphasis marker or tag:" prompt))
4101 (setq char (read-char-exclusive)))
4102 (setq char (or (cdr (assoc char det)) char))
4103 (if (equal char ?\ )
4104 (setq s "" move nil)
4105 (unless (assoc (char-to-string char) org-emphasis-alist)
4106 (error "No such emphasis marker: \"%c\"" char))
4107 (setq s (char-to-string char)))
4108 (while (and (> (length string) 1)
4109 (equal (substring string 0 1) (substring string -1))
4110 (assoc (substring string 0 1) org-emphasis-alist))
4111 (setq string (substring string 1 -1)))
4112 (setq string (concat s string s))
4113 (if beg (delete-region beg end))
4114 (unless (or (bolp)
4115 (string-match (concat "[" (nth 0 erc) "\n]")
4116 (char-to-string (char-before (point)))))
4117 (insert " "))
4118 (unless (string-match (concat "[" (nth 1 erc) "\n]")
4119 (char-to-string (char-after (point))))
4120 (insert " ") (backward-char 1))
4121 (insert string)
4122 (and move (backward-char 1))))
4124 (defconst org-nonsticky-props
4125 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
4127 (defsubst org-rear-nonsticky-at (pos)
4128 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
4130 (defun org-activate-plain-links (limit)
4131 "Run through the buffer and add overlays to links."
4132 (catch 'exit
4133 (let (f)
4134 (while (re-search-forward org-plain-link-re limit t)
4135 (setq f (get-text-property (match-beginning 0) 'face))
4136 (if (or (eq f 'org-tag)
4137 (and (listp f) (memq 'org-tag f)))
4139 (add-text-properties (match-beginning 0) (match-end 0)
4140 (list 'mouse-face 'highlight
4141 'keymap org-mouse-map))
4142 (org-rear-nonsticky-at (match-end 0))
4143 (throw 'exit t))))))
4145 (defun org-activate-code (limit)
4146 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
4147 (progn
4148 (remove-text-properties (match-beginning 0) (match-end 0)
4149 '(display t invisible t intangible t))
4150 t)))
4152 (defun org-activate-angle-links (limit)
4153 "Run through the buffer and add overlays to links."
4154 (if (re-search-forward org-angle-link-re limit t)
4155 (progn
4156 (add-text-properties (match-beginning 0) (match-end 0)
4157 (list 'mouse-face 'highlight
4158 'keymap org-mouse-map))
4159 (org-rear-nonsticky-at (match-end 0))
4160 t)))
4162 (defun org-activate-footnote-links (limit)
4163 "Run through the buffer and add overlays to links."
4164 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
4165 limit t)
4166 (progn
4167 (add-text-properties (match-beginning 2) (match-end 2)
4168 (list 'mouse-face 'highlight
4169 'keymap org-mouse-map
4170 'help-echo
4171 (if (= (point-at-bol) (match-beginning 2))
4172 "Footnote definition"
4173 "Footnote reference")
4175 (org-rear-nonsticky-at (match-end 2))
4176 t)))
4178 (defun org-activate-bracket-links (limit)
4179 "Run through the buffer and add overlays to bracketed links."
4180 (if (re-search-forward org-bracket-link-regexp limit t)
4181 (let* ((help (concat "LINK: "
4182 (org-match-string-no-properties 1)))
4183 ;; FIXME: above we should remove the escapes.
4184 ;; but that requires another match, protecting match data,
4185 ;; a lot of overhead for font-lock.
4186 (ip (org-maybe-intangible
4187 (list 'invisible 'org-link
4188 'keymap org-mouse-map 'mouse-face 'highlight
4189 'font-lock-multiline t 'help-echo help)))
4190 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
4191 'font-lock-multiline t 'help-echo help)))
4192 ;; We need to remove the invisible property here. Table narrowing
4193 ;; may have made some of this invisible.
4194 (remove-text-properties (match-beginning 0) (match-end 0)
4195 '(invisible nil))
4196 (if (match-end 3)
4197 (progn
4198 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
4199 (org-rear-nonsticky-at (match-beginning 3))
4200 (add-text-properties (match-beginning 3) (match-end 3) vp)
4201 (org-rear-nonsticky-at (match-end 3))
4202 (add-text-properties (match-end 3) (match-end 0) ip)
4203 (org-rear-nonsticky-at (match-end 0)))
4204 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
4205 (org-rear-nonsticky-at (match-beginning 1))
4206 (add-text-properties (match-beginning 1) (match-end 1) vp)
4207 (org-rear-nonsticky-at (match-end 1))
4208 (add-text-properties (match-end 1) (match-end 0) ip)
4209 (org-rear-nonsticky-at (match-end 0)))
4210 t)))
4212 (defun org-activate-dates (limit)
4213 "Run through the buffer and add overlays to dates."
4214 (if (re-search-forward org-tsr-regexp-both limit t)
4215 (progn
4216 (add-text-properties (match-beginning 0) (match-end 0)
4217 (list 'mouse-face 'highlight
4218 'keymap org-mouse-map))
4219 (org-rear-nonsticky-at (match-end 0))
4220 (when org-display-custom-times
4221 (if (match-end 3)
4222 (org-display-custom-time (match-beginning 3) (match-end 3)))
4223 (org-display-custom-time (match-beginning 1) (match-end 1)))
4224 t)))
4226 (defvar org-target-link-regexp nil
4227 "Regular expression matching radio targets in plain text.")
4228 (make-variable-buffer-local 'org-target-link-regexp)
4229 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
4230 "Regular expression matching a link target.")
4231 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
4232 "Regular expression matching a radio target.")
4233 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
4234 "Regular expression matching any target.")
4236 (defun org-activate-target-links (limit)
4237 "Run through the buffer and add overlays to target matches."
4238 (when org-target-link-regexp
4239 (let ((case-fold-search t))
4240 (if (re-search-forward org-target-link-regexp limit t)
4241 (progn
4242 (add-text-properties (match-beginning 0) (match-end 0)
4243 (list 'mouse-face 'highlight
4244 'keymap org-mouse-map
4245 'help-echo "Radio target link"
4246 'org-linked-text t))
4247 (org-rear-nonsticky-at (match-end 0))
4248 t)))))
4250 (defun org-update-radio-target-regexp ()
4251 "Find all radio targets in this file and update the regular expression."
4252 (interactive)
4253 (when (memq 'radio org-activate-links)
4254 (setq org-target-link-regexp
4255 (org-make-target-link-regexp (org-all-targets 'radio)))
4256 (org-restart-font-lock)))
4258 (defun org-hide-wide-columns (limit)
4259 (let (s e)
4260 (setq s (text-property-any (point) (or limit (point-max))
4261 'org-cwidth t))
4262 (when s
4263 (setq e (next-single-property-change s 'org-cwidth))
4264 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
4265 (goto-char e)
4266 t)))
4268 (defvar org-latex-and-specials-regexp nil
4269 "Regular expression for highlighting export special stuff.")
4270 (defvar org-match-substring-regexp)
4271 (defvar org-match-substring-with-braces-regexp)
4272 (defvar org-export-html-special-string-regexps)
4274 (defun org-compute-latex-and-specials-regexp ()
4275 "Compute regular expression for stuff treated specially by exporters."
4276 (if (not org-highlight-latex-fragments-and-specials)
4277 (org-set-local 'org-latex-and-specials-regexp nil)
4278 (require 'org-exp)
4279 (let*
4280 ((matchers (plist-get org-format-latex-options :matchers))
4281 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
4282 org-latex-regexps)))
4283 (options (org-combine-plists (org-default-export-plist)
4284 (org-infile-export-plist)))
4285 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
4286 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
4287 (org-export-with-TeX-macros (plist-get options :TeX-macros))
4288 (org-export-html-expand (plist-get options :expand-quoted-html))
4289 (org-export-with-special-strings (plist-get options :special-strings))
4290 (re-sub
4291 (cond
4292 ((equal org-export-with-sub-superscripts '{})
4293 (list org-match-substring-with-braces-regexp))
4294 (org-export-with-sub-superscripts
4295 (list org-match-substring-regexp))
4296 (t nil)))
4297 (re-latex
4298 (if org-export-with-LaTeX-fragments
4299 (mapcar (lambda (x) (nth 1 x)) latexs)))
4300 (re-macros
4301 (if org-export-with-TeX-macros
4302 (list (concat "\\\\"
4303 (regexp-opt
4304 (append (mapcar 'car org-html-entities)
4305 (if (boundp 'org-latex-entities)
4306 org-latex-entities nil))
4307 'words))) ; FIXME
4309 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
4310 (re-special (if org-export-with-special-strings
4311 (mapcar (lambda (x) (car x))
4312 org-export-html-special-string-regexps)))
4313 (re-rest
4314 (delq nil
4315 (list
4316 (if org-export-html-expand "@<[^>\n]+>")
4317 ))))
4318 (org-set-local
4319 'org-latex-and-specials-regexp
4320 (mapconcat 'identity (append re-latex re-sub re-macros re-special
4321 re-rest) "\\|")))))
4323 (defun org-do-latex-and-special-faces (limit)
4324 "Run through the buffer and add overlays to links."
4325 (when org-latex-and-specials-regexp
4326 (let (rtn d)
4327 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
4328 limit t))
4329 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
4330 'face))
4331 '(org-code org-verbatim underline)))
4332 (progn
4333 (setq rtn t
4334 d (cond ((member (char-after (1+ (match-beginning 0)))
4335 '(?_ ?^)) 1)
4336 (t 0)))
4337 (font-lock-prepend-text-property
4338 (+ d (match-beginning 0)) (match-end 0)
4339 'face 'org-latex-and-export-specials)
4340 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
4341 '(font-lock-multiline t)))))
4342 rtn)))
4344 (defun org-restart-font-lock ()
4345 "Restart font-lock-mode, to force refontification."
4346 (when (and (boundp 'font-lock-mode) font-lock-mode)
4347 (font-lock-mode -1)
4348 (font-lock-mode 1)))
4350 (defun org-all-targets (&optional radio)
4351 "Return a list of all targets in this file.
4352 With optional argument RADIO, only find radio targets."
4353 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4354 rtn)
4355 (save-excursion
4356 (goto-char (point-min))
4357 (while (re-search-forward re nil t)
4358 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4359 rtn)))
4361 (defun org-make-target-link-regexp (targets)
4362 "Make regular expression matching all strings in TARGETS.
4363 The regular expression finds the targets also if there is a line break
4364 between words."
4365 (and targets
4366 (concat
4367 "\\<\\("
4368 (mapconcat
4369 (lambda (x)
4370 (while (string-match " +" x)
4371 (setq x (replace-match "\\s-+" t t x)))
4373 targets
4374 "\\|")
4375 "\\)\\>")))
4377 (defun org-activate-tags (limit)
4378 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
4379 (progn
4380 (add-text-properties (match-beginning 1) (match-end 1)
4381 (list 'mouse-face 'highlight
4382 'keymap org-mouse-map))
4383 (org-rear-nonsticky-at (match-end 1))
4384 t)))
4386 (defun org-outline-level ()
4387 (save-excursion
4388 (looking-at outline-regexp)
4389 (if (match-beginning 1)
4390 (+ (org-get-string-indentation (match-string 1)) 1000)
4391 (1- (- (match-end 0) (match-beginning 0))))))
4393 (defvar org-font-lock-keywords nil)
4395 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
4396 "Regular expression matching a property line.")
4398 (defvar org-font-lock-hook nil
4399 "Functions to be called for special font lock stuff.")
4401 (defun org-font-lock-hook (limit)
4402 (run-hook-with-args 'org-font-lock-hook limit))
4404 (defun org-set-font-lock-defaults ()
4405 (let* ((em org-fontify-emphasized-text)
4406 (lk org-activate-links)
4407 (org-font-lock-extra-keywords
4408 (list
4409 ;; Call the hook
4410 '(org-font-lock-hook)
4411 ;; Headlines
4412 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
4413 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
4414 ;; Table lines
4415 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4416 (1 'org-table t))
4417 ;; Table internals
4418 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4419 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4420 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4421 ;; Drawers
4422 (list org-drawer-regexp '(0 'org-special-keyword t))
4423 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4424 ;; Properties
4425 (list org-property-re
4426 '(1 'org-special-keyword t)
4427 '(3 'org-property-value t))
4428 (if org-format-transports-properties-p
4429 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
4430 ;; Links
4431 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4432 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4433 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
4434 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4435 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4436 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4437 (if (memq 'footnote lk) '(org-activate-footnote-links
4438 (2 'org-footnote t)))
4439 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4440 '(org-hide-wide-columns (0 nil append))
4441 ;; TODO lines
4442 (list (concat "^\\*+[ \t]+" org-todo-regexp "\\([ \t]\\|$\\)")
4443 '(1 (org-get-todo-face 1) t))
4444 ;; DONE
4445 (if org-fontify-done-headline
4446 (list (concat "^[*]+ +\\<\\("
4447 (mapconcat 'regexp-quote org-done-keywords "\\|")
4448 "\\)\\(.*\\)")
4449 '(2 'org-headline-done t))
4450 nil)
4451 ;; Priorities
4452 '(org-font-lock-add-priority-faces)
4453 ;; Tags
4454 '(org-font-lock-add-tag-faces)
4455 ;; Special keywords
4456 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4457 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4458 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4459 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4460 ;; Emphasis
4461 (if em
4462 (if (featurep 'xemacs)
4463 '(org-do-emphasis-faces (0 nil append))
4464 '(org-do-emphasis-faces)))
4465 ;; Checkboxes
4466 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
4467 2 'org-checkbox prepend)
4468 (if org-provide-checkbox-statistics
4469 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4470 (0 (org-get-checkbox-statistics-face) t)))
4471 ;; Description list items
4472 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
4473 2 'bold prepend)
4474 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
4475 '(1 'org-archived prepend))
4476 ;; Specials
4477 '(org-do-latex-and-special-faces)
4478 ;; Code
4479 '(org-activate-code (1 'org-code t))
4480 ;; COMMENT
4481 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
4482 "\\|" org-quote-string "\\)\\>")
4483 '(1 'org-special-keyword t))
4484 '("^#.*" (0 'font-lock-comment-face t))
4486 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
4487 ;; Now set the full font-lock-keywords
4488 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
4489 (org-set-local 'font-lock-defaults
4490 '(org-font-lock-keywords t nil nil backward-paragraph))
4491 (kill-local-variable 'font-lock-keywords) nil))
4493 (defvar org-m nil)
4494 (defvar org-l nil)
4495 (defvar org-f nil)
4496 (defun org-get-level-face (n)
4497 "Get the right face for match N in font-lock matching of headlines."
4498 (setq org-l (- (match-end 2) (match-beginning 1) 1))
4499 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
4500 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
4501 (cond
4502 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
4503 ((eq n 2) org-f)
4504 (t (if org-level-color-stars-only nil org-f))))
4506 (defun org-get-todo-face (kwd)
4507 "Get the right face for a TODO keyword KWD.
4508 If KWD is a number, get the corresponding match group."
4509 (if (numberp kwd) (setq kwd (match-string kwd)))
4510 (or (cdr (assoc kwd org-todo-keyword-faces))
4511 (and (member kwd org-done-keywords) 'org-done)
4512 'org-todo))
4514 (defun org-font-lock-add-tag-faces (limit)
4515 "Add the special tag faces."
4516 (when (and org-tag-faces org-tags-special-faces-re)
4517 (while (re-search-forward org-tags-special-faces-re limit t)
4518 (add-text-properties (match-beginning 1) (match-end 1)
4519 (list 'face (org-get-tag-face 1)
4520 'font-lock-fontified t))
4521 (backward-char 1))))
4523 (defun org-font-lock-add-priority-faces (limit)
4524 "Add the special priority faces."
4525 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
4526 (add-text-properties
4527 (match-beginning 0) (match-end 0)
4528 (list 'face (or (cdr (assoc (char-after (match-beginning 1))
4529 org-priority-faces))
4530 'org-special-keyword)
4531 'font-lock-fontified t))))
4533 (defun org-get-tag-face (kwd)
4534 "Get the right face for a TODO keyword KWD.
4535 If KWD is a number, get the corresponding match group."
4536 (if (numberp kwd) (setq kwd (match-string kwd)))
4537 (or (cdr (assoc kwd org-tag-faces))
4538 'org-tag))
4540 (defun org-unfontify-region (beg end &optional maybe_loudly)
4541 "Remove fontification and activation overlays from links."
4542 (font-lock-default-unfontify-region beg end)
4543 (let* ((buffer-undo-list t)
4544 (inhibit-read-only t) (inhibit-point-motion-hooks t)
4545 (inhibit-modification-hooks t)
4546 deactivate-mark buffer-file-name buffer-file-truename)
4547 (remove-text-properties beg end
4548 '(mouse-face t keymap t org-linked-text t
4549 invisible t intangible t))))
4551 ;;;; Visibility cycling, including org-goto and indirect buffer
4553 ;;; Cycling
4555 (defvar org-cycle-global-status nil)
4556 (make-variable-buffer-local 'org-cycle-global-status)
4557 (defvar org-cycle-subtree-status nil)
4558 (make-variable-buffer-local 'org-cycle-subtree-status)
4560 ;;;###autoload
4562 (defvar org-inlinetask-min-level)
4564 (defun org-cycle (&optional arg)
4565 "TAB-action and visibility cycling for Org-mode.
4567 This is the command invoked in Org-moe by the TAB key. It's main purpose
4568 is outine visibility cycling, but it also invokes other actions
4569 in special contexts.
4571 - When this function is called with a prefix argument, rotate the entire
4572 buffer through 3 states (global cycling)
4573 1. OVERVIEW: Show only top-level headlines.
4574 2. CONTENTS: Show all headlines of all levels, but no body text.
4575 3. SHOW ALL: Show everything.
4576 When called with two `C-u C-u' prefixes, switch to the startup visibility,
4577 determined by the variable `org-startup-folded', and by any VISIBILITY
4578 properties in the buffer.
4579 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
4580 including any drawers.
4582 - When inside a table, re-align the table and move to the next field.
4584 - When point is at the beginning of a headline, rotate the subtree started
4585 by this line through 3 different states (local cycling)
4586 1. FOLDED: Only the main headline is shown.
4587 2. CHILDREN: The main headline and the direct children are shown.
4588 From this state, you can move to one of the children
4589 and zoom in further.
4590 3. SUBTREE: Show the entire subtree, including body text.
4592 - When there is a numeric prefix, go up to a heading with level ARG, do
4593 a `show-subtree' and return to the previous cursor position. If ARG
4594 is negative, go up that many levels.
4596 - When point is not at the beginning of a headline, execute the global
4597 binding for TAB, which is re-indenting the line. See the option
4598 `org-cycle-emulate-tab' for details.
4600 - Special case: if point is at the beginning of the buffer and there is
4601 no headline in line 1, this function will act as if called with prefix arg.
4602 But only if also the variable `org-cycle-global-at-bob' is t."
4603 (interactive "P")
4604 (org-load-modules-maybe)
4605 (unless (run-hook-with-args-until-success 'org-tab-first-hook)
4606 (let* ((limit-level
4607 (or org-cycle-max-level
4608 (and (boundp 'org-inlinetask-min-level)
4609 org-inlinetask-min-level
4610 (1- org-inlinetask-min-level))))
4611 (nstars (and limit-level
4612 (if org-odd-levels-only
4613 (and limit-level (1- (* limit-level 2)))
4614 limit-level)))
4615 (outline-regexp
4616 (cond
4617 ((not (org-mode-p)) outline-regexp)
4618 (org-cycle-include-plain-lists
4619 (concat "\\(?:\\*"
4620 (if nstars (format "\\{1,%d\\} " nstars) "+")
4621 " \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"))
4622 (t (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))))
4623 (bob-special (and org-cycle-global-at-bob (bobp)
4624 (not (looking-at outline-regexp))))
4625 (org-cycle-hook
4626 (if bob-special
4627 (delq 'org-optimize-window-after-visibility-change
4628 (copy-sequence org-cycle-hook))
4629 org-cycle-hook))
4630 (pos (point)))
4632 (if (or bob-special (equal arg '(4)))
4633 ;; special case: use global cycling
4634 (setq arg t))
4636 (cond
4638 ((equal arg '(16))
4639 (org-set-startup-visibility)
4640 (message "Startup visibility, plus VISIBILITY properties"))
4642 ((equal arg '(64))
4643 (show-all)
4644 (message "Entire buffer visible, including drawers"))
4646 ((org-at-table-p 'any)
4647 ;; Enter the table or move to the next field in the table
4648 (or (org-table-recognize-table.el)
4649 (progn
4650 (if arg (org-table-edit-field t)
4651 (org-table-justify-field-maybe)
4652 (call-interactively 'org-table-next-field)))))
4654 ((run-hook-with-args-until-success
4655 'org-tab-after-check-for-table-hook))
4657 ((eq arg t) ;; Global cycling
4658 (org-cycle-internal-global))
4660 ((and org-drawers org-drawer-regexp
4661 (save-excursion
4662 (beginning-of-line 1)
4663 (looking-at org-drawer-regexp)))
4664 ;; Toggle block visibility
4665 (org-flag-drawer
4666 (not (get-char-property (match-end 0) 'invisible))))
4668 ((integerp arg)
4669 ;; Show-subtree, ARG levels up from here.
4670 (save-excursion
4671 (org-back-to-heading)
4672 (outline-up-heading (if (< arg 0) (- arg)
4673 (- (funcall outline-level) arg)))
4674 (org-show-subtree)))
4676 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4677 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4679 (org-cycle-internal-local))
4681 ;; TAB emulation and template completion
4682 (buffer-read-only (org-back-to-heading))
4684 ((run-hook-with-args-until-success
4685 'org-tab-after-check-for-cycling-hook))
4687 ((org-try-structure-completion))
4689 ((org-try-cdlatex-tab))
4691 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4692 (or (not (bolp))
4693 (not (looking-at outline-regexp))))
4694 (call-interactively (global-key-binding "\t")))
4696 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4697 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4698 (or (and (eq org-cycle-emulate-tab 'white)
4699 (= (match-end 0) (point-at-eol)))
4700 (and (eq org-cycle-emulate-tab 'whitestart)
4701 (>= (match-end 0) pos))))
4703 (eq org-cycle-emulate-tab t))
4704 (call-interactively (global-key-binding "\t")))
4706 (t (save-excursion
4707 (org-back-to-heading)
4708 (org-cycle)))))))
4710 (defun org-cycle-internal-global ()
4711 "Do the global cycling action."
4712 (cond
4713 ((and (eq last-command this-command)
4714 (eq org-cycle-global-status 'overview))
4715 ;; We just created the overview - now do table of contents
4716 ;; This can be slow in very large buffers, so indicate action
4717 (run-hook-with-args 'org-pre-cycle-hook 'contents)
4718 (message "CONTENTS...")
4719 (org-content)
4720 (message "CONTENTS...done")
4721 (setq org-cycle-global-status 'contents)
4722 (run-hook-with-args 'org-cycle-hook 'contents))
4724 ((and (eq last-command this-command)
4725 (eq org-cycle-global-status 'contents))
4726 ;; We just showed the table of contents - now show everything
4727 (run-hook-with-args 'org-pre-cycle-hook 'all)
4728 (show-all)
4729 (message "SHOW ALL")
4730 (setq org-cycle-global-status 'all)
4731 (run-hook-with-args 'org-cycle-hook 'all))
4734 ;; Default action: go to overview
4735 (run-hook-with-args 'org-pre-cycle-hook 'overview)
4736 (org-overview)
4737 (message "OVERVIEW")
4738 (setq org-cycle-global-status 'overview)
4739 (run-hook-with-args 'org-cycle-hook 'overview))))
4741 (defun org-cycle-internal-local ()
4742 "Do the local cycling action."
4743 (org-back-to-heading)
4744 (let ((goal-column 0) eoh eol eos)
4745 ;; First, some boundaries
4746 (save-excursion
4747 (org-back-to-heading)
4748 (save-excursion
4749 (beginning-of-line 2)
4750 (while (and (not (eobp)) ;; this is like `next-line'
4751 (get-char-property (1- (point)) 'invisible))
4752 (beginning-of-line 2)) (setq eol (point)))
4753 (outline-end-of-heading) (setq eoh (point))
4754 (org-end-of-subtree t)
4755 (unless (eobp)
4756 (skip-chars-forward " \t\n")
4757 (beginning-of-line 1) ; in case this is an item
4759 (setq eos (1- (point))))
4760 ;; Find out what to do next and set `this-command'
4761 (cond
4762 ((= eos eoh)
4763 ;; Nothing is hidden behind this heading
4764 (run-hook-with-args 'org-pre-cycle-hook 'empty)
4765 (message "EMPTY ENTRY")
4766 (setq org-cycle-subtree-status nil)
4767 (save-excursion
4768 (goto-char eos)
4769 (outline-next-heading)
4770 (if (org-invisible-p) (org-flag-heading nil))))
4771 ((or (>= eol eos)
4772 (not (string-match "\\S-" (buffer-substring eol eos))))
4773 ;; Entire subtree is hidden in one line: open it
4774 (run-hook-with-args 'org-pre-cycle-hook 'children)
4775 (org-show-entry)
4776 (show-children)
4777 (message "CHILDREN")
4778 (save-excursion
4779 (goto-char eos)
4780 (outline-next-heading)
4781 (if (org-invisible-p) (org-flag-heading nil)))
4782 (setq org-cycle-subtree-status 'children)
4783 (run-hook-with-args 'org-cycle-hook 'children))
4784 ((and (eq last-command this-command)
4785 (eq org-cycle-subtree-status 'children))
4786 ;; We just showed the children, now show everything.
4787 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
4788 (org-show-subtree)
4789 (message "SUBTREE")
4790 (setq org-cycle-subtree-status 'subtree)
4791 (run-hook-with-args 'org-cycle-hook 'subtree))
4793 ;; Default action: hide the subtree.
4794 (run-hook-with-args 'org-pre-cycle-hook 'folded)
4795 (hide-subtree)
4796 (message "FOLDED")
4797 (setq org-cycle-subtree-status 'folded)
4798 (run-hook-with-args 'org-cycle-hook 'folded)))))
4800 ;;;###autoload
4801 (defun org-global-cycle (&optional arg)
4802 "Cycle the global visibility. For details see `org-cycle'.
4803 With C-u prefix arg, switch to startup visibility.
4804 With a numeric prefix, show all headlines up to that level."
4805 (interactive "P")
4806 (let ((org-cycle-include-plain-lists
4807 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4808 (cond
4809 ((integerp arg)
4810 (show-all)
4811 (hide-sublevels arg)
4812 (setq org-cycle-global-status 'contents))
4813 ((equal arg '(4))
4814 (org-set-startup-visibility)
4815 (message "Startup visibility, plus VISIBILITY properties."))
4817 (org-cycle '(4))))))
4819 (defun org-set-startup-visibility ()
4820 "Set the visibility required by startup options and properties."
4821 (cond
4822 ((eq org-startup-folded t)
4823 (org-cycle '(4)))
4824 ((eq org-startup-folded 'content)
4825 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4826 (org-cycle '(4)) (org-cycle '(4)))))
4827 (org-set-visibility-according-to-property 'no-cleanup)
4828 (org-cycle-hide-archived-subtrees 'all)
4829 (org-cycle-hide-drawers 'all)
4830 (org-cycle-show-empty-lines 'all))
4832 (defun org-set-visibility-according-to-property (&optional no-cleanup)
4833 "Switch subtree visibilities according to :VISIBILITY: property."
4834 (interactive)
4835 (let (org-show-entry-below state)
4836 (save-excursion
4837 (goto-char (point-min))
4838 (while (re-search-forward
4839 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
4840 nil t)
4841 (setq state (match-string 1))
4842 (save-excursion
4843 (org-back-to-heading t)
4844 (hide-subtree)
4845 (org-reveal)
4846 (cond
4847 ((equal state '("fold" "folded"))
4848 (hide-subtree))
4849 ((equal state "children")
4850 (org-show-hidden-entry)
4851 (show-children))
4852 ((equal state "content")
4853 (save-excursion
4854 (save-restriction
4855 (org-narrow-to-subtree)
4856 (org-content))))
4857 ((member state '("all" "showall"))
4858 (show-subtree)))))
4859 (unless no-cleanup
4860 (org-cycle-hide-archived-subtrees 'all)
4861 (org-cycle-hide-drawers 'all)
4862 (org-cycle-show-empty-lines 'all)))))
4864 (defun org-overview ()
4865 "Switch to overview mode, showing only top-level headlines.
4866 Really, this shows all headlines with level equal or greater than the level
4867 of the first headline in the buffer. This is important, because if the
4868 first headline is not level one, then (hide-sublevels 1) gives confusing
4869 results."
4870 (interactive)
4871 (let ((level (save-excursion
4872 (goto-char (point-min))
4873 (if (re-search-forward (concat "^" outline-regexp) nil t)
4874 (progn
4875 (goto-char (match-beginning 0))
4876 (funcall outline-level))))))
4877 (and level (hide-sublevels level))))
4879 (defun org-content (&optional arg)
4880 "Show all headlines in the buffer, like a table of contents.
4881 With numerical argument N, show content up to level N."
4882 (interactive "P")
4883 (save-excursion
4884 ;; Visit all headings and show their offspring
4885 (and (integerp arg) (org-overview))
4886 (goto-char (point-max))
4887 (catch 'exit
4888 (while (and (progn (condition-case nil
4889 (outline-previous-visible-heading 1)
4890 (error (goto-char (point-min))))
4892 (looking-at outline-regexp))
4893 (if (integerp arg)
4894 (show-children (1- arg))
4895 (show-branches))
4896 (if (bobp) (throw 'exit nil))))))
4899 (defun org-optimize-window-after-visibility-change (state)
4900 "Adjust the window after a change in outline visibility.
4901 This function is the default value of the hook `org-cycle-hook'."
4902 (when (get-buffer-window (current-buffer))
4903 (cond
4904 ((eq state 'content) nil)
4905 ((eq state 'all) nil)
4906 ((eq state 'folded) nil)
4907 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4908 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4910 (defun org-compact-display-after-subtree-move ()
4911 "Show a compacter version of the tree of the entry's parent."
4912 (save-excursion
4913 (if (org-up-heading-safe)
4914 (progn
4915 (hide-subtree)
4916 (show-entry)
4917 (show-children)
4918 (org-cycle-show-empty-lines 'children)
4919 (org-cycle-hide-drawers 'children))
4920 (org-overview))))
4922 (defun org-cycle-show-empty-lines (state)
4923 "Show empty lines above all visible headlines.
4924 The region to be covered depends on STATE when called through
4925 `org-cycle-hook'. Lisp program can use t for STATE to get the
4926 entire buffer covered. Note that an empty line is only shown if there
4927 are at least `org-cycle-separator-lines' empty lines before the headline."
4928 (when (> org-cycle-separator-lines 0)
4929 (save-excursion
4930 (let* ((n org-cycle-separator-lines)
4931 (re (cond
4932 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
4933 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
4934 (t (let ((ns (number-to-string (- n 2))))
4935 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
4936 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
4937 beg end)
4938 (cond
4939 ((memq state '(overview contents t))
4940 (setq beg (point-min) end (point-max)))
4941 ((memq state '(children folded))
4942 (setq beg (point) end (progn (org-end-of-subtree t t)
4943 (beginning-of-line 2)
4944 (point)))))
4945 (when beg
4946 (goto-char beg)
4947 (while (re-search-forward re end t)
4948 (if (not (get-char-property (match-end 1) 'invisible))
4949 (outline-flag-region
4950 (match-beginning 1) (match-end 1) nil)))))))
4951 ;; Never hide empty lines at the end of the file.
4952 (save-excursion
4953 (goto-char (point-max))
4954 (outline-previous-heading)
4955 (outline-end-of-heading)
4956 (if (and (looking-at "[ \t\n]+")
4957 (= (match-end 0) (point-max)))
4958 (outline-flag-region (point) (match-end 0) nil))))
4960 (defun org-show-empty-lines-in-parent ()
4961 "Move to the parent and re-show empty lines before visible headlines."
4962 (save-excursion
4963 (let ((context (if (org-up-heading-safe) 'children 'overview)))
4964 (org-cycle-show-empty-lines context))))
4966 (defun org-cycle-hide-drawers (state)
4967 "Re-hide all drawers after a visibility state change."
4968 (when (and (org-mode-p)
4969 (not (memq state '(overview folded))))
4970 (save-excursion
4971 (let* ((globalp (memq state '(contents all)))
4972 (beg (if globalp (point-min) (point)))
4973 (end (if globalp (point-max) (org-end-of-subtree t))))
4974 (goto-char beg)
4975 (while (re-search-forward org-drawer-regexp end t)
4976 (org-flag-drawer t))))))
4978 (defun org-flag-drawer (flag)
4979 (save-excursion
4980 (beginning-of-line 1)
4981 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
4982 (let ((b (match-end 0))
4983 (outline-regexp org-outline-regexp))
4984 (if (re-search-forward
4985 "^[ \t]*:END:"
4986 (save-excursion (outline-next-heading) (point)) t)
4987 (outline-flag-region b (point-at-eol) flag)
4988 (error ":END: line missing"))))))
4990 (defun org-subtree-end-visible-p ()
4991 "Is the end of the current subtree visible?"
4992 (pos-visible-in-window-p
4993 (save-excursion (org-end-of-subtree t) (point))))
4995 (defun org-first-headline-recenter (&optional N)
4996 "Move cursor to the first headline and recenter the headline.
4997 Optional argument N means, put the headline into the Nth line of the window."
4998 (goto-char (point-min))
4999 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5000 (beginning-of-line)
5001 (recenter (prefix-numeric-value N))))
5003 ;;; Org-goto
5005 (defvar org-goto-window-configuration nil)
5006 (defvar org-goto-marker nil)
5007 (defvar org-goto-map
5008 (let ((map (make-sparse-keymap)))
5009 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
5010 (while (setq cmd (pop cmds))
5011 (substitute-key-definition cmd cmd map global-map)))
5012 (suppress-keymap map)
5013 (org-defkey map "\C-m" 'org-goto-ret)
5014 (org-defkey map [(return)] 'org-goto-ret)
5015 (org-defkey map [(left)] 'org-goto-left)
5016 (org-defkey map [(right)] 'org-goto-right)
5017 (org-defkey map [(control ?g)] 'org-goto-quit)
5018 (org-defkey map "\C-i" 'org-cycle)
5019 (org-defkey map [(tab)] 'org-cycle)
5020 (org-defkey map [(down)] 'outline-next-visible-heading)
5021 (org-defkey map [(up)] 'outline-previous-visible-heading)
5022 (if org-goto-auto-isearch
5023 (if (fboundp 'define-key-after)
5024 (define-key-after map [t] 'org-goto-local-auto-isearch)
5025 nil)
5026 (org-defkey map "q" 'org-goto-quit)
5027 (org-defkey map "n" 'outline-next-visible-heading)
5028 (org-defkey map "p" 'outline-previous-visible-heading)
5029 (org-defkey map "f" 'outline-forward-same-level)
5030 (org-defkey map "b" 'outline-backward-same-level)
5031 (org-defkey map "u" 'outline-up-heading))
5032 (org-defkey map "/" 'org-occur)
5033 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
5034 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
5035 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
5036 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
5037 (org-defkey map "\C-c\C-u" 'outline-up-heading)
5038 map))
5040 (defconst org-goto-help
5041 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
5042 RET=jump to location [Q]uit and return to previous location
5043 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
5045 (defvar org-goto-start-pos) ; dynamically scoped parameter
5047 ;; FIXME: Docstring doe not mention both interfaces
5048 (defun org-goto (&optional alternative-interface)
5049 "Look up a different location in the current file, keeping current visibility.
5051 When you want look-up or go to a different location in a document, the
5052 fastest way is often to fold the entire buffer and then dive into the tree.
5053 This method has the disadvantage, that the previous location will be folded,
5054 which may not be what you want.
5056 This command works around this by showing a copy of the current buffer
5057 in an indirect buffer, in overview mode. You can dive into the tree in
5058 that copy, use org-occur and incremental search to find a location.
5059 When pressing RET or `Q', the command returns to the original buffer in
5060 which the visibility is still unchanged. After RET is will also jump to
5061 the location selected in the indirect buffer and expose the
5062 the headline hierarchy above."
5063 (interactive "P")
5064 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
5065 (org-refile-use-outline-path t)
5066 (org-refile-target-verify-function nil)
5067 (interface
5068 (if (not alternative-interface)
5069 org-goto-interface
5070 (if (eq org-goto-interface 'outline)
5071 'outline-path-completion
5072 'outline)))
5073 (org-goto-start-pos (point))
5074 (selected-point
5075 (if (eq interface 'outline)
5076 (car (org-get-location (current-buffer) org-goto-help))
5077 (nth 3 (org-refile-get-location "Goto: ")))))
5078 (if selected-point
5079 (progn
5080 (org-mark-ring-push org-goto-start-pos)
5081 (goto-char selected-point)
5082 (if (or (org-invisible-p) (org-invisible-p2))
5083 (org-show-context 'org-goto)))
5084 (message "Quit"))))
5086 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
5087 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
5088 (defvar org-goto-local-auto-isearch-map) ; defined below
5090 (defun org-get-location (buf help)
5091 "Let the user select a location in the Org-mode buffer BUF.
5092 This function uses a recursive edit. It returns the selected position
5093 or nil."
5094 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
5095 (isearch-hide-immediately nil)
5096 (isearch-search-fun-function
5097 (lambda () 'org-goto-local-search-headings))
5098 (org-goto-selected-point org-goto-exit-command))
5099 (save-excursion
5100 (save-window-excursion
5101 (delete-other-windows)
5102 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
5103 (switch-to-buffer
5104 (condition-case nil
5105 (make-indirect-buffer (current-buffer) "*org-goto*")
5106 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
5107 (with-output-to-temp-buffer "*Help*"
5108 (princ help))
5109 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
5110 (setq buffer-read-only nil)
5111 (let ((org-startup-truncated t)
5112 (org-startup-folded nil)
5113 (org-startup-align-all-tables nil))
5114 (org-mode)
5115 (org-overview))
5116 (setq buffer-read-only t)
5117 (if (and (boundp 'org-goto-start-pos)
5118 (integer-or-marker-p org-goto-start-pos))
5119 (let ((org-show-hierarchy-above t)
5120 (org-show-siblings t)
5121 (org-show-following-heading t))
5122 (goto-char org-goto-start-pos)
5123 (and (org-invisible-p) (org-show-context)))
5124 (goto-char (point-min)))
5125 (let (org-special-ctrl-a/e) (org-beginning-of-line))
5126 (message "Select location and press RET")
5127 (use-local-map org-goto-map)
5128 (recursive-edit)
5130 (kill-buffer "*org-goto*")
5131 (cons org-goto-selected-point org-goto-exit-command)))
5133 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
5134 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
5135 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
5136 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
5138 (defun org-goto-local-search-headings (string bound noerror)
5139 "Search and make sure that any matches are in headlines."
5140 (catch 'return
5141 (while (if isearch-forward
5142 (search-forward string bound noerror)
5143 (search-backward string bound noerror))
5144 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
5145 (and (member :headline context)
5146 (not (member :tags context))))
5147 (throw 'return (point))))))
5149 (defun org-goto-local-auto-isearch ()
5150 "Start isearch."
5151 (interactive)
5152 (goto-char (point-min))
5153 (let ((keys (this-command-keys)))
5154 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
5155 (isearch-mode t)
5156 (isearch-process-search-char (string-to-char keys)))))
5158 (defun org-goto-ret (&optional arg)
5159 "Finish `org-goto' by going to the new location."
5160 (interactive "P")
5161 (setq org-goto-selected-point (point)
5162 org-goto-exit-command 'return)
5163 (throw 'exit nil))
5165 (defun org-goto-left ()
5166 "Finish `org-goto' by going to the new location."
5167 (interactive)
5168 (if (org-on-heading-p)
5169 (progn
5170 (beginning-of-line 1)
5171 (setq org-goto-selected-point (point)
5172 org-goto-exit-command 'left)
5173 (throw 'exit nil))
5174 (error "Not on a heading")))
5176 (defun org-goto-right ()
5177 "Finish `org-goto' by going to the new location."
5178 (interactive)
5179 (if (org-on-heading-p)
5180 (progn
5181 (setq org-goto-selected-point (point)
5182 org-goto-exit-command 'right)
5183 (throw 'exit nil))
5184 (error "Not on a heading")))
5186 (defun org-goto-quit ()
5187 "Finish `org-goto' without cursor motion."
5188 (interactive)
5189 (setq org-goto-selected-point nil)
5190 (setq org-goto-exit-command 'quit)
5191 (throw 'exit nil))
5193 ;;; Indirect buffer display of subtrees
5195 (defvar org-indirect-dedicated-frame nil
5196 "This is the frame being used for indirect tree display.")
5197 (defvar org-last-indirect-buffer nil)
5199 (defun org-tree-to-indirect-buffer (&optional arg)
5200 "Create indirect buffer and narrow it to current subtree.
5201 With numerical prefix ARG, go up to this level and then take that tree.
5202 If ARG is negative, go up that many levels.
5203 If `org-indirect-buffer-display' is not `new-frame', the command removes the
5204 indirect buffer previously made with this command, to avoid proliferation of
5205 indirect buffers. However, when you call the command with a `C-u' prefix, or
5206 when `org-indirect-buffer-display' is `new-frame', the last buffer
5207 is kept so that you can work with several indirect buffers at the same time.
5208 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
5209 requests that a new frame be made for the new buffer, so that the dedicated
5210 frame is not changed."
5211 (interactive "P")
5212 (let ((cbuf (current-buffer))
5213 (cwin (selected-window))
5214 (pos (point))
5215 beg end level heading ibuf)
5216 (save-excursion
5217 (org-back-to-heading t)
5218 (when (numberp arg)
5219 (setq level (org-outline-level))
5220 (if (< arg 0) (setq arg (+ level arg)))
5221 (while (> (setq level (org-outline-level)) arg)
5222 (outline-up-heading 1 t)))
5223 (setq beg (point)
5224 heading (org-get-heading))
5225 (org-end-of-subtree t) (setq end (point)))
5226 (if (and (buffer-live-p org-last-indirect-buffer)
5227 (not (eq org-indirect-buffer-display 'new-frame))
5228 (not arg))
5229 (kill-buffer org-last-indirect-buffer))
5230 (setq ibuf (org-get-indirect-buffer cbuf)
5231 org-last-indirect-buffer ibuf)
5232 (cond
5233 ((or (eq org-indirect-buffer-display 'new-frame)
5234 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
5235 (select-frame (make-frame))
5236 (delete-other-windows)
5237 (switch-to-buffer ibuf)
5238 (org-set-frame-title heading))
5239 ((eq org-indirect-buffer-display 'dedicated-frame)
5240 (raise-frame
5241 (select-frame (or (and org-indirect-dedicated-frame
5242 (frame-live-p org-indirect-dedicated-frame)
5243 org-indirect-dedicated-frame)
5244 (setq org-indirect-dedicated-frame (make-frame)))))
5245 (delete-other-windows)
5246 (switch-to-buffer ibuf)
5247 (org-set-frame-title (concat "Indirect: " heading)))
5248 ((eq org-indirect-buffer-display 'current-window)
5249 (switch-to-buffer ibuf))
5250 ((eq org-indirect-buffer-display 'other-window)
5251 (pop-to-buffer ibuf))
5252 (t (error "Invalid value.")))
5253 (if (featurep 'xemacs)
5254 (save-excursion (org-mode) (turn-on-font-lock)))
5255 (narrow-to-region beg end)
5256 (show-all)
5257 (goto-char pos)
5258 (and (window-live-p cwin) (select-window cwin))))
5260 (defun org-get-indirect-buffer (&optional buffer)
5261 (setq buffer (or buffer (current-buffer)))
5262 (let ((n 1) (base (buffer-name buffer)) bname)
5263 (while (buffer-live-p
5264 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
5265 (setq n (1+ n)))
5266 (condition-case nil
5267 (make-indirect-buffer buffer bname 'clone)
5268 (error (make-indirect-buffer buffer bname)))))
5270 (defun org-set-frame-title (title)
5271 "Set the title of the current frame to the string TITLE."
5272 ;; FIXME: how to name a single frame in XEmacs???
5273 (unless (featurep 'xemacs)
5274 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
5276 ;;;; Structure editing
5278 ;;; Inserting headlines
5280 (defun org-previous-line-empty-p ()
5281 (save-excursion
5282 (and (not (bobp))
5283 (or (beginning-of-line 0) t)
5284 (save-match-data
5285 (looking-at "[ \t]*$")))))
5287 (defun org-insert-heading (&optional force-heading)
5288 "Insert a new heading or item with same depth at point.
5289 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
5290 If point is at the beginning of a headline, insert a sibling before the
5291 current headline. If point is not at the beginning, do not split the line,
5292 but create the new headline after the current line."
5293 (interactive "P")
5294 (if (= (buffer-size) 0)
5295 (insert "\n* ")
5296 (when (or force-heading (not (org-insert-item)))
5297 (let* ((empty-line-p nil)
5298 (head (save-excursion
5299 (condition-case nil
5300 (progn
5301 (org-back-to-heading)
5302 (setq empty-line-p (org-previous-line-empty-p))
5303 (match-string 0))
5304 (error "*"))))
5305 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
5306 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
5307 pos hide-previous previous-pos)
5308 (cond
5309 ((and (org-on-heading-p) (bolp)
5310 (or (bobp)
5311 (save-excursion (backward-char 1) (not (org-invisible-p)))))
5312 ;; insert before the current line
5313 (open-line (if blank 2 1)))
5314 ((and (bolp)
5315 (or (bobp)
5316 (save-excursion
5317 (backward-char 1) (not (org-invisible-p)))))
5318 ;; insert right here
5319 nil)
5321 ;; somewhere in the line
5322 (save-excursion
5323 (setq previous-pos (point-at-bol))
5324 (end-of-line)
5325 (setq hide-previous (org-invisible-p)))
5326 (and org-insert-heading-respect-content (org-show-subtree))
5327 (let ((split
5328 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
5329 (save-excursion
5330 (let ((p (point)))
5331 (goto-char (point-at-bol))
5332 (and (looking-at org-complex-heading-regexp)
5333 (> p (match-beginning 4)))))))
5334 tags pos)
5335 (cond
5336 (org-insert-heading-respect-content
5337 (org-end-of-subtree nil t)
5338 (or (bolp) (newline))
5339 (or (org-previous-line-empty-p)
5340 (and blank (newline)))
5341 (open-line 1))
5342 ((org-on-heading-p)
5343 (when hide-previous
5344 (show-children)
5345 (org-show-entry))
5346 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
5347 (setq tags (and (match-end 2) (match-string 2)))
5348 (and (match-end 1)
5349 (delete-region (match-beginning 1) (match-end 1)))
5350 (setq pos (point-at-bol))
5351 (or split (end-of-line 1))
5352 (delete-horizontal-space)
5353 (newline (if blank 2 1))
5354 (when tags
5355 (save-excursion
5356 (goto-char pos)
5357 (end-of-line 1)
5358 (insert " " tags)
5359 (org-set-tags nil 'align))))
5361 (or split (end-of-line 1))
5362 (newline (if blank 2 1)))))))
5363 (insert head) (just-one-space)
5364 (setq pos (point))
5365 (end-of-line 1)
5366 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
5367 (when (and org-insert-heading-respect-content hide-previous)
5368 (save-excursion
5369 (goto-char previous-pos)
5370 (hide-subtree)))
5371 (run-hooks 'org-insert-heading-hook)))))
5373 (defun org-get-heading (&optional no-tags)
5374 "Return the heading of the current entry, without the stars."
5375 (save-excursion
5376 (org-back-to-heading t)
5377 (if (looking-at
5378 (if no-tags
5379 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
5380 "\\*+[ \t]+\\([^\r\n]*\\)"))
5381 (match-string 1) "")))
5383 (defun org-heading-components ()
5384 "Return the components of the current heading.
5385 This is a list with the following elements:
5386 - the level as an integer
5387 - the reduced level, different if `org-odd-levels-only' is set.
5388 - the TODO keyword, or nil
5389 - the priority character, like ?A, or nil if no priority is given
5390 - the headline text itself, or the tags string if no headline text
5391 - the tags string, or nil."
5392 (save-excursion
5393 (org-back-to-heading t)
5394 (if (looking-at org-complex-heading-regexp)
5395 (list (length (match-string 1))
5396 (org-reduced-level (length (match-string 1)))
5397 (org-match-string-no-properties 2)
5398 (and (match-end 3) (aref (match-string 3) 2))
5399 (org-match-string-no-properties 4)
5400 (org-match-string-no-properties 5)))))
5402 (defun org-get-entry ()
5403 "Get the entry text, after heading, entire subtree."
5404 (save-excursion
5405 (org-back-to-heading t)
5406 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
5408 (defun org-insert-heading-after-current ()
5409 "Insert a new heading with same level as current, after current subtree."
5410 (interactive)
5411 (org-back-to-heading)
5412 (org-insert-heading)
5413 (org-move-subtree-down)
5414 (end-of-line 1))
5416 (defun org-insert-heading-respect-content ()
5417 (interactive)
5418 (let ((org-insert-heading-respect-content t))
5419 (org-insert-heading t)))
5421 (defun org-insert-todo-heading-respect-content (&optional force-state)
5422 (interactive "P")
5423 (let ((org-insert-heading-respect-content t))
5424 (org-insert-todo-heading force-state t)))
5426 (defun org-insert-todo-heading (arg &optional force-heading)
5427 "Insert a new heading with the same level and TODO state as current heading.
5428 If the heading has no TODO state, or if the state is DONE, use the first
5429 state (TODO by default). Also with prefix arg, force first state."
5430 (interactive "P")
5431 (when (or force-heading (not (org-insert-item 'checkbox)))
5432 (org-insert-heading force-heading)
5433 (save-excursion
5434 (org-back-to-heading)
5435 (outline-previous-heading)
5436 (looking-at org-todo-line-regexp))
5437 (let*
5438 ((new-mark-x
5439 (if (or arg
5440 (not (match-beginning 2))
5441 (member (match-string 2) org-done-keywords))
5442 (car org-todo-keywords-1)
5443 (match-string 2)))
5444 (new-mark
5446 (run-hook-with-args-until-success
5447 'org-todo-get-default-hook new-mark-x nil)
5448 new-mark-x)))
5449 (beginning-of-line 1)
5450 (and (looking-at "\\*+ ") (goto-char (match-end 0))
5451 (insert new-mark " ")))
5452 (when org-provide-todo-statistics
5453 (org-update-parent-todo-statistics))))
5455 (defun org-insert-subheading (arg)
5456 "Insert a new subheading and demote it.
5457 Works for outline headings and for plain lists alike."
5458 (interactive "P")
5459 (org-insert-heading arg)
5460 (cond
5461 ((org-on-heading-p) (org-do-demote))
5462 ((org-at-item-p) (org-indent-item 1))))
5464 (defun org-insert-todo-subheading (arg)
5465 "Insert a new subheading with TODO keyword or checkbox and demote it.
5466 Works for outline headings and for plain lists alike."
5467 (interactive "P")
5468 (org-insert-todo-heading arg)
5469 (cond
5470 ((org-on-heading-p) (org-do-demote))
5471 ((org-at-item-p) (org-indent-item 1))))
5473 ;;; Promotion and Demotion
5475 (defun org-promote-subtree ()
5476 "Promote the entire subtree.
5477 See also `org-promote'."
5478 (interactive)
5479 (save-excursion
5480 (org-map-tree 'org-promote))
5481 (org-fix-position-after-promote))
5483 (defun org-demote-subtree ()
5484 "Demote the entire subtree. See `org-demote'.
5485 See also `org-promote'."
5486 (interactive)
5487 (save-excursion
5488 (org-map-tree 'org-demote))
5489 (org-fix-position-after-promote))
5492 (defun org-do-promote ()
5493 "Promote the current heading higher up the tree.
5494 If the region is active in `transient-mark-mode', promote all headings
5495 in the region."
5496 (interactive)
5497 (save-excursion
5498 (if (org-region-active-p)
5499 (org-map-region 'org-promote (region-beginning) (region-end))
5500 (org-promote)))
5501 (org-fix-position-after-promote))
5503 (defun org-do-demote ()
5504 "Demote the current heading lower down the tree.
5505 If the region is active in `transient-mark-mode', demote all headings
5506 in the region."
5507 (interactive)
5508 (save-excursion
5509 (if (org-region-active-p)
5510 (org-map-region 'org-demote (region-beginning) (region-end))
5511 (org-demote)))
5512 (org-fix-position-after-promote))
5514 (defun org-fix-position-after-promote ()
5515 "Make sure that after pro/demotion cursor position is right."
5516 (let ((pos (point)))
5517 (when (save-excursion
5518 (beginning-of-line 1)
5519 (looking-at org-todo-line-regexp)
5520 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
5521 (cond ((eobp) (insert " "))
5522 ((eolp) (insert " "))
5523 ((equal (char-after) ?\ ) (forward-char 1))))))
5525 (defun org-reduced-level (l)
5526 "Compute the effective level of a heading.
5527 This takes into account the setting of `org-odd-levels-only'."
5528 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
5530 (defun org-get-valid-level (level &optional change)
5531 "Rectify a level change under the influence of `org-odd-levels-only'
5532 LEVEL is a current level, CHANGE is by how much the level should be
5533 modified. Even if CHANGE is nil, LEVEL may be returned modified because
5534 even level numbers will become the next higher odd number."
5535 (if org-odd-levels-only
5536 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
5537 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
5538 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
5539 (max 1 (+ level (or change 0)))))
5541 (if (boundp 'define-obsolete-function-alias)
5542 (if (or (featurep 'xemacs) (< emacs-major-version 23))
5543 (define-obsolete-function-alias 'org-get-legal-level
5544 'org-get-valid-level)
5545 (define-obsolete-function-alias 'org-get-legal-level
5546 'org-get-valid-level "23.1")))
5548 (defun org-promote ()
5549 "Promote the current heading higher up the tree.
5550 If the region is active in `transient-mark-mode', promote all headings
5551 in the region."
5552 (org-back-to-heading t)
5553 (let* ((level (save-match-data (funcall outline-level)))
5554 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
5555 (diff (abs (- level (length up-head) -1))))
5556 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
5557 (replace-match up-head nil t)
5558 ;; Fixup tag positioning
5559 (and org-auto-align-tags (org-set-tags nil t))
5560 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
5562 (defun org-demote ()
5563 "Demote the current heading lower down the tree.
5564 If the region is active in `transient-mark-mode', demote all headings
5565 in the region."
5566 (org-back-to-heading t)
5567 (let* ((level (save-match-data (funcall outline-level)))
5568 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
5569 (diff (abs (- level (length down-head) -1))))
5570 (replace-match down-head nil t)
5571 ;; Fixup tag positioning
5572 (and org-auto-align-tags (org-set-tags nil t))
5573 (if org-adapt-indentation (org-fixup-indentation diff))))
5575 (defun org-map-tree (fun)
5576 "Call FUN for every heading underneath the current one."
5577 (org-back-to-heading)
5578 (let ((level (funcall outline-level)))
5579 (save-excursion
5580 (funcall fun)
5581 (while (and (progn
5582 (outline-next-heading)
5583 (> (funcall outline-level) level))
5584 (not (eobp)))
5585 (funcall fun)))))
5587 (defun org-map-region (fun beg end)
5588 "Call FUN for every heading between BEG and END."
5589 (let ((org-ignore-region t))
5590 (save-excursion
5591 (setq end (copy-marker end))
5592 (goto-char beg)
5593 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
5594 (< (point) end))
5595 (funcall fun))
5596 (while (and (progn
5597 (outline-next-heading)
5598 (< (point) end))
5599 (not (eobp)))
5600 (funcall fun)))))
5602 (defun org-fixup-indentation (diff)
5603 "Change the indentation in the current entry by DIFF
5604 However, if any line in the current entry has no indentation, or if it
5605 would end up with no indentation after the change, nothing at all is done."
5606 (save-excursion
5607 (let ((end (save-excursion (outline-next-heading)
5608 (point-marker)))
5609 (prohibit (if (> diff 0)
5610 "^\\S-"
5611 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
5612 col)
5613 (unless (save-excursion (end-of-line 1)
5614 (re-search-forward prohibit end t))
5615 (while (and (< (point) end)
5616 (re-search-forward "^[ \t]+" end t))
5617 (goto-char (match-end 0))
5618 (setq col (current-column))
5619 (if (< diff 0) (replace-match ""))
5620 (org-indent-to-column (+ diff col))))
5621 (move-marker end nil))))
5623 (defun org-convert-to-odd-levels ()
5624 "Convert an org-mode file with all levels allowed to one with odd levels.
5625 This will leave level 1 alone, convert level 2 to level 3, level 3 to
5626 level 5 etc."
5627 (interactive)
5628 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
5629 (let ((org-odd-levels-only nil) n)
5630 (save-excursion
5631 (goto-char (point-min))
5632 (while (re-search-forward "^\\*\\*+ " nil t)
5633 (setq n (- (length (match-string 0)) 2))
5634 (while (>= (setq n (1- n)) 0)
5635 (org-demote))
5636 (end-of-line 1))))))
5639 (defun org-convert-to-oddeven-levels ()
5640 "Convert an org-mode file with only odd levels to one with odd and even levels.
5641 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
5642 section with an even level, conversion would destroy the structure of the file. An error
5643 is signaled in this case."
5644 (interactive)
5645 (goto-char (point-min))
5646 ;; First check if there are no even levels
5647 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
5648 (org-show-context t)
5649 (error "Not all levels are odd in this file. Conversion not possible."))
5650 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
5651 (let ((org-odd-levels-only nil) n)
5652 (save-excursion
5653 (goto-char (point-min))
5654 (while (re-search-forward "^\\*\\*+ " nil t)
5655 (setq n (/ (1- (length (match-string 0))) 2))
5656 (while (>= (setq n (1- n)) 0)
5657 (org-promote))
5658 (end-of-line 1))))))
5660 (defun org-tr-level (n)
5661 "Make N odd if required."
5662 (if org-odd-levels-only (1+ (/ n 2)) n))
5664 ;;; Vertical tree motion, cutting and pasting of subtrees
5666 (defun org-move-subtree-up (&optional arg)
5667 "Move the current subtree up past ARG headlines of the same level."
5668 (interactive "p")
5669 (org-move-subtree-down (- (prefix-numeric-value arg))))
5671 (defun org-move-subtree-down (&optional arg)
5672 "Move the current subtree down past ARG headlines of the same level."
5673 (interactive "p")
5674 (setq arg (prefix-numeric-value arg))
5675 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
5676 'outline-get-last-sibling))
5677 (ins-point (make-marker))
5678 (cnt (abs arg))
5679 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
5680 ;; Select the tree
5681 (org-back-to-heading)
5682 (setq beg0 (point))
5683 (save-excursion
5684 (setq ne-beg (org-back-over-empty-lines))
5685 (setq beg (point)))
5686 (save-match-data
5687 (save-excursion (outline-end-of-heading)
5688 (setq folded (org-invisible-p)))
5689 (outline-end-of-subtree))
5690 (outline-next-heading)
5691 (setq ne-end (org-back-over-empty-lines))
5692 (setq end (point))
5693 (goto-char beg0)
5694 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
5695 ;; include less whitespace
5696 (save-excursion
5697 (goto-char beg)
5698 (forward-line (- ne-beg ne-end))
5699 (setq beg (point))))
5700 ;; Find insertion point, with error handling
5701 (while (> cnt 0)
5702 (or (and (funcall movfunc) (looking-at outline-regexp))
5703 (progn (goto-char beg0)
5704 (error "Cannot move past superior level or buffer limit")))
5705 (setq cnt (1- cnt)))
5706 (if (> arg 0)
5707 ;; Moving forward - still need to move over subtree
5708 (progn (org-end-of-subtree t t)
5709 (save-excursion
5710 (org-back-over-empty-lines)
5711 (or (bolp) (newline)))))
5712 (setq ne-ins (org-back-over-empty-lines))
5713 (move-marker ins-point (point))
5714 (setq txt (buffer-substring beg end))
5715 (org-save-markers-in-region beg end)
5716 (delete-region beg end)
5717 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
5718 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
5719 (and (not (bolp)) (looking-at "\n") (forward-char 1))
5720 (let ((bbb (point)))
5721 (insert-before-markers txt)
5722 (org-reinstall-markers-in-region bbb)
5723 (move-marker ins-point bbb))
5724 (or (bolp) (insert "\n"))
5725 (setq ins-end (point))
5726 (goto-char ins-point)
5727 (org-skip-whitespace)
5728 (when (and (< arg 0)
5729 (org-first-sibling-p)
5730 (> ne-ins ne-beg))
5731 ;; Move whitespace back to beginning
5732 (save-excursion
5733 (goto-char ins-end)
5734 (let ((kill-whole-line t))
5735 (kill-line (- ne-ins ne-beg)) (point)))
5736 (insert (make-string (- ne-ins ne-beg) ?\n)))
5737 (move-marker ins-point nil)
5738 (org-compact-display-after-subtree-move)
5739 (org-show-empty-lines-in-parent)
5740 (unless folded
5741 (org-show-entry)
5742 (show-children)
5743 (org-cycle-hide-drawers 'children))))
5745 (defvar org-subtree-clip ""
5746 "Clipboard for cut and paste of subtrees.
5747 This is actually only a copy of the kill, because we use the normal kill
5748 ring. We need it to check if the kill was created by `org-copy-subtree'.")
5750 (defvar org-subtree-clip-folded nil
5751 "Was the last copied subtree folded?
5752 This is used to fold the tree back after pasting.")
5754 (defun org-cut-subtree (&optional n)
5755 "Cut the current subtree into the clipboard.
5756 With prefix arg N, cut this many sequential subtrees.
5757 This is a short-hand for marking the subtree and then cutting it."
5758 (interactive "p")
5759 (org-copy-subtree n 'cut))
5761 (defun org-copy-subtree (&optional n cut force-store-markers)
5762 "Cut the current subtree into the clipboard.
5763 With prefix arg N, cut this many sequential subtrees.
5764 This is a short-hand for marking the subtree and then copying it.
5765 If CUT is non-nil, actually cut the subtree.
5766 If FORCE-STORE-MARKERS is non-nil, store the relative locations
5767 of some markers in the region, even if CUT is non-nil. This is
5768 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
5769 (interactive "p")
5770 (let (beg end folded (beg0 (point)))
5771 (if (interactive-p)
5772 (org-back-to-heading nil) ; take what looks like a subtree
5773 (org-back-to-heading t)) ; take what is really there
5774 (org-back-over-empty-lines)
5775 (setq beg (point))
5776 (skip-chars-forward " \t\r\n")
5777 (save-match-data
5778 (save-excursion (outline-end-of-heading)
5779 (setq folded (org-invisible-p)))
5780 (condition-case nil
5781 (outline-forward-same-level (1- n))
5782 (error nil))
5783 (org-end-of-subtree t t))
5784 (org-back-over-empty-lines)
5785 (setq end (point))
5786 (goto-char beg0)
5787 (when (> end beg)
5788 (setq org-subtree-clip-folded folded)
5789 (when (or cut force-store-markers)
5790 (org-save-markers-in-region beg end))
5791 (if cut (kill-region beg end) (copy-region-as-kill beg end))
5792 (setq org-subtree-clip (current-kill 0))
5793 (message "%s: Subtree(s) with %d characters"
5794 (if cut "Cut" "Copied")
5795 (length org-subtree-clip)))))
5797 (defun org-paste-subtree (&optional level tree for-yank)
5798 "Paste the clipboard as a subtree, with modification of headline level.
5799 The entire subtree is promoted or demoted in order to match a new headline
5800 level.
5802 If the cursor is at the beginning of a headline, the same level as
5803 that headline is used to paste the tree
5805 If not, the new level is derived from the *visible* headings
5806 before and after the insertion point, and taken to be the inferior headline
5807 level of the two. So if the previous visible heading is level 3 and the
5808 next is level 4 (or vice versa), level 4 will be used for insertion.
5809 This makes sure that the subtree remains an independent subtree and does
5810 not swallow low level entries.
5812 You can also force a different level, either by using a numeric prefix
5813 argument, or by inserting the heading marker by hand. For example, if the
5814 cursor is after \"*****\", then the tree will be shifted to level 5.
5816 If optional TREE is given, use this text instead of the kill ring.
5818 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
5819 move back over whitespace before inserting, and move point to the end of
5820 the inserted text when done."
5821 (interactive "P")
5822 (unless (org-kill-is-subtree-p tree)
5823 (error "%s"
5824 (substitute-command-keys
5825 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
5826 (let* ((visp (not (org-invisible-p)))
5827 (txt (or tree (and kill-ring (current-kill 0))))
5828 (^re (concat "^\\(" outline-regexp "\\)"))
5829 (re (concat "\\(" outline-regexp "\\)"))
5830 (^re_ (concat "\\(\\*+\\)[ \t]*"))
5832 (old-level (if (string-match ^re txt)
5833 (- (match-end 0) (match-beginning 0) 1)
5834 -1))
5835 (force-level (cond (level (prefix-numeric-value level))
5836 ((and (looking-at "[ \t]*$")
5837 (string-match
5838 ^re_ (buffer-substring
5839 (point-at-bol) (point))))
5840 (- (match-end 1) (match-beginning 1)))
5841 ((and (bolp)
5842 (looking-at org-outline-regexp))
5843 (- (match-end 0) (point) 1))
5844 (t nil)))
5845 (previous-level (save-excursion
5846 (condition-case nil
5847 (progn
5848 (outline-previous-visible-heading 1)
5849 (if (looking-at re)
5850 (- (match-end 0) (match-beginning 0) 1)
5852 (error 1))))
5853 (next-level (save-excursion
5854 (condition-case nil
5855 (progn
5856 (or (looking-at outline-regexp)
5857 (outline-next-visible-heading 1))
5858 (if (looking-at re)
5859 (- (match-end 0) (match-beginning 0) 1)
5861 (error 1))))
5862 (new-level (or force-level (max previous-level next-level)))
5863 (shift (if (or (= old-level -1)
5864 (= new-level -1)
5865 (= old-level new-level))
5867 (- new-level old-level)))
5868 (delta (if (> shift 0) -1 1))
5869 (func (if (> shift 0) 'org-demote 'org-promote))
5870 (org-odd-levels-only nil)
5871 beg end newend)
5872 ;; Remove the forced level indicator
5873 (if force-level
5874 (delete-region (point-at-bol) (point)))
5875 ;; Paste
5876 (beginning-of-line 1)
5877 (unless for-yank (org-back-over-empty-lines))
5878 (setq beg (point))
5879 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
5880 (insert-before-markers txt)
5881 (unless (string-match "\n\\'" txt) (insert "\n"))
5882 (setq newend (point))
5883 (org-reinstall-markers-in-region beg)
5884 (setq end (point))
5885 (goto-char beg)
5886 (skip-chars-forward " \t\n\r")
5887 (setq beg (point))
5888 (if (and (org-invisible-p) visp)
5889 (save-excursion (outline-show-heading)))
5890 ;; Shift if necessary
5891 (unless (= shift 0)
5892 (save-restriction
5893 (narrow-to-region beg end)
5894 (while (not (= shift 0))
5895 (org-map-region func (point-min) (point-max))
5896 (setq shift (+ delta shift)))
5897 (goto-char (point-min))
5898 (setq newend (point-max))))
5899 (when (or (interactive-p) for-yank)
5900 (message "Clipboard pasted as level %d subtree" new-level))
5901 (if (and (not for-yank) ; in this case, org-yank will decide about folding
5902 kill-ring
5903 (eq org-subtree-clip (current-kill 0))
5904 org-subtree-clip-folded)
5905 ;; The tree was folded before it was killed/copied
5906 (hide-subtree))
5907 (and for-yank (goto-char newend))))
5909 (defun org-kill-is-subtree-p (&optional txt)
5910 "Check if the current kill is an outline subtree, or a set of trees.
5911 Returns nil if kill does not start with a headline, or if the first
5912 headline level is not the largest headline level in the tree.
5913 So this will actually accept several entries of equal levels as well,
5914 which is OK for `org-paste-subtree'.
5915 If optional TXT is given, check this string instead of the current kill."
5916 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
5917 (start-level (and kill
5918 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
5919 org-outline-regexp "\\)")
5920 kill)
5921 (- (match-end 2) (match-beginning 2) 1)))
5922 (re (concat "^" org-outline-regexp))
5923 (start (1+ (or (match-beginning 2) -1))))
5924 (if (not start-level)
5925 (progn
5926 nil) ;; does not even start with a heading
5927 (catch 'exit
5928 (while (setq start (string-match re kill (1+ start)))
5929 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
5930 (throw 'exit nil)))
5931 t))))
5933 (defvar org-markers-to-move nil
5934 "Markers that should be moved with a cut-and-paste operation.
5935 Those markers are stored together with their positions relative to
5936 the start of the region.")
5938 (defun org-save-markers-in-region (beg end)
5939 "Check markers in region.
5940 If these markers are between BEG and END, record their position relative
5941 to BEG, so that after moving the block of text, we can put the markers back
5942 into place.
5943 This function gets called just before an entry or tree gets cut from the
5944 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
5945 called immediately, to move the markers with the entries."
5946 (setq org-markers-to-move nil)
5947 (when (featurep 'org-clock)
5948 (org-clock-save-markers-for-cut-and-paste beg end))
5949 (when (featurep 'org-agenda)
5950 (org-agenda-save-markers-for-cut-and-paste beg end)))
5952 (defun org-check-and-save-marker (marker beg end)
5953 "Check if MARKER is between BEG and END.
5954 If yes, remember the marker and the distance to BEG."
5955 (when (and (marker-buffer marker)
5956 (equal (marker-buffer marker) (current-buffer)))
5957 (if (and (>= marker beg) (< marker end))
5958 (push (cons marker (- marker beg)) org-markers-to-move))))
5960 (defun org-reinstall-markers-in-region (beg)
5961 "Move all remembered markers to their position relative to BEG."
5962 (mapc (lambda (x)
5963 (move-marker (car x) (+ beg (cdr x))))
5964 org-markers-to-move)
5965 (setq org-markers-to-move nil))
5967 (defun org-narrow-to-subtree ()
5968 "Narrow buffer to the current subtree."
5969 (interactive)
5970 (save-excursion
5971 (save-match-data
5972 (narrow-to-region
5973 (progn (org-back-to-heading) (point))
5974 (progn (org-end-of-subtree t) (point))))))
5976 (defun org-clone-subtree-with-time-shift (n &optional shift)
5977 "Clone the task (subtree) at point N times.
5978 The clones will be inserted as siblings.
5980 In interactive use, the user will be prompted for the number of clones
5981 to be produced, and for a time SHIFT, which may be a repeater as used
5982 in time stamps, for example `+3d'.
5984 When a valid repeater is given and the entry contains any time stamps,
5985 the clones will become a sequence in time, with time stamps in the
5986 subtree shifted for each clone produced. If SHIFT is nil or the
5987 empty string, time stamps will be left alone.
5989 If the original subtree did contain time stamps with a repeater,
5990 the following will happen:
5991 - the repeater will be removed in each clone
5992 - an additional clone will be produced, with the current, unshifted
5993 date(s) in the entry.
5994 - the original entry will be placed *after* all the clones, with
5995 repeater intact.
5996 - the start days in the repeater in the original entry will be shifted
5997 to past the last clone.
5998 I this way you can spell out a number of instances of a repeating task,
5999 and still retain the repeater to cover future instances of the task."
6000 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
6001 (let (beg end template task
6002 shift-n shift-what doshift nmin nmax (n-no-remove -1))
6003 (if (not (and (integerp n) (> n 0)))
6004 (error "Invalid number of replications %s" n))
6005 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
6006 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
6007 shift)))
6008 (error "Invalid shift specification %s" shift))
6009 (when doshift
6010 (setq shift-n (string-to-number (match-string 1 shift))
6011 shift-what (cdr (assoc (match-string 2 shift)
6012 '(("d" . day) ("w" . week)
6013 ("m" . month) ("y" . year))))))
6014 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
6015 (setq nmin 1 nmax n)
6016 (org-back-to-heading t)
6017 (setq beg (point))
6018 (org-end-of-subtree t t)
6019 (setq end (point))
6020 (setq template (buffer-substring beg end))
6021 (when (and doshift
6022 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
6023 (delete-region beg end)
6024 (setq end beg)
6025 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
6026 (goto-char end)
6027 (loop for n from nmin to nmax do
6028 (if (not doshift)
6029 (setq task template)
6030 (with-temp-buffer
6031 (insert template)
6032 (org-mode)
6033 (goto-char (point-min))
6034 (while (re-search-forward org-ts-regexp nil t)
6035 (org-timestamp-change (* n shift-n) shift-what))
6036 (unless (= n n-no-remove)
6037 (goto-char (point-min))
6038 (while (re-search-forward org-ts-regexp nil t)
6039 (save-excursion
6040 (goto-char (match-beginning 0))
6041 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
6042 (delete-region (match-beginning 1) (match-end 1))))))
6043 (setq task (buffer-string))))
6044 (insert task))
6045 (goto-char beg)))
6047 ;;; Outline Sorting
6049 (defun org-sort (with-case)
6050 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6051 Optional argument WITH-CASE means sort case-sensitively.
6052 With a double prefix argument, also remove duplicate entries."
6053 (interactive "P")
6054 (if (org-at-table-p)
6055 (org-call-with-arg 'org-table-sort-lines with-case)
6056 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6058 (defun org-sort-remove-invisible (s)
6059 (remove-text-properties 0 (length s) org-rm-props s)
6060 (while (string-match org-bracket-link-regexp s)
6061 (setq s (replace-match (if (match-end 2)
6062 (match-string 3 s)
6063 (match-string 1 s)) t t s)))
6066 (defvar org-priority-regexp) ; defined later in the file
6068 (defun org-sort-entries-or-items
6069 (&optional with-case sorting-type getkey-func compare-func property)
6070 "Sort entries on a certain level of an outline tree.
6071 If there is an active region, the entries in the region are sorted.
6072 Else, if the cursor is before the first entry, sort the top-level items.
6073 Else, the children of the entry at point are sorted.
6075 Sorting can be alphabetically, numerically, and by date/time as given by
6076 the first time stamp in the entry. The command prompts for the sorting
6077 type unless it has been given to the function through the SORTING-TYPE
6078 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
6079 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6080 called with point at the beginning of the record. It must return either
6081 a string or a number that should serve as the sorting key for that record.
6083 Comparing entries ignores case by default. However, with an optional argument
6084 WITH-CASE, the sorting considers case as well."
6085 (interactive "P")
6086 (let ((case-func (if with-case 'identity 'downcase))
6087 start beg end stars re re2
6088 txt what tmp plain-list-p)
6089 ;; Find beginning and end of region to sort
6090 (cond
6091 ((org-region-active-p)
6092 ;; we will sort the region
6093 (setq end (region-end)
6094 what "region")
6095 (goto-char (region-beginning))
6096 (if (not (org-on-heading-p)) (outline-next-heading))
6097 (setq start (point)))
6098 ((org-at-item-p)
6099 ;; we will sort this plain list
6100 (org-beginning-of-item-list) (setq start (point))
6101 (org-end-of-item-list) (setq end (point))
6102 (goto-char start)
6103 (setq plain-list-p t
6104 what "plain list"))
6105 ((or (org-on-heading-p)
6106 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6107 ;; we will sort the children of the current headline
6108 (org-back-to-heading)
6109 (setq start (point)
6110 end (progn (org-end-of-subtree t t)
6111 (org-back-over-empty-lines)
6112 (point))
6113 what "children")
6114 (goto-char start)
6115 (show-subtree)
6116 (outline-next-heading))
6118 ;; we will sort the top-level entries in this file
6119 (goto-char (point-min))
6120 (or (org-on-heading-p) (outline-next-heading))
6121 (setq start (point) end (point-max) what "top-level")
6122 (goto-char start)
6123 (show-all)))
6125 (setq beg (point))
6126 (if (>= beg end) (error "Nothing to sort"))
6128 (unless plain-list-p
6129 (looking-at "\\(\\*+\\)")
6130 (setq stars (match-string 1)
6131 re (concat "^" (regexp-quote stars) " +")
6132 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
6133 txt (buffer-substring beg end))
6134 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
6135 (if (and (not (equal stars "*")) (string-match re2 txt))
6136 (error "Region to sort contains a level above the first entry")))
6138 (unless sorting-type
6139 (message
6140 (if plain-list-p
6141 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
6142 "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:")
6143 what)
6144 (setq sorting-type (read-char-exclusive))
6146 (and (= (downcase sorting-type) ?f)
6147 (setq getkey-func
6148 (org-ido-completing-read "Sort using function: "
6149 obarray 'fboundp t nil nil))
6150 (setq getkey-func (intern getkey-func)))
6152 (and (= (downcase sorting-type) ?r)
6153 (setq property
6154 (org-ido-completing-read "Property: "
6155 (mapcar 'list (org-buffer-property-keys t))
6156 nil t))))
6158 (message "Sorting entries...")
6160 (save-restriction
6161 (narrow-to-region start end)
6163 (let ((dcst (downcase sorting-type))
6164 (case-fold-search nil)
6165 (now (current-time)))
6166 (sort-subr
6167 (/= dcst sorting-type)
6168 ;; This function moves to the beginning character of the "record" to
6169 ;; be sorted.
6170 (if plain-list-p
6171 (lambda nil
6172 (if (org-at-item-p) t (goto-char (point-max))))
6173 (lambda nil
6174 (if (re-search-forward re nil t)
6175 (goto-char (match-beginning 0))
6176 (goto-char (point-max)))))
6177 ;; This function moves to the last character of the "record" being
6178 ;; sorted.
6179 (if plain-list-p
6180 'org-end-of-item
6181 (lambda nil
6182 (save-match-data
6183 (condition-case nil
6184 (outline-forward-same-level 1)
6185 (error
6186 (goto-char (point-max)))))))
6188 ;; This function returns the value that gets sorted against.
6189 (if plain-list-p
6190 (lambda nil
6191 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
6192 (cond
6193 ((= dcst ?n)
6194 (string-to-number (buffer-substring (match-end 0)
6195 (point-at-eol))))
6196 ((= dcst ?a)
6197 (buffer-substring (match-end 0) (point-at-eol)))
6198 ((= dcst ?t)
6199 (if (re-search-forward org-ts-regexp
6200 (point-at-eol) t)
6201 (org-time-string-to-time (match-string 0))
6202 now))
6203 ((= dcst ?f)
6204 (if getkey-func
6205 (progn
6206 (setq tmp (funcall getkey-func))
6207 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6208 tmp)
6209 (error "Invalid key function `%s'" getkey-func)))
6210 (t (error "Invalid sorting type `%c'" sorting-type)))))
6211 (lambda nil
6212 (cond
6213 ((= dcst ?n)
6214 (if (looking-at org-complex-heading-regexp)
6215 (string-to-number (match-string 4))
6216 nil))
6217 ((= dcst ?a)
6218 (if (looking-at org-complex-heading-regexp)
6219 (funcall case-func (match-string 4))
6220 nil))
6221 ((= dcst ?t)
6222 (if (re-search-forward org-ts-regexp
6223 (save-excursion
6224 (forward-line 2)
6225 (point)) t)
6226 (org-time-string-to-time (match-string 0))
6227 now))
6228 ((= dcst ?p)
6229 (if (re-search-forward org-priority-regexp (point-at-eol) t)
6230 (string-to-char (match-string 2))
6231 org-default-priority))
6232 ((= dcst ?r)
6233 (or (org-entry-get nil property) ""))
6234 ((= dcst ?o)
6235 (if (looking-at org-complex-heading-regexp)
6236 (- 9999 (length (member (match-string 2)
6237 org-todo-keywords-1)))))
6238 ((= dcst ?f)
6239 (if getkey-func
6240 (progn
6241 (setq tmp (funcall getkey-func))
6242 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6243 tmp)
6244 (error "Invalid key function `%s'" getkey-func)))
6245 (t (error "Invalid sorting type `%c'" sorting-type)))))
6247 (cond
6248 ((= dcst ?a) 'string<)
6249 ((= dcst ?t) 'time-less-p)
6250 ((= dcst ?f) compare-func)
6251 (t nil)))))
6252 (message "Sorting entries...done")))
6254 (defun org-do-sort (table what &optional with-case sorting-type)
6255 "Sort TABLE of WHAT according to SORTING-TYPE.
6256 The user will be prompted for the SORTING-TYPE if the call to this
6257 function does not specify it. WHAT is only for the prompt, to indicate
6258 what is being sorted. The sorting key will be extracted from
6259 the car of the elements of the table.
6260 If WITH-CASE is non-nil, the sorting will be case-sensitive."
6261 (unless sorting-type
6262 (message
6263 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
6264 what)
6265 (setq sorting-type (read-char-exclusive)))
6266 (let ((dcst (downcase sorting-type))
6267 extractfun comparefun)
6268 ;; Define the appropriate functions
6269 (cond
6270 ((= dcst ?n)
6271 (setq extractfun 'string-to-number
6272 comparefun (if (= dcst sorting-type) '< '>)))
6273 ((= dcst ?a)
6274 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
6275 (lambda(x) (downcase (org-sort-remove-invisible x))))
6276 comparefun (if (= dcst sorting-type)
6277 'string<
6278 (lambda (a b) (and (not (string< a b))
6279 (not (string= a b)))))))
6280 ((= dcst ?t)
6281 (setq extractfun
6282 (lambda (x)
6283 (if (or (string-match org-ts-regexp x)
6284 (string-match org-ts-regexp-both x))
6285 (time-to-seconds
6286 (org-time-string-to-time (match-string 0 x)))
6288 comparefun (if (= dcst sorting-type) '< '>)))
6289 (t (error "Invalid sorting type `%c'" sorting-type)))
6291 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
6292 table)
6293 (lambda (a b) (funcall comparefun (car a) (car b))))))
6295 ;;; Editing source examples
6297 (defvar org-exit-edit-mode-map (make-sparse-keymap))
6298 (define-key org-exit-edit-mode-map "\C-c'" 'org-edit-src-exit)
6299 (defvar org-edit-src-force-single-line nil)
6300 (defvar org-edit-src-from-org-mode nil)
6301 (defvar org-edit-src-picture nil)
6303 (define-minor-mode org-exit-edit-mode
6304 "Minor mode installing a single key binding, \"C-c '\" to exit special edit.")
6306 (defun org-edit-src-code ()
6307 "Edit the source code example at point.
6308 An indirect buffer is created, and that buffer is then narrowed to the
6309 example at point and switched to the correct language mode. When done,
6310 exit by killing the buffer with \\[org-edit-src-exit]."
6311 (interactive)
6312 (let ((line (org-current-line))
6313 (case-fold-search t)
6314 (msg (substitute-command-keys
6315 "Edit, then exit with C-c ' (C-c and single quote)"))
6316 (info (org-edit-src-find-region-and-lang))
6317 (org-mode-p (eq major-mode 'org-mode))
6318 beg end lang lang-f single lfmt)
6319 (if (not info)
6321 (setq beg (nth 0 info)
6322 end (nth 1 info)
6323 lang (nth 2 info)
6324 single (nth 3 info)
6325 lfmt (nth 4 info)
6326 lang-f (intern (concat lang "-mode")))
6327 (unless (functionp lang-f)
6328 (error "No such language mode: %s" lang-f))
6329 (goto-line line)
6330 (if (get-buffer "*Org Edit Src Example*")
6331 (kill-buffer "*Org Edit Src Example*"))
6332 (switch-to-buffer (make-indirect-buffer (current-buffer)
6333 "*Org Edit Src Example*"))
6334 (narrow-to-region beg end)
6335 (remove-text-properties beg end '(display nil invisible nil
6336 intangible nil))
6337 (let ((org-inhibit-startup t))
6338 (funcall lang-f))
6339 (set (make-local-variable 'org-edit-src-force-single-line) single)
6340 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
6341 (when lfmt
6342 (set (make-local-variable 'org-coderef-label-format) lfmt))
6343 (when org-mode-p
6344 (goto-char (point-min))
6345 (while (re-search-forward "^," nil t)
6346 (replace-match "")))
6347 (goto-line line)
6348 (org-exit-edit-mode)
6349 (org-set-local 'header-line-format msg)
6350 (message "%s" msg)
6351 t)))
6353 (defun org-edit-fixed-width-region ()
6354 "Edit the fixed-width ascii drawing at point.
6355 This must be a region where each line starts with a colon followed by
6356 a space character.
6357 An indirect buffer is created, and that buffer is then narrowed to the
6358 example at point and switched to artist-mode. When done,
6359 exit by killing the buffer with \\[org-edit-src-exit]."
6360 (interactive)
6361 (let ((line (org-current-line))
6362 (case-fold-search t)
6363 (msg (substitute-command-keys
6364 "Edit, then exit with C-c ' (C-c and single quote)"))
6365 (org-mode-p (eq major-mode 'org-mode))
6366 beg end)
6367 (beginning-of-line 1)
6368 (if (looking-at "[ \t]*[^:\n \t]")
6370 (if (looking-at "[ \t]*\\(\n\\|\\'\\)")
6371 (setq beg (point) end beg)
6372 (save-excursion
6373 (if (re-search-backward "^[ \t]*[^:]" nil 'move)
6374 (setq beg (point-at-bol 2))
6375 (setq beg (point))))
6376 (save-excursion
6377 (if (re-search-forward "^[ \t]*[^:]" nil 'move)
6378 (setq end (1- (match-beginning 0)))
6379 (setq end (point))))
6380 (goto-line line))
6381 (if (get-buffer "*Org Edit Picture*")
6382 (kill-buffer "*Org Edit Picture*"))
6383 (switch-to-buffer (make-indirect-buffer (current-buffer)
6384 "*Org Edit Picture*"))
6385 (narrow-to-region beg end)
6386 (remove-text-properties beg end '(display nil invisible nil
6387 intangible nil))
6388 (when (fboundp 'font-lock-unfontify-region)
6389 (font-lock-unfontify-region (point-min) (point-max)))
6390 (cond
6391 ((eq org-edit-fixed-width-region-mode 'artist-mode)
6392 (fundamental-mode)
6393 (artist-mode 1))
6394 (t (funcall org-edit-fixed-width-region-mode)))
6395 (set (make-local-variable 'org-edit-src-force-single-line) nil)
6396 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
6397 (set (make-local-variable 'org-edit-src-picture) t)
6398 (goto-char (point-min))
6399 (while (re-search-forward "^[ \t]*: ?" nil t)
6400 (replace-match ""))
6401 (goto-line line)
6402 (org-exit-edit-mode)
6403 (org-set-local 'header-line-format msg)
6404 (message "%s" msg)
6405 t)))
6408 (defun org-edit-src-find-region-and-lang ()
6409 "Find the region and language for a local edit.
6410 Return a list with beginning and end of the region, a string representing
6411 the language, a switch telling of the content should be in a single line."
6412 (let ((re-list
6413 (append
6414 org-edit-src-region-extra
6416 ("<src\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</src>" lang)
6417 ("<literal\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</literal>" style)
6418 ("<example>[ \t]*\n?" "\n?[ \t]*</example>" "fundamental")
6419 ("<lisp>[ \t]*\n?" "\n?[ \t]*</lisp>" "emacs-lisp")
6420 ("<perl>[ \t]*\n?" "\n?[ \t]*</perl>" "perl")
6421 ("<python>[ \t]*\n?" "\n?[ \t]*</python>" "python")
6422 ("<ruby>[ \t]*\n?" "\n?[ \t]*</ruby>" "ruby")
6423 ("^#\\+begin_src\\( \\([^ \t\n]+\\)\\)?.*\n" "\n#\\+end_src" 2)
6424 ("^#\\+begin_example.*\n" "\n#\\+end_example" "fundamental")
6425 ("^#\\+html:" "\n" "html" single-line)
6426 ("^#\\+begin_html.*\n" "\n#\\+end_html" "html")
6427 ("^#\\+begin_latex.*\n" "\n#\\+end_latex" "latex")
6428 ("^#\\+latex:" "\n" "latex" single-line)
6429 ("^#\\+begin_ascii.*\n" "\n#\\+end_ascii" "fundamental")
6430 ("^#\\+ascii:" "\n" "ascii" single-line)
6432 (pos (point))
6433 re1 re2 single beg end lang lfmt match-re1)
6434 (catch 'exit
6435 (while (setq entry (pop re-list))
6436 (setq re1 (car entry) re2 (nth 1 entry) lang (nth 2 entry)
6437 single (nth 3 entry))
6438 (save-excursion
6439 (if (or (looking-at re1)
6440 (re-search-backward re1 nil t))
6441 (progn
6442 (setq match-re1 (match-string 0))
6443 (setq beg (match-end 0)
6444 lang (org-edit-src-get-lang lang)
6445 lfmt (org-edit-src-get-label-format match-re1))
6446 (if (and (re-search-forward re2 nil t)
6447 (>= (match-end 0) pos))
6448 (throw 'exit (list beg (match-beginning 0)
6449 lang single lfmt))))
6450 (if (or (looking-at re2)
6451 (re-search-forward re2 nil t))
6452 (progn
6453 (setq end (match-beginning 0))
6454 (if (and (re-search-backward re1 nil t)
6455 (<= (match-beginning 0) pos))
6456 (progn
6457 (setq lfmt (org-edit-src-get-label-format
6458 (match-string 0)))
6459 (throw 'exit
6460 (list (match-end 0) end
6461 (org-edit-src-get-lang lang)
6462 single lfmt))))))))))))
6464 (defun org-edit-src-get-lang (lang)
6465 "Extract the src language."
6466 (let ((m (match-string 0)))
6467 (cond
6468 ((stringp lang) lang)
6469 ((integerp lang) (match-string lang))
6470 ((and (eq lang 'lang)
6471 (string-match "\\<lang=\"\\([^ \t\n\"]+\\)\"" m))
6472 (match-string 1 m))
6473 ((and (eq lang 'style)
6474 (string-match "\\<style=\"\\([^ \t\n\"]+\\)\"" m))
6475 (match-string 1 m))
6476 (t "fundamental"))))
6478 (defun org-edit-src-get-label-format (s)
6479 "Extract the label format."
6480 (save-match-data
6481 (if (string-match "-l[ \t]+\\\\?\"\\([^\t\r\n\"]+\\)\\\\?\"" s)
6482 (match-string 1 s))))
6484 (defun org-edit-src-exit ()
6485 "Exit special edit and protect problematic lines."
6486 (interactive)
6487 (unless (buffer-base-buffer (current-buffer))
6488 (error "This is not an indirect buffer, something is wrong..."))
6489 (unless (> (point-min) 1)
6490 (error "This buffer is not narrowed, something is wrong..."))
6491 (goto-char (point-min))
6492 (if (looking-at "[ \t\n]*\n") (replace-match ""))
6493 (if (re-search-forward "\n[ \t\n]*\\'" nil t) (replace-match ""))
6494 (when (org-bound-and-true-p org-edit-src-force-single-line)
6495 (goto-char (point-min))
6496 (while (re-search-forward "\n" nil t)
6497 (replace-match " "))
6498 (goto-char (point-min))
6499 (if (looking-at "\\s-*") (replace-match " "))
6500 (if (re-search-forward "\\s-+\\'" nil t)
6501 (replace-match "")))
6502 (when (org-bound-and-true-p org-edit-src-from-org-mode)
6503 (goto-char (point-min))
6504 (while (re-search-forward (if (org-mode-p) "^\\(.\\)" "^\\([*#]\\)") nil t)
6505 (replace-match ",\\1"))
6506 (when font-lock-mode
6507 (font-lock-unfontify-region (point-min) (point-max)))
6508 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
6509 (when (org-bound-and-true-p org-edit-src-picture)
6510 (untabify (point-min) (point-max))
6511 (goto-char (point-min))
6512 (while (re-search-forward "^" nil t)
6513 (replace-match ": "))
6514 (when font-lock-mode
6515 (font-lock-unfontify-region (point-min) (point-max)))
6516 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
6517 (kill-buffer (current-buffer))
6518 (and (org-mode-p) (org-restart-font-lock)))
6521 ;;; The orgstruct minor mode
6523 ;; Define a minor mode which can be used in other modes in order to
6524 ;; integrate the org-mode structure editing commands.
6526 ;; This is really a hack, because the org-mode structure commands use
6527 ;; keys which normally belong to the major mode. Here is how it
6528 ;; works: The minor mode defines all the keys necessary to operate the
6529 ;; structure commands, but wraps the commands into a function which
6530 ;; tests if the cursor is currently at a headline or a plain list
6531 ;; item. If that is the case, the structure command is used,
6532 ;; temporarily setting many Org-mode variables like regular
6533 ;; expressions for filling etc. However, when any of those keys is
6534 ;; used at a different location, function uses `key-binding' to look
6535 ;; up if the key has an associated command in another currently active
6536 ;; keymap (minor modes, major mode, global), and executes that
6537 ;; command. There might be problems if any of the keys is otherwise
6538 ;; used as a prefix key.
6540 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
6541 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
6542 ;; addresses this by checking explicitly for both bindings.
6544 (defvar orgstruct-mode-map (make-sparse-keymap)
6545 "Keymap for the minor `orgstruct-mode'.")
6547 (defvar org-local-vars nil
6548 "List of local variables, for use by `orgstruct-mode'")
6550 ;;;###autoload
6551 (define-minor-mode orgstruct-mode
6552 "Toggle the minor more `orgstruct-mode'.
6553 This mode is for using Org-mode structure commands in other modes.
6554 The following key behave as if Org-mode was active, if the cursor
6555 is on a headline, or on a plain list item (both in the definition
6556 of Org-mode).
6558 M-up Move entry/item up
6559 M-down Move entry/item down
6560 M-left Promote
6561 M-right Demote
6562 M-S-up Move entry/item up
6563 M-S-down Move entry/item down
6564 M-S-left Promote subtree
6565 M-S-right Demote subtree
6566 M-q Fill paragraph and items like in Org-mode
6567 C-c ^ Sort entries
6568 C-c - Cycle list bullet
6569 TAB Cycle item visibility
6570 M-RET Insert new heading/item
6571 S-M-RET Insert new TODO heading / Checkbox item
6572 C-c C-c Set tags / toggle checkbox"
6573 nil " OrgStruct" nil
6574 (org-load-modules-maybe)
6575 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
6577 ;;;###autoload
6578 (defun turn-on-orgstruct ()
6579 "Unconditionally turn on `orgstruct-mode'."
6580 (orgstruct-mode 1))
6582 (defun orgstruct++-mode (&optional arg)
6583 "Toggle `orgstruct-mode', the enhanced version of it.
6584 In addition to setting orgstruct-mode, this also exports all indentation and
6585 autofilling variables from org-mode into the buffer. It will also
6586 recognize item context in multiline items.
6587 Note that turning off orgstruct-mode will *not* remove the
6588 indentation/paragraph settings. This can only be done by refreshing the
6589 major mode, for example with \[normal-mode]."
6590 (interactive "P")
6591 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
6592 (if (< arg 1)
6593 (orgstruct-mode -1)
6594 (orgstruct-mode 1)
6595 (let (var val)
6596 (mapc
6597 (lambda (x)
6598 (when (string-match
6599 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6600 (symbol-name (car x)))
6601 (setq var (car x) val (nth 1 x))
6602 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
6603 org-local-vars)
6604 (org-set-local 'orgstruct-is-++ t))))
6606 (defvar orgstruct-is-++ nil
6607 "Is orgstruct-mode in ++ version in the current-buffer?")
6608 (make-variable-buffer-local 'orgstruct-is-++)
6610 ;;;###autoload
6611 (defun turn-on-orgstruct++ ()
6612 "Unconditionally turn on `orgstruct++-mode'."
6613 (orgstruct++-mode 1))
6615 (defun orgstruct-error ()
6616 "Error when there is no default binding for a structure key."
6617 (interactive)
6618 (error "This key has no function outside structure elements"))
6620 (defun orgstruct-setup ()
6621 "Setup orgstruct keymaps."
6622 (let ((nfunc 0)
6623 (bindings
6624 (list
6625 '([(meta up)] org-metaup)
6626 '([(meta down)] org-metadown)
6627 '([(meta left)] org-metaleft)
6628 '([(meta right)] org-metaright)
6629 '([(meta shift up)] org-shiftmetaup)
6630 '([(meta shift down)] org-shiftmetadown)
6631 '([(meta shift left)] org-shiftmetaleft)
6632 '([(meta shift right)] org-shiftmetaright)
6633 '([(shift up)] org-shiftup)
6634 '([(shift down)] org-shiftdown)
6635 '([(shift left)] org-shiftleft)
6636 '([(shift right)] org-shiftright)
6637 '("\C-c\C-c" org-ctrl-c-ctrl-c)
6638 '("\M-q" fill-paragraph)
6639 '("\C-c^" org-sort)
6640 '("\C-c-" org-cycle-list-bullet)))
6641 elt key fun cmd)
6642 (while (setq elt (pop bindings))
6643 (setq nfunc (1+ nfunc))
6644 (setq key (org-key (car elt))
6645 fun (nth 1 elt)
6646 cmd (orgstruct-make-binding fun nfunc key))
6647 (org-defkey orgstruct-mode-map key cmd))
6649 ;; Special treatment needed for TAB and RET
6650 (org-defkey orgstruct-mode-map [(tab)]
6651 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
6652 (org-defkey orgstruct-mode-map "\C-i"
6653 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
6655 (org-defkey orgstruct-mode-map "\M-\C-m"
6656 (orgstruct-make-binding 'org-insert-heading 105
6657 "\M-\C-m" [(meta return)]))
6658 (org-defkey orgstruct-mode-map [(meta return)]
6659 (orgstruct-make-binding 'org-insert-heading 106
6660 [(meta return)] "\M-\C-m"))
6662 (org-defkey orgstruct-mode-map [(shift meta return)]
6663 (orgstruct-make-binding 'org-insert-todo-heading 107
6664 [(meta return)] "\M-\C-m"))
6666 (unless org-local-vars
6667 (setq org-local-vars (org-get-local-variables)))
6671 (defun orgstruct-make-binding (fun n &rest keys)
6672 "Create a function for binding in the structure minor mode.
6673 FUN is the command to call inside a table. N is used to create a unique
6674 command name. KEYS are keys that should be checked in for a command
6675 to execute outside of tables."
6676 (eval
6677 (list 'defun
6678 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6679 '(arg)
6680 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6681 "Outside of structure, run the binding of `"
6682 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6683 "'.")
6684 '(interactive "p")
6685 (list 'if
6686 `(org-context-p 'headline 'item
6687 (and orgstruct-is-++
6688 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
6689 'item-body))
6690 (list 'org-run-like-in-org-mode (list 'quote fun))
6691 (list 'let '(orgstruct-mode)
6692 (list 'call-interactively
6693 (append '(or)
6694 (mapcar (lambda (k)
6695 (list 'key-binding k))
6696 keys)
6697 '('orgstruct-error))))))))
6699 (defun org-context-p (&rest contexts)
6700 "Check if local context is any of CONTEXTS.
6701 Possible values in the list of contexts are `table', `headline', and `item'."
6702 (let ((pos (point)))
6703 (goto-char (point-at-bol))
6704 (prog1 (or (and (memq 'table contexts)
6705 (looking-at "[ \t]*|"))
6706 (and (memq 'headline contexts)
6707 ;;????????? (looking-at "\\*+"))
6708 (looking-at outline-regexp))
6709 (and (memq 'item contexts)
6710 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
6711 (and (memq 'item-body contexts)
6712 (org-in-item-p)))
6713 (goto-char pos))))
6715 (defun org-get-local-variables ()
6716 "Return a list of all local variables in an org-mode buffer."
6717 (let (varlist)
6718 (with-current-buffer (get-buffer-create "*Org tmp*")
6719 (erase-buffer)
6720 (org-mode)
6721 (setq varlist (buffer-local-variables)))
6722 (kill-buffer "*Org tmp*")
6723 (delq nil
6724 (mapcar
6725 (lambda (x)
6726 (setq x
6727 (if (symbolp x)
6728 (list x)
6729 (list (car x) (list 'quote (cdr x)))))
6730 (if (string-match
6731 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6732 (symbol-name (car x)))
6733 x nil))
6734 varlist))))
6736 ;;;###autoload
6737 (defun org-run-like-in-org-mode (cmd)
6738 "Run a command, pretending that the current buffer is in Org-mode.
6739 This will temporarily bind local variables that are typically bound in
6740 Org-mode to the values they have in Org-mode, and then interactively
6741 call CMD."
6742 (org-load-modules-maybe)
6743 (unless org-local-vars
6744 (setq org-local-vars (org-get-local-variables)))
6745 (eval (list 'let org-local-vars
6746 (list 'call-interactively (list 'quote cmd)))))
6748 ;;;; Archiving
6750 (defun org-get-category (&optional pos)
6751 "Get the category applying to position POS."
6752 (get-text-property (or pos (point)) 'org-category))
6754 (defun org-refresh-category-properties ()
6755 "Refresh category text properties in the buffer."
6756 (let ((def-cat (cond
6757 ((null org-category)
6758 (if buffer-file-name
6759 (file-name-sans-extension
6760 (file-name-nondirectory buffer-file-name))
6761 "???"))
6762 ((symbolp org-category) (symbol-name org-category))
6763 (t org-category)))
6764 beg end cat pos optionp)
6765 (org-unmodified
6766 (save-excursion
6767 (save-restriction
6768 (widen)
6769 (goto-char (point-min))
6770 (put-text-property (point) (point-max) 'org-category def-cat)
6771 (while (re-search-forward
6772 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6773 (setq pos (match-end 0)
6774 optionp (equal (char-after (match-beginning 0)) ?#)
6775 cat (org-trim (match-string 2)))
6776 (if optionp
6777 (setq beg (point-at-bol) end (point-max))
6778 (org-back-to-heading t)
6779 (setq beg (point) end (org-end-of-subtree t t)))
6780 (put-text-property beg end 'org-category cat)
6781 (goto-char pos)))))))
6784 ;;;; Link Stuff
6786 ;;; Link abbreviations
6788 (defun org-link-expand-abbrev (link)
6789 "Apply replacements as defined in `org-link-abbrev-alist."
6790 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6791 (let* ((key (match-string 1 link))
6792 (as (or (assoc key org-link-abbrev-alist-local)
6793 (assoc key org-link-abbrev-alist)))
6794 (tag (and (match-end 2) (match-string 3 link)))
6795 rpl)
6796 (if (not as)
6797 link
6798 (setq rpl (cdr as))
6799 (cond
6800 ((symbolp rpl) (funcall rpl tag))
6801 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
6802 ((string-match "%h" rpl)
6803 (replace-match (url-hexify-string (or tag "")) t t rpl))
6804 (t (concat rpl tag)))))
6805 link))
6807 ;;; Storing and inserting links
6809 (defvar org-insert-link-history nil
6810 "Minibuffer history for links inserted with `org-insert-link'.")
6812 (defvar org-stored-links nil
6813 "Contains the links stored with `org-store-link'.")
6815 (defvar org-store-link-plist nil
6816 "Plist with info about the most recently link created with `org-store-link'.")
6818 (defvar org-link-protocols nil
6819 "Link protocols added to Org-mode using `org-add-link-type'.")
6821 (defvar org-store-link-functions nil
6822 "List of functions that are called to create and store a link.
6823 Each function will be called in turn until one returns a non-nil
6824 value. Each function should check if it is responsible for creating
6825 this link (for example by looking at the major mode).
6826 If not, it must exit and return nil.
6827 If yes, it should return a non-nil value after a calling
6828 `org-store-link-props' with a list of properties and values.
6829 Special properties are:
6831 :type The link prefix. like \"http\". This must be given.
6832 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6833 This is obligatory as well.
6834 :description Optional default description for the second pair
6835 of brackets in an Org-mode link. The user can still change
6836 this when inserting this link into an Org-mode buffer.
6838 In addition to these, any additional properties can be specified
6839 and then used in remember templates.")
6841 (defun org-add-link-type (type &optional follow export)
6842 "Add TYPE to the list of `org-link-types'.
6843 Re-compute all regular expressions depending on `org-link-types'
6845 FOLLOW and EXPORT are two functions.
6847 FOLLOW should take the link path as the single argument and do whatever
6848 is necessary to follow the link, for example find a file or display
6849 a mail message.
6851 EXPORT should format the link path for export to one of the export formats.
6852 It should be a function accepting three arguments:
6854 path the path of the link, the text after the prefix (like \"http:\")
6855 desc the description of the link, if any, nil if there was no description
6856 format the export format, a symbol like `html' or `latex'.
6858 The function may use the FORMAT information to return different values
6859 depending on the format. The return value will be put literally into
6860 the exported file.
6861 Org-mode has a built-in default for exporting links. If you are happy with
6862 this default, there is no need to define an export function for the link
6863 type. For a simple example of an export function, see `org-bbdb.el'."
6864 (add-to-list 'org-link-types type t)
6865 (org-make-link-regexps)
6866 (if (assoc type org-link-protocols)
6867 (setcdr (assoc type org-link-protocols) (list follow export))
6868 (push (list type follow export) org-link-protocols)))
6870 ;;;###autoload
6871 (defun org-store-link (arg)
6872 "\\<org-mode-map>Store an org-link to the current location.
6873 This link is added to `org-stored-links' and can later be inserted
6874 into an org-buffer with \\[org-insert-link].
6876 For some link types, a prefix arg is interpreted:
6877 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
6878 For file links, arg negates `org-context-in-file-links'."
6879 (interactive "P")
6880 (org-load-modules-maybe)
6881 (setq org-store-link-plist nil) ; reset
6882 (let (link cpltxt desc description search txt custom-id)
6883 (cond
6885 ((run-hook-with-args-until-success 'org-store-link-functions)
6886 (setq link (plist-get org-store-link-plist :link)
6887 desc (or (plist-get org-store-link-plist :description) link)))
6889 ((equal (buffer-name) "*Org Edit Src Example*")
6890 (let (label gc)
6891 (while (or (not label)
6892 (save-excursion
6893 (save-restriction
6894 (widen)
6895 (goto-char (point-min))
6896 (re-search-forward
6897 (regexp-quote (format org-coderef-label-format label))
6898 nil t))))
6899 (when label (message "Label exists already") (sit-for 2))
6900 (setq label (read-string "Code line label: " label)))
6901 (end-of-line 1)
6902 (setq link (format org-coderef-label-format label))
6903 (setq gc (- 79 (length link)))
6904 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
6905 (insert link)
6906 (setq link (concat "(" label ")") desc nil)))
6908 ((eq major-mode 'calendar-mode)
6909 (let ((cd (calendar-cursor-to-date)))
6910 (setq link
6911 (format-time-string
6912 (car org-time-stamp-formats)
6913 (apply 'encode-time
6914 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6915 nil nil nil))))
6916 (org-store-link-props :type "calendar" :date cd)))
6918 ((eq major-mode 'w3-mode)
6919 (setq cpltxt (if (and (buffer-name)
6920 (not (string-match "Untitled" (buffer-name))))
6921 (buffer-name)
6922 (url-view-url t))
6923 link (org-make-link (url-view-url t)))
6924 (org-store-link-props :type "w3" :url (url-view-url t)))
6926 ((eq major-mode 'w3m-mode)
6927 (setq cpltxt (or w3m-current-title w3m-current-url)
6928 link (org-make-link w3m-current-url))
6929 (org-store-link-props :type "w3m" :url (url-view-url t)))
6931 ((setq search (run-hook-with-args-until-success
6932 'org-create-file-search-functions))
6933 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6934 "::" search))
6935 (setq cpltxt (or description link)))
6937 ((eq major-mode 'image-mode)
6938 (setq cpltxt (concat "file:"
6939 (abbreviate-file-name buffer-file-name))
6940 link (org-make-link cpltxt))
6941 (org-store-link-props :type "image" :file buffer-file-name))
6943 ((eq major-mode 'dired-mode)
6944 ;; link to the file in the current line
6945 (setq cpltxt (concat "file:"
6946 (abbreviate-file-name
6947 (expand-file-name
6948 (dired-get-filename nil t))))
6949 link (org-make-link cpltxt)))
6951 ((and buffer-file-name (org-mode-p))
6952 (setq custom-id (org-entry-get nil "CUSTOM_ID"))
6953 (cond
6954 ((org-in-regexp "<<\\(.*?\\)>>")
6955 (setq cpltxt
6956 (concat "file:"
6957 (abbreviate-file-name buffer-file-name)
6958 "::" (match-string 1))
6959 link (org-make-link cpltxt)))
6960 ((and (featurep 'org-id)
6961 (or (eq org-link-to-org-use-id t)
6962 (and (eq org-link-to-org-use-id 'create-if-interactive)
6963 (interactive-p))
6964 (and (eq org-link-to-org-use-id 'create-if-interactive-and-no-custom-id)
6965 (interactive-p)
6966 (not custom-id))
6967 (and org-link-to-org-use-id
6968 (condition-case nil
6969 (org-entry-get nil "ID")
6970 (error nil)))))
6971 ;; We can make a link using the ID.
6972 (setq link (condition-case nil
6973 (prog1 (org-id-store-link)
6974 (setq desc (plist-get org-store-link-plist
6975 :description)))
6976 (error
6977 ;; probably before first headline, link to file only
6978 (concat "file:"
6979 (abbreviate-file-name buffer-file-name))))))
6981 ;; Just link to current headline
6982 (setq cpltxt (concat "file:"
6983 (abbreviate-file-name buffer-file-name)))
6984 ;; Add a context search string
6985 (when (org-xor org-context-in-file-links arg)
6986 (setq txt (cond
6987 ((org-on-heading-p) nil)
6988 ((org-region-active-p)
6989 (buffer-substring (region-beginning) (region-end)))
6990 (t nil)))
6991 (when (or (null txt) (string-match "\\S-" txt))
6992 (setq cpltxt
6993 (concat cpltxt "::"
6994 (condition-case nil
6995 (org-make-org-heading-search-string txt)
6996 (error "")))
6997 desc "NONE")))
6998 (if (string-match "::\\'" cpltxt)
6999 (setq cpltxt (substring cpltxt 0 -2)))
7000 (setq link (org-make-link cpltxt)))))
7002 ((buffer-file-name (buffer-base-buffer))
7003 ;; Just link to this file here.
7004 (setq cpltxt (concat "file:"
7005 (abbreviate-file-name
7006 (buffer-file-name (buffer-base-buffer)))))
7007 ;; Add a context string
7008 (when (org-xor org-context-in-file-links arg)
7009 (setq txt (if (org-region-active-p)
7010 (buffer-substring (region-beginning) (region-end))
7011 (buffer-substring (point-at-bol) (point-at-eol))))
7012 ;; Only use search option if there is some text.
7013 (when (string-match "\\S-" txt)
7014 (setq cpltxt
7015 (concat cpltxt "::" (org-make-org-heading-search-string txt))
7016 desc "NONE")))
7017 (setq link (org-make-link cpltxt)))
7019 ((interactive-p)
7020 (error "Cannot link to a buffer which is not visiting a file"))
7022 (t (setq link nil)))
7024 (if (consp link) (setq cpltxt (car link) link (cdr link)))
7025 (setq link (or link cpltxt)
7026 desc (or desc cpltxt))
7027 (if (equal desc "NONE") (setq desc nil))
7029 (if (and (interactive-p) link)
7030 (progn
7031 (setq org-stored-links
7032 (cons (list link desc) org-stored-links))
7033 (message "Stored: %s" (or desc link))
7034 (when custom-id
7035 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
7036 "::#" custom-id))
7037 (setq org-stored-links
7038 (cons (list link desc) org-stored-links))))
7039 (and link (org-make-link-string link desc)))))
7041 (defun org-store-link-props (&rest plist)
7042 "Store link properties, extract names and addresses."
7043 (let (x adr)
7044 (when (setq x (plist-get plist :from))
7045 (setq adr (mail-extract-address-components x))
7046 (setq plist (plist-put plist :fromname (car adr)))
7047 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
7048 (when (setq x (plist-get plist :to))
7049 (setq adr (mail-extract-address-components x))
7050 (setq plist (plist-put plist :toname (car adr)))
7051 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
7052 (let ((from (plist-get plist :from))
7053 (to (plist-get plist :to)))
7054 (when (and from to org-from-is-user-regexp)
7055 (setq plist
7056 (plist-put plist :fromto
7057 (if (string-match org-from-is-user-regexp from)
7058 (concat "to %t")
7059 (concat "from %f"))))))
7060 (setq org-store-link-plist plist))
7062 (defun org-add-link-props (&rest plist)
7063 "Add these properties to the link property list."
7064 (let (key value)
7065 (while plist
7066 (setq key (pop plist) value (pop plist))
7067 (setq org-store-link-plist
7068 (plist-put org-store-link-plist key value)))))
7070 (defun org-email-link-description (&optional fmt)
7071 "Return the description part of an email link.
7072 This takes information from `org-store-link-plist' and formats it
7073 according to FMT (default from `org-email-link-description-format')."
7074 (setq fmt (or fmt org-email-link-description-format))
7075 (let* ((p org-store-link-plist)
7076 (to (plist-get p :toaddress))
7077 (from (plist-get p :fromaddress))
7078 (table
7079 (list
7080 (cons "%c" (plist-get p :fromto))
7081 (cons "%F" (plist-get p :from))
7082 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
7083 (cons "%T" (plist-get p :to))
7084 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
7085 (cons "%s" (plist-get p :subject))
7086 (cons "%m" (plist-get p :message-id)))))
7087 (when (string-match "%c" fmt)
7088 ;; Check if the user wrote this message
7089 (if (and org-from-is-user-regexp from to
7090 (save-match-data (string-match org-from-is-user-regexp from)))
7091 (setq fmt (replace-match "to %t" t t fmt))
7092 (setq fmt (replace-match "from %f" t t fmt))))
7093 (org-replace-escapes fmt table)))
7095 (defun org-make-org-heading-search-string (&optional string heading)
7096 "Make search string for STRING or current headline."
7097 (interactive)
7098 (let ((s (or string (org-get-heading))))
7099 (unless (and string (not heading))
7100 ;; We are using a headline, clean up garbage in there.
7101 (if (string-match org-todo-regexp s)
7102 (setq s (replace-match "" t t s)))
7103 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
7104 (setq s (replace-match "" t t s)))
7105 (setq s (org-trim s))
7106 (if (string-match (concat "^\\(" org-quote-string "\\|"
7107 org-comment-string "\\)") s)
7108 (setq s (replace-match "" t t s)))
7109 (while (string-match org-ts-regexp s)
7110 (setq s (replace-match "" t t s))))
7111 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
7112 (setq s (replace-match " " t t s)))
7113 (or string (setq s (concat "*" s))) ; Add * for headlines
7114 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
7116 (defun org-make-link (&rest strings)
7117 "Concatenate STRINGS."
7118 (apply 'concat strings))
7120 (defun org-make-link-string (link &optional description)
7121 "Make a link with brackets, consisting of LINK and DESCRIPTION."
7122 (unless (string-match "\\S-" link)
7123 (error "Empty link"))
7124 (when (stringp description)
7125 ;; Remove brackets from the description, they are fatal.
7126 (while (string-match "\\[" description)
7127 (setq description (replace-match "{" t t description)))
7128 (while (string-match "\\]" description)
7129 (setq description (replace-match "}" t t description))))
7130 (when (equal (org-link-escape link) description)
7131 ;; No description needed, it is identical
7132 (setq description nil))
7133 (when (and (not description)
7134 (not (equal link (org-link-escape link))))
7135 (setq description (org-extract-attributes link)))
7136 (concat "[[" (org-link-escape link) "]"
7137 (if description (concat "[" description "]") "")
7138 "]"))
7140 (defconst org-link-escape-chars
7141 '((?\ . "%20")
7142 (?\[ . "%5B")
7143 (?\] . "%5D")
7144 (?\340 . "%E0") ; `a
7145 (?\342 . "%E2") ; ^a
7146 (?\347 . "%E7") ; ,c
7147 (?\350 . "%E8") ; `e
7148 (?\351 . "%E9") ; 'e
7149 (?\352 . "%EA") ; ^e
7150 (?\356 . "%EE") ; ^i
7151 (?\364 . "%F4") ; ^o
7152 (?\371 . "%F9") ; `u
7153 (?\373 . "%FB") ; ^u
7154 (?\; . "%3B")
7155 (?? . "%3F")
7156 (?= . "%3D")
7157 (?+ . "%2B")
7159 "Association list of escapes for some characters problematic in links.
7160 This is the list that is used for internal purposes.")
7162 (defvar org-url-encoding-use-url-hexify nil)
7164 (defconst org-link-escape-chars-browser
7165 '((?\ . "%20")) ; 32 for the SPC char
7166 "Association list of escapes for some characters problematic in links.
7167 This is the list that is used before handing over to the browser.")
7169 (defun org-link-escape (text &optional table)
7170 "Escape characters in TEXT that are problematic for links."
7171 (if org-url-encoding-use-url-hexify
7172 (url-hexify-string text)
7173 (setq table (or table org-link-escape-chars))
7174 (when text
7175 (let ((re (mapconcat (lambda (x) (regexp-quote
7176 (char-to-string (car x))))
7177 table "\\|")))
7178 (while (string-match re text)
7179 (setq text
7180 (replace-match
7181 (cdr (assoc (string-to-char (match-string 0 text))
7182 table))
7183 t t text)))
7184 text))))
7186 (defun org-link-unescape (text &optional table)
7187 "Reverse the action of `org-link-escape'."
7188 (if org-url-encoding-use-url-hexify
7189 (url-unhex-string text)
7190 (setq table (or table org-link-escape-chars))
7191 (when text
7192 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
7193 table "\\|")))
7194 (while (string-match re text)
7195 (setq text
7196 (replace-match
7197 (char-to-string (car (rassoc (match-string 0 text) table)))
7198 t t text)))
7199 text))))
7201 (defun org-xor (a b)
7202 "Exclusive or."
7203 (if a (not b) b))
7205 (defun org-fixup-message-id-for-http (s)
7206 "Replace special characters in a message id, so it can be used in an http query."
7207 (while (string-match "<" s)
7208 (setq s (replace-match "%3C" t t s)))
7209 (while (string-match ">" s)
7210 (setq s (replace-match "%3E" t t s)))
7211 (while (string-match "@" s)
7212 (setq s (replace-match "%40" t t s)))
7215 ;;;###autoload
7216 (defun org-insert-link-global ()
7217 "Insert a link like Org-mode does.
7218 This command can be called in any mode to insert a link in Org-mode syntax."
7219 (interactive)
7220 (org-load-modules-maybe)
7221 (org-run-like-in-org-mode 'org-insert-link))
7223 (defun org-insert-link (&optional complete-file link-location)
7224 "Insert a link. At the prompt, enter the link.
7226 Completion can be used to insert any of the link protocol prefixes like
7227 http or ftp in use.
7229 The history can be used to select a link previously stored with
7230 `org-store-link'. When the empty string is entered (i.e. if you just
7231 press RET at the prompt), the link defaults to the most recently
7232 stored link. As SPC triggers completion in the minibuffer, you need to
7233 use M-SPC or C-q SPC to force the insertion of a space character.
7235 You will also be prompted for a description, and if one is given, it will
7236 be displayed in the buffer instead of the link.
7238 If there is already a link at point, this command will allow you to edit link
7239 and description parts.
7241 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
7242 be selected using completion. The path to the file will be relative to the
7243 current directory if the file is in the current directory or a subdirectory.
7244 Otherwise, the link will be the absolute path as completed in the minibuffer
7245 \(i.e. normally ~/path/to/file). You can configure this behavior using the
7246 option `org-link-file-path-type'.
7248 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
7249 the current directory or below.
7251 With three \\[universal-argument] prefixes, negate the meaning of
7252 `org-keep-stored-link-after-insertion'.
7254 If `org-make-link-description-function' is non-nil, this function will be
7255 called with the link target, and the result will be the default
7256 link description.
7258 If the LINK-LOCATION parameter is non-nil, this value will be
7259 used as the link location instead of reading one interactively."
7260 (interactive "P")
7261 (let* ((wcf (current-window-configuration))
7262 (region (if (org-region-active-p)
7263 (buffer-substring (region-beginning) (region-end))))
7264 (remove (and region (list (region-beginning) (region-end))))
7265 (desc region)
7266 tmphist ; byte-compile incorrectly complains about this
7267 (link link-location)
7268 entry file)
7269 (cond
7270 (link-location) ; specified by arg, just use it.
7271 ((org-in-regexp org-bracket-link-regexp 1)
7272 ;; We do have a link at point, and we are going to edit it.
7273 (setq remove (list (match-beginning 0) (match-end 0)))
7274 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
7275 (setq link (read-string "Link: "
7276 (org-link-unescape
7277 (org-match-string-no-properties 1)))))
7278 ((or (org-in-regexp org-angle-link-re)
7279 (org-in-regexp org-plain-link-re))
7280 ;; Convert to bracket link
7281 (setq remove (list (match-beginning 0) (match-end 0))
7282 link (read-string "Link: "
7283 (org-remove-angle-brackets (match-string 0)))))
7284 ((member complete-file '((4) (16)))
7285 ;; Completing read for file names.
7286 (setq file (read-file-name "File: "))
7287 (let ((pwd (file-name-as-directory (expand-file-name ".")))
7288 (pwd1 (file-name-as-directory (abbreviate-file-name
7289 (expand-file-name ".")))))
7290 (cond
7291 ((equal complete-file '(16))
7292 (setq link (org-make-link
7293 "file:"
7294 (abbreviate-file-name (expand-file-name file)))))
7295 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
7296 (setq link (org-make-link "file:" (match-string 1 file))))
7297 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
7298 (expand-file-name file))
7299 (setq link (org-make-link
7300 "file:" (match-string 1 (expand-file-name file)))))
7301 (t (setq link (org-make-link "file:" file))))))
7303 ;; Read link, with completion for stored links.
7304 (with-output-to-temp-buffer "*Org Links*"
7305 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
7306 (when org-stored-links
7307 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
7308 (princ (mapconcat
7309 (lambda (x)
7310 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
7311 (reverse org-stored-links) "\n"))))
7312 (let ((cw (selected-window)))
7313 (select-window (get-buffer-window "*Org Links*"))
7314 (setq truncate-lines t)
7315 (org-fit-window-to-buffer)
7316 (select-window cw))
7317 ;; Fake a link history, containing the stored links.
7318 (setq tmphist (append (mapcar 'car org-stored-links)
7319 org-insert-link-history))
7320 (unwind-protect
7321 (setq link
7322 (let ((org-completion-use-ido nil))
7323 (org-completing-read
7324 "Link: "
7325 (append
7326 (mapcar (lambda (x) (list (concat (car x) ":")))
7327 (append org-link-abbrev-alist-local org-link-abbrev-alist))
7328 (mapcar (lambda (x) (list (concat x ":")))
7329 org-link-types))
7330 nil nil nil
7331 'tmphist
7332 (or (car (car org-stored-links))))))
7333 (set-window-configuration wcf)
7334 (kill-buffer "*Org Links*"))
7335 (setq entry (assoc link org-stored-links))
7336 (or entry (push link org-insert-link-history))
7337 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
7338 (not org-keep-stored-link-after-insertion))
7339 (setq org-stored-links (delq (assoc link org-stored-links)
7340 org-stored-links)))
7341 (setq desc (or desc (nth 1 entry)))))
7343 (if (string-match org-plain-link-re link)
7344 ;; URL-like link, normalize the use of angular brackets.
7345 (setq link (org-make-link (org-remove-angle-brackets link))))
7347 ;; Check if we are linking to the current file with a search option
7348 ;; If yes, simplify the link by using only the search option.
7349 (when (and buffer-file-name
7350 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
7351 (let* ((path (match-string 1 link))
7352 (case-fold-search nil)
7353 (search (match-string 2 link)))
7354 (save-match-data
7355 (if (equal (file-truename buffer-file-name) (file-truename path))
7356 ;; We are linking to this same file, with a search option
7357 (setq link search)))))
7359 ;; Check if we can/should use a relative path. If yes, simplify the link
7360 (when (string-match "^file:\\(.*\\)" link)
7361 (let* ((path (match-string 1 link))
7362 (origpath path)
7363 (case-fold-search nil))
7364 (cond
7365 ((or (eq org-link-file-path-type 'absolute)
7366 (equal complete-file '(16)))
7367 (setq path (abbreviate-file-name (expand-file-name path))))
7368 ((eq org-link-file-path-type 'noabbrev)
7369 (setq path (expand-file-name path)))
7370 ((eq org-link-file-path-type 'relative)
7371 (setq path (file-relative-name path)))
7373 (save-match-data
7374 (if (string-match (concat "^" (regexp-quote
7375 (file-name-as-directory
7376 (expand-file-name "."))))
7377 (expand-file-name path))
7378 ;; We are linking a file with relative path name.
7379 (setq path (substring (expand-file-name path)
7380 (match-end 0)))
7381 (setq path (abbreviate-file-name (expand-file-name path)))))))
7382 (setq link (concat "file:" path))
7383 (if (equal desc origpath)
7384 (setq desc path))))
7386 (if org-make-link-description-function
7387 (setq desc (funcall org-make-link-description-function link desc)))
7389 (setq desc (read-string "Description: " desc))
7390 (unless (string-match "\\S-" desc) (setq desc nil))
7391 (if remove (apply 'delete-region remove))
7392 (insert (org-make-link-string link desc))))
7394 (defun org-completing-read (&rest args)
7395 "Completing-read with SPACE being a normal character."
7396 (let ((minibuffer-local-completion-map
7397 (copy-keymap minibuffer-local-completion-map)))
7398 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
7399 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
7400 (apply 'org-ido-completing-read args)))
7402 (defun org-completing-read-no-ido (&rest args)
7403 (let (org-completion-use-ido)
7404 (apply 'org-completing-read args)))
7406 (defun org-ido-completing-read (&rest args)
7407 "Completing-read using `ido-mode' speedups if available"
7408 (if (and org-completion-use-ido
7409 (fboundp 'ido-completing-read)
7410 (boundp 'ido-mode) ido-mode
7411 (listp (second args)))
7412 (let ((ido-enter-matching-directory nil))
7413 (apply 'ido-completing-read (concat (car args))
7414 (mapcar (lambda (x) (car x)) (nth 1 args))
7415 (cddr args)))
7416 (apply 'completing-read args)))
7418 (defun org-extract-attributes (s)
7419 "Extract the attributes cookie from a string and set as text property."
7420 (let (a attr (start 0) key value)
7421 (save-match-data
7422 (when (string-match "{{\\([^}]+\\)}}$" s)
7423 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
7424 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
7425 (setq key (match-string 1 a) value (match-string 2 a)
7426 start (match-end 0)
7427 attr (plist-put attr (intern key) value))))
7428 (org-add-props s nil 'org-attr attr))
7431 (defun org-extract-attributes-from-string (tag)
7432 (let (key value attr)
7433 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
7434 (setq key (match-string 1 tag) value (match-string 2 tag)
7435 tag (replace-match "" t t tag)
7436 attr (plist-put attr (intern key) value)))
7437 (cons tag attr)))
7439 (defun org-attributes-to-string (plist)
7440 "Format a property list into an HTML attribute list."
7441 (let ((s "") key value)
7442 (while plist
7443 (setq key (pop plist) value (pop plist))
7444 (and value
7445 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
7448 ;;; Opening/following a link
7450 (defvar org-link-search-failed nil)
7452 (defun org-next-link ()
7453 "Move forward to the next link.
7454 If the link is in hidden text, expose it."
7455 (interactive)
7456 (when (and org-link-search-failed (eq this-command last-command))
7457 (goto-char (point-min))
7458 (message "Link search wrapped back to beginning of buffer"))
7459 (setq org-link-search-failed nil)
7460 (let* ((pos (point))
7461 (ct (org-context))
7462 (a (assoc :link ct)))
7463 (if a (goto-char (nth 2 a)))
7464 (if (re-search-forward org-any-link-re nil t)
7465 (progn
7466 (goto-char (match-beginning 0))
7467 (if (org-invisible-p) (org-show-context)))
7468 (goto-char pos)
7469 (setq org-link-search-failed t)
7470 (error "No further link found"))))
7472 (defun org-previous-link ()
7473 "Move backward to the previous link.
7474 If the link is in hidden text, expose it."
7475 (interactive)
7476 (when (and org-link-search-failed (eq this-command last-command))
7477 (goto-char (point-max))
7478 (message "Link search wrapped back to end of buffer"))
7479 (setq org-link-search-failed nil)
7480 (let* ((pos (point))
7481 (ct (org-context))
7482 (a (assoc :link ct)))
7483 (if a (goto-char (nth 1 a)))
7484 (if (re-search-backward org-any-link-re nil t)
7485 (progn
7486 (goto-char (match-beginning 0))
7487 (if (org-invisible-p) (org-show-context)))
7488 (goto-char pos)
7489 (setq org-link-search-failed t)
7490 (error "No further link found"))))
7492 (defun org-translate-link (s)
7493 "Translate a link string if a translation function has been defined."
7494 (if (and org-link-translation-function
7495 (fboundp org-link-translation-function)
7496 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
7497 (progn
7498 (setq s (funcall org-link-translation-function
7499 (match-string 1) (match-string 2)))
7500 (concat (car s) ":" (cdr s)))
7503 (defun org-translate-link-from-planner (type path)
7504 "Translate a link from Emacs Planner syntax so that Org can follow it.
7505 This is still an experimental function, your mileage may vary."
7506 (cond
7507 ((member type '("http" "https" "news" "ftp"))
7508 ;; standard Internet links are the same.
7509 nil)
7510 ((and (equal type "irc") (string-match "^//" path))
7511 ;; Planner has two / at the beginning of an irc link, we have 1.
7512 ;; We should have zero, actually....
7513 (setq path (substring path 1)))
7514 ((and (equal type "lisp") (string-match "^/" path))
7515 ;; Planner has a slash, we do not.
7516 (setq type "elisp" path (substring path 1)))
7517 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
7518 ;; A typical message link. Planner has the id after the fina slash,
7519 ;; we separate it with a hash mark
7520 (setq path (concat (match-string 1 path) "#"
7521 (org-remove-angle-brackets (match-string 2 path)))))
7523 (cons type path))
7525 (defun org-find-file-at-mouse (ev)
7526 "Open file link or URL at mouse."
7527 (interactive "e")
7528 (mouse-set-point ev)
7529 (org-open-at-point 'in-emacs))
7531 (defun org-open-at-mouse (ev)
7532 "Open file link or URL at mouse."
7533 (interactive "e")
7534 (mouse-set-point ev)
7535 (if (eq major-mode 'org-agenda-mode)
7536 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
7537 (org-open-at-point))
7539 (defvar org-window-config-before-follow-link nil
7540 "The window configuration before following a link.
7541 This is saved in case the need arises to restore it.")
7543 (defvar org-open-link-marker (make-marker)
7544 "Marker pointing to the location where `org-open-at-point; was called.")
7546 ;;;###autoload
7547 (defun org-open-at-point-global ()
7548 "Follow a link like Org-mode does.
7549 This command can be called in any mode to follow a link that has
7550 Org-mode syntax."
7551 (interactive)
7552 (org-run-like-in-org-mode 'org-open-at-point))
7554 ;;;###autoload
7555 (defun org-open-link-from-string (s &optional arg)
7556 "Open a link in the string S, as if it was in Org-mode."
7557 (interactive "sLink: \nP")
7558 (let ((reference-buffer (current-buffer)))
7559 (with-temp-buffer
7560 (let ((org-inhibit-startup t))
7561 (org-mode)
7562 (insert s)
7563 (goto-char (point-min))
7564 (org-open-at-point arg reference-buffer)))))
7566 (defun org-open-at-point (&optional in-emacs reference-buffer)
7567 "Open link at or after point.
7568 If there is no link at point, this function will search forward up to
7569 the end of the current line.
7570 Normally, files will be opened by an appropriate application. If the
7571 optional argument IN-EMACS is non-nil, Emacs will visit the file.
7572 With a double prefix argument, try to open outside of Emacs, in the
7573 application the system uses for this file type."
7574 (interactive "P")
7575 (org-load-modules-maybe)
7576 (move-marker org-open-link-marker (point))
7577 (setq org-window-config-before-follow-link (current-window-configuration))
7578 (org-remove-occur-highlights nil nil t)
7579 (cond
7580 ((org-at-timestamp-p t) (org-follow-timestamp-link))
7581 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
7582 (org-footnote-action))
7584 (let (type path link line search (pos (point)))
7585 (catch 'match
7586 (save-excursion
7587 (skip-chars-forward "^]\n\r")
7588 (when (org-in-regexp org-bracket-link-regexp)
7589 (setq link (org-extract-attributes
7590 (org-link-unescape (org-match-string-no-properties 1))))
7591 (while (string-match " *\n *" link)
7592 (setq link (replace-match " " t t link)))
7593 (setq link (org-link-expand-abbrev link))
7594 (cond
7595 ((or (file-name-absolute-p link)
7596 (string-match "^\\.\\.?/" link))
7597 (setq type "file" path link))
7598 ((string-match org-link-re-with-space3 link)
7599 (setq type (match-string 1 link) path (match-string 2 link)))
7600 (t (setq type "thisfile" path link)))
7601 (throw 'match t)))
7603 (when (get-text-property (point) 'org-linked-text)
7604 (setq type "thisfile"
7605 pos (if (get-text-property (1+ (point)) 'org-linked-text)
7606 (1+ (point)) (point))
7607 path (buffer-substring
7608 (previous-single-property-change pos 'org-linked-text)
7609 (next-single-property-change pos 'org-linked-text)))
7610 (throw 'match t))
7612 (save-excursion
7613 (when (or (org-in-regexp org-angle-link-re)
7614 (org-in-regexp org-plain-link-re))
7615 (setq type (match-string 1) path (match-string 2))
7616 (throw 'match t)))
7617 (save-excursion
7618 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
7619 (setq type "tags"
7620 path (match-string 1))
7621 (while (string-match ":" path)
7622 (setq path (replace-match "+" t t path)))
7623 (throw 'match t)))
7624 (when (org-in-regexp "<\\([^><\n]+\\)>")
7625 (setq type "tree-match"
7626 path (match-string 1))
7627 (throw 'match t)))
7628 (unless path
7629 (error "No link found"))
7631 ;; switch back to reference buffer
7632 ;; needed when if called in a temporary buffer through
7633 ;; org-open-link-from-string
7634 (and reference-buffer (switch-to-buffer reference-buffer))
7636 ;; Remove any trailing spaces in path
7637 (if (string-match " +\\'" path)
7638 (setq path (replace-match "" t t path)))
7639 (if (and org-link-translation-function
7640 (fboundp org-link-translation-function))
7641 ;; Check if we need to translate the link
7642 (let ((tmp (funcall org-link-translation-function type path)))
7643 (setq type (car tmp) path (cdr tmp))))
7645 (cond
7647 ((assoc type org-link-protocols)
7648 (funcall (nth 1 (assoc type org-link-protocols)) path))
7650 ((equal type "mailto")
7651 (let ((cmd (car org-link-mailto-program))
7652 (args (cdr org-link-mailto-program)) args1
7653 (address path) (subject "") a)
7654 (if (string-match "\\(.*\\)::\\(.*\\)" path)
7655 (setq address (match-string 1 path)
7656 subject (org-link-escape (match-string 2 path))))
7657 (while args
7658 (cond
7659 ((not (stringp (car args))) (push (pop args) args1))
7660 (t (setq a (pop args))
7661 (if (string-match "%a" a)
7662 (setq a (replace-match address t t a)))
7663 (if (string-match "%s" a)
7664 (setq a (replace-match subject t t a)))
7665 (push a args1))))
7666 (apply cmd (nreverse args1))))
7668 ((member type '("http" "https" "ftp" "news"))
7669 (browse-url (concat type ":" (org-link-escape
7670 path org-link-escape-chars-browser))))
7672 ((member type '("message"))
7673 (browse-url (concat type ":" path)))
7675 ((string= type "tags")
7676 (org-tags-view in-emacs path))
7677 ((string= type "thisfile")
7678 (if in-emacs
7679 (switch-to-buffer-other-window
7680 (org-get-buffer-for-internal-link (current-buffer)))
7681 (org-mark-ring-push))
7682 (let ((cmd `(org-link-search
7683 ,path
7684 ,(cond ((equal in-emacs '(4)) 'occur)
7685 ((equal in-emacs '(16)) 'org-occur)
7686 (t nil))
7687 ,pos)))
7688 (condition-case nil (eval cmd)
7689 (error (progn (widen) (eval cmd))))))
7691 ((string= type "tree-match")
7692 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
7694 ((string= type "file")
7695 (if (string-match "::\\([0-9]+\\)\\'" path)
7696 (setq line (string-to-number (match-string 1 path))
7697 path (substring path 0 (match-beginning 0)))
7698 (if (string-match "::\\(.+\\)\\'" path)
7699 (setq search (match-string 1 path)
7700 path (substring path 0 (match-beginning 0)))))
7701 (if (string-match "[*?{]" (file-name-nondirectory path))
7702 (dired path)
7703 (org-open-file path in-emacs line search)))
7705 ((string= type "news")
7706 (require 'org-gnus)
7707 (org-gnus-follow-link path))
7709 ((string= type "shell")
7710 (let ((cmd path))
7711 (if (or (not org-confirm-shell-link-function)
7712 (funcall org-confirm-shell-link-function
7713 (format "Execute \"%s\" in shell? "
7714 (org-add-props cmd nil
7715 'face 'org-warning))))
7716 (progn
7717 (message "Executing %s" cmd)
7718 (shell-command cmd))
7719 (error "Abort"))))
7721 ((string= type "elisp")
7722 (let ((cmd path))
7723 (if (or (not org-confirm-elisp-link-function)
7724 (funcall org-confirm-elisp-link-function
7725 (format "Execute \"%s\" as elisp? "
7726 (org-add-props cmd nil
7727 'face 'org-warning))))
7728 (message "%s => %s" cmd
7729 (if (equal (string-to-char cmd) ?\()
7730 (eval (read cmd))
7731 (call-interactively (read cmd))))
7732 (error "Abort"))))
7735 (browse-url-at-point))))))
7736 (move-marker org-open-link-marker nil)
7737 (run-hook-with-args 'org-follow-link-hook))
7739 ;;;; Time estimates
7741 (defun org-get-effort (&optional pom)
7742 "Get the effort estimate for the current entry."
7743 (org-entry-get pom org-effort-property))
7745 ;;; File search
7747 (defvar org-create-file-search-functions nil
7748 "List of functions to construct the right search string for a file link.
7749 These functions are called in turn with point at the location to
7750 which the link should point.
7752 A function in the hook should first test if it would like to
7753 handle this file type, for example by checking the major-mode or
7754 the file extension. If it decides not to handle this file, it
7755 should just return nil to give other functions a chance. If it
7756 does handle the file, it must return the search string to be used
7757 when following the link. The search string will be part of the
7758 file link, given after a double colon, and `org-open-at-point'
7759 will automatically search for it. If special measures must be
7760 taken to make the search successful, another function should be
7761 added to the companion hook `org-execute-file-search-functions',
7762 which see.
7764 A function in this hook may also use `setq' to set the variable
7765 `description' to provide a suggestion for the descriptive text to
7766 be used for this link when it gets inserted into an Org-mode
7767 buffer with \\[org-insert-link].")
7769 (defvar org-execute-file-search-functions nil
7770 "List of functions to execute a file search triggered by a link.
7772 Functions added to this hook must accept a single argument, the
7773 search string that was part of the file link, the part after the
7774 double colon. The function must first check if it would like to
7775 handle this search, for example by checking the major-mode or the
7776 file extension. If it decides not to handle this search, it
7777 should just return nil to give other functions a chance. If it
7778 does handle the search, it must return a non-nil value to keep
7779 other functions from trying.
7781 Each function can access the current prefix argument through the
7782 variable `current-prefix-argument'. Note that a single prefix is
7783 used to force opening a link in Emacs, so it may be good to only
7784 use a numeric or double prefix to guide the search function.
7786 In case this is needed, a function in this hook can also restore
7787 the window configuration before `org-open-at-point' was called using:
7789 (set-window-configuration org-window-config-before-follow-link)")
7791 (defun org-link-search (s &optional type avoid-pos)
7792 "Search for a link search option.
7793 If S is surrounded by forward slashes, it is interpreted as a
7794 regular expression. In org-mode files, this will create an `org-occur'
7795 sparse tree. In ordinary files, `occur' will be used to list matches.
7796 If the current buffer is in `dired-mode', grep will be used to search
7797 in all files. If AVOID-POS is given, ignore matches near that position."
7798 (let ((case-fold-search t)
7799 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
7800 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
7801 (append '(("") (" ") ("\t") ("\n"))
7802 org-emphasis-alist)
7803 "\\|") "\\)"))
7804 (pos (point))
7805 (pre nil) (post nil)
7806 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
7807 (cond
7808 ;; First check if there are any special
7809 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
7810 ;; Now try the builtin stuff
7811 ((and (equal (string-to-char s0) ?#)
7812 (> (length s0) 1)
7813 (save-excursion
7814 (goto-char (point-min))
7815 (and
7816 (re-search-forward
7817 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
7818 (setq type 'dedicated
7819 pos (match-beginning 0))))
7820 ;; There is an exact target for this
7821 (goto-char pos)
7822 (org-back-to-heading t)))
7823 ((save-excursion
7824 (goto-char (point-min))
7825 (and
7826 (re-search-forward
7827 (concat "<<" (regexp-quote s0) ">>") nil t)
7828 (setq type 'dedicated
7829 pos (match-beginning 0))))
7830 ;; There is an exact target for this
7831 (goto-char pos))
7832 ((and (string-match "^(\\(.*\\))$" s0)
7833 (save-excursion
7834 (goto-char (point-min))
7835 (and
7836 (re-search-forward
7837 (concat "[^[]" (regexp-quote
7838 (format org-coderef-label-format
7839 (match-string 1 s0))))
7840 nil t)
7841 (setq type 'dedicated
7842 pos (1+ (match-beginning 0))))))
7843 ;; There is a coderef target for this
7844 (goto-char pos))
7845 ((string-match "^/\\(.*\\)/$" s)
7846 ;; A regular expression
7847 (cond
7848 ((org-mode-p)
7849 (org-occur (match-string 1 s)))
7850 ;;((eq major-mode 'dired-mode)
7851 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
7852 (t (org-do-occur (match-string 1 s)))))
7854 ;; A normal search strings
7855 (when (equal (string-to-char s) ?*)
7856 ;; Anchor on headlines, post may include tags.
7857 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
7858 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
7859 s (substring s 1)))
7860 (remove-text-properties
7861 0 (length s)
7862 '(face nil mouse-face nil keymap nil fontified nil) s)
7863 ;; Make a series of regular expressions to find a match
7864 (setq words (org-split-string s "[ \n\r\t]+")
7866 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
7867 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
7868 "\\)" markers)
7869 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
7870 re2a (concat "[ \t\r\n]" re2a_)
7871 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
7872 re4 (concat "[^a-zA-Z_]" re4_)
7874 re1 (concat pre re2 post)
7875 re3 (concat pre (if pre re4_ re4) post)
7876 re5 (concat pre ".*" re4)
7877 re2 (concat pre re2)
7878 re2a (concat pre (if pre re2a_ re2a))
7879 re4 (concat pre (if pre re4_ re4))
7880 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7881 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7882 re5 "\\)"
7884 (cond
7885 ((eq type 'org-occur) (org-occur reall))
7886 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7887 (t (goto-char (point-min))
7888 (setq type 'fuzzy)
7889 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
7890 (org-search-not-self 1 re1 nil t)
7891 (org-search-not-self 1 re2 nil t)
7892 (org-search-not-self 1 re2a nil t)
7893 (org-search-not-self 1 re3 nil t)
7894 (org-search-not-self 1 re4 nil t)
7895 (org-search-not-self 1 re5 nil t)
7897 (goto-char (match-beginning 1))
7898 (goto-char pos)
7899 (error "No match")))))
7901 ;; Normal string-search
7902 (goto-char (point-min))
7903 (if (search-forward s nil t)
7904 (goto-char (match-beginning 0))
7905 (error "No match"))))
7906 (and (org-mode-p) (org-show-context 'link-search))
7907 type))
7909 (defun org-search-not-self (group &rest args)
7910 "Execute `re-search-forward', but only accept matches that do not
7911 enclose the position of `org-open-link-marker'."
7912 (let ((m org-open-link-marker))
7913 (catch 'exit
7914 (while (apply 're-search-forward args)
7915 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
7916 (goto-char (match-end group))
7917 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
7918 (> (match-beginning 0) (marker-position m))
7919 (< (match-end 0) (marker-position m)))
7920 (save-match-data
7921 (or (not (org-in-regexp
7922 org-bracket-link-analytic-regexp 1))
7923 (not (match-end 4)) ; no description
7924 (and (<= (match-beginning 4) (point))
7925 (>= (match-end 4) (point))))))
7926 (throw 'exit (point))))))))
7928 (defun org-get-buffer-for-internal-link (buffer)
7929 "Return a buffer to be used for displaying the link target of internal links."
7930 (cond
7931 ((not org-display-internal-link-with-indirect-buffer)
7932 buffer)
7933 ((string-match "(Clone)$" (buffer-name buffer))
7934 (message "Buffer is already a clone, not making another one")
7935 ;; we also do not modify visibility in this case
7936 buffer)
7937 (t ; make a new indirect buffer for displaying the link
7938 (let* ((bn (buffer-name buffer))
7939 (ibn (concat bn "(Clone)"))
7940 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
7941 (with-current-buffer ib (org-overview))
7942 ib))))
7944 (defun org-do-occur (regexp &optional cleanup)
7945 "Call the Emacs command `occur'.
7946 If CLEANUP is non-nil, remove the printout of the regular expression
7947 in the *Occur* buffer. This is useful if the regex is long and not useful
7948 to read."
7949 (occur regexp)
7950 (when cleanup
7951 (let ((cwin (selected-window)) win beg end)
7952 (when (setq win (get-buffer-window "*Occur*"))
7953 (select-window win))
7954 (goto-char (point-min))
7955 (when (re-search-forward "match[a-z]+" nil t)
7956 (setq beg (match-end 0))
7957 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7958 (setq end (1- (match-beginning 0)))))
7959 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
7960 (goto-char (point-min))
7961 (select-window cwin))))
7963 ;;; The mark ring for links jumps
7965 (defvar org-mark-ring nil
7966 "Mark ring for positions before jumps in Org-mode.")
7967 (defvar org-mark-ring-last-goto nil
7968 "Last position in the mark ring used to go back.")
7969 ;; Fill and close the ring
7970 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7971 (loop for i from 1 to org-mark-ring-length do
7972 (push (make-marker) org-mark-ring))
7973 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7974 org-mark-ring)
7976 (defun org-mark-ring-push (&optional pos buffer)
7977 "Put the current position or POS into the mark ring and rotate it."
7978 (interactive)
7979 (setq pos (or pos (point)))
7980 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7981 (move-marker (car org-mark-ring)
7982 (or pos (point))
7983 (or buffer (current-buffer)))
7984 (message "%s"
7985 (substitute-command-keys
7986 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7988 (defun org-mark-ring-goto (&optional n)
7989 "Jump to the previous position in the mark ring.
7990 With prefix arg N, jump back that many stored positions. When
7991 called several times in succession, walk through the entire ring.
7992 Org-mode commands jumping to a different position in the current file,
7993 or to another Org-mode file, automatically push the old position
7994 onto the ring."
7995 (interactive "p")
7996 (let (p m)
7997 (if (eq last-command this-command)
7998 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7999 (setq p org-mark-ring))
8000 (setq org-mark-ring-last-goto p)
8001 (setq m (car p))
8002 (switch-to-buffer (marker-buffer m))
8003 (goto-char m)
8004 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
8006 (defun org-remove-angle-brackets (s)
8007 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
8008 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
8010 (defun org-add-angle-brackets (s)
8011 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
8012 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
8014 (defun org-remove-double-quotes (s)
8015 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
8016 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
8019 ;;; Following specific links
8021 (defun org-follow-timestamp-link ()
8022 (cond
8023 ((org-at-date-range-p t)
8024 (let ((org-agenda-start-on-weekday)
8025 (t1 (match-string 1))
8026 (t2 (match-string 2)))
8027 (setq t1 (time-to-days (org-time-string-to-time t1))
8028 t2 (time-to-days (org-time-string-to-time t2)))
8029 (org-agenda-list nil t1 (1+ (- t2 t1)))))
8030 ((org-at-timestamp-p t)
8031 (org-agenda-list nil (time-to-days (org-time-string-to-time
8032 (substring (match-string 1) 0 10)))
8034 (t (error "This should not happen"))))
8037 ;;; Following file links
8038 (defvar org-wait nil)
8039 (defun org-open-file (path &optional in-emacs line search)
8040 "Open the file at PATH.
8041 First, this expands any special file name abbreviations. Then the
8042 configuration variable `org-file-apps' is checked if it contains an
8043 entry for this file type, and if yes, the corresponding command is launched.
8045 If no application is found, Emacs simply visits the file.
8047 With optional prefix argument IN-EMACS, Emacs will visit the file.
8048 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
8049 and o use an external application to visit the file.
8051 Optional LINE specifies a line to go to, optional SEARCH a string to
8052 search for. If LINE or SEARCH is given, the file will always be
8053 opened in Emacs.
8054 If the file does not exist, an error is thrown."
8055 (setq in-emacs (or in-emacs line search))
8056 (let* ((file (if (equal path "")
8057 buffer-file-name
8058 (substitute-in-file-name (expand-file-name path))))
8059 (apps (append org-file-apps (org-default-apps)))
8060 (remp (and (assq 'remote apps) (org-file-remote-p file)))
8061 (dirp (if remp nil (file-directory-p file)))
8062 (file (if (and dirp org-open-directory-means-index-dot-org)
8063 (concat (file-name-as-directory file) "index.org")
8064 file))
8065 (a-m-a-p (assq 'auto-mode apps))
8066 (dfile (downcase file))
8067 (old-buffer (current-buffer))
8068 (old-pos (point))
8069 (old-mode major-mode)
8070 ext cmd)
8071 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
8072 (setq ext (match-string 1 dfile))
8073 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
8074 (setq ext (match-string 1 dfile))))
8075 (cond
8076 ((equal in-emacs '(16))
8077 (setq cmd (cdr (assoc 'system apps))))
8078 (in-emacs (setq cmd 'emacs))
8080 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
8081 (and dirp (cdr (assoc 'directory apps)))
8082 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
8083 'string-match)
8084 (cdr (assoc ext apps))
8085 (cdr (assoc t apps))))))
8086 (when (eq cmd 'system)
8087 (setq cmd (cdr (assoc 'system apps))))
8088 (when (eq cmd 'default)
8089 (setq cmd (cdr (assoc t apps))))
8090 (when (eq cmd 'mailcap)
8091 (require 'mailcap)
8092 (mailcap-parse-mailcaps)
8093 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
8094 (command (mailcap-mime-info mime-type)))
8095 (if (stringp command)
8096 (setq cmd command)
8097 (setq cmd 'emacs))))
8098 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
8099 (not (file-exists-p file))
8100 (not org-open-non-existing-files))
8101 (error "No such file: %s" file))
8102 (cond
8103 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
8104 ;; Remove quotes around the file name - we'll use shell-quote-argument.
8105 (while (string-match "['\"]%s['\"]" cmd)
8106 (setq cmd (replace-match "%s" t t cmd)))
8107 (while (string-match "%s" cmd)
8108 (setq cmd (replace-match
8109 (save-match-data
8110 (shell-quote-argument
8111 (convert-standard-filename file)))
8112 t t cmd)))
8113 (save-window-excursion
8114 (start-process-shell-command cmd nil cmd)
8115 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
8117 ((or (stringp cmd)
8118 (eq cmd 'emacs))
8119 (funcall (cdr (assq 'file org-link-frame-setup)) file)
8120 (widen)
8121 (if line (goto-line line)
8122 (if search (org-link-search search))))
8123 ((consp cmd)
8124 (let ((file (convert-standard-filename file)))
8125 (eval cmd)))
8126 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
8127 (and (org-mode-p) (eq old-mode 'org-mode)
8128 (or (not (equal old-buffer (current-buffer)))
8129 (not (equal old-pos (point))))
8130 (org-mark-ring-push old-pos old-buffer))))
8132 (defun org-default-apps ()
8133 "Return the default applications for this operating system."
8134 (cond
8135 ((eq system-type 'darwin)
8136 org-file-apps-defaults-macosx)
8137 ((eq system-type 'windows-nt)
8138 org-file-apps-defaults-windowsnt)
8139 (t org-file-apps-defaults-gnu)))
8141 (defun org-apps-regexp-alist (list &optional add-auto-mode)
8142 "Convert extensions to regular expressions in the cars of LIST.
8143 Also, weed out any non-string entries, because the return value is used
8144 only for regexp matching.
8145 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
8146 point to the symbol `emacs', indicating that the file should
8147 be opened in Emacs."
8148 (append
8149 (delq nil
8150 (mapcar (lambda (x)
8151 (if (not (stringp (car x)))
8153 (if (string-match "\\W" (car x))
8155 (cons (concat "\\." (car x) "\\'") (cdr x)))))
8156 list))
8157 (if add-auto-mode
8158 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
8160 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
8161 (defun org-file-remote-p (file)
8162 "Test whether FILE specifies a location on a remote system.
8163 Return non-nil if the location is indeed remote.
8165 For example, the filename \"/user@host:/foo\" specifies a location
8166 on the system \"/user@host:\"."
8167 (cond ((fboundp 'file-remote-p)
8168 (file-remote-p file))
8169 ((fboundp 'tramp-handle-file-remote-p)
8170 (tramp-handle-file-remote-p file))
8171 ((and (boundp 'ange-ftp-name-format)
8172 (string-match (car ange-ftp-name-format) file))
8174 (t nil)))
8177 ;;;; Refiling
8179 (defun org-get-org-file ()
8180 "Read a filename, with default directory `org-directory'."
8181 (let ((default (or org-default-notes-file remember-data-file)))
8182 (read-file-name (format "File name [%s]: " default)
8183 (file-name-as-directory org-directory)
8184 default)))
8186 (defun org-notes-order-reversed-p ()
8187 "Check if the current file should receive notes in reversed order."
8188 (cond
8189 ((not org-reverse-note-order) nil)
8190 ((eq t org-reverse-note-order) t)
8191 ((not (listp org-reverse-note-order)) nil)
8192 (t (catch 'exit
8193 (let ((all org-reverse-note-order)
8194 entry)
8195 (while (setq entry (pop all))
8196 (if (string-match (car entry) buffer-file-name)
8197 (throw 'exit (cdr entry))))
8198 nil)))))
8200 (defvar org-refile-target-table nil
8201 "The list of refile targets, created by `org-refile'.")
8203 (defvar org-agenda-new-buffers nil
8204 "Buffers created to visit agenda files.")
8206 (defun org-get-refile-targets (&optional default-buffer)
8207 "Produce a table with refile targets."
8208 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
8209 targets txt re files f desc descre fast-path-p level pos0)
8210 (message "Getting targets...")
8211 (with-current-buffer (or default-buffer (current-buffer))
8212 (while (setq entry (pop entries))
8213 (setq files (car entry) desc (cdr entry))
8214 (setq fast-path-p nil)
8215 (cond
8216 ((null files) (setq files (list (current-buffer))))
8217 ((eq files 'org-agenda-files)
8218 (setq files (org-agenda-files 'unrestricted)))
8219 ((and (symbolp files) (fboundp files))
8220 (setq files (funcall files)))
8221 ((and (symbolp files) (boundp files))
8222 (setq files (symbol-value files))))
8223 (if (stringp files) (setq files (list files)))
8224 (cond
8225 ((eq (car desc) :tag)
8226 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
8227 ((eq (car desc) :todo)
8228 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
8229 ((eq (car desc) :regexp)
8230 (setq descre (cdr desc)))
8231 ((eq (car desc) :level)
8232 (setq descre (concat "^\\*\\{" (number-to-string
8233 (if org-odd-levels-only
8234 (1- (* 2 (cdr desc)))
8235 (cdr desc)))
8236 "\\}[ \t]")))
8237 ((eq (car desc) :maxlevel)
8238 (setq fast-path-p t)
8239 (setq descre (concat "^\\*\\{1," (number-to-string
8240 (if org-odd-levels-only
8241 (1- (* 2 (cdr desc)))
8242 (cdr desc)))
8243 "\\}[ \t]")))
8244 (t (error "Bad refiling target description %s" desc)))
8245 (while (setq f (pop files))
8246 (save-excursion
8247 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
8248 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
8249 (setq f (expand-file-name f))
8250 (if (eq org-refile-use-outline-path 'file)
8251 (push (list (file-name-nondirectory f) f nil nil) targets))
8252 (save-excursion
8253 (save-restriction
8254 (widen)
8255 (goto-char (point-min))
8256 (while (re-search-forward descre nil t)
8257 (goto-char (setq pos0 (point-at-bol)))
8258 (catch 'next
8259 (when org-refile-target-verify-function
8260 (save-match-data
8261 (or (funcall org-refile-target-verify-function)
8262 (throw 'next t))))
8263 (when (looking-at org-complex-heading-regexp)
8264 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
8265 txt (org-link-display-format (match-string 4))
8266 re (concat "^" (regexp-quote
8267 (buffer-substring (match-beginning 1)
8268 (match-end 4)))))
8269 (if (match-end 5) (setq re (concat re "[ \t]+"
8270 (regexp-quote
8271 (match-string 5)))))
8272 (setq re (concat re "[ \t]*$"))
8273 (when org-refile-use-outline-path
8274 (setq txt (mapconcat 'org-protect-slash
8275 (append
8276 (if (eq org-refile-use-outline-path 'file)
8277 (list (file-name-nondirectory
8278 (buffer-file-name (buffer-base-buffer))))
8279 (if (eq org-refile-use-outline-path 'full-file-path)
8280 (list (buffer-file-name (buffer-base-buffer)))))
8281 (org-get-outline-path fast-path-p level txt)
8282 (list txt))
8283 "/")))
8284 (push (list txt f re (point)) targets)))
8285 (when (= (point) pos0)
8286 ;; verification function has not moved point
8287 (goto-char (point-at-eol))))))))))
8288 (message "Getting targets...done")
8289 (nreverse targets)))
8291 (defun org-protect-slash (s)
8292 (while (string-match "/" s)
8293 (setq s (replace-match "\\" t t s)))
8296 (defvar org-olpa (make-vector 20 nil))
8298 (defun org-get-outline-path (&optional fastp level heading)
8299 "Return the outline path to the current entry, as a list."
8300 (if fastp
8301 (progn
8302 (if (> level 19)
8303 (error "Outline path failure, more than 19 levels."))
8304 (loop for i from level upto 19 do
8305 (aset org-olpa i nil))
8306 (prog1
8307 (delq nil (append org-olpa nil))
8308 (aset org-olpa level heading)))
8309 (let (rtn)
8310 (save-excursion
8311 (while (org-up-heading-safe)
8312 (when (looking-at org-complex-heading-regexp)
8313 (push (org-match-string-no-properties 4) rtn)))
8314 rtn))))
8316 (defvar org-refile-history nil
8317 "History for refiling operations.")
8319 (defun org-refile (&optional goto default-buffer)
8320 "Move the entry at point to another heading.
8321 The list of target headings is compiled using the information in
8322 `org-refile-targets', which see. This list is created before each use
8323 and will therefore always be up-to-date.
8325 At the target location, the entry is filed as a subitem of the target heading.
8326 Depending on `org-reverse-note-order', the new subitem will either be the
8327 first or the last subitem.
8329 If there is an active region, all entries in that region will be moved.
8330 However, the region must fulfil the requirement that the first heading
8331 is the first one sets the top-level of the moved text - at most siblings
8332 below it are allowed.
8334 With prefix arg GOTO, the command will only visit the target location,
8335 not actually move anything.
8336 With a double prefix `C-u C-u', go to the location where the last refiling
8337 operation has put the subtree.
8339 See also `org-refile-use-outline-path' and `org-completion-use-ido'"
8340 (interactive "P")
8341 (let* ((cbuf (current-buffer))
8342 (regionp (org-region-active-p))
8343 (region-start (and regionp (region-beginning)))
8344 (region-end (and regionp (region-end)))
8345 (region-length (and regionp (- region-end region-start)))
8346 (filename (buffer-file-name (buffer-base-buffer cbuf)))
8347 pos it nbuf file re level reversed)
8348 (when regionp (goto-char region-start)
8349 (unless (org-kill-is-subtree-p
8350 (buffer-substring region-start region-end))
8351 (error "The region is not a (sequence of) subtree(s)")))
8352 (if (equal goto '(16))
8353 (org-refile-goto-last-stored)
8354 (when (setq it (org-refile-get-location
8355 (if goto "Goto: " "Refile to: ") default-buffer
8356 org-refile-allow-creating-parent-nodes))
8357 (setq file (nth 1 it)
8358 re (nth 2 it)
8359 pos (nth 3 it))
8360 (if (and (not goto)
8362 (equal (buffer-file-name) file)
8363 (if regionp
8364 (and (>= pos region-start)
8365 (<= pos region-end))
8366 (and (>= pos (point))
8367 (< pos (save-excursion
8368 (org-end-of-subtree t t))))))
8369 (error "Cannot refile to position inside the tree or region"))
8371 (setq nbuf (or (find-buffer-visiting file)
8372 (find-file-noselect file)))
8373 (if goto
8374 (progn
8375 (switch-to-buffer nbuf)
8376 (goto-char pos)
8377 (org-show-context 'org-goto))
8378 (if regionp
8379 (progn
8380 (kill-new (buffer-substring region-start region-end))
8381 (org-save-markers-in-region region-start region-end))
8382 (org-copy-subtree 1 nil t))
8383 (save-excursion
8384 (set-buffer (setq nbuf (or (find-buffer-visiting file)
8385 (find-file-noselect file))))
8386 (setq reversed (org-notes-order-reversed-p))
8387 (save-excursion
8388 (save-restriction
8389 (widen)
8390 (if pos
8391 (progn
8392 (goto-char pos)
8393 (looking-at outline-regexp)
8394 (setq level (org-get-valid-level (funcall outline-level) 1))
8395 (goto-char
8396 (if reversed
8397 (or (outline-next-heading) (point-max))
8398 (or (save-excursion (outline-get-next-sibling))
8399 (org-end-of-subtree t t)
8400 (point-max)))))
8401 (setq level 1)
8402 (if (not reversed)
8403 (goto-char (point-max))
8404 (goto-char (point-min))
8405 (or (outline-next-heading) (goto-char (point-max)))))
8406 (if (not (bolp)) (newline))
8407 (bookmark-set "org-refile-last-stored")
8408 (org-paste-subtree level))))
8409 (if regionp
8410 (delete-region (point) (+ (point) region-length))
8411 (org-cut-subtree))
8412 (setq org-markers-to-move nil)
8413 (message "Refiled to \"%s\"" (car it))))))
8414 (org-reveal))
8416 (defun org-refile-goto-last-stored ()
8417 "Go to the location where the last refile was stored."
8418 (interactive)
8419 (bookmark-jump "org-refile-last-stored")
8420 (message "This is the location of the last refile"))
8422 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
8423 "Prompt the user for a refile location, using PROMPT."
8424 (let ((org-refile-targets org-refile-targets)
8425 (org-refile-use-outline-path org-refile-use-outline-path))
8426 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
8427 (unless org-refile-target-table
8428 (error "No refile targets"))
8429 (let* ((cbuf (current-buffer))
8430 (partial-completion-mode nil)
8431 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
8432 (cfunc (if (and org-refile-use-outline-path
8433 org-outline-path-complete-in-steps)
8434 'org-olpath-completing-read
8435 'org-ido-completing-read))
8436 (extra (if org-refile-use-outline-path "/" ""))
8437 (filename (and cfn (expand-file-name cfn)))
8438 (tbl (mapcar
8439 (lambda (x)
8440 (if (and (not (member org-refile-use-outline-path
8441 '(file full-file-path)))
8442 (not (equal filename (nth 1 x))))
8443 (cons (concat (car x) extra " ("
8444 (file-name-nondirectory (nth 1 x)) ")")
8445 (cdr x))
8446 (cons (concat (car x) extra) (cdr x))))
8447 org-refile-target-table))
8448 (completion-ignore-case t)
8449 pa answ parent-target child parent)
8450 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
8451 nil 'org-refile-history))
8452 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
8453 (if pa
8455 (when (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
8456 (setq parent (match-string 1 answ)
8457 child (match-string 2 answ))
8458 (setq parent-target (or (assoc parent tbl) (assoc (concat parent "/") tbl)))
8459 (when (and parent-target
8460 (or (eq new-nodes t)
8461 (and (eq new-nodes 'confirm)
8462 (y-or-n-p (format "Create new node \"%s\"? " child)))))
8463 (org-refile-new-child parent-target child))))))
8465 (defun org-refile-new-child (parent-target child)
8466 "Use refile target PARENT-TARGET to add new CHILD below it."
8467 (unless parent-target
8468 (error "Cannot find parent for new node"))
8469 (let ((file (nth 1 parent-target))
8470 (pos (nth 3 parent-target))
8471 level)
8472 (with-current-buffer (or (find-buffer-visiting file)
8473 (find-file-noselect file))
8474 (save-excursion
8475 (save-restriction
8476 (widen)
8477 (if pos
8478 (goto-char pos)
8479 (goto-char (point-max))
8480 (if (not (bolp)) (newline)))
8481 (when (looking-at outline-regexp)
8482 (setq level (funcall outline-level))
8483 (org-end-of-subtree t t))
8484 (org-back-over-empty-lines)
8485 (insert "\n" (make-string
8486 (if pos (org-get-valid-level level 1) 1) ?*)
8487 " " child "\n")
8488 (beginning-of-line 0)
8489 (list (concat (car parent-target) "/" child) file "" (point)))))))
8491 (defun org-olpath-completing-read (prompt collection &rest args)
8492 "Read an outline path like a file name."
8493 (let ((thetable collection)
8494 (org-completion-use-ido nil)) ; does not work with ido.
8495 (apply
8496 'org-ido-completing-read prompt
8497 (lambda (string predicate &optional flag)
8498 (let (rtn r f (l (length string)))
8499 (cond
8500 ((eq flag nil)
8501 ;; try completion
8502 (try-completion string thetable))
8503 ((eq flag t)
8504 ;; all-completions
8505 (setq rtn (all-completions string thetable predicate))
8506 (mapcar
8507 (lambda (x)
8508 (setq r (substring x l))
8509 (if (string-match " ([^)]*)$" x)
8510 (setq f (match-string 0 x))
8511 (setq f ""))
8512 (if (string-match "/" r)
8513 (concat string (substring r 0 (match-end 0)) f)
8515 rtn))
8516 ((eq flag 'lambda)
8517 ;; exact match?
8518 (assoc string thetable)))
8520 args)))
8522 ;;;; Dynamic blocks
8524 (defun org-find-dblock (name)
8525 "Find the first dynamic block with name NAME in the buffer.
8526 If not found, stay at current position and return nil."
8527 (let (pos)
8528 (save-excursion
8529 (goto-char (point-min))
8530 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
8531 nil t)
8532 (match-beginning 0))))
8533 (if pos (goto-char pos))
8534 pos))
8536 (defconst org-dblock-start-re
8537 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
8538 "Matches the startline of a dynamic block, with parameters.")
8540 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
8541 "Matches the end of a dynamic block.")
8543 (defun org-create-dblock (plist)
8544 "Create a dynamic block section, with parameters taken from PLIST.
8545 PLIST must contain a :name entry which is used as name of the block."
8546 (unless (bolp) (newline))
8547 (let ((name (plist-get plist :name)))
8548 (insert "#+BEGIN: " name)
8549 (while plist
8550 (if (eq (car plist) :name)
8551 (setq plist (cddr plist))
8552 (insert " " (prin1-to-string (pop plist)))))
8553 (insert "\n\n#+END:\n")
8554 (beginning-of-line -2)))
8556 (defun org-prepare-dblock ()
8557 "Prepare dynamic block for refresh.
8558 This empties the block, puts the cursor at the insert position and returns
8559 the property list including an extra property :name with the block name."
8560 (unless (looking-at org-dblock-start-re)
8561 (error "Not at a dynamic block"))
8562 (let* ((begdel (1+ (match-end 0)))
8563 (name (org-no-properties (match-string 1)))
8564 (params (append (list :name name)
8565 (read (concat "(" (match-string 3) ")")))))
8566 (unless (re-search-forward org-dblock-end-re nil t)
8567 (error "Dynamic block not terminated"))
8568 (setq params
8569 (append params
8570 (list :content (buffer-substring
8571 begdel (match-beginning 0)))))
8572 (delete-region begdel (match-beginning 0))
8573 (goto-char begdel)
8574 (open-line 1)
8575 params))
8577 (defun org-map-dblocks (&optional command)
8578 "Apply COMMAND to all dynamic blocks in the current buffer.
8579 If COMMAND is not given, use `org-update-dblock'."
8580 (let ((cmd (or command 'org-update-dblock))
8581 pos)
8582 (save-excursion
8583 (goto-char (point-min))
8584 (while (re-search-forward org-dblock-start-re nil t)
8585 (goto-char (setq pos (match-beginning 0)))
8586 (condition-case nil
8587 (funcall cmd)
8588 (error (message "Error during update of dynamic block")))
8589 (goto-char pos)
8590 (unless (re-search-forward org-dblock-end-re nil t)
8591 (error "Dynamic block not terminated"))))))
8593 (defun org-dblock-update (&optional arg)
8594 "User command for updating dynamic blocks.
8595 Update the dynamic block at point. With prefix ARG, update all dynamic
8596 blocks in the buffer."
8597 (interactive "P")
8598 (if arg
8599 (org-update-all-dblocks)
8600 (or (looking-at org-dblock-start-re)
8601 (org-beginning-of-dblock))
8602 (org-update-dblock)))
8604 (defun org-update-dblock ()
8605 "Update the dynamic block at point
8606 This means to empty the block, parse for parameters and then call
8607 the correct writing function."
8608 (save-window-excursion
8609 (let* ((pos (point))
8610 (line (org-current-line))
8611 (params (org-prepare-dblock))
8612 (name (plist-get params :name))
8613 (cmd (intern (concat "org-dblock-write:" name))))
8614 (message "Updating dynamic block `%s' at line %d..." name line)
8615 (funcall cmd params)
8616 (message "Updating dynamic block `%s' at line %d...done" name line)
8617 (goto-char pos))))
8619 (defun org-beginning-of-dblock ()
8620 "Find the beginning of the dynamic block at point.
8621 Error if there is no such block at point."
8622 (let ((pos (point))
8623 beg)
8624 (end-of-line 1)
8625 (if (and (re-search-backward org-dblock-start-re nil t)
8626 (setq beg (match-beginning 0))
8627 (re-search-forward org-dblock-end-re nil t)
8628 (> (match-end 0) pos))
8629 (goto-char beg)
8630 (goto-char pos)
8631 (error "Not in a dynamic block"))))
8633 (defun org-update-all-dblocks ()
8634 "Update all dynamic blocks in the buffer.
8635 This function can be used in a hook."
8636 (when (org-mode-p)
8637 (org-map-dblocks 'org-update-dblock)))
8640 ;;;; Completion
8642 (defconst org-additional-option-like-keywords
8643 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
8644 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
8645 "BEGIN_EXAMPLE" "END_EXAMPLE"
8646 "BEGIN_QUOTE" "END_QUOTE"
8647 "BEGIN_VERSE" "END_VERSE"
8648 "BEGIN_CENTER" "END_CENTER"
8649 "BEGIN_SRC" "END_SRC"
8650 "CATEGORY" "COLUMNS"
8651 "CAPTION" "LABEL" "ATTR_HTML" "ATTR_LaTeX"))
8653 (defcustom org-structure-template-alist
8655 ("s" "#+begin_src ?\n\n#+end_src"
8656 "<src lang=\"?\">\n\n</src>")
8657 ("e" "#+begin_example\n?\n#+end_example"
8658 "<example>\n?\n</example>")
8659 ("q" "#+begin_quote\n?\n#+end_quote"
8660 "<quote>\n?\n</quote>")
8661 ("v" "#+begin_verse\n?\n#+end_verse"
8662 "<verse>\n?\n/verse>")
8663 ("c" "#+begin_center\n?\n#+end_center"
8664 "<center>\n?\n/center>")
8665 ("l" "#+begin_latex\n?\n#+end_latex"
8666 "<literal style=\"latex\">\n?\n</literal>")
8667 ("L" "#+latex: "
8668 "<literal style=\"latex\">?</literal>")
8669 ("h" "#+begin_html\n?\n#+end_html"
8670 "<literal style=\"html\">\n?\n</literal>")
8671 ("H" "#+html: "
8672 "<literal style=\"html\">?</literal>")
8673 ("a" "#+begin_ascii\n?\n#+end_ascii")
8674 ("A" "#+ascii: ")
8675 ("i" "#+include %file ?"
8676 "<include file=%file markup=\"?\">")
8678 "Structure completion elements.
8679 This is a list of abbreviation keys and values. The value gets inserted
8680 it you type @samp{.} followed by the key and then the completion key,
8681 usually `M-TAB'. %file will be replaced by a file name after prompting
8682 for the file using completion.
8683 There are two templates for each key, the first uses the original Org syntax,
8684 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
8685 the default when the /org-mtags.el/ module has been loaded. See also the
8686 variable `org-mtags-prefer-muse-templates'.
8687 This is an experimental feature, it is undecided if it is going to stay in."
8688 :group 'org-completion
8689 :type '(repeat
8690 (string :tag "Key")
8691 (string :tag "Template")
8692 (string :tag "Muse Template")))
8694 (defun org-try-structure-completion ()
8695 "Try to complete a structure template before point.
8696 This looks for strings like \"<e\" on an otherwise empty line and
8697 expands them."
8698 (let ((l (buffer-substring (point-at-bol) (point)))
8700 (when (and (looking-at "[ \t]*$")
8701 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
8702 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
8703 (org-complete-expand-structure-template (+ -1 (point-at-bol)
8704 (match-beginning 1)) a)
8705 t)))
8707 (defun org-complete-expand-structure-template (start cell)
8708 "Expand a structure template."
8709 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
8710 (rpl (nth (if musep 2 1) cell)))
8711 (delete-region start (point))
8712 (when (string-match "\\`#\\+" rpl)
8713 (cond
8714 ((bolp))
8715 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
8716 (delete-region (point-at-bol) (point)))
8717 (t (newline))))
8718 (setq start (point))
8719 (if (string-match "%file" rpl)
8720 (setq rpl (replace-match
8721 (concat
8722 "\""
8723 (save-match-data
8724 (abbreviate-file-name (read-file-name "Include file: ")))
8725 "\"")
8726 t t rpl)))
8727 (insert rpl)
8728 (if (re-search-backward "\\?" start t) (delete-char 1))))
8731 (defun org-complete (&optional arg)
8732 "Perform completion on word at point.
8733 At the beginning of a headline, this completes TODO keywords as given in
8734 `org-todo-keywords'.
8735 If the current word is preceded by a backslash, completes the TeX symbols
8736 that are supported for HTML support.
8737 If the current word is preceded by \"#+\", completes special words for
8738 setting file options.
8739 In the line after \"#+STARTUP:, complete valid keywords.\"
8740 At all other locations, this simply calls the value of
8741 `org-completion-fallback-command'."
8742 (interactive "P")
8743 (org-without-partial-completion
8744 (catch 'exit
8745 (let* ((a nil)
8746 (end (point))
8747 (beg1 (save-excursion
8748 (skip-chars-backward (org-re "[:alnum:]_@"))
8749 (point)))
8750 (beg (save-excursion
8751 (skip-chars-backward "a-zA-Z0-9_:$")
8752 (point)))
8753 (confirm (lambda (x) (stringp (car x))))
8754 (searchhead (equal (char-before beg) ?*))
8755 (struct
8756 (when (and (member (char-before beg1) '(?. ?<))
8757 (setq a (assoc (buffer-substring beg1 (point))
8758 org-structure-template-alist)))
8759 (org-complete-expand-structure-template (1- beg1) a)
8760 (throw 'exit t)))
8761 (tag (and (equal (char-before beg1) ?:)
8762 (equal (char-after (point-at-bol)) ?*)))
8763 (prop (and (equal (char-before beg1) ?:)
8764 (not (equal (char-after (point-at-bol)) ?*))))
8765 (texp (equal (char-before beg) ?\\))
8766 (link (equal (char-before beg) ?\[))
8767 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
8768 beg)
8769 "#+"))
8770 (startup (string-match "^#\\+STARTUP:.*"
8771 (buffer-substring (point-at-bol) (point))))
8772 (completion-ignore-case opt)
8773 (type nil)
8774 (tbl nil)
8775 (table (cond
8776 (opt
8777 (setq type :opt)
8778 (require 'org-exp)
8779 (append
8780 (mapcar
8781 (lambda (x)
8782 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
8783 (cons (match-string 2 x) (match-string 1 x)))
8784 (org-split-string (org-get-current-options) "\n"))
8785 (mapcar 'list org-additional-option-like-keywords)))
8786 (startup
8787 (setq type :startup)
8788 org-startup-options)
8789 (link (append org-link-abbrev-alist-local
8790 org-link-abbrev-alist))
8791 (texp
8792 (setq type :tex)
8793 org-html-entities)
8794 ((string-match "\\`\\*+[ \t]+\\'"
8795 (buffer-substring (point-at-bol) beg))
8796 (setq type :todo)
8797 (mapcar 'list org-todo-keywords-1))
8798 (searchhead
8799 (setq type :searchhead)
8800 (save-excursion
8801 (goto-char (point-min))
8802 (while (re-search-forward org-todo-line-regexp nil t)
8803 (push (list
8804 (org-make-org-heading-search-string
8805 (match-string 3) t))
8806 tbl)))
8807 tbl)
8808 (tag (setq type :tag beg beg1)
8809 (or org-tag-alist (org-get-buffer-tags)))
8810 (prop (setq type :prop beg beg1)
8811 (mapcar 'list (org-buffer-property-keys nil t t)))
8812 (t (progn
8813 (call-interactively org-completion-fallback-command)
8814 (throw 'exit nil)))))
8815 (pattern (buffer-substring-no-properties beg end))
8816 (completion (try-completion pattern table confirm)))
8817 (cond ((eq completion t)
8818 (if (not (assoc (upcase pattern) table))
8819 (message "Already complete")
8820 (if (and (equal type :opt)
8821 (not (member (car (assoc (upcase pattern) table))
8822 org-additional-option-like-keywords)))
8823 (insert (substring (cdr (assoc (upcase pattern) table))
8824 (length pattern)))
8825 (if (memq type '(:tag :prop)) (insert ":")))))
8826 ((null completion)
8827 (message "Can't find completion for \"%s\"" pattern)
8828 (ding))
8829 ((not (string= pattern completion))
8830 (delete-region beg end)
8831 (if (string-match " +$" completion)
8832 (setq completion (replace-match "" t t completion)))
8833 (insert completion)
8834 (if (get-buffer-window "*Completions*")
8835 (delete-window (get-buffer-window "*Completions*")))
8836 (if (assoc completion table)
8837 (if (eq type :todo) (insert " ")
8838 (if (memq type '(:tag :prop)) (insert ":"))))
8839 (if (and (equal type :opt) (assoc completion table))
8840 (message "%s" (substitute-command-keys
8841 "Press \\[org-complete] again to insert example settings"))))
8843 (message "Making completion list...")
8844 (let ((list (sort (all-completions pattern table confirm)
8845 'string<)))
8846 (with-output-to-temp-buffer "*Completions*"
8847 (condition-case nil
8848 ;; Protection needed for XEmacs and emacs 21
8849 (display-completion-list list pattern)
8850 (error (display-completion-list list)))))
8851 (message "Making completion list...%s" "done")))))))
8853 ;;;; TODO, DEADLINE, Comments
8855 (defun org-toggle-comment ()
8856 "Change the COMMENT state of an entry."
8857 (interactive)
8858 (save-excursion
8859 (org-back-to-heading)
8860 (let (case-fold-search)
8861 (if (looking-at (concat outline-regexp
8862 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
8863 (replace-match "" t t nil 1)
8864 (if (looking-at outline-regexp)
8865 (progn
8866 (goto-char (match-end 0))
8867 (insert org-comment-string " ")))))))
8869 (defvar org-last-todo-state-is-todo nil
8870 "This is non-nil when the last TODO state change led to a TODO state.
8871 If the last change removed the TODO tag or switched to DONE, then
8872 this is nil.")
8874 (defvar org-setting-tags nil) ; dynamically skipped
8876 (defun org-parse-local-options (string var)
8877 "Parse STRING for startup setting relevant for variable VAR."
8878 (let ((rtn (symbol-value var))
8879 e opts)
8880 (save-match-data
8881 (if (or (not string) (not (string-match "\\S-" string)))
8883 (setq opts (delq nil (mapcar (lambda (x)
8884 (setq e (assoc x org-startup-options))
8885 (if (eq (nth 1 e) var) e nil))
8886 (org-split-string string "[ \t]+"))))
8887 (if (not opts)
8889 (setq rtn nil)
8890 (while (setq e (pop opts))
8891 (if (not (nth 3 e))
8892 (setq rtn (nth 2 e))
8893 (if (not (listp rtn)) (setq rtn nil))
8894 (push (nth 2 e) rtn)))
8895 rtn)))))
8897 (defvar org-todo-setup-filter-hook nil
8898 "Hook for functions that pre-filter todo specs.
8900 Each function takes a todo spec and returns either `nil' or the spec
8901 transformed into canonical form." )
8903 (defvar org-todo-get-default-hook nil
8904 "Hook for functions that get a default item for todo.
8906 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
8907 `nil' or a string to be used for the todo mark." )
8909 (defvar org-agenda-headline-snapshot-before-repeat)
8910 (defun org-todo (&optional arg)
8911 "Change the TODO state of an item.
8912 The state of an item is given by a keyword at the start of the heading,
8913 like
8914 *** TODO Write paper
8915 *** DONE Call mom
8917 The different keywords are specified in the variable `org-todo-keywords'.
8918 By default the available states are \"TODO\" and \"DONE\".
8919 So for this example: when the item starts with TODO, it is changed to DONE.
8920 When it starts with DONE, the DONE is removed. And when neither TODO nor
8921 DONE are present, add TODO at the beginning of the heading.
8923 With C-u prefix arg, use completion to determine the new state.
8924 With numeric prefix arg, switch to that state.
8925 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
8926 With a tripple C-u prefix, circumvent any state blocking.
8928 For calling through lisp, arg is also interpreted in the following way:
8929 'none -> empty state
8930 \"\"(empty string) -> switch to empty state
8931 'done -> switch to DONE
8932 'nextset -> switch to the next set of keywords
8933 'previousset -> switch to the previous set of keywords
8934 \"WAITING\" -> switch to the specified keyword, but only if it
8935 really is a member of `org-todo-keywords'."
8936 (interactive "P")
8937 (if (equal arg '(16)) (setq arg 'nextset))
8938 (let ((org-blocker-hook org-blocker-hook)
8939 (case-fold-search nil))
8940 (when (equal arg '(64))
8941 (setq arg nil org-blocker-hook nil))
8942 (when (and org-blocker-hook
8943 (org-entry-get nil "NOBLOCKING"))
8944 (setq org-blocker-hook nil))
8945 (save-excursion
8946 (catch 'exit
8947 (org-back-to-heading)
8948 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
8949 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|$\\)"))
8950 (looking-at " *"))
8951 (let* ((match-data (match-data))
8952 (startpos (point-at-bol))
8953 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
8954 (org-log-done org-log-done)
8955 (org-log-repeat org-log-repeat)
8956 (org-todo-log-states org-todo-log-states)
8957 (this (match-string 1))
8958 (hl-pos (match-beginning 0))
8959 (head (org-get-todo-sequence-head this))
8960 (ass (assoc head org-todo-kwd-alist))
8961 (interpret (nth 1 ass))
8962 (done-word (nth 3 ass))
8963 (final-done-word (nth 4 ass))
8964 (last-state (or this ""))
8965 (completion-ignore-case t)
8966 (member (member this org-todo-keywords-1))
8967 (tail (cdr member))
8968 (state (cond
8969 ((and org-todo-key-trigger
8970 (or (and (equal arg '(4))
8971 (eq org-use-fast-todo-selection 'prefix))
8972 (and (not arg) org-use-fast-todo-selection
8973 (not (eq org-use-fast-todo-selection
8974 'prefix)))))
8975 ;; Use fast selection
8976 (org-fast-todo-selection))
8977 ((and (equal arg '(4))
8978 (or (not org-use-fast-todo-selection)
8979 (not org-todo-key-trigger)))
8980 ;; Read a state with completion
8981 (org-ido-completing-read
8982 "State: " (mapcar (lambda(x) (list x))
8983 org-todo-keywords-1)
8984 nil t))
8985 ((eq arg 'right)
8986 (if this
8987 (if tail (car tail) nil)
8988 (car org-todo-keywords-1)))
8989 ((eq arg 'left)
8990 (if (equal member org-todo-keywords-1)
8992 (if this
8993 (nth (- (length org-todo-keywords-1)
8994 (length tail) 2)
8995 org-todo-keywords-1)
8996 (org-last org-todo-keywords-1))))
8997 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
8998 (setq arg nil))) ; hack to fall back to cycling
8999 (arg
9000 ;; user or caller requests a specific state
9001 (cond
9002 ((equal arg "") nil)
9003 ((eq arg 'none) nil)
9004 ((eq arg 'done) (or done-word (car org-done-keywords)))
9005 ((eq arg 'nextset)
9006 (or (car (cdr (member head org-todo-heads)))
9007 (car org-todo-heads)))
9008 ((eq arg 'previousset)
9009 (let ((org-todo-heads (reverse org-todo-heads)))
9010 (or (car (cdr (member head org-todo-heads)))
9011 (car org-todo-heads))))
9012 ((car (member arg org-todo-keywords-1)))
9013 ((nth (1- (prefix-numeric-value arg))
9014 org-todo-keywords-1))))
9015 ((null member) (or head (car org-todo-keywords-1)))
9016 ((equal this final-done-word) nil) ;; -> make empty
9017 ((null tail) nil) ;; -> first entry
9018 ((memq interpret '(type priority))
9019 (if (eq this-command last-command)
9020 (car tail)
9021 (if (> (length tail) 0)
9022 (or done-word (car org-done-keywords))
9023 nil)))
9025 (car tail))))
9026 (state (or
9027 (run-hook-with-args-until-success
9028 'org-todo-get-default-hook state last-state)
9029 state))
9030 (next (if state (concat " " state " ") " "))
9031 (change-plist (list :type 'todo-state-change :from this :to state
9032 :position startpos))
9033 dolog now-done-p)
9034 (when org-blocker-hook
9035 (setq org-last-todo-state-is-todo
9036 (not (member this org-done-keywords)))
9037 (unless (save-excursion
9038 (save-match-data
9039 (run-hook-with-args-until-failure
9040 'org-blocker-hook change-plist)))
9041 (if (interactive-p)
9042 (error "TODO state change from %s to %s blocked" this state)
9043 ;; fail silently
9044 (message "TODO state change from %s to %s blocked" this state)
9045 (throw 'exit nil))))
9046 (store-match-data match-data)
9047 (replace-match next t t)
9048 (unless (pos-visible-in-window-p hl-pos)
9049 (message "TODO state changed to %s" (org-trim next)))
9050 (unless head
9051 (setq head (org-get-todo-sequence-head state)
9052 ass (assoc head org-todo-kwd-alist)
9053 interpret (nth 1 ass)
9054 done-word (nth 3 ass)
9055 final-done-word (nth 4 ass)))
9056 (when (memq arg '(nextset previousset))
9057 (message "Keyword-Set %d/%d: %s"
9058 (- (length org-todo-sets) -1
9059 (length (memq (assoc state org-todo-sets) org-todo-sets)))
9060 (length org-todo-sets)
9061 (mapconcat 'identity (assoc state org-todo-sets) " ")))
9062 (setq org-last-todo-state-is-todo
9063 (not (member state org-done-keywords)))
9064 (setq now-done-p (and (member state org-done-keywords)
9065 (not (member this org-done-keywords))))
9066 (and logging (org-local-logging logging))
9067 (when (and (or org-todo-log-states org-log-done)
9068 (not (memq arg '(nextset previousset))))
9069 ;; we need to look at recording a time and note
9070 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
9071 (nth 2 (assoc this org-todo-log-states))))
9072 (when (and state
9073 (member state org-not-done-keywords)
9074 (not (member this org-not-done-keywords)))
9075 ;; This is now a todo state and was not one before
9076 ;; If there was a CLOSED time stamp, get rid of it.
9077 (org-add-planning-info nil nil 'closed))
9078 (when (and now-done-p org-log-done)
9079 ;; It is now done, and it was not done before
9080 (org-add-planning-info 'closed (org-current-time))
9081 (if (and (not dolog) (eq 'note org-log-done))
9082 (org-add-log-setup 'done state this 'findpos 'note)))
9083 (when (and state dolog)
9084 ;; This is a non-nil state, and we need to log it
9085 (org-add-log-setup 'state state this 'findpos dolog)))
9086 ;; Fixup tag positioning
9087 (org-todo-trigger-tag-changes state)
9088 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
9089 (when org-provide-todo-statistics
9090 (org-update-parent-todo-statistics))
9091 (run-hooks 'org-after-todo-state-change-hook)
9092 (if (and arg (not (member state org-done-keywords)))
9093 (setq head (org-get-todo-sequence-head state)))
9094 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
9095 ;; Do we need to trigger a repeat?
9096 (when now-done-p
9097 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
9098 ;; This is for the agenda, take a snapshot of the headline.
9099 (save-match-data
9100 (setq org-agenda-headline-snapshot-before-repeat
9101 (org-get-heading))))
9102 (org-auto-repeat-maybe state))
9103 ;; Fixup cursor location if close to the keyword
9104 (if (and (outline-on-heading-p)
9105 (not (bolp))
9106 (save-excursion (beginning-of-line 1)
9107 (looking-at org-todo-line-regexp))
9108 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
9109 (progn
9110 (goto-char (or (match-end 2) (match-end 1)))
9111 (and (looking-at " ") (just-one-space))))
9112 (when org-trigger-hook
9113 (save-excursion
9114 (run-hook-with-args 'org-trigger-hook change-plist))))))))
9116 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
9117 "Block turning an entry into a TODO, using the hierarchy.
9118 This checks whether the current task should be blocked from state
9119 changes. Such blocking occurs when:
9121 1. The task has children which are not all in a completed state.
9123 2. A task has a parent with the property :ORDERED:, and there
9124 are siblings prior to the current task with incomplete
9125 status.
9127 3. The parent of the task is blocked because it has siblings that should
9128 be done first, or is child of a block grandparent TODO entry."
9130 (catch 'dont-block
9131 ;; If this is not a todo state change, or if this entry is already DONE,
9132 ;; do not block
9133 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
9134 (member (plist-get change-plist :from)
9135 (cons 'done org-done-keywords))
9136 (member (plist-get change-plist :to)
9137 (cons 'todo org-not-done-keywords)))
9138 (throw 'dont-block t))
9139 ;; If this task has children, and any are undone, it's blocked
9140 (save-excursion
9141 (org-back-to-heading t)
9142 (let ((this-level (funcall outline-level)))
9143 (outline-next-heading)
9144 (let ((child-level (funcall outline-level)))
9145 (while (and (not (eobp))
9146 (> child-level this-level))
9147 ;; this todo has children, check whether they are all
9148 ;; completed
9149 (if (and (not (org-entry-is-done-p))
9150 (org-entry-is-todo-p))
9151 (throw 'dont-block nil))
9152 (outline-next-heading)
9153 (setq child-level (funcall outline-level))))))
9154 ;; Otherwise, if the task's parent has the :ORDERED: property, and
9155 ;; any previous siblings are undone, it's blocked
9156 (save-excursion
9157 (org-back-to-heading t)
9158 (let* ((pos (point))
9159 (parent-pos (and (org-up-heading-safe) (point))))
9160 (if (not parent-pos) (throw 'dont-block t)) ; no parent
9161 (when (and (org-entry-get (point) "ORDERED")
9162 (forward-line 1)
9163 (re-search-forward org-not-done-heading-regexp pos t))
9164 (throw 'dont-block nil)) ; block, there is an older sibling not done.
9165 ;; Search further up the hierarchy, to see if an anchestor is blocked
9166 (while t
9167 (goto-char parent-pos)
9168 (if (not (looking-at org-not-done-heading-regexp))
9169 (throw 'dont-block t)) ; do not block, parent is not a TODO
9170 (setq pos (point))
9171 (setq parent-pos (and (org-up-heading-safe) (point)))
9172 (if (not parent-pos) (throw 'dont-block t)) ; no parent
9173 (when (and (org-entry-get (point) "ORDERED")
9174 (forward-line 1)
9175 (re-search-forward org-not-done-heading-regexp pos t))
9176 (throw 'dont-block nil))))))) ; block, older sibling not done.
9178 (defcustom org-track-ordered-property-with-tag nil
9179 "Should the ORDERED property also be shown as a tag?
9180 The ORDERED property decides if an entry should require subtasks to be
9181 completed in sequence. Since a property is not very visible, setting
9182 this option means that toggling the ORDERED property with the command
9183 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
9184 not relevant for the behavior, but it makes things more visible.
9186 Note that toggling the tag with tags commands will not change the property
9187 and therefore not influence behavior!
9189 This can be t, meaning the tag ORDERED should be used, It can also be a
9190 string to select a different tag for this task."
9191 :group 'org-todo
9192 :type '(choice
9193 (const :tag "No tracking" nil)
9194 (const :tag "Track with ORDERED tag" t)
9195 (string :tag "Use other tag")))
9197 (defun org-toggle-ordered-property ()
9198 "Toggle the ORDERED property of the current entry.
9199 For better visibility, you can track the value of this property with a tag.
9200 See variable `org-track-ordered-property-with-tag'."
9201 (interactive)
9202 (let* ((t1 org-track-ordered-property-with-tag)
9203 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
9204 (save-excursion
9205 (org-back-to-heading)
9206 (if (org-entry-get nil "ORDERED")
9207 (progn
9208 (org-delete-property "ORDERED")
9209 (and tag (org-toggle-tag tag 'off))
9210 (message "Subtasks can be completed in arbitrary order"))
9211 (org-entry-put nil "ORDERED" "t")
9212 (and tag (org-toggle-tag tag 'on))
9213 (message "Subtasks must be completed in sequence")))))
9215 (defvar org-blocked-by-checkboxes) ; dynamically scoped
9216 (defun org-block-todo-from-checkboxes (change-plist)
9217 "Block turning an entry into a TODO, using checkboxes.
9218 This checks whether the current task should be blocked from state
9219 changes because there are uncheckd boxes in this entry."
9220 (catch 'dont-block
9221 ;; If this is not a todo state change, or if this entry is already DONE,
9222 ;; do not block
9223 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
9224 (member (plist-get change-plist :from)
9225 (cons 'done org-done-keywords))
9226 (member (plist-get change-plist :to)
9227 (cons 'todo org-not-done-keywords)))
9228 (throw 'dont-block t))
9229 ;; If this task has checkboxes that are not checked, it's blocked
9230 (save-excursion
9231 (org-back-to-heading t)
9232 (let ((beg (point)) end)
9233 (outline-next-heading)
9234 (setq end (point))
9235 (goto-char beg)
9236 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
9237 end t)
9238 (progn
9239 (if (boundp 'org-blocked-by-checkboxes)
9240 (setq org-blocked-by-checkboxes t))
9241 (throw 'dont-block nil)))))
9242 t)) ; do not block
9244 (defun org-update-parent-todo-statistics ()
9245 "Update any statistics cookie in the parent of the current headline."
9246 (interactive)
9247 (let ((box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
9248 level (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
9249 (catch 'exit
9250 (save-excursion
9251 (setq level (org-up-heading-safe))
9252 (unless level
9253 (throw 'exit nil))
9254 (while (re-search-forward box-re (point-at-eol) t)
9255 (setq cnt-all 0 cnt-done 0 cookie-present t)
9256 (setq is-percent (match-end 2))
9257 (save-match-data
9258 (unless (outline-next-heading) (throw 'exit nil))
9259 (while (looking-at org-todo-line-regexp)
9260 (setq kwd (match-string 2))
9261 (and kwd (setq cnt-all (1+ cnt-all)))
9262 (and (member kwd org-done-keywords)
9263 (setq cnt-done (1+ cnt-done)))
9264 (condition-case nil
9265 (org-forward-same-level 1)
9266 (error (end-of-line 1)))))
9267 (replace-match
9268 (if is-percent
9269 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
9270 (format "[%d/%d]" cnt-done cnt-all))))
9271 (when cookie-present
9272 (run-hook-with-args 'org-after-todo-statistics-hook
9273 cnt-done (- cnt-all cnt-done)))))))
9275 (defvar org-after-todo-statistics-hook nil
9276 "Hook that is called after a TODO statistics cookie has been updated.
9277 Each function is called with two arguments: the number of not-done entries
9278 and the number of done entries.
9280 For example, the following function, when added to this hook, will switch
9281 an entry to DONE when all children are done, and back to TODO when new
9282 entries are set to a TODO status. Note that this hook is only called
9283 when there is a statistics cookie in the headline!
9285 (defun org-summary-todo (n-done n-not-done)
9286 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
9287 (let (org-log-done org-log-states) ; turn off logging
9288 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
9291 (defun org-todo-trigger-tag-changes (state)
9292 "Apply the changes defined in `org-todo-state-tags-triggers'."
9293 (let ((l org-todo-state-tags-triggers)
9294 changes)
9295 (when (or (not state) (equal state ""))
9296 (setq changes (append changes (cdr (assoc "" l)))))
9297 (when (and (stringp state) (> (length state) 0))
9298 (setq changes (append changes (cdr (assoc state l)))))
9299 (when (member state org-not-done-keywords)
9300 (setq changes (append changes (cdr (assoc 'todo l)))))
9301 (when (member state org-done-keywords)
9302 (setq changes (append changes (cdr (assoc 'done l)))))
9303 (dolist (c changes)
9304 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
9306 (defun org-local-logging (value)
9307 "Get logging settings from a property VALUE."
9308 (let* (words w a)
9309 ;; directly set the variables, they are already local.
9310 (setq org-log-done nil
9311 org-log-repeat nil
9312 org-todo-log-states nil)
9313 (setq words (org-split-string value))
9314 (while (setq w (pop words))
9315 (cond
9316 ((setq a (assoc w org-startup-options))
9317 (and (member (nth 1 a) '(org-log-done org-log-repeat))
9318 (set (nth 1 a) (nth 2 a))))
9319 ((setq a (org-extract-log-state-settings w))
9320 (and (member (car a) org-todo-keywords-1)
9321 (push a org-todo-log-states)))))))
9323 (defun org-get-todo-sequence-head (kwd)
9324 "Return the head of the TODO sequence to which KWD belongs.
9325 If KWD is not set, check if there is a text property remembering the
9326 right sequence."
9327 (let (p)
9328 (cond
9329 ((not kwd)
9330 (or (get-text-property (point-at-bol) 'org-todo-head)
9331 (progn
9332 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
9333 nil (point-at-eol)))
9334 (get-text-property p 'org-todo-head))))
9335 ((not (member kwd org-todo-keywords-1))
9336 (car org-todo-keywords-1))
9337 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
9339 (defun org-fast-todo-selection ()
9340 "Fast TODO keyword selection with single keys.
9341 Returns the new TODO keyword, or nil if no state change should occur."
9342 (let* ((fulltable org-todo-key-alist)
9343 (done-keywords org-done-keywords) ;; needed for the faces.
9344 (maxlen (apply 'max (mapcar
9345 (lambda (x)
9346 (if (stringp (car x)) (string-width (car x)) 0))
9347 fulltable)))
9348 (expert nil)
9349 (fwidth (+ maxlen 3 1 3))
9350 (ncol (/ (- (window-width) 4) fwidth))
9351 tg cnt e c tbl
9352 groups ingroup)
9353 (save-excursion
9354 (save-window-excursion
9355 (if expert
9356 (set-buffer (get-buffer-create " *Org todo*"))
9357 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
9358 (erase-buffer)
9359 (org-set-local 'org-done-keywords done-keywords)
9360 (setq tbl fulltable cnt 0)
9361 (while (setq e (pop tbl))
9362 (cond
9363 ((equal e '(:startgroup))
9364 (push '() groups) (setq ingroup t)
9365 (when (not (= cnt 0))
9366 (setq cnt 0)
9367 (insert "\n"))
9368 (insert "{ "))
9369 ((equal e '(:endgroup))
9370 (setq ingroup nil cnt 0)
9371 (insert "}\n"))
9372 ((equal e '(:newline))
9373 (when (not (= cnt 0))
9374 (setq cnt 0)
9375 (insert "\n")
9376 (setq e (car tbl))
9377 (while (equal (car tbl) '(:newline))
9378 (insert "\n")
9379 (setq tbl (cdr tbl)))))
9381 (setq tg (car e) c (cdr e))
9382 (if ingroup (push tg (car groups)))
9383 (setq tg (org-add-props tg nil 'face
9384 (org-get-todo-face tg)))
9385 (if (and (= cnt 0) (not ingroup)) (insert " "))
9386 (insert "[" c "] " tg (make-string
9387 (- fwidth 4 (length tg)) ?\ ))
9388 (when (= (setq cnt (1+ cnt)) ncol)
9389 (insert "\n")
9390 (if ingroup (insert " "))
9391 (setq cnt 0)))))
9392 (insert "\n")
9393 (goto-char (point-min))
9394 (if (not expert) (org-fit-window-to-buffer))
9395 (message "[a-z..]:Set [SPC]:clear")
9396 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9397 (cond
9398 ((or (= c ?\C-g)
9399 (and (= c ?q) (not (rassoc c fulltable))))
9400 (setq quit-flag t))
9401 ((= c ?\ ) nil)
9402 ((setq e (rassoc c fulltable) tg (car e))
9404 (t (setq quit-flag t)))))))
9406 (defun org-entry-is-todo-p ()
9407 (member (org-get-todo-state) org-not-done-keywords))
9409 (defun org-entry-is-done-p ()
9410 (member (org-get-todo-state) org-done-keywords))
9412 (defun org-get-todo-state ()
9413 (save-excursion
9414 (org-back-to-heading t)
9415 (and (looking-at org-todo-line-regexp)
9416 (match-end 2)
9417 (match-string 2))))
9419 (defun org-at-date-range-p (&optional inactive-ok)
9420 "Is the cursor inside a date range?"
9421 (interactive)
9422 (save-excursion
9423 (catch 'exit
9424 (let ((pos (point)))
9425 (skip-chars-backward "^[<\r\n")
9426 (skip-chars-backward "<[")
9427 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
9428 (>= (match-end 0) pos)
9429 (throw 'exit t))
9430 (skip-chars-backward "^<[\r\n")
9431 (skip-chars-backward "<[")
9432 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
9433 (>= (match-end 0) pos)
9434 (throw 'exit t)))
9435 nil)))
9437 (defun org-get-repeat ()
9438 "Check if there is a deadline/schedule with repeater in this entry."
9439 (save-match-data
9440 (save-excursion
9441 (org-back-to-heading t)
9442 (if (re-search-forward
9443 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
9444 (match-string 1)))))
9446 (defvar org-last-changed-timestamp)
9447 (defvar org-last-inserted-timestamp)
9448 (defvar org-log-post-message)
9449 (defvar org-log-note-purpose)
9450 (defvar org-log-note-how)
9451 (defvar org-log-note-extra)
9452 (defun org-auto-repeat-maybe (done-word)
9453 "Check if the current headline contains a repeated deadline/schedule.
9454 If yes, set TODO state back to what it was and change the base date
9455 of repeating deadline/scheduled time stamps to new date.
9456 This function is run automatically after each state change to a DONE state."
9457 ;; last-state is dynamically scoped into this function
9458 (let* ((repeat (org-get-repeat))
9459 (aa (assoc last-state org-todo-kwd-alist))
9460 (interpret (nth 1 aa))
9461 (head (nth 2 aa))
9462 (whata '(("d" . day) ("m" . month) ("y" . year)))
9463 (msg "Entry repeats: ")
9464 (org-log-done nil)
9465 (org-todo-log-states nil)
9466 (nshiftmax 10) (nshift 0)
9467 re type n what ts time)
9468 (when repeat
9469 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
9470 (org-todo (if (eq interpret 'type) last-state head))
9471 (when org-log-repeat
9472 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
9473 (memq 'org-add-log-note post-command-hook))
9474 ;; OK, we are already setup for some record
9475 (if (eq org-log-repeat 'note)
9476 ;; make sure we take a note, not only a time stamp
9477 (setq org-log-note-how 'note))
9478 ;; Set up for taking a record
9479 (org-add-log-setup 'state (or done-word (car org-done-keywords))
9480 last-state
9481 'findpos org-log-repeat)))
9482 (org-back-to-heading t)
9483 (org-add-planning-info nil nil 'closed)
9484 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
9485 org-deadline-time-regexp "\\)\\|\\("
9486 org-ts-regexp "\\)"))
9487 (while (re-search-forward
9488 re (save-excursion (outline-next-heading) (point)) t)
9489 (setq type (if (match-end 1) org-scheduled-string
9490 (if (match-end 3) org-deadline-string "Plain:"))
9491 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
9492 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
9493 (setq n (string-to-number (match-string 2 ts))
9494 what (match-string 3 ts))
9495 (if (equal what "w") (setq n (* n 7) what "d"))
9496 ;; Preparation, see if we need to modify the start date for the change
9497 (when (match-end 1)
9498 (setq time (save-match-data (org-time-string-to-time ts)))
9499 (cond
9500 ((equal (match-string 1 ts) ".")
9501 ;; Shift starting date to today
9502 (org-timestamp-change
9503 (- (time-to-days (current-time)) (time-to-days time))
9504 'day))
9505 ((equal (match-string 1 ts) "+")
9506 (while (or (= nshift 0)
9507 (<= (time-to-days time) (time-to-days (current-time))))
9508 (when (= (incf nshift) nshiftmax)
9509 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
9510 (error "Abort")))
9511 (org-timestamp-change n (cdr (assoc what whata)))
9512 (org-at-timestamp-p t)
9513 (setq ts (match-string 1))
9514 (setq time (save-match-data (org-time-string-to-time ts))))
9515 (org-timestamp-change (- n) (cdr (assoc what whata)))
9516 ;; rematch, so that we have everything in place for the real shift
9517 (org-at-timestamp-p t)
9518 (setq ts (match-string 1))
9519 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
9520 (org-timestamp-change n (cdr (assoc what whata)))
9521 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
9522 (setq org-log-post-message msg)
9523 (message "%s" msg))))
9525 (defun org-show-todo-tree (arg)
9526 "Make a compact tree which shows all headlines marked with TODO.
9527 The tree will show the lines where the regexp matches, and all higher
9528 headlines above the match.
9529 With a \\[universal-argument] prefix, also show the DONE entries.
9530 With a numeric prefix N, construct a sparse tree for the Nth element
9531 of `org-todo-keywords-1'."
9532 (interactive "P")
9533 (let ((case-fold-search nil)
9534 (kwd-re
9535 (cond ((null arg) org-not-done-regexp)
9536 ((equal arg '(4))
9537 (let ((kwd (org-ido-completing-read "Keyword (or KWD1|KWD2|...): "
9538 (mapcar 'list org-todo-keywords-1))))
9539 (concat "\\("
9540 (mapconcat 'identity (org-split-string kwd "|") "\\|")
9541 "\\)\\>")))
9542 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
9543 (regexp-quote (nth (1- (prefix-numeric-value arg))
9544 org-todo-keywords-1)))
9545 (t (error "Invalid prefix argument: %s" arg)))))
9546 (message "%d TODO entries found"
9547 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
9549 (defun org-deadline (&optional remove time)
9550 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
9551 With argument REMOVE, remove any deadline from the item.
9552 When TIME is set, it should be an internal time specification, and the
9553 scheduling will use the corresponding date."
9554 (interactive "P")
9555 (if remove
9556 (progn
9557 (org-remove-timestamp-with-keyword org-deadline-string)
9558 (message "Item no longer has a deadline."))
9559 (if (org-get-repeat)
9560 (error "Cannot change deadline on task with repeater, please do that by hand")
9561 (org-add-planning-info 'deadline time 'closed)
9562 (message "Deadline on %s" org-last-inserted-timestamp))))
9564 (defun org-schedule (&optional remove time)
9565 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
9566 With argument REMOVE, remove any scheduling date from the item.
9567 When TIME is set, it should be an internal time specification, and the
9568 scheduling will use the corresponding date."
9569 (interactive "P")
9570 (if remove
9571 (progn
9572 (org-remove-timestamp-with-keyword org-scheduled-string)
9573 (message "Item is no longer scheduled."))
9574 (if (org-get-repeat)
9575 (error "Cannot reschedule task with repeater, please do that by hand")
9576 (org-add-planning-info 'scheduled time 'closed)
9577 (message "Scheduled to %s" org-last-inserted-timestamp))))
9579 (defun org-get-scheduled-time (pom &optional inherit)
9580 "Get the scheduled time as a time tuple, of a format suitable
9581 for calling org-schedule with, or if there is no scheduling,
9582 returns nil."
9583 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
9584 (when time
9585 (apply 'encode-time (org-parse-time-string time)))))
9587 (defun org-get-deadline-time (pom &optional inherit)
9588 "Get the deadine as a time tuple, of a format suitable for
9589 calling org-deadlin with, or if there is no scheduling, returns
9590 nil."
9591 (let ((time (org-entry-get pom "DEADLINE" inherit)))
9592 (when time
9593 (apply 'encode-time (org-parse-time-string time)))))
9595 (defun org-remove-timestamp-with-keyword (keyword)
9596 "Remove all time stamps with KEYWORD in the current entry."
9597 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
9598 beg)
9599 (save-excursion
9600 (org-back-to-heading t)
9601 (setq beg (point))
9602 (org-end-of-subtree t t)
9603 (while (re-search-backward re beg t)
9604 (replace-match "")
9605 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
9606 (equal (char-before) ?\ ))
9607 (backward-delete-char 1)
9608 (if (string-match "^[ \t]*$" (buffer-substring
9609 (point-at-bol) (point-at-eol)))
9610 (delete-region (point-at-bol)
9611 (min (point-max) (1+ (point-at-eol))))))))))
9613 (defun org-add-planning-info (what &optional time &rest remove)
9614 "Insert new timestamp with keyword in the line directly after the headline.
9615 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
9616 If non is given, the user is prompted for a date.
9617 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
9618 be removed."
9619 (interactive)
9620 (let (org-time-was-given org-end-time-was-given ts
9621 end default-time default-input)
9623 (catch 'exit
9624 (when (and (not time) (memq what '(scheduled deadline)))
9625 ;; Try to get a default date/time from existing timestamp
9626 (save-excursion
9627 (org-back-to-heading t)
9628 (setq end (save-excursion (outline-next-heading) (point)))
9629 (when (re-search-forward (if (eq what 'scheduled)
9630 org-scheduled-time-regexp
9631 org-deadline-time-regexp)
9632 end t)
9633 (setq ts (match-string 1)
9634 default-time
9635 (apply 'encode-time (org-parse-time-string ts))
9636 default-input (and ts (org-get-compact-tod ts))))))
9637 (when what
9638 ;; If necessary, get the time from the user
9639 (setq time (or time (org-read-date nil 'to-time nil nil
9640 default-time default-input))))
9642 (when (and org-insert-labeled-timestamps-at-point
9643 (member what '(scheduled deadline)))
9644 (insert
9645 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
9646 (org-insert-time-stamp time org-time-was-given
9647 nil nil nil (list org-end-time-was-given))
9648 (setq what nil))
9649 (save-excursion
9650 (save-restriction
9651 (let (col list elt ts buffer-invisibility-spec)
9652 (org-back-to-heading t)
9653 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
9654 (goto-char (match-end 1))
9655 (setq col (current-column))
9656 (goto-char (match-end 0))
9657 (if (eobp) (insert "\n") (forward-char 1))
9658 (when (and (not what)
9659 (not (looking-at
9660 (concat "[ \t]*"
9661 org-keyword-time-not-clock-regexp))))
9662 ;; Nothing to add, nothing to remove...... :-)
9663 (throw 'exit nil))
9664 (if (and (not (looking-at outline-regexp))
9665 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
9666 "[^\r\n]*"))
9667 (not (equal (match-string 1) org-clock-string)))
9668 (narrow-to-region (match-beginning 0) (match-end 0))
9669 (insert-before-markers "\n")
9670 (backward-char 1)
9671 (narrow-to-region (point) (point))
9672 (and org-adapt-indentation (org-indent-to-column col)))
9673 ;; Check if we have to remove something.
9674 (setq list (cons what remove))
9675 (while list
9676 (setq elt (pop list))
9677 (goto-char (point-min))
9678 (when (or (and (eq elt 'scheduled)
9679 (re-search-forward org-scheduled-time-regexp nil t))
9680 (and (eq elt 'deadline)
9681 (re-search-forward org-deadline-time-regexp nil t))
9682 (and (eq elt 'closed)
9683 (re-search-forward org-closed-time-regexp nil t)))
9684 (replace-match "")
9685 (if (looking-at "--+<[^>]+>") (replace-match ""))
9686 (if (looking-at " +") (replace-match ""))))
9687 (goto-char (point-max))
9688 (when what
9689 (insert
9690 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
9691 (cond ((eq what 'scheduled) org-scheduled-string)
9692 ((eq what 'deadline) org-deadline-string)
9693 ((eq what 'closed) org-closed-string))
9694 " ")
9695 (setq ts (org-insert-time-stamp
9696 time
9697 (or org-time-was-given
9698 (and (eq what 'closed) org-log-done-with-time))
9699 (eq what 'closed)
9700 nil nil (list org-end-time-was-given)))
9701 (end-of-line 1))
9702 (goto-char (point-min))
9703 (widen)
9704 (if (and (looking-at "[ \t]+\n")
9705 (equal (char-before) ?\n))
9706 (delete-region (1- (point)) (point-at-eol)))
9707 ts))))))
9709 (defvar org-log-note-marker (make-marker))
9710 (defvar org-log-note-purpose nil)
9711 (defvar org-log-note-state nil)
9712 (defvar org-log-note-previous-state nil)
9713 (defvar org-log-note-how nil)
9714 (defvar org-log-note-extra nil)
9715 (defvar org-log-note-window-configuration nil)
9716 (defvar org-log-note-return-to (make-marker))
9717 (defvar org-log-post-message nil
9718 "Message to be displayed after a log note has been stored.
9719 The auto-repeater uses this.")
9721 (defun org-add-note ()
9722 "Add a note to the current entry.
9723 This is done in the same way as adding a state change note."
9724 (interactive)
9725 (org-add-log-setup 'note nil nil 'findpos nil))
9727 (defvar org-property-end-re)
9728 (defun org-add-log-setup (&optional purpose state prev-state
9729 findpos how &optional extra)
9730 "Set up the post command hook to take a note.
9731 If this is about to TODO state change, the new state is expected in STATE.
9732 When FINDPOS is non-nil, find the correct position for the note in
9733 the current entry. If not, assume that it can be inserted at point.
9734 HOW is an indicator what kind of note should be created.
9735 EXTRA is additional text that will be inserted into the notes buffer."
9736 (let ((drawer (cond ((stringp org-log-into-drawer)
9737 org-log-into-drawer)
9738 (org-log-into-drawer "LOGBOOK")
9739 (t nil))))
9740 (save-restriction
9741 (save-excursion
9742 (when findpos
9743 (org-back-to-heading t)
9744 (narrow-to-region (point) (save-excursion
9745 (outline-next-heading) (point)))
9746 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
9747 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
9748 "[^\r\n]*\\)?"))
9749 (goto-char (match-end 0))
9750 (cond
9751 (drawer
9752 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
9753 nil t)
9754 (progn
9755 (goto-char (match-end 0))
9756 (or org-log-states-order-reversed
9757 (and (re-search-forward org-property-end-re nil t)
9758 (goto-char (1- (match-beginning 0))))))
9759 (insert "\n:" drawer ":\n:END:")
9760 (beginning-of-line 0)
9761 (org-indent-line-function)
9762 (beginning-of-line 2)
9763 (org-indent-line-function)
9764 (end-of-line 0)))
9765 ((and org-log-state-notes-insert-after-drawers
9766 (save-excursion
9767 (forward-line) (looking-at org-drawer-regexp)))
9768 (forward-line)
9769 (while (looking-at org-drawer-regexp)
9770 (goto-char (match-end 0))
9771 (re-search-forward org-property-end-re (point-max) t)
9772 (forward-line))
9773 (forward-line -1)))
9774 (unless org-log-states-order-reversed
9775 (and (= (char-after) ?\n) (forward-char 1))
9776 (org-skip-over-state-notes)
9777 (skip-chars-backward " \t\n\r")))
9778 (move-marker org-log-note-marker (point))
9779 (setq org-log-note-purpose purpose
9780 org-log-note-state state
9781 org-log-note-previous-state prev-state
9782 org-log-note-how how
9783 org-log-note-extra extra)
9784 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
9786 (defun org-skip-over-state-notes ()
9787 "Skip past the list of State notes in an entry."
9788 (if (looking-at "\n[ \t]*- State") (forward-char 1))
9789 (while (looking-at "[ \t]*- State")
9790 (condition-case nil
9791 (org-next-item)
9792 (error (org-end-of-item)))))
9794 (defun org-add-log-note (&optional purpose)
9795 "Pop up a window for taking a note, and add this note later at point."
9796 (remove-hook 'post-command-hook 'org-add-log-note)
9797 (setq org-log-note-window-configuration (current-window-configuration))
9798 (delete-other-windows)
9799 (move-marker org-log-note-return-to (point))
9800 (switch-to-buffer (marker-buffer org-log-note-marker))
9801 (goto-char org-log-note-marker)
9802 (org-switch-to-buffer-other-window "*Org Note*")
9803 (erase-buffer)
9804 (if (memq org-log-note-how '(time state))
9805 (let (current-prefix-arg) (org-store-log-note))
9806 (let ((org-inhibit-startup t)) (org-mode))
9807 (insert (format "# Insert note for %s.
9808 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
9809 (cond
9810 ((eq org-log-note-purpose 'clock-out) "stopped clock")
9811 ((eq org-log-note-purpose 'done) "closed todo item")
9812 ((eq org-log-note-purpose 'state)
9813 (format "state change from \"%s\" to \"%s\""
9814 (or org-log-note-previous-state "")
9815 (or org-log-note-state "")))
9816 ((eq org-log-note-purpose 'note)
9817 "this entry")
9818 (t (error "This should not happen")))))
9819 (if org-log-note-extra (insert org-log-note-extra))
9820 (org-set-local 'org-finish-function 'org-store-log-note)))
9822 (defvar org-note-abort nil) ; dynamically scoped
9823 (defun org-store-log-note ()
9824 "Finish taking a log note, and insert it to where it belongs."
9825 (let ((txt (buffer-string))
9826 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
9827 lines ind)
9828 (kill-buffer (current-buffer))
9829 (while (string-match "\\`#.*\n[ \t\n]*" txt)
9830 (setq txt (replace-match "" t t txt)))
9831 (if (string-match "\\s-+\\'" txt)
9832 (setq txt (replace-match "" t t txt)))
9833 (setq lines (org-split-string txt "\n"))
9834 (when (and note (string-match "\\S-" note))
9835 (setq note
9836 (org-replace-escapes
9837 note
9838 (list (cons "%u" (user-login-name))
9839 (cons "%U" user-full-name)
9840 (cons "%t" (format-time-string
9841 (org-time-stamp-format 'long 'inactive)
9842 (current-time)))
9843 (cons "%s" (if org-log-note-state
9844 (concat "\"" org-log-note-state "\"")
9845 ""))
9846 (cons "%S" (if org-log-note-previous-state
9847 (concat "\"" org-log-note-previous-state "\"")
9848 "\"\"")))))
9849 (if lines (setq note (concat note " \\\\")))
9850 (push note lines))
9851 (when (or current-prefix-arg org-note-abort)
9852 (when org-log-into-drawer
9853 (org-remove-empty-drawer-at
9854 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
9855 org-log-note-marker))
9856 (setq lines nil))
9857 (when lines
9858 (save-excursion
9859 (set-buffer (marker-buffer org-log-note-marker))
9860 (save-excursion
9861 (goto-char org-log-note-marker)
9862 (move-marker org-log-note-marker nil)
9863 (end-of-line 1)
9864 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
9865 (insert "- " (pop lines))
9866 (org-indent-line-function)
9867 (beginning-of-line 1)
9868 (looking-at "[ \t]*")
9869 (setq ind (concat (match-string 0) " "))
9870 (end-of-line 1)
9871 (while lines (insert "\n" ind (pop lines)))
9872 (message "Note stored")
9873 (org-back-to-heading t)
9874 (org-cycle-hide-drawers 'children)))))
9875 (set-window-configuration org-log-note-window-configuration)
9876 (with-current-buffer (marker-buffer org-log-note-return-to)
9877 (goto-char org-log-note-return-to))
9878 (move-marker org-log-note-return-to nil)
9879 (and org-log-post-message (message "%s" org-log-post-message)))
9881 (defun org-remove-empty-drawer-at (drawer pos)
9882 "Remove an emptyr DARWER drawer at position POS.
9883 POS may also be a marker."
9884 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
9885 (save-excursion
9886 (save-restriction
9887 (widen)
9888 (goto-char pos)
9889 (if (org-in-regexp
9890 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
9891 (replace-match ""))))))
9893 (defun org-sparse-tree (&optional arg)
9894 "Create a sparse tree, prompt for the details.
9895 This command can create sparse trees. You first need to select the type
9896 of match used to create the tree:
9898 t Show entries with a specific TODO keyword.
9899 m Show entries selected by a tags/property match.
9900 p Enter a property name and its value (both with completion on existing
9901 names/values) and show entries with that property.
9902 r Show entries matching a regular expression.
9903 d Show deadlines due within `org-deadline-warning-days'.
9904 b Show deadlines and scheduled items before a date.
9905 a Show deadlines and scheduled items after a date."
9906 (interactive "P")
9907 (let (ans kwd value)
9908 (message "Sparse tree: [/]regexp [t]odo-kwd [m]atch [p]roperty [d]eadlines [b]efore-date [a]fter-date")
9909 (setq ans (read-char-exclusive))
9910 (cond
9911 ((equal ans ?d)
9912 (call-interactively 'org-check-deadlines))
9913 ((equal ans ?b)
9914 (call-interactively 'org-check-before-date))
9915 ((equal ans ?a)
9916 (call-interactively 'org-check-after-date))
9917 ((equal ans ?t)
9918 (org-show-todo-tree '(4)))
9919 ((member ans '(?T ?m))
9920 (call-interactively 'org-match-sparse-tree))
9921 ((member ans '(?p ?P))
9922 (setq kwd (org-ido-completing-read "Property: "
9923 (mapcar 'list (org-buffer-property-keys))))
9924 (setq value (org-ido-completing-read "Value: "
9925 (mapcar 'list (org-property-values kwd))))
9926 (unless (string-match "\\`{.*}\\'" value)
9927 (setq value (concat "\"" value "\"")))
9928 (org-match-sparse-tree arg (concat kwd "=" value)))
9929 ((member ans '(?r ?R ?/))
9930 (call-interactively 'org-occur))
9931 (t (error "No such sparse tree command \"%c\"" ans)))))
9933 (defvar org-occur-highlights nil
9934 "List of overlays used for occur matches.")
9935 (make-variable-buffer-local 'org-occur-highlights)
9936 (defvar org-occur-parameters nil
9937 "Parameters of the active org-occur calls.
9938 This is a list, each call to org-occur pushes as cons cell,
9939 containing the regular expression and the callback, onto the list.
9940 The list can contain several entries if `org-occur' has been called
9941 several time with the KEEP-PREVIOUS argument. Otherwise, this list
9942 will only contain one set of parameters. When the highlights are
9943 removed (for example with `C-c C-c', or with the next edit (depending
9944 on `org-remove-highlights-with-change'), this variable is emptied
9945 as well.")
9946 (make-variable-buffer-local 'org-occur-parameters)
9948 (defun org-occur (regexp &optional keep-previous callback)
9949 "Make a compact tree which shows all matches of REGEXP.
9950 The tree will show the lines where the regexp matches, and all higher
9951 headlines above the match. It will also show the heading after the match,
9952 to make sure editing the matching entry is easy.
9953 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
9954 call to `org-occur' will be kept, to allow stacking of calls to this
9955 command.
9956 If CALLBACK is non-nil, it is a function which is called to confirm
9957 that the match should indeed be shown."
9958 (interactive "sRegexp: \nP")
9959 (unless keep-previous
9960 (org-remove-occur-highlights nil nil t))
9961 (push (cons regexp callback) org-occur-parameters)
9962 (let ((cnt 0))
9963 (save-excursion
9964 (goto-char (point-min))
9965 (if (or (not keep-previous) ; do not want to keep
9966 (not org-occur-highlights)) ; no previous matches
9967 ;; hide everything
9968 (org-overview))
9969 (while (re-search-forward regexp nil t)
9970 (when (or (not callback)
9971 (save-match-data (funcall callback)))
9972 (setq cnt (1+ cnt))
9973 (when org-highlight-sparse-tree-matches
9974 (org-highlight-new-match (match-beginning 0) (match-end 0)))
9975 (org-show-context 'occur-tree))))
9976 (when org-remove-highlights-with-change
9977 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
9978 nil 'local))
9979 (unless org-sparse-tree-open-archived-trees
9980 (org-hide-archived-subtrees (point-min) (point-max)))
9981 (run-hooks 'org-occur-hook)
9982 (if (interactive-p)
9983 (message "%d match(es) for regexp %s" cnt regexp))
9984 cnt))
9986 (defun org-show-context (&optional key)
9987 "Make sure point and context and visible.
9988 How much context is shown depends upon the variables
9989 `org-show-hierarchy-above', `org-show-following-heading'. and
9990 `org-show-siblings'."
9991 (let ((heading-p (org-on-heading-p t))
9992 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
9993 (following-p (org-get-alist-option org-show-following-heading key))
9994 (entry-p (org-get-alist-option org-show-entry-below key))
9995 (siblings-p (org-get-alist-option org-show-siblings key)))
9996 (catch 'exit
9997 ;; Show heading or entry text
9998 (if (and heading-p (not entry-p))
9999 (org-flag-heading nil) ; only show the heading
10000 (and (or entry-p (org-invisible-p) (org-invisible-p2))
10001 (org-show-hidden-entry))) ; show entire entry
10002 (when following-p
10003 ;; Show next sibling, or heading below text
10004 (save-excursion
10005 (and (if heading-p (org-goto-sibling) (outline-next-heading))
10006 (org-flag-heading nil))))
10007 (when siblings-p (org-show-siblings))
10008 (when hierarchy-p
10009 ;; show all higher headings, possibly with siblings
10010 (save-excursion
10011 (while (and (condition-case nil
10012 (progn (org-up-heading-all 1) t)
10013 (error nil))
10014 (not (bobp)))
10015 (org-flag-heading nil)
10016 (when siblings-p (org-show-siblings))))))))
10018 (defun org-reveal (&optional siblings)
10019 "Show current entry, hierarchy above it, and the following headline.
10020 This can be used to show a consistent set of context around locations
10021 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
10022 not t for the search context.
10024 With optional argument SIBLINGS, on each level of the hierarchy all
10025 siblings are shown. This repairs the tree structure to what it would
10026 look like when opened with hierarchical calls to `org-cycle'."
10027 (interactive "P")
10028 (let ((org-show-hierarchy-above t)
10029 (org-show-following-heading t)
10030 (org-show-siblings (if siblings t org-show-siblings)))
10031 (org-show-context nil)))
10033 (defun org-highlight-new-match (beg end)
10034 "Highlight from BEG to END and mark the highlight is an occur headline."
10035 (let ((ov (org-make-overlay beg end)))
10036 (org-overlay-put ov 'face 'secondary-selection)
10037 (push ov org-occur-highlights)))
10039 (defun org-remove-occur-highlights (&optional beg end noremove)
10040 "Remove the occur highlights from the buffer.
10041 BEG and END are ignored. If NOREMOVE is nil, remove this function
10042 from the `before-change-functions' in the current buffer."
10043 (interactive)
10044 (unless org-inhibit-highlight-removal
10045 (mapc 'org-delete-overlay org-occur-highlights)
10046 (setq org-occur-highlights nil)
10047 (setq org-occur-parameters nil)
10048 (unless noremove
10049 (remove-hook 'before-change-functions
10050 'org-remove-occur-highlights 'local))))
10052 ;;;; Priorities
10054 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
10055 "Regular expression matching the priority indicator.")
10057 (defvar org-remove-priority-next-time nil)
10059 (defun org-priority-up ()
10060 "Increase the priority of the current item."
10061 (interactive)
10062 (org-priority 'up))
10064 (defun org-priority-down ()
10065 "Decrease the priority of the current item."
10066 (interactive)
10067 (org-priority 'down))
10069 (defun org-priority (&optional action)
10070 "Change the priority of an item by ARG.
10071 ACTION can be `set', `up', `down', or a character."
10072 (interactive)
10073 (setq action (or action 'set))
10074 (let (current new news have remove)
10075 (save-excursion
10076 (org-back-to-heading t)
10077 (if (looking-at org-priority-regexp)
10078 (setq current (string-to-char (match-string 2))
10079 have t)
10080 (setq current org-default-priority))
10081 (cond
10082 ((or (eq action 'set)
10083 (if (featurep 'xemacs) (characterp action) (integerp action)))
10084 (if (not (eq action 'set))
10085 (setq new action)
10086 (message "Priority %c-%c, SPC to remove: "
10087 org-highest-priority org-lowest-priority)
10088 (setq new (read-char-exclusive)))
10089 (if (and (= (upcase org-highest-priority) org-highest-priority)
10090 (= (upcase org-lowest-priority) org-lowest-priority))
10091 (setq new (upcase new)))
10092 (cond ((equal new ?\ ) (setq remove t))
10093 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
10094 (error "Priority must be between `%c' and `%c'"
10095 org-highest-priority org-lowest-priority))))
10096 ((eq action 'up)
10097 (if (and (not have) (eq last-command this-command))
10098 (setq new org-lowest-priority)
10099 (setq new (if (and org-priority-start-cycle-with-default (not have))
10100 org-default-priority (1- current)))))
10101 ((eq action 'down)
10102 (if (and (not have) (eq last-command this-command))
10103 (setq new org-highest-priority)
10104 (setq new (if (and org-priority-start-cycle-with-default (not have))
10105 org-default-priority (1+ current)))))
10106 (t (error "Invalid action")))
10107 (if (or (< (upcase new) org-highest-priority)
10108 (> (upcase new) org-lowest-priority))
10109 (setq remove t))
10110 (setq news (format "%c" new))
10111 (if have
10112 (if remove
10113 (replace-match "" t t nil 1)
10114 (replace-match news t t nil 2))
10115 (if remove
10116 (error "No priority cookie found in line")
10117 (let ((case-fold-search nil))
10118 (looking-at org-todo-line-regexp))
10119 (if (match-end 2)
10120 (progn
10121 (goto-char (match-end 2))
10122 (insert " [#" news "]"))
10123 (goto-char (match-beginning 3))
10124 (insert "[#" news "] ")))))
10125 (org-preserve-lc (org-set-tags nil 'align))
10126 (if remove
10127 (message "Priority removed")
10128 (message "Priority of current item set to %s" news))))
10131 (defun org-get-priority (s)
10132 "Find priority cookie and return priority."
10133 (save-match-data
10134 (if (not (string-match org-priority-regexp s))
10135 (* 1000 (- org-lowest-priority org-default-priority))
10136 (* 1000 (- org-lowest-priority
10137 (string-to-char (match-string 2 s)))))))
10139 ;;;; Tags
10141 (defvar org-agenda-archives-mode)
10142 (defvar org-map-continue-from nil
10143 "Position from where mapping should continue.
10144 Can be set byt the action argument to `org-scan-tag's and `org-map-entries'.")
10146 (defvar org-scanner-tags nil
10147 "The current tag list while the tags scanner is running.")
10148 (defvar org-trust-scanner-tags nil
10149 "Should `org-get-tags-at' use the tags fro the scanner.
10150 This is for internal dynamical scoping only.
10151 When this is non-nil, the function `org-get-tags-at' will return the value
10152 of `org-scanner-tags' instead of building the list by itself. This
10153 can lead to large speed-ups when the tags scanner is used in a file with
10154 many entries, and when the list of tags is retrieved, for example to
10155 obtain a list of properties. Building the tags list for each entry in such
10156 a file becomes an N^2 operation - but with this variable set, it scales
10157 as N.")
10159 (defun org-scan-tags (action matcher &optional todo-only)
10160 "Scan headline tags with inheritance and produce output ACTION.
10162 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
10163 or `agenda' to produce an entry list for an agenda view. It can also be
10164 a Lisp form or a function that should be called at each matched headline, in
10165 this case the return value is a list of all return values from these calls.
10167 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
10168 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
10169 only lines with a TODO keyword are included in the output."
10170 (require 'org-agenda)
10171 (let* ((re (concat "^" outline-regexp " *\\(\\<\\("
10172 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
10173 (org-re
10174 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
10175 (props (list 'face 'default
10176 'done-face 'org-agenda-done
10177 'undone-face 'default
10178 'mouse-face 'highlight
10179 'org-not-done-regexp org-not-done-regexp
10180 'org-todo-regexp org-todo-regexp
10181 'keymap org-agenda-keymap
10182 'help-echo
10183 (format "mouse-2 or RET jump to org file %s"
10184 (abbreviate-file-name
10185 (or (buffer-file-name (buffer-base-buffer))
10186 (buffer-name (buffer-base-buffer)))))))
10187 (case-fold-search nil)
10188 (org-map-continue-from nil)
10189 lspos tags tags-list
10190 (tags-alist (list (cons 0 org-file-tags)))
10191 (llast 0) rtn rtn1 level category i txt
10192 todo marker entry priority)
10193 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
10194 (setq action (list 'lambda nil action)))
10195 (save-excursion
10196 (goto-char (point-min))
10197 (when (eq action 'sparse-tree)
10198 (org-overview)
10199 (org-remove-occur-highlights))
10200 (while (re-search-forward re nil t)
10201 (catch :skip
10202 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
10203 tags (if (match-end 4) (org-match-string-no-properties 4)))
10204 (goto-char (setq lspos (match-beginning 0)))
10205 (setq level (org-reduced-level (funcall outline-level))
10206 category (org-get-category))
10207 (setq i llast llast level)
10208 ;; remove tag lists from same and sublevels
10209 (while (>= i level)
10210 (when (setq entry (assoc i tags-alist))
10211 (setq tags-alist (delete entry tags-alist)))
10212 (setq i (1- i)))
10213 ;; add the next tags
10214 (when tags
10215 (setq tags (org-split-string tags ":")
10216 tags-alist
10217 (cons (cons level tags) tags-alist)))
10218 ;; compile tags for current headline
10219 (setq tags-list
10220 (if org-use-tag-inheritance
10221 (apply 'append (mapcar 'cdr (reverse tags-alist)))
10222 tags)
10223 org-scanner-tags tags-list)
10224 (when org-use-tag-inheritance
10225 (setcdr (car tags-alist)
10226 (mapcar (lambda (x)
10227 (setq x (copy-sequence x))
10228 (org-add-prop-inherited x))
10229 (cdar tags-alist))))
10230 (when (and tags org-use-tag-inheritance
10231 (or (not (eq t org-use-tag-inheritance))
10232 org-tags-exclude-from-inheritance))
10233 ;; selective inheritance, remove uninherited ones
10234 (setcdr (car tags-alist)
10235 (org-remove-uniherited-tags (cdar tags-alist))))
10236 (when (and (or (not todo-only)
10237 (and (member todo org-not-done-keywords)
10238 (or (not org-agenda-tags-todo-honor-ignore-options)
10239 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
10240 (let ((case-fold-search t)) (eval matcher))
10242 (not (member org-archive-tag tags-list))
10243 ;; we have an archive tag, should we use this anyway?
10244 (or (not org-agenda-skip-archived-trees)
10245 (and (eq action 'agenda) org-agenda-archives-mode))))
10246 (unless (eq action 'sparse-tree) (org-agenda-skip))
10248 ;; select this headline
10250 (cond
10251 ((eq action 'sparse-tree)
10252 (and org-highlight-sparse-tree-matches
10253 (org-get-heading) (match-end 0)
10254 (org-highlight-new-match
10255 (match-beginning 0) (match-beginning 1)))
10256 (org-show-context 'tags-tree))
10257 ((eq action 'agenda)
10258 (setq txt (org-format-agenda-item
10260 (concat
10261 (if (eq org-tags-match-list-sublevels 'indented)
10262 (make-string (1- level) ?.) "")
10263 (org-get-heading))
10264 category
10265 tags-list
10267 priority (org-get-priority txt))
10268 (goto-char lspos)
10269 (setq marker (org-agenda-new-marker))
10270 (org-add-props txt props
10271 'org-marker marker 'org-hd-marker marker 'org-category category
10272 'todo-state todo
10273 'priority priority 'type "tagsmatch")
10274 (push txt rtn))
10275 ((functionp action)
10276 (setq org-map-continue-from nil)
10277 (save-excursion
10278 (setq rtn1 (funcall action))
10279 (push rtn1 rtn)))
10280 (t (error "Invalid action")))
10282 ;; if we are to skip sublevels, jump to end of subtree
10283 (unless org-tags-match-list-sublevels
10284 (org-end-of-subtree t)
10285 (backward-char 1))))
10286 ;; Get the correct position from where to continue
10287 (if org-map-continue-from
10288 (goto-char org-map-continue-from)
10289 (and (= (point) lspos) (end-of-line 1)))))
10290 (when (and (eq action 'sparse-tree)
10291 (not org-sparse-tree-open-archived-trees))
10292 (org-hide-archived-subtrees (point-min) (point-max)))
10293 (nreverse rtn)))
10295 (defun org-remove-uniherited-tags (tags)
10296 "Remove all tags that are not inherited from the list TAGS."
10297 (cond
10298 ((eq org-use-tag-inheritance t)
10299 (if org-tags-exclude-from-inheritance
10300 (org-delete-all org-tags-exclude-from-inheritance tags)
10301 tags))
10302 ((not org-use-tag-inheritance) nil)
10303 ((stringp org-use-tag-inheritance)
10304 (delq nil (mapcar
10305 (lambda (x)
10306 (if (and (string-match org-use-tag-inheritance x)
10307 (not (member x org-tags-exclude-from-inheritance)))
10308 x nil))
10309 tags)))
10310 ((listp org-use-tag-inheritance)
10311 (delq nil (mapcar
10312 (lambda (x)
10313 (if (member x org-use-tag-inheritance) x nil))
10314 tags)))))
10316 (defvar todo-only) ;; dynamically scoped
10318 (defun org-match-sparse-tree (&optional todo-only match)
10319 "Create a sparse tree according to tags string MATCH.
10320 MATCH can contain positive and negative selection of tags, like
10321 \"+WORK+URGENT-WITHBOSS\".
10322 If optional argument TODO-ONLY is non-nil, only select lines that are
10323 also TODO lines."
10324 (interactive "P")
10325 (org-prepare-agenda-buffers (list (current-buffer)))
10326 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
10328 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
10330 (defvar org-cached-props nil)
10331 (defun org-cached-entry-get (pom property)
10332 (if (or (eq t org-use-property-inheritance)
10333 (and (stringp org-use-property-inheritance)
10334 (string-match org-use-property-inheritance property))
10335 (and (listp org-use-property-inheritance)
10336 (member property org-use-property-inheritance)))
10337 ;; Caching is not possible, check it directly
10338 (org-entry-get pom property 'inherit)
10339 ;; Get all properties, so that we can do complicated checks easily
10340 (cdr (assoc property (or org-cached-props
10341 (setq org-cached-props
10342 (org-entry-properties pom)))))))
10344 (defun org-global-tags-completion-table (&optional files)
10345 "Return the list of all tags in all agenda buffer/files."
10346 (save-excursion
10347 (org-uniquify
10348 (delq nil
10349 (apply 'append
10350 (mapcar
10351 (lambda (file)
10352 (set-buffer (find-file-noselect file))
10353 (append (org-get-buffer-tags)
10354 (mapcar (lambda (x) (if (stringp (car-safe x))
10355 (list (car-safe x)) nil))
10356 org-tag-alist)))
10357 (if (and files (car files))
10358 files
10359 (org-agenda-files))))))))
10361 (defun org-make-tags-matcher (match)
10362 "Create the TAGS//TODO matcher form for the selection string MATCH."
10363 ;; todo-only is scoped dynamically into this function, and the function
10364 ;; may change it if the matcher asks for it.
10365 (unless match
10366 ;; Get a new match request, with completion
10367 (let ((org-last-tags-completion-table
10368 (org-global-tags-completion-table)))
10369 (setq match (org-completing-read-no-ido
10370 "Match: " 'org-tags-completion-function nil nil nil
10371 'org-tags-history))))
10373 ;; Parse the string and create a lisp form
10374 (let ((match0 match)
10375 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
10376 minus tag mm
10377 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
10378 orterms term orlist re-p str-p level-p level-op time-p
10379 prop-p pn pv po cat-p gv rest)
10380 (if (string-match "/+" match)
10381 ;; match contains also a todo-matching request
10382 (progn
10383 (setq tagsmatch (substring match 0 (match-beginning 0))
10384 todomatch (substring match (match-end 0)))
10385 (if (string-match "^!" todomatch)
10386 (setq todo-only t todomatch (substring todomatch 1)))
10387 (if (string-match "^\\s-*$" todomatch)
10388 (setq todomatch nil)))
10389 ;; only matching tags
10390 (setq tagsmatch match todomatch nil))
10392 ;; Make the tags matcher
10393 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
10394 (setq tagsmatcher t)
10395 (setq orterms (org-split-string tagsmatch "|") orlist nil)
10396 (while (setq term (pop orterms))
10397 (while (and (equal (substring term -1) "\\") orterms)
10398 (setq term (concat term "|" (pop orterms)))) ; repair bad split
10399 (while (string-match re term)
10400 (setq rest (substring term (match-end 0))
10401 minus (and (match-end 1)
10402 (equal (match-string 1 term) "-"))
10403 tag (match-string 2 term)
10404 re-p (equal (string-to-char tag) ?{)
10405 level-p (match-end 4)
10406 prop-p (match-end 5)
10407 mm (cond
10408 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
10409 (level-p
10410 (setq level-op (org-op-to-function (match-string 3 term)))
10411 `(,level-op level ,(string-to-number
10412 (match-string 4 term))))
10413 (prop-p
10414 (setq pn (match-string 5 term)
10415 po (match-string 6 term)
10416 pv (match-string 7 term)
10417 cat-p (equal pn "CATEGORY")
10418 re-p (equal (string-to-char pv) ?{)
10419 str-p (equal (string-to-char pv) ?\")
10420 time-p (save-match-data
10421 (string-match "^\"[[<].*[]>]\"$" pv))
10422 pv (if (or re-p str-p) (substring pv 1 -1) pv))
10423 (if time-p (setq pv (org-matcher-time pv)))
10424 (setq po (org-op-to-function po (if time-p 'time str-p)))
10425 (cond
10426 ((equal pn "CATEGORY")
10427 (setq gv '(get-text-property (point) 'org-category)))
10428 ((equal pn "TODO")
10429 (setq gv 'todo))
10431 (setq gv `(org-cached-entry-get nil ,pn))))
10432 (if re-p
10433 (if (eq po 'org<>)
10434 `(not (string-match ,pv (or ,gv "")))
10435 `(string-match ,pv (or ,gv "")))
10436 (if str-p
10437 `(,po (or ,gv "") ,pv)
10438 `(,po (string-to-number (or ,gv ""))
10439 ,(string-to-number pv) ))))
10440 (t `(member ,tag tags-list)))
10441 mm (if minus (list 'not mm) mm)
10442 term rest)
10443 (push mm tagsmatcher))
10444 (push (if (> (length tagsmatcher) 1)
10445 (cons 'and tagsmatcher)
10446 (car tagsmatcher))
10447 orlist)
10448 (setq tagsmatcher nil))
10449 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
10450 (setq tagsmatcher
10451 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
10452 ;; Make the todo matcher
10453 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
10454 (setq todomatcher t)
10455 (setq orterms (org-split-string todomatch "|") orlist nil)
10456 (while (setq term (pop orterms))
10457 (while (string-match re term)
10458 (setq minus (and (match-end 1)
10459 (equal (match-string 1 term) "-"))
10460 kwd (match-string 2 term)
10461 re-p (equal (string-to-char kwd) ?{)
10462 term (substring term (match-end 0))
10463 mm (if re-p
10464 `(string-match ,(substring kwd 1 -1) todo)
10465 (list 'equal 'todo kwd))
10466 mm (if minus (list 'not mm) mm))
10467 (push mm todomatcher))
10468 (push (if (> (length todomatcher) 1)
10469 (cons 'and todomatcher)
10470 (car todomatcher))
10471 orlist)
10472 (setq todomatcher nil))
10473 (setq todomatcher (if (> (length orlist) 1)
10474 (cons 'or orlist) (car orlist))))
10476 ;; Return the string and lisp forms of the matcher
10477 (setq matcher (if todomatcher
10478 (list 'and tagsmatcher todomatcher)
10479 tagsmatcher))
10480 (cons match0 matcher)))
10482 (defun org-op-to-function (op &optional stringp)
10483 "Turn an operator into the appropriate function."
10484 (setq op
10485 (cond
10486 ((equal op "<" ) '(< string< org-time<))
10487 ((equal op ">" ) '(> org-string> org-time>))
10488 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
10489 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
10490 ((member op '("=" "==")) '(= string= org-time=))
10491 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
10492 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
10494 (defun org<> (a b) (not (= a b)))
10495 (defun org-string<= (a b) (or (string= a b) (string< a b)))
10496 (defun org-string>= (a b) (not (string< a b)))
10497 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
10498 (defun org-string<> (a b) (not (string= a b)))
10499 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
10500 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
10501 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
10502 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
10503 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
10504 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
10505 (defun org-2ft (s)
10506 "Convert S to a floating point time.
10507 If S is already a number, just return it. If it is a string, parse
10508 it as a time string and apply `float-time' to it. If S is nil, just return 0."
10509 (cond
10510 ((numberp s) s)
10511 ((stringp s)
10512 (condition-case nil
10513 (float-time (apply 'encode-time (org-parse-time-string s)))
10514 (error 0.)))
10515 (t 0.)))
10517 (defun org-time-today ()
10518 "Time in seconds today at 0:00.
10519 Returns the float number of seconds since the beginning of the
10520 epoch to the beginning of today (00:00)."
10521 (float-time (apply 'encode-time
10522 (append '(0 0 0) (nthcdr 3 (decode-time))))))
10524 (defun org-matcher-time (s)
10525 "Interpret a time comparison value."
10526 (save-match-data
10527 (cond
10528 ((string= s "<now>") (float-time))
10529 ((string= s "<today>") (org-time-today))
10530 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
10531 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
10532 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
10533 (+ (org-time-today)
10534 (* (string-to-number (match-string 1 s))
10535 (cdr (assoc (match-string 2 s)
10536 '(("d" . 86400.0) ("w" . 604800.0)
10537 ("m" . 2678400.0) ("y" . 31557600.0)))))))
10538 (t (org-2ft s)))))
10540 (defun org-match-any-p (re list)
10541 "Does re match any element of list?"
10542 (setq list (mapcar (lambda (x) (string-match re x)) list))
10543 (delq nil list))
10545 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
10546 (defvar org-tags-overlay (org-make-overlay 1 1))
10547 (org-detach-overlay org-tags-overlay)
10549 (defun org-get-local-tags-at (&optional pos)
10550 "Get a list of tags defined in the current headline."
10551 (org-get-tags-at pos 'local))
10553 (defun org-get-local-tags ()
10554 "Get a list of tags defined in the current headline."
10555 (org-get-tags-at nil 'local))
10557 (defun org-get-tags-at (&optional pos local)
10558 "Get a list of all headline tags applicable at POS.
10559 POS defaults to point. If tags are inherited, the list contains
10560 the targets in the same sequence as the headlines appear, i.e.
10561 the tags of the current headline come last.
10562 When LOCAL is non-nil, only return tags from the current headline,
10563 ignore inherited ones."
10564 (interactive)
10565 (if (and org-trust-scanner-tags
10566 (or (not pos) (equal pos (point)))
10567 (not local))
10568 org-scanner-tags
10569 (let (tags ltags lastpos parent)
10570 (save-excursion
10571 (save-restriction
10572 (widen)
10573 (goto-char (or pos (point)))
10574 (save-match-data
10575 (catch 'done
10576 (condition-case nil
10577 (progn
10578 (org-back-to-heading t)
10579 (while (not (equal lastpos (point)))
10580 (setq lastpos (point))
10581 (when (looking-at
10582 (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
10583 (setq ltags (org-split-string
10584 (org-match-string-no-properties 1) ":"))
10585 (when parent
10586 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
10587 (setq tags (append
10588 (if parent
10589 (org-remove-uniherited-tags ltags)
10590 ltags)
10591 tags)))
10592 (or org-use-tag-inheritance (throw 'done t))
10593 (if local (throw 'done t))
10594 (org-up-heading-all 1)
10595 (setq parent t)))
10596 (error nil)))))
10597 (append (org-remove-uniherited-tags org-file-tags) tags)))))
10599 (defun org-add-prop-inherited (s)
10600 (add-text-properties 0 (length s) '(inherited t) s)
10603 (defun org-toggle-tag (tag &optional onoff)
10604 "Toggle the tag TAG for the current line.
10605 If ONOFF is `on' or `off', don't toggle but set to this state."
10606 (let (res current)
10607 (save-excursion
10608 (org-back-to-heading t)
10609 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
10610 (point-at-eol) t)
10611 (progn
10612 (setq current (match-string 1))
10613 (replace-match ""))
10614 (setq current ""))
10615 (setq current (nreverse (org-split-string current ":")))
10616 (cond
10617 ((eq onoff 'on)
10618 (setq res t)
10619 (or (member tag current) (push tag current)))
10620 ((eq onoff 'off)
10621 (or (not (member tag current)) (setq current (delete tag current))))
10622 (t (if (member tag current)
10623 (setq current (delete tag current))
10624 (setq res t)
10625 (push tag current))))
10626 (end-of-line 1)
10627 (if current
10628 (progn
10629 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
10630 (org-set-tags nil t))
10631 (delete-horizontal-space))
10632 (run-hooks 'org-after-tags-change-hook))
10633 res))
10635 (defun org-align-tags-here (to-col)
10636 ;; Assumes that this is a headline
10637 (let ((pos (point)) (col (current-column)) ncol tags-l p)
10638 (beginning-of-line 1)
10639 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10640 (< pos (match-beginning 2)))
10641 (progn
10642 (setq tags-l (- (match-end 2) (match-beginning 2)))
10643 (goto-char (match-beginning 1))
10644 (insert " ")
10645 (delete-region (point) (1+ (match-beginning 2)))
10646 (setq ncol (max (1+ (current-column))
10647 (1+ col)
10648 (if (> to-col 0)
10649 to-col
10650 (- (abs to-col) tags-l))))
10651 (setq p (point))
10652 (insert (make-string (- ncol (current-column)) ?\ ))
10653 (setq ncol (current-column))
10654 (when indent-tabs-mode (tabify p (point-at-eol)))
10655 (org-move-to-column (min ncol col) t))
10656 (goto-char pos))))
10658 (defun org-set-tags-command (&optional arg just-align)
10659 "Call the set-tags command for the current entry."
10660 (interactive "P")
10661 (if (org-on-heading-p)
10662 (org-set-tags arg just-align)
10663 (save-excursion
10664 (org-back-to-heading t)
10665 (org-set-tags arg just-align))))
10667 (defun org-set-tags (&optional arg just-align)
10668 "Set the tags for the current headline.
10669 With prefix ARG, realign all tags in headings in the current buffer."
10670 (interactive "P")
10671 (let* ((re (concat "^" outline-regexp))
10672 (current (org-get-tags-string))
10673 (col (current-column))
10674 (org-setting-tags t)
10675 table current-tags inherited-tags ; computed below when needed
10676 tags p0 c0 c1 rpl)
10677 (if arg
10678 (save-excursion
10679 (goto-char (point-min))
10680 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
10681 (while (re-search-forward re nil t)
10682 (org-set-tags nil t)
10683 (end-of-line 1)))
10684 (message "All tags realigned to column %d" org-tags-column))
10685 (if just-align
10686 (setq tags current)
10687 ;; Get a new set of tags from the user
10688 (save-excursion
10689 (setq table (append org-tag-persistent-alist
10690 (or org-tag-alist (org-get-buffer-tags)))
10691 org-last-tags-completion-table table
10692 current-tags (org-split-string current ":")
10693 inherited-tags (nreverse
10694 (nthcdr (length current-tags)
10695 (nreverse (org-get-tags-at))))
10696 tags
10697 (if (or (eq t org-use-fast-tag-selection)
10698 (and org-use-fast-tag-selection
10699 (delq nil (mapcar 'cdr table))))
10700 (org-fast-tag-selection
10701 current-tags inherited-tags table
10702 (if org-fast-tag-selection-include-todo org-todo-key-alist))
10703 (let ((org-add-colon-after-tag-completion t))
10704 (org-trim
10705 (org-without-partial-completion
10706 (org-ido-completing-read "Tags: " 'org-tags-completion-function
10707 nil nil current 'org-tags-history)))))))
10708 (while (string-match "[-+&]+" tags)
10709 ;; No boolean logic, just a list
10710 (setq tags (replace-match ":" t t tags))))
10712 (if (string-match "\\`[\t ]*\\'" tags)
10713 (setq tags "")
10714 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
10715 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
10717 ;; Insert new tags at the correct column
10718 (beginning-of-line 1)
10719 (cond
10720 ((and (equal current "") (equal tags "")))
10721 ((re-search-forward
10722 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
10723 (point-at-eol) t)
10724 (if (equal tags "")
10725 (setq rpl "")
10726 (goto-char (match-beginning 0))
10727 (setq c0 (current-column) p0 (point)
10728 c1 (max (1+ c0) (if (> org-tags-column 0)
10729 org-tags-column
10730 (- (- org-tags-column) (length tags))))
10731 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
10732 (replace-match rpl t t)
10733 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
10734 tags)
10735 (t (error "Tags alignment failed")))
10736 (org-move-to-column col)
10737 (unless just-align
10738 (run-hooks 'org-after-tags-change-hook)))))
10740 (defun org-change-tag-in-region (beg end tag off)
10741 "Add or remove TAG for each entry in the region.
10742 This works in the agenda, and also in an org-mode buffer."
10743 (interactive
10744 (list (region-beginning) (region-end)
10745 (let ((org-last-tags-completion-table
10746 (if (org-mode-p)
10747 (org-get-buffer-tags)
10748 (org-global-tags-completion-table))))
10749 (org-ido-completing-read
10750 "Tag: " 'org-tags-completion-function nil nil nil
10751 'org-tags-history))
10752 (progn
10753 (message "[s]et or [r]emove? ")
10754 (equal (read-char-exclusive) ?r))))
10755 (if (fboundp 'deactivate-mark) (deactivate-mark))
10756 (let ((agendap (equal major-mode 'org-agenda-mode))
10757 l1 l2 m buf pos newhead (cnt 0))
10758 (goto-char end)
10759 (setq l2 (1- (org-current-line)))
10760 (goto-char beg)
10761 (setq l1 (org-current-line))
10762 (loop for l from l1 to l2 do
10763 (goto-line l)
10764 (setq m (get-text-property (point) 'org-hd-marker))
10765 (when (or (and (org-mode-p) (org-on-heading-p))
10766 (and agendap m))
10767 (setq buf (if agendap (marker-buffer m) (current-buffer))
10768 pos (if agendap m (point)))
10769 (with-current-buffer buf
10770 (save-excursion
10771 (save-restriction
10772 (goto-char pos)
10773 (setq cnt (1+ cnt))
10774 (org-toggle-tag tag (if off 'off 'on))
10775 (setq newhead (org-get-heading)))))
10776 (and agendap (org-agenda-change-all-lines newhead m))))
10777 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
10779 (defun org-tags-completion-function (string predicate &optional flag)
10780 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
10781 (confirm (lambda (x) (stringp (car x)))))
10782 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
10783 (setq s1 (match-string 1 string)
10784 s2 (match-string 2 string))
10785 (setq s1 "" s2 string))
10786 (cond
10787 ((eq flag nil)
10788 ;; try completion
10789 (setq rtn (try-completion s2 ctable confirm))
10790 (if (stringp rtn)
10791 (setq rtn
10792 (concat s1 s2 (substring rtn (length s2))
10793 (if (and org-add-colon-after-tag-completion
10794 (assoc rtn ctable))
10795 ":" ""))))
10796 rtn)
10797 ((eq flag t)
10798 ;; all-completions
10799 (all-completions s2 ctable confirm)
10801 ((eq flag 'lambda)
10802 ;; exact match?
10803 (assoc s2 ctable)))
10806 (defun org-fast-tag-insert (kwd tags face &optional end)
10807 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
10808 (insert (format "%-12s" (concat kwd ":"))
10809 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
10810 (or end "")))
10812 (defun org-fast-tag-show-exit (flag)
10813 (save-excursion
10814 (goto-line 3)
10815 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
10816 (replace-match ""))
10817 (when flag
10818 (end-of-line 1)
10819 (org-move-to-column (- (window-width) 19) t)
10820 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
10822 (defun org-set-current-tags-overlay (current prefix)
10823 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
10824 (if (featurep 'xemacs)
10825 (org-overlay-display org-tags-overlay (concat prefix s)
10826 'secondary-selection)
10827 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
10828 (org-overlay-display org-tags-overlay (concat prefix s)))))
10830 (defun org-fast-tag-selection (current inherited table &optional todo-table)
10831 "Fast tag selection with single keys.
10832 CURRENT is the current list of tags in the headline, INHERITED is the
10833 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
10834 possibly with grouping information. TODO-TABLE is a similar table with
10835 TODO keywords, should these have keys assigned to them.
10836 If the keys are nil, a-z are automatically assigned.
10837 Returns the new tags string, or nil to not change the current settings."
10838 (let* ((fulltable (append table todo-table))
10839 (maxlen (apply 'max (mapcar
10840 (lambda (x)
10841 (if (stringp (car x)) (string-width (car x)) 0))
10842 fulltable)))
10843 (buf (current-buffer))
10844 (expert (eq org-fast-tag-selection-single-key 'expert))
10845 (buffer-tags nil)
10846 (fwidth (+ maxlen 3 1 3))
10847 (ncol (/ (- (window-width) 4) fwidth))
10848 (i-face 'org-done)
10849 (c-face 'org-todo)
10850 tg cnt e c char c1 c2 ntable tbl rtn
10851 ov-start ov-end ov-prefix
10852 (exit-after-next org-fast-tag-selection-single-key)
10853 (done-keywords org-done-keywords)
10854 groups ingroup)
10855 (save-excursion
10856 (beginning-of-line 1)
10857 (if (looking-at
10858 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10859 (setq ov-start (match-beginning 1)
10860 ov-end (match-end 1)
10861 ov-prefix "")
10862 (setq ov-start (1- (point-at-eol))
10863 ov-end (1+ ov-start))
10864 (skip-chars-forward "^\n\r")
10865 (setq ov-prefix
10866 (concat
10867 (buffer-substring (1- (point)) (point))
10868 (if (> (current-column) org-tags-column)
10870 (make-string (- org-tags-column (current-column)) ?\ ))))))
10871 (org-move-overlay org-tags-overlay ov-start ov-end)
10872 (save-window-excursion
10873 (if expert
10874 (set-buffer (get-buffer-create " *Org tags*"))
10875 (delete-other-windows)
10876 (split-window-vertically)
10877 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
10878 (erase-buffer)
10879 (org-set-local 'org-done-keywords done-keywords)
10880 (org-fast-tag-insert "Inherited" inherited i-face "\n")
10881 (org-fast-tag-insert "Current" current c-face "\n\n")
10882 (org-fast-tag-show-exit exit-after-next)
10883 (org-set-current-tags-overlay current ov-prefix)
10884 (setq tbl fulltable char ?a cnt 0)
10885 (while (setq e (pop tbl))
10886 (cond
10887 ((equal e '(:startgroup))
10888 (push '() groups) (setq ingroup t)
10889 (when (not (= cnt 0))
10890 (setq cnt 0)
10891 (insert "\n"))
10892 (insert "{ "))
10893 ((equal e '(:endgroup))
10894 (setq ingroup nil cnt 0)
10895 (insert "}\n"))
10896 ((equal e '(:newline))
10897 (when (not (= cnt 0))
10898 (setq cnt 0)
10899 (insert "\n")
10900 (setq e (car tbl))
10901 (while (equal (car tbl) '(:newline))
10902 (insert "\n")
10903 (setq tbl (cdr tbl)))))
10905 (setq tg (car e) c2 nil)
10906 (if (cdr e)
10907 (setq c (cdr e))
10908 ;; automatically assign a character.
10909 (setq c1 (string-to-char
10910 (downcase (substring
10911 tg (if (= (string-to-char tg) ?@) 1 0)))))
10912 (if (or (rassoc c1 ntable) (rassoc c1 table))
10913 (while (or (rassoc char ntable) (rassoc char table))
10914 (setq char (1+ char)))
10915 (setq c2 c1))
10916 (setq c (or c2 char)))
10917 (if ingroup (push tg (car groups)))
10918 (setq tg (org-add-props tg nil 'face
10919 (cond
10920 ((not (assoc tg table))
10921 (org-get-todo-face tg))
10922 ((member tg current) c-face)
10923 ((member tg inherited) i-face)
10924 (t nil))))
10925 (if (and (= cnt 0) (not ingroup)) (insert " "))
10926 (insert "[" c "] " tg (make-string
10927 (- fwidth 4 (length tg)) ?\ ))
10928 (push (cons tg c) ntable)
10929 (when (= (setq cnt (1+ cnt)) ncol)
10930 (insert "\n")
10931 (if ingroup (insert " "))
10932 (setq cnt 0)))))
10933 (setq ntable (nreverse ntable))
10934 (insert "\n")
10935 (goto-char (point-min))
10936 (if (not expert) (org-fit-window-to-buffer))
10937 (setq rtn
10938 (catch 'exit
10939 (while t
10940 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
10941 (if groups " [!] no groups" " [!]groups")
10942 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
10943 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
10944 (cond
10945 ((= c ?\r) (throw 'exit t))
10946 ((= c ?!)
10947 (setq groups (not groups))
10948 (goto-char (point-min))
10949 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
10950 ((= c ?\C-c)
10951 (if (not expert)
10952 (org-fast-tag-show-exit
10953 (setq exit-after-next (not exit-after-next)))
10954 (setq expert nil)
10955 (delete-other-windows)
10956 (split-window-vertically)
10957 (org-switch-to-buffer-other-window " *Org tags*")
10958 (org-fit-window-to-buffer)))
10959 ((or (= c ?\C-g)
10960 (and (= c ?q) (not (rassoc c ntable))))
10961 (org-detach-overlay org-tags-overlay)
10962 (setq quit-flag t))
10963 ((= c ?\ )
10964 (setq current nil)
10965 (if exit-after-next (setq exit-after-next 'now)))
10966 ((= c ?\t)
10967 (condition-case nil
10968 (setq tg (org-ido-completing-read
10969 "Tag: "
10970 (or buffer-tags
10971 (with-current-buffer buf
10972 (org-get-buffer-tags)))))
10973 (quit (setq tg "")))
10974 (when (string-match "\\S-" tg)
10975 (add-to-list 'buffer-tags (list tg))
10976 (if (member tg current)
10977 (setq current (delete tg current))
10978 (push tg current)))
10979 (if exit-after-next (setq exit-after-next 'now)))
10980 ((setq e (rassoc c todo-table) tg (car e))
10981 (with-current-buffer buf
10982 (save-excursion (org-todo tg)))
10983 (if exit-after-next (setq exit-after-next 'now)))
10984 ((setq e (rassoc c ntable) tg (car e))
10985 (if (member tg current)
10986 (setq current (delete tg current))
10987 (loop for g in groups do
10988 (if (member tg g)
10989 (mapc (lambda (x)
10990 (setq current (delete x current)))
10991 g)))
10992 (push tg current))
10993 (if exit-after-next (setq exit-after-next 'now))))
10995 ;; Create a sorted list
10996 (setq current
10997 (sort current
10998 (lambda (a b)
10999 (assoc b (cdr (memq (assoc a ntable) ntable))))))
11000 (if (eq exit-after-next 'now) (throw 'exit t))
11001 (goto-char (point-min))
11002 (beginning-of-line 2)
11003 (delete-region (point) (point-at-eol))
11004 (org-fast-tag-insert "Current" current c-face)
11005 (org-set-current-tags-overlay current ov-prefix)
11006 (while (re-search-forward
11007 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
11008 (setq tg (match-string 1))
11009 (add-text-properties
11010 (match-beginning 1) (match-end 1)
11011 (list 'face
11012 (cond
11013 ((member tg current) c-face)
11014 ((member tg inherited) i-face)
11015 (t (get-text-property (match-beginning 1) 'face))))))
11016 (goto-char (point-min)))))
11017 (org-detach-overlay org-tags-overlay)
11018 (if rtn
11019 (mapconcat 'identity current ":")
11020 nil))))
11022 (defun org-get-tags-string ()
11023 "Get the TAGS string in the current headline."
11024 (unless (org-on-heading-p t)
11025 (error "Not on a heading"))
11026 (save-excursion
11027 (beginning-of-line 1)
11028 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11029 (org-match-string-no-properties 1)
11030 "")))
11032 (defun org-get-tags ()
11033 "Get the list of tags specified in the current headline."
11034 (org-split-string (org-get-tags-string) ":"))
11036 (defun org-get-buffer-tags ()
11037 "Get a table of all tags used in the buffer, for completion."
11038 (let (tags)
11039 (save-excursion
11040 (goto-char (point-min))
11041 (while (re-search-forward
11042 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
11043 (when (equal (char-after (point-at-bol 0)) ?*)
11044 (mapc (lambda (x) (add-to-list 'tags x))
11045 (org-split-string (org-match-string-no-properties 1) ":")))))
11046 (mapcar 'list tags)))
11048 ;;;; The mapping API
11050 ;;;###autoload
11051 (defun org-map-entries (func &optional match scope &rest skip)
11052 "Call FUNC at each headline selected by MATCH in SCOPE.
11054 FUNC is a function or a lisp form. The function will be called without
11055 arguments, with the cursor positioned at the beginning of the headline.
11056 The return values of all calls to the function will be collected and
11057 returned as a list.
11059 The call to FUNC will be wrapped into a save-excursion form, so FUNC
11060 does not need to preserve point. After evaluaton, the cursor will be
11061 moved to the end of the line (presumably of the headline of the
11062 processed entry) and search continues from there. Under some
11063 circumstances, this may not produce the wanted results. For example,
11064 if you have removed (e.g. archived) the current (sub)tree it could
11065 mean that the next entry will be skipped entirely. In such cases, you
11066 can specify the position from where search should continue by making
11067 FUNC set the variable `org-map-continue-from' to the desired buffer
11068 position.
11070 MATCH is a tags/property/todo match as it is used in the agenda tags view.
11071 Only headlines that are matched by this query will be considered during
11072 the iteration. When MATCH is nil or t, all headlines will be
11073 visited by the iteration.
11075 SCOPE determines the scope of this command. It can be any of:
11077 nil The current buffer, respecting the restriction if any
11078 tree The subtree started with the entry at point
11079 file The current buffer, without restriction
11080 file-with-archives
11081 The current buffer, and any archives associated with it
11082 agenda All agenda files
11083 agenda-with-archives
11084 All agenda files with any archive files associated with them
11085 \(file1 file2 ...)
11086 If this is a list, all files in the list will be scanned
11088 The remaining args are treated as settings for the skipping facilities of
11089 the scanner. The following items can be given here:
11091 archive skip trees with the archive tag.
11092 comment skip trees with the COMMENT keyword
11093 function or Emacs Lisp form:
11094 will be used as value for `org-agenda-skip-function', so whenever
11095 the the function returns t, FUNC will not be called for that
11096 entry and search will continue from the point where the
11097 function leaves it.
11099 If your function needs to retrieve the tags including inherited tags
11100 at the *current* entry, you can use the value of the variable
11101 `org-scanner-tags' which will be much faster than getting the value
11102 with `org-get-tags-at'. If your function gets properties with
11103 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
11104 to t around the call to `org-entry-properties' to get the same speedup.
11105 Note that if your function moves around to retrieve tags and properties at
11106 a *different* entry, you cannot use these techniques."
11107 (let* ((org-agenda-archives-mode nil) ; just to make sure
11108 (org-agenda-skip-archived-trees (memq 'archive skip))
11109 (org-agenda-skip-comment-trees (memq 'comment skip))
11110 (org-agenda-skip-function
11111 (car (org-delete-all '(comment archive) skip)))
11112 (org-tags-match-list-sublevels t)
11113 matcher file res
11114 org-todo-keywords-for-agenda
11115 org-done-keywords-for-agenda
11116 org-todo-keyword-alist-for-agenda
11117 org-tag-alist-for-agenda)
11119 (cond
11120 ((eq match t) (setq matcher t))
11121 ((eq match nil) (setq matcher t))
11122 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
11124 (save-excursion
11125 (save-restriction
11126 (when (eq scope 'tree)
11127 (org-back-to-heading t)
11128 (org-narrow-to-subtree)
11129 (setq scope nil))
11131 (if (not scope)
11132 (progn
11133 (org-prepare-agenda-buffers
11134 (list (buffer-file-name (current-buffer))))
11135 (setq res (org-scan-tags func matcher)))
11136 ;; Get the right scope
11137 (cond
11138 ((and scope (listp scope) (symbolp (car scope)))
11139 (setq scope (eval scope)))
11140 ((eq scope 'agenda)
11141 (setq scope (org-agenda-files t)))
11142 ((eq scope 'agenda-with-archives)
11143 (setq scope (org-agenda-files t))
11144 (setq scope (org-add-archive-files scope)))
11145 ((eq scope 'file)
11146 (setq scope (list (buffer-file-name))))
11147 ((eq scope 'file-with-archives)
11148 (setq scope (org-add-archive-files (list (buffer-file-name))))))
11149 (org-prepare-agenda-buffers scope)
11150 (while (setq file (pop scope))
11151 (with-current-buffer (org-find-base-buffer-visiting file)
11152 (save-excursion
11153 (save-restriction
11154 (widen)
11155 (goto-char (point-min))
11156 (setq res (append res (org-scan-tags func matcher))))))))))
11157 res))
11159 ;;;; Properties
11161 ;;; Setting and retrieving properties
11163 (defconst org-special-properties
11164 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
11165 "TIMESTAMP" "TIMESTAMP_IA")
11166 "The special properties valid in Org-mode.
11168 These are properties that are not defined in the property drawer,
11169 but in some other way.")
11171 (defconst org-default-properties
11172 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
11173 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
11174 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
11175 "EXPORT_FILE_NAME" "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
11176 "ORDERED" "NOBLOCKING")
11177 "Some properties that are used by Org-mode for various purposes.
11178 Being in this list makes sure that they are offered for completion.")
11180 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
11181 "Regular expression matching the first line of a property drawer.")
11183 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
11184 "Regular expression matching the first line of a property drawer.")
11186 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
11187 "Regular expression matching the first line of a property drawer.")
11189 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
11190 "Regular expression matching the first line of a property drawer.")
11192 (defconst org-property-drawer-re
11193 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
11194 org-property-end-re "\\)\n?")
11195 "Matches an entire property drawer.")
11197 (defconst org-clock-drawer-re
11198 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
11199 org-property-end-re "\\)\n?")
11200 "Matches an entire clock drawer.")
11202 (defun org-property-action ()
11203 "Do an action on properties."
11204 (interactive)
11205 (let (c)
11206 (org-at-property-p)
11207 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
11208 (setq c (read-char-exclusive))
11209 (cond
11210 ((equal c ?s)
11211 (call-interactively 'org-set-property))
11212 ((equal c ?d)
11213 (call-interactively 'org-delete-property))
11214 ((equal c ?D)
11215 (call-interactively 'org-delete-property-globally))
11216 ((equal c ?c)
11217 (call-interactively 'org-compute-property-at-point))
11218 (t (error "No such property action %c" c)))))
11220 (defun org-at-property-p ()
11221 "Is the cursor in a property line?"
11222 ;; FIXME: Does not check if we are actually in the drawer.
11223 ;; FIXME: also returns true on any drawers.....
11224 ;; This is used by C-c C-c for property action.
11225 (save-excursion
11226 (beginning-of-line 1)
11227 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
11229 (defun org-get-property-block (&optional beg end force)
11230 "Return the (beg . end) range of the body of the property drawer.
11231 BEG and END can be beginning and end of subtree, if not given
11232 they will be found.
11233 If the drawer does not exist and FORCE is non-nil, create the drawer."
11234 (catch 'exit
11235 (save-excursion
11236 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
11237 (end (or end (progn (outline-next-heading) (point)))))
11238 (goto-char beg)
11239 (if (re-search-forward org-property-start-re end t)
11240 (setq beg (1+ (match-end 0)))
11241 (if force
11242 (save-excursion
11243 (org-insert-property-drawer)
11244 (setq end (progn (outline-next-heading) (point))))
11245 (throw 'exit nil))
11246 (goto-char beg)
11247 (if (re-search-forward org-property-start-re end t)
11248 (setq beg (1+ (match-end 0)))))
11249 (if (re-search-forward org-property-end-re end t)
11250 (setq end (match-beginning 0))
11251 (or force (throw 'exit nil))
11252 (goto-char beg)
11253 (setq end beg)
11254 (org-indent-line-function)
11255 (insert ":END:\n"))
11256 (cons beg end)))))
11258 (defun org-entry-properties (&optional pom which)
11259 "Get all properties of the entry at point-or-marker POM.
11260 This includes the TODO keyword, the tags, time strings for deadline,
11261 scheduled, and clocking, and any additional properties defined in the
11262 entry. The return value is an alist, keys may occur multiple times
11263 if the property key was used several times.
11264 POM may also be nil, in which case the current entry is used.
11265 If WHICH is nil or `all', get all properties. If WHICH is
11266 `special' or `standard', only get that subclass."
11267 (setq which (or which 'all))
11268 (org-with-point-at pom
11269 (let ((clockstr (substring org-clock-string 0 -1))
11270 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
11271 beg end range props sum-props key value string clocksum)
11272 (save-excursion
11273 (when (condition-case nil
11274 (and (org-mode-p) (org-back-to-heading t))
11275 (error nil))
11276 (setq beg (point))
11277 (setq sum-props (get-text-property (point) 'org-summaries))
11278 (setq clocksum (get-text-property (point) :org-clock-minutes))
11279 (outline-next-heading)
11280 (setq end (point))
11281 (when (memq which '(all special))
11282 ;; Get the special properties, like TODO and tags
11283 (goto-char beg)
11284 (when (and (looking-at org-todo-line-regexp) (match-end 2))
11285 (push (cons "TODO" (org-match-string-no-properties 2)) props))
11286 (when (looking-at org-priority-regexp)
11287 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
11288 (when (and (setq value (org-get-tags-string))
11289 (string-match "\\S-" value))
11290 (push (cons "TAGS" value) props))
11291 (when (setq value (org-get-tags-at))
11292 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
11293 props))
11294 (while (re-search-forward org-maybe-keyword-time-regexp end t)
11295 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
11296 string (if (equal key clockstr)
11297 (org-no-properties
11298 (org-trim
11299 (buffer-substring
11300 (match-beginning 3) (goto-char (point-at-eol)))))
11301 (substring (org-match-string-no-properties 3) 1 -1)))
11302 (unless key
11303 (if (= (char-after (match-beginning 3)) ?\[)
11304 (setq key "TIMESTAMP_IA")
11305 (setq key "TIMESTAMP")))
11306 (when (or (equal key clockstr) (not (assoc key props)))
11307 (push (cons key string) props)))
11311 (when (memq which '(all standard))
11312 ;; Get the standard properties, like :PROP: ...
11313 (setq range (org-get-property-block beg end))
11314 (when range
11315 (goto-char (car range))
11316 (while (re-search-forward
11317 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
11318 (cdr range) t)
11319 (setq key (org-match-string-no-properties 1)
11320 value (org-trim (or (org-match-string-no-properties 2) "")))
11321 (unless (member key excluded)
11322 (push (cons key (or value "")) props)))))
11323 (if clocksum
11324 (push (cons "CLOCKSUM"
11325 (org-columns-number-to-string (/ (float clocksum) 60.)
11326 'add_times))
11327 props))
11328 (unless (assoc "CATEGORY" props)
11329 (setq value (or (org-get-category)
11330 (progn (org-refresh-category-properties)
11331 (org-get-category))))
11332 (push (cons "CATEGORY" value) props))
11333 (append sum-props (nreverse props)))))))
11335 (defun org-entry-get (pom property &optional inherit)
11336 "Get value of PROPERTY for entry at point-or-marker POM.
11337 If INHERIT is non-nil and the entry does not have the property,
11338 then also check higher levels of the hierarchy.
11339 If INHERIT is the symbol `selective', use inheritance only if the setting
11340 in `org-use-property-inheritance' selects PROPERTY for inheritance.
11341 If the property is present but empty, the return value is the empty string.
11342 If the property is not present at all, nil is returned."
11343 (org-with-point-at pom
11344 (if (and inherit (if (eq inherit 'selective)
11345 (org-property-inherit-p property)
11347 (org-entry-get-with-inheritance property)
11348 (if (member property org-special-properties)
11349 ;; We need a special property. Use brute force, get all properties.
11350 (cdr (assoc property (org-entry-properties nil 'special)))
11351 (let ((range (org-get-property-block)))
11352 (if (and range
11353 (goto-char (car range))
11354 (re-search-forward
11355 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
11356 (cdr range) t))
11357 ;; Found the property, return it.
11358 (if (match-end 1)
11359 (org-match-string-no-properties 1)
11360 "")))))))
11362 (defun org-property-or-variable-value (var &optional inherit)
11363 "Check if there is a property fixing the value of VAR.
11364 If yes, return this value. If not, return the current value of the variable."
11365 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
11366 (if (and prop (stringp prop) (string-match "\\S-" prop))
11367 (read prop)
11368 (symbol-value var))))
11370 (defun org-entry-delete (pom property)
11371 "Delete the property PROPERTY from entry at point-or-marker POM."
11372 (org-with-point-at pom
11373 (if (member property org-special-properties)
11374 nil ; cannot delete these properties.
11375 (let ((range (org-get-property-block)))
11376 (if (and range
11377 (goto-char (car range))
11378 (re-search-forward
11379 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
11380 (cdr range) t))
11381 (progn
11382 (delete-region (match-beginning 0) (1+ (point-at-eol)))
11384 nil)))))
11386 ;; Multi-values properties are properties that contain multiple values
11387 ;; These values are assumed to be single words, separated by whitespace.
11388 (defun org-entry-add-to-multivalued-property (pom property value)
11389 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
11390 (let* ((old (org-entry-get pom property))
11391 (values (and old (org-split-string old "[ \t]"))))
11392 (setq value (org-entry-protect-space value))
11393 (unless (member value values)
11394 (setq values (cons value values))
11395 (org-entry-put pom property
11396 (mapconcat 'identity values " ")))))
11398 (defun org-entry-remove-from-multivalued-property (pom property value)
11399 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
11400 (let* ((old (org-entry-get pom property))
11401 (values (and old (org-split-string old "[ \t]"))))
11402 (setq value (org-entry-protect-space value))
11403 (when (member value values)
11404 (setq values (delete value values))
11405 (org-entry-put pom property
11406 (mapconcat 'identity values " ")))))
11408 (defun org-entry-member-in-multivalued-property (pom property value)
11409 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
11410 (let* ((old (org-entry-get pom property))
11411 (values (and old (org-split-string old "[ \t]"))))
11412 (setq value (org-entry-protect-space value))
11413 (member value values)))
11415 (defun org-entry-get-multivalued-property (pom property)
11416 "Return a list of values in a multivalued property."
11417 (let* ((value (org-entry-get pom property))
11418 (values (and value (org-split-string value "[ \t]"))))
11419 (mapcar 'org-entry-restore-space values)))
11421 (defun org-entry-put-multivalued-property (pom property &rest values)
11422 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
11423 VALUES should be a list of strings. Spaces will be protected."
11424 (org-entry-put pom property
11425 (mapconcat 'org-entry-protect-space values " "))
11426 (let* ((value (org-entry-get pom property))
11427 (values (and value (org-split-string value "[ \t]"))))
11428 (mapcar 'org-entry-restore-space values)))
11430 (defun org-entry-protect-space (s)
11431 "Protect spaces and newline in string S."
11432 (while (string-match " " s)
11433 (setq s (replace-match "%20" t t s)))
11434 (while (string-match "\n" s)
11435 (setq s (replace-match "%0A" t t s)))
11438 (defun org-entry-restore-space (s)
11439 "Restore spaces and newline in string S."
11440 (while (string-match "%20" s)
11441 (setq s (replace-match " " t t s)))
11442 (while (string-match "%0A" s)
11443 (setq s (replace-match "\n" t t s)))
11446 (defvar org-entry-property-inherited-from (make-marker)
11447 "Marker pointing to the entry from where a property was inherited.
11448 Each call to `org-entry-get-with-inheritance' will set this marker to the
11449 location of the entry where the inheritance search matched. If there was
11450 no match, the marker will point nowhere.
11451 Note that also `org-entry-get' calls this function, if the INHERIT flag
11452 is set.")
11454 (defun org-entry-get-with-inheritance (property)
11455 "Get entry property, and search higher levels if not present."
11456 (move-marker org-entry-property-inherited-from nil)
11457 (let (tmp)
11458 (save-excursion
11459 (save-restriction
11460 (widen)
11461 (catch 'ex
11462 (while t
11463 (when (setq tmp (org-entry-get nil property))
11464 (org-back-to-heading t)
11465 (move-marker org-entry-property-inherited-from (point))
11466 (throw 'ex tmp))
11467 (or (org-up-heading-safe) (throw 'ex nil)))))
11468 (or tmp
11469 (cdr (assoc property org-file-properties))
11470 (cdr (assoc property org-global-properties))
11471 (cdr (assoc property org-global-properties-fixed))))))
11473 (defun org-entry-put (pom property value)
11474 "Set PROPERTY to VALUE for entry at point-or-marker POM."
11475 (org-with-point-at pom
11476 (org-back-to-heading t)
11477 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
11478 range)
11479 (cond
11480 ((equal property "TODO")
11481 (when (and (stringp value) (string-match "\\S-" value)
11482 (not (member value org-todo-keywords-1)))
11483 (error "\"%s\" is not a valid TODO state" value))
11484 (if (or (not value)
11485 (not (string-match "\\S-" value)))
11486 (setq value 'none))
11487 (org-todo value)
11488 (org-set-tags nil 'align))
11489 ((equal property "PRIORITY")
11490 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
11491 (string-to-char value) ?\ ))
11492 (org-set-tags nil 'align))
11493 ((equal property "SCHEDULED")
11494 (if (re-search-forward org-scheduled-time-regexp end t)
11495 (cond
11496 ((eq value 'earlier) (org-timestamp-change -1 'day))
11497 ((eq value 'later) (org-timestamp-change 1 'day))
11498 (t (call-interactively 'org-schedule)))
11499 (call-interactively 'org-schedule)))
11500 ((equal property "DEADLINE")
11501 (if (re-search-forward org-deadline-time-regexp end t)
11502 (cond
11503 ((eq value 'earlier) (org-timestamp-change -1 'day))
11504 ((eq value 'later) (org-timestamp-change 1 'day))
11505 (t (call-interactively 'org-deadline)))
11506 (call-interactively 'org-deadline)))
11507 ((member property org-special-properties)
11508 (error "The %s property can not yet be set with `org-entry-put'"
11509 property))
11510 (t ; a non-special property
11511 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
11512 (setq range (org-get-property-block beg end 'force))
11513 (goto-char (car range))
11514 (if (re-search-forward
11515 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
11516 (progn
11517 (delete-region (match-beginning 1) (match-end 1))
11518 (goto-char (match-beginning 1)))
11519 (goto-char (cdr range))
11520 (insert "\n")
11521 (backward-char 1)
11522 (org-indent-line-function)
11523 (insert ":" property ":"))
11524 (and value (insert " " value))
11525 (org-indent-line-function)))))))
11527 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
11528 "Get all property keys in the current buffer.
11529 With INCLUDE-SPECIALS, also list the special properties that reflect things
11530 like tags and TODO state.
11531 With INCLUDE-DEFAULTS, also include properties that has special meaning
11532 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
11533 With INCLUDE-COLUMNS, also include property names given in COLUMN
11534 formats in the current buffer."
11535 (let (rtn range cfmt s p)
11536 (save-excursion
11537 (save-restriction
11538 (widen)
11539 (goto-char (point-min))
11540 (while (re-search-forward org-property-start-re nil t)
11541 (setq range (org-get-property-block))
11542 (goto-char (car range))
11543 (while (re-search-forward
11544 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
11545 (cdr range) t)
11546 (add-to-list 'rtn (org-match-string-no-properties 1)))
11547 (outline-next-heading))))
11549 (when include-specials
11550 (setq rtn (append org-special-properties rtn)))
11552 (when include-defaults
11553 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
11555 (when include-columns
11556 (save-excursion
11557 (save-restriction
11558 (widen)
11559 (goto-char (point-min))
11560 (while (re-search-forward
11561 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
11562 nil t)
11563 (setq cfmt (match-string 2) s 0)
11564 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
11565 cfmt s)
11566 (setq s (match-end 0)
11567 p (match-string 1 cfmt))
11568 (unless (or (equal p "ITEM")
11569 (member p org-special-properties))
11570 (add-to-list 'rtn (match-string 1 cfmt))))))))
11572 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
11574 (defun org-property-values (key)
11575 "Return a list of all values of property KEY."
11576 (save-excursion
11577 (save-restriction
11578 (widen)
11579 (goto-char (point-min))
11580 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
11581 values)
11582 (while (re-search-forward re nil t)
11583 (add-to-list 'values (org-trim (match-string 1))))
11584 (delete "" values)))))
11586 (defun org-insert-property-drawer ()
11587 "Insert a property drawer into the current entry."
11588 (interactive)
11589 (org-back-to-heading t)
11590 (looking-at outline-regexp)
11591 (let ((indent (- (match-end 0)(match-beginning 0)))
11592 (beg (point))
11593 (re (concat "^[ \t]*" org-keyword-time-regexp))
11594 end hiddenp)
11595 (outline-next-heading)
11596 (setq end (point))
11597 (goto-char beg)
11598 (while (re-search-forward re end t))
11599 (setq hiddenp (org-invisible-p))
11600 (end-of-line 1)
11601 (and (equal (char-after) ?\n) (forward-char 1))
11602 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
11603 (if (member (match-string 1) '("CLOCK:" ":END:"))
11604 ;; just skip this line
11605 (beginning-of-line 2)
11606 ;; Drawer start, find the end
11607 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
11608 (beginning-of-line 1)))
11609 (org-skip-over-state-notes)
11610 (skip-chars-backward " \t\n\r")
11611 (if (eq (char-before) ?*) (forward-char 1))
11612 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
11613 (beginning-of-line 0)
11614 (org-indent-to-column indent)
11615 (beginning-of-line 2)
11616 (org-indent-to-column indent)
11617 (beginning-of-line 0)
11618 (if hiddenp
11619 (save-excursion
11620 (org-back-to-heading t)
11621 (hide-entry))
11622 (org-flag-drawer t))))
11624 (defun org-set-property (property value)
11625 "In the current entry, set PROPERTY to VALUE.
11626 When called interactively, this will prompt for a property name, offering
11627 completion on existing and default properties. And then it will prompt
11628 for a value, offering completion either on allowed values (via an inherited
11629 xxx_ALL property) or on existing values in other instances of this property
11630 in the current file."
11631 (interactive
11632 (let* ((completion-ignore-case t)
11633 (keys (org-buffer-property-keys nil t t))
11634 (prop0 (org-ido-completing-read "Property: " (mapcar 'list keys)))
11635 (prop (if (member prop0 keys)
11636 prop0
11637 (or (cdr (assoc (downcase prop0)
11638 (mapcar (lambda (x) (cons (downcase x) x))
11639 keys)))
11640 prop0)))
11641 (cur (org-entry-get nil prop))
11642 (allowed (org-property-get-allowed-values nil prop 'table))
11643 (existing (mapcar 'list (org-property-values prop)))
11644 (val (if allowed
11645 (org-completing-read "Value: " allowed nil 'req-match)
11646 (let (org-completion-use-ido)
11647 (org-completing-read
11648 (concat "Value" (if (and cur (string-match "\\S-" cur))
11649 (concat "[" cur "]") "")
11650 ": ")
11651 existing nil nil "" nil cur)))))
11652 (list prop (if (equal val "") cur val))))
11653 (unless (equal (org-entry-get nil property) value)
11654 (org-entry-put nil property value)))
11656 (defun org-delete-property (property)
11657 "In the current entry, delete PROPERTY."
11658 (interactive
11659 (let* ((completion-ignore-case t)
11660 (prop (org-ido-completing-read
11661 "Property: " (org-entry-properties nil 'standard))))
11662 (list prop)))
11663 (message "Property %s %s" property
11664 (if (org-entry-delete nil property)
11665 "deleted"
11666 "was not present in the entry")))
11668 (defun org-delete-property-globally (property)
11669 "Remove PROPERTY globally, from all entries."
11670 (interactive
11671 (let* ((completion-ignore-case t)
11672 (prop (org-ido-completing-read
11673 "Globally remove property: "
11674 (mapcar 'list (org-buffer-property-keys)))))
11675 (list prop)))
11676 (save-excursion
11677 (save-restriction
11678 (widen)
11679 (goto-char (point-min))
11680 (let ((cnt 0))
11681 (while (re-search-forward
11682 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
11683 nil t)
11684 (setq cnt (1+ cnt))
11685 (replace-match ""))
11686 (message "Property \"%s\" removed from %d entries" property cnt)))))
11688 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
11690 (defun org-compute-property-at-point ()
11691 "Compute the property at point.
11692 This looks for an enclosing column format, extracts the operator and
11693 then applies it to the property in the column format's scope."
11694 (interactive)
11695 (unless (org-at-property-p)
11696 (error "Not at a property"))
11697 (let ((prop (org-match-string-no-properties 2)))
11698 (org-columns-get-format-and-top-level)
11699 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
11700 (error "No operator defined for property %s" prop))
11701 (org-columns-compute prop)))
11703 (defun org-property-get-allowed-values (pom property &optional table)
11704 "Get allowed values for the property PROPERTY.
11705 When TABLE is non-nil, return an alist that can directly be used for
11706 completion."
11707 (let (vals)
11708 (cond
11709 ((equal property "TODO")
11710 (setq vals (org-with-point-at pom
11711 (append org-todo-keywords-1 '("")))))
11712 ((equal property "PRIORITY")
11713 (let ((n org-lowest-priority))
11714 (while (>= n org-highest-priority)
11715 (push (char-to-string n) vals)
11716 (setq n (1- n)))))
11717 ((member property org-special-properties))
11719 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
11721 (when (and vals (string-match "\\S-" vals))
11722 (setq vals (car (read-from-string (concat "(" vals ")"))))
11723 (setq vals (mapcar (lambda (x)
11724 (cond ((stringp x) x)
11725 ((numberp x) (number-to-string x))
11726 ((symbolp x) (symbol-name x))
11727 (t "???")))
11728 vals)))))
11729 (if table (mapcar 'list vals) vals)))
11731 (defun org-property-previous-allowed-value (&optional previous)
11732 "Switch to the next allowed value for this property."
11733 (interactive)
11734 (org-property-next-allowed-value t))
11736 (defun org-property-next-allowed-value (&optional previous)
11737 "Switch to the next allowed value for this property."
11738 (interactive)
11739 (unless (org-at-property-p)
11740 (error "Not at a property"))
11741 (let* ((key (match-string 2))
11742 (value (match-string 3))
11743 (allowed (or (org-property-get-allowed-values (point) key)
11744 (and (member value '("[ ]" "[-]" "[X]"))
11745 '("[ ]" "[X]"))))
11746 nval)
11747 (unless allowed
11748 (error "Allowed values for this property have not been defined"))
11749 (if previous (setq allowed (reverse allowed)))
11750 (if (member value allowed)
11751 (setq nval (car (cdr (member value allowed)))))
11752 (setq nval (or nval (car allowed)))
11753 (if (equal nval value)
11754 (error "Only one allowed value for this property"))
11755 (org-at-property-p)
11756 (replace-match (concat " :" key ": " nval) t t)
11757 (org-indent-line-function)
11758 (beginning-of-line 1)
11759 (skip-chars-forward " \t")))
11761 (defun org-find-entry-with-id (ident)
11762 "Locate the entry that contains the ID property with exact value IDENT.
11763 IDENT can be a string, a symbol or a number, this function will search for
11764 the string representation of it.
11765 Return the position where this entry starts, or nil if there is no such entry."
11766 (interactive "sID: ")
11767 (let ((id (cond
11768 ((stringp ident) ident)
11769 ((symbol-name ident) (symbol-name ident))
11770 ((numberp ident) (number-to-string ident))
11771 (t (error "IDENT %s must be a string, symbol or number" ident))))
11772 (case-fold-search nil))
11773 (save-excursion
11774 (save-restriction
11775 (widen)
11776 (goto-char (point-min))
11777 (when (re-search-forward
11778 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
11779 nil t)
11780 (org-back-to-heading)
11781 (point))))))
11783 ;;;; Timestamps
11785 (defvar org-last-changed-timestamp nil)
11786 (defvar org-last-inserted-timestamp nil
11787 "The last time stamp inserted with `org-insert-time-stamp'.")
11788 (defvar org-time-was-given) ; dynamically scoped parameter
11789 (defvar org-end-time-was-given) ; dynamically scoped parameter
11790 (defvar org-ts-what) ; dynamically scoped parameter
11792 (defun org-time-stamp (arg &optional inactive)
11793 "Prompt for a date/time and insert a time stamp.
11794 If the user specifies a time like HH:MM, or if this command is called
11795 with a prefix argument, the time stamp will contain date and time.
11796 Otherwise, only the date will be included. All parts of a date not
11797 specified by the user will be filled in from the current date/time.
11798 So if you press just return without typing anything, the time stamp
11799 will represent the current date/time. If there is already a timestamp
11800 at the cursor, it will be modified."
11801 (interactive "P")
11802 (let* ((ts nil)
11803 (default-time
11804 ;; Default time is either today, or, when entering a range,
11805 ;; the range start.
11806 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
11807 (save-excursion
11808 (re-search-backward
11809 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
11810 (- (point) 20) t)))
11811 (apply 'encode-time (org-parse-time-string (match-string 1)))
11812 (current-time)))
11813 (default-input (and ts (org-get-compact-tod ts)))
11814 org-time-was-given org-end-time-was-given time)
11815 (cond
11816 ((and (org-at-timestamp-p t)
11817 (memq last-command '(org-time-stamp org-time-stamp-inactive))
11818 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
11819 (insert "--")
11820 (setq time (let ((this-command this-command))
11821 (org-read-date arg 'totime nil nil
11822 default-time default-input)))
11823 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
11824 ((org-at-timestamp-p t)
11825 (setq time (let ((this-command this-command))
11826 (org-read-date arg 'totime nil nil default-time default-input)))
11827 (when (org-at-timestamp-p t) ; just to get the match data
11828 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
11829 (replace-match "")
11830 (setq org-last-changed-timestamp
11831 (org-insert-time-stamp
11832 time (or org-time-was-given arg)
11833 inactive nil nil (list org-end-time-was-given))))
11834 (message "Timestamp updated"))
11836 (setq time (let ((this-command this-command))
11837 (org-read-date arg 'totime nil nil default-time default-input)))
11838 (org-insert-time-stamp time (or org-time-was-given arg) inactive
11839 nil nil (list org-end-time-was-given))))))
11841 ;; FIXME: can we use this for something else, like computing time differences?
11842 (defun org-get-compact-tod (s)
11843 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
11844 (let* ((t1 (match-string 1 s))
11845 (h1 (string-to-number (match-string 2 s)))
11846 (m1 (string-to-number (match-string 3 s)))
11847 (t2 (and (match-end 4) (match-string 5 s)))
11848 (h2 (and t2 (string-to-number (match-string 6 s))))
11849 (m2 (and t2 (string-to-number (match-string 7 s))))
11850 dh dm)
11851 (if (not t2)
11853 (setq dh (- h2 h1) dm (- m2 m1))
11854 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
11855 (concat t1 "+" (number-to-string dh)
11856 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
11858 (defun org-time-stamp-inactive (&optional arg)
11859 "Insert an inactive time stamp.
11860 An inactive time stamp is enclosed in square brackets instead of angle
11861 brackets. It is inactive in the sense that it does not trigger agenda entries,
11862 does not link to the calendar and cannot be changed with the S-cursor keys.
11863 So these are more for recording a certain time/date."
11864 (interactive "P")
11865 (org-time-stamp arg 'inactive))
11867 (defvar org-date-ovl (org-make-overlay 1 1))
11868 (org-overlay-put org-date-ovl 'face 'org-warning)
11869 (org-detach-overlay org-date-ovl)
11871 (defvar org-ans1) ; dynamically scoped parameter
11872 (defvar org-ans2) ; dynamically scoped parameter
11874 (defvar org-plain-time-of-day-regexp) ; defined below
11876 (defvar org-overriding-default-time nil) ; dynamically scoped
11877 (defvar org-read-date-overlay nil)
11878 (defvar org-dcst nil) ; dynamically scoped
11879 (defvar org-read-date-history nil)
11881 (defun org-read-date (&optional with-time to-time from-string prompt
11882 default-time default-input)
11883 "Read a date, possibly a time, and make things smooth for the user.
11884 The prompt will suggest to enter an ISO date, but you can also enter anything
11885 which will at least partially be understood by `parse-time-string'.
11886 Unrecognized parts of the date will default to the current day, month, year,
11887 hour and minute. If this command is called to replace a timestamp at point,
11888 of to enter the second timestamp of a range, the default time is taken from the
11889 existing stamp. For example,
11890 3-2-5 --> 2003-02-05
11891 feb 15 --> currentyear-02-15
11892 sep 12 9 --> 2009-09-12
11893 12:45 --> today 12:45
11894 22 sept 0:34 --> currentyear-09-22 0:34
11895 12 --> currentyear-currentmonth-12
11896 Fri --> nearest Friday (today or later)
11897 etc.
11899 Furthermore you can specify a relative date by giving, as the *first* thing
11900 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
11901 change in days weeks, months, years.
11902 With a single plus or minus, the date is relative to today. With a double
11903 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
11904 +4d --> four days from today
11905 +4 --> same as above
11906 +2w --> two weeks from today
11907 ++5 --> five days from default date
11909 The function understands only English month and weekday abbreviations,
11910 but this can be configured with the variables `parse-time-months' and
11911 `parse-time-weekdays'.
11913 While prompting, a calendar is popped up - you can also select the
11914 date with the mouse (button 1). The calendar shows a period of three
11915 months. To scroll it to other months, use the keys `>' and `<'.
11916 If you don't like the calendar, turn it off with
11917 \(setq org-read-date-popup-calendar nil)
11919 With optional argument TO-TIME, the date will immediately be converted
11920 to an internal time.
11921 With an optional argument WITH-TIME, the prompt will suggest to also
11922 insert a time. Note that when WITH-TIME is not set, you can still
11923 enter a time, and this function will inform the calling routine about
11924 this change. The calling routine may then choose to change the format
11925 used to insert the time stamp into the buffer to include the time.
11926 With optional argument FROM-STRING, read from this string instead from
11927 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
11928 the time/date that is used for everything that is not specified by the
11929 user."
11930 (require 'parse-time)
11931 (let* ((org-time-stamp-rounding-minutes
11932 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
11933 (org-dcst org-display-custom-times)
11934 (ct (org-current-time))
11935 (def (or org-overriding-default-time default-time ct))
11936 (defdecode (decode-time def))
11937 (dummy (progn
11938 (when (< (nth 2 defdecode) org-extend-today-until)
11939 (setcar (nthcdr 2 defdecode) -1)
11940 (setcar (nthcdr 1 defdecode) 59)
11941 (setq def (apply 'encode-time defdecode)
11942 defdecode (decode-time def)))))
11943 (calendar-move-hook nil)
11944 (calendar-view-diary-initially-flag nil)
11945 (view-diary-entries-initially nil)
11946 (calendar-view-holidays-initially-flag nil)
11947 (view-calendar-holidays-initially nil)
11948 (timestr (format-time-string
11949 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
11950 (prompt (concat (if prompt (concat prompt " ") "")
11951 (format "Date+time [%s]: " timestr)))
11952 ans (org-ans0 "") org-ans1 org-ans2 final)
11954 (cond
11955 (from-string (setq ans from-string))
11956 (org-read-date-popup-calendar
11957 (save-excursion
11958 (save-window-excursion
11959 (calendar)
11960 (calendar-forward-day (- (time-to-days def)
11961 (calendar-absolute-from-gregorian
11962 (calendar-current-date))))
11963 (org-eval-in-calendar nil t)
11964 (let* ((old-map (current-local-map))
11965 (map (copy-keymap calendar-mode-map))
11966 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
11967 (org-defkey map (kbd "RET") 'org-calendar-select)
11968 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
11969 'org-calendar-select-mouse)
11970 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
11971 'org-calendar-select-mouse)
11972 (org-defkey minibuffer-local-map [(meta shift left)]
11973 (lambda () (interactive)
11974 (org-eval-in-calendar '(calendar-backward-month 1))))
11975 (org-defkey minibuffer-local-map [(meta shift right)]
11976 (lambda () (interactive)
11977 (org-eval-in-calendar '(calendar-forward-month 1))))
11978 (org-defkey minibuffer-local-map [(meta shift up)]
11979 (lambda () (interactive)
11980 (org-eval-in-calendar '(calendar-backward-year 1))))
11981 (org-defkey minibuffer-local-map [(meta shift down)]
11982 (lambda () (interactive)
11983 (org-eval-in-calendar '(calendar-forward-year 1))))
11984 (org-defkey minibuffer-local-map [(shift up)]
11985 (lambda () (interactive)
11986 (org-eval-in-calendar '(calendar-backward-week 1))))
11987 (org-defkey minibuffer-local-map [(shift down)]
11988 (lambda () (interactive)
11989 (org-eval-in-calendar '(calendar-forward-week 1))))
11990 (org-defkey minibuffer-local-map [(shift left)]
11991 (lambda () (interactive)
11992 (org-eval-in-calendar '(calendar-backward-day 1))))
11993 (org-defkey minibuffer-local-map [(shift right)]
11994 (lambda () (interactive)
11995 (org-eval-in-calendar '(calendar-forward-day 1))))
11996 (org-defkey minibuffer-local-map ">"
11997 (lambda () (interactive)
11998 (org-eval-in-calendar '(scroll-calendar-left 1))))
11999 (org-defkey minibuffer-local-map "<"
12000 (lambda () (interactive)
12001 (org-eval-in-calendar '(scroll-calendar-right 1))))
12002 (run-hooks 'org-read-date-minibuffer-setup-hook)
12003 (unwind-protect
12004 (progn
12005 (use-local-map map)
12006 (add-hook 'post-command-hook 'org-read-date-display)
12007 (setq org-ans0 (read-string prompt default-input
12008 'org-read-date-history nil))
12009 ;; org-ans0: from prompt
12010 ;; org-ans1: from mouse click
12011 ;; org-ans2: from calendar motion
12012 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
12013 (remove-hook 'post-command-hook 'org-read-date-display)
12014 (use-local-map old-map)
12015 (when org-read-date-overlay
12016 (org-delete-overlay org-read-date-overlay)
12017 (setq org-read-date-overlay nil)))))))
12019 (t ; Naked prompt only
12020 (unwind-protect
12021 (setq ans (read-string prompt default-input
12022 'org-read-date-history timestr))
12023 (when org-read-date-overlay
12024 (org-delete-overlay org-read-date-overlay)
12025 (setq org-read-date-overlay nil)))))
12027 (setq final (org-read-date-analyze ans def defdecode))
12029 (if to-time
12030 (apply 'encode-time final)
12031 (if (and (boundp 'org-time-was-given) org-time-was-given)
12032 (format "%04d-%02d-%02d %02d:%02d"
12033 (nth 5 final) (nth 4 final) (nth 3 final)
12034 (nth 2 final) (nth 1 final))
12035 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
12036 (defvar def)
12037 (defvar defdecode)
12038 (defvar with-time)
12039 (defun org-read-date-display ()
12040 "Display the current date prompt interpretation in the minibuffer."
12041 (when org-read-date-display-live
12042 (when org-read-date-overlay
12043 (org-delete-overlay org-read-date-overlay))
12044 (let ((p (point)))
12045 (end-of-line 1)
12046 (while (not (equal (buffer-substring
12047 (max (point-min) (- (point) 4)) (point))
12048 " "))
12049 (insert " "))
12050 (goto-char p))
12051 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
12052 " " (or org-ans1 org-ans2)))
12053 (org-end-time-was-given nil)
12054 (f (org-read-date-analyze ans def defdecode))
12055 (fmts (if org-dcst
12056 org-time-stamp-custom-formats
12057 org-time-stamp-formats))
12058 (fmt (if (or with-time
12059 (and (boundp 'org-time-was-given) org-time-was-given))
12060 (cdr fmts)
12061 (car fmts)))
12062 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
12063 (when (and org-end-time-was-given
12064 (string-match org-plain-time-of-day-regexp txt))
12065 (setq txt (concat (substring txt 0 (match-end 0)) "-"
12066 org-end-time-was-given
12067 (substring txt (match-end 0)))))
12068 (setq org-read-date-overlay
12069 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
12070 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
12072 (defun org-read-date-analyze (ans def defdecode)
12073 "Analyse the combined answer of the date prompt."
12074 ;; FIXME: cleanup and comment
12075 (let (delta deltan deltaw deltadef year month day
12076 hour minute second wday pm h2 m2 tl wday1
12077 iso-year iso-weekday iso-week iso-year iso-date)
12079 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
12080 (setq ans "+0"))
12082 (when (setq delta (org-read-date-get-relative ans (current-time) def))
12083 (setq ans (replace-match "" t t ans)
12084 deltan (car delta)
12085 deltaw (nth 1 delta)
12086 deltadef (nth 2 delta)))
12088 ;; Check if there is an iso week date in there
12089 ;; If yes, sore the info and postpone interpreting it until the rest
12090 ;; of the parsing is done
12091 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
12092 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
12093 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
12094 iso-week (string-to-number (match-string 2 ans)))
12095 (setq ans (replace-match "" t t ans)))
12097 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
12098 (when (string-match
12099 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
12100 (setq year (if (match-end 2)
12101 (string-to-number (match-string 2 ans))
12102 (string-to-number (format-time-string "%Y")))
12103 month (string-to-number (match-string 3 ans))
12104 day (string-to-number (match-string 4 ans)))
12105 (if (< year 100) (setq year (+ 2000 year)))
12106 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
12107 t nil ans)))
12108 ;; Help matching am/pm times, because `parse-time-string' does not do that.
12109 ;; If there is a time with am/pm, and *no* time without it, we convert
12110 ;; so that matching will be successful.
12111 (loop for i from 1 to 2 do ; twice, for end time as well
12112 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
12113 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
12114 (setq hour (string-to-number (match-string 1 ans))
12115 minute (if (match-end 3)
12116 (string-to-number (match-string 3 ans))
12118 pm (equal ?p
12119 (string-to-char (downcase (match-string 4 ans)))))
12120 (if (and (= hour 12) (not pm))
12121 (setq hour 0)
12122 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
12123 (setq ans (replace-match (format "%02d:%02d" hour minute)
12124 t t ans))))
12126 ;; Check if a time range is given as a duration
12127 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
12128 (setq hour (string-to-number (match-string 1 ans))
12129 h2 (+ hour (string-to-number (match-string 3 ans)))
12130 minute (string-to-number (match-string 2 ans))
12131 m2 (+ minute (if (match-end 5) (string-to-number
12132 (match-string 5 ans))0)))
12133 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
12134 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
12135 t t ans)))
12137 ;; Check if there is a time range
12138 (when (boundp 'org-end-time-was-given)
12139 (setq org-time-was-given nil)
12140 (when (and (string-match org-plain-time-of-day-regexp ans)
12141 (match-end 8))
12142 (setq org-end-time-was-given (match-string 8 ans))
12143 (setq ans (concat (substring ans 0 (match-beginning 7))
12144 (substring ans (match-end 7))))))
12146 (setq tl (parse-time-string ans)
12147 day (or (nth 3 tl) (nth 3 defdecode))
12148 month (or (nth 4 tl)
12149 (if (and org-read-date-prefer-future
12150 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
12151 (1+ (nth 4 defdecode))
12152 (nth 4 defdecode)))
12153 year (or (nth 5 tl)
12154 (if (and org-read-date-prefer-future
12155 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
12156 (1+ (nth 5 defdecode))
12157 (nth 5 defdecode)))
12158 hour (or (nth 2 tl) (nth 2 defdecode))
12159 minute (or (nth 1 tl) (nth 1 defdecode))
12160 second (or (nth 0 tl) 0)
12161 wday (nth 6 tl))
12163 ;; Special date definitions below
12164 (cond
12165 (iso-week
12166 ;; There was an iso week
12167 (setq year (or iso-year year)
12168 day (or iso-weekday wday 1)
12169 wday nil ; to make sure that the trigger below does not match
12170 iso-date (calendar-gregorian-from-absolute
12171 (calendar-absolute-from-iso
12172 (list iso-week day year))))
12173 ; FIXME: Should we also push ISO weeks into the future?
12174 ; (when (and org-read-date-prefer-future
12175 ; (not iso-year)
12176 ; (< (calendar-absolute-from-gregorian iso-date)
12177 ; (time-to-days (current-time))))
12178 ; (setq year (1+ year)
12179 ; iso-date (calendar-gregorian-from-absolute
12180 ; (calendar-absolute-from-iso
12181 ; (list iso-week day year)))))
12182 (setq month (car iso-date)
12183 year (nth 2 iso-date)
12184 day (nth 1 iso-date)))
12185 (deltan
12186 (unless deltadef
12187 (let ((now (decode-time (current-time))))
12188 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
12189 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
12190 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
12191 ((equal deltaw "m") (setq month (+ month deltan)))
12192 ((equal deltaw "y") (setq year (+ year deltan)))))
12193 ((and wday (not (nth 3 tl)))
12194 ;; Weekday was given, but no day, so pick that day in the week
12195 ;; on or after the derived date.
12196 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
12197 (unless (equal wday wday1)
12198 (setq day (+ day (% (- wday wday1 -7) 7))))))
12199 (if (and (boundp 'org-time-was-given)
12200 (nth 2 tl))
12201 (setq org-time-was-given t))
12202 (if (< year 100) (setq year (+ 2000 year)))
12203 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
12204 (list second minute hour day month year)))
12206 (defvar parse-time-weekdays)
12208 (defun org-read-date-get-relative (s today default)
12209 "Check string S for special relative date string.
12210 TODAY and DEFAULT are internal times, for today and for a default.
12211 Return shift list (N what def-flag)
12212 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
12213 N is the number of WHATs to shift.
12214 DEF-FLAG is t when a double ++ or -- indicates shift relative to
12215 the DEFAULT date rather than TODAY."
12216 (when (and
12217 (string-match
12218 (concat
12219 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
12220 "\\([0-9]+\\)?"
12221 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
12222 "\\([ \t]\\|$\\)") s)
12223 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
12224 (let* ((dir (if (> (match-end 1) (match-beginning 1))
12225 (string-to-char (substring (match-string 1 s) -1))
12226 ?+))
12227 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
12228 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
12229 (what (if (match-end 3) (match-string 3 s) "d"))
12230 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
12231 (date (if rel default today))
12232 (wday (nth 6 (decode-time date)))
12233 delta)
12234 (if wday1
12235 (progn
12236 (setq delta (mod (+ 7 (- wday1 wday)) 7))
12237 (if (= dir ?-) (setq delta (- delta 7)))
12238 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
12239 (list delta "d" rel))
12240 (list (* n (if (= dir ?-) -1 1)) what rel)))))
12242 (defun org-eval-in-calendar (form &optional keepdate)
12243 "Eval FORM in the calendar window and return to current window.
12244 Also, store the cursor date in variable org-ans2."
12245 (let ((sw (selected-window)))
12246 (select-window (get-buffer-window "*Calendar*"))
12247 (eval form)
12248 (when (and (not keepdate) (calendar-cursor-to-date))
12249 (let* ((date (calendar-cursor-to-date))
12250 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12251 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
12252 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
12253 (select-window sw)))
12255 (defun org-calendar-select ()
12256 "Return to `org-read-date' with the date currently selected.
12257 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
12258 (interactive)
12259 (when (calendar-cursor-to-date)
12260 (let* ((date (calendar-cursor-to-date))
12261 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12262 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
12263 (if (active-minibuffer-window) (exit-minibuffer))))
12265 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
12266 "Insert a date stamp for the date given by the internal TIME.
12267 WITH-HM means, use the stamp format that includes the time of the day.
12268 INACTIVE means use square brackets instead of angular ones, so that the
12269 stamp will not contribute to the agenda.
12270 PRE and POST are optional strings to be inserted before and after the
12271 stamp.
12272 The command returns the inserted time stamp."
12273 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
12274 stamp)
12275 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
12276 (insert-before-markers (or pre ""))
12277 (insert-before-markers (setq stamp (format-time-string fmt time)))
12278 (when (listp extra)
12279 (setq extra (car extra))
12280 (if (and (stringp extra)
12281 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
12282 (setq extra (format "-%02d:%02d"
12283 (string-to-number (match-string 1 extra))
12284 (string-to-number (match-string 2 extra))))
12285 (setq extra nil)))
12286 (when extra
12287 (backward-char 1)
12288 (insert-before-markers extra)
12289 (forward-char 1))
12290 (insert-before-markers (or post ""))
12291 (setq org-last-inserted-timestamp stamp)))
12293 (defun org-toggle-time-stamp-overlays ()
12294 "Toggle the use of custom time stamp formats."
12295 (interactive)
12296 (setq org-display-custom-times (not org-display-custom-times))
12297 (unless org-display-custom-times
12298 (let ((p (point-min)) (bmp (buffer-modified-p)))
12299 (while (setq p (next-single-property-change p 'display))
12300 (if (and (get-text-property p 'display)
12301 (eq (get-text-property p 'face) 'org-date))
12302 (remove-text-properties
12303 p (setq p (next-single-property-change p 'display))
12304 '(display t))))
12305 (set-buffer-modified-p bmp)))
12306 (if (featurep 'xemacs)
12307 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
12308 (org-restart-font-lock)
12309 (setq org-table-may-need-update t)
12310 (if org-display-custom-times
12311 (message "Time stamps are overlayed with custom format")
12312 (message "Time stamp overlays removed")))
12314 (defun org-display-custom-time (beg end)
12315 "Overlay modified time stamp format over timestamp between BEG and END."
12316 (let* ((ts (buffer-substring beg end))
12317 t1 w1 with-hm tf time str w2 (off 0))
12318 (save-match-data
12319 (setq t1 (org-parse-time-string ts t))
12320 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
12321 (setq off (- (match-end 0) (match-beginning 0)))))
12322 (setq end (- end off))
12323 (setq w1 (- end beg)
12324 with-hm (and (nth 1 t1) (nth 2 t1))
12325 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
12326 time (org-fix-decoded-time t1)
12327 str (org-add-props
12328 (format-time-string
12329 (substring tf 1 -1) (apply 'encode-time time))
12330 nil 'mouse-face 'highlight)
12331 w2 (length str))
12332 (if (not (= w2 w1))
12333 (add-text-properties (1+ beg) (+ 2 beg)
12334 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
12335 (if (featurep 'xemacs)
12336 (progn
12337 (put-text-property beg end 'invisible t)
12338 (put-text-property beg end 'end-glyph (make-glyph str)))
12339 (put-text-property beg end 'display str))))
12341 (defun org-translate-time (string)
12342 "Translate all timestamps in STRING to custom format.
12343 But do this only if the variable `org-display-custom-times' is set."
12344 (when org-display-custom-times
12345 (save-match-data
12346 (let* ((start 0)
12347 (re org-ts-regexp-both)
12348 t1 with-hm inactive tf time str beg end)
12349 (while (setq start (string-match re string start))
12350 (setq beg (match-beginning 0)
12351 end (match-end 0)
12352 t1 (save-match-data
12353 (org-parse-time-string (substring string beg end) t))
12354 with-hm (and (nth 1 t1) (nth 2 t1))
12355 inactive (equal (substring string beg (1+ beg)) "[")
12356 tf (funcall (if with-hm 'cdr 'car)
12357 org-time-stamp-custom-formats)
12358 time (org-fix-decoded-time t1)
12359 str (format-time-string
12360 (concat
12361 (if inactive "[" "<") (substring tf 1 -1)
12362 (if inactive "]" ">"))
12363 (apply 'encode-time time))
12364 string (replace-match str t t string)
12365 start (+ start (length str)))))))
12366 string)
12368 (defun org-fix-decoded-time (time)
12369 "Set 0 instead of nil for the first 6 elements of time.
12370 Don't touch the rest."
12371 (let ((n 0))
12372 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
12374 (defun org-days-to-time (timestamp-string)
12375 "Difference between TIMESTAMP-STRING and now in days."
12376 (- (time-to-days (org-time-string-to-time timestamp-string))
12377 (time-to-days (current-time))))
12379 (defun org-deadline-close (timestamp-string &optional ndays)
12380 "Is the time in TIMESTAMP-STRING close to the current date?"
12381 (setq ndays (or ndays (org-get-wdays timestamp-string)))
12382 (and (< (org-days-to-time timestamp-string) ndays)
12383 (not (org-entry-is-done-p))))
12385 (defun org-get-wdays (ts)
12386 "Get the deadline lead time appropriate for timestring TS."
12387 (cond
12388 ((<= org-deadline-warning-days 0)
12389 ;; 0 or negative, enforce this value no matter what
12390 (- org-deadline-warning-days))
12391 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
12392 ;; lead time is specified.
12393 (floor (* (string-to-number (match-string 1 ts))
12394 (cdr (assoc (match-string 2 ts)
12395 '(("d" . 1) ("w" . 7)
12396 ("m" . 30.4) ("y" . 365.25)))))))
12397 ;; go for the default.
12398 (t org-deadline-warning-days)))
12400 (defun org-calendar-select-mouse (ev)
12401 "Return to `org-read-date' with the date currently selected.
12402 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
12403 (interactive "e")
12404 (mouse-set-point ev)
12405 (when (calendar-cursor-to-date)
12406 (let* ((date (calendar-cursor-to-date))
12407 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12408 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
12409 (if (active-minibuffer-window) (exit-minibuffer))))
12411 (defun org-check-deadlines (ndays)
12412 "Check if there are any deadlines due or past due.
12413 A deadline is considered due if it happens within `org-deadline-warning-days'
12414 days from today's date. If the deadline appears in an entry marked DONE,
12415 it is not shown. The prefix arg NDAYS can be used to test that many
12416 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
12417 (interactive "P")
12418 (let* ((org-warn-days
12419 (cond
12420 ((equal ndays '(4)) 100000)
12421 (ndays (prefix-numeric-value ndays))
12422 (t (abs org-deadline-warning-days))))
12423 (case-fold-search nil)
12424 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
12425 (callback
12426 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
12428 (message "%d deadlines past-due or due within %d days"
12429 (org-occur regexp nil callback)
12430 org-warn-days)))
12432 (defun org-check-before-date (date)
12433 "Check if there are deadlines or scheduled entries before DATE."
12434 (interactive (list (org-read-date)))
12435 (let ((case-fold-search nil)
12436 (regexp (concat "\\<\\(" org-deadline-string
12437 "\\|" org-scheduled-string
12438 "\\) *<\\([^>]+\\)>"))
12439 (callback
12440 (lambda () (time-less-p
12441 (org-time-string-to-time (match-string 2))
12442 (org-time-string-to-time date)))))
12443 (message "%d entries before %s"
12444 (org-occur regexp nil callback) date)))
12446 (defun org-check-after-date (date)
12447 "Check if there are deadlines or scheduled entries after DATE."
12448 (interactive (list (org-read-date)))
12449 (let ((case-fold-search nil)
12450 (regexp (concat "\\<\\(" org-deadline-string
12451 "\\|" org-scheduled-string
12452 "\\) *<\\([^>]+\\)>"))
12453 (callback
12454 (lambda () (not
12455 (time-less-p
12456 (org-time-string-to-time (match-string 2))
12457 (org-time-string-to-time date))))))
12458 (message "%d entries after %s"
12459 (org-occur regexp nil callback) date)))
12461 (defun org-evaluate-time-range (&optional to-buffer)
12462 "Evaluate a time range by computing the difference between start and end.
12463 Normally the result is just printed in the echo area, but with prefix arg
12464 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
12465 If the time range is actually in a table, the result is inserted into the
12466 next column.
12467 For time difference computation, a year is assumed to be exactly 365
12468 days in order to avoid rounding problems."
12469 (interactive "P")
12471 (org-clock-update-time-maybe)
12472 (save-excursion
12473 (unless (org-at-date-range-p t)
12474 (goto-char (point-at-bol))
12475 (re-search-forward org-tr-regexp-both (point-at-eol) t))
12476 (if (not (org-at-date-range-p t))
12477 (error "Not at a time-stamp range, and none found in current line")))
12478 (let* ((ts1 (match-string 1))
12479 (ts2 (match-string 2))
12480 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
12481 (match-end (match-end 0))
12482 (time1 (org-time-string-to-time ts1))
12483 (time2 (org-time-string-to-time ts2))
12484 (t1 (time-to-seconds time1))
12485 (t2 (time-to-seconds time2))
12486 (diff (abs (- t2 t1)))
12487 (negative (< (- t2 t1) 0))
12488 ;; (ys (floor (* 365 24 60 60)))
12489 (ds (* 24 60 60))
12490 (hs (* 60 60))
12491 (fy "%dy %dd %02d:%02d")
12492 (fy1 "%dy %dd")
12493 (fd "%dd %02d:%02d")
12494 (fd1 "%dd")
12495 (fh "%02d:%02d")
12496 y d h m align)
12497 (if havetime
12498 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
12500 d (floor (/ diff ds)) diff (mod diff ds)
12501 h (floor (/ diff hs)) diff (mod diff hs)
12502 m (floor (/ diff 60)))
12503 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
12505 d (floor (+ (/ diff ds) 0.5))
12506 h 0 m 0))
12507 (if (not to-buffer)
12508 (message "%s" (org-make-tdiff-string y d h m))
12509 (if (org-at-table-p)
12510 (progn
12511 (goto-char match-end)
12512 (setq align t)
12513 (and (looking-at " *|") (goto-char (match-end 0))))
12514 (goto-char match-end))
12515 (if (looking-at
12516 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
12517 (replace-match ""))
12518 (if negative (insert " -"))
12519 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
12520 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
12521 (insert " " (format fh h m))))
12522 (if align (org-table-align))
12523 (message "Time difference inserted")))))
12525 (defun org-make-tdiff-string (y d h m)
12526 (let ((fmt "")
12527 (l nil))
12528 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
12529 l (push y l)))
12530 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
12531 l (push d l)))
12532 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
12533 l (push h l)))
12534 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
12535 l (push m l)))
12536 (apply 'format fmt (nreverse l))))
12538 (defun org-time-string-to-time (s)
12539 (apply 'encode-time (org-parse-time-string s)))
12541 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
12542 "Convert a time stamp to an absolute day number.
12543 If there is a specifyer for a cyclic time stamp, get the closest date to
12544 DAYNR.
12545 PREFER and SHOW-ALL are passed through to `org-closest-date'."
12546 (cond
12547 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
12548 (if (org-diary-sexp-entry (match-string 1 s) "" date)
12549 daynr
12550 (+ daynr 1000)))
12551 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
12552 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
12553 (time-to-days (current-time))) (match-string 0 s)
12554 prefer show-all))
12555 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
12557 (defun org-days-to-iso-week (days)
12558 "Return the iso week number."
12559 (require 'cal-iso)
12560 (car (calendar-iso-from-absolute days)))
12562 (defun org-small-year-to-year (year)
12563 "Convert 2-digit years into 4-digit years.
12564 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
12565 The year 2000 cannot be abbreviated. Any year larger than 99
12566 is returned unchanged."
12567 (if (< year 38)
12568 (setq year (+ 2000 year))
12569 (if (< year 100)
12570 (setq year (+ 1900 year))))
12571 year)
12573 (defun org-time-from-absolute (d)
12574 "Return the time corresponding to date D.
12575 D may be an absolute day number, or a calendar-type list (month day year)."
12576 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
12577 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
12579 (defun org-calendar-holiday ()
12580 "List of holidays, for Diary display in Org-mode."
12581 (require 'holidays)
12582 (let ((hl (funcall
12583 (if (fboundp 'calendar-check-holidays)
12584 'calendar-check-holidays 'check-calendar-holidays) date)))
12585 (if hl (mapconcat 'identity hl "; "))))
12587 (defun org-diary-sexp-entry (sexp entry date)
12588 "Process a SEXP diary ENTRY for DATE."
12589 (require 'diary-lib)
12590 (let ((result (if calendar-debug-sexp
12591 (let ((stack-trace-on-error t))
12592 (eval (car (read-from-string sexp))))
12593 (condition-case nil
12594 (eval (car (read-from-string sexp)))
12595 (error
12596 (beep)
12597 (message "Bad sexp at line %d in %s: %s"
12598 (org-current-line)
12599 (buffer-file-name) sexp)
12600 (sleep-for 2))))))
12601 (cond ((stringp result) result)
12602 ((and (consp result)
12603 (stringp (cdr result))) (cdr result))
12604 (result entry)
12605 (t nil))))
12607 (defun org-diary-to-ical-string (frombuf)
12608 "Get iCalendar entries from diary entries in buffer FROMBUF.
12609 This uses the icalendar.el library."
12610 (let* ((tmpdir (if (featurep 'xemacs)
12611 (temp-directory)
12612 temporary-file-directory))
12613 (tmpfile (make-temp-name
12614 (expand-file-name "orgics" tmpdir)))
12615 buf rtn b e)
12616 (save-excursion
12617 (set-buffer frombuf)
12618 (icalendar-export-region (point-min) (point-max) tmpfile)
12619 (setq buf (find-buffer-visiting tmpfile))
12620 (set-buffer buf)
12621 (goto-char (point-min))
12622 (if (re-search-forward "^BEGIN:VEVENT" nil t)
12623 (setq b (match-beginning 0)))
12624 (goto-char (point-max))
12625 (if (re-search-backward "^END:VEVENT" nil t)
12626 (setq e (match-end 0)))
12627 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
12628 (kill-buffer buf)
12629 (delete-file tmpfile)
12630 rtn))
12632 (defun org-closest-date (start current change prefer show-all)
12633 "Find the date closest to CURRENT that is consistent with START and CHANGE.
12634 When PREFER is `past' return a date that is either CURRENT or past.
12635 When PREFER is `future', return a date that is either CURRENT or future.
12636 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
12637 ;; Make the proper lists from the dates
12638 (catch 'exit
12639 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
12640 dn dw sday cday n1 n2 n0
12641 d m y y1 y2 date1 date2 nmonths nm ny m2)
12643 (setq start (org-date-to-gregorian start)
12644 current (org-date-to-gregorian
12645 (if show-all
12646 current
12647 (time-to-days (current-time))))
12648 sday (calendar-absolute-from-gregorian start)
12649 cday (calendar-absolute-from-gregorian current))
12651 (if (<= cday sday) (throw 'exit sday))
12653 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
12654 (setq dn (string-to-number (match-string 1 change))
12655 dw (cdr (assoc (match-string 2 change) a1)))
12656 (error "Invalid change specifyer: %s" change))
12657 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
12658 (cond
12659 ((eq dw 'day)
12660 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
12661 n2 (+ n1 dn)))
12662 ((eq dw 'year)
12663 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
12664 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
12665 (setq date1 (list m d y1)
12666 n1 (calendar-absolute-from-gregorian date1)
12667 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
12668 n2 (calendar-absolute-from-gregorian date2)))
12669 ((eq dw 'month)
12670 ;; approx number of month between the two dates
12671 (setq nmonths (floor (/ (- cday sday) 30.436875)))
12672 ;; How often does dn fit in there?
12673 (setq d (nth 1 start) m (car start) y (nth 2 start)
12674 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
12675 m (+ m nm)
12676 ny (floor (/ m 12))
12677 y (+ y ny)
12678 m (- m (* ny 12)))
12679 (while (> m 12) (setq m (- m 12) y (1+ y)))
12680 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
12681 (setq m2 (+ m dn) y2 y)
12682 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
12683 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
12684 (while (<= n2 cday)
12685 (setq n1 n2 m m2 y y2)
12686 (setq m2 (+ m dn) y2 y)
12687 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
12688 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
12689 ;; Make sure n1 is the earlier date
12690 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
12691 (if show-all
12692 (cond
12693 ((eq prefer 'past) n1)
12694 ((eq prefer 'future) (if (= cday n1) n1 n2))
12695 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
12696 (cond
12697 ((eq prefer 'past) n1)
12698 ((eq prefer 'future) (if (= cday n1) n1 n2))
12699 (t (if (= cday n1) n1 n2)))))))
12701 (defun org-date-to-gregorian (date)
12702 "Turn any specification of DATE into a gregorian date for the calendar."
12703 (cond ((integerp date) (calendar-gregorian-from-absolute date))
12704 ((and (listp date) (= (length date) 3)) date)
12705 ((stringp date)
12706 (setq date (org-parse-time-string date))
12707 (list (nth 4 date) (nth 3 date) (nth 5 date)))
12708 ((listp date)
12709 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
12711 (defun org-parse-time-string (s &optional nodefault)
12712 "Parse the standard Org-mode time string.
12713 This should be a lot faster than the normal `parse-time-string'.
12714 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
12715 hour and minute fields will be nil if not given."
12716 (if (string-match org-ts-regexp0 s)
12717 (list 0
12718 (if (or (match-beginning 8) (not nodefault))
12719 (string-to-number (or (match-string 8 s) "0")))
12720 (if (or (match-beginning 7) (not nodefault))
12721 (string-to-number (or (match-string 7 s) "0")))
12722 (string-to-number (match-string 4 s))
12723 (string-to-number (match-string 3 s))
12724 (string-to-number (match-string 2 s))
12725 nil nil nil)
12726 (make-list 9 0)))
12728 (defun org-timestamp-up (&optional arg)
12729 "Increase the date item at the cursor by one.
12730 If the cursor is on the year, change the year. If it is on the month or
12731 the day, change that.
12732 With prefix ARG, change by that many units."
12733 (interactive "p")
12734 (org-timestamp-change (prefix-numeric-value arg)))
12736 (defun org-timestamp-down (&optional arg)
12737 "Decrease the date item at the cursor by one.
12738 If the cursor is on the year, change the year. If it is on the month or
12739 the day, change that.
12740 With prefix ARG, change by that many units."
12741 (interactive "p")
12742 (org-timestamp-change (- (prefix-numeric-value arg))))
12744 (defun org-timestamp-up-day (&optional arg)
12745 "Increase the date in the time stamp by one day.
12746 With prefix ARG, change that many days."
12747 (interactive "p")
12748 (if (and (not (org-at-timestamp-p t))
12749 (org-on-heading-p))
12750 (org-todo 'up)
12751 (org-timestamp-change (prefix-numeric-value arg) 'day)))
12753 (defun org-timestamp-down-day (&optional arg)
12754 "Decrease the date in the time stamp by one day.
12755 With prefix ARG, change that many days."
12756 (interactive "p")
12757 (if (and (not (org-at-timestamp-p t))
12758 (org-on-heading-p))
12759 (org-todo 'down)
12760 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
12762 (defun org-at-timestamp-p (&optional inactive-ok)
12763 "Determine if the cursor is in or at a timestamp."
12764 (interactive)
12765 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
12766 (pos (point))
12767 (ans (or (looking-at tsr)
12768 (save-excursion
12769 (skip-chars-backward "^[<\n\r\t")
12770 (if (> (point) (point-min)) (backward-char 1))
12771 (and (looking-at tsr)
12772 (> (- (match-end 0) pos) -1))))))
12773 (and ans
12774 (boundp 'org-ts-what)
12775 (setq org-ts-what
12776 (cond
12777 ((= pos (match-beginning 0)) 'bracket)
12778 ((= pos (1- (match-end 0))) 'bracket)
12779 ((org-pos-in-match-range pos 2) 'year)
12780 ((org-pos-in-match-range pos 3) 'month)
12781 ((org-pos-in-match-range pos 7) 'hour)
12782 ((org-pos-in-match-range pos 8) 'minute)
12783 ((or (org-pos-in-match-range pos 4)
12784 (org-pos-in-match-range pos 5)) 'day)
12785 ((and (> pos (or (match-end 8) (match-end 5)))
12786 (< pos (match-end 0)))
12787 (- pos (or (match-end 8) (match-end 5))))
12788 (t 'day))))
12789 ans))
12791 (defun org-toggle-timestamp-type ()
12792 "Toggle the type (<active> or [inactive]) of a time stamp."
12793 (interactive)
12794 (when (org-at-timestamp-p t)
12795 (let ((beg (match-beginning 0)) (end (match-end 0))
12796 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
12797 (save-excursion
12798 (goto-char beg)
12799 (while (re-search-forward "[][<>]" end t)
12800 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
12801 t t)))
12802 (message "Timestamp is now %sactive"
12803 (if (equal (char-after beg) ?<) "" "in")))))
12805 (defun org-timestamp-change (n &optional what)
12806 "Change the date in the time stamp at point.
12807 The date will be changed by N times WHAT. WHAT can be `day', `month',
12808 `year', `minute', `second'. If WHAT is not given, the cursor position
12809 in the timestamp determines what will be changed."
12810 (let ((pos (point))
12811 with-hm inactive
12812 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
12813 org-ts-what
12814 extra rem
12815 ts time time0)
12816 (if (not (org-at-timestamp-p t))
12817 (error "Not at a timestamp"))
12818 (if (and (not what) (eq org-ts-what 'bracket))
12819 (org-toggle-timestamp-type)
12820 (if (and (not what) (not (eq org-ts-what 'day))
12821 org-display-custom-times
12822 (get-text-property (point) 'display)
12823 (not (get-text-property (1- (point)) 'display)))
12824 (setq org-ts-what 'day))
12825 (setq org-ts-what (or what org-ts-what)
12826 inactive (= (char-after (match-beginning 0)) ?\[)
12827 ts (match-string 0))
12828 (replace-match "")
12829 (if (string-match
12830 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
12832 (setq extra (match-string 1 ts)))
12833 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
12834 (setq with-hm t))
12835 (setq time0 (org-parse-time-string ts))
12836 (when (and (eq org-ts-what 'minute)
12837 (eq current-prefix-arg nil))
12838 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
12839 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
12840 (setcar (cdr time0) (+ (nth 1 time0)
12841 (if (> n 0) (- rem) (- dm rem))))))
12842 (setq time
12843 (encode-time (or (car time0) 0)
12844 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
12845 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
12846 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
12847 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
12848 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
12849 (nthcdr 6 time0)))
12850 (when (and (member org-ts-what '(hour minute))
12851 extra
12852 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
12853 (setq extra (org-modify-ts-extra
12854 extra
12855 (if (eq org-ts-what 'hour) 2 5)
12856 n dm)))
12857 (when (integerp org-ts-what)
12858 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
12859 (if (eq what 'calendar)
12860 (let ((cal-date (org-get-date-from-calendar)))
12861 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
12862 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
12863 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
12864 (setcar time0 (or (car time0) 0))
12865 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
12866 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
12867 (setq time (apply 'encode-time time0))))
12868 (setq org-last-changed-timestamp
12869 (org-insert-time-stamp time with-hm inactive nil nil extra))
12870 (org-clock-update-time-maybe)
12871 (goto-char pos)
12872 ;; Try to recenter the calendar window, if any
12873 (if (and org-calendar-follow-timestamp-change
12874 (get-buffer-window "*Calendar*" t)
12875 (memq org-ts-what '(day month year)))
12876 (org-recenter-calendar (time-to-days time))))))
12878 (defun org-modify-ts-extra (s pos n dm)
12879 "Change the different parts of the lead-time and repeat fields in timestamp."
12880 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
12881 ng h m new rem)
12882 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
12883 (cond
12884 ((or (org-pos-in-match-range pos 2)
12885 (org-pos-in-match-range pos 3))
12886 (setq m (string-to-number (match-string 3 s))
12887 h (string-to-number (match-string 2 s)))
12888 (if (org-pos-in-match-range pos 2)
12889 (setq h (+ h n))
12890 (setq n (* dm (org-no-warnings (signum n))))
12891 (when (not (= 0 (setq rem (% m dm))))
12892 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
12893 (setq m (+ m n)))
12894 (if (< m 0) (setq m (+ m 60) h (1- h)))
12895 (if (> m 59) (setq m (- m 60) h (1+ h)))
12896 (setq h (min 24 (max 0 h)))
12897 (setq ng 1 new (format "-%02d:%02d" h m)))
12898 ((org-pos-in-match-range pos 6)
12899 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
12900 ((org-pos-in-match-range pos 5)
12901 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
12903 ((org-pos-in-match-range pos 9)
12904 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
12905 ((org-pos-in-match-range pos 8)
12906 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
12908 (when ng
12909 (setq s (concat
12910 (substring s 0 (match-beginning ng))
12912 (substring s (match-end ng))))))
12915 (defun org-recenter-calendar (date)
12916 "If the calendar is visible, recenter it to DATE."
12917 (let* ((win (selected-window))
12918 (cwin (get-buffer-window "*Calendar*" t))
12919 (calendar-move-hook nil))
12920 (when cwin
12921 (select-window cwin)
12922 (calendar-goto-date (if (listp date) date
12923 (calendar-gregorian-from-absolute date)))
12924 (select-window win))))
12926 (defun org-goto-calendar (&optional arg)
12927 "Go to the Emacs calendar at the current date.
12928 If there is a time stamp in the current line, go to that date.
12929 A prefix ARG can be used to force the current date."
12930 (interactive "P")
12931 (let ((tsr org-ts-regexp) diff
12932 (calendar-move-hook nil)
12933 (calendar-view-holidays-initially-flag nil)
12934 (view-calendar-holidays-initially nil)
12935 (calendar-view-diary-initially-flag nil)
12936 (view-diary-entries-initially nil))
12937 (if (or (org-at-timestamp-p)
12938 (save-excursion
12939 (beginning-of-line 1)
12940 (looking-at (concat ".*" tsr))))
12941 (let ((d1 (time-to-days (current-time)))
12942 (d2 (time-to-days
12943 (org-time-string-to-time (match-string 1)))))
12944 (setq diff (- d2 d1))))
12945 (calendar)
12946 (calendar-goto-today)
12947 (if (and diff (not arg)) (calendar-forward-day diff))))
12949 (defun org-get-date-from-calendar ()
12950 "Return a list (month day year) of date at point in calendar."
12951 (with-current-buffer "*Calendar*"
12952 (save-match-data
12953 (calendar-cursor-to-date))))
12955 (defun org-date-from-calendar ()
12956 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
12957 If there is already a time stamp at the cursor position, update it."
12958 (interactive)
12959 (if (org-at-timestamp-p t)
12960 (org-timestamp-change 0 'calendar)
12961 (let ((cal-date (org-get-date-from-calendar)))
12962 (org-insert-time-stamp
12963 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
12965 (defun org-minutes-to-hh:mm-string (m)
12966 "Compute H:MM from a number of minutes."
12967 (let ((h (/ m 60)))
12968 (setq m (- m (* 60 h)))
12969 (format org-time-clocksum-format h m)))
12971 (defun org-hh:mm-string-to-minutes (s)
12972 "Convert a string H:MM to a number of minutes."
12973 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
12974 (+ (* (string-to-number (match-string 1 s)) 60)
12975 (string-to-number (match-string 2 s)))
12978 ;;;; Files
12980 (defun org-save-all-org-buffers ()
12981 "Save all Org-mode buffers without user confirmation."
12982 (interactive)
12983 (message "Saving all Org-mode buffers...")
12984 (save-some-buffers t 'org-mode-p)
12985 (when (featurep 'org-id) (org-id-locations-save))
12986 (message "Saving all Org-mode buffers... done"))
12988 (defun org-revert-all-org-buffers ()
12989 "Revert all Org-mode buffers.
12990 Prompt for confirmation when there are unsaved changes.
12991 Be sure you know what you are doing before letting this function
12992 overwrite your changes.
12994 This function is useful in a setup where one tracks org files
12995 with a version control system, to revert on one machine after pulling
12996 changes from another. I believe the procedure must be like this:
12998 1. M-x org-save-all-org-buffers
12999 2. Pull changes from the other machine, resolve conflicts
13000 3. M-x org-revert-all-org-buffers"
13001 (interactive)
13002 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
13003 (error "Abort"))
13004 (save-excursion
13005 (save-window-excursion
13006 (mapc
13007 (lambda (b)
13008 (when (and (with-current-buffer b (org-mode-p))
13009 (with-current-buffer b buffer-file-name))
13010 (switch-to-buffer b)
13011 (revert-buffer t 'no-confirm)))
13012 (buffer-list))
13013 (when (and (featurep 'org-id) org-id-track-globally)
13014 (org-id-locations-load)))))
13016 ;;;; Agenda files
13018 ;;;###autoload
13019 (defun org-iswitchb (&optional arg)
13020 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
13021 With a prefix argument, restrict available to files.
13022 With two prefix arguments, restrict available buffers to agenda files.
13024 Due to some yet unresolved reason, the global function
13025 `iswitchb-mode' needs to be active for this function to work."
13026 (interactive "P")
13027 (require 'iswitchb)
13028 (let ((enabled iswitchb-mode) blist)
13029 (or enabled (iswitchb-mode 1))
13030 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
13031 ((equal arg '(16)) (org-buffer-list 'agenda))
13032 (t (org-buffer-list))))
13033 (unwind-protect
13034 (let ((iswitchb-make-buflist-hook
13035 (lambda ()
13036 (setq iswitchb-temp-buflist
13037 (mapcar 'buffer-name blist)))))
13038 (switch-to-buffer
13039 (iswitchb-read-buffer
13040 "Switch-to: " nil t))
13041 (or enabled (iswitchb-mode -1))))))
13043 ;;;###autoload
13044 (defun org-ido-switchb (&optional arg)
13045 "Use `org-ido-completing-read' to prompt for an Org buffer to switch to.
13046 With a prefix argument, restrict available to files.
13047 With two prefix arguments, restrict available buffers to agenda files."
13048 (interactive "P")
13049 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
13050 ((equal arg '(16)) (org-buffer-list 'agenda))
13051 (t (org-buffer-list)))))
13052 (switch-to-buffer
13053 (org-ido-completing-read "Org buffer: "
13054 (mapcar 'list (mapcar 'buffer-name blist))
13055 nil t))))
13057 (defun org-buffer-list (&optional predicate exclude-tmp)
13058 "Return a list of Org buffers.
13059 PREDICATE can be `export', `files' or `agenda'.
13061 export restrict the list to Export buffers.
13062 files restrict the list to buffers visiting Org files.
13063 agenda restrict the list to buffers visiting agenda files.
13065 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
13066 (let* ((bfn nil)
13067 (agenda-files (and (eq predicate 'agenda)
13068 (mapcar 'file-truename (org-agenda-files t))))
13069 (filter
13070 (cond
13071 ((eq predicate 'files)
13072 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
13073 ((eq predicate 'export)
13074 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
13075 ((eq predicate 'agenda)
13076 (lambda (b)
13077 (with-current-buffer b
13078 (and (eq major-mode 'org-mode)
13079 (setq bfn (buffer-file-name b))
13080 (member (file-truename bfn) agenda-files)))))
13081 (t (lambda (b) (with-current-buffer b
13082 (or (eq major-mode 'org-mode)
13083 (string-match "\*Org .*Export"
13084 (buffer-name b)))))))))
13085 (delq nil
13086 (mapcar
13087 (lambda(b)
13088 (if (and (funcall filter b)
13089 (or (not exclude-tmp)
13090 (not (string-match "tmp" (buffer-name b)))))
13092 nil))
13093 (buffer-list)))))
13095 (defun org-agenda-files (&optional unrestricted archives)
13096 "Get the list of agenda files.
13097 Optional UNRESTRICTED means return the full list even if a restriction
13098 is currently in place.
13099 When ARCHIVES is t, include all archive files hat are really being
13100 used by the agenda files. If ARCHIVE is `ifmode', do this only if
13101 `org-agenda-archives-mode' is t."
13102 (let ((files
13103 (cond
13104 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
13105 ((stringp org-agenda-files) (org-read-agenda-file-list))
13106 ((listp org-agenda-files) org-agenda-files)
13107 (t (error "Invalid value of `org-agenda-files'")))))
13108 (setq files (apply 'append
13109 (mapcar (lambda (f)
13110 (if (file-directory-p f)
13111 (directory-files
13112 f t org-agenda-file-regexp)
13113 (list f)))
13114 files)))
13115 (when org-agenda-skip-unavailable-files
13116 (setq files (delq nil
13117 (mapcar (function
13118 (lambda (file)
13119 (and (file-readable-p file) file)))
13120 files))))
13121 (when (or (eq archives t)
13122 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
13123 (setq files (org-add-archive-files files)))
13124 files))
13126 (defun org-edit-agenda-file-list ()
13127 "Edit the list of agenda files.
13128 Depending on setup, this either uses customize to edit the variable
13129 `org-agenda-files', or it visits the file that is holding the list. In the
13130 latter case, the buffer is set up in a way that saving it automatically kills
13131 the buffer and restores the previous window configuration."
13132 (interactive)
13133 (if (stringp org-agenda-files)
13134 (let ((cw (current-window-configuration)))
13135 (find-file org-agenda-files)
13136 (org-set-local 'org-window-configuration cw)
13137 (org-add-hook 'after-save-hook
13138 (lambda ()
13139 (set-window-configuration
13140 (prog1 org-window-configuration
13141 (kill-buffer (current-buffer))))
13142 (org-install-agenda-files-menu)
13143 (message "New agenda file list installed"))
13144 nil 'local)
13145 (message "%s" (substitute-command-keys
13146 "Edit list and finish with \\[save-buffer]")))
13147 (customize-variable 'org-agenda-files)))
13149 (defun org-store-new-agenda-file-list (list)
13150 "Set new value for the agenda file list and save it correctly."
13151 (if (stringp org-agenda-files)
13152 (let ((f org-agenda-files) b)
13153 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
13154 (with-temp-file f
13155 (insert (mapconcat 'identity list "\n") "\n")))
13156 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
13157 (setq org-agenda-files list)
13158 (customize-save-variable 'org-agenda-files org-agenda-files))))
13160 (defun org-read-agenda-file-list ()
13161 "Read the list of agenda files from a file."
13162 (when (file-directory-p org-agenda-files)
13163 (error "`org-agenda-files' cannot be a single directory"))
13164 (when (stringp org-agenda-files)
13165 (with-temp-buffer
13166 (insert-file-contents org-agenda-files)
13167 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
13170 ;;;###autoload
13171 (defun org-cycle-agenda-files ()
13172 "Cycle through the files in `org-agenda-files'.
13173 If the current buffer visits an agenda file, find the next one in the list.
13174 If the current buffer does not, find the first agenda file."
13175 (interactive)
13176 (let* ((fs (org-agenda-files t))
13177 (files (append fs (list (car fs))))
13178 (tcf (if buffer-file-name (file-truename buffer-file-name)))
13179 file)
13180 (unless files (error "No agenda files"))
13181 (catch 'exit
13182 (while (setq file (pop files))
13183 (if (equal (file-truename file) tcf)
13184 (when (car files)
13185 (find-file (car files))
13186 (throw 'exit t))))
13187 (find-file (car fs)))
13188 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
13190 (defun org-agenda-file-to-front (&optional to-end)
13191 "Move/add the current file to the top of the agenda file list.
13192 If the file is not present in the list, it is added to the front. If it is
13193 present, it is moved there. With optional argument TO-END, add/move to the
13194 end of the list."
13195 (interactive "P")
13196 (let ((org-agenda-skip-unavailable-files nil)
13197 (file-alist (mapcar (lambda (x)
13198 (cons (file-truename x) x))
13199 (org-agenda-files t)))
13200 (ctf (file-truename buffer-file-name))
13201 x had)
13202 (setq x (assoc ctf file-alist) had x)
13204 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
13205 (if to-end
13206 (setq file-alist (append (delq x file-alist) (list x)))
13207 (setq file-alist (cons x (delq x file-alist))))
13208 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
13209 (org-install-agenda-files-menu)
13210 (message "File %s to %s of agenda file list"
13211 (if had "moved" "added") (if to-end "end" "front"))))
13213 (defun org-remove-file (&optional file)
13214 "Remove current file from the list of files in variable `org-agenda-files'.
13215 These are the files which are being checked for agenda entries.
13216 Optional argument FILE means, use this file instead of the current."
13217 (interactive)
13218 (let* ((org-agenda-skip-unavailable-files nil)
13219 (file (or file buffer-file-name))
13220 (true-file (file-truename file))
13221 (afile (abbreviate-file-name file))
13222 (files (delq nil (mapcar
13223 (lambda (x)
13224 (if (equal true-file
13225 (file-truename x))
13226 nil x))
13227 (org-agenda-files t)))))
13228 (if (not (= (length files) (length (org-agenda-files t))))
13229 (progn
13230 (org-store-new-agenda-file-list files)
13231 (org-install-agenda-files-menu)
13232 (message "Removed file: %s" afile))
13233 (message "File was not in list: %s (not removed)" afile))))
13235 (defun org-file-menu-entry (file)
13236 (vector file (list 'find-file file) t))
13238 (defun org-check-agenda-file (file)
13239 "Make sure FILE exists. If not, ask user what to do."
13240 (when (not (file-exists-p file))
13241 (message "non-existent file %s. [R]emove from list or [A]bort?"
13242 (abbreviate-file-name file))
13243 (let ((r (downcase (read-char-exclusive))))
13244 (cond
13245 ((equal r ?r)
13246 (org-remove-file file)
13247 (throw 'nextfile t))
13248 (t (error "Abort"))))))
13250 (defun org-get-agenda-file-buffer (file)
13251 "Get a buffer visiting FILE. If the buffer needs to be created, add
13252 it to the list of buffers which might be released later."
13253 (let ((buf (org-find-base-buffer-visiting file)))
13254 (if buf
13255 buf ; just return it
13256 ;; Make a new buffer and remember it
13257 (setq buf (find-file-noselect file))
13258 (if buf (push buf org-agenda-new-buffers))
13259 buf)))
13261 (defun org-release-buffers (blist)
13262 "Release all buffers in list, asking the user for confirmation when needed.
13263 When a buffer is unmodified, it is just killed. When modified, it is saved
13264 \(if the user agrees) and then killed."
13265 (let (buf file)
13266 (while (setq buf (pop blist))
13267 (setq file (buffer-file-name buf))
13268 (when (and (buffer-modified-p buf)
13269 file
13270 (y-or-n-p (format "Save file %s? " file)))
13271 (with-current-buffer buf (save-buffer)))
13272 (kill-buffer buf))))
13274 (defun org-prepare-agenda-buffers (files)
13275 "Create buffers for all agenda files, protect archived trees and comments."
13276 (interactive)
13277 (let ((pa '(:org-archived t))
13278 (pc '(:org-comment t))
13279 (pall '(:org-archived t :org-comment t))
13280 (inhibit-read-only t)
13281 (rea (concat ":" org-archive-tag ":"))
13282 bmp file re)
13283 (save-excursion
13284 (save-restriction
13285 (while (setq file (pop files))
13286 (if (bufferp file)
13287 (set-buffer file)
13288 (org-check-agenda-file file)
13289 (set-buffer (org-get-agenda-file-buffer file)))
13290 (widen)
13291 (setq bmp (buffer-modified-p))
13292 (org-refresh-category-properties)
13293 (setq org-todo-keywords-for-agenda
13294 (append org-todo-keywords-for-agenda org-todo-keywords-1))
13295 (setq org-done-keywords-for-agenda
13296 (append org-done-keywords-for-agenda org-done-keywords))
13297 (setq org-todo-keyword-alist-for-agenda
13298 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
13299 (setq org-tag-alist-for-agenda
13300 (append org-tag-alist-for-agenda org-tag-alist))
13302 (save-excursion
13303 (remove-text-properties (point-min) (point-max) pall)
13304 (when org-agenda-skip-archived-trees
13305 (goto-char (point-min))
13306 (while (re-search-forward rea nil t)
13307 (if (org-on-heading-p t)
13308 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
13309 (goto-char (point-min))
13310 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
13311 (while (re-search-forward re nil t)
13312 (add-text-properties
13313 (match-beginning 0) (org-end-of-subtree t) pc)))
13314 (set-buffer-modified-p bmp))))
13315 (setq org-todo-keyword-alist-for-agenda
13316 (org-uniquify org-todo-keyword-alist-for-agenda)
13317 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
13319 ;;;; Embedded LaTeX
13321 (defvar org-cdlatex-mode-map (make-sparse-keymap)
13322 "Keymap for the minor `org-cdlatex-mode'.")
13324 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
13325 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
13326 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
13327 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
13328 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
13330 (defvar org-cdlatex-texmathp-advice-is-done nil
13331 "Flag remembering if we have applied the advice to texmathp already.")
13333 (define-minor-mode org-cdlatex-mode
13334 "Toggle the minor `org-cdlatex-mode'.
13335 This mode supports entering LaTeX environment and math in LaTeX fragments
13336 in Org-mode.
13337 \\{org-cdlatex-mode-map}"
13338 nil " OCDL" nil
13339 (when org-cdlatex-mode (require 'cdlatex))
13340 (unless org-cdlatex-texmathp-advice-is-done
13341 (setq org-cdlatex-texmathp-advice-is-done t)
13342 (defadvice texmathp (around org-math-always-on activate)
13343 "Always return t in org-mode buffers.
13344 This is because we want to insert math symbols without dollars even outside
13345 the LaTeX math segments. If Orgmode thinks that point is actually inside
13346 an embedded LaTeX fragment, let texmathp do its job.
13347 \\[org-cdlatex-mode-map]"
13348 (interactive)
13349 (let (p)
13350 (cond
13351 ((not (org-mode-p)) ad-do-it)
13352 ((eq this-command 'cdlatex-math-symbol)
13353 (setq ad-return-value t
13354 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
13356 (let ((p (org-inside-LaTeX-fragment-p)))
13357 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
13358 (setq ad-return-value t
13359 texmathp-why '("Org-mode embedded math" . 0))
13360 (if p ad-do-it)))))))))
13362 (defun turn-on-org-cdlatex ()
13363 "Unconditionally turn on `org-cdlatex-mode'."
13364 (org-cdlatex-mode 1))
13366 (defun org-inside-LaTeX-fragment-p ()
13367 "Test if point is inside a LaTeX fragment.
13368 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
13369 sequence appearing also before point.
13370 Even though the matchers for math are configurable, this function assumes
13371 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
13372 delimiters are skipped when they have been removed by customization.
13373 The return value is nil, or a cons cell with the delimiter and
13374 and the position of this delimiter.
13376 This function does a reasonably good job, but can locally be fooled by
13377 for example currency specifications. For example it will assume being in
13378 inline math after \"$22.34\". The LaTeX fragment formatter will only format
13379 fragments that are properly closed, but during editing, we have to live
13380 with the uncertainty caused by missing closing delimiters. This function
13381 looks only before point, not after."
13382 (catch 'exit
13383 (let ((pos (point))
13384 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
13385 (lim (progn
13386 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
13387 (point)))
13388 dd-on str (start 0) m re)
13389 (goto-char pos)
13390 (when dodollar
13391 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
13392 re (nth 1 (assoc "$" org-latex-regexps)))
13393 (while (string-match re str start)
13394 (cond
13395 ((= (match-end 0) (length str))
13396 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
13397 ((= (match-end 0) (- (length str) 5))
13398 (throw 'exit nil))
13399 (t (setq start (match-end 0))))))
13400 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
13401 (goto-char pos)
13402 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
13403 (and (match-beginning 2) (throw 'exit nil))
13404 ;; count $$
13405 (while (re-search-backward "\\$\\$" lim t)
13406 (setq dd-on (not dd-on)))
13407 (goto-char pos)
13408 (if dd-on (cons "$$" m))))))
13411 (defun org-try-cdlatex-tab ()
13412 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
13413 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
13414 - inside a LaTeX fragment, or
13415 - after the first word in a line, where an abbreviation expansion could
13416 insert a LaTeX environment."
13417 (when org-cdlatex-mode
13418 (cond
13419 ((save-excursion
13420 (skip-chars-backward "a-zA-Z0-9*")
13421 (skip-chars-backward " \t")
13422 (bolp))
13423 (cdlatex-tab) t)
13424 ((org-inside-LaTeX-fragment-p)
13425 (cdlatex-tab) t)
13426 (t nil))))
13428 (defun org-cdlatex-underscore-caret (&optional arg)
13429 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
13430 Revert to the normal definition outside of these fragments."
13431 (interactive "P")
13432 (if (org-inside-LaTeX-fragment-p)
13433 (call-interactively 'cdlatex-sub-superscript)
13434 (let (org-cdlatex-mode)
13435 (call-interactively (key-binding (vector last-input-event))))))
13437 (defun org-cdlatex-math-modify (&optional arg)
13438 "Execute `cdlatex-math-modify' in LaTeX fragments.
13439 Revert to the normal definition outside of these fragments."
13440 (interactive "P")
13441 (if (org-inside-LaTeX-fragment-p)
13442 (call-interactively 'cdlatex-math-modify)
13443 (let (org-cdlatex-mode)
13444 (call-interactively (key-binding (vector last-input-event))))))
13446 (defvar org-latex-fragment-image-overlays nil
13447 "List of overlays carrying the images of latex fragments.")
13448 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
13450 (defun org-remove-latex-fragment-image-overlays ()
13451 "Remove all overlays with LaTeX fragment images in current buffer."
13452 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
13453 (setq org-latex-fragment-image-overlays nil))
13455 (defun org-preview-latex-fragment (&optional subtree)
13456 "Preview the LaTeX fragment at point, or all locally or globally.
13457 If the cursor is in a LaTeX fragment, create the image and overlay
13458 it over the source code. If there is no fragment at point, display
13459 all fragments in the current text, from one headline to the next. With
13460 prefix SUBTREE, display all fragments in the current subtree. With a
13461 double prefix `C-u C-u', or when the cursor is before the first headline,
13462 display all fragments in the buffer.
13463 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
13464 (interactive "P")
13465 (org-remove-latex-fragment-image-overlays)
13466 (save-excursion
13467 (save-restriction
13468 (let (beg end at msg)
13469 (cond
13470 ((or (equal subtree '(16))
13471 (not (save-excursion
13472 (re-search-backward (concat "^" outline-regexp) nil t))))
13473 (setq beg (point-min) end (point-max)
13474 msg "Creating images for buffer...%s"))
13475 ((equal subtree '(4))
13476 (org-back-to-heading)
13477 (setq beg (point) end (org-end-of-subtree t)
13478 msg "Creating images for subtree...%s"))
13480 (if (setq at (org-inside-LaTeX-fragment-p))
13481 (goto-char (max (point-min) (- (cdr at) 2)))
13482 (org-back-to-heading))
13483 (setq beg (point) end (progn (outline-next-heading) (point))
13484 msg (if at "Creating image...%s"
13485 "Creating images for entry...%s"))))
13486 (message msg "")
13487 (narrow-to-region beg end)
13488 (goto-char beg)
13489 (org-format-latex
13490 (concat "ltxpng/" (file-name-sans-extension
13491 (file-name-nondirectory
13492 buffer-file-name)))
13493 default-directory 'overlays msg at 'forbuffer)
13494 (message msg "done. Use `C-c C-c' to remove images.")))))
13496 (defvar org-latex-regexps
13497 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
13498 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
13499 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
13500 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
13501 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
13502 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
13503 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
13504 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
13505 "Regular expressions for matching embedded LaTeX.")
13507 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
13508 "Replace LaTeX fragments with links to an image, and produce images."
13509 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
13510 (let* ((prefixnodir (file-name-nondirectory prefix))
13511 (absprefix (expand-file-name prefix dir))
13512 (todir (file-name-directory absprefix))
13513 (opt org-format-latex-options)
13514 (matchers (plist-get opt :matchers))
13515 (re-list org-latex-regexps)
13516 (cnt 0) txt link beg end re e checkdir
13517 m n block linkfile movefile ov)
13518 ;; Check if there are old images files with this prefix, and remove them
13519 (when (file-directory-p todir)
13520 (mapc 'delete-file
13521 (directory-files
13522 todir 'full
13523 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
13524 ;; Check the different regular expressions
13525 (while (setq e (pop re-list))
13526 (setq m (car e) re (nth 1 e) n (nth 2 e)
13527 block (if (nth 3 e) "\n\n" ""))
13528 (when (member m matchers)
13529 (goto-char (point-min))
13530 (while (re-search-forward re nil t)
13531 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
13532 (not (get-text-property (match-beginning n)
13533 'org-protected)))
13534 (setq txt (match-string n)
13535 beg (match-beginning n) end (match-end n)
13536 cnt (1+ cnt)
13537 linkfile (format "%s_%04d.png" prefix cnt)
13538 movefile (format "%s_%04d.png" absprefix cnt)
13539 link (concat block "[[file:" linkfile "]]" block))
13540 (if msg (message msg cnt))
13541 (goto-char beg)
13542 (unless checkdir ; make sure the directory exists
13543 (setq checkdir t)
13544 (or (file-directory-p todir) (make-directory todir)))
13545 (org-create-formula-image
13546 txt movefile opt forbuffer)
13547 (if overlays
13548 (progn
13549 (setq ov (org-make-overlay beg end))
13550 (if (featurep 'xemacs)
13551 (progn
13552 (org-overlay-put ov 'invisible t)
13553 (org-overlay-put
13554 ov 'end-glyph
13555 (make-glyph (vector 'png :file movefile))))
13556 (org-overlay-put
13557 ov 'display
13558 (list 'image :type 'png :file movefile :ascent 'center)))
13559 (push ov org-latex-fragment-image-overlays)
13560 (goto-char end))
13561 (delete-region beg end)
13562 (insert link))))))))
13564 ;; This function borrows from Ganesh Swami's latex2png.el
13565 (defun org-create-formula-image (string tofile options buffer)
13566 (let* ((tmpdir (if (featurep 'xemacs)
13567 (temp-directory)
13568 temporary-file-directory))
13569 (texfilebase (make-temp-name
13570 (expand-file-name "orgtex" tmpdir)))
13571 (texfile (concat texfilebase ".tex"))
13572 (dvifile (concat texfilebase ".dvi"))
13573 (pngfile (concat texfilebase ".png"))
13574 (fnh (if (featurep 'xemacs)
13575 (font-height (get-face-font 'default))
13576 (face-attribute 'default :height nil)))
13577 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
13578 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
13579 (fg (or (plist-get options (if buffer :foreground :html-foreground))
13580 "Black"))
13581 (bg (or (plist-get options (if buffer :background :html-background))
13582 "Transparent")))
13583 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
13584 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
13585 (with-temp-file texfile
13586 (insert org-format-latex-header
13587 "\n\\begin{document}\n" string "\n\\end{document}\n"))
13588 (let ((dir default-directory))
13589 (condition-case nil
13590 (progn
13591 (cd tmpdir)
13592 (call-process "latex" nil nil nil texfile))
13593 (error nil))
13594 (cd dir))
13595 (if (not (file-exists-p dvifile))
13596 (progn (message "Failed to create dvi file from %s" texfile) nil)
13597 (condition-case nil
13598 (call-process "dvipng" nil nil nil
13599 "-E" "-fg" fg "-bg" bg
13600 "-D" dpi
13601 ;;"-x" scale "-y" scale
13602 "-T" "tight"
13603 "-o" pngfile
13604 dvifile)
13605 (error nil))
13606 (if (not (file-exists-p pngfile))
13607 (progn (message "Failed to create png file from %s" texfile) nil)
13608 ;; Use the requested file name and clean up
13609 (copy-file pngfile tofile 'replace)
13610 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
13611 (delete-file (concat texfilebase e)))
13612 pngfile))))
13614 (defun org-dvipng-color (attr)
13615 "Return an rgb color specification for dvipng."
13616 (apply 'format "rgb %s %s %s"
13617 (mapcar 'org-normalize-color
13618 (color-values (face-attribute 'default attr nil)))))
13620 (defun org-normalize-color (value)
13621 "Return string to be used as color value for an RGB component."
13622 (format "%g" (/ value 65535.0)))
13624 ;;;; Key bindings
13626 ;; Make `C-c C-x' a prefix key
13627 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
13629 ;; TAB key with modifiers
13630 (org-defkey org-mode-map "\C-i" 'org-cycle)
13631 (org-defkey org-mode-map [(tab)] 'org-cycle)
13632 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
13633 (org-defkey org-mode-map [(meta tab)] 'org-complete)
13634 (org-defkey org-mode-map "\M-\t" 'org-complete)
13635 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
13636 ;; The following line is necessary under Suse GNU/Linux
13637 (unless (featurep 'xemacs)
13638 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
13639 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
13640 (define-key org-mode-map [backtab] 'org-shifttab)
13642 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
13643 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
13644 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
13646 ;; Cursor keys with modifiers
13647 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
13648 (org-defkey org-mode-map [(meta right)] 'org-metaright)
13649 (org-defkey org-mode-map [(meta up)] 'org-metaup)
13650 (org-defkey org-mode-map [(meta down)] 'org-metadown)
13652 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
13653 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
13654 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
13655 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
13657 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
13658 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
13659 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
13660 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
13662 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
13663 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
13665 ;;; Extra keys for tty access.
13666 ;; We only set them when really needed because otherwise the
13667 ;; menus don't show the simple keys
13669 (when (or org-use-extra-keys
13670 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
13671 (not window-system))
13672 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
13673 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
13674 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
13675 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
13676 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
13677 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
13678 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
13679 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
13680 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
13681 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
13682 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
13683 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
13684 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
13685 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
13686 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
13687 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
13688 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
13689 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
13690 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
13691 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
13692 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
13693 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
13695 ;; All the other keys
13697 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
13698 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
13699 (if (boundp 'narrow-map)
13700 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
13701 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
13702 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
13703 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
13704 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
13705 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
13706 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
13707 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
13708 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
13709 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
13710 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
13711 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
13712 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
13713 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
13714 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
13715 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
13716 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
13717 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
13718 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
13719 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
13720 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
13721 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
13722 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
13723 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
13724 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
13725 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
13726 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
13727 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
13728 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
13729 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
13730 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
13731 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
13732 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
13733 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
13734 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
13735 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
13736 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
13737 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
13738 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
13739 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
13740 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
13741 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
13742 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
13743 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
13744 (org-defkey org-mode-map "\C-c^" 'org-sort)
13745 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
13746 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
13747 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
13748 (org-defkey org-mode-map "\C-m" 'org-return)
13749 (org-defkey org-mode-map "\C-j" 'org-return-indent)
13750 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
13751 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
13752 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
13753 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
13754 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
13755 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
13756 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
13757 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
13758 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
13759 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
13760 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
13761 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
13762 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
13763 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
13764 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
13765 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
13767 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
13768 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
13769 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
13770 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
13772 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
13773 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
13774 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
13775 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
13776 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
13777 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
13778 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
13779 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
13780 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
13781 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
13782 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
13783 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
13784 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
13786 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
13787 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
13788 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
13789 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
13791 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
13793 (define-key org-mode-map "\C-c\C-xr" 'org-reload)
13795 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
13796 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
13798 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
13801 (when (featurep 'xemacs)
13802 (org-defkey org-mode-map 'button3 'popup-mode-menu))
13805 (defvar org-self-insert-command-undo-counter 0)
13807 (defvar org-table-auto-blank-field) ; defined in org-table.el
13808 (defun org-self-insert-command (N)
13809 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
13810 If the cursor is in a table looking at whitespace, the whitespace is
13811 overwritten, and the table is not marked as requiring realignment."
13812 (interactive "p")
13813 (if (and
13814 (org-table-p)
13815 (progn
13816 ;; check if we blank the field, and if that triggers align
13817 (and (featurep 'org-table) org-table-auto-blank-field
13818 (member last-command
13819 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
13820 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
13821 ;; got extra space, this field does not determine column width
13822 (let (org-table-may-need-update) (org-table-blank-field))
13823 ;; no extra space, this field may determine column width
13824 (org-table-blank-field)))
13826 (eq N 1)
13827 (looking-at "[^|\n]* |"))
13828 (let (org-table-may-need-update)
13829 (goto-char (1- (match-end 0)))
13830 (delete-backward-char 1)
13831 (goto-char (match-beginning 0))
13832 (self-insert-command N))
13833 (setq org-table-may-need-update t)
13834 (self-insert-command N)
13835 (org-fix-tags-on-the-fly)
13836 (if org-self-insert-cluster-for-undo
13837 (if (not (eq last-command 'org-self-insert-command))
13838 (setq org-self-insert-command-undo-counter 1)
13839 (if (>= org-self-insert-command-undo-counter 20)
13840 (setq org-self-insert-command-undo-counter 1)
13841 (and (> org-self-insert-command-undo-counter 0)
13842 buffer-undo-list
13843 (not (cadr buffer-undo-list)) ; remove nil entry
13844 (setcdr buffer-undo-list (cddr buffer-undo-list)))
13845 (setq org-self-insert-command-undo-counter
13846 (1+ org-self-insert-command-undo-counter)))))))
13848 (defun org-fix-tags-on-the-fly ()
13849 (when (and (equal (char-after (point-at-bol)) ?*)
13850 (org-on-heading-p))
13851 (org-align-tags-here org-tags-column)))
13853 (defun org-delete-backward-char (N)
13854 "Like `delete-backward-char', insert whitespace at field end in tables.
13855 When deleting backwards, in tables this function will insert whitespace in
13856 front of the next \"|\" separator, to keep the table aligned. The table will
13857 still be marked for re-alignment if the field did fill the entire column,
13858 because, in this case the deletion might narrow the column."
13859 (interactive "p")
13860 (if (and (org-table-p)
13861 (eq N 1)
13862 (string-match "|" (buffer-substring (point-at-bol) (point)))
13863 (looking-at ".*?|"))
13864 (let ((pos (point))
13865 (noalign (looking-at "[^|\n\r]* |"))
13866 (c org-table-may-need-update))
13867 (backward-delete-char N)
13868 (skip-chars-forward "^|")
13869 (insert " ")
13870 (goto-char (1- pos))
13871 ;; noalign: if there were two spaces at the end, this field
13872 ;; does not determine the width of the column.
13873 (if noalign (setq org-table-may-need-update c)))
13874 (backward-delete-char N)
13875 (org-fix-tags-on-the-fly)))
13877 (defun org-delete-char (N)
13878 "Like `delete-char', but insert whitespace at field end in tables.
13879 When deleting characters, in tables this function will insert whitespace in
13880 front of the next \"|\" separator, to keep the table aligned. The table will
13881 still be marked for re-alignment if the field did fill the entire column,
13882 because, in this case the deletion might narrow the column."
13883 (interactive "p")
13884 (if (and (org-table-p)
13885 (not (bolp))
13886 (not (= (char-after) ?|))
13887 (eq N 1))
13888 (if (looking-at ".*?|")
13889 (let ((pos (point))
13890 (noalign (looking-at "[^|\n\r]* |"))
13891 (c org-table-may-need-update))
13892 (replace-match (concat
13893 (substring (match-string 0) 1 -1)
13894 " |"))
13895 (goto-char pos)
13896 ;; noalign: if there were two spaces at the end, this field
13897 ;; does not determine the width of the column.
13898 (if noalign (setq org-table-may-need-update c)))
13899 (delete-char N))
13900 (delete-char N)
13901 (org-fix-tags-on-the-fly)))
13903 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
13904 (put 'org-self-insert-command 'delete-selection t)
13905 (put 'orgtbl-self-insert-command 'delete-selection t)
13906 (put 'org-delete-char 'delete-selection 'supersede)
13907 (put 'org-delete-backward-char 'delete-selection 'supersede)
13908 (put 'org-yank 'delete-selection 'yank)
13910 ;; Make `flyspell-mode' delay after some commands
13911 (put 'org-self-insert-command 'flyspell-delayed t)
13912 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
13913 (put 'org-delete-char 'flyspell-delayed t)
13914 (put 'org-delete-backward-char 'flyspell-delayed t)
13916 ;; Make pabbrev-mode expand after org-mode commands
13917 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
13918 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
13920 ;; How to do this: Measure non-white length of current string
13921 ;; If equal to column width, we should realign.
13923 (defun org-remap (map &rest commands)
13924 "In MAP, remap the functions given in COMMANDS.
13925 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
13926 (let (new old)
13927 (while commands
13928 (setq old (pop commands) new (pop commands))
13929 (if (fboundp 'command-remapping)
13930 (org-defkey map (vector 'remap old) new)
13931 (substitute-key-definition old new map global-map)))))
13933 (when (eq org-enable-table-editor 'optimized)
13934 ;; If the user wants maximum table support, we need to hijack
13935 ;; some standard editing functions
13936 (org-remap org-mode-map
13937 'self-insert-command 'org-self-insert-command
13938 'delete-char 'org-delete-char
13939 'delete-backward-char 'org-delete-backward-char)
13940 (org-defkey org-mode-map "|" 'org-force-self-insert))
13942 (defvar org-ctrl-c-ctrl-c-hook nil
13943 "Hook for functions attaching themselves to `C-c C-c'.
13944 This can be used to add additional functionality to the C-c C-c key which
13945 executes context-dependent commands.
13946 Each function will be called with no arguments. The function must check
13947 if the context is appropriate for it to act. If yes, it should do its
13948 thing and then return a non-nil value. If the context is wrong,
13949 just do nothing and return nil.")
13951 (defvar org-tab-first-hook nil
13952 "Hook for functions to attach themselves to TAB.
13953 See `org-ctrl-c-ctrl-c-hook' for more information.
13954 This hook runs as the first action when TAB is pressed, even before
13955 `org-cycle' messes around with the `outline-regexp' to cater for
13956 inline tasks and plain list item folding.
13957 If any function in this hook returns t, not other actions like table
13958 field motion visibility cycling will be done.")
13960 (defvar org-tab-after-check-for-table-hook nil
13961 "Hook for functions to attach themselves to TAB.
13962 See `org-ctrl-c-ctrl-c-hook' for more information.
13963 This hook runs after it has been established that the cursor is not in a
13964 table, but before checking if the cursor is in a headline or if global cycling
13965 should be done.
13966 If any function in this hook returns t, not other actions like visibility
13967 cycling will be done.")
13969 (defvar org-tab-after-check-for-cycling-hook nil
13970 "Hook for functions to attach themselves to TAB.
13971 See `org-ctrl-c-ctrl-c-hook' for more information.
13972 This hook runs after it has been established that not table field motion and
13973 not visibility should be done because of current context. This is probably
13974 the place where a package like yasnippets can hook in.")
13976 (defvar org-metaleft-hook nil
13977 "Hook for functions attaching themselves to `M-left'.
13978 See `org-ctrl-c-ctrl-c-hook' for more information.")
13979 (defvar org-metaright-hook nil
13980 "Hook for functions attaching themselves to `M-right'.
13981 See `org-ctrl-c-ctrl-c-hook' for more information.")
13982 (defvar org-metaup-hook nil
13983 "Hook for functions attaching themselves to `M-up'.
13984 See `org-ctrl-c-ctrl-c-hook' for more information.")
13985 (defvar org-metadown-hook nil
13986 "Hook for functions attaching themselves to `M-down'.
13987 See `org-ctrl-c-ctrl-c-hook' for more information.")
13988 (defvar org-shiftmetaleft-hook nil
13989 "Hook for functions attaching themselves to `M-S-left'.
13990 See `org-ctrl-c-ctrl-c-hook' for more information.")
13991 (defvar org-shiftmetaright-hook nil
13992 "Hook for functions attaching themselves to `M-S-right'.
13993 See `org-ctrl-c-ctrl-c-hook' for more information.")
13994 (defvar org-shiftmetaup-hook nil
13995 "Hook for functions attaching themselves to `M-S-up'.
13996 See `org-ctrl-c-ctrl-c-hook' for more information.")
13997 (defvar org-shiftmetadown-hook nil
13998 "Hook for functions attaching themselves to `M-S-down'.
13999 See `org-ctrl-c-ctrl-c-hook' for more information.")
14000 (defvar org-metareturn-hook nil
14001 "Hook for functions attaching themselves to `M-RET'.
14002 See `org-ctrl-c-ctrl-c-hook' for more information.")
14004 (defun org-modifier-cursor-error ()
14005 "Throw an error, a modified cursor command was applied in wrong context."
14006 (error "This command is active in special context like tables, headlines or items"))
14008 (defun org-shiftselect-error ()
14009 "Throw an error because Shift-Cursor command was applied in wrong context."
14010 (if (and (boundp 'shift-select-mode) shift-select-mode)
14011 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'.")
14012 (error "This command works only in special context like headlines or timestamps.")))
14014 (defun org-call-for-shift-select (cmd)
14015 (let ((this-command-keys-shift-translated t))
14016 (call-interactively cmd)))
14018 (defun org-shifttab (&optional arg)
14019 "Global visibility cycling or move to previous table field.
14020 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
14021 on context.
14022 See the individual commands for more information."
14023 (interactive "P")
14024 (cond
14025 ((org-at-table-p) (call-interactively 'org-table-previous-field))
14026 ((integerp arg)
14027 (message "Content view to level: %d" arg)
14028 (org-content (prefix-numeric-value arg))
14029 (setq org-cycle-global-status 'overview))
14030 (t (call-interactively 'org-global-cycle))))
14032 (defun org-shiftmetaleft ()
14033 "Promote subtree or delete table column.
14034 Calls `org-promote-subtree', `org-outdent-item',
14035 or `org-table-delete-column', depending on context.
14036 See the individual commands for more information."
14037 (interactive)
14038 (cond
14039 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
14040 ((org-at-table-p) (call-interactively 'org-table-delete-column))
14041 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
14042 ((org-at-item-p) (call-interactively 'org-outdent-item))
14043 (t (org-modifier-cursor-error))))
14045 (defun org-shiftmetaright ()
14046 "Demote subtree or insert table column.
14047 Calls `org-demote-subtree', `org-indent-item',
14048 or `org-table-insert-column', depending on context.
14049 See the individual commands for more information."
14050 (interactive)
14051 (cond
14052 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
14053 ((org-at-table-p) (call-interactively 'org-table-insert-column))
14054 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
14055 ((org-at-item-p) (call-interactively 'org-indent-item))
14056 (t (org-modifier-cursor-error))))
14058 (defun org-shiftmetaup (&optional arg)
14059 "Move subtree up or kill table row.
14060 Calls `org-move-subtree-up' or `org-table-kill-row' or
14061 `org-move-item-up' depending on context. See the individual commands
14062 for more information."
14063 (interactive "P")
14064 (cond
14065 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
14066 ((org-at-table-p) (call-interactively 'org-table-kill-row))
14067 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
14068 ((org-at-item-p) (call-interactively 'org-move-item-up))
14069 (t (org-modifier-cursor-error))))
14071 (defun org-shiftmetadown (&optional arg)
14072 "Move subtree down or insert table row.
14073 Calls `org-move-subtree-down' or `org-table-insert-row' or
14074 `org-move-item-down', depending on context. See the individual
14075 commands for more information."
14076 (interactive "P")
14077 (cond
14078 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
14079 ((org-at-table-p) (call-interactively 'org-table-insert-row))
14080 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
14081 ((org-at-item-p) (call-interactively 'org-move-item-down))
14082 (t (org-modifier-cursor-error))))
14084 (defun org-metaleft (&optional arg)
14085 "Promote heading or move table column to left.
14086 Calls `org-do-promote' or `org-table-move-column', depending on context.
14087 With no specific context, calls the Emacs default `backward-word'.
14088 See the individual commands for more information."
14089 (interactive "P")
14090 (cond
14091 ((run-hook-with-args-until-success 'org-metaleft-hook))
14092 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
14093 ((or (org-on-heading-p)
14094 (and (org-region-active-p)
14095 (save-excursion
14096 (goto-char (region-beginning))
14097 (org-on-heading-p))))
14098 (call-interactively 'org-do-promote))
14099 ((or (org-at-item-p)
14100 (and (org-region-active-p)
14101 (save-excursion
14102 (goto-char (region-beginning))
14103 (org-at-item-p))))
14104 (call-interactively 'org-outdent-item))
14105 (t (call-interactively 'backward-word))))
14107 (defun org-metaright (&optional arg)
14108 "Demote subtree or move table column to right.
14109 Calls `org-do-demote' or `org-table-move-column', depending on context.
14110 With no specific context, calls the Emacs default `forward-word'.
14111 See the individual commands for more information."
14112 (interactive "P")
14113 (cond
14114 ((run-hook-with-args-until-success 'org-metaright-hook))
14115 ((org-at-table-p) (call-interactively 'org-table-move-column))
14116 ((or (org-on-heading-p)
14117 (and (org-region-active-p)
14118 (save-excursion
14119 (goto-char (region-beginning))
14120 (org-on-heading-p))))
14121 (call-interactively 'org-do-demote))
14122 ((or (org-at-item-p)
14123 (and (org-region-active-p)
14124 (save-excursion
14125 (goto-char (region-beginning))
14126 (org-at-item-p))))
14127 (call-interactively 'org-indent-item))
14128 (t (call-interactively 'forward-word))))
14130 (defun org-metaup (&optional arg)
14131 "Move subtree up or move table row up.
14132 Calls `org-move-subtree-up' or `org-table-move-row' or
14133 `org-move-item-up', depending on context. See the individual commands
14134 for more information."
14135 (interactive "P")
14136 (cond
14137 ((run-hook-with-args-until-success 'org-metaup-hook))
14138 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
14139 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
14140 ((org-at-item-p) (call-interactively 'org-move-item-up))
14141 (t (transpose-lines 1) (beginning-of-line -1))))
14143 (defun org-metadown (&optional arg)
14144 "Move subtree down or move table row down.
14145 Calls `org-move-subtree-down' or `org-table-move-row' or
14146 `org-move-item-down', depending on context. See the individual
14147 commands for more information."
14148 (interactive "P")
14149 (cond
14150 ((run-hook-with-args-until-success 'org-metadown-hook))
14151 ((org-at-table-p) (call-interactively 'org-table-move-row))
14152 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
14153 ((org-at-item-p) (call-interactively 'org-move-item-down))
14154 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
14156 (defun org-shiftup (&optional arg)
14157 "Increase item in timestamp or increase priority of current headline.
14158 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
14159 depending on context. See the individual commands for more information."
14160 (interactive "P")
14161 (cond
14162 ((and org-support-shift-select (org-region-active-p))
14163 (org-call-for-shift-select 'previous-line))
14164 ((org-at-timestamp-p t)
14165 (call-interactively (if org-edit-timestamp-down-means-later
14166 'org-timestamp-down 'org-timestamp-up)))
14167 ((and (not (eq org-support-shift-select 'always))
14168 (org-on-heading-p))
14169 (call-interactively 'org-priority-up))
14170 ((and (not org-support-shift-select) (org-at-item-p))
14171 (call-interactively 'org-previous-item))
14172 ((org-clocktable-try-shift 'up arg))
14173 (org-support-shift-select
14174 (org-call-for-shift-select 'previous-line))
14175 (t (org-shiftselect-error))))
14177 (defun org-shiftdown (&optional arg)
14178 "Decrease item in timestamp or decrease priority of current headline.
14179 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
14180 depending on context. See the individual commands for more information."
14181 (interactive "P")
14182 (cond
14183 ((and org-support-shift-select (org-region-active-p))
14184 (org-call-for-shift-select 'next-line))
14185 ((org-at-timestamp-p t)
14186 (call-interactively (if org-edit-timestamp-down-means-later
14187 'org-timestamp-up 'org-timestamp-down)))
14188 ((and (not (eq org-support-shift-select 'always))
14189 (org-on-heading-p))
14190 (call-interactively 'org-priority-down))
14191 ((and (not org-support-shift-select) (org-at-item-p))
14192 (call-interactively 'org-next-item))
14193 ((org-clocktable-try-shift 'down arg))
14194 (org-support-shift-select
14195 (org-call-for-shift-select 'next-line))
14196 (t (org-shiftselect-error))))
14198 (defun org-shiftright (&optional arg)
14199 "Cycle the thing at point or in the current line, depending on context.
14200 Depending on context, this does one of the following:
14202 - switch a timestamp at point one day into the future
14203 - on a headline, switch to the next TODO keyword.
14204 - on an item, switch entire list to the next bullet type
14205 - on a property line, switch to the next allowed value
14206 - on a clocktable definition line, move time block into the future"
14207 (interactive "P")
14208 (cond
14209 ((and org-support-shift-select (org-region-active-p))
14210 (org-call-for-shift-select 'forward-char))
14211 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
14212 ((and (not (eq org-support-shift-select 'always))
14213 (org-on-heading-p))
14214 (org-call-with-arg 'org-todo 'right))
14215 ((or (and org-support-shift-select
14216 (not (eq org-support-shift-select 'always))
14217 (org-at-item-bullet-p))
14218 (and (not org-support-shift-select) (org-at-item-p)))
14219 (org-call-with-arg 'org-cycle-list-bullet nil))
14220 ((and (not (eq org-support-shift-select 'always))
14221 (org-at-property-p))
14222 (call-interactively 'org-property-next-allowed-value))
14223 ((org-clocktable-try-shift 'right arg))
14224 (org-support-shift-select
14225 (org-call-for-shift-select 'forward-char))
14226 (t (org-shiftselect-error))))
14228 (defun org-shiftleft (&optional arg)
14229 "Cycle the thing at point or in the current line, depending on context.
14230 Depending on context, this does one of the following:
14232 - switch a timestamp at point one day into the past
14233 - on a headline, switch to the previous TODO keyword.
14234 - on an item, switch entire list to the previous bullet type
14235 - on a property line, switch to the previous allowed value
14236 - on a clocktable definition line, move time block into the past"
14237 (interactive "P")
14238 (cond
14239 ((and org-support-shift-select (org-region-active-p))
14240 (org-call-for-shift-select 'backward-char))
14241 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
14242 ((and (not (eq org-support-shift-select 'always))
14243 (org-on-heading-p))
14244 (org-call-with-arg 'org-todo 'left))
14245 ((or (and org-support-shift-select
14246 (not (eq org-support-shift-select 'always))
14247 (org-at-item-bullet-p))
14248 (and (not org-support-shift-select) (org-at-item-p)))
14249 (org-call-with-arg 'org-cycle-list-bullet 'previous))
14250 ((and (not (eq org-support-shift-select 'always))
14251 (org-at-property-p))
14252 (call-interactively 'org-property-previous-allowed-value))
14253 ((org-clocktable-try-shift 'left arg))
14254 (org-support-shift-select
14255 (org-call-for-shift-select 'backward-char))
14256 (t (org-shiftselect-error))))
14258 (defun org-shiftcontrolright ()
14259 "Switch to next TODO set."
14260 (interactive)
14261 (cond
14262 ((and org-support-shift-select (org-region-active-p))
14263 (org-call-for-shift-select 'forward-word))
14264 ((and (not (eq org-support-shift-select 'always))
14265 (org-on-heading-p))
14266 (org-call-with-arg 'org-todo 'nextset))
14267 (org-support-shift-select
14268 (org-call-for-shift-select 'forward-word))
14269 (t (org-shiftselect-error))))
14271 (defun org-shiftcontrolleft ()
14272 "Switch to previous TODO set."
14273 (interactive)
14274 (cond
14275 ((and org-support-shift-select (org-region-active-p))
14276 (org-call-for-shift-select 'backward-word))
14277 ((and (not (eq org-support-shift-select 'always))
14278 (org-on-heading-p))
14279 (org-call-with-arg 'org-todo 'previousset))
14280 (org-support-shift-select
14281 (org-call-for-shift-select 'backward-word))
14282 (t (org-shiftselect-error))))
14284 (defun org-ctrl-c-ret ()
14285 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
14286 (interactive)
14287 (cond
14288 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
14289 (t (call-interactively 'org-insert-heading))))
14291 (defun org-copy-special ()
14292 "Copy region in table or copy current subtree.
14293 Calls `org-table-copy' or `org-copy-subtree', depending on context.
14294 See the individual commands for more information."
14295 (interactive)
14296 (call-interactively
14297 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
14299 (defun org-cut-special ()
14300 "Cut region in table or cut current subtree.
14301 Calls `org-table-copy' or `org-cut-subtree', depending on context.
14302 See the individual commands for more information."
14303 (interactive)
14304 (call-interactively
14305 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
14307 (defun org-paste-special (arg)
14308 "Paste rectangular region into table, or past subtree relative to level.
14309 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
14310 See the individual commands for more information."
14311 (interactive "P")
14312 (if (org-at-table-p)
14313 (org-table-paste-rectangle)
14314 (org-paste-subtree arg)))
14316 (defun org-edit-special ()
14317 "Call a special editor for the stuff at point.
14318 When at a table, call the formula editor with `org-table-edit-formulas'.
14319 When at the first line of an src example, call `org-edit-src-code'.
14320 When in an #+include line, visit the include file. Otherwise call
14321 `ffap' to visit the file at point."
14322 (interactive)
14323 (cond
14324 ((org-at-table-p)
14325 (call-interactively 'org-table-edit-formulas))
14326 ((save-excursion
14327 (beginning-of-line 1)
14328 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
14329 (find-file (org-trim (match-string 1))))
14330 ((org-edit-src-code))
14331 ((org-edit-fixed-width-region))
14332 (t (call-interactively 'ffap))))
14335 (defun org-ctrl-c-ctrl-c (&optional arg)
14336 "Set tags in headline, or update according to changed information at point.
14338 This command does many different things, depending on context:
14340 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
14341 this is what we do.
14343 - If the cursor is in a headline, prompt for tags and insert them
14344 into the current line, aligned to `org-tags-column'. When called
14345 with prefix arg, realign all tags in the current buffer.
14347 - If the cursor is in one of the special #+KEYWORD lines, this
14348 triggers scanning the buffer for these lines and updating the
14349 information.
14351 - If the cursor is inside a table, realign the table. This command
14352 works even if the automatic table editor has been turned off.
14354 - If the cursor is on a #+TBLFM line, re-apply the formulas to
14355 the entire table.
14357 - If the cursor is at a footnote reference or definition, jump to
14358 the corresponding definition or references, respectively.
14360 - If the cursor is a the beginning of a dynamic block, update it.
14362 - If the cursor is inside a table created by the table.el package,
14363 activate that table.
14365 - If the current buffer is a remember buffer, close note and file
14366 it. A prefix argument of 1 files to the default location
14367 without further interaction. A prefix argument of 2 files to
14368 the currently clocking task.
14370 - If the cursor is on a <<<target>>>, update radio targets and corresponding
14371 links in this buffer.
14373 - If the cursor is on a numbered item in a plain list, renumber the
14374 ordered list.
14376 - If the cursor is on a checkbox, toggle it."
14377 (interactive "P")
14378 (let ((org-enable-table-editor t))
14379 (cond
14380 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
14381 org-occur-highlights
14382 org-latex-fragment-image-overlays)
14383 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
14384 (org-remove-occur-highlights)
14385 (org-remove-latex-fragment-image-overlays)
14386 (message "Temporary highlights/overlays removed from current buffer"))
14387 ((and (local-variable-p 'org-finish-function (current-buffer))
14388 (fboundp org-finish-function))
14389 (funcall org-finish-function))
14390 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
14391 ((org-at-property-p)
14392 (call-interactively 'org-property-action))
14393 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
14394 ((org-on-heading-p) (call-interactively 'org-set-tags))
14395 ((org-at-table.el-p)
14396 (require 'table)
14397 (beginning-of-line 1)
14398 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
14399 (call-interactively 'table-recognize-table))
14400 ((org-at-table-p)
14401 (org-table-maybe-eval-formula)
14402 (if arg
14403 (call-interactively 'org-table-recalculate)
14404 (org-table-maybe-recalculate-line))
14405 (call-interactively 'org-table-align))
14406 ((or (org-footnote-at-reference-p)
14407 (org-footnote-at-definition-p))
14408 (call-interactively 'org-footnote-action))
14409 ((org-at-item-checkbox-p)
14410 (call-interactively 'org-toggle-checkbox))
14411 ((org-at-item-p)
14412 (if arg
14413 (call-interactively 'org-toggle-checkbox)
14414 (call-interactively 'org-maybe-renumber-ordered-list)))
14415 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
14416 ;; Dynamic block
14417 (beginning-of-line 1)
14418 (save-excursion (org-update-dblock)))
14419 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
14420 (cond
14421 ((equal (match-string 1) "TBLFM")
14422 ;; Recalculate the table before this line
14423 (save-excursion
14424 (beginning-of-line 1)
14425 (skip-chars-backward " \r\n\t")
14426 (if (org-at-table-p)
14427 (org-call-with-arg 'org-table-recalculate t))))
14429 ; (org-set-regexps-and-options)
14430 ; (org-restart-font-lock)
14431 (let ((org-inhibit-startup t)) (org-mode-restart))
14432 (message "Local setup has been refreshed"))))
14433 (t (error "C-c C-c can do nothing useful at this location.")))))
14435 (defun org-mode-restart ()
14436 "Restart Org-mode, to scan again for special lines.
14437 Also updates the keyword regular expressions."
14438 (interactive)
14439 (org-mode)
14440 (message "Org-mode restarted"))
14442 (defun org-kill-note-or-show-branches ()
14443 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
14444 (interactive)
14445 (if (not org-finish-function)
14446 (call-interactively 'show-branches)
14447 (let ((org-note-abort t))
14448 (funcall org-finish-function))))
14450 (defun org-return (&optional indent)
14451 "Goto next table row or insert a newline.
14452 Calls `org-table-next-row' or `newline', depending on context.
14453 See the individual commands for more information."
14454 (interactive)
14455 (cond
14456 ((bobp) (if indent (newline-and-indent) (newline)))
14457 ((org-at-table-p)
14458 (org-table-justify-field-maybe)
14459 (call-interactively 'org-table-next-row))
14460 ((and org-return-follows-link
14461 (eq (get-text-property (point) 'face) 'org-link))
14462 (call-interactively 'org-open-at-point))
14463 ((and (org-at-heading-p)
14464 (looking-at
14465 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
14466 (org-show-entry)
14467 (end-of-line 1)
14468 (newline))
14469 (t (if indent (newline-and-indent) (newline)))))
14471 (defun org-return-indent ()
14472 "Goto next table row or insert a newline and indent.
14473 Calls `org-table-next-row' or `newline-and-indent', depending on
14474 context. See the individual commands for more information."
14475 (interactive)
14476 (org-return t))
14478 (defun org-ctrl-c-star ()
14479 "Compute table, or change heading status of lines.
14480 Calls `org-table-recalculate' or `org-toggle-heading',
14481 depending on context."
14482 (interactive)
14483 (cond
14484 ((org-at-table-p)
14485 (call-interactively 'org-table-recalculate))
14487 ;; Convert all lines in region to list items
14488 (call-interactively 'org-toggle-heading))))
14490 (defun org-ctrl-c-minus ()
14491 "Insert separator line in table or modify bullet status of line.
14492 Also turns a plain line or a region of lines into list items.
14493 Calls `org-table-insert-hline', `org-toggle-item', or
14494 `org-cycle-list-bullet', depending on context."
14495 (interactive)
14496 (cond
14497 ((org-at-table-p)
14498 (call-interactively 'org-table-insert-hline))
14499 ((org-region-active-p)
14500 (call-interactively 'org-toggle-item))
14501 ((org-in-item-p)
14502 (call-interactively 'org-cycle-list-bullet))
14504 (call-interactively 'org-toggle-item))))
14506 (defun org-toggle-item ()
14507 "Convert headings or normal lines to items, items to normal lines.
14508 If there is no active region, only the current line is considered.
14510 If the first line in the region is a headline, convert all headlines to items.
14512 If the first line in the region is an item, convert all items to normal lines.
14514 If the first line is normal text, add an item bullet to each line."
14515 (interactive)
14516 (let (l2 l beg end)
14517 (if (org-region-active-p)
14518 (setq beg (region-beginning) end (region-end))
14519 (setq beg (point-at-bol)
14520 end (min (1+ (point-at-eol)) (point-max))))
14521 (save-excursion
14522 (goto-char end)
14523 (setq l2 (org-current-line))
14524 (goto-char beg)
14525 (beginning-of-line 1)
14526 (setq l (1- (org-current-line)))
14527 (if (org-at-item-p)
14528 ;; We already have items, de-itemize
14529 (while (< (setq l (1+ l)) l2)
14530 (when (org-at-item-p)
14531 (goto-char (match-beginning 2))
14532 (delete-region (match-beginning 2) (match-end 2))
14533 (and (looking-at "[ \t]+") (replace-match "")))
14534 (beginning-of-line 2))
14535 (if (org-on-heading-p)
14536 ;; Headings, convert to items
14537 (while (< (setq l (1+ l)) l2)
14538 (if (looking-at org-outline-regexp)
14539 (replace-match "- " t t))
14540 (beginning-of-line 2))
14541 ;; normal lines, turn them into items
14542 (while (< (setq l (1+ l)) l2)
14543 (unless (org-at-item-p)
14544 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
14545 (replace-match "\\1- \\2")))
14546 (beginning-of-line 2)))))))
14548 (defun org-toggle-heading (&optional nstars)
14549 "Convert headings to normal text, or items or text to headings.
14550 If there is no active region, only the current line is considered.
14552 If the first line is a heading, remove the stars from all headlines
14553 in the region.
14555 If the first line is a plain list item, turn all plain list items into
14556 headings.
14558 If the first line is a normal line, turn each and every line in the region
14559 into a heading.
14561 When converting a line into a heading, the number of stars is chosen
14562 such that the lines become children of the current entry. However, when
14563 a prefix argument is given, its value determines the number of stars to add."
14564 (interactive "P")
14565 (let (l2 l itemp beg end)
14566 (if (org-region-active-p)
14567 (setq beg (region-beginning) end (region-end))
14568 (setq beg (point-at-bol)
14569 end (min (1+ (point-at-eol)) (point-max))))
14570 (save-excursion
14571 (goto-char end)
14572 (setq l2 (org-current-line))
14573 (goto-char beg)
14574 (beginning-of-line 1)
14575 (setq l (1- (org-current-line)))
14576 (if (org-on-heading-p)
14577 ;; We already have headlines, de-star them
14578 (while (< (setq l (1+ l)) l2)
14579 (when (org-on-heading-p t)
14580 (and (looking-at outline-regexp) (replace-match "")))
14581 (beginning-of-line 2))
14582 (setq itemp (org-at-item-p))
14583 (let* ((stars
14584 (if nstars
14585 (make-string (prefix-numeric-value current-prefix-arg)
14587 (save-excursion
14588 (re-search-backward org-complex-heading-regexp nil t)
14589 (or (match-string 1) ""))))
14590 (add-stars (cond (nstars "")
14591 ((equal stars "") "*")
14592 (org-odd-levels-only "**")
14593 (t "*")))
14594 (rpl (concat stars add-stars " ")))
14595 (while (< (setq l (1+ l)) l2)
14596 (if itemp
14597 (and (org-at-item-p) (replace-match rpl t t))
14598 (unless (org-on-heading-p)
14599 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
14600 (replace-match (concat rpl (match-string 2))))))
14601 (beginning-of-line 2)))))))
14603 (defun org-meta-return (&optional arg)
14604 "Insert a new heading or wrap a region in a table.
14605 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
14606 See the individual commands for more information."
14607 (interactive "P")
14608 (cond
14609 ((run-hook-with-args-until-success 'org-metareturn-hook))
14610 ((org-at-table-p)
14611 (call-interactively 'org-table-wrap-region))
14612 (t (call-interactively 'org-insert-heading))))
14614 ;;; Menu entries
14616 ;; Define the Org-mode menus
14617 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
14618 '("Tbl"
14619 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
14620 ["Next Field" org-cycle (org-at-table-p)]
14621 ["Previous Field" org-shifttab (org-at-table-p)]
14622 ["Next Row" org-return (org-at-table-p)]
14623 "--"
14624 ["Blank Field" org-table-blank-field (org-at-table-p)]
14625 ["Edit Field" org-table-edit-field (org-at-table-p)]
14626 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
14627 "--"
14628 ("Column"
14629 ["Move Column Left" org-metaleft (org-at-table-p)]
14630 ["Move Column Right" org-metaright (org-at-table-p)]
14631 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
14632 ["Insert Column" org-shiftmetaright (org-at-table-p)])
14633 ("Row"
14634 ["Move Row Up" org-metaup (org-at-table-p)]
14635 ["Move Row Down" org-metadown (org-at-table-p)]
14636 ["Delete Row" org-shiftmetaup (org-at-table-p)]
14637 ["Insert Row" org-shiftmetadown (org-at-table-p)]
14638 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
14639 "--"
14640 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
14641 ("Rectangle"
14642 ["Copy Rectangle" org-copy-special (org-at-table-p)]
14643 ["Cut Rectangle" org-cut-special (org-at-table-p)]
14644 ["Paste Rectangle" org-paste-special (org-at-table-p)]
14645 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
14646 "--"
14647 ("Calculate"
14648 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
14649 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
14650 ["Edit Formulas" org-edit-special (org-at-table-p)]
14651 "--"
14652 ["Recalculate line" org-table-recalculate (org-at-table-p)]
14653 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
14654 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
14655 "--"
14656 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
14657 "--"
14658 ["Sum Column/Rectangle" org-table-sum
14659 (or (org-at-table-p) (org-region-active-p))]
14660 ["Which Column?" org-table-current-column (org-at-table-p)])
14661 ["Debug Formulas"
14662 org-table-toggle-formula-debugger
14663 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
14664 ["Show Col/Row Numbers"
14665 org-table-toggle-coordinate-overlays
14666 :style toggle
14667 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
14668 "--"
14669 ["Create" org-table-create (and (not (org-at-table-p))
14670 org-enable-table-editor)]
14671 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
14672 ["Import from File" org-table-import (not (org-at-table-p))]
14673 ["Export to File" org-table-export (org-at-table-p)]
14674 "--"
14675 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
14677 (easy-menu-define org-org-menu org-mode-map "Org menu"
14678 '("Org"
14679 ("Show/Hide"
14680 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
14681 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
14682 ["Sparse Tree..." org-sparse-tree t]
14683 ["Reveal Context" org-reveal t]
14684 ["Show All" show-all t]
14685 "--"
14686 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
14687 "--"
14688 ["New Heading" org-insert-heading t]
14689 ("Navigate Headings"
14690 ["Up" outline-up-heading t]
14691 ["Next" outline-next-visible-heading t]
14692 ["Previous" outline-previous-visible-heading t]
14693 ["Next Same Level" outline-forward-same-level t]
14694 ["Previous Same Level" outline-backward-same-level t]
14695 "--"
14696 ["Jump" org-goto t])
14697 ("Edit Structure"
14698 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
14699 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
14700 "--"
14701 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
14702 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
14703 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
14704 "--"
14705 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
14706 "--"
14707 ["Promote Heading" org-metaleft (not (org-at-table-p))]
14708 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
14709 ["Demote Heading" org-metaright (not (org-at-table-p))]
14710 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
14711 "--"
14712 ["Sort Region/Children" org-sort (not (org-at-table-p))]
14713 "--"
14714 ["Convert to odd levels" org-convert-to-odd-levels t]
14715 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
14716 ("Editing"
14717 ["Emphasis..." org-emphasize t]
14718 ["Edit Source Example" org-edit-special t]
14719 "--"
14720 ["Footnote new/jump" org-footnote-action t]
14721 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
14722 ("Archive"
14723 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
14724 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
14725 ; :active t :keys "C-u C-c C-x C-a"]
14726 ["Sparse trees open ARCHIVE trees"
14727 (setq org-sparse-tree-open-archived-trees
14728 (not org-sparse-tree-open-archived-trees))
14729 :style toggle :selected org-sparse-tree-open-archived-trees]
14730 ["Cycling opens ARCHIVE trees"
14731 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
14732 :style toggle :selected org-cycle-open-archived-trees]
14733 "--"
14734 ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
14735 ["Move Subtree to Archive" org-advertized-archive-subtree t]
14736 ; ["Check and Move Children" (org-archive-subtree '(4))
14737 ; :active t :keys "C-u C-c C-x C-s"]
14739 "--"
14740 ("Hyperlinks"
14741 ["Store Link (Global)" org-store-link t]
14742 ["Insert Link" org-insert-link t]
14743 ["Follow Link" org-open-at-point t]
14744 "--"
14745 ["Next link" org-next-link t]
14746 ["Previous link" org-previous-link t]
14747 "--"
14748 ["Descriptive Links"
14749 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
14750 :style radio
14751 :selected (member '(org-link) buffer-invisibility-spec)]
14752 ["Literal Links"
14753 (progn
14754 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
14755 :style radio
14756 :selected (not (member '(org-link) buffer-invisibility-spec))])
14757 "--"
14758 ("TODO Lists"
14759 ["TODO/DONE/-" org-todo t]
14760 ("Select keyword"
14761 ["Next keyword" org-shiftright (org-on-heading-p)]
14762 ["Previous keyword" org-shiftleft (org-on-heading-p)]
14763 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
14764 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
14765 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
14766 ["Show TODO Tree" org-show-todo-tree t]
14767 ["Global TODO list" org-todo-list t]
14768 "--"
14769 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
14770 :selected org-enforce-todo-dependencies :style toggle :active t]
14771 "Settings for tree at point"
14772 ["Do Children sequentially" org-toggle-ordered-property :style radio
14773 :selected (ignore-errors (org-entry-get nil "ORDERED"))
14774 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
14775 ["Do Children parallel" org-toggle-ordered-property :style radio
14776 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
14777 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
14778 "--"
14779 ["Set Priority" org-priority t]
14780 ["Priority Up" org-shiftup t]
14781 ["Priority Down" org-shiftdown t]
14782 "--"
14783 ["Get news from all feeds" org-feed-update-all t]
14784 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
14785 ["Customize feeds" (customize-variable 'org-feed-alist) t])
14786 ("TAGS and Properties"
14787 ["Set Tags" org-set-tags-command t]
14788 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
14789 "--"
14790 ["Set property" org-set-property t]
14791 ["Column view of properties" org-columns t]
14792 ["Insert Column View DBlock" org-insert-columns-dblock t])
14793 ("Dates and Scheduling"
14794 ["Timestamp" org-time-stamp t]
14795 ["Timestamp (inactive)" org-time-stamp-inactive t]
14796 ("Change Date"
14797 ["1 Day Later" org-shiftright t]
14798 ["1 Day Earlier" org-shiftleft t]
14799 ["1 ... Later" org-shiftup t]
14800 ["1 ... Earlier" org-shiftdown t])
14801 ["Compute Time Range" org-evaluate-time-range t]
14802 ["Schedule Item" org-schedule t]
14803 ["Deadline" org-deadline t]
14804 "--"
14805 ["Custom time format" org-toggle-time-stamp-overlays
14806 :style radio :selected org-display-custom-times]
14807 "--"
14808 ["Goto Calendar" org-goto-calendar t]
14809 ["Date from Calendar" org-date-from-calendar t]
14810 "--"
14811 ["Start/Restart Timer" org-timer-start t]
14812 ["Pause/Continue Timer" org-timer-pause-or-continue t]
14813 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
14814 ["Insert Timer String" org-timer t]
14815 ["Insert Timer Item" org-timer-item t])
14816 ("Logging work"
14817 ["Clock in" org-clock-in t]
14818 ["Clock out" org-clock-out t]
14819 ["Clock cancel" org-clock-cancel t]
14820 ["Goto running clock" org-clock-goto t]
14821 ["Display times" org-clock-display t]
14822 ["Create clock table" org-clock-report t]
14823 "--"
14824 ["Record DONE time"
14825 (progn (setq org-log-done (not org-log-done))
14826 (message "Switching to %s will %s record a timestamp"
14827 (car org-done-keywords)
14828 (if org-log-done "automatically" "not")))
14829 :style toggle :selected org-log-done])
14830 "--"
14831 ["Agenda Command..." org-agenda t]
14832 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
14833 ("File List for Agenda")
14834 ("Special views current file"
14835 ["TODO Tree" org-show-todo-tree t]
14836 ["Check Deadlines" org-check-deadlines t]
14837 ["Timeline" org-timeline t]
14838 ["Tags/Property tree" org-match-sparse-tree t])
14839 "--"
14840 ["Export/Publish..." org-export t]
14841 ("LaTeX"
14842 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
14843 :selected org-cdlatex-mode]
14844 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
14845 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
14846 ["Modify math symbol" org-cdlatex-math-modify
14847 (org-inside-LaTeX-fragment-p)]
14848 ["Insert citation" org-reftex-citation t]
14849 "--"
14850 ["Export LaTeX fragments as images"
14851 (if (featurep 'org-exp)
14852 (setq org-export-with-LaTeX-fragments
14853 (not org-export-with-LaTeX-fragments))
14854 (require 'org-exp))
14855 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
14856 org-export-with-LaTeX-fragments)])
14857 "--"
14858 ("Documentation"
14859 ["Show Version" org-version t]
14860 ["Info Documentation" org-info t])
14861 ("Customize"
14862 ["Browse Org Group" org-customize t]
14863 "--"
14864 ["Expand This Menu" org-create-customize-menu
14865 (fboundp 'customize-menu-create)])
14866 "--"
14867 ("Refresh/Reload"
14868 ["Refresh setup current buffer" org-mode-restart t]
14869 ["Reload Org (after update)" org-reload t]
14870 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
14873 (defun org-info (&optional node)
14874 "Read documentation for Org-mode in the info system.
14875 With optional NODE, go directly to that node."
14876 (interactive)
14877 (info (format "(org)%s" (or node ""))))
14879 (defun org-install-agenda-files-menu ()
14880 (let ((bl (buffer-list)))
14881 (save-excursion
14882 (while bl
14883 (set-buffer (pop bl))
14884 (if (org-mode-p) (setq bl nil)))
14885 (when (org-mode-p)
14886 (easy-menu-change
14887 '("Org") "File List for Agenda"
14888 (append
14889 (list
14890 ["Edit File List" (org-edit-agenda-file-list) t]
14891 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
14892 ["Remove Current File from List" org-remove-file t]
14893 ["Cycle through agenda files" org-cycle-agenda-files t]
14894 ["Occur in all agenda files" org-occur-in-agenda-files t]
14895 "--")
14896 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
14898 ;;;; Documentation
14900 ;;;###autoload
14901 (defun org-require-autoloaded-modules ()
14902 (interactive)
14903 (mapc 'require
14904 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
14905 org-docbook org-exp org-html org-icalendar
14906 org-id org-latex
14907 org-publish org-remember org-table
14908 org-timer org-xoxo)))
14910 ;;;###autoload
14911 (defun org-reload (&optional uncompiled)
14912 "Reload all org lisp files.
14913 With prefix arg UNCOMPILED, load the uncompiled versions."
14914 (interactive "P")
14915 (require 'find-func)
14916 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
14917 (dir-org (file-name-directory (org-find-library-name "org")))
14918 (dir-org-contrib (ignore-errors
14919 (file-name-directory
14920 (org-find-library-name "org-contribdir"))))
14921 (files
14922 (append (directory-files dir-org t file-re)
14923 (and dir-org-contrib
14924 (directory-files dir-org-contrib t file-re))))
14925 (remove-re (concat (if (featurep 'xemacs)
14926 "org-colview" "org-colview-xemacs")
14927 "\\'")))
14928 (setq files (mapcar 'file-name-sans-extension files))
14929 (setq files (mapcar
14930 (lambda (x) (if (string-match remove-re x) nil x))
14931 files))
14932 (setq files (delq nil files))
14933 (mapc
14934 (lambda (f)
14935 (when (featurep (intern (file-name-nondirectory f)))
14936 (if (and (not uncompiled)
14937 (file-exists-p (concat f ".elc")))
14938 (load (concat f ".elc") nil nil t)
14939 (load (concat f ".el") nil nil t))))
14940 files))
14941 (org-version))
14943 ;;;###autoload
14944 (defun org-customize ()
14945 "Call the customize function with org as argument."
14946 (interactive)
14947 (org-load-modules-maybe)
14948 (org-require-autoloaded-modules)
14949 (customize-browse 'org))
14951 (defun org-create-customize-menu ()
14952 "Create a full customization menu for Org-mode, insert it into the menu."
14953 (interactive)
14954 (org-load-modules-maybe)
14955 (org-require-autoloaded-modules)
14956 (if (fboundp 'customize-menu-create)
14957 (progn
14958 (easy-menu-change
14959 '("Org") "Customize"
14960 `(["Browse Org group" org-customize t]
14961 "--"
14962 ,(customize-menu-create 'org)
14963 ["Set" Custom-set t]
14964 ["Save" Custom-save t]
14965 ["Reset to Current" Custom-reset-current t]
14966 ["Reset to Saved" Custom-reset-saved t]
14967 ["Reset to Standard Settings" Custom-reset-standard t]))
14968 (message "\"Org\"-menu now contains full customization menu"))
14969 (error "Cannot expand menu (outdated version of cus-edit.el)")))
14971 ;;;; Miscellaneous stuff
14973 ;;; Generally useful functions
14975 (defun org-find-text-property-in-string (prop s)
14976 "Return the first non-nil value of property PROP in string S."
14977 (or (get-text-property 0 prop s)
14978 (get-text-property (or (next-single-property-change 0 prop s) 0)
14979 prop s)))
14981 (defun org-display-warning (message) ;; Copied from Emacs-Muse
14982 "Display the given MESSAGE as a warning."
14983 (if (fboundp 'display-warning)
14984 (display-warning 'org message
14985 (if (featurep 'xemacs)
14986 'warning
14987 :warning))
14988 (let ((buf (get-buffer-create "*Org warnings*")))
14989 (with-current-buffer buf
14990 (goto-char (point-max))
14991 (insert "Warning (Org): " message)
14992 (unless (bolp)
14993 (newline)))
14994 (display-buffer buf)
14995 (sit-for 0))))
14997 (defun org-goto-marker-or-bmk (marker &optional bookmark)
14998 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
14999 (if (and marker (marker-buffer marker)
15000 (buffer-live-p (marker-buffer marker)))
15001 (progn
15002 (switch-to-buffer (marker-buffer marker))
15003 (if (or (> marker (point-max)) (< marker (point-min)))
15004 (widen))
15005 (goto-char marker)
15006 (org-show-context 'org-goto))
15007 (if bookmark
15008 (bookmark-jump bookmark)
15009 (error "Cannot find location"))))
15011 (defun org-quote-csv-field (s)
15012 "Quote field for inclusion in CSV material."
15013 (if (string-match "[\",]" s)
15014 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
15017 (defun org-plist-delete (plist property)
15018 "Delete PROPERTY from PLIST.
15019 This is in contrast to merely setting it to 0."
15020 (let (p)
15021 (while plist
15022 (if (not (eq property (car plist)))
15023 (setq p (plist-put p (car plist) (nth 1 plist))))
15024 (setq plist (cddr plist)))
15027 (defun org-force-self-insert (N)
15028 "Needed to enforce self-insert under remapping."
15029 (interactive "p")
15030 (self-insert-command N))
15032 (defun org-string-width (s)
15033 "Compute width of string, ignoring invisible characters.
15034 This ignores character with invisibility property `org-link', and also
15035 characters with property `org-cwidth', because these will become invisible
15036 upon the next fontification round."
15037 (let (b l)
15038 (when (or (eq t buffer-invisibility-spec)
15039 (assq 'org-link buffer-invisibility-spec))
15040 (while (setq b (text-property-any 0 (length s)
15041 'invisible 'org-link s))
15042 (setq s (concat (substring s 0 b)
15043 (substring s (or (next-single-property-change
15044 b 'invisible s) (length s)))))))
15045 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
15046 (setq s (concat (substring s 0 b)
15047 (substring s (or (next-single-property-change
15048 b 'org-cwidth s) (length s))))))
15049 (setq l (string-width s) b -1)
15050 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
15051 (setq l (- l (get-text-property b 'org-dwidth-n s))))
15054 (defun org-get-indentation (&optional line)
15055 "Get the indentation of the current line, interpreting tabs.
15056 When LINE is given, assume it represents a line and compute its indentation."
15057 (if line
15058 (if (string-match "^ *" (org-remove-tabs line))
15059 (match-end 0))
15060 (save-excursion
15061 (beginning-of-line 1)
15062 (skip-chars-forward " \t")
15063 (current-column))))
15065 (defun org-remove-tabs (s &optional width)
15066 "Replace tabulators in S with spaces.
15067 Assumes that s is a single line, starting in column 0."
15068 (setq width (or width tab-width))
15069 (while (string-match "\t" s)
15070 (setq s (replace-match
15071 (make-string
15072 (- (* width (/ (+ (match-beginning 0) width) width))
15073 (match-beginning 0)) ?\ )
15074 t t s)))
15077 (defun org-fix-indentation (line ind)
15078 "Fix indentation in LINE.
15079 IND is a cons cell with target and minimum indentation.
15080 If the current indentation in LINE is smaller than the minimum,
15081 leave it alone. If it is larger than ind, set it to the target."
15082 (let* ((l (org-remove-tabs line))
15083 (i (org-get-indentation l))
15084 (i1 (car ind)) (i2 (cdr ind)))
15085 (if (>= i i2) (setq l (substring line i2)))
15086 (if (> i1 0)
15087 (concat (make-string i1 ?\ ) l)
15088 l)))
15090 (defun org-base-buffer (buffer)
15091 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
15092 (if (not buffer)
15093 buffer
15094 (or (buffer-base-buffer buffer)
15095 buffer)))
15097 (defun org-trim (s)
15098 "Remove whitespace at beginning and end of string."
15099 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
15100 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
15103 (defun org-wrap (string &optional width lines)
15104 "Wrap string to either a number of lines, or a width in characters.
15105 If WIDTH is non-nil, the string is wrapped to that width, however many lines
15106 that costs. If there is a word longer than WIDTH, the text is actually
15107 wrapped to the length of that word.
15108 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
15109 many lines, whatever width that takes.
15110 The return value is a list of lines, without newlines at the end."
15111 (let* ((words (org-split-string string "[ \t\n]+"))
15112 (maxword (apply 'max (mapcar 'org-string-width words)))
15113 w ll)
15114 (cond (width
15115 (org-do-wrap words (max maxword width)))
15116 (lines
15117 (setq w maxword)
15118 (setq ll (org-do-wrap words maxword))
15119 (if (<= (length ll) lines)
15121 (setq ll words)
15122 (while (> (length ll) lines)
15123 (setq w (1+ w))
15124 (setq ll (org-do-wrap words w)))
15125 ll))
15126 (t (error "Cannot wrap this")))))
15128 (defun org-do-wrap (words width)
15129 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
15130 (let (lines line)
15131 (while words
15132 (setq line (pop words))
15133 (while (and words (< (+ (length line) (length (car words))) width))
15134 (setq line (concat line " " (pop words))))
15135 (setq lines (push line lines)))
15136 (nreverse lines)))
15138 (defun org-split-string (string &optional separators)
15139 "Splits STRING into substrings at SEPARATORS.
15140 No empty strings are returned if there are matches at the beginning
15141 and end of string."
15142 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
15143 (start 0)
15144 notfirst
15145 (list nil))
15146 (while (and (string-match rexp string
15147 (if (and notfirst
15148 (= start (match-beginning 0))
15149 (< start (length string)))
15150 (1+ start) start))
15151 (< (match-beginning 0) (length string)))
15152 (setq notfirst t)
15153 (or (eq (match-beginning 0) 0)
15154 (and (eq (match-beginning 0) (match-end 0))
15155 (eq (match-beginning 0) start))
15156 (setq list
15157 (cons (substring string start (match-beginning 0))
15158 list)))
15159 (setq start (match-end 0)))
15160 (or (eq start (length string))
15161 (setq list
15162 (cons (substring string start)
15163 list)))
15164 (nreverse list)))
15166 (defun org-uuidgen-p (s)
15167 "Is S an ID created by UUIDGEN?"
15168 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
15170 (defun org-context ()
15171 "Return a list of contexts of the current cursor position.
15172 If several contexts apply, all are returned.
15173 Each context entry is a list with a symbol naming the context, and
15174 two positions indicating start and end of the context. Possible
15175 contexts are:
15177 :headline anywhere in a headline
15178 :headline-stars on the leading stars in a headline
15179 :todo-keyword on a TODO keyword (including DONE) in a headline
15180 :tags on the TAGS in a headline
15181 :priority on the priority cookie in a headline
15182 :item on the first line of a plain list item
15183 :item-bullet on the bullet/number of a plain list item
15184 :checkbox on the checkbox in a plain list item
15185 :table in an org-mode table
15186 :table-special on a special filed in a table
15187 :table-table in a table.el table
15188 :link on a hyperlink
15189 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
15190 :target on a <<target>>
15191 :radio-target on a <<<radio-target>>>
15192 :latex-fragment on a LaTeX fragment
15193 :latex-preview on a LaTeX fragment with overlayed preview image
15195 This function expects the position to be visible because it uses font-lock
15196 faces as a help to recognize the following contexts: :table-special, :link,
15197 and :keyword."
15198 (let* ((f (get-text-property (point) 'face))
15199 (faces (if (listp f) f (list f)))
15200 (p (point)) clist o)
15201 ;; First the large context
15202 (cond
15203 ((org-on-heading-p t)
15204 (push (list :headline (point-at-bol) (point-at-eol)) clist)
15205 (when (progn
15206 (beginning-of-line 1)
15207 (looking-at org-todo-line-tags-regexp))
15208 (push (org-point-in-group p 1 :headline-stars) clist)
15209 (push (org-point-in-group p 2 :todo-keyword) clist)
15210 (push (org-point-in-group p 4 :tags) clist))
15211 (goto-char p)
15212 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
15213 (if (looking-at "\\[#[A-Z0-9]\\]")
15214 (push (org-point-in-group p 0 :priority) clist)))
15216 ((org-at-item-p)
15217 (push (org-point-in-group p 2 :item-bullet) clist)
15218 (push (list :item (point-at-bol)
15219 (save-excursion (org-end-of-item) (point)))
15220 clist)
15221 (and (org-at-item-checkbox-p)
15222 (push (org-point-in-group p 0 :checkbox) clist)))
15224 ((org-at-table-p)
15225 (push (list :table (org-table-begin) (org-table-end)) clist)
15226 (if (memq 'org-formula faces)
15227 (push (list :table-special
15228 (previous-single-property-change p 'face)
15229 (next-single-property-change p 'face)) clist)))
15230 ((org-at-table-p 'any)
15231 (push (list :table-table) clist)))
15232 (goto-char p)
15234 ;; Now the small context
15235 (cond
15236 ((org-at-timestamp-p)
15237 (push (org-point-in-group p 0 :timestamp) clist))
15238 ((memq 'org-link faces)
15239 (push (list :link
15240 (previous-single-property-change p 'face)
15241 (next-single-property-change p 'face)) clist))
15242 ((memq 'org-special-keyword faces)
15243 (push (list :keyword
15244 (previous-single-property-change p 'face)
15245 (next-single-property-change p 'face)) clist))
15246 ((org-on-target-p)
15247 (push (org-point-in-group p 0 :target) clist)
15248 (goto-char (1- (match-beginning 0)))
15249 (if (looking-at org-radio-target-regexp)
15250 (push (org-point-in-group p 0 :radio-target) clist))
15251 (goto-char p))
15252 ((setq o (car (delq nil
15253 (mapcar
15254 (lambda (x)
15255 (if (memq x org-latex-fragment-image-overlays) x))
15256 (org-overlays-at (point))))))
15257 (push (list :latex-fragment
15258 (org-overlay-start o) (org-overlay-end o)) clist)
15259 (push (list :latex-preview
15260 (org-overlay-start o) (org-overlay-end o)) clist))
15261 ((org-inside-LaTeX-fragment-p)
15262 ;; FIXME: positions wrong.
15263 (push (list :latex-fragment (point) (point)) clist)))
15265 (setq clist (nreverse (delq nil clist)))
15266 clist))
15268 ;; FIXME: Compare with at-regexp-p Do we need both?
15269 (defun org-in-regexp (re &optional nlines visually)
15270 "Check if point is inside a match of regexp.
15271 Normally only the current line is checked, but you can include NLINES extra
15272 lines both before and after point into the search.
15273 If VISUALLY is set, require that the cursor is not after the match but
15274 really on, so that the block visually is on the match."
15275 (catch 'exit
15276 (let ((pos (point))
15277 (eol (point-at-eol (+ 1 (or nlines 0))))
15278 (inc (if visually 1 0)))
15279 (save-excursion
15280 (beginning-of-line (- 1 (or nlines 0)))
15281 (while (re-search-forward re eol t)
15282 (if (and (<= (match-beginning 0) pos)
15283 (>= (+ inc (match-end 0)) pos))
15284 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
15286 (defun org-at-regexp-p (regexp)
15287 "Is point inside a match of REGEXP in the current line?"
15288 (catch 'exit
15289 (save-excursion
15290 (let ((pos (point)) (end (point-at-eol)))
15291 (beginning-of-line 1)
15292 (while (re-search-forward regexp end t)
15293 (if (and (<= (match-beginning 0) pos)
15294 (>= (match-end 0) pos))
15295 (throw 'exit t)))
15296 nil))))
15298 (defun org-occur-in-agenda-files (regexp &optional nlines)
15299 "Call `multi-occur' with buffers for all agenda files."
15300 (interactive "sOrg-files matching: \np")
15301 (let* ((files (org-agenda-files))
15302 (tnames (mapcar 'file-truename files))
15303 (extra org-agenda-text-search-extra-files)
15305 (when (eq (car extra) 'agenda-archives)
15306 (setq extra (cdr extra))
15307 (setq files (org-add-archive-files files)))
15308 (while (setq f (pop extra))
15309 (unless (member (file-truename f) tnames)
15310 (add-to-list 'files f 'append)
15311 (add-to-list 'tnames (file-truename f) 'append)))
15312 (multi-occur
15313 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
15314 regexp)))
15316 (if (boundp 'occur-mode-find-occurrence-hook)
15317 ;; Emacs 23
15318 (add-hook 'occur-mode-find-occurrence-hook
15319 (lambda ()
15320 (when (org-mode-p)
15321 (org-reveal))))
15322 ;; Emacs 22
15323 (defadvice occur-mode-goto-occurrence
15324 (after org-occur-reveal activate)
15325 (and (org-mode-p) (org-reveal)))
15326 (defadvice occur-mode-goto-occurrence-other-window
15327 (after org-occur-reveal activate)
15328 (and (org-mode-p) (org-reveal)))
15329 (defadvice occur-mode-display-occurrence
15330 (after org-occur-reveal activate)
15331 (when (org-mode-p)
15332 (let ((pos (occur-mode-find-occurrence)))
15333 (with-current-buffer (marker-buffer pos)
15334 (save-excursion
15335 (goto-char pos)
15336 (org-reveal)))))))
15338 (defun org-uniquify (list)
15339 "Remove duplicate elements from LIST."
15340 (let (res)
15341 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
15342 res))
15344 (defun org-delete-all (elts list)
15345 "Remove all elements in ELTS from LIST."
15346 (while elts
15347 (setq list (delete (pop elts) list)))
15348 list)
15350 (defun org-back-over-empty-lines ()
15351 "Move backwards over whitespace, to the beginning of the first empty line.
15352 Returns the number of empty lines passed."
15353 (let ((pos (point)))
15354 (skip-chars-backward " \t\n\r")
15355 (beginning-of-line 2)
15356 (goto-char (min (point) pos))
15357 (count-lines (point) pos)))
15359 (defun org-skip-whitespace ()
15360 (skip-chars-forward " \t\n\r"))
15362 (defun org-point-in-group (point group &optional context)
15363 "Check if POINT is in match-group GROUP.
15364 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
15365 match. If the match group does ot exist or point is not inside it,
15366 return nil."
15367 (and (match-beginning group)
15368 (>= point (match-beginning group))
15369 (<= point (match-end group))
15370 (if context
15371 (list context (match-beginning group) (match-end group))
15372 t)))
15374 (defun org-switch-to-buffer-other-window (&rest args)
15375 "Switch to buffer in a second window on the current frame.
15376 In particular, do not allow pop-up frames."
15377 (let (pop-up-frames special-display-buffer-names special-display-regexps
15378 special-display-function)
15379 (apply 'switch-to-buffer-other-window args)))
15381 (defun org-combine-plists (&rest plists)
15382 "Create a single property list from all plists in PLISTS.
15383 The process starts by copying the first list, and then setting properties
15384 from the other lists. Settings in the last list are the most significant
15385 ones and overrule settings in the other lists."
15386 (let ((rtn (copy-sequence (pop plists)))
15387 p v ls)
15388 (while plists
15389 (setq ls (pop plists))
15390 (while ls
15391 (setq p (pop ls) v (pop ls))
15392 (setq rtn (plist-put rtn p v))))
15393 rtn))
15395 (defun org-move-line-down (arg)
15396 "Move the current line down. With prefix argument, move it past ARG lines."
15397 (interactive "p")
15398 (let ((col (current-column))
15399 beg end pos)
15400 (beginning-of-line 1) (setq beg (point))
15401 (beginning-of-line 2) (setq end (point))
15402 (beginning-of-line (+ 1 arg))
15403 (setq pos (move-marker (make-marker) (point)))
15404 (insert (delete-and-extract-region beg end))
15405 (goto-char pos)
15406 (org-move-to-column col)))
15408 (defun org-move-line-up (arg)
15409 "Move the current line up. With prefix argument, move it past ARG lines."
15410 (interactive "p")
15411 (let ((col (current-column))
15412 beg end pos)
15413 (beginning-of-line 1) (setq beg (point))
15414 (beginning-of-line 2) (setq end (point))
15415 (beginning-of-line (- arg))
15416 (setq pos (move-marker (make-marker) (point)))
15417 (insert (delete-and-extract-region beg end))
15418 (goto-char pos)
15419 (org-move-to-column col)))
15421 (defun org-replace-escapes (string table)
15422 "Replace %-escapes in STRING with values in TABLE.
15423 TABLE is an association list with keys like \"%a\" and string values.
15424 The sequences in STRING may contain normal field width and padding information,
15425 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
15426 so values can contain further %-escapes if they are define later in TABLE."
15427 (let ((case-fold-search nil)
15428 e re rpl)
15429 (while (setq e (pop table))
15430 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
15431 (while (string-match re string)
15432 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
15433 (cdr e)))
15434 (setq string (replace-match rpl t t string))))
15435 string))
15438 (defun org-sublist (list start end)
15439 "Return a section of LIST, from START to END.
15440 Counting starts at 1."
15441 (let (rtn (c start))
15442 (setq list (nthcdr (1- start) list))
15443 (while (and list (<= c end))
15444 (push (pop list) rtn)
15445 (setq c (1+ c)))
15446 (nreverse rtn)))
15448 (defun org-find-base-buffer-visiting (file)
15449 "Like `find-buffer-visiting' but alway return the base buffer and
15450 not an indirect buffer."
15451 (let ((buf (find-buffer-visiting file)))
15452 (if buf
15453 (or (buffer-base-buffer buf) buf)
15454 nil)))
15456 (defun org-image-file-name-regexp (&optional extensions)
15457 "Return regexp matching the file names of images.
15458 If EXTENSIONS is given, only match these."
15459 (if (and (not extensions) (fboundp 'image-file-name-regexp))
15460 (image-file-name-regexp)
15461 (let ((image-file-name-extensions
15462 (or extensions
15463 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
15464 "xbm" "xpm" "pbm" "pgm" "ppm"))))
15465 (concat "\\."
15466 (regexp-opt (nconc (mapcar 'upcase
15467 image-file-name-extensions)
15468 image-file-name-extensions)
15470 "\\'"))))
15472 (defun org-file-image-p (file &optional extensions)
15473 "Return non-nil if FILE is an image."
15474 (save-match-data
15475 (string-match (org-image-file-name-regexp extensions) file)))
15477 (defun org-get-cursor-date ()
15478 "Return the date at cursor in as a time.
15479 This works in the calendar and in the agenda, anywhere else it just
15480 returns the current time."
15481 (let (date day defd)
15482 (cond
15483 ((eq major-mode 'calendar-mode)
15484 (setq date (calendar-cursor-to-date)
15485 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15486 ((eq major-mode 'org-agenda-mode)
15487 (setq day (get-text-property (point) 'day))
15488 (if day
15489 (setq date (calendar-gregorian-from-absolute day)
15490 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
15491 (nth 2 date))))))
15492 (or defd (current-time))))
15494 (defvar org-agenda-action-marker (make-marker)
15495 "Marker pointing to the entry for the next agenda action.")
15497 (defun org-mark-entry-for-agenda-action ()
15498 "Mark the current entry as target of an agenda action.
15499 Agenda actions are actions executed from the agenda with the key `k',
15500 which make use of the date at the cursor."
15501 (interactive)
15502 (move-marker org-agenda-action-marker
15503 (save-excursion (org-back-to-heading t) (point))
15504 (current-buffer))
15505 (message
15506 "Entry marked for action; press `k' at desired date in agenda or calendar"))
15508 ;;; Paragraph filling stuff.
15509 ;; We want this to be just right, so use the full arsenal.
15511 (defun org-indent-line-function ()
15512 "Indent line like previous, but further if previous was headline or item."
15513 (interactive)
15514 (let* ((pos (point))
15515 (itemp (org-at-item-p))
15516 (org-drawer-regexp (or org-drawer-regexp "\000"))
15517 column bpos bcol tpos tcol bullet btype bullet-type)
15518 ;; Find the previous relevant line
15519 (beginning-of-line 1)
15520 (cond
15521 ((looking-at "#") (setq column 0))
15522 ((looking-at "\\*+ ") (setq column 0))
15523 ((and (looking-at "[ \t]*:END:")
15524 (save-excursion (re-search-backward org-drawer-regexp nil t)))
15525 (save-excursion
15526 (goto-char (1- (match-beginning 1)))
15527 (setq column (current-column))))
15529 (beginning-of-line 0)
15530 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]")
15531 (not (looking-at "[ \t]*:END:"))
15532 (not (looking-at org-drawer-regexp)))
15533 (beginning-of-line 0))
15534 (cond
15535 ((looking-at "\\*+[ \t]+")
15536 (if (not org-adapt-indentation)
15537 (setq column 0)
15538 (goto-char (match-end 0))
15539 (setq column (current-column))))
15540 ((looking-at org-drawer-regexp)
15541 (goto-char (1- (match-beginning 1)))
15542 (setq column (current-column)))
15543 ((looking-at "\\([ \t]*\\):END:")
15544 (goto-char (match-end 1))
15545 (setq column (current-column)))
15546 ((org-in-item-p)
15547 (org-beginning-of-item)
15548 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
15549 (setq bpos (match-beginning 1) tpos (match-end 0)
15550 bcol (progn (goto-char bpos) (current-column))
15551 tcol (progn (goto-char tpos) (current-column))
15552 bullet (match-string 1)
15553 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
15554 (if (> tcol (+ bcol org-description-max-indent))
15555 (setq tcol (+ bcol 5)))
15556 (if (not itemp)
15557 (setq column tcol)
15558 (goto-char pos)
15559 (beginning-of-line 1)
15560 (if (looking-at "\\S-")
15561 (progn
15562 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
15563 (setq bullet (match-string 1)
15564 btype (if (string-match "[0-9]" bullet) "n" bullet))
15565 (setq column (if (equal btype bullet-type) bcol tcol)))
15566 (setq column (org-get-indentation)))))
15567 (t (setq column (org-get-indentation))))))
15568 (goto-char pos)
15569 (if (<= (current-column) (current-indentation))
15570 (org-indent-line-to column)
15571 (save-excursion (org-indent-line-to column)))
15572 (setq column (current-column))
15573 (beginning-of-line 1)
15574 (if (looking-at
15575 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
15576 (replace-match (concat "\\1" (format org-property-format
15577 (match-string 2) (match-string 3)))
15578 t nil))
15579 (org-move-to-column column)))
15581 (defun org-set-autofill-regexps ()
15582 (interactive)
15583 ;; In the paragraph separator we include headlines, because filling
15584 ;; text in a line directly attached to a headline would otherwise
15585 ;; fill the headline as well.
15586 (org-set-local 'comment-start-skip "^#+[ \t]*")
15587 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
15588 ;; The paragraph starter includes hand-formatted lists.
15589 (org-set-local 'paragraph-start
15590 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
15591 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
15592 ;; But only if the user has not turned off tables or fixed-width regions
15593 (org-set-local
15594 'auto-fill-inhibit-regexp
15595 (concat "\\*+ \\|#\\+"
15596 "\\|[ \t]*" org-keyword-time-regexp
15597 (if (or org-enable-table-editor org-enable-fixed-width-editor)
15598 (concat
15599 "\\|[ \t]*["
15600 (if org-enable-table-editor "|" "")
15601 (if org-enable-fixed-width-editor ":" "")
15602 "]"))))
15603 ;; We use our own fill-paragraph function, to make sure that tables
15604 ;; and fixed-width regions are not wrapped. That function will pass
15605 ;; through to `fill-paragraph' when appropriate.
15606 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
15607 ; Adaptive filling: To get full control, first make sure that
15608 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
15609 (org-set-local 'adaptive-fill-regexp "\000")
15610 (org-set-local 'adaptive-fill-function
15611 'org-adaptive-fill-function)
15612 (org-set-local
15613 'align-mode-rules-list
15614 '((org-in-buffer-settings
15615 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
15616 (modes . '(org-mode))))))
15618 (defun org-fill-paragraph (&optional justify)
15619 "Re-align a table, pass through to fill-paragraph if no table."
15620 (let ((table-p (org-at-table-p))
15621 (table.el-p (org-at-table.el-p)))
15622 (cond ((and (equal (char-after (point-at-bol)) ?*)
15623 (save-excursion (goto-char (point-at-bol))
15624 (looking-at outline-regexp)))
15625 t) ; skip headlines
15626 (table.el-p t) ; skip table.el tables
15627 (table-p (org-table-align) t) ; align org-mode tables
15628 (t nil)))) ; call paragraph-fill
15630 ;; For reference, this is the default value of adaptive-fill-regexp
15631 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
15633 (defun org-adaptive-fill-function ()
15634 "Return a fill prefix for org-mode files.
15635 In particular, this makes sure hanging paragraphs for hand-formatted lists
15636 work correctly."
15637 (cond ((looking-at "#[ \t]+")
15638 (match-string 0))
15639 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
15640 (save-excursion
15641 (if (> (match-end 1) (+ (match-beginning 1)
15642 org-description-max-indent))
15643 (goto-char (+ (match-beginning 1) 5))
15644 (goto-char (match-end 0)))
15645 (make-string (current-column) ?\ )))
15646 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
15647 (save-excursion
15648 (goto-char (match-end 0))
15649 (make-string (current-column) ?\ )))
15650 (t nil)))
15652 ;;; Other stuff.
15654 (defun org-toggle-fixed-width-section (arg)
15655 "Toggle the fixed-width export.
15656 If there is no active region, the QUOTE keyword at the current headline is
15657 inserted or removed. When present, it causes the text between this headline
15658 and the next to be exported as fixed-width text, and unmodified.
15659 If there is an active region, this command adds or removes a colon as the
15660 first character of this line. If the first character of a line is a colon,
15661 this line is also exported in fixed-width font."
15662 (interactive "P")
15663 (let* ((cc 0)
15664 (regionp (org-region-active-p))
15665 (beg (if regionp (region-beginning) (point)))
15666 (end (if regionp (region-end)))
15667 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
15668 (case-fold-search nil)
15669 (re "[ \t]*\\(: \\)")
15670 off)
15671 (if regionp
15672 (save-excursion
15673 (goto-char beg)
15674 (setq cc (current-column))
15675 (beginning-of-line 1)
15676 (setq off (looking-at re))
15677 (while (> nlines 0)
15678 (setq nlines (1- nlines))
15679 (beginning-of-line 1)
15680 (cond
15681 (arg
15682 (org-move-to-column cc t)
15683 (insert ": \n")
15684 (forward-line -1))
15685 ((and off (looking-at re))
15686 (replace-match "" t t nil 1))
15687 ((not off) (org-move-to-column cc t) (insert ": ")))
15688 (forward-line 1)))
15689 (save-excursion
15690 (org-back-to-heading)
15691 (if (looking-at (concat outline-regexp
15692 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
15693 (replace-match "" t t nil 1)
15694 (if (looking-at outline-regexp)
15695 (progn
15696 (goto-char (match-end 0))
15697 (insert org-quote-string " "))))))))
15699 (defun org-reftex-citation ()
15700 "Use reftex-citation to insert a citation into the buffer.
15701 This looks for a line like
15703 #+BIBLIOGRAPHY: foo plain option:-d
15705 and derives from it that foo.bib is the bbliography file relevant
15706 for this document. It then installs the necessary environment for RefTeX
15707 to work in this buffer and calls `reftex-citation' to insert a citation
15708 into the buffer.
15710 Export of such citations to both LaTeX and HTML is handled by the contributed
15711 package org-exp-bibtex by Taru Karttunen."
15712 (interactive)
15713 (let ((reftex-docstruct-symbol 'rds)
15714 (reftex-cite-format "\\cite{%l}")
15715 rds bib)
15716 (save-excursion
15717 (save-restriction
15718 (widen)
15719 (let ((case-fold-search t)
15720 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
15721 (if (not (save-excursion
15722 (or (re-search-forward re nil t)
15723 (re-search-backward re nil t))))
15724 (error "No bibliography defined in file")
15725 (setq bib (concat (match-string 1) ".bib")
15726 rds (list (list 'bib bib)))))))
15727 (call-interactively 'reftex-citation)))
15729 ;;;; Functions extending outline functionality
15731 (defun org-beginning-of-line (&optional arg)
15732 "Go to the beginning of the current line. If that is invisible, continue
15733 to a visible line beginning. This makes the function of C-a more intuitive.
15734 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
15735 first attempt, and only move to after the tags when the cursor is already
15736 beyond the end of the headline."
15737 (interactive "P")
15738 (let ((pos (point))
15739 (special (if (consp org-special-ctrl-a/e)
15740 (car org-special-ctrl-a/e)
15741 org-special-ctrl-a/e))
15742 refpos)
15743 (beginning-of-line 1)
15744 (if (and arg (fboundp 'move-beginning-of-line))
15745 (call-interactively 'move-beginning-of-line)
15746 (if (bobp)
15748 (backward-char 1)
15749 (if (org-invisible-p)
15750 (while (and (not (bobp)) (org-invisible-p))
15751 (backward-char 1)
15752 (beginning-of-line 1))
15753 (forward-char 1))))
15754 (when special
15755 (cond
15756 ((and (looking-at org-complex-heading-regexp)
15757 (= (char-after (match-end 1)) ?\ ))
15758 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
15759 (point-at-eol)))
15760 (goto-char
15761 (if (eq special t)
15762 (cond ((> pos refpos) refpos)
15763 ((= pos (point)) refpos)
15764 (t (point)))
15765 (cond ((> pos (point)) (point))
15766 ((not (eq last-command this-command)) (point))
15767 (t refpos)))))
15768 ((org-at-item-p)
15769 (goto-char
15770 (if (eq special t)
15771 (cond ((> pos (match-end 4)) (match-end 4))
15772 ((= pos (point)) (match-end 4))
15773 (t (point)))
15774 (cond ((> pos (point)) (point))
15775 ((not (eq last-command this-command)) (point))
15776 (t (match-end 4))))))))
15777 (org-no-warnings
15778 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
15780 (defun org-end-of-line (&optional arg)
15781 "Go to the end of the line.
15782 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
15783 first attempt, and only move to after the tags when the cursor is already
15784 beyond the end of the headline."
15785 (interactive "P")
15786 (let ((special (if (consp org-special-ctrl-a/e)
15787 (cdr org-special-ctrl-a/e)
15788 org-special-ctrl-a/e)))
15789 (if (or (not special)
15790 (not (org-on-heading-p))
15791 arg)
15792 (call-interactively (if (fboundp 'move-end-of-line)
15793 'move-end-of-line
15794 'end-of-line))
15795 (let ((pos (point)))
15796 (beginning-of-line 1)
15797 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15798 (if (eq special t)
15799 (if (or (< pos (match-beginning 1))
15800 (= pos (match-end 0)))
15801 (goto-char (match-beginning 1))
15802 (goto-char (match-end 0)))
15803 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
15804 (goto-char (match-end 0))
15805 (goto-char (match-beginning 1))))
15806 (call-interactively (if (fboundp 'move-end-of-line)
15807 'move-end-of-line
15808 'end-of-line)))))
15809 (org-no-warnings
15810 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
15812 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
15813 (define-key org-mode-map "\C-e" 'org-end-of-line)
15815 (defun org-backward-sentence (&optional arg)
15816 "Go to beginning of sentence, or beginning of table field.
15817 This will call `backward-sentence' or `org-table-beginning-of-field',
15818 depending on context."
15819 (interactive "P")
15820 (cond
15821 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
15822 (t (call-interactively 'backward-sentence))))
15824 (defun org-forward-sentence (&optional arg)
15825 "Go to end of sentence, or end of table field.
15826 This will call `forward-sentence' or `org-table-end-of-field',
15827 depending on context."
15828 (interactive "P")
15829 (cond
15830 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
15831 (t (call-interactively 'forward-sentence))))
15833 (define-key org-mode-map "\M-a" 'org-backward-sentence)
15834 (define-key org-mode-map "\M-e" 'org-forward-sentence)
15836 (defun org-kill-line (&optional arg)
15837 "Kill line, to tags or end of line."
15838 (interactive "P")
15839 (cond
15840 ((or (not org-special-ctrl-k)
15841 (bolp)
15842 (not (org-on-heading-p)))
15843 (call-interactively 'kill-line))
15844 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
15845 (kill-region (point) (match-beginning 1))
15846 (org-set-tags nil t))
15847 (t (kill-region (point) (point-at-eol)))))
15849 (define-key org-mode-map "\C-k" 'org-kill-line)
15851 (defun org-yank (&optional arg)
15852 "Yank. If the kill is a subtree, treat it specially.
15853 This command will look at the current kill and check if is a single
15854 subtree, or a series of subtrees[1]. If it passes the test, and if the
15855 cursor is at the beginning of a line or after the stars of a currently
15856 empty headline, then the yank is handled specially. How exactly depends
15857 on the value of the following variables, both set by default.
15859 org-yank-folded-subtrees
15860 When set, the subtree(s) will be folded after insertion, but only
15861 if doing so would now swallow text after the yanked text.
15863 org-yank-adjusted-subtrees
15864 When set, the subtree will be promoted or demoted in order to
15865 fit into the local outline tree structure, which means that the level
15866 will be adjusted so that it becomes the smaller one of the two
15867 *visible* surrounding headings.
15869 Any prefix to this command will cause `yank' to be called directly with
15870 no special treatment. In particular, a simple `C-u' prefix will just
15871 plainly yank the text as it is.
15873 \[1] Basically, the test checks if the first non-white line is a heading
15874 and if there are no other headings with fewer stars."
15875 (interactive "P")
15876 (setq this-command 'yank)
15877 (if arg
15878 (call-interactively 'yank)
15879 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
15880 (and (org-kill-is-subtree-p)
15881 (or (bolp)
15882 (and (looking-at "[ \t]*$")
15883 (string-match
15884 "\\`\\*+\\'"
15885 (buffer-substring (point-at-bol) (point)))))))
15886 swallowp)
15887 (cond
15888 ((and subtreep org-yank-folded-subtrees)
15889 (let ((beg (point))
15890 end)
15891 (if (and subtreep org-yank-adjusted-subtrees)
15892 (org-paste-subtree nil nil 'for-yank)
15893 (call-interactively 'yank))
15894 (setq end (point))
15895 (goto-char beg)
15896 (when (and (bolp) subtreep
15897 (not (setq swallowp
15898 (org-yank-folding-would-swallow-text beg end))))
15899 (or (looking-at outline-regexp)
15900 (re-search-forward (concat "^" outline-regexp) end t))
15901 (while (and (< (point) end) (looking-at outline-regexp))
15902 (hide-subtree)
15903 (org-cycle-show-empty-lines 'folded)
15904 (condition-case nil
15905 (outline-forward-same-level 1)
15906 (error (goto-char end)))))
15907 (when swallowp
15908 (message
15909 "Yanked text not folded because that would swallow text"))
15910 (goto-char end)
15911 (skip-chars-forward " \t\n\r")
15912 (beginning-of-line 1)
15913 (push-mark beg 'nomsg)))
15914 ((and subtreep org-yank-adjusted-subtrees)
15915 (let ((beg (point-at-bol)))
15916 (org-paste-subtree nil nil 'for-yank)
15917 (push-mark beg 'nomsg)))
15919 (call-interactively 'yank))))))
15921 (defun org-yank-folding-would-swallow-text (beg end)
15922 "Would hide-subtree at BEG swallow any text after END?"
15923 (let (level)
15924 (save-excursion
15925 (goto-char beg)
15926 (when (or (looking-at outline-regexp)
15927 (re-search-forward (concat "^" outline-regexp) end t))
15928 (setq level (org-outline-level)))
15929 (goto-char end)
15930 (skip-chars-forward " \t\r\n\v\f")
15931 (if (or (eobp)
15932 (and (bolp) (looking-at org-outline-regexp)
15933 (<= (org-outline-level) level)))
15934 nil ; Nothing would be swallowed
15935 t)))) ; something would swallow
15937 (define-key org-mode-map "\C-y" 'org-yank)
15939 (defun org-invisible-p ()
15940 "Check if point is at a character currently not visible."
15941 ;; Early versions of noutline don't have `outline-invisible-p'.
15942 (if (fboundp 'outline-invisible-p)
15943 (outline-invisible-p)
15944 (get-char-property (point) 'invisible)))
15946 (defun org-invisible-p2 ()
15947 "Check if point is at a character currently not visible."
15948 (save-excursion
15949 (if (and (eolp) (not (bobp))) (backward-char 1))
15950 ;; Early versions of noutline don't have `outline-invisible-p'.
15951 (if (fboundp 'outline-invisible-p)
15952 (outline-invisible-p)
15953 (get-char-property (point) 'invisible))))
15955 (defun org-back-to-heading (&optional invisible-ok)
15956 "Call `outline-back-to-heading', but provide a better error message."
15957 (condition-case nil
15958 (outline-back-to-heading invisible-ok)
15959 (error (error "Before first headline at position %d in buffer %s"
15960 (point) (current-buffer)))))
15962 (defun org-before-first-heading-p ()
15963 "Before first heading?"
15964 (save-excursion
15965 (null (re-search-backward "^\\*+ " nil t))))
15967 (defalias 'org-on-heading-p 'outline-on-heading-p)
15968 (defalias 'org-at-heading-p 'outline-on-heading-p)
15969 (defun org-at-heading-or-item-p ()
15970 (or (org-on-heading-p) (org-at-item-p)))
15972 (defun org-on-target-p ()
15973 (or (org-in-regexp org-radio-target-regexp)
15974 (org-in-regexp org-target-regexp)))
15976 (defun org-up-heading-all (arg)
15977 "Move to the heading line of which the present line is a subheading.
15978 This function considers both visible and invisible heading lines.
15979 With argument, move up ARG levels."
15980 (if (fboundp 'outline-up-heading-all)
15981 (outline-up-heading-all arg) ; emacs 21 version of outline.el
15982 (outline-up-heading arg t))) ; emacs 22 version of outline.el
15984 (defun org-up-heading-safe ()
15985 "Move to the heading line of which the present line is a subheading.
15986 This version will not throw an error. It will return the level of the
15987 headline found, or nil if no higher level is found.
15989 Also, this function will be a lot faster than `outline-up-heading',
15990 because it relies on stars being the outline starters. This can really
15991 make a significant difference in outlines with very many siblings."
15992 (let (start-level re)
15993 (org-back-to-heading t)
15994 (setq start-level (funcall outline-level))
15995 (if (equal start-level 1)
15997 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
15998 (if (re-search-backward re nil t)
15999 (funcall outline-level)))))
16001 (defun org-first-sibling-p ()
16002 "Is this heading the first child of its parents?"
16003 (interactive)
16004 (let ((re (concat "^" outline-regexp))
16005 level l)
16006 (unless (org-at-heading-p t)
16007 (error "Not at a heading"))
16008 (setq level (funcall outline-level))
16009 (save-excursion
16010 (if (not (re-search-backward re nil t))
16012 (setq l (funcall outline-level))
16013 (< l level)))))
16015 (defun org-goto-sibling (&optional previous)
16016 "Goto the next sibling, even if it is invisible.
16017 When PREVIOUS is set, go to the previous sibling instead. Returns t
16018 when a sibling was found. When none is found, return nil and don't
16019 move point."
16020 (let ((fun (if previous 're-search-backward 're-search-forward))
16021 (pos (point))
16022 (re (concat "^" outline-regexp))
16023 level l)
16024 (when (condition-case nil (org-back-to-heading t) (error nil))
16025 (setq level (funcall outline-level))
16026 (catch 'exit
16027 (or previous (forward-char 1))
16028 (while (funcall fun re nil t)
16029 (setq l (funcall outline-level))
16030 (when (< l level) (goto-char pos) (throw 'exit nil))
16031 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
16032 (goto-char pos)
16033 nil))))
16035 (defun org-show-siblings ()
16036 "Show all siblings of the current headline."
16037 (save-excursion
16038 (while (org-goto-sibling) (org-flag-heading nil)))
16039 (save-excursion
16040 (while (org-goto-sibling 'previous)
16041 (org-flag-heading nil))))
16043 (defun org-show-hidden-entry ()
16044 "Show an entry where even the heading is hidden."
16045 (save-excursion
16046 (org-show-entry)))
16048 (defun org-flag-heading (flag &optional entry)
16049 "Flag the current heading. FLAG non-nil means make invisible.
16050 When ENTRY is non-nil, show the entire entry."
16051 (save-excursion
16052 (org-back-to-heading t)
16053 ;; Check if we should show the entire entry
16054 (if entry
16055 (progn
16056 (org-show-entry)
16057 (save-excursion
16058 (and (outline-next-heading)
16059 (org-flag-heading nil))))
16060 (outline-flag-region (max (point-min) (1- (point)))
16061 (save-excursion (outline-end-of-heading) (point))
16062 flag))))
16064 (defun org-forward-same-level (arg)
16065 "Move forward to the ARG'th subheading at same level as this one.
16066 Stop at the first and last subheadings of a superior heading.
16067 This is like outline-forward-same-level, but invisible headings are ok."
16068 (interactive "p")
16069 (org-back-to-heading t)
16070 (while (> arg 0)
16071 (let ((point-to-move-to (save-excursion
16072 (org-get-next-sibling))))
16073 (if point-to-move-to
16074 (progn
16075 (goto-char point-to-move-to)
16076 (setq arg (1- arg)))
16077 (progn
16078 (setq arg 0)
16079 (error "No following same-level heading"))))))
16081 (defun org-get-next-sibling ()
16082 "Move to next heading of the same level, and return point.
16083 If there is no such heading, return nil.
16084 This is like outline-next-sibling, but invisible headings are ok."
16085 (let ((level (funcall outline-level)))
16086 (outline-next-heading)
16087 (while (and (not (eobp)) (> (funcall outline-level) level))
16088 (outline-next-heading))
16089 (if (or (eobp) (< (funcall outline-level) level))
16091 (point))))
16093 (defun org-end-of-subtree (&optional invisible-OK to-heading)
16094 ;; This is an exact copy of the original function, but it uses
16095 ;; `org-back-to-heading', to make it work also in invisible
16096 ;; trees. And is uses an invisible-OK argument.
16097 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
16098 (org-back-to-heading invisible-OK)
16099 (let ((first t)
16100 (level (funcall outline-level)))
16101 (while (and (not (eobp))
16102 (or first (> (funcall outline-level) level)))
16103 (setq first nil)
16104 (outline-next-heading))
16105 (unless to-heading
16106 (if (memq (preceding-char) '(?\n ?\^M))
16107 (progn
16108 ;; Go to end of line before heading
16109 (forward-char -1)
16110 (if (memq (preceding-char) '(?\n ?\^M))
16111 ;; leave blank line before heading
16112 (forward-char -1))))))
16113 (point))
16115 (defun org-show-subtree ()
16116 "Show everything after this heading at deeper levels."
16117 (outline-flag-region
16118 (point)
16119 (save-excursion
16120 (outline-end-of-subtree) (outline-next-heading) (point))
16121 nil))
16123 (defun org-show-entry ()
16124 "Show the body directly following this heading.
16125 Show the heading too, if it is currently invisible."
16126 (interactive)
16127 (save-excursion
16128 (condition-case nil
16129 (progn
16130 (org-back-to-heading t)
16131 (outline-flag-region
16132 (max (point-min) (1- (point)))
16133 (save-excursion
16134 (if (re-search-forward
16135 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
16136 (match-beginning 1)
16137 (point-max)))
16138 nil))
16139 (error nil))))
16141 (defun org-make-options-regexp (kwds &optional extra)
16142 "Make a regular expression for keyword lines."
16143 (concat
16145 "#?[ \t]*\\+\\("
16146 (mapconcat 'regexp-quote kwds "\\|")
16147 (if extra (concat "\\|" extra))
16148 "\\):[ \t]*"
16149 "\\(.+\\)"))
16151 ;; Make isearch reveal the necessary context
16152 (defun org-isearch-end ()
16153 "Reveal context after isearch exits."
16154 (when isearch-success ; only if search was successful
16155 (if (featurep 'xemacs)
16156 ;; Under XEmacs, the hook is run in the correct place,
16157 ;; we directly show the context.
16158 (org-show-context 'isearch)
16159 ;; In Emacs the hook runs *before* restoring the overlays.
16160 ;; So we have to use a one-time post-command-hook to do this.
16161 ;; (Emacs 22 has a special variable, see function `org-mode')
16162 (unless (and (boundp 'isearch-mode-end-hook-quit)
16163 isearch-mode-end-hook-quit)
16164 ;; Only when the isearch was not quitted.
16165 (org-add-hook 'post-command-hook 'org-isearch-post-command
16166 'append 'local)))))
16168 (defun org-isearch-post-command ()
16169 "Remove self from hook, and show context."
16170 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
16171 (org-show-context 'isearch))
16174 ;;;; Integration with and fixes for other packages
16176 ;;; Imenu support
16178 (defvar org-imenu-markers nil
16179 "All markers currently used by Imenu.")
16180 (make-variable-buffer-local 'org-imenu-markers)
16182 (defun org-imenu-new-marker (&optional pos)
16183 "Return a new marker for use by Imenu, and remember the marker."
16184 (let ((m (make-marker)))
16185 (move-marker m (or pos (point)))
16186 (push m org-imenu-markers)
16189 (defun org-imenu-get-tree ()
16190 "Produce the index for Imenu."
16191 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
16192 (setq org-imenu-markers nil)
16193 (let* ((n org-imenu-depth)
16194 (re (concat "^" outline-regexp))
16195 (subs (make-vector (1+ n) nil))
16196 (last-level 0)
16197 m level head)
16198 (save-excursion
16199 (save-restriction
16200 (widen)
16201 (goto-char (point-max))
16202 (while (re-search-backward re nil t)
16203 (setq level (org-reduced-level (funcall outline-level)))
16204 (when (<= level n)
16205 (looking-at org-complex-heading-regexp)
16206 (setq head (org-link-display-format
16207 (org-match-string-no-properties 4))
16208 m (org-imenu-new-marker))
16209 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
16210 (if (>= level last-level)
16211 (push (cons head m) (aref subs level))
16212 (push (cons head (aref subs (1+ level))) (aref subs level))
16213 (loop for i from (1+ level) to n do (aset subs i nil)))
16214 (setq last-level level)))))
16215 (aref subs 1)))
16217 (eval-after-load "imenu"
16218 '(progn
16219 (add-hook 'imenu-after-jump-hook
16220 (lambda ()
16221 (if (eq major-mode 'org-mode)
16222 (org-show-context 'org-goto))))))
16224 (defun org-link-display-format (link)
16225 "Replace a link with either the description, or the link target
16226 if no description is present"
16227 (save-match-data
16228 (if (string-match org-bracket-link-analytic-regexp link)
16229 (replace-match (or (match-string 5 link)
16230 (concat (match-string 1 link)
16231 (match-string 3 link)))
16232 nil nil link)
16233 link)))
16235 ;; Speedbar support
16237 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
16238 "Overlay marking the agenda restriction line in speedbar.")
16239 (org-overlay-put org-speedbar-restriction-lock-overlay
16240 'face 'org-agenda-restriction-lock)
16241 (org-overlay-put org-speedbar-restriction-lock-overlay
16242 'help-echo "Agendas are currently limited to this item.")
16243 (org-detach-overlay org-speedbar-restriction-lock-overlay)
16245 (defun org-speedbar-set-agenda-restriction ()
16246 "Restrict future agenda commands to the location at point in speedbar.
16247 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
16248 (interactive)
16249 (require 'org-agenda)
16250 (let (p m tp np dir txt)
16251 (cond
16252 ((setq p (text-property-any (point-at-bol) (point-at-eol)
16253 'org-imenu t))
16254 (setq m (get-text-property p 'org-imenu-marker))
16255 (save-excursion
16256 (save-restriction
16257 (set-buffer (marker-buffer m))
16258 (goto-char m)
16259 (org-agenda-set-restriction-lock 'subtree))))
16260 ((setq p (text-property-any (point-at-bol) (point-at-eol)
16261 'speedbar-function 'speedbar-find-file))
16262 (setq tp (previous-single-property-change
16263 (1+ p) 'speedbar-function)
16264 np (next-single-property-change
16265 tp 'speedbar-function)
16266 dir (speedbar-line-directory)
16267 txt (buffer-substring-no-properties (or tp (point-min))
16268 (or np (point-max))))
16269 (save-excursion
16270 (save-restriction
16271 (set-buffer (find-file-noselect
16272 (let ((default-directory dir))
16273 (expand-file-name txt))))
16274 (unless (org-mode-p)
16275 (error "Cannot restrict to non-Org-mode file"))
16276 (org-agenda-set-restriction-lock 'file))))
16277 (t (error "Don't know how to restrict Org-mode's agenda")))
16278 (org-move-overlay org-speedbar-restriction-lock-overlay
16279 (point-at-bol) (point-at-eol))
16280 (setq current-prefix-arg nil)
16281 (org-agenda-maybe-redo)))
16283 (eval-after-load "speedbar"
16284 '(progn
16285 (speedbar-add-supported-extension ".org")
16286 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
16287 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
16288 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
16289 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
16290 (add-hook 'speedbar-visiting-tag-hook
16291 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
16294 ;;; Fixes and Hacks for problems with other packages
16296 ;; Make flyspell not check words in links, to not mess up our keymap
16297 (defun org-mode-flyspell-verify ()
16298 "Don't let flyspell put overlays at active buttons."
16299 (not (get-text-property (point) 'keymap)))
16301 ;; Make `bookmark-jump' show the jump location if it was hidden.
16302 (eval-after-load "bookmark"
16303 '(if (boundp 'bookmark-after-jump-hook)
16304 ;; We can use the hook
16305 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
16306 ;; Hook not available, use advice
16307 (defadvice bookmark-jump (after org-make-visible activate)
16308 "Make the position visible."
16309 (org-bookmark-jump-unhide))))
16311 ;; Make sure saveplace show the location if it was hidden
16312 (eval-after-load "saveplace"
16313 '(defadvice save-place-find-file-hook (after org-make-visible activate)
16314 "Make the position visible."
16315 (org-bookmark-jump-unhide)))
16317 (defun org-bookmark-jump-unhide ()
16318 "Unhide the current position, to show the bookmark location."
16319 (and (org-mode-p)
16320 (or (org-invisible-p)
16321 (save-excursion (goto-char (max (point-min) (1- (point))))
16322 (org-invisible-p)))
16323 (org-show-context 'bookmark-jump)))
16325 ;; Make session.el ignore our circular variable
16326 (eval-after-load "session"
16327 '(add-to-list 'session-globals-exclude 'org-mark-ring))
16329 ;;;; Experimental code
16331 (defun org-closed-in-range ()
16332 "Sparse tree of items closed in a certain time range.
16333 Still experimental, may disappear in the future."
16334 (interactive)
16335 ;; Get the time interval from the user.
16336 (let* ((time1 (time-to-seconds
16337 (org-read-date nil 'to-time nil "Starting date: ")))
16338 (time2 (time-to-seconds
16339 (org-read-date nil 'to-time nil "End date:")))
16340 ;; callback function
16341 (callback (lambda ()
16342 (let ((time
16343 (time-to-seconds
16344 (apply 'encode-time
16345 (org-parse-time-string
16346 (match-string 1))))))
16347 ;; check if time in interval
16348 (and (>= time time1) (<= time time2))))))
16349 ;; make tree, check each match with the callback
16350 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
16352 ;;;; Finish up
16354 (provide 'org)
16356 (run-hooks 'org-load-hook)
16358 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
16360 ;;; org.el ends here