Reload: New key, works also in the Agenda
[org-mode.git] / lisp / org.el
blob1eec5bac89faffa47b9953e2d11a64b88d435a98
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.26trans
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.26trans"
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 ((= dcst ?p) '<)
6252 (t nil)))))
6253 (message "Sorting entries...done")))
6255 (defun org-do-sort (table what &optional with-case sorting-type)
6256 "Sort TABLE of WHAT according to SORTING-TYPE.
6257 The user will be prompted for the SORTING-TYPE if the call to this
6258 function does not specify it. WHAT is only for the prompt, to indicate
6259 what is being sorted. The sorting key will be extracted from
6260 the car of the elements of the table.
6261 If WITH-CASE is non-nil, the sorting will be case-sensitive."
6262 (unless sorting-type
6263 (message
6264 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
6265 what)
6266 (setq sorting-type (read-char-exclusive)))
6267 (let ((dcst (downcase sorting-type))
6268 extractfun comparefun)
6269 ;; Define the appropriate functions
6270 (cond
6271 ((= dcst ?n)
6272 (setq extractfun 'string-to-number
6273 comparefun (if (= dcst sorting-type) '< '>)))
6274 ((= dcst ?a)
6275 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
6276 (lambda(x) (downcase (org-sort-remove-invisible x))))
6277 comparefun (if (= dcst sorting-type)
6278 'string<
6279 (lambda (a b) (and (not (string< a b))
6280 (not (string= a b)))))))
6281 ((= dcst ?t)
6282 (setq extractfun
6283 (lambda (x)
6284 (if (or (string-match org-ts-regexp x)
6285 (string-match org-ts-regexp-both x))
6286 (time-to-seconds
6287 (org-time-string-to-time (match-string 0 x)))
6289 comparefun (if (= dcst sorting-type) '< '>)))
6290 (t (error "Invalid sorting type `%c'" sorting-type)))
6292 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
6293 table)
6294 (lambda (a b) (funcall comparefun (car a) (car b))))))
6296 ;;; Editing source examples
6298 (defvar org-exit-edit-mode-map (make-sparse-keymap))
6299 (define-key org-exit-edit-mode-map "\C-c'" 'org-edit-src-exit)
6300 (defvar org-edit-src-force-single-line nil)
6301 (defvar org-edit-src-from-org-mode nil)
6302 (defvar org-edit-src-picture nil)
6304 (define-minor-mode org-exit-edit-mode
6305 "Minor mode installing a single key binding, \"C-c '\" to exit special edit.")
6307 (defun org-edit-src-code ()
6308 "Edit the source code example at point.
6309 An indirect buffer is created, and that buffer is then narrowed to the
6310 example at point and switched to the correct language mode. When done,
6311 exit by killing the buffer with \\[org-edit-src-exit]."
6312 (interactive)
6313 (let ((line (org-current-line))
6314 (case-fold-search t)
6315 (msg (substitute-command-keys
6316 "Edit, then exit with C-c ' (C-c and single quote)"))
6317 (info (org-edit-src-find-region-and-lang))
6318 (org-mode-p (eq major-mode 'org-mode))
6319 beg end lang lang-f single lfmt)
6320 (if (not info)
6322 (setq beg (nth 0 info)
6323 end (nth 1 info)
6324 lang (nth 2 info)
6325 single (nth 3 info)
6326 lfmt (nth 4 info)
6327 lang-f (intern (concat lang "-mode")))
6328 (unless (functionp lang-f)
6329 (error "No such language mode: %s" lang-f))
6330 (goto-line line)
6331 (if (get-buffer "*Org Edit Src Example*")
6332 (kill-buffer "*Org Edit Src Example*"))
6333 (switch-to-buffer (make-indirect-buffer (current-buffer)
6334 "*Org Edit Src Example*"))
6335 (narrow-to-region beg end)
6336 (remove-text-properties beg end '(display nil invisible nil
6337 intangible nil))
6338 (let ((org-inhibit-startup t))
6339 (funcall lang-f))
6340 (set (make-local-variable 'org-edit-src-force-single-line) single)
6341 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
6342 (when lfmt
6343 (set (make-local-variable 'org-coderef-label-format) lfmt))
6344 (when org-mode-p
6345 (goto-char (point-min))
6346 (while (re-search-forward "^," nil t)
6347 (replace-match "")))
6348 (goto-line line)
6349 (org-exit-edit-mode)
6350 (org-set-local 'header-line-format msg)
6351 (message "%s" msg)
6352 t)))
6354 (defun org-edit-fixed-width-region ()
6355 "Edit the fixed-width ascii drawing at point.
6356 This must be a region where each line starts with a colon followed by
6357 a space character.
6358 An indirect buffer is created, and that buffer is then narrowed to the
6359 example at point and switched to artist-mode. When done,
6360 exit by killing the buffer with \\[org-edit-src-exit]."
6361 (interactive)
6362 (let ((line (org-current-line))
6363 (case-fold-search t)
6364 (msg (substitute-command-keys
6365 "Edit, then exit with C-c ' (C-c and single quote)"))
6366 (org-mode-p (eq major-mode 'org-mode))
6367 beg end)
6368 (beginning-of-line 1)
6369 (if (looking-at "[ \t]*[^:\n \t]")
6371 (if (looking-at "[ \t]*\\(\n\\|\\'\\)")
6372 (setq beg (point) end beg)
6373 (save-excursion
6374 (if (re-search-backward "^[ \t]*[^:]" nil 'move)
6375 (setq beg (point-at-bol 2))
6376 (setq beg (point))))
6377 (save-excursion
6378 (if (re-search-forward "^[ \t]*[^:]" nil 'move)
6379 (setq end (1- (match-beginning 0)))
6380 (setq end (point))))
6381 (goto-line line))
6382 (if (get-buffer "*Org Edit Picture*")
6383 (kill-buffer "*Org Edit Picture*"))
6384 (switch-to-buffer (make-indirect-buffer (current-buffer)
6385 "*Org Edit Picture*"))
6386 (narrow-to-region beg end)
6387 (remove-text-properties beg end '(display nil invisible nil
6388 intangible nil))
6389 (when (fboundp 'font-lock-unfontify-region)
6390 (font-lock-unfontify-region (point-min) (point-max)))
6391 (cond
6392 ((eq org-edit-fixed-width-region-mode 'artist-mode)
6393 (fundamental-mode)
6394 (artist-mode 1))
6395 (t (funcall org-edit-fixed-width-region-mode)))
6396 (set (make-local-variable 'org-edit-src-force-single-line) nil)
6397 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
6398 (set (make-local-variable 'org-edit-src-picture) t)
6399 (goto-char (point-min))
6400 (while (re-search-forward "^[ \t]*: ?" nil t)
6401 (replace-match ""))
6402 (goto-line line)
6403 (org-exit-edit-mode)
6404 (org-set-local 'header-line-format msg)
6405 (message "%s" msg)
6406 t)))
6409 (defun org-edit-src-find-region-and-lang ()
6410 "Find the region and language for a local edit.
6411 Return a list with beginning and end of the region, a string representing
6412 the language, a switch telling of the content should be in a single line."
6413 (let ((re-list
6414 (append
6415 org-edit-src-region-extra
6417 ("<src\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</src>" lang)
6418 ("<literal\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</literal>" style)
6419 ("<example>[ \t]*\n?" "\n?[ \t]*</example>" "fundamental")
6420 ("<lisp>[ \t]*\n?" "\n?[ \t]*</lisp>" "emacs-lisp")
6421 ("<perl>[ \t]*\n?" "\n?[ \t]*</perl>" "perl")
6422 ("<python>[ \t]*\n?" "\n?[ \t]*</python>" "python")
6423 ("<ruby>[ \t]*\n?" "\n?[ \t]*</ruby>" "ruby")
6424 ("^#\\+begin_src\\( \\([^ \t\n]+\\)\\)?.*\n" "\n#\\+end_src" 2)
6425 ("^#\\+begin_example.*\n" "\n#\\+end_example" "fundamental")
6426 ("^#\\+html:" "\n" "html" single-line)
6427 ("^#\\+begin_html.*\n" "\n#\\+end_html" "html")
6428 ("^#\\+begin_latex.*\n" "\n#\\+end_latex" "latex")
6429 ("^#\\+latex:" "\n" "latex" single-line)
6430 ("^#\\+begin_ascii.*\n" "\n#\\+end_ascii" "fundamental")
6431 ("^#\\+ascii:" "\n" "ascii" single-line)
6433 (pos (point))
6434 re1 re2 single beg end lang lfmt match-re1)
6435 (catch 'exit
6436 (while (setq entry (pop re-list))
6437 (setq re1 (car entry) re2 (nth 1 entry) lang (nth 2 entry)
6438 single (nth 3 entry))
6439 (save-excursion
6440 (if (or (looking-at re1)
6441 (re-search-backward re1 nil t))
6442 (progn
6443 (setq match-re1 (match-string 0))
6444 (setq beg (match-end 0)
6445 lang (org-edit-src-get-lang lang)
6446 lfmt (org-edit-src-get-label-format match-re1))
6447 (if (and (re-search-forward re2 nil t)
6448 (>= (match-end 0) pos))
6449 (throw 'exit (list beg (match-beginning 0)
6450 lang single lfmt))))
6451 (if (or (looking-at re2)
6452 (re-search-forward re2 nil t))
6453 (progn
6454 (setq end (match-beginning 0))
6455 (if (and (re-search-backward re1 nil t)
6456 (<= (match-beginning 0) pos))
6457 (progn
6458 (setq lfmt (org-edit-src-get-label-format
6459 (match-string 0)))
6460 (throw 'exit
6461 (list (match-end 0) end
6462 (org-edit-src-get-lang lang)
6463 single lfmt))))))))))))
6465 (defun org-edit-src-get-lang (lang)
6466 "Extract the src language."
6467 (let ((m (match-string 0)))
6468 (cond
6469 ((stringp lang) lang)
6470 ((integerp lang) (match-string lang))
6471 ((and (eq lang 'lang)
6472 (string-match "\\<lang=\"\\([^ \t\n\"]+\\)\"" m))
6473 (match-string 1 m))
6474 ((and (eq lang 'style)
6475 (string-match "\\<style=\"\\([^ \t\n\"]+\\)\"" m))
6476 (match-string 1 m))
6477 (t "fundamental"))))
6479 (defun org-edit-src-get-label-format (s)
6480 "Extract the label format."
6481 (save-match-data
6482 (if (string-match "-l[ \t]+\\\\?\"\\([^\t\r\n\"]+\\)\\\\?\"" s)
6483 (match-string 1 s))))
6485 (defun org-edit-src-exit ()
6486 "Exit special edit and protect problematic lines."
6487 (interactive)
6488 (unless (buffer-base-buffer (current-buffer))
6489 (error "This is not an indirect buffer, something is wrong..."))
6490 (unless (> (point-min) 1)
6491 (error "This buffer is not narrowed, something is wrong..."))
6492 (goto-char (point-min))
6493 (if (looking-at "[ \t\n]*\n") (replace-match ""))
6494 (if (re-search-forward "\n[ \t\n]*\\'" nil t) (replace-match ""))
6495 (when (org-bound-and-true-p org-edit-src-force-single-line)
6496 (goto-char (point-min))
6497 (while (re-search-forward "\n" nil t)
6498 (replace-match " "))
6499 (goto-char (point-min))
6500 (if (looking-at "\\s-*") (replace-match " "))
6501 (if (re-search-forward "\\s-+\\'" nil t)
6502 (replace-match "")))
6503 (when (org-bound-and-true-p org-edit-src-from-org-mode)
6504 (goto-char (point-min))
6505 (while (re-search-forward (if (org-mode-p) "^\\(.\\)" "^\\([*#]\\)") nil t)
6506 (replace-match ",\\1"))
6507 (when font-lock-mode
6508 (font-lock-unfontify-region (point-min) (point-max)))
6509 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
6510 (when (org-bound-and-true-p org-edit-src-picture)
6511 (untabify (point-min) (point-max))
6512 (goto-char (point-min))
6513 (while (re-search-forward "^" nil t)
6514 (replace-match ": "))
6515 (when font-lock-mode
6516 (font-lock-unfontify-region (point-min) (point-max)))
6517 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
6518 (kill-buffer (current-buffer))
6519 (and (org-mode-p) (org-restart-font-lock)))
6522 ;;; The orgstruct minor mode
6524 ;; Define a minor mode which can be used in other modes in order to
6525 ;; integrate the org-mode structure editing commands.
6527 ;; This is really a hack, because the org-mode structure commands use
6528 ;; keys which normally belong to the major mode. Here is how it
6529 ;; works: The minor mode defines all the keys necessary to operate the
6530 ;; structure commands, but wraps the commands into a function which
6531 ;; tests if the cursor is currently at a headline or a plain list
6532 ;; item. If that is the case, the structure command is used,
6533 ;; temporarily setting many Org-mode variables like regular
6534 ;; expressions for filling etc. However, when any of those keys is
6535 ;; used at a different location, function uses `key-binding' to look
6536 ;; up if the key has an associated command in another currently active
6537 ;; keymap (minor modes, major mode, global), and executes that
6538 ;; command. There might be problems if any of the keys is otherwise
6539 ;; used as a prefix key.
6541 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
6542 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
6543 ;; addresses this by checking explicitly for both bindings.
6545 (defvar orgstruct-mode-map (make-sparse-keymap)
6546 "Keymap for the minor `orgstruct-mode'.")
6548 (defvar org-local-vars nil
6549 "List of local variables, for use by `orgstruct-mode'")
6551 ;;;###autoload
6552 (define-minor-mode orgstruct-mode
6553 "Toggle the minor more `orgstruct-mode'.
6554 This mode is for using Org-mode structure commands in other modes.
6555 The following key behave as if Org-mode was active, if the cursor
6556 is on a headline, or on a plain list item (both in the definition
6557 of Org-mode).
6559 M-up Move entry/item up
6560 M-down Move entry/item down
6561 M-left Promote
6562 M-right Demote
6563 M-S-up Move entry/item up
6564 M-S-down Move entry/item down
6565 M-S-left Promote subtree
6566 M-S-right Demote subtree
6567 M-q Fill paragraph and items like in Org-mode
6568 C-c ^ Sort entries
6569 C-c - Cycle list bullet
6570 TAB Cycle item visibility
6571 M-RET Insert new heading/item
6572 S-M-RET Insert new TODO heading / Checkbox item
6573 C-c C-c Set tags / toggle checkbox"
6574 nil " OrgStruct" nil
6575 (org-load-modules-maybe)
6576 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
6578 ;;;###autoload
6579 (defun turn-on-orgstruct ()
6580 "Unconditionally turn on `orgstruct-mode'."
6581 (orgstruct-mode 1))
6583 (defun orgstruct++-mode (&optional arg)
6584 "Toggle `orgstruct-mode', the enhanced version of it.
6585 In addition to setting orgstruct-mode, this also exports all indentation and
6586 autofilling variables from org-mode into the buffer. It will also
6587 recognize item context in multiline items.
6588 Note that turning off orgstruct-mode will *not* remove the
6589 indentation/paragraph settings. This can only be done by refreshing the
6590 major mode, for example with \[normal-mode]."
6591 (interactive "P")
6592 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
6593 (if (< arg 1)
6594 (orgstruct-mode -1)
6595 (orgstruct-mode 1)
6596 (let (var val)
6597 (mapc
6598 (lambda (x)
6599 (when (string-match
6600 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6601 (symbol-name (car x)))
6602 (setq var (car x) val (nth 1 x))
6603 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
6604 org-local-vars)
6605 (org-set-local 'orgstruct-is-++ t))))
6607 (defvar orgstruct-is-++ nil
6608 "Is orgstruct-mode in ++ version in the current-buffer?")
6609 (make-variable-buffer-local 'orgstruct-is-++)
6611 ;;;###autoload
6612 (defun turn-on-orgstruct++ ()
6613 "Unconditionally turn on `orgstruct++-mode'."
6614 (orgstruct++-mode 1))
6616 (defun orgstruct-error ()
6617 "Error when there is no default binding for a structure key."
6618 (interactive)
6619 (error "This key has no function outside structure elements"))
6621 (defun orgstruct-setup ()
6622 "Setup orgstruct keymaps."
6623 (let ((nfunc 0)
6624 (bindings
6625 (list
6626 '([(meta up)] org-metaup)
6627 '([(meta down)] org-metadown)
6628 '([(meta left)] org-metaleft)
6629 '([(meta right)] org-metaright)
6630 '([(meta shift up)] org-shiftmetaup)
6631 '([(meta shift down)] org-shiftmetadown)
6632 '([(meta shift left)] org-shiftmetaleft)
6633 '([(meta shift right)] org-shiftmetaright)
6634 '([(shift up)] org-shiftup)
6635 '([(shift down)] org-shiftdown)
6636 '([(shift left)] org-shiftleft)
6637 '([(shift right)] org-shiftright)
6638 '("\C-c\C-c" org-ctrl-c-ctrl-c)
6639 '("\M-q" fill-paragraph)
6640 '("\C-c^" org-sort)
6641 '("\C-c-" org-cycle-list-bullet)))
6642 elt key fun cmd)
6643 (while (setq elt (pop bindings))
6644 (setq nfunc (1+ nfunc))
6645 (setq key (org-key (car elt))
6646 fun (nth 1 elt)
6647 cmd (orgstruct-make-binding fun nfunc key))
6648 (org-defkey orgstruct-mode-map key cmd))
6650 ;; Special treatment needed for TAB and RET
6651 (org-defkey orgstruct-mode-map [(tab)]
6652 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
6653 (org-defkey orgstruct-mode-map "\C-i"
6654 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
6656 (org-defkey orgstruct-mode-map "\M-\C-m"
6657 (orgstruct-make-binding 'org-insert-heading 105
6658 "\M-\C-m" [(meta return)]))
6659 (org-defkey orgstruct-mode-map [(meta return)]
6660 (orgstruct-make-binding 'org-insert-heading 106
6661 [(meta return)] "\M-\C-m"))
6663 (org-defkey orgstruct-mode-map [(shift meta return)]
6664 (orgstruct-make-binding 'org-insert-todo-heading 107
6665 [(meta return)] "\M-\C-m"))
6667 (unless org-local-vars
6668 (setq org-local-vars (org-get-local-variables)))
6672 (defun orgstruct-make-binding (fun n &rest keys)
6673 "Create a function for binding in the structure minor mode.
6674 FUN is the command to call inside a table. N is used to create a unique
6675 command name. KEYS are keys that should be checked in for a command
6676 to execute outside of tables."
6677 (eval
6678 (list 'defun
6679 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6680 '(arg)
6681 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6682 "Outside of structure, run the binding of `"
6683 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6684 "'.")
6685 '(interactive "p")
6686 (list 'if
6687 `(org-context-p 'headline 'item
6688 (and orgstruct-is-++
6689 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
6690 'item-body))
6691 (list 'org-run-like-in-org-mode (list 'quote fun))
6692 (list 'let '(orgstruct-mode)
6693 (list 'call-interactively
6694 (append '(or)
6695 (mapcar (lambda (k)
6696 (list 'key-binding k))
6697 keys)
6698 '('orgstruct-error))))))))
6700 (defun org-context-p (&rest contexts)
6701 "Check if local context is any of CONTEXTS.
6702 Possible values in the list of contexts are `table', `headline', and `item'."
6703 (let ((pos (point)))
6704 (goto-char (point-at-bol))
6705 (prog1 (or (and (memq 'table contexts)
6706 (looking-at "[ \t]*|"))
6707 (and (memq 'headline contexts)
6708 ;;????????? (looking-at "\\*+"))
6709 (looking-at outline-regexp))
6710 (and (memq 'item contexts)
6711 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
6712 (and (memq 'item-body contexts)
6713 (org-in-item-p)))
6714 (goto-char pos))))
6716 (defun org-get-local-variables ()
6717 "Return a list of all local variables in an org-mode buffer."
6718 (let (varlist)
6719 (with-current-buffer (get-buffer-create "*Org tmp*")
6720 (erase-buffer)
6721 (org-mode)
6722 (setq varlist (buffer-local-variables)))
6723 (kill-buffer "*Org tmp*")
6724 (delq nil
6725 (mapcar
6726 (lambda (x)
6727 (setq x
6728 (if (symbolp x)
6729 (list x)
6730 (list (car x) (list 'quote (cdr x)))))
6731 (if (string-match
6732 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6733 (symbol-name (car x)))
6734 x nil))
6735 varlist))))
6737 ;;;###autoload
6738 (defun org-run-like-in-org-mode (cmd)
6739 "Run a command, pretending that the current buffer is in Org-mode.
6740 This will temporarily bind local variables that are typically bound in
6741 Org-mode to the values they have in Org-mode, and then interactively
6742 call CMD."
6743 (org-load-modules-maybe)
6744 (unless org-local-vars
6745 (setq org-local-vars (org-get-local-variables)))
6746 (eval (list 'let org-local-vars
6747 (list 'call-interactively (list 'quote cmd)))))
6749 ;;;; Archiving
6751 (defun org-get-category (&optional pos)
6752 "Get the category applying to position POS."
6753 (get-text-property (or pos (point)) 'org-category))
6755 (defun org-refresh-category-properties ()
6756 "Refresh category text properties in the buffer."
6757 (let ((def-cat (cond
6758 ((null org-category)
6759 (if buffer-file-name
6760 (file-name-sans-extension
6761 (file-name-nondirectory buffer-file-name))
6762 "???"))
6763 ((symbolp org-category) (symbol-name org-category))
6764 (t org-category)))
6765 beg end cat pos optionp)
6766 (org-unmodified
6767 (save-excursion
6768 (save-restriction
6769 (widen)
6770 (goto-char (point-min))
6771 (put-text-property (point) (point-max) 'org-category def-cat)
6772 (while (re-search-forward
6773 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6774 (setq pos (match-end 0)
6775 optionp (equal (char-after (match-beginning 0)) ?#)
6776 cat (org-trim (match-string 2)))
6777 (if optionp
6778 (setq beg (point-at-bol) end (point-max))
6779 (org-back-to-heading t)
6780 (setq beg (point) end (org-end-of-subtree t t)))
6781 (put-text-property beg end 'org-category cat)
6782 (goto-char pos)))))))
6785 ;;;; Link Stuff
6787 ;;; Link abbreviations
6789 (defun org-link-expand-abbrev (link)
6790 "Apply replacements as defined in `org-link-abbrev-alist."
6791 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6792 (let* ((key (match-string 1 link))
6793 (as (or (assoc key org-link-abbrev-alist-local)
6794 (assoc key org-link-abbrev-alist)))
6795 (tag (and (match-end 2) (match-string 3 link)))
6796 rpl)
6797 (if (not as)
6798 link
6799 (setq rpl (cdr as))
6800 (cond
6801 ((symbolp rpl) (funcall rpl tag))
6802 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
6803 ((string-match "%h" rpl)
6804 (replace-match (url-hexify-string (or tag "")) t t rpl))
6805 (t (concat rpl tag)))))
6806 link))
6808 ;;; Storing and inserting links
6810 (defvar org-insert-link-history nil
6811 "Minibuffer history for links inserted with `org-insert-link'.")
6813 (defvar org-stored-links nil
6814 "Contains the links stored with `org-store-link'.")
6816 (defvar org-store-link-plist nil
6817 "Plist with info about the most recently link created with `org-store-link'.")
6819 (defvar org-link-protocols nil
6820 "Link protocols added to Org-mode using `org-add-link-type'.")
6822 (defvar org-store-link-functions nil
6823 "List of functions that are called to create and store a link.
6824 Each function will be called in turn until one returns a non-nil
6825 value. Each function should check if it is responsible for creating
6826 this link (for example by looking at the major mode).
6827 If not, it must exit and return nil.
6828 If yes, it should return a non-nil value after a calling
6829 `org-store-link-props' with a list of properties and values.
6830 Special properties are:
6832 :type The link prefix. like \"http\". This must be given.
6833 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6834 This is obligatory as well.
6835 :description Optional default description for the second pair
6836 of brackets in an Org-mode link. The user can still change
6837 this when inserting this link into an Org-mode buffer.
6839 In addition to these, any additional properties can be specified
6840 and then used in remember templates.")
6842 (defun org-add-link-type (type &optional follow export)
6843 "Add TYPE to the list of `org-link-types'.
6844 Re-compute all regular expressions depending on `org-link-types'
6846 FOLLOW and EXPORT are two functions.
6848 FOLLOW should take the link path as the single argument and do whatever
6849 is necessary to follow the link, for example find a file or display
6850 a mail message.
6852 EXPORT should format the link path for export to one of the export formats.
6853 It should be a function accepting three arguments:
6855 path the path of the link, the text after the prefix (like \"http:\")
6856 desc the description of the link, if any, nil if there was no description
6857 format the export format, a symbol like `html' or `latex'.
6859 The function may use the FORMAT information to return different values
6860 depending on the format. The return value will be put literally into
6861 the exported file.
6862 Org-mode has a built-in default for exporting links. If you are happy with
6863 this default, there is no need to define an export function for the link
6864 type. For a simple example of an export function, see `org-bbdb.el'."
6865 (add-to-list 'org-link-types type t)
6866 (org-make-link-regexps)
6867 (if (assoc type org-link-protocols)
6868 (setcdr (assoc type org-link-protocols) (list follow export))
6869 (push (list type follow export) org-link-protocols)))
6871 ;;;###autoload
6872 (defun org-store-link (arg)
6873 "\\<org-mode-map>Store an org-link to the current location.
6874 This link is added to `org-stored-links' and can later be inserted
6875 into an org-buffer with \\[org-insert-link].
6877 For some link types, a prefix arg is interpreted:
6878 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
6879 For file links, arg negates `org-context-in-file-links'."
6880 (interactive "P")
6881 (org-load-modules-maybe)
6882 (setq org-store-link-plist nil) ; reset
6883 (let (link cpltxt desc description search txt custom-id)
6884 (cond
6886 ((run-hook-with-args-until-success 'org-store-link-functions)
6887 (setq link (plist-get org-store-link-plist :link)
6888 desc (or (plist-get org-store-link-plist :description) link)))
6890 ((equal (buffer-name) "*Org Edit Src Example*")
6891 (let (label gc)
6892 (while (or (not label)
6893 (save-excursion
6894 (save-restriction
6895 (widen)
6896 (goto-char (point-min))
6897 (re-search-forward
6898 (regexp-quote (format org-coderef-label-format label))
6899 nil t))))
6900 (when label (message "Label exists already") (sit-for 2))
6901 (setq label (read-string "Code line label: " label)))
6902 (end-of-line 1)
6903 (setq link (format org-coderef-label-format label))
6904 (setq gc (- 79 (length link)))
6905 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
6906 (insert link)
6907 (setq link (concat "(" label ")") desc nil)))
6909 ((eq major-mode 'calendar-mode)
6910 (let ((cd (calendar-cursor-to-date)))
6911 (setq link
6912 (format-time-string
6913 (car org-time-stamp-formats)
6914 (apply 'encode-time
6915 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6916 nil nil nil))))
6917 (org-store-link-props :type "calendar" :date cd)))
6919 ((eq major-mode 'w3-mode)
6920 (setq cpltxt (if (and (buffer-name)
6921 (not (string-match "Untitled" (buffer-name))))
6922 (buffer-name)
6923 (url-view-url t))
6924 link (org-make-link (url-view-url t)))
6925 (org-store-link-props :type "w3" :url (url-view-url t)))
6927 ((eq major-mode 'w3m-mode)
6928 (setq cpltxt (or w3m-current-title w3m-current-url)
6929 link (org-make-link w3m-current-url))
6930 (org-store-link-props :type "w3m" :url (url-view-url t)))
6932 ((setq search (run-hook-with-args-until-success
6933 'org-create-file-search-functions))
6934 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6935 "::" search))
6936 (setq cpltxt (or description link)))
6938 ((eq major-mode 'image-mode)
6939 (setq cpltxt (concat "file:"
6940 (abbreviate-file-name buffer-file-name))
6941 link (org-make-link cpltxt))
6942 (org-store-link-props :type "image" :file buffer-file-name))
6944 ((eq major-mode 'dired-mode)
6945 ;; link to the file in the current line
6946 (setq cpltxt (concat "file:"
6947 (abbreviate-file-name
6948 (expand-file-name
6949 (dired-get-filename nil t))))
6950 link (org-make-link cpltxt)))
6952 ((and buffer-file-name (org-mode-p))
6953 (setq custom-id (ignore-errors (org-entry-get nil "CUSTOM_ID")))
6954 (cond
6955 ((org-in-regexp "<<\\(.*?\\)>>")
6956 (setq cpltxt
6957 (concat "file:"
6958 (abbreviate-file-name buffer-file-name)
6959 "::" (match-string 1))
6960 link (org-make-link cpltxt)))
6961 ((and (featurep 'org-id)
6962 (or (eq org-link-to-org-use-id t)
6963 (and (eq org-link-to-org-use-id 'create-if-interactive)
6964 (interactive-p))
6965 (and (eq org-link-to-org-use-id 'create-if-interactive-and-no-custom-id)
6966 (interactive-p)
6967 (not custom-id))
6968 (and org-link-to-org-use-id
6969 (condition-case nil
6970 (org-entry-get nil "ID")
6971 (error nil)))))
6972 ;; We can make a link using the ID.
6973 (setq link (condition-case nil
6974 (prog1 (org-id-store-link)
6975 (setq desc (plist-get org-store-link-plist
6976 :description)))
6977 (error
6978 ;; probably before first headline, link to file only
6979 (concat "file:"
6980 (abbreviate-file-name buffer-file-name))))))
6982 ;; Just link to current headline
6983 (setq cpltxt (concat "file:"
6984 (abbreviate-file-name buffer-file-name)))
6985 ;; Add a context search string
6986 (when (org-xor org-context-in-file-links arg)
6987 (setq txt (cond
6988 ((org-on-heading-p) nil)
6989 ((org-region-active-p)
6990 (buffer-substring (region-beginning) (region-end)))
6991 (t nil)))
6992 (when (or (null txt) (string-match "\\S-" txt))
6993 (setq cpltxt
6994 (concat cpltxt "::"
6995 (condition-case nil
6996 (org-make-org-heading-search-string txt)
6997 (error "")))
6998 desc "NONE")))
6999 (if (string-match "::\\'" cpltxt)
7000 (setq cpltxt (substring cpltxt 0 -2)))
7001 (setq link (org-make-link cpltxt)))))
7003 ((buffer-file-name (buffer-base-buffer))
7004 ;; Just link to this file here.
7005 (setq cpltxt (concat "file:"
7006 (abbreviate-file-name
7007 (buffer-file-name (buffer-base-buffer)))))
7008 ;; Add a context string
7009 (when (org-xor org-context-in-file-links arg)
7010 (setq txt (if (org-region-active-p)
7011 (buffer-substring (region-beginning) (region-end))
7012 (buffer-substring (point-at-bol) (point-at-eol))))
7013 ;; Only use search option if there is some text.
7014 (when (string-match "\\S-" txt)
7015 (setq cpltxt
7016 (concat cpltxt "::" (org-make-org-heading-search-string txt))
7017 desc "NONE")))
7018 (setq link (org-make-link cpltxt)))
7020 ((interactive-p)
7021 (error "Cannot link to a buffer which is not visiting a file"))
7023 (t (setq link nil)))
7025 (if (consp link) (setq cpltxt (car link) link (cdr link)))
7026 (setq link (or link cpltxt)
7027 desc (or desc cpltxt))
7028 (if (equal desc "NONE") (setq desc nil))
7030 (if (and (interactive-p) link)
7031 (progn
7032 (setq org-stored-links
7033 (cons (list link desc) org-stored-links))
7034 (message "Stored: %s" (or desc link))
7035 (when custom-id
7036 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
7037 "::#" custom-id))
7038 (setq org-stored-links
7039 (cons (list link desc) org-stored-links))))
7040 (and link (org-make-link-string link desc)))))
7042 (defun org-store-link-props (&rest plist)
7043 "Store link properties, extract names and addresses."
7044 (let (x adr)
7045 (when (setq x (plist-get plist :from))
7046 (setq adr (mail-extract-address-components x))
7047 (setq plist (plist-put plist :fromname (car adr)))
7048 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
7049 (when (setq x (plist-get plist :to))
7050 (setq adr (mail-extract-address-components x))
7051 (setq plist (plist-put plist :toname (car adr)))
7052 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
7053 (let ((from (plist-get plist :from))
7054 (to (plist-get plist :to)))
7055 (when (and from to org-from-is-user-regexp)
7056 (setq plist
7057 (plist-put plist :fromto
7058 (if (string-match org-from-is-user-regexp from)
7059 (concat "to %t")
7060 (concat "from %f"))))))
7061 (setq org-store-link-plist plist))
7063 (defun org-add-link-props (&rest plist)
7064 "Add these properties to the link property list."
7065 (let (key value)
7066 (while plist
7067 (setq key (pop plist) value (pop plist))
7068 (setq org-store-link-plist
7069 (plist-put org-store-link-plist key value)))))
7071 (defun org-email-link-description (&optional fmt)
7072 "Return the description part of an email link.
7073 This takes information from `org-store-link-plist' and formats it
7074 according to FMT (default from `org-email-link-description-format')."
7075 (setq fmt (or fmt org-email-link-description-format))
7076 (let* ((p org-store-link-plist)
7077 (to (plist-get p :toaddress))
7078 (from (plist-get p :fromaddress))
7079 (table
7080 (list
7081 (cons "%c" (plist-get p :fromto))
7082 (cons "%F" (plist-get p :from))
7083 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
7084 (cons "%T" (plist-get p :to))
7085 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
7086 (cons "%s" (plist-get p :subject))
7087 (cons "%m" (plist-get p :message-id)))))
7088 (when (string-match "%c" fmt)
7089 ;; Check if the user wrote this message
7090 (if (and org-from-is-user-regexp from to
7091 (save-match-data (string-match org-from-is-user-regexp from)))
7092 (setq fmt (replace-match "to %t" t t fmt))
7093 (setq fmt (replace-match "from %f" t t fmt))))
7094 (org-replace-escapes fmt table)))
7096 (defun org-make-org-heading-search-string (&optional string heading)
7097 "Make search string for STRING or current headline."
7098 (interactive)
7099 (let ((s (or string (org-get-heading))))
7100 (unless (and string (not heading))
7101 ;; We are using a headline, clean up garbage in there.
7102 (if (string-match org-todo-regexp s)
7103 (setq s (replace-match "" t t s)))
7104 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
7105 (setq s (replace-match "" t t s)))
7106 (setq s (org-trim s))
7107 (if (string-match (concat "^\\(" org-quote-string "\\|"
7108 org-comment-string "\\)") s)
7109 (setq s (replace-match "" t t s)))
7110 (while (string-match org-ts-regexp s)
7111 (setq s (replace-match "" t t s))))
7112 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
7113 (setq s (replace-match " " t t s)))
7114 (or string (setq s (concat "*" s))) ; Add * for headlines
7115 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
7117 (defun org-make-link (&rest strings)
7118 "Concatenate STRINGS."
7119 (apply 'concat strings))
7121 (defun org-make-link-string (link &optional description)
7122 "Make a link with brackets, consisting of LINK and DESCRIPTION."
7123 (unless (string-match "\\S-" link)
7124 (error "Empty link"))
7125 (when (stringp description)
7126 ;; Remove brackets from the description, they are fatal.
7127 (while (string-match "\\[" description)
7128 (setq description (replace-match "{" t t description)))
7129 (while (string-match "\\]" description)
7130 (setq description (replace-match "}" t t description))))
7131 (when (equal (org-link-escape link) description)
7132 ;; No description needed, it is identical
7133 (setq description nil))
7134 (when (and (not description)
7135 (not (equal link (org-link-escape link))))
7136 (setq description (org-extract-attributes link)))
7137 (concat "[[" (org-link-escape link) "]"
7138 (if description (concat "[" description "]") "")
7139 "]"))
7141 (defconst org-link-escape-chars
7142 '((?\ . "%20")
7143 (?\[ . "%5B")
7144 (?\] . "%5D")
7145 (?\340 . "%E0") ; `a
7146 (?\342 . "%E2") ; ^a
7147 (?\347 . "%E7") ; ,c
7148 (?\350 . "%E8") ; `e
7149 (?\351 . "%E9") ; 'e
7150 (?\352 . "%EA") ; ^e
7151 (?\356 . "%EE") ; ^i
7152 (?\364 . "%F4") ; ^o
7153 (?\371 . "%F9") ; `u
7154 (?\373 . "%FB") ; ^u
7155 (?\; . "%3B")
7156 (?? . "%3F")
7157 (?= . "%3D")
7158 (?+ . "%2B")
7160 "Association list of escapes for some characters problematic in links.
7161 This is the list that is used for internal purposes.")
7163 (defvar org-url-encoding-use-url-hexify nil)
7165 (defconst org-link-escape-chars-browser
7166 '((?\ . "%20")) ; 32 for the SPC char
7167 "Association list of escapes for some characters problematic in links.
7168 This is the list that is used before handing over to the browser.")
7170 (defun org-link-escape (text &optional table)
7171 "Escape characters in TEXT that are problematic for links."
7172 (if org-url-encoding-use-url-hexify
7173 (url-hexify-string text)
7174 (setq table (or table org-link-escape-chars))
7175 (when text
7176 (let ((re (mapconcat (lambda (x) (regexp-quote
7177 (char-to-string (car x))))
7178 table "\\|")))
7179 (while (string-match re text)
7180 (setq text
7181 (replace-match
7182 (cdr (assoc (string-to-char (match-string 0 text))
7183 table))
7184 t t text)))
7185 text))))
7187 (defun org-link-unescape (text &optional table)
7188 "Reverse the action of `org-link-escape'."
7189 (if org-url-encoding-use-url-hexify
7190 (url-unhex-string text)
7191 (setq table (or table org-link-escape-chars))
7192 (when text
7193 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
7194 table "\\|")))
7195 (while (string-match re text)
7196 (setq text
7197 (replace-match
7198 (char-to-string (car (rassoc (match-string 0 text) table)))
7199 t t text)))
7200 text))))
7202 (defun org-xor (a b)
7203 "Exclusive or."
7204 (if a (not b) b))
7206 (defun org-fixup-message-id-for-http (s)
7207 "Replace special characters in a message id, so it can be used in an http query."
7208 (while (string-match "<" s)
7209 (setq s (replace-match "%3C" t t s)))
7210 (while (string-match ">" s)
7211 (setq s (replace-match "%3E" t t s)))
7212 (while (string-match "@" s)
7213 (setq s (replace-match "%40" t t s)))
7216 ;;;###autoload
7217 (defun org-insert-link-global ()
7218 "Insert a link like Org-mode does.
7219 This command can be called in any mode to insert a link in Org-mode syntax."
7220 (interactive)
7221 (org-load-modules-maybe)
7222 (org-run-like-in-org-mode 'org-insert-link))
7224 (defun org-insert-link (&optional complete-file link-location)
7225 "Insert a link. At the prompt, enter the link.
7227 Completion can be used to insert any of the link protocol prefixes like
7228 http or ftp in use.
7230 The history can be used to select a link previously stored with
7231 `org-store-link'. When the empty string is entered (i.e. if you just
7232 press RET at the prompt), the link defaults to the most recently
7233 stored link. As SPC triggers completion in the minibuffer, you need to
7234 use M-SPC or C-q SPC to force the insertion of a space character.
7236 You will also be prompted for a description, and if one is given, it will
7237 be displayed in the buffer instead of the link.
7239 If there is already a link at point, this command will allow you to edit link
7240 and description parts.
7242 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
7243 be selected using completion. The path to the file will be relative to the
7244 current directory if the file is in the current directory or a subdirectory.
7245 Otherwise, the link will be the absolute path as completed in the minibuffer
7246 \(i.e. normally ~/path/to/file). You can configure this behavior using the
7247 option `org-link-file-path-type'.
7249 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
7250 the current directory or below.
7252 With three \\[universal-argument] prefixes, negate the meaning of
7253 `org-keep-stored-link-after-insertion'.
7255 If `org-make-link-description-function' is non-nil, this function will be
7256 called with the link target, and the result will be the default
7257 link description.
7259 If the LINK-LOCATION parameter is non-nil, this value will be
7260 used as the link location instead of reading one interactively."
7261 (interactive "P")
7262 (let* ((wcf (current-window-configuration))
7263 (region (if (org-region-active-p)
7264 (buffer-substring (region-beginning) (region-end))))
7265 (remove (and region (list (region-beginning) (region-end))))
7266 (desc region)
7267 tmphist ; byte-compile incorrectly complains about this
7268 (link link-location)
7269 entry file)
7270 (cond
7271 (link-location) ; specified by arg, just use it.
7272 ((org-in-regexp org-bracket-link-regexp 1)
7273 ;; We do have a link at point, and we are going to edit it.
7274 (setq remove (list (match-beginning 0) (match-end 0)))
7275 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
7276 (setq link (read-string "Link: "
7277 (org-link-unescape
7278 (org-match-string-no-properties 1)))))
7279 ((or (org-in-regexp org-angle-link-re)
7280 (org-in-regexp org-plain-link-re))
7281 ;; Convert to bracket link
7282 (setq remove (list (match-beginning 0) (match-end 0))
7283 link (read-string "Link: "
7284 (org-remove-angle-brackets (match-string 0)))))
7285 ((member complete-file '((4) (16)))
7286 ;; Completing read for file names.
7287 (setq file (read-file-name "File: "))
7288 (let ((pwd (file-name-as-directory (expand-file-name ".")))
7289 (pwd1 (file-name-as-directory (abbreviate-file-name
7290 (expand-file-name ".")))))
7291 (cond
7292 ((equal complete-file '(16))
7293 (setq link (org-make-link
7294 "file:"
7295 (abbreviate-file-name (expand-file-name file)))))
7296 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
7297 (setq link (org-make-link "file:" (match-string 1 file))))
7298 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
7299 (expand-file-name file))
7300 (setq link (org-make-link
7301 "file:" (match-string 1 (expand-file-name file)))))
7302 (t (setq link (org-make-link "file:" file))))))
7304 ;; Read link, with completion for stored links.
7305 (with-output-to-temp-buffer "*Org Links*"
7306 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
7307 (when org-stored-links
7308 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
7309 (princ (mapconcat
7310 (lambda (x)
7311 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
7312 (reverse org-stored-links) "\n"))))
7313 (let ((cw (selected-window)))
7314 (select-window (get-buffer-window "*Org Links*"))
7315 (setq truncate-lines t)
7316 (org-fit-window-to-buffer)
7317 (select-window cw))
7318 ;; Fake a link history, containing the stored links.
7319 (setq tmphist (append (mapcar 'car org-stored-links)
7320 org-insert-link-history))
7321 (unwind-protect
7322 (setq link
7323 (let ((org-completion-use-ido nil))
7324 (org-completing-read
7325 "Link: "
7326 (append
7327 (mapcar (lambda (x) (list (concat (car x) ":")))
7328 (append org-link-abbrev-alist-local org-link-abbrev-alist))
7329 (mapcar (lambda (x) (list (concat x ":")))
7330 org-link-types))
7331 nil nil nil
7332 'tmphist
7333 (or (car (car org-stored-links))))))
7334 (set-window-configuration wcf)
7335 (kill-buffer "*Org Links*"))
7336 (setq entry (assoc link org-stored-links))
7337 (or entry (push link org-insert-link-history))
7338 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
7339 (not org-keep-stored-link-after-insertion))
7340 (setq org-stored-links (delq (assoc link org-stored-links)
7341 org-stored-links)))
7342 (setq desc (or desc (nth 1 entry)))))
7344 (if (string-match org-plain-link-re link)
7345 ;; URL-like link, normalize the use of angular brackets.
7346 (setq link (org-make-link (org-remove-angle-brackets link))))
7348 ;; Check if we are linking to the current file with a search option
7349 ;; If yes, simplify the link by using only the search option.
7350 (when (and buffer-file-name
7351 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
7352 (let* ((path (match-string 1 link))
7353 (case-fold-search nil)
7354 (search (match-string 2 link)))
7355 (save-match-data
7356 (if (equal (file-truename buffer-file-name) (file-truename path))
7357 ;; We are linking to this same file, with a search option
7358 (setq link search)))))
7360 ;; Check if we can/should use a relative path. If yes, simplify the link
7361 (when (string-match "^file:\\(.*\\)" link)
7362 (let* ((path (match-string 1 link))
7363 (origpath path)
7364 (case-fold-search nil))
7365 (cond
7366 ((or (eq org-link-file-path-type 'absolute)
7367 (equal complete-file '(16)))
7368 (setq path (abbreviate-file-name (expand-file-name path))))
7369 ((eq org-link-file-path-type 'noabbrev)
7370 (setq path (expand-file-name path)))
7371 ((eq org-link-file-path-type 'relative)
7372 (setq path (file-relative-name path)))
7374 (save-match-data
7375 (if (string-match (concat "^" (regexp-quote
7376 (file-name-as-directory
7377 (expand-file-name "."))))
7378 (expand-file-name path))
7379 ;; We are linking a file with relative path name.
7380 (setq path (substring (expand-file-name path)
7381 (match-end 0)))
7382 (setq path (abbreviate-file-name (expand-file-name path)))))))
7383 (setq link (concat "file:" path))
7384 (if (equal desc origpath)
7385 (setq desc path))))
7387 (if org-make-link-description-function
7388 (setq desc (funcall org-make-link-description-function link desc)))
7390 (setq desc (read-string "Description: " desc))
7391 (unless (string-match "\\S-" desc) (setq desc nil))
7392 (if remove (apply 'delete-region remove))
7393 (insert (org-make-link-string link desc))))
7395 (defun org-completing-read (&rest args)
7396 "Completing-read with SPACE being a normal character."
7397 (let ((minibuffer-local-completion-map
7398 (copy-keymap minibuffer-local-completion-map)))
7399 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
7400 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
7401 (apply 'org-ido-completing-read args)))
7403 (defun org-completing-read-no-ido (&rest args)
7404 (let (org-completion-use-ido)
7405 (apply 'org-completing-read args)))
7407 (defun org-ido-completing-read (&rest args)
7408 "Completing-read using `ido-mode' speedups if available"
7409 (if (and org-completion-use-ido
7410 (fboundp 'ido-completing-read)
7411 (boundp 'ido-mode) ido-mode
7412 (listp (second args)))
7413 (let ((ido-enter-matching-directory nil))
7414 (apply 'ido-completing-read (concat (car args))
7415 (mapcar (lambda (x) (car x)) (nth 1 args))
7416 (cddr args)))
7417 (apply 'completing-read args)))
7419 (defun org-extract-attributes (s)
7420 "Extract the attributes cookie from a string and set as text property."
7421 (let (a attr (start 0) key value)
7422 (save-match-data
7423 (when (string-match "{{\\([^}]+\\)}}$" s)
7424 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
7425 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
7426 (setq key (match-string 1 a) value (match-string 2 a)
7427 start (match-end 0)
7428 attr (plist-put attr (intern key) value))))
7429 (org-add-props s nil 'org-attr attr))
7432 (defun org-extract-attributes-from-string (tag)
7433 (let (key value attr)
7434 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
7435 (setq key (match-string 1 tag) value (match-string 2 tag)
7436 tag (replace-match "" t t tag)
7437 attr (plist-put attr (intern key) value)))
7438 (cons tag attr)))
7440 (defun org-attributes-to-string (plist)
7441 "Format a property list into an HTML attribute list."
7442 (let ((s "") key value)
7443 (while plist
7444 (setq key (pop plist) value (pop plist))
7445 (and value
7446 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
7449 ;;; Opening/following a link
7451 (defvar org-link-search-failed nil)
7453 (defun org-next-link ()
7454 "Move forward to the next link.
7455 If the link is in hidden text, expose it."
7456 (interactive)
7457 (when (and org-link-search-failed (eq this-command last-command))
7458 (goto-char (point-min))
7459 (message "Link search wrapped back to beginning of buffer"))
7460 (setq org-link-search-failed nil)
7461 (let* ((pos (point))
7462 (ct (org-context))
7463 (a (assoc :link ct)))
7464 (if a (goto-char (nth 2 a)))
7465 (if (re-search-forward org-any-link-re nil t)
7466 (progn
7467 (goto-char (match-beginning 0))
7468 (if (org-invisible-p) (org-show-context)))
7469 (goto-char pos)
7470 (setq org-link-search-failed t)
7471 (error "No further link found"))))
7473 (defun org-previous-link ()
7474 "Move backward to the previous link.
7475 If the link is in hidden text, expose it."
7476 (interactive)
7477 (when (and org-link-search-failed (eq this-command last-command))
7478 (goto-char (point-max))
7479 (message "Link search wrapped back to end of buffer"))
7480 (setq org-link-search-failed nil)
7481 (let* ((pos (point))
7482 (ct (org-context))
7483 (a (assoc :link ct)))
7484 (if a (goto-char (nth 1 a)))
7485 (if (re-search-backward org-any-link-re nil t)
7486 (progn
7487 (goto-char (match-beginning 0))
7488 (if (org-invisible-p) (org-show-context)))
7489 (goto-char pos)
7490 (setq org-link-search-failed t)
7491 (error "No further link found"))))
7493 (defun org-translate-link (s)
7494 "Translate a link string if a translation function has been defined."
7495 (if (and org-link-translation-function
7496 (fboundp org-link-translation-function)
7497 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
7498 (progn
7499 (setq s (funcall org-link-translation-function
7500 (match-string 1) (match-string 2)))
7501 (concat (car s) ":" (cdr s)))
7504 (defun org-translate-link-from-planner (type path)
7505 "Translate a link from Emacs Planner syntax so that Org can follow it.
7506 This is still an experimental function, your mileage may vary."
7507 (cond
7508 ((member type '("http" "https" "news" "ftp"))
7509 ;; standard Internet links are the same.
7510 nil)
7511 ((and (equal type "irc") (string-match "^//" path))
7512 ;; Planner has two / at the beginning of an irc link, we have 1.
7513 ;; We should have zero, actually....
7514 (setq path (substring path 1)))
7515 ((and (equal type "lisp") (string-match "^/" path))
7516 ;; Planner has a slash, we do not.
7517 (setq type "elisp" path (substring path 1)))
7518 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
7519 ;; A typical message link. Planner has the id after the fina slash,
7520 ;; we separate it with a hash mark
7521 (setq path (concat (match-string 1 path) "#"
7522 (org-remove-angle-brackets (match-string 2 path)))))
7524 (cons type path))
7526 (defun org-find-file-at-mouse (ev)
7527 "Open file link or URL at mouse."
7528 (interactive "e")
7529 (mouse-set-point ev)
7530 (org-open-at-point 'in-emacs))
7532 (defun org-open-at-mouse (ev)
7533 "Open file link or URL at mouse."
7534 (interactive "e")
7535 (mouse-set-point ev)
7536 (if (eq major-mode 'org-agenda-mode)
7537 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
7538 (org-open-at-point))
7540 (defvar org-window-config-before-follow-link nil
7541 "The window configuration before following a link.
7542 This is saved in case the need arises to restore it.")
7544 (defvar org-open-link-marker (make-marker)
7545 "Marker pointing to the location where `org-open-at-point; was called.")
7547 ;;;###autoload
7548 (defun org-open-at-point-global ()
7549 "Follow a link like Org-mode does.
7550 This command can be called in any mode to follow a link that has
7551 Org-mode syntax."
7552 (interactive)
7553 (org-run-like-in-org-mode 'org-open-at-point))
7555 ;;;###autoload
7556 (defun org-open-link-from-string (s &optional arg)
7557 "Open a link in the string S, as if it was in Org-mode."
7558 (interactive "sLink: \nP")
7559 (let ((reference-buffer (current-buffer)))
7560 (with-temp-buffer
7561 (let ((org-inhibit-startup t))
7562 (org-mode)
7563 (insert s)
7564 (goto-char (point-min))
7565 (org-open-at-point arg reference-buffer)))))
7567 (defun org-open-at-point (&optional in-emacs reference-buffer)
7568 "Open link at or after point.
7569 If there is no link at point, this function will search forward up to
7570 the end of the current line.
7571 Normally, files will be opened by an appropriate application. If the
7572 optional argument IN-EMACS is non-nil, Emacs will visit the file.
7573 With a double prefix argument, try to open outside of Emacs, in the
7574 application the system uses for this file type."
7575 (interactive "P")
7576 (org-load-modules-maybe)
7577 (move-marker org-open-link-marker (point))
7578 (setq org-window-config-before-follow-link (current-window-configuration))
7579 (org-remove-occur-highlights nil nil t)
7580 (cond
7581 ((org-at-timestamp-p t) (org-follow-timestamp-link))
7582 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
7583 (org-footnote-action))
7585 (let (type path link line search (pos (point)))
7586 (catch 'match
7587 (save-excursion
7588 (skip-chars-forward "^]\n\r")
7589 (when (org-in-regexp org-bracket-link-regexp)
7590 (setq link (org-extract-attributes
7591 (org-link-unescape (org-match-string-no-properties 1))))
7592 (while (string-match " *\n *" link)
7593 (setq link (replace-match " " t t link)))
7594 (setq link (org-link-expand-abbrev link))
7595 (cond
7596 ((or (file-name-absolute-p link)
7597 (string-match "^\\.\\.?/" link))
7598 (setq type "file" path link))
7599 ((string-match org-link-re-with-space3 link)
7600 (setq type (match-string 1 link) path (match-string 2 link)))
7601 (t (setq type "thisfile" path link)))
7602 (throw 'match t)))
7604 (when (get-text-property (point) 'org-linked-text)
7605 (setq type "thisfile"
7606 pos (if (get-text-property (1+ (point)) 'org-linked-text)
7607 (1+ (point)) (point))
7608 path (buffer-substring
7609 (previous-single-property-change pos 'org-linked-text)
7610 (next-single-property-change pos 'org-linked-text)))
7611 (throw 'match t))
7613 (save-excursion
7614 (when (or (org-in-regexp org-angle-link-re)
7615 (org-in-regexp org-plain-link-re))
7616 (setq type (match-string 1) path (match-string 2))
7617 (throw 'match t)))
7618 (save-excursion
7619 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
7620 (setq type "tags"
7621 path (match-string 1))
7622 (while (string-match ":" path)
7623 (setq path (replace-match "+" t t path)))
7624 (throw 'match t)))
7625 (when (org-in-regexp "<\\([^><\n]+\\)>")
7626 (setq type "tree-match"
7627 path (match-string 1))
7628 (throw 'match t)))
7629 (unless path
7630 (error "No link found"))
7632 ;; switch back to reference buffer
7633 ;; needed when if called in a temporary buffer through
7634 ;; org-open-link-from-string
7635 (and reference-buffer (switch-to-buffer reference-buffer))
7637 ;; Remove any trailing spaces in path
7638 (if (string-match " +\\'" path)
7639 (setq path (replace-match "" t t path)))
7640 (if (and org-link-translation-function
7641 (fboundp org-link-translation-function))
7642 ;; Check if we need to translate the link
7643 (let ((tmp (funcall org-link-translation-function type path)))
7644 (setq type (car tmp) path (cdr tmp))))
7646 (cond
7648 ((assoc type org-link-protocols)
7649 (funcall (nth 1 (assoc type org-link-protocols)) path))
7651 ((equal type "mailto")
7652 (let ((cmd (car org-link-mailto-program))
7653 (args (cdr org-link-mailto-program)) args1
7654 (address path) (subject "") a)
7655 (if (string-match "\\(.*\\)::\\(.*\\)" path)
7656 (setq address (match-string 1 path)
7657 subject (org-link-escape (match-string 2 path))))
7658 (while args
7659 (cond
7660 ((not (stringp (car args))) (push (pop args) args1))
7661 (t (setq a (pop args))
7662 (if (string-match "%a" a)
7663 (setq a (replace-match address t t a)))
7664 (if (string-match "%s" a)
7665 (setq a (replace-match subject t t a)))
7666 (push a args1))))
7667 (apply cmd (nreverse args1))))
7669 ((member type '("http" "https" "ftp" "news"))
7670 (browse-url (concat type ":" (org-link-escape
7671 path org-link-escape-chars-browser))))
7673 ((member type '("message"))
7674 (browse-url (concat type ":" path)))
7676 ((string= type "tags")
7677 (org-tags-view in-emacs path))
7678 ((string= type "thisfile")
7679 (if in-emacs
7680 (switch-to-buffer-other-window
7681 (org-get-buffer-for-internal-link (current-buffer)))
7682 (org-mark-ring-push))
7683 (let ((cmd `(org-link-search
7684 ,path
7685 ,(cond ((equal in-emacs '(4)) 'occur)
7686 ((equal in-emacs '(16)) 'org-occur)
7687 (t nil))
7688 ,pos)))
7689 (condition-case nil (eval cmd)
7690 (error (progn (widen) (eval cmd))))))
7692 ((string= type "tree-match")
7693 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
7695 ((string= type "file")
7696 (if (string-match "::\\([0-9]+\\)\\'" path)
7697 (setq line (string-to-number (match-string 1 path))
7698 path (substring path 0 (match-beginning 0)))
7699 (if (string-match "::\\(.+\\)\\'" path)
7700 (setq search (match-string 1 path)
7701 path (substring path 0 (match-beginning 0)))))
7702 (if (string-match "[*?{]" (file-name-nondirectory path))
7703 (dired path)
7704 (org-open-file path in-emacs line search)))
7706 ((string= type "news")
7707 (require 'org-gnus)
7708 (org-gnus-follow-link path))
7710 ((string= type "shell")
7711 (let ((cmd path))
7712 (if (or (not org-confirm-shell-link-function)
7713 (funcall org-confirm-shell-link-function
7714 (format "Execute \"%s\" in shell? "
7715 (org-add-props cmd nil
7716 'face 'org-warning))))
7717 (progn
7718 (message "Executing %s" cmd)
7719 (shell-command cmd))
7720 (error "Abort"))))
7722 ((string= type "elisp")
7723 (let ((cmd path))
7724 (if (or (not org-confirm-elisp-link-function)
7725 (funcall org-confirm-elisp-link-function
7726 (format "Execute \"%s\" as elisp? "
7727 (org-add-props cmd nil
7728 'face 'org-warning))))
7729 (message "%s => %s" cmd
7730 (if (equal (string-to-char cmd) ?\()
7731 (eval (read cmd))
7732 (call-interactively (read cmd))))
7733 (error "Abort"))))
7736 (browse-url-at-point))))))
7737 (move-marker org-open-link-marker nil)
7738 (run-hook-with-args 'org-follow-link-hook))
7740 ;;;; Time estimates
7742 (defun org-get-effort (&optional pom)
7743 "Get the effort estimate for the current entry."
7744 (org-entry-get pom org-effort-property))
7746 ;;; File search
7748 (defvar org-create-file-search-functions nil
7749 "List of functions to construct the right search string for a file link.
7750 These functions are called in turn with point at the location to
7751 which the link should point.
7753 A function in the hook should first test if it would like to
7754 handle this file type, for example by checking the major-mode or
7755 the file extension. If it decides not to handle this file, it
7756 should just return nil to give other functions a chance. If it
7757 does handle the file, it must return the search string to be used
7758 when following the link. The search string will be part of the
7759 file link, given after a double colon, and `org-open-at-point'
7760 will automatically search for it. If special measures must be
7761 taken to make the search successful, another function should be
7762 added to the companion hook `org-execute-file-search-functions',
7763 which see.
7765 A function in this hook may also use `setq' to set the variable
7766 `description' to provide a suggestion for the descriptive text to
7767 be used for this link when it gets inserted into an Org-mode
7768 buffer with \\[org-insert-link].")
7770 (defvar org-execute-file-search-functions nil
7771 "List of functions to execute a file search triggered by a link.
7773 Functions added to this hook must accept a single argument, the
7774 search string that was part of the file link, the part after the
7775 double colon. The function must first check if it would like to
7776 handle this search, for example by checking the major-mode or the
7777 file extension. If it decides not to handle this search, it
7778 should just return nil to give other functions a chance. If it
7779 does handle the search, it must return a non-nil value to keep
7780 other functions from trying.
7782 Each function can access the current prefix argument through the
7783 variable `current-prefix-argument'. Note that a single prefix is
7784 used to force opening a link in Emacs, so it may be good to only
7785 use a numeric or double prefix to guide the search function.
7787 In case this is needed, a function in this hook can also restore
7788 the window configuration before `org-open-at-point' was called using:
7790 (set-window-configuration org-window-config-before-follow-link)")
7792 (defun org-link-search (s &optional type avoid-pos)
7793 "Search for a link search option.
7794 If S is surrounded by forward slashes, it is interpreted as a
7795 regular expression. In org-mode files, this will create an `org-occur'
7796 sparse tree. In ordinary files, `occur' will be used to list matches.
7797 If the current buffer is in `dired-mode', grep will be used to search
7798 in all files. If AVOID-POS is given, ignore matches near that position."
7799 (let ((case-fold-search t)
7800 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
7801 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
7802 (append '(("") (" ") ("\t") ("\n"))
7803 org-emphasis-alist)
7804 "\\|") "\\)"))
7805 (pos (point))
7806 (pre nil) (post nil)
7807 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
7808 (cond
7809 ;; First check if there are any special
7810 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
7811 ;; Now try the builtin stuff
7812 ((and (equal (string-to-char s0) ?#)
7813 (> (length s0) 1)
7814 (save-excursion
7815 (goto-char (point-min))
7816 (and
7817 (re-search-forward
7818 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
7819 (setq type 'dedicated
7820 pos (match-beginning 0))))
7821 ;; There is an exact target for this
7822 (goto-char pos)
7823 (org-back-to-heading t)))
7824 ((save-excursion
7825 (goto-char (point-min))
7826 (and
7827 (re-search-forward
7828 (concat "<<" (regexp-quote s0) ">>") nil t)
7829 (setq type 'dedicated
7830 pos (match-beginning 0))))
7831 ;; There is an exact target for this
7832 (goto-char pos))
7833 ((and (string-match "^(\\(.*\\))$" s0)
7834 (save-excursion
7835 (goto-char (point-min))
7836 (and
7837 (re-search-forward
7838 (concat "[^[]" (regexp-quote
7839 (format org-coderef-label-format
7840 (match-string 1 s0))))
7841 nil t)
7842 (setq type 'dedicated
7843 pos (1+ (match-beginning 0))))))
7844 ;; There is a coderef target for this
7845 (goto-char pos))
7846 ((string-match "^/\\(.*\\)/$" s)
7847 ;; A regular expression
7848 (cond
7849 ((org-mode-p)
7850 (org-occur (match-string 1 s)))
7851 ;;((eq major-mode 'dired-mode)
7852 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
7853 (t (org-do-occur (match-string 1 s)))))
7855 ;; A normal search strings
7856 (when (equal (string-to-char s) ?*)
7857 ;; Anchor on headlines, post may include tags.
7858 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
7859 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
7860 s (substring s 1)))
7861 (remove-text-properties
7862 0 (length s)
7863 '(face nil mouse-face nil keymap nil fontified nil) s)
7864 ;; Make a series of regular expressions to find a match
7865 (setq words (org-split-string s "[ \n\r\t]+")
7867 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
7868 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
7869 "\\)" markers)
7870 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
7871 re2a (concat "[ \t\r\n]" re2a_)
7872 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
7873 re4 (concat "[^a-zA-Z_]" re4_)
7875 re1 (concat pre re2 post)
7876 re3 (concat pre (if pre re4_ re4) post)
7877 re5 (concat pre ".*" re4)
7878 re2 (concat pre re2)
7879 re2a (concat pre (if pre re2a_ re2a))
7880 re4 (concat pre (if pre re4_ re4))
7881 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7882 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7883 re5 "\\)"
7885 (cond
7886 ((eq type 'org-occur) (org-occur reall))
7887 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7888 (t (goto-char (point-min))
7889 (setq type 'fuzzy)
7890 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
7891 (org-search-not-self 1 re1 nil t)
7892 (org-search-not-self 1 re2 nil t)
7893 (org-search-not-self 1 re2a nil t)
7894 (org-search-not-self 1 re3 nil t)
7895 (org-search-not-self 1 re4 nil t)
7896 (org-search-not-self 1 re5 nil t)
7898 (goto-char (match-beginning 1))
7899 (goto-char pos)
7900 (error "No match")))))
7902 ;; Normal string-search
7903 (goto-char (point-min))
7904 (if (search-forward s nil t)
7905 (goto-char (match-beginning 0))
7906 (error "No match"))))
7907 (and (org-mode-p) (org-show-context 'link-search))
7908 type))
7910 (defun org-search-not-self (group &rest args)
7911 "Execute `re-search-forward', but only accept matches that do not
7912 enclose the position of `org-open-link-marker'."
7913 (let ((m org-open-link-marker))
7914 (catch 'exit
7915 (while (apply 're-search-forward args)
7916 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
7917 (goto-char (match-end group))
7918 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
7919 (> (match-beginning 0) (marker-position m))
7920 (< (match-end 0) (marker-position m)))
7921 (save-match-data
7922 (or (not (org-in-regexp
7923 org-bracket-link-analytic-regexp 1))
7924 (not (match-end 4)) ; no description
7925 (and (<= (match-beginning 4) (point))
7926 (>= (match-end 4) (point))))))
7927 (throw 'exit (point))))))))
7929 (defun org-get-buffer-for-internal-link (buffer)
7930 "Return a buffer to be used for displaying the link target of internal links."
7931 (cond
7932 ((not org-display-internal-link-with-indirect-buffer)
7933 buffer)
7934 ((string-match "(Clone)$" (buffer-name buffer))
7935 (message "Buffer is already a clone, not making another one")
7936 ;; we also do not modify visibility in this case
7937 buffer)
7938 (t ; make a new indirect buffer for displaying the link
7939 (let* ((bn (buffer-name buffer))
7940 (ibn (concat bn "(Clone)"))
7941 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
7942 (with-current-buffer ib (org-overview))
7943 ib))))
7945 (defun org-do-occur (regexp &optional cleanup)
7946 "Call the Emacs command `occur'.
7947 If CLEANUP is non-nil, remove the printout of the regular expression
7948 in the *Occur* buffer. This is useful if the regex is long and not useful
7949 to read."
7950 (occur regexp)
7951 (when cleanup
7952 (let ((cwin (selected-window)) win beg end)
7953 (when (setq win (get-buffer-window "*Occur*"))
7954 (select-window win))
7955 (goto-char (point-min))
7956 (when (re-search-forward "match[a-z]+" nil t)
7957 (setq beg (match-end 0))
7958 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7959 (setq end (1- (match-beginning 0)))))
7960 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
7961 (goto-char (point-min))
7962 (select-window cwin))))
7964 ;;; The mark ring for links jumps
7966 (defvar org-mark-ring nil
7967 "Mark ring for positions before jumps in Org-mode.")
7968 (defvar org-mark-ring-last-goto nil
7969 "Last position in the mark ring used to go back.")
7970 ;; Fill and close the ring
7971 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7972 (loop for i from 1 to org-mark-ring-length do
7973 (push (make-marker) org-mark-ring))
7974 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7975 org-mark-ring)
7977 (defun org-mark-ring-push (&optional pos buffer)
7978 "Put the current position or POS into the mark ring and rotate it."
7979 (interactive)
7980 (setq pos (or pos (point)))
7981 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7982 (move-marker (car org-mark-ring)
7983 (or pos (point))
7984 (or buffer (current-buffer)))
7985 (message "%s"
7986 (substitute-command-keys
7987 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7989 (defun org-mark-ring-goto (&optional n)
7990 "Jump to the previous position in the mark ring.
7991 With prefix arg N, jump back that many stored positions. When
7992 called several times in succession, walk through the entire ring.
7993 Org-mode commands jumping to a different position in the current file,
7994 or to another Org-mode file, automatically push the old position
7995 onto the ring."
7996 (interactive "p")
7997 (let (p m)
7998 (if (eq last-command this-command)
7999 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
8000 (setq p org-mark-ring))
8001 (setq org-mark-ring-last-goto p)
8002 (setq m (car p))
8003 (switch-to-buffer (marker-buffer m))
8004 (goto-char m)
8005 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
8007 (defun org-remove-angle-brackets (s)
8008 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
8009 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
8011 (defun org-add-angle-brackets (s)
8012 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
8013 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
8015 (defun org-remove-double-quotes (s)
8016 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
8017 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
8020 ;;; Following specific links
8022 (defun org-follow-timestamp-link ()
8023 (cond
8024 ((org-at-date-range-p t)
8025 (let ((org-agenda-start-on-weekday)
8026 (t1 (match-string 1))
8027 (t2 (match-string 2)))
8028 (setq t1 (time-to-days (org-time-string-to-time t1))
8029 t2 (time-to-days (org-time-string-to-time t2)))
8030 (org-agenda-list nil t1 (1+ (- t2 t1)))))
8031 ((org-at-timestamp-p t)
8032 (org-agenda-list nil (time-to-days (org-time-string-to-time
8033 (substring (match-string 1) 0 10)))
8035 (t (error "This should not happen"))))
8038 ;;; Following file links
8039 (defvar org-wait nil)
8040 (defun org-open-file (path &optional in-emacs line search)
8041 "Open the file at PATH.
8042 First, this expands any special file name abbreviations. Then the
8043 configuration variable `org-file-apps' is checked if it contains an
8044 entry for this file type, and if yes, the corresponding command is launched.
8046 If no application is found, Emacs simply visits the file.
8048 With optional prefix argument IN-EMACS, Emacs will visit the file.
8049 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
8050 and o use an external application to visit the file.
8052 Optional LINE specifies a line to go to, optional SEARCH a string to
8053 search for. If LINE or SEARCH is given, the file will always be
8054 opened in Emacs.
8055 If the file does not exist, an error is thrown."
8056 (setq in-emacs (or in-emacs line search))
8057 (let* ((file (if (equal path "")
8058 buffer-file-name
8059 (substitute-in-file-name (expand-file-name path))))
8060 (apps (append org-file-apps (org-default-apps)))
8061 (remp (and (assq 'remote apps) (org-file-remote-p file)))
8062 (dirp (if remp nil (file-directory-p file)))
8063 (file (if (and dirp org-open-directory-means-index-dot-org)
8064 (concat (file-name-as-directory file) "index.org")
8065 file))
8066 (a-m-a-p (assq 'auto-mode apps))
8067 (dfile (downcase file))
8068 (old-buffer (current-buffer))
8069 (old-pos (point))
8070 (old-mode major-mode)
8071 ext cmd)
8072 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
8073 (setq ext (match-string 1 dfile))
8074 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
8075 (setq ext (match-string 1 dfile))))
8076 (cond
8077 ((equal in-emacs '(16))
8078 (setq cmd (cdr (assoc 'system apps))))
8079 (in-emacs (setq cmd 'emacs))
8081 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
8082 (and dirp (cdr (assoc 'directory apps)))
8083 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
8084 'string-match)
8085 (cdr (assoc ext apps))
8086 (cdr (assoc t apps))))))
8087 (when (eq cmd 'system)
8088 (setq cmd (cdr (assoc 'system apps))))
8089 (when (eq cmd 'default)
8090 (setq cmd (cdr (assoc t apps))))
8091 (when (eq cmd 'mailcap)
8092 (require 'mailcap)
8093 (mailcap-parse-mailcaps)
8094 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
8095 (command (mailcap-mime-info mime-type)))
8096 (if (stringp command)
8097 (setq cmd command)
8098 (setq cmd 'emacs))))
8099 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
8100 (not (file-exists-p file))
8101 (not org-open-non-existing-files))
8102 (error "No such file: %s" file))
8103 (cond
8104 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
8105 ;; Remove quotes around the file name - we'll use shell-quote-argument.
8106 (while (string-match "['\"]%s['\"]" cmd)
8107 (setq cmd (replace-match "%s" t t cmd)))
8108 (while (string-match "%s" cmd)
8109 (setq cmd (replace-match
8110 (save-match-data
8111 (shell-quote-argument
8112 (convert-standard-filename file)))
8113 t t cmd)))
8114 (save-window-excursion
8115 (start-process-shell-command cmd nil cmd)
8116 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
8118 ((or (stringp cmd)
8119 (eq cmd 'emacs))
8120 (funcall (cdr (assq 'file org-link-frame-setup)) file)
8121 (widen)
8122 (if line (goto-line line)
8123 (if search (org-link-search search))))
8124 ((consp cmd)
8125 (let ((file (convert-standard-filename file)))
8126 (eval cmd)))
8127 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
8128 (and (org-mode-p) (eq old-mode 'org-mode)
8129 (or (not (equal old-buffer (current-buffer)))
8130 (not (equal old-pos (point))))
8131 (org-mark-ring-push old-pos old-buffer))))
8133 (defun org-default-apps ()
8134 "Return the default applications for this operating system."
8135 (cond
8136 ((eq system-type 'darwin)
8137 org-file-apps-defaults-macosx)
8138 ((eq system-type 'windows-nt)
8139 org-file-apps-defaults-windowsnt)
8140 (t org-file-apps-defaults-gnu)))
8142 (defun org-apps-regexp-alist (list &optional add-auto-mode)
8143 "Convert extensions to regular expressions in the cars of LIST.
8144 Also, weed out any non-string entries, because the return value is used
8145 only for regexp matching.
8146 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
8147 point to the symbol `emacs', indicating that the file should
8148 be opened in Emacs."
8149 (append
8150 (delq nil
8151 (mapcar (lambda (x)
8152 (if (not (stringp (car x)))
8154 (if (string-match "\\W" (car x))
8156 (cons (concat "\\." (car x) "\\'") (cdr x)))))
8157 list))
8158 (if add-auto-mode
8159 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
8161 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
8162 (defun org-file-remote-p (file)
8163 "Test whether FILE specifies a location on a remote system.
8164 Return non-nil if the location is indeed remote.
8166 For example, the filename \"/user@host:/foo\" specifies a location
8167 on the system \"/user@host:\"."
8168 (cond ((fboundp 'file-remote-p)
8169 (file-remote-p file))
8170 ((fboundp 'tramp-handle-file-remote-p)
8171 (tramp-handle-file-remote-p file))
8172 ((and (boundp 'ange-ftp-name-format)
8173 (string-match (car ange-ftp-name-format) file))
8175 (t nil)))
8178 ;;;; Refiling
8180 (defun org-get-org-file ()
8181 "Read a filename, with default directory `org-directory'."
8182 (let ((default (or org-default-notes-file remember-data-file)))
8183 (read-file-name (format "File name [%s]: " default)
8184 (file-name-as-directory org-directory)
8185 default)))
8187 (defun org-notes-order-reversed-p ()
8188 "Check if the current file should receive notes in reversed order."
8189 (cond
8190 ((not org-reverse-note-order) nil)
8191 ((eq t org-reverse-note-order) t)
8192 ((not (listp org-reverse-note-order)) nil)
8193 (t (catch 'exit
8194 (let ((all org-reverse-note-order)
8195 entry)
8196 (while (setq entry (pop all))
8197 (if (string-match (car entry) buffer-file-name)
8198 (throw 'exit (cdr entry))))
8199 nil)))))
8201 (defvar org-refile-target-table nil
8202 "The list of refile targets, created by `org-refile'.")
8204 (defvar org-agenda-new-buffers nil
8205 "Buffers created to visit agenda files.")
8207 (defun org-get-refile-targets (&optional default-buffer)
8208 "Produce a table with refile targets."
8209 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
8210 targets txt re files f desc descre fast-path-p level pos0)
8211 (message "Getting targets...")
8212 (with-current-buffer (or default-buffer (current-buffer))
8213 (while (setq entry (pop entries))
8214 (setq files (car entry) desc (cdr entry))
8215 (setq fast-path-p nil)
8216 (cond
8217 ((null files) (setq files (list (current-buffer))))
8218 ((eq files 'org-agenda-files)
8219 (setq files (org-agenda-files 'unrestricted)))
8220 ((and (symbolp files) (fboundp files))
8221 (setq files (funcall files)))
8222 ((and (symbolp files) (boundp files))
8223 (setq files (symbol-value files))))
8224 (if (stringp files) (setq files (list files)))
8225 (cond
8226 ((eq (car desc) :tag)
8227 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
8228 ((eq (car desc) :todo)
8229 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
8230 ((eq (car desc) :regexp)
8231 (setq descre (cdr desc)))
8232 ((eq (car desc) :level)
8233 (setq descre (concat "^\\*\\{" (number-to-string
8234 (if org-odd-levels-only
8235 (1- (* 2 (cdr desc)))
8236 (cdr desc)))
8237 "\\}[ \t]")))
8238 ((eq (car desc) :maxlevel)
8239 (setq fast-path-p t)
8240 (setq descre (concat "^\\*\\{1," (number-to-string
8241 (if org-odd-levels-only
8242 (1- (* 2 (cdr desc)))
8243 (cdr desc)))
8244 "\\}[ \t]")))
8245 (t (error "Bad refiling target description %s" desc)))
8246 (while (setq f (pop files))
8247 (save-excursion
8248 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
8249 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
8250 (setq f (expand-file-name f))
8251 (if (eq org-refile-use-outline-path 'file)
8252 (push (list (file-name-nondirectory f) f nil nil) targets))
8253 (save-excursion
8254 (save-restriction
8255 (widen)
8256 (goto-char (point-min))
8257 (while (re-search-forward descre nil t)
8258 (goto-char (setq pos0 (point-at-bol)))
8259 (catch 'next
8260 (when org-refile-target-verify-function
8261 (save-match-data
8262 (or (funcall org-refile-target-verify-function)
8263 (throw 'next t))))
8264 (when (looking-at org-complex-heading-regexp)
8265 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
8266 txt (org-link-display-format (match-string 4))
8267 re (concat "^" (regexp-quote
8268 (buffer-substring (match-beginning 1)
8269 (match-end 4)))))
8270 (if (match-end 5) (setq re (concat re "[ \t]+"
8271 (regexp-quote
8272 (match-string 5)))))
8273 (setq re (concat re "[ \t]*$"))
8274 (when org-refile-use-outline-path
8275 (setq txt (mapconcat 'org-protect-slash
8276 (append
8277 (if (eq org-refile-use-outline-path 'file)
8278 (list (file-name-nondirectory
8279 (buffer-file-name (buffer-base-buffer))))
8280 (if (eq org-refile-use-outline-path 'full-file-path)
8281 (list (buffer-file-name (buffer-base-buffer)))))
8282 (org-get-outline-path fast-path-p level txt)
8283 (list txt))
8284 "/")))
8285 (push (list txt f re (point)) targets)))
8286 (when (= (point) pos0)
8287 ;; verification function has not moved point
8288 (goto-char (point-at-eol))))))))))
8289 (message "Getting targets...done")
8290 (nreverse targets)))
8292 (defun org-protect-slash (s)
8293 (while (string-match "/" s)
8294 (setq s (replace-match "\\" t t s)))
8297 (defvar org-olpa (make-vector 20 nil))
8299 (defun org-get-outline-path (&optional fastp level heading)
8300 "Return the outline path to the current entry, as a list."
8301 (if fastp
8302 (progn
8303 (if (> level 19)
8304 (error "Outline path failure, more than 19 levels."))
8305 (loop for i from level upto 19 do
8306 (aset org-olpa i nil))
8307 (prog1
8308 (delq nil (append org-olpa nil))
8309 (aset org-olpa level heading)))
8310 (let (rtn)
8311 (save-excursion
8312 (while (org-up-heading-safe)
8313 (when (looking-at org-complex-heading-regexp)
8314 (push (org-match-string-no-properties 4) rtn)))
8315 rtn))))
8317 (defvar org-refile-history nil
8318 "History for refiling operations.")
8320 (defun org-refile (&optional goto default-buffer)
8321 "Move the entry at point to another heading.
8322 The list of target headings is compiled using the information in
8323 `org-refile-targets', which see. This list is created before each use
8324 and will therefore always be up-to-date.
8326 At the target location, the entry is filed as a subitem of the target heading.
8327 Depending on `org-reverse-note-order', the new subitem will either be the
8328 first or the last subitem.
8330 If there is an active region, all entries in that region will be moved.
8331 However, the region must fulfil the requirement that the first heading
8332 is the first one sets the top-level of the moved text - at most siblings
8333 below it are allowed.
8335 With prefix arg GOTO, the command will only visit the target location,
8336 not actually move anything.
8337 With a double prefix `C-u C-u', go to the location where the last refiling
8338 operation has put the subtree.
8340 See also `org-refile-use-outline-path' and `org-completion-use-ido'"
8341 (interactive "P")
8342 (let* ((cbuf (current-buffer))
8343 (regionp (org-region-active-p))
8344 (region-start (and regionp (region-beginning)))
8345 (region-end (and regionp (region-end)))
8346 (region-length (and regionp (- region-end region-start)))
8347 (filename (buffer-file-name (buffer-base-buffer cbuf)))
8348 pos it nbuf file re level reversed)
8349 (when regionp (goto-char region-start)
8350 (unless (org-kill-is-subtree-p
8351 (buffer-substring region-start region-end))
8352 (error "The region is not a (sequence of) subtree(s)")))
8353 (if (equal goto '(16))
8354 (org-refile-goto-last-stored)
8355 (when (setq it (org-refile-get-location
8356 (if goto "Goto: " "Refile to: ") default-buffer
8357 org-refile-allow-creating-parent-nodes))
8358 (setq file (nth 1 it)
8359 re (nth 2 it)
8360 pos (nth 3 it))
8361 (if (and (not goto)
8363 (equal (buffer-file-name) file)
8364 (if regionp
8365 (and (>= pos region-start)
8366 (<= pos region-end))
8367 (and (>= pos (point))
8368 (< pos (save-excursion
8369 (org-end-of-subtree t t))))))
8370 (error "Cannot refile to position inside the tree or region"))
8372 (setq nbuf (or (find-buffer-visiting file)
8373 (find-file-noselect file)))
8374 (if goto
8375 (progn
8376 (switch-to-buffer nbuf)
8377 (goto-char pos)
8378 (org-show-context 'org-goto))
8379 (if regionp
8380 (progn
8381 (kill-new (buffer-substring region-start region-end))
8382 (org-save-markers-in-region region-start region-end))
8383 (org-copy-subtree 1 nil t))
8384 (save-excursion
8385 (set-buffer (setq nbuf (or (find-buffer-visiting file)
8386 (find-file-noselect file))))
8387 (setq reversed (org-notes-order-reversed-p))
8388 (save-excursion
8389 (save-restriction
8390 (widen)
8391 (if pos
8392 (progn
8393 (goto-char pos)
8394 (looking-at outline-regexp)
8395 (setq level (org-get-valid-level (funcall outline-level) 1))
8396 (goto-char
8397 (if reversed
8398 (or (outline-next-heading) (point-max))
8399 (or (save-excursion (outline-get-next-sibling))
8400 (org-end-of-subtree t t)
8401 (point-max)))))
8402 (setq level 1)
8403 (if (not reversed)
8404 (goto-char (point-max))
8405 (goto-char (point-min))
8406 (or (outline-next-heading) (goto-char (point-max)))))
8407 (if (not (bolp)) (newline))
8408 (bookmark-set "org-refile-last-stored")
8409 (org-paste-subtree level))))
8410 (if regionp
8411 (delete-region (point) (+ (point) region-length))
8412 (org-cut-subtree))
8413 (setq org-markers-to-move nil)
8414 (message "Refiled to \"%s\"" (car it))))))
8415 (org-reveal))
8417 (defun org-refile-goto-last-stored ()
8418 "Go to the location where the last refile was stored."
8419 (interactive)
8420 (bookmark-jump "org-refile-last-stored")
8421 (message "This is the location of the last refile"))
8423 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
8424 "Prompt the user for a refile location, using PROMPT."
8425 (let ((org-refile-targets org-refile-targets)
8426 (org-refile-use-outline-path org-refile-use-outline-path))
8427 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
8428 (unless org-refile-target-table
8429 (error "No refile targets"))
8430 (let* ((cbuf (current-buffer))
8431 (partial-completion-mode nil)
8432 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
8433 (cfunc (if (and org-refile-use-outline-path
8434 org-outline-path-complete-in-steps)
8435 'org-olpath-completing-read
8436 'org-ido-completing-read))
8437 (extra (if org-refile-use-outline-path "/" ""))
8438 (filename (and cfn (expand-file-name cfn)))
8439 (tbl (mapcar
8440 (lambda (x)
8441 (if (and (not (member org-refile-use-outline-path
8442 '(file full-file-path)))
8443 (not (equal filename (nth 1 x))))
8444 (cons (concat (car x) extra " ("
8445 (file-name-nondirectory (nth 1 x)) ")")
8446 (cdr x))
8447 (cons (concat (car x) extra) (cdr x))))
8448 org-refile-target-table))
8449 (completion-ignore-case t)
8450 pa answ parent-target child parent)
8451 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
8452 nil 'org-refile-history))
8453 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
8454 (if pa
8456 (when (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
8457 (setq parent (match-string 1 answ)
8458 child (match-string 2 answ))
8459 (setq parent-target (or (assoc parent tbl) (assoc (concat parent "/") tbl)))
8460 (when (and parent-target
8461 (or (eq new-nodes t)
8462 (and (eq new-nodes 'confirm)
8463 (y-or-n-p (format "Create new node \"%s\"? " child)))))
8464 (org-refile-new-child parent-target child))))))
8466 (defun org-refile-new-child (parent-target child)
8467 "Use refile target PARENT-TARGET to add new CHILD below it."
8468 (unless parent-target
8469 (error "Cannot find parent for new node"))
8470 (let ((file (nth 1 parent-target))
8471 (pos (nth 3 parent-target))
8472 level)
8473 (with-current-buffer (or (find-buffer-visiting file)
8474 (find-file-noselect file))
8475 (save-excursion
8476 (save-restriction
8477 (widen)
8478 (if pos
8479 (goto-char pos)
8480 (goto-char (point-max))
8481 (if (not (bolp)) (newline)))
8482 (when (looking-at outline-regexp)
8483 (setq level (funcall outline-level))
8484 (org-end-of-subtree t t))
8485 (org-back-over-empty-lines)
8486 (insert "\n" (make-string
8487 (if pos (org-get-valid-level level 1) 1) ?*)
8488 " " child "\n")
8489 (beginning-of-line 0)
8490 (list (concat (car parent-target) "/" child) file "" (point)))))))
8492 (defun org-olpath-completing-read (prompt collection &rest args)
8493 "Read an outline path like a file name."
8494 (let ((thetable collection)
8495 (org-completion-use-ido nil)) ; does not work with ido.
8496 (apply
8497 'org-ido-completing-read prompt
8498 (lambda (string predicate &optional flag)
8499 (let (rtn r f (l (length string)))
8500 (cond
8501 ((eq flag nil)
8502 ;; try completion
8503 (try-completion string thetable))
8504 ((eq flag t)
8505 ;; all-completions
8506 (setq rtn (all-completions string thetable predicate))
8507 (mapcar
8508 (lambda (x)
8509 (setq r (substring x l))
8510 (if (string-match " ([^)]*)$" x)
8511 (setq f (match-string 0 x))
8512 (setq f ""))
8513 (if (string-match "/" r)
8514 (concat string (substring r 0 (match-end 0)) f)
8516 rtn))
8517 ((eq flag 'lambda)
8518 ;; exact match?
8519 (assoc string thetable)))
8521 args)))
8523 ;;;; Dynamic blocks
8525 (defun org-find-dblock (name)
8526 "Find the first dynamic block with name NAME in the buffer.
8527 If not found, stay at current position and return nil."
8528 (let (pos)
8529 (save-excursion
8530 (goto-char (point-min))
8531 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
8532 nil t)
8533 (match-beginning 0))))
8534 (if pos (goto-char pos))
8535 pos))
8537 (defconst org-dblock-start-re
8538 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
8539 "Matches the startline of a dynamic block, with parameters.")
8541 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
8542 "Matches the end of a dynamic block.")
8544 (defun org-create-dblock (plist)
8545 "Create a dynamic block section, with parameters taken from PLIST.
8546 PLIST must contain a :name entry which is used as name of the block."
8547 (unless (bolp) (newline))
8548 (let ((name (plist-get plist :name)))
8549 (insert "#+BEGIN: " name)
8550 (while plist
8551 (if (eq (car plist) :name)
8552 (setq plist (cddr plist))
8553 (insert " " (prin1-to-string (pop plist)))))
8554 (insert "\n\n#+END:\n")
8555 (beginning-of-line -2)))
8557 (defun org-prepare-dblock ()
8558 "Prepare dynamic block for refresh.
8559 This empties the block, puts the cursor at the insert position and returns
8560 the property list including an extra property :name with the block name."
8561 (unless (looking-at org-dblock-start-re)
8562 (error "Not at a dynamic block"))
8563 (let* ((begdel (1+ (match-end 0)))
8564 (name (org-no-properties (match-string 1)))
8565 (params (append (list :name name)
8566 (read (concat "(" (match-string 3) ")")))))
8567 (unless (re-search-forward org-dblock-end-re nil t)
8568 (error "Dynamic block not terminated"))
8569 (setq params
8570 (append params
8571 (list :content (buffer-substring
8572 begdel (match-beginning 0)))))
8573 (delete-region begdel (match-beginning 0))
8574 (goto-char begdel)
8575 (open-line 1)
8576 params))
8578 (defun org-map-dblocks (&optional command)
8579 "Apply COMMAND to all dynamic blocks in the current buffer.
8580 If COMMAND is not given, use `org-update-dblock'."
8581 (let ((cmd (or command 'org-update-dblock))
8582 pos)
8583 (save-excursion
8584 (goto-char (point-min))
8585 (while (re-search-forward org-dblock-start-re nil t)
8586 (goto-char (setq pos (match-beginning 0)))
8587 (condition-case nil
8588 (funcall cmd)
8589 (error (message "Error during update of dynamic block")))
8590 (goto-char pos)
8591 (unless (re-search-forward org-dblock-end-re nil t)
8592 (error "Dynamic block not terminated"))))))
8594 (defun org-dblock-update (&optional arg)
8595 "User command for updating dynamic blocks.
8596 Update the dynamic block at point. With prefix ARG, update all dynamic
8597 blocks in the buffer."
8598 (interactive "P")
8599 (if arg
8600 (org-update-all-dblocks)
8601 (or (looking-at org-dblock-start-re)
8602 (org-beginning-of-dblock))
8603 (org-update-dblock)))
8605 (defun org-update-dblock ()
8606 "Update the dynamic block at point
8607 This means to empty the block, parse for parameters and then call
8608 the correct writing function."
8609 (save-window-excursion
8610 (let* ((pos (point))
8611 (line (org-current-line))
8612 (params (org-prepare-dblock))
8613 (name (plist-get params :name))
8614 (cmd (intern (concat "org-dblock-write:" name))))
8615 (message "Updating dynamic block `%s' at line %d..." name line)
8616 (funcall cmd params)
8617 (message "Updating dynamic block `%s' at line %d...done" name line)
8618 (goto-char pos))))
8620 (defun org-beginning-of-dblock ()
8621 "Find the beginning of the dynamic block at point.
8622 Error if there is no such block at point."
8623 (let ((pos (point))
8624 beg)
8625 (end-of-line 1)
8626 (if (and (re-search-backward org-dblock-start-re nil t)
8627 (setq beg (match-beginning 0))
8628 (re-search-forward org-dblock-end-re nil t)
8629 (> (match-end 0) pos))
8630 (goto-char beg)
8631 (goto-char pos)
8632 (error "Not in a dynamic block"))))
8634 (defun org-update-all-dblocks ()
8635 "Update all dynamic blocks in the buffer.
8636 This function can be used in a hook."
8637 (when (org-mode-p)
8638 (org-map-dblocks 'org-update-dblock)))
8641 ;;;; Completion
8643 (defconst org-additional-option-like-keywords
8644 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
8645 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
8646 "BEGIN_EXAMPLE" "END_EXAMPLE"
8647 "BEGIN_QUOTE" "END_QUOTE"
8648 "BEGIN_VERSE" "END_VERSE"
8649 "BEGIN_CENTER" "END_CENTER"
8650 "BEGIN_SRC" "END_SRC"
8651 "CATEGORY" "COLUMNS"
8652 "CAPTION" "LABEL" "ATTR_HTML" "ATTR_LaTeX"))
8654 (defcustom org-structure-template-alist
8656 ("s" "#+begin_src ?\n\n#+end_src"
8657 "<src lang=\"?\">\n\n</src>")
8658 ("e" "#+begin_example\n?\n#+end_example"
8659 "<example>\n?\n</example>")
8660 ("q" "#+begin_quote\n?\n#+end_quote"
8661 "<quote>\n?\n</quote>")
8662 ("v" "#+begin_verse\n?\n#+end_verse"
8663 "<verse>\n?\n/verse>")
8664 ("c" "#+begin_center\n?\n#+end_center"
8665 "<center>\n?\n/center>")
8666 ("l" "#+begin_latex\n?\n#+end_latex"
8667 "<literal style=\"latex\">\n?\n</literal>")
8668 ("L" "#+latex: "
8669 "<literal style=\"latex\">?</literal>")
8670 ("h" "#+begin_html\n?\n#+end_html"
8671 "<literal style=\"html\">\n?\n</literal>")
8672 ("H" "#+html: "
8673 "<literal style=\"html\">?</literal>")
8674 ("a" "#+begin_ascii\n?\n#+end_ascii")
8675 ("A" "#+ascii: ")
8676 ("i" "#+include %file ?"
8677 "<include file=%file markup=\"?\">")
8679 "Structure completion elements.
8680 This is a list of abbreviation keys and values. The value gets inserted
8681 it you type @samp{.} followed by the key and then the completion key,
8682 usually `M-TAB'. %file will be replaced by a file name after prompting
8683 for the file using completion.
8684 There are two templates for each key, the first uses the original Org syntax,
8685 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
8686 the default when the /org-mtags.el/ module has been loaded. See also the
8687 variable `org-mtags-prefer-muse-templates'.
8688 This is an experimental feature, it is undecided if it is going to stay in."
8689 :group 'org-completion
8690 :type '(repeat
8691 (string :tag "Key")
8692 (string :tag "Template")
8693 (string :tag "Muse Template")))
8695 (defun org-try-structure-completion ()
8696 "Try to complete a structure template before point.
8697 This looks for strings like \"<e\" on an otherwise empty line and
8698 expands them."
8699 (let ((l (buffer-substring (point-at-bol) (point)))
8701 (when (and (looking-at "[ \t]*$")
8702 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
8703 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
8704 (org-complete-expand-structure-template (+ -1 (point-at-bol)
8705 (match-beginning 1)) a)
8706 t)))
8708 (defun org-complete-expand-structure-template (start cell)
8709 "Expand a structure template."
8710 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
8711 (rpl (nth (if musep 2 1) cell)))
8712 (delete-region start (point))
8713 (when (string-match "\\`#\\+" rpl)
8714 (cond
8715 ((bolp))
8716 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
8717 (delete-region (point-at-bol) (point)))
8718 (t (newline))))
8719 (setq start (point))
8720 (if (string-match "%file" rpl)
8721 (setq rpl (replace-match
8722 (concat
8723 "\""
8724 (save-match-data
8725 (abbreviate-file-name (read-file-name "Include file: ")))
8726 "\"")
8727 t t rpl)))
8728 (insert rpl)
8729 (if (re-search-backward "\\?" start t) (delete-char 1))))
8732 (defun org-complete (&optional arg)
8733 "Perform completion on word at point.
8734 At the beginning of a headline, this completes TODO keywords as given in
8735 `org-todo-keywords'.
8736 If the current word is preceded by a backslash, completes the TeX symbols
8737 that are supported for HTML support.
8738 If the current word is preceded by \"#+\", completes special words for
8739 setting file options.
8740 In the line after \"#+STARTUP:, complete valid keywords.\"
8741 At all other locations, this simply calls the value of
8742 `org-completion-fallback-command'."
8743 (interactive "P")
8744 (org-without-partial-completion
8745 (catch 'exit
8746 (let* ((a nil)
8747 (end (point))
8748 (beg1 (save-excursion
8749 (skip-chars-backward (org-re "[:alnum:]_@"))
8750 (point)))
8751 (beg (save-excursion
8752 (skip-chars-backward "a-zA-Z0-9_:$")
8753 (point)))
8754 (confirm (lambda (x) (stringp (car x))))
8755 (searchhead (equal (char-before beg) ?*))
8756 (struct
8757 (when (and (member (char-before beg1) '(?. ?<))
8758 (setq a (assoc (buffer-substring beg1 (point))
8759 org-structure-template-alist)))
8760 (org-complete-expand-structure-template (1- beg1) a)
8761 (throw 'exit t)))
8762 (tag (and (equal (char-before beg1) ?:)
8763 (equal (char-after (point-at-bol)) ?*)))
8764 (prop (and (equal (char-before beg1) ?:)
8765 (not (equal (char-after (point-at-bol)) ?*))))
8766 (texp (equal (char-before beg) ?\\))
8767 (link (equal (char-before beg) ?\[))
8768 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
8769 beg)
8770 "#+"))
8771 (startup (string-match "^#\\+STARTUP:.*"
8772 (buffer-substring (point-at-bol) (point))))
8773 (completion-ignore-case opt)
8774 (type nil)
8775 (tbl nil)
8776 (table (cond
8777 (opt
8778 (setq type :opt)
8779 (require 'org-exp)
8780 (append
8781 (mapcar
8782 (lambda (x)
8783 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
8784 (cons (match-string 2 x) (match-string 1 x)))
8785 (org-split-string (org-get-current-options) "\n"))
8786 (mapcar 'list org-additional-option-like-keywords)))
8787 (startup
8788 (setq type :startup)
8789 org-startup-options)
8790 (link (append org-link-abbrev-alist-local
8791 org-link-abbrev-alist))
8792 (texp
8793 (setq type :tex)
8794 org-html-entities)
8795 ((string-match "\\`\\*+[ \t]+\\'"
8796 (buffer-substring (point-at-bol) beg))
8797 (setq type :todo)
8798 (mapcar 'list org-todo-keywords-1))
8799 (searchhead
8800 (setq type :searchhead)
8801 (save-excursion
8802 (goto-char (point-min))
8803 (while (re-search-forward org-todo-line-regexp nil t)
8804 (push (list
8805 (org-make-org-heading-search-string
8806 (match-string 3) t))
8807 tbl)))
8808 tbl)
8809 (tag (setq type :tag beg beg1)
8810 (or org-tag-alist (org-get-buffer-tags)))
8811 (prop (setq type :prop beg beg1)
8812 (mapcar 'list (org-buffer-property-keys nil t t)))
8813 (t (progn
8814 (call-interactively org-completion-fallback-command)
8815 (throw 'exit nil)))))
8816 (pattern (buffer-substring-no-properties beg end))
8817 (completion (try-completion pattern table confirm)))
8818 (cond ((eq completion t)
8819 (if (not (assoc (upcase pattern) table))
8820 (message "Already complete")
8821 (if (and (equal type :opt)
8822 (not (member (car (assoc (upcase pattern) table))
8823 org-additional-option-like-keywords)))
8824 (insert (substring (cdr (assoc (upcase pattern) table))
8825 (length pattern)))
8826 (if (memq type '(:tag :prop)) (insert ":")))))
8827 ((null completion)
8828 (message "Can't find completion for \"%s\"" pattern)
8829 (ding))
8830 ((not (string= pattern completion))
8831 (delete-region beg end)
8832 (if (string-match " +$" completion)
8833 (setq completion (replace-match "" t t completion)))
8834 (insert completion)
8835 (if (get-buffer-window "*Completions*")
8836 (delete-window (get-buffer-window "*Completions*")))
8837 (if (assoc completion table)
8838 (if (eq type :todo) (insert " ")
8839 (if (memq type '(:tag :prop)) (insert ":"))))
8840 (if (and (equal type :opt) (assoc completion table))
8841 (message "%s" (substitute-command-keys
8842 "Press \\[org-complete] again to insert example settings"))))
8844 (message "Making completion list...")
8845 (let ((list (sort (all-completions pattern table confirm)
8846 'string<)))
8847 (with-output-to-temp-buffer "*Completions*"
8848 (condition-case nil
8849 ;; Protection needed for XEmacs and emacs 21
8850 (display-completion-list list pattern)
8851 (error (display-completion-list list)))))
8852 (message "Making completion list...%s" "done")))))))
8854 ;;;; TODO, DEADLINE, Comments
8856 (defun org-toggle-comment ()
8857 "Change the COMMENT state of an entry."
8858 (interactive)
8859 (save-excursion
8860 (org-back-to-heading)
8861 (let (case-fold-search)
8862 (if (looking-at (concat outline-regexp
8863 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
8864 (replace-match "" t t nil 1)
8865 (if (looking-at outline-regexp)
8866 (progn
8867 (goto-char (match-end 0))
8868 (insert org-comment-string " ")))))))
8870 (defvar org-last-todo-state-is-todo nil
8871 "This is non-nil when the last TODO state change led to a TODO state.
8872 If the last change removed the TODO tag or switched to DONE, then
8873 this is nil.")
8875 (defvar org-setting-tags nil) ; dynamically skipped
8877 (defun org-parse-local-options (string var)
8878 "Parse STRING for startup setting relevant for variable VAR."
8879 (let ((rtn (symbol-value var))
8880 e opts)
8881 (save-match-data
8882 (if (or (not string) (not (string-match "\\S-" string)))
8884 (setq opts (delq nil (mapcar (lambda (x)
8885 (setq e (assoc x org-startup-options))
8886 (if (eq (nth 1 e) var) e nil))
8887 (org-split-string string "[ \t]+"))))
8888 (if (not opts)
8890 (setq rtn nil)
8891 (while (setq e (pop opts))
8892 (if (not (nth 3 e))
8893 (setq rtn (nth 2 e))
8894 (if (not (listp rtn)) (setq rtn nil))
8895 (push (nth 2 e) rtn)))
8896 rtn)))))
8898 (defvar org-todo-setup-filter-hook nil
8899 "Hook for functions that pre-filter todo specs.
8901 Each function takes a todo spec and returns either `nil' or the spec
8902 transformed into canonical form." )
8904 (defvar org-todo-get-default-hook nil
8905 "Hook for functions that get a default item for todo.
8907 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
8908 `nil' or a string to be used for the todo mark." )
8910 (defvar org-agenda-headline-snapshot-before-repeat)
8911 (defun org-todo (&optional arg)
8912 "Change the TODO state of an item.
8913 The state of an item is given by a keyword at the start of the heading,
8914 like
8915 *** TODO Write paper
8916 *** DONE Call mom
8918 The different keywords are specified in the variable `org-todo-keywords'.
8919 By default the available states are \"TODO\" and \"DONE\".
8920 So for this example: when the item starts with TODO, it is changed to DONE.
8921 When it starts with DONE, the DONE is removed. And when neither TODO nor
8922 DONE are present, add TODO at the beginning of the heading.
8924 With C-u prefix arg, use completion to determine the new state.
8925 With numeric prefix arg, switch to that state.
8926 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
8927 With a tripple C-u prefix, circumvent any state blocking.
8929 For calling through lisp, arg is also interpreted in the following way:
8930 'none -> empty state
8931 \"\"(empty string) -> switch to empty state
8932 'done -> switch to DONE
8933 'nextset -> switch to the next set of keywords
8934 'previousset -> switch to the previous set of keywords
8935 \"WAITING\" -> switch to the specified keyword, but only if it
8936 really is a member of `org-todo-keywords'."
8937 (interactive "P")
8938 (if (equal arg '(16)) (setq arg 'nextset))
8939 (let ((org-blocker-hook org-blocker-hook)
8940 (case-fold-search nil))
8941 (when (equal arg '(64))
8942 (setq arg nil org-blocker-hook nil))
8943 (when (and org-blocker-hook
8944 (org-entry-get nil "NOBLOCKING"))
8945 (setq org-blocker-hook nil))
8946 (save-excursion
8947 (catch 'exit
8948 (org-back-to-heading)
8949 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
8950 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|$\\)"))
8951 (looking-at " *"))
8952 (let* ((match-data (match-data))
8953 (startpos (point-at-bol))
8954 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
8955 (org-log-done org-log-done)
8956 (org-log-repeat org-log-repeat)
8957 (org-todo-log-states org-todo-log-states)
8958 (this (match-string 1))
8959 (hl-pos (match-beginning 0))
8960 (head (org-get-todo-sequence-head this))
8961 (ass (assoc head org-todo-kwd-alist))
8962 (interpret (nth 1 ass))
8963 (done-word (nth 3 ass))
8964 (final-done-word (nth 4 ass))
8965 (last-state (or this ""))
8966 (completion-ignore-case t)
8967 (member (member this org-todo-keywords-1))
8968 (tail (cdr member))
8969 (state (cond
8970 ((and org-todo-key-trigger
8971 (or (and (equal arg '(4))
8972 (eq org-use-fast-todo-selection 'prefix))
8973 (and (not arg) org-use-fast-todo-selection
8974 (not (eq org-use-fast-todo-selection
8975 'prefix)))))
8976 ;; Use fast selection
8977 (org-fast-todo-selection))
8978 ((and (equal arg '(4))
8979 (or (not org-use-fast-todo-selection)
8980 (not org-todo-key-trigger)))
8981 ;; Read a state with completion
8982 (org-ido-completing-read
8983 "State: " (mapcar (lambda(x) (list x))
8984 org-todo-keywords-1)
8985 nil t))
8986 ((eq arg 'right)
8987 (if this
8988 (if tail (car tail) nil)
8989 (car org-todo-keywords-1)))
8990 ((eq arg 'left)
8991 (if (equal member org-todo-keywords-1)
8993 (if this
8994 (nth (- (length org-todo-keywords-1)
8995 (length tail) 2)
8996 org-todo-keywords-1)
8997 (org-last org-todo-keywords-1))))
8998 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
8999 (setq arg nil))) ; hack to fall back to cycling
9000 (arg
9001 ;; user or caller requests a specific state
9002 (cond
9003 ((equal arg "") nil)
9004 ((eq arg 'none) nil)
9005 ((eq arg 'done) (or done-word (car org-done-keywords)))
9006 ((eq arg 'nextset)
9007 (or (car (cdr (member head org-todo-heads)))
9008 (car org-todo-heads)))
9009 ((eq arg 'previousset)
9010 (let ((org-todo-heads (reverse org-todo-heads)))
9011 (or (car (cdr (member head org-todo-heads)))
9012 (car org-todo-heads))))
9013 ((car (member arg org-todo-keywords-1)))
9014 ((nth (1- (prefix-numeric-value arg))
9015 org-todo-keywords-1))))
9016 ((null member) (or head (car org-todo-keywords-1)))
9017 ((equal this final-done-word) nil) ;; -> make empty
9018 ((null tail) nil) ;; -> first entry
9019 ((memq interpret '(type priority))
9020 (if (eq this-command last-command)
9021 (car tail)
9022 (if (> (length tail) 0)
9023 (or done-word (car org-done-keywords))
9024 nil)))
9026 (car tail))))
9027 (state (or
9028 (run-hook-with-args-until-success
9029 'org-todo-get-default-hook state last-state)
9030 state))
9031 (next (if state (concat " " state " ") " "))
9032 (change-plist (list :type 'todo-state-change :from this :to state
9033 :position startpos))
9034 dolog now-done-p)
9035 (when org-blocker-hook
9036 (setq org-last-todo-state-is-todo
9037 (not (member this org-done-keywords)))
9038 (unless (save-excursion
9039 (save-match-data
9040 (run-hook-with-args-until-failure
9041 'org-blocker-hook change-plist)))
9042 (if (interactive-p)
9043 (error "TODO state change from %s to %s blocked" this state)
9044 ;; fail silently
9045 (message "TODO state change from %s to %s blocked" this state)
9046 (throw 'exit nil))))
9047 (store-match-data match-data)
9048 (replace-match next t t)
9049 (unless (pos-visible-in-window-p hl-pos)
9050 (message "TODO state changed to %s" (org-trim next)))
9051 (unless head
9052 (setq head (org-get-todo-sequence-head state)
9053 ass (assoc head org-todo-kwd-alist)
9054 interpret (nth 1 ass)
9055 done-word (nth 3 ass)
9056 final-done-word (nth 4 ass)))
9057 (when (memq arg '(nextset previousset))
9058 (message "Keyword-Set %d/%d: %s"
9059 (- (length org-todo-sets) -1
9060 (length (memq (assoc state org-todo-sets) org-todo-sets)))
9061 (length org-todo-sets)
9062 (mapconcat 'identity (assoc state org-todo-sets) " ")))
9063 (setq org-last-todo-state-is-todo
9064 (not (member state org-done-keywords)))
9065 (setq now-done-p (and (member state org-done-keywords)
9066 (not (member this org-done-keywords))))
9067 (and logging (org-local-logging logging))
9068 (when (and (or org-todo-log-states org-log-done)
9069 (not (memq arg '(nextset previousset))))
9070 ;; we need to look at recording a time and note
9071 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
9072 (nth 2 (assoc this org-todo-log-states))))
9073 (when (and state
9074 (member state org-not-done-keywords)
9075 (not (member this org-not-done-keywords)))
9076 ;; This is now a todo state and was not one before
9077 ;; If there was a CLOSED time stamp, get rid of it.
9078 (org-add-planning-info nil nil 'closed))
9079 (when (and now-done-p org-log-done)
9080 ;; It is now done, and it was not done before
9081 (org-add-planning-info 'closed (org-current-time))
9082 (if (and (not dolog) (eq 'note org-log-done))
9083 (org-add-log-setup 'done state this 'findpos 'note)))
9084 (when (and state dolog)
9085 ;; This is a non-nil state, and we need to log it
9086 (org-add-log-setup 'state state this 'findpos dolog)))
9087 ;; Fixup tag positioning
9088 (org-todo-trigger-tag-changes state)
9089 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
9090 (when org-provide-todo-statistics
9091 (org-update-parent-todo-statistics))
9092 (run-hooks 'org-after-todo-state-change-hook)
9093 (if (and arg (not (member state org-done-keywords)))
9094 (setq head (org-get-todo-sequence-head state)))
9095 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
9096 ;; Do we need to trigger a repeat?
9097 (when now-done-p
9098 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
9099 ;; This is for the agenda, take a snapshot of the headline.
9100 (save-match-data
9101 (setq org-agenda-headline-snapshot-before-repeat
9102 (org-get-heading))))
9103 (org-auto-repeat-maybe state))
9104 ;; Fixup cursor location if close to the keyword
9105 (if (and (outline-on-heading-p)
9106 (not (bolp))
9107 (save-excursion (beginning-of-line 1)
9108 (looking-at org-todo-line-regexp))
9109 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
9110 (progn
9111 (goto-char (or (match-end 2) (match-end 1)))
9112 (and (looking-at " ") (just-one-space))))
9113 (when org-trigger-hook
9114 (save-excursion
9115 (run-hook-with-args 'org-trigger-hook change-plist))))))))
9117 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
9118 "Block turning an entry into a TODO, using the hierarchy.
9119 This checks whether the current task should be blocked from state
9120 changes. Such blocking occurs when:
9122 1. The task has children which are not all in a completed state.
9124 2. A task has a parent with the property :ORDERED:, and there
9125 are siblings prior to the current task with incomplete
9126 status.
9128 3. The parent of the task is blocked because it has siblings that should
9129 be done first, or is child of a block grandparent TODO entry."
9131 (catch 'dont-block
9132 ;; If this is not a todo state change, or if this entry is already DONE,
9133 ;; do not block
9134 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
9135 (member (plist-get change-plist :from)
9136 (cons 'done org-done-keywords))
9137 (member (plist-get change-plist :to)
9138 (cons 'todo org-not-done-keywords)))
9139 (throw 'dont-block t))
9140 ;; If this task has children, and any are undone, it's blocked
9141 (save-excursion
9142 (org-back-to-heading t)
9143 (let ((this-level (funcall outline-level)))
9144 (outline-next-heading)
9145 (let ((child-level (funcall outline-level)))
9146 (while (and (not (eobp))
9147 (> child-level this-level))
9148 ;; this todo has children, check whether they are all
9149 ;; completed
9150 (if (and (not (org-entry-is-done-p))
9151 (org-entry-is-todo-p))
9152 (throw 'dont-block nil))
9153 (outline-next-heading)
9154 (setq child-level (funcall outline-level))))))
9155 ;; Otherwise, if the task's parent has the :ORDERED: property, and
9156 ;; any previous siblings are undone, it's blocked
9157 (save-excursion
9158 (org-back-to-heading t)
9159 (let* ((pos (point))
9160 (parent-pos (and (org-up-heading-safe) (point))))
9161 (if (not parent-pos) (throw 'dont-block t)) ; no parent
9162 (when (and (org-entry-get (point) "ORDERED")
9163 (forward-line 1)
9164 (re-search-forward org-not-done-heading-regexp pos t))
9165 (throw 'dont-block nil)) ; block, there is an older sibling not done.
9166 ;; Search further up the hierarchy, to see if an anchestor is blocked
9167 (while t
9168 (goto-char parent-pos)
9169 (if (not (looking-at org-not-done-heading-regexp))
9170 (throw 'dont-block t)) ; do not block, parent is not a TODO
9171 (setq pos (point))
9172 (setq parent-pos (and (org-up-heading-safe) (point)))
9173 (if (not parent-pos) (throw 'dont-block t)) ; no parent
9174 (when (and (org-entry-get (point) "ORDERED")
9175 (forward-line 1)
9176 (re-search-forward org-not-done-heading-regexp pos t))
9177 (throw 'dont-block nil))))))) ; block, older sibling not done.
9179 (defcustom org-track-ordered-property-with-tag nil
9180 "Should the ORDERED property also be shown as a tag?
9181 The ORDERED property decides if an entry should require subtasks to be
9182 completed in sequence. Since a property is not very visible, setting
9183 this option means that toggling the ORDERED property with the command
9184 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
9185 not relevant for the behavior, but it makes things more visible.
9187 Note that toggling the tag with tags commands will not change the property
9188 and therefore not influence behavior!
9190 This can be t, meaning the tag ORDERED should be used, It can also be a
9191 string to select a different tag for this task."
9192 :group 'org-todo
9193 :type '(choice
9194 (const :tag "No tracking" nil)
9195 (const :tag "Track with ORDERED tag" t)
9196 (string :tag "Use other tag")))
9198 (defun org-toggle-ordered-property ()
9199 "Toggle the ORDERED property of the current entry.
9200 For better visibility, you can track the value of this property with a tag.
9201 See variable `org-track-ordered-property-with-tag'."
9202 (interactive)
9203 (let* ((t1 org-track-ordered-property-with-tag)
9204 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
9205 (save-excursion
9206 (org-back-to-heading)
9207 (if (org-entry-get nil "ORDERED")
9208 (progn
9209 (org-delete-property "ORDERED")
9210 (and tag (org-toggle-tag tag 'off))
9211 (message "Subtasks can be completed in arbitrary order"))
9212 (org-entry-put nil "ORDERED" "t")
9213 (and tag (org-toggle-tag tag 'on))
9214 (message "Subtasks must be completed in sequence")))))
9216 (defvar org-blocked-by-checkboxes) ; dynamically scoped
9217 (defun org-block-todo-from-checkboxes (change-plist)
9218 "Block turning an entry into a TODO, using checkboxes.
9219 This checks whether the current task should be blocked from state
9220 changes because there are uncheckd boxes in this entry."
9221 (catch 'dont-block
9222 ;; If this is not a todo state change, or if this entry is already DONE,
9223 ;; do not block
9224 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
9225 (member (plist-get change-plist :from)
9226 (cons 'done org-done-keywords))
9227 (member (plist-get change-plist :to)
9228 (cons 'todo org-not-done-keywords)))
9229 (throw 'dont-block t))
9230 ;; If this task has checkboxes that are not checked, it's blocked
9231 (save-excursion
9232 (org-back-to-heading t)
9233 (let ((beg (point)) end)
9234 (outline-next-heading)
9235 (setq end (point))
9236 (goto-char beg)
9237 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
9238 end t)
9239 (progn
9240 (if (boundp 'org-blocked-by-checkboxes)
9241 (setq org-blocked-by-checkboxes t))
9242 (throw 'dont-block nil)))))
9243 t)) ; do not block
9245 (defun org-update-parent-todo-statistics ()
9246 "Update any statistics cookie in the parent of the current headline."
9247 (interactive)
9248 (let ((box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
9249 level (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
9250 (catch 'exit
9251 (save-excursion
9252 (setq level (org-up-heading-safe))
9253 (unless (and level
9254 (not (equal (downcase
9255 (or (org-entry-get
9256 nil "COOKIE_DATA")
9257 ""))
9258 "checkbox")))
9259 (throw 'exit nil))
9260 (while (re-search-forward box-re (point-at-eol) t)
9261 (setq cnt-all 0 cnt-done 0 cookie-present t)
9262 (setq is-percent (match-end 2))
9263 (save-match-data
9264 (unless (outline-next-heading) (throw 'exit nil))
9265 (while (looking-at org-todo-line-regexp)
9266 (setq kwd (match-string 2))
9267 (and kwd (setq cnt-all (1+ cnt-all)))
9268 (and (member kwd org-done-keywords)
9269 (setq cnt-done (1+ cnt-done)))
9270 (condition-case nil
9271 (org-forward-same-level 1)
9272 (error (end-of-line 1)))))
9273 (replace-match
9274 (if is-percent
9275 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
9276 (format "[%d/%d]" cnt-done cnt-all))))
9277 (when cookie-present
9278 (run-hook-with-args 'org-after-todo-statistics-hook
9279 cnt-done (- cnt-all cnt-done)))))))
9281 (defvar org-after-todo-statistics-hook nil
9282 "Hook that is called after a TODO statistics cookie has been updated.
9283 Each function is called with two arguments: the number of not-done entries
9284 and the number of done entries.
9286 For example, the following function, when added to this hook, will switch
9287 an entry to DONE when all children are done, and back to TODO when new
9288 entries are set to a TODO status. Note that this hook is only called
9289 when there is a statistics cookie in the headline!
9291 (defun org-summary-todo (n-done n-not-done)
9292 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
9293 (let (org-log-done org-log-states) ; turn off logging
9294 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
9297 (defun org-todo-trigger-tag-changes (state)
9298 "Apply the changes defined in `org-todo-state-tags-triggers'."
9299 (let ((l org-todo-state-tags-triggers)
9300 changes)
9301 (when (or (not state) (equal state ""))
9302 (setq changes (append changes (cdr (assoc "" l)))))
9303 (when (and (stringp state) (> (length state) 0))
9304 (setq changes (append changes (cdr (assoc state l)))))
9305 (when (member state org-not-done-keywords)
9306 (setq changes (append changes (cdr (assoc 'todo l)))))
9307 (when (member state org-done-keywords)
9308 (setq changes (append changes (cdr (assoc 'done l)))))
9309 (dolist (c changes)
9310 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
9312 (defun org-local-logging (value)
9313 "Get logging settings from a property VALUE."
9314 (let* (words w a)
9315 ;; directly set the variables, they are already local.
9316 (setq org-log-done nil
9317 org-log-repeat nil
9318 org-todo-log-states nil)
9319 (setq words (org-split-string value))
9320 (while (setq w (pop words))
9321 (cond
9322 ((setq a (assoc w org-startup-options))
9323 (and (member (nth 1 a) '(org-log-done org-log-repeat))
9324 (set (nth 1 a) (nth 2 a))))
9325 ((setq a (org-extract-log-state-settings w))
9326 (and (member (car a) org-todo-keywords-1)
9327 (push a org-todo-log-states)))))))
9329 (defun org-get-todo-sequence-head (kwd)
9330 "Return the head of the TODO sequence to which KWD belongs.
9331 If KWD is not set, check if there is a text property remembering the
9332 right sequence."
9333 (let (p)
9334 (cond
9335 ((not kwd)
9336 (or (get-text-property (point-at-bol) 'org-todo-head)
9337 (progn
9338 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
9339 nil (point-at-eol)))
9340 (get-text-property p 'org-todo-head))))
9341 ((not (member kwd org-todo-keywords-1))
9342 (car org-todo-keywords-1))
9343 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
9345 (defun org-fast-todo-selection ()
9346 "Fast TODO keyword selection with single keys.
9347 Returns the new TODO keyword, or nil if no state change should occur."
9348 (let* ((fulltable org-todo-key-alist)
9349 (done-keywords org-done-keywords) ;; needed for the faces.
9350 (maxlen (apply 'max (mapcar
9351 (lambda (x)
9352 (if (stringp (car x)) (string-width (car x)) 0))
9353 fulltable)))
9354 (expert nil)
9355 (fwidth (+ maxlen 3 1 3))
9356 (ncol (/ (- (window-width) 4) fwidth))
9357 tg cnt e c tbl
9358 groups ingroup)
9359 (save-excursion
9360 (save-window-excursion
9361 (if expert
9362 (set-buffer (get-buffer-create " *Org todo*"))
9363 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
9364 (erase-buffer)
9365 (org-set-local 'org-done-keywords done-keywords)
9366 (setq tbl fulltable cnt 0)
9367 (while (setq e (pop tbl))
9368 (cond
9369 ((equal e '(:startgroup))
9370 (push '() groups) (setq ingroup t)
9371 (when (not (= cnt 0))
9372 (setq cnt 0)
9373 (insert "\n"))
9374 (insert "{ "))
9375 ((equal e '(:endgroup))
9376 (setq ingroup nil cnt 0)
9377 (insert "}\n"))
9378 ((equal e '(:newline))
9379 (when (not (= cnt 0))
9380 (setq cnt 0)
9381 (insert "\n")
9382 (setq e (car tbl))
9383 (while (equal (car tbl) '(:newline))
9384 (insert "\n")
9385 (setq tbl (cdr tbl)))))
9387 (setq tg (car e) c (cdr e))
9388 (if ingroup (push tg (car groups)))
9389 (setq tg (org-add-props tg nil 'face
9390 (org-get-todo-face tg)))
9391 (if (and (= cnt 0) (not ingroup)) (insert " "))
9392 (insert "[" c "] " tg (make-string
9393 (- fwidth 4 (length tg)) ?\ ))
9394 (when (= (setq cnt (1+ cnt)) ncol)
9395 (insert "\n")
9396 (if ingroup (insert " "))
9397 (setq cnt 0)))))
9398 (insert "\n")
9399 (goto-char (point-min))
9400 (if (not expert) (org-fit-window-to-buffer))
9401 (message "[a-z..]:Set [SPC]:clear")
9402 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9403 (cond
9404 ((or (= c ?\C-g)
9405 (and (= c ?q) (not (rassoc c fulltable))))
9406 (setq quit-flag t))
9407 ((= c ?\ ) nil)
9408 ((setq e (rassoc c fulltable) tg (car e))
9410 (t (setq quit-flag t)))))))
9412 (defun org-entry-is-todo-p ()
9413 (member (org-get-todo-state) org-not-done-keywords))
9415 (defun org-entry-is-done-p ()
9416 (member (org-get-todo-state) org-done-keywords))
9418 (defun org-get-todo-state ()
9419 (save-excursion
9420 (org-back-to-heading t)
9421 (and (looking-at org-todo-line-regexp)
9422 (match-end 2)
9423 (match-string 2))))
9425 (defun org-at-date-range-p (&optional inactive-ok)
9426 "Is the cursor inside a date range?"
9427 (interactive)
9428 (save-excursion
9429 (catch 'exit
9430 (let ((pos (point)))
9431 (skip-chars-backward "^[<\r\n")
9432 (skip-chars-backward "<[")
9433 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
9434 (>= (match-end 0) pos)
9435 (throw 'exit t))
9436 (skip-chars-backward "^<[\r\n")
9437 (skip-chars-backward "<[")
9438 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
9439 (>= (match-end 0) pos)
9440 (throw 'exit t)))
9441 nil)))
9443 (defun org-get-repeat ()
9444 "Check if there is a deadline/schedule with repeater in this entry."
9445 (save-match-data
9446 (save-excursion
9447 (org-back-to-heading t)
9448 (if (re-search-forward
9449 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
9450 (match-string 1)))))
9452 (defvar org-last-changed-timestamp)
9453 (defvar org-last-inserted-timestamp)
9454 (defvar org-log-post-message)
9455 (defvar org-log-note-purpose)
9456 (defvar org-log-note-how)
9457 (defvar org-log-note-extra)
9458 (defun org-auto-repeat-maybe (done-word)
9459 "Check if the current headline contains a repeated deadline/schedule.
9460 If yes, set TODO state back to what it was and change the base date
9461 of repeating deadline/scheduled time stamps to new date.
9462 This function is run automatically after each state change to a DONE state."
9463 ;; last-state is dynamically scoped into this function
9464 (let* ((repeat (org-get-repeat))
9465 (aa (assoc last-state org-todo-kwd-alist))
9466 (interpret (nth 1 aa))
9467 (head (nth 2 aa))
9468 (whata '(("d" . day) ("m" . month) ("y" . year)))
9469 (msg "Entry repeats: ")
9470 (org-log-done nil)
9471 (org-todo-log-states nil)
9472 (nshiftmax 10) (nshift 0)
9473 re type n what ts time)
9474 (when repeat
9475 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
9476 (org-todo (if (eq interpret 'type) last-state head))
9477 (when org-log-repeat
9478 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
9479 (memq 'org-add-log-note post-command-hook))
9480 ;; OK, we are already setup for some record
9481 (if (eq org-log-repeat 'note)
9482 ;; make sure we take a note, not only a time stamp
9483 (setq org-log-note-how 'note))
9484 ;; Set up for taking a record
9485 (org-add-log-setup 'state (or done-word (car org-done-keywords))
9486 last-state
9487 'findpos org-log-repeat)))
9488 (org-back-to-heading t)
9489 (org-add-planning-info nil nil 'closed)
9490 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
9491 org-deadline-time-regexp "\\)\\|\\("
9492 org-ts-regexp "\\)"))
9493 (while (re-search-forward
9494 re (save-excursion (outline-next-heading) (point)) t)
9495 (setq type (if (match-end 1) org-scheduled-string
9496 (if (match-end 3) org-deadline-string "Plain:"))
9497 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
9498 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
9499 (setq n (string-to-number (match-string 2 ts))
9500 what (match-string 3 ts))
9501 (if (equal what "w") (setq n (* n 7) what "d"))
9502 ;; Preparation, see if we need to modify the start date for the change
9503 (when (match-end 1)
9504 (setq time (save-match-data (org-time-string-to-time ts)))
9505 (cond
9506 ((equal (match-string 1 ts) ".")
9507 ;; Shift starting date to today
9508 (org-timestamp-change
9509 (- (time-to-days (current-time)) (time-to-days time))
9510 'day))
9511 ((equal (match-string 1 ts) "+")
9512 (while (or (= nshift 0)
9513 (<= (time-to-days time) (time-to-days (current-time))))
9514 (when (= (incf nshift) nshiftmax)
9515 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
9516 (error "Abort")))
9517 (org-timestamp-change n (cdr (assoc what whata)))
9518 (org-at-timestamp-p t)
9519 (setq ts (match-string 1))
9520 (setq time (save-match-data (org-time-string-to-time ts))))
9521 (org-timestamp-change (- n) (cdr (assoc what whata)))
9522 ;; rematch, so that we have everything in place for the real shift
9523 (org-at-timestamp-p t)
9524 (setq ts (match-string 1))
9525 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
9526 (org-timestamp-change n (cdr (assoc what whata)))
9527 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
9528 (setq org-log-post-message msg)
9529 (message "%s" msg))))
9531 (defun org-show-todo-tree (arg)
9532 "Make a compact tree which shows all headlines marked with TODO.
9533 The tree will show the lines where the regexp matches, and all higher
9534 headlines above the match.
9535 With a \\[universal-argument] prefix, also show the DONE entries.
9536 With a numeric prefix N, construct a sparse tree for the Nth element
9537 of `org-todo-keywords-1'."
9538 (interactive "P")
9539 (let ((case-fold-search nil)
9540 (kwd-re
9541 (cond ((null arg) org-not-done-regexp)
9542 ((equal arg '(4))
9543 (let ((kwd (org-ido-completing-read "Keyword (or KWD1|KWD2|...): "
9544 (mapcar 'list org-todo-keywords-1))))
9545 (concat "\\("
9546 (mapconcat 'identity (org-split-string kwd "|") "\\|")
9547 "\\)\\>")))
9548 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
9549 (regexp-quote (nth (1- (prefix-numeric-value arg))
9550 org-todo-keywords-1)))
9551 (t (error "Invalid prefix argument: %s" arg)))))
9552 (message "%d TODO entries found"
9553 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
9555 (defun org-deadline (&optional remove time)
9556 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
9557 With argument REMOVE, remove any deadline from the item.
9558 When TIME is set, it should be an internal time specification, and the
9559 scheduling will use the corresponding date."
9560 (interactive "P")
9561 (if remove
9562 (progn
9563 (org-remove-timestamp-with-keyword org-deadline-string)
9564 (message "Item no longer has a deadline."))
9565 (if (org-get-repeat)
9566 (error "Cannot change deadline on task with repeater, please do that by hand")
9567 (org-add-planning-info 'deadline time 'closed)
9568 (message "Deadline on %s" org-last-inserted-timestamp))))
9570 (defun org-schedule (&optional remove time)
9571 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
9572 With argument REMOVE, remove any scheduling date from the item.
9573 When TIME is set, it should be an internal time specification, and the
9574 scheduling will use the corresponding date."
9575 (interactive "P")
9576 (if remove
9577 (progn
9578 (org-remove-timestamp-with-keyword org-scheduled-string)
9579 (message "Item is no longer scheduled."))
9580 (if (org-get-repeat)
9581 (error "Cannot reschedule task with repeater, please do that by hand")
9582 (org-add-planning-info 'scheduled time 'closed)
9583 (message "Scheduled to %s" org-last-inserted-timestamp))))
9585 (defun org-get-scheduled-time (pom &optional inherit)
9586 "Get the scheduled time as a time tuple, of a format suitable
9587 for calling org-schedule with, or if there is no scheduling,
9588 returns nil."
9589 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
9590 (when time
9591 (apply 'encode-time (org-parse-time-string time)))))
9593 (defun org-get-deadline-time (pom &optional inherit)
9594 "Get the deadine as a time tuple, of a format suitable for
9595 calling org-deadlin with, or if there is no scheduling, returns
9596 nil."
9597 (let ((time (org-entry-get pom "DEADLINE" inherit)))
9598 (when time
9599 (apply 'encode-time (org-parse-time-string time)))))
9601 (defun org-remove-timestamp-with-keyword (keyword)
9602 "Remove all time stamps with KEYWORD in the current entry."
9603 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
9604 beg)
9605 (save-excursion
9606 (org-back-to-heading t)
9607 (setq beg (point))
9608 (org-end-of-subtree t t)
9609 (while (re-search-backward re beg t)
9610 (replace-match "")
9611 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
9612 (equal (char-before) ?\ ))
9613 (backward-delete-char 1)
9614 (if (string-match "^[ \t]*$" (buffer-substring
9615 (point-at-bol) (point-at-eol)))
9616 (delete-region (point-at-bol)
9617 (min (point-max) (1+ (point-at-eol))))))))))
9619 (defun org-add-planning-info (what &optional time &rest remove)
9620 "Insert new timestamp with keyword in the line directly after the headline.
9621 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
9622 If non is given, the user is prompted for a date.
9623 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
9624 be removed."
9625 (interactive)
9626 (let (org-time-was-given org-end-time-was-given ts
9627 end default-time default-input)
9629 (catch 'exit
9630 (when (and (not time) (memq what '(scheduled deadline)))
9631 ;; Try to get a default date/time from existing timestamp
9632 (save-excursion
9633 (org-back-to-heading t)
9634 (setq end (save-excursion (outline-next-heading) (point)))
9635 (when (re-search-forward (if (eq what 'scheduled)
9636 org-scheduled-time-regexp
9637 org-deadline-time-regexp)
9638 end t)
9639 (setq ts (match-string 1)
9640 default-time
9641 (apply 'encode-time (org-parse-time-string ts))
9642 default-input (and ts (org-get-compact-tod ts))))))
9643 (when what
9644 ;; If necessary, get the time from the user
9645 (setq time (or time (org-read-date nil 'to-time nil nil
9646 default-time default-input))))
9648 (when (and org-insert-labeled-timestamps-at-point
9649 (member what '(scheduled deadline)))
9650 (insert
9651 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
9652 (org-insert-time-stamp time org-time-was-given
9653 nil nil nil (list org-end-time-was-given))
9654 (setq what nil))
9655 (save-excursion
9656 (save-restriction
9657 (let (col list elt ts buffer-invisibility-spec)
9658 (org-back-to-heading t)
9659 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
9660 (goto-char (match-end 1))
9661 (setq col (current-column))
9662 (goto-char (match-end 0))
9663 (if (eobp) (insert "\n") (forward-char 1))
9664 (when (and (not what)
9665 (not (looking-at
9666 (concat "[ \t]*"
9667 org-keyword-time-not-clock-regexp))))
9668 ;; Nothing to add, nothing to remove...... :-)
9669 (throw 'exit nil))
9670 (if (and (not (looking-at outline-regexp))
9671 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
9672 "[^\r\n]*"))
9673 (not (equal (match-string 1) org-clock-string)))
9674 (narrow-to-region (match-beginning 0) (match-end 0))
9675 (insert-before-markers "\n")
9676 (backward-char 1)
9677 (narrow-to-region (point) (point))
9678 (and org-adapt-indentation (org-indent-to-column col)))
9679 ;; Check if we have to remove something.
9680 (setq list (cons what remove))
9681 (while list
9682 (setq elt (pop list))
9683 (goto-char (point-min))
9684 (when (or (and (eq elt 'scheduled)
9685 (re-search-forward org-scheduled-time-regexp nil t))
9686 (and (eq elt 'deadline)
9687 (re-search-forward org-deadline-time-regexp nil t))
9688 (and (eq elt 'closed)
9689 (re-search-forward org-closed-time-regexp nil t)))
9690 (replace-match "")
9691 (if (looking-at "--+<[^>]+>") (replace-match ""))
9692 (if (looking-at " +") (replace-match ""))))
9693 (goto-char (point-max))
9694 (when what
9695 (insert
9696 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
9697 (cond ((eq what 'scheduled) org-scheduled-string)
9698 ((eq what 'deadline) org-deadline-string)
9699 ((eq what 'closed) org-closed-string))
9700 " ")
9701 (setq ts (org-insert-time-stamp
9702 time
9703 (or org-time-was-given
9704 (and (eq what 'closed) org-log-done-with-time))
9705 (eq what 'closed)
9706 nil nil (list org-end-time-was-given)))
9707 (end-of-line 1))
9708 (goto-char (point-min))
9709 (widen)
9710 (if (and (looking-at "[ \t]+\n")
9711 (equal (char-before) ?\n))
9712 (delete-region (1- (point)) (point-at-eol)))
9713 ts))))))
9715 (defvar org-log-note-marker (make-marker))
9716 (defvar org-log-note-purpose nil)
9717 (defvar org-log-note-state nil)
9718 (defvar org-log-note-previous-state nil)
9719 (defvar org-log-note-how nil)
9720 (defvar org-log-note-extra nil)
9721 (defvar org-log-note-window-configuration nil)
9722 (defvar org-log-note-return-to (make-marker))
9723 (defvar org-log-post-message nil
9724 "Message to be displayed after a log note has been stored.
9725 The auto-repeater uses this.")
9727 (defun org-add-note ()
9728 "Add a note to the current entry.
9729 This is done in the same way as adding a state change note."
9730 (interactive)
9731 (org-add-log-setup 'note nil nil 'findpos nil))
9733 (defvar org-property-end-re)
9734 (defun org-add-log-setup (&optional purpose state prev-state
9735 findpos how &optional extra)
9736 "Set up the post command hook to take a note.
9737 If this is about to TODO state change, the new state is expected in STATE.
9738 When FINDPOS is non-nil, find the correct position for the note in
9739 the current entry. If not, assume that it can be inserted at point.
9740 HOW is an indicator what kind of note should be created.
9741 EXTRA is additional text that will be inserted into the notes buffer."
9742 (let ((drawer (cond ((stringp org-log-into-drawer)
9743 org-log-into-drawer)
9744 (org-log-into-drawer "LOGBOOK")
9745 (t nil))))
9746 (save-restriction
9747 (save-excursion
9748 (when findpos
9749 (org-back-to-heading t)
9750 (narrow-to-region (point) (save-excursion
9751 (outline-next-heading) (point)))
9752 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
9753 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
9754 "[^\r\n]*\\)?"))
9755 (goto-char (match-end 0))
9756 (cond
9757 (drawer
9758 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
9759 nil t)
9760 (progn
9761 (goto-char (match-end 0))
9762 (or org-log-states-order-reversed
9763 (and (re-search-forward org-property-end-re nil t)
9764 (goto-char (1- (match-beginning 0))))))
9765 (insert "\n:" drawer ":\n:END:")
9766 (beginning-of-line 0)
9767 (org-indent-line-function)
9768 (beginning-of-line 2)
9769 (org-indent-line-function)
9770 (end-of-line 0)))
9771 ((and org-log-state-notes-insert-after-drawers
9772 (save-excursion
9773 (forward-line) (looking-at org-drawer-regexp)))
9774 (forward-line)
9775 (while (looking-at org-drawer-regexp)
9776 (goto-char (match-end 0))
9777 (re-search-forward org-property-end-re (point-max) t)
9778 (forward-line))
9779 (forward-line -1)))
9780 (unless org-log-states-order-reversed
9781 (and (= (char-after) ?\n) (forward-char 1))
9782 (org-skip-over-state-notes)
9783 (skip-chars-backward " \t\n\r")))
9784 (move-marker org-log-note-marker (point))
9785 (setq org-log-note-purpose purpose
9786 org-log-note-state state
9787 org-log-note-previous-state prev-state
9788 org-log-note-how how
9789 org-log-note-extra extra)
9790 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
9792 (defun org-skip-over-state-notes ()
9793 "Skip past the list of State notes in an entry."
9794 (if (looking-at "\n[ \t]*- State") (forward-char 1))
9795 (while (looking-at "[ \t]*- State")
9796 (condition-case nil
9797 (org-next-item)
9798 (error (org-end-of-item)))))
9800 (defun org-add-log-note (&optional purpose)
9801 "Pop up a window for taking a note, and add this note later at point."
9802 (remove-hook 'post-command-hook 'org-add-log-note)
9803 (setq org-log-note-window-configuration (current-window-configuration))
9804 (delete-other-windows)
9805 (move-marker org-log-note-return-to (point))
9806 (switch-to-buffer (marker-buffer org-log-note-marker))
9807 (goto-char org-log-note-marker)
9808 (org-switch-to-buffer-other-window "*Org Note*")
9809 (erase-buffer)
9810 (if (memq org-log-note-how '(time state))
9811 (let (current-prefix-arg) (org-store-log-note))
9812 (let ((org-inhibit-startup t)) (org-mode))
9813 (insert (format "# Insert note for %s.
9814 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
9815 (cond
9816 ((eq org-log-note-purpose 'clock-out) "stopped clock")
9817 ((eq org-log-note-purpose 'done) "closed todo item")
9818 ((eq org-log-note-purpose 'state)
9819 (format "state change from \"%s\" to \"%s\""
9820 (or org-log-note-previous-state "")
9821 (or org-log-note-state "")))
9822 ((eq org-log-note-purpose 'note)
9823 "this entry")
9824 (t (error "This should not happen")))))
9825 (if org-log-note-extra (insert org-log-note-extra))
9826 (org-set-local 'org-finish-function 'org-store-log-note)))
9828 (defvar org-note-abort nil) ; dynamically scoped
9829 (defun org-store-log-note ()
9830 "Finish taking a log note, and insert it to where it belongs."
9831 (let ((txt (buffer-string))
9832 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
9833 lines ind)
9834 (kill-buffer (current-buffer))
9835 (while (string-match "\\`#.*\n[ \t\n]*" txt)
9836 (setq txt (replace-match "" t t txt)))
9837 (if (string-match "\\s-+\\'" txt)
9838 (setq txt (replace-match "" t t txt)))
9839 (setq lines (org-split-string txt "\n"))
9840 (when (and note (string-match "\\S-" note))
9841 (setq note
9842 (org-replace-escapes
9843 note
9844 (list (cons "%u" (user-login-name))
9845 (cons "%U" user-full-name)
9846 (cons "%t" (format-time-string
9847 (org-time-stamp-format 'long 'inactive)
9848 (current-time)))
9849 (cons "%s" (if org-log-note-state
9850 (concat "\"" org-log-note-state "\"")
9851 ""))
9852 (cons "%S" (if org-log-note-previous-state
9853 (concat "\"" org-log-note-previous-state "\"")
9854 "\"\"")))))
9855 (if lines (setq note (concat note " \\\\")))
9856 (push note lines))
9857 (when (or current-prefix-arg org-note-abort)
9858 (when org-log-into-drawer
9859 (org-remove-empty-drawer-at
9860 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
9861 org-log-note-marker))
9862 (setq lines nil))
9863 (when lines
9864 (save-excursion
9865 (set-buffer (marker-buffer org-log-note-marker))
9866 (save-excursion
9867 (goto-char org-log-note-marker)
9868 (move-marker org-log-note-marker nil)
9869 (end-of-line 1)
9870 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
9871 (insert "- " (pop lines))
9872 (org-indent-line-function)
9873 (beginning-of-line 1)
9874 (looking-at "[ \t]*")
9875 (setq ind (concat (match-string 0) " "))
9876 (end-of-line 1)
9877 (while lines (insert "\n" ind (pop lines)))
9878 (message "Note stored")
9879 (org-back-to-heading t)
9880 (org-cycle-hide-drawers 'children)))))
9881 (set-window-configuration org-log-note-window-configuration)
9882 (with-current-buffer (marker-buffer org-log-note-return-to)
9883 (goto-char org-log-note-return-to))
9884 (move-marker org-log-note-return-to nil)
9885 (and org-log-post-message (message "%s" org-log-post-message)))
9887 (defun org-remove-empty-drawer-at (drawer pos)
9888 "Remove an emptyr DARWER drawer at position POS.
9889 POS may also be a marker."
9890 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
9891 (save-excursion
9892 (save-restriction
9893 (widen)
9894 (goto-char pos)
9895 (if (org-in-regexp
9896 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
9897 (replace-match ""))))))
9899 (defun org-sparse-tree (&optional arg)
9900 "Create a sparse tree, prompt for the details.
9901 This command can create sparse trees. You first need to select the type
9902 of match used to create the tree:
9904 t Show entries with a specific TODO keyword.
9905 m Show entries selected by a tags/property match.
9906 p Enter a property name and its value (both with completion on existing
9907 names/values) and show entries with that property.
9908 r Show entries matching a regular expression.
9909 d Show deadlines due within `org-deadline-warning-days'.
9910 b Show deadlines and scheduled items before a date.
9911 a Show deadlines and scheduled items after a date."
9912 (interactive "P")
9913 (let (ans kwd value)
9914 (message "Sparse tree: [/]regexp [t]odo-kwd [m]atch [p]roperty [d]eadlines [b]efore-date [a]fter-date")
9915 (setq ans (read-char-exclusive))
9916 (cond
9917 ((equal ans ?d)
9918 (call-interactively 'org-check-deadlines))
9919 ((equal ans ?b)
9920 (call-interactively 'org-check-before-date))
9921 ((equal ans ?a)
9922 (call-interactively 'org-check-after-date))
9923 ((equal ans ?t)
9924 (org-show-todo-tree '(4)))
9925 ((member ans '(?T ?m))
9926 (call-interactively 'org-match-sparse-tree))
9927 ((member ans '(?p ?P))
9928 (setq kwd (org-ido-completing-read "Property: "
9929 (mapcar 'list (org-buffer-property-keys))))
9930 (setq value (org-ido-completing-read "Value: "
9931 (mapcar 'list (org-property-values kwd))))
9932 (unless (string-match "\\`{.*}\\'" value)
9933 (setq value (concat "\"" value "\"")))
9934 (org-match-sparse-tree arg (concat kwd "=" value)))
9935 ((member ans '(?r ?R ?/))
9936 (call-interactively 'org-occur))
9937 (t (error "No such sparse tree command \"%c\"" ans)))))
9939 (defvar org-occur-highlights nil
9940 "List of overlays used for occur matches.")
9941 (make-variable-buffer-local 'org-occur-highlights)
9942 (defvar org-occur-parameters nil
9943 "Parameters of the active org-occur calls.
9944 This is a list, each call to org-occur pushes as cons cell,
9945 containing the regular expression and the callback, onto the list.
9946 The list can contain several entries if `org-occur' has been called
9947 several time with the KEEP-PREVIOUS argument. Otherwise, this list
9948 will only contain one set of parameters. When the highlights are
9949 removed (for example with `C-c C-c', or with the next edit (depending
9950 on `org-remove-highlights-with-change'), this variable is emptied
9951 as well.")
9952 (make-variable-buffer-local 'org-occur-parameters)
9954 (defun org-occur (regexp &optional keep-previous callback)
9955 "Make a compact tree which shows all matches of REGEXP.
9956 The tree will show the lines where the regexp matches, and all higher
9957 headlines above the match. It will also show the heading after the match,
9958 to make sure editing the matching entry is easy.
9959 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
9960 call to `org-occur' will be kept, to allow stacking of calls to this
9961 command.
9962 If CALLBACK is non-nil, it is a function which is called to confirm
9963 that the match should indeed be shown."
9964 (interactive "sRegexp: \nP")
9965 (unless keep-previous
9966 (org-remove-occur-highlights nil nil t))
9967 (push (cons regexp callback) org-occur-parameters)
9968 (let ((cnt 0))
9969 (save-excursion
9970 (goto-char (point-min))
9971 (if (or (not keep-previous) ; do not want to keep
9972 (not org-occur-highlights)) ; no previous matches
9973 ;; hide everything
9974 (org-overview))
9975 (while (re-search-forward regexp nil t)
9976 (when (or (not callback)
9977 (save-match-data (funcall callback)))
9978 (setq cnt (1+ cnt))
9979 (when org-highlight-sparse-tree-matches
9980 (org-highlight-new-match (match-beginning 0) (match-end 0)))
9981 (org-show-context 'occur-tree))))
9982 (when org-remove-highlights-with-change
9983 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
9984 nil 'local))
9985 (unless org-sparse-tree-open-archived-trees
9986 (org-hide-archived-subtrees (point-min) (point-max)))
9987 (run-hooks 'org-occur-hook)
9988 (if (interactive-p)
9989 (message "%d match(es) for regexp %s" cnt regexp))
9990 cnt))
9992 (defun org-show-context (&optional key)
9993 "Make sure point and context and visible.
9994 How much context is shown depends upon the variables
9995 `org-show-hierarchy-above', `org-show-following-heading'. and
9996 `org-show-siblings'."
9997 (let ((heading-p (org-on-heading-p t))
9998 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
9999 (following-p (org-get-alist-option org-show-following-heading key))
10000 (entry-p (org-get-alist-option org-show-entry-below key))
10001 (siblings-p (org-get-alist-option org-show-siblings key)))
10002 (catch 'exit
10003 ;; Show heading or entry text
10004 (if (and heading-p (not entry-p))
10005 (org-flag-heading nil) ; only show the heading
10006 (and (or entry-p (org-invisible-p) (org-invisible-p2))
10007 (org-show-hidden-entry))) ; show entire entry
10008 (when following-p
10009 ;; Show next sibling, or heading below text
10010 (save-excursion
10011 (and (if heading-p (org-goto-sibling) (outline-next-heading))
10012 (org-flag-heading nil))))
10013 (when siblings-p (org-show-siblings))
10014 (when hierarchy-p
10015 ;; show all higher headings, possibly with siblings
10016 (save-excursion
10017 (while (and (condition-case nil
10018 (progn (org-up-heading-all 1) t)
10019 (error nil))
10020 (not (bobp)))
10021 (org-flag-heading nil)
10022 (when siblings-p (org-show-siblings))))))))
10024 (defun org-reveal (&optional siblings)
10025 "Show current entry, hierarchy above it, and the following headline.
10026 This can be used to show a consistent set of context around locations
10027 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
10028 not t for the search context.
10030 With optional argument SIBLINGS, on each level of the hierarchy all
10031 siblings are shown. This repairs the tree structure to what it would
10032 look like when opened with hierarchical calls to `org-cycle'."
10033 (interactive "P")
10034 (let ((org-show-hierarchy-above t)
10035 (org-show-following-heading t)
10036 (org-show-siblings (if siblings t org-show-siblings)))
10037 (org-show-context nil)))
10039 (defun org-highlight-new-match (beg end)
10040 "Highlight from BEG to END and mark the highlight is an occur headline."
10041 (let ((ov (org-make-overlay beg end)))
10042 (org-overlay-put ov 'face 'secondary-selection)
10043 (push ov org-occur-highlights)))
10045 (defun org-remove-occur-highlights (&optional beg end noremove)
10046 "Remove the occur highlights from the buffer.
10047 BEG and END are ignored. If NOREMOVE is nil, remove this function
10048 from the `before-change-functions' in the current buffer."
10049 (interactive)
10050 (unless org-inhibit-highlight-removal
10051 (mapc 'org-delete-overlay org-occur-highlights)
10052 (setq org-occur-highlights nil)
10053 (setq org-occur-parameters nil)
10054 (unless noremove
10055 (remove-hook 'before-change-functions
10056 'org-remove-occur-highlights 'local))))
10058 ;;;; Priorities
10060 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
10061 "Regular expression matching the priority indicator.")
10063 (defvar org-remove-priority-next-time nil)
10065 (defun org-priority-up ()
10066 "Increase the priority of the current item."
10067 (interactive)
10068 (org-priority 'up))
10070 (defun org-priority-down ()
10071 "Decrease the priority of the current item."
10072 (interactive)
10073 (org-priority 'down))
10075 (defun org-priority (&optional action)
10076 "Change the priority of an item by ARG.
10077 ACTION can be `set', `up', `down', or a character."
10078 (interactive)
10079 (setq action (or action 'set))
10080 (let (current new news have remove)
10081 (save-excursion
10082 (org-back-to-heading t)
10083 (if (looking-at org-priority-regexp)
10084 (setq current (string-to-char (match-string 2))
10085 have t)
10086 (setq current org-default-priority))
10087 (cond
10088 ((or (eq action 'set)
10089 (if (featurep 'xemacs) (characterp action) (integerp action)))
10090 (if (not (eq action 'set))
10091 (setq new action)
10092 (message "Priority %c-%c, SPC to remove: "
10093 org-highest-priority org-lowest-priority)
10094 (setq new (read-char-exclusive)))
10095 (if (and (= (upcase org-highest-priority) org-highest-priority)
10096 (= (upcase org-lowest-priority) org-lowest-priority))
10097 (setq new (upcase new)))
10098 (cond ((equal new ?\ ) (setq remove t))
10099 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
10100 (error "Priority must be between `%c' and `%c'"
10101 org-highest-priority org-lowest-priority))))
10102 ((eq action 'up)
10103 (if (and (not have) (eq last-command this-command))
10104 (setq new org-lowest-priority)
10105 (setq new (if (and org-priority-start-cycle-with-default (not have))
10106 org-default-priority (1- current)))))
10107 ((eq action 'down)
10108 (if (and (not have) (eq last-command this-command))
10109 (setq new org-highest-priority)
10110 (setq new (if (and org-priority-start-cycle-with-default (not have))
10111 org-default-priority (1+ current)))))
10112 (t (error "Invalid action")))
10113 (if (or (< (upcase new) org-highest-priority)
10114 (> (upcase new) org-lowest-priority))
10115 (setq remove t))
10116 (setq news (format "%c" new))
10117 (if have
10118 (if remove
10119 (replace-match "" t t nil 1)
10120 (replace-match news t t nil 2))
10121 (if remove
10122 (error "No priority cookie found in line")
10123 (let ((case-fold-search nil))
10124 (looking-at org-todo-line-regexp))
10125 (if (match-end 2)
10126 (progn
10127 (goto-char (match-end 2))
10128 (insert " [#" news "]"))
10129 (goto-char (match-beginning 3))
10130 (insert "[#" news "] ")))))
10131 (org-preserve-lc (org-set-tags nil 'align))
10132 (if remove
10133 (message "Priority removed")
10134 (message "Priority of current item set to %s" news))))
10137 (defun org-get-priority (s)
10138 "Find priority cookie and return priority."
10139 (save-match-data
10140 (if (not (string-match org-priority-regexp s))
10141 (* 1000 (- org-lowest-priority org-default-priority))
10142 (* 1000 (- org-lowest-priority
10143 (string-to-char (match-string 2 s)))))))
10145 ;;;; Tags
10147 (defvar org-agenda-archives-mode)
10148 (defvar org-map-continue-from nil
10149 "Position from where mapping should continue.
10150 Can be set byt the action argument to `org-scan-tag's and `org-map-entries'.")
10152 (defvar org-scanner-tags nil
10153 "The current tag list while the tags scanner is running.")
10154 (defvar org-trust-scanner-tags nil
10155 "Should `org-get-tags-at' use the tags fro the scanner.
10156 This is for internal dynamical scoping only.
10157 When this is non-nil, the function `org-get-tags-at' will return the value
10158 of `org-scanner-tags' instead of building the list by itself. This
10159 can lead to large speed-ups when the tags scanner is used in a file with
10160 many entries, and when the list of tags is retrieved, for example to
10161 obtain a list of properties. Building the tags list for each entry in such
10162 a file becomes an N^2 operation - but with this variable set, it scales
10163 as N.")
10165 (defun org-scan-tags (action matcher &optional todo-only)
10166 "Scan headline tags with inheritance and produce output ACTION.
10168 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
10169 or `agenda' to produce an entry list for an agenda view. It can also be
10170 a Lisp form or a function that should be called at each matched headline, in
10171 this case the return value is a list of all return values from these calls.
10173 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
10174 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
10175 only lines with a TODO keyword are included in the output."
10176 (require 'org-agenda)
10177 (let* ((re (concat "^" outline-regexp " *\\(\\<\\("
10178 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
10179 (org-re
10180 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
10181 (props (list 'face 'default
10182 'done-face 'org-agenda-done
10183 'undone-face 'default
10184 'mouse-face 'highlight
10185 'org-not-done-regexp org-not-done-regexp
10186 'org-todo-regexp org-todo-regexp
10187 'keymap org-agenda-keymap
10188 'help-echo
10189 (format "mouse-2 or RET jump to org file %s"
10190 (abbreviate-file-name
10191 (or (buffer-file-name (buffer-base-buffer))
10192 (buffer-name (buffer-base-buffer)))))))
10193 (case-fold-search nil)
10194 (org-map-continue-from nil)
10195 lspos tags tags-list
10196 (tags-alist (list (cons 0 org-file-tags)))
10197 (llast 0) rtn rtn1 level category i txt
10198 todo marker entry priority)
10199 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
10200 (setq action (list 'lambda nil action)))
10201 (save-excursion
10202 (goto-char (point-min))
10203 (when (eq action 'sparse-tree)
10204 (org-overview)
10205 (org-remove-occur-highlights))
10206 (while (re-search-forward re nil t)
10207 (catch :skip
10208 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
10209 tags (if (match-end 4) (org-match-string-no-properties 4)))
10210 (goto-char (setq lspos (match-beginning 0)))
10211 (setq level (org-reduced-level (funcall outline-level))
10212 category (org-get-category))
10213 (setq i llast llast level)
10214 ;; remove tag lists from same and sublevels
10215 (while (>= i level)
10216 (when (setq entry (assoc i tags-alist))
10217 (setq tags-alist (delete entry tags-alist)))
10218 (setq i (1- i)))
10219 ;; add the next tags
10220 (when tags
10221 (setq tags (org-split-string tags ":")
10222 tags-alist
10223 (cons (cons level tags) tags-alist)))
10224 ;; compile tags for current headline
10225 (setq tags-list
10226 (if org-use-tag-inheritance
10227 (apply 'append (mapcar 'cdr (reverse tags-alist)))
10228 tags)
10229 org-scanner-tags tags-list)
10230 (when org-use-tag-inheritance
10231 (setcdr (car tags-alist)
10232 (mapcar (lambda (x)
10233 (setq x (copy-sequence x))
10234 (org-add-prop-inherited x))
10235 (cdar tags-alist))))
10236 (when (and tags org-use-tag-inheritance
10237 (or (not (eq t org-use-tag-inheritance))
10238 org-tags-exclude-from-inheritance))
10239 ;; selective inheritance, remove uninherited ones
10240 (setcdr (car tags-alist)
10241 (org-remove-uniherited-tags (cdar tags-alist))))
10242 (when (and (or (not todo-only)
10243 (and (member todo org-not-done-keywords)
10244 (or (not org-agenda-tags-todo-honor-ignore-options)
10245 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
10246 (let ((case-fold-search t)) (eval matcher))
10248 (not (member org-archive-tag tags-list))
10249 ;; we have an archive tag, should we use this anyway?
10250 (or (not org-agenda-skip-archived-trees)
10251 (and (eq action 'agenda) org-agenda-archives-mode))))
10252 (unless (eq action 'sparse-tree) (org-agenda-skip))
10254 ;; select this headline
10256 (cond
10257 ((eq action 'sparse-tree)
10258 (and org-highlight-sparse-tree-matches
10259 (org-get-heading) (match-end 0)
10260 (org-highlight-new-match
10261 (match-beginning 0) (match-beginning 1)))
10262 (org-show-context 'tags-tree))
10263 ((eq action 'agenda)
10264 (setq txt (org-format-agenda-item
10266 (concat
10267 (if (eq org-tags-match-list-sublevels 'indented)
10268 (make-string (1- level) ?.) "")
10269 (org-get-heading))
10270 category
10271 tags-list
10273 priority (org-get-priority txt))
10274 (goto-char lspos)
10275 (setq marker (org-agenda-new-marker))
10276 (org-add-props txt props
10277 'org-marker marker 'org-hd-marker marker 'org-category category
10278 'todo-state todo
10279 'priority priority 'type "tagsmatch")
10280 (push txt rtn))
10281 ((functionp action)
10282 (setq org-map-continue-from nil)
10283 (save-excursion
10284 (setq rtn1 (funcall action))
10285 (push rtn1 rtn)))
10286 (t (error "Invalid action")))
10288 ;; if we are to skip sublevels, jump to end of subtree
10289 (unless org-tags-match-list-sublevels
10290 (org-end-of-subtree t)
10291 (backward-char 1))))
10292 ;; Get the correct position from where to continue
10293 (if org-map-continue-from
10294 (goto-char org-map-continue-from)
10295 (and (= (point) lspos) (end-of-line 1)))))
10296 (when (and (eq action 'sparse-tree)
10297 (not org-sparse-tree-open-archived-trees))
10298 (org-hide-archived-subtrees (point-min) (point-max)))
10299 (nreverse rtn)))
10301 (defun org-remove-uniherited-tags (tags)
10302 "Remove all tags that are not inherited from the list TAGS."
10303 (cond
10304 ((eq org-use-tag-inheritance t)
10305 (if org-tags-exclude-from-inheritance
10306 (org-delete-all org-tags-exclude-from-inheritance tags)
10307 tags))
10308 ((not org-use-tag-inheritance) nil)
10309 ((stringp org-use-tag-inheritance)
10310 (delq nil (mapcar
10311 (lambda (x)
10312 (if (and (string-match org-use-tag-inheritance x)
10313 (not (member x org-tags-exclude-from-inheritance)))
10314 x nil))
10315 tags)))
10316 ((listp org-use-tag-inheritance)
10317 (delq nil (mapcar
10318 (lambda (x)
10319 (if (member x org-use-tag-inheritance) x nil))
10320 tags)))))
10322 (defvar todo-only) ;; dynamically scoped
10324 (defun org-match-sparse-tree (&optional todo-only match)
10325 "Create a sparse tree according to tags string MATCH.
10326 MATCH can contain positive and negative selection of tags, like
10327 \"+WORK+URGENT-WITHBOSS\".
10328 If optional argument TODO-ONLY is non-nil, only select lines that are
10329 also TODO lines."
10330 (interactive "P")
10331 (org-prepare-agenda-buffers (list (current-buffer)))
10332 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
10334 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
10336 (defvar org-cached-props nil)
10337 (defun org-cached-entry-get (pom property)
10338 (if (or (eq t org-use-property-inheritance)
10339 (and (stringp org-use-property-inheritance)
10340 (string-match org-use-property-inheritance property))
10341 (and (listp org-use-property-inheritance)
10342 (member property org-use-property-inheritance)))
10343 ;; Caching is not possible, check it directly
10344 (org-entry-get pom property 'inherit)
10345 ;; Get all properties, so that we can do complicated checks easily
10346 (cdr (assoc property (or org-cached-props
10347 (setq org-cached-props
10348 (org-entry-properties pom)))))))
10350 (defun org-global-tags-completion-table (&optional files)
10351 "Return the list of all tags in all agenda buffer/files."
10352 (save-excursion
10353 (org-uniquify
10354 (delq nil
10355 (apply 'append
10356 (mapcar
10357 (lambda (file)
10358 (set-buffer (find-file-noselect file))
10359 (append (org-get-buffer-tags)
10360 (mapcar (lambda (x) (if (stringp (car-safe x))
10361 (list (car-safe x)) nil))
10362 org-tag-alist)))
10363 (if (and files (car files))
10364 files
10365 (org-agenda-files))))))))
10367 (defun org-make-tags-matcher (match)
10368 "Create the TAGS//TODO matcher form for the selection string MATCH."
10369 ;; todo-only is scoped dynamically into this function, and the function
10370 ;; may change it if the matcher asks for it.
10371 (unless match
10372 ;; Get a new match request, with completion
10373 (let ((org-last-tags-completion-table
10374 (org-global-tags-completion-table)))
10375 (setq match (org-completing-read-no-ido
10376 "Match: " 'org-tags-completion-function nil nil nil
10377 'org-tags-history))))
10379 ;; Parse the string and create a lisp form
10380 (let ((match0 match)
10381 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
10382 minus tag mm
10383 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
10384 orterms term orlist re-p str-p level-p level-op time-p
10385 prop-p pn pv po cat-p gv rest)
10386 (if (string-match "/+" match)
10387 ;; match contains also a todo-matching request
10388 (progn
10389 (setq tagsmatch (substring match 0 (match-beginning 0))
10390 todomatch (substring match (match-end 0)))
10391 (if (string-match "^!" todomatch)
10392 (setq todo-only t todomatch (substring todomatch 1)))
10393 (if (string-match "^\\s-*$" todomatch)
10394 (setq todomatch nil)))
10395 ;; only matching tags
10396 (setq tagsmatch match todomatch nil))
10398 ;; Make the tags matcher
10399 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
10400 (setq tagsmatcher t)
10401 (setq orterms (org-split-string tagsmatch "|") orlist nil)
10402 (while (setq term (pop orterms))
10403 (while (and (equal (substring term -1) "\\") orterms)
10404 (setq term (concat term "|" (pop orterms)))) ; repair bad split
10405 (while (string-match re term)
10406 (setq rest (substring term (match-end 0))
10407 minus (and (match-end 1)
10408 (equal (match-string 1 term) "-"))
10409 tag (match-string 2 term)
10410 re-p (equal (string-to-char tag) ?{)
10411 level-p (match-end 4)
10412 prop-p (match-end 5)
10413 mm (cond
10414 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
10415 (level-p
10416 (setq level-op (org-op-to-function (match-string 3 term)))
10417 `(,level-op level ,(string-to-number
10418 (match-string 4 term))))
10419 (prop-p
10420 (setq pn (match-string 5 term)
10421 po (match-string 6 term)
10422 pv (match-string 7 term)
10423 cat-p (equal pn "CATEGORY")
10424 re-p (equal (string-to-char pv) ?{)
10425 str-p (equal (string-to-char pv) ?\")
10426 time-p (save-match-data
10427 (string-match "^\"[[<].*[]>]\"$" pv))
10428 pv (if (or re-p str-p) (substring pv 1 -1) pv))
10429 (if time-p (setq pv (org-matcher-time pv)))
10430 (setq po (org-op-to-function po (if time-p 'time str-p)))
10431 (cond
10432 ((equal pn "CATEGORY")
10433 (setq gv '(get-text-property (point) 'org-category)))
10434 ((equal pn "TODO")
10435 (setq gv 'todo))
10437 (setq gv `(org-cached-entry-get nil ,pn))))
10438 (if re-p
10439 (if (eq po 'org<>)
10440 `(not (string-match ,pv (or ,gv "")))
10441 `(string-match ,pv (or ,gv "")))
10442 (if str-p
10443 `(,po (or ,gv "") ,pv)
10444 `(,po (string-to-number (or ,gv ""))
10445 ,(string-to-number pv) ))))
10446 (t `(member ,tag tags-list)))
10447 mm (if minus (list 'not mm) mm)
10448 term rest)
10449 (push mm tagsmatcher))
10450 (push (if (> (length tagsmatcher) 1)
10451 (cons 'and tagsmatcher)
10452 (car tagsmatcher))
10453 orlist)
10454 (setq tagsmatcher nil))
10455 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
10456 (setq tagsmatcher
10457 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
10458 ;; Make the todo matcher
10459 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
10460 (setq todomatcher t)
10461 (setq orterms (org-split-string todomatch "|") orlist nil)
10462 (while (setq term (pop orterms))
10463 (while (string-match re term)
10464 (setq minus (and (match-end 1)
10465 (equal (match-string 1 term) "-"))
10466 kwd (match-string 2 term)
10467 re-p (equal (string-to-char kwd) ?{)
10468 term (substring term (match-end 0))
10469 mm (if re-p
10470 `(string-match ,(substring kwd 1 -1) todo)
10471 (list 'equal 'todo kwd))
10472 mm (if minus (list 'not mm) mm))
10473 (push mm todomatcher))
10474 (push (if (> (length todomatcher) 1)
10475 (cons 'and todomatcher)
10476 (car todomatcher))
10477 orlist)
10478 (setq todomatcher nil))
10479 (setq todomatcher (if (> (length orlist) 1)
10480 (cons 'or orlist) (car orlist))))
10482 ;; Return the string and lisp forms of the matcher
10483 (setq matcher (if todomatcher
10484 (list 'and tagsmatcher todomatcher)
10485 tagsmatcher))
10486 (cons match0 matcher)))
10488 (defun org-op-to-function (op &optional stringp)
10489 "Turn an operator into the appropriate function."
10490 (setq op
10491 (cond
10492 ((equal op "<" ) '(< string< org-time<))
10493 ((equal op ">" ) '(> org-string> org-time>))
10494 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
10495 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
10496 ((member op '("=" "==")) '(= string= org-time=))
10497 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
10498 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
10500 (defun org<> (a b) (not (= a b)))
10501 (defun org-string<= (a b) (or (string= a b) (string< a b)))
10502 (defun org-string>= (a b) (not (string< a b)))
10503 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
10504 (defun org-string<> (a b) (not (string= a b)))
10505 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
10506 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
10507 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
10508 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
10509 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
10510 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
10511 (defun org-2ft (s)
10512 "Convert S to a floating point time.
10513 If S is already a number, just return it. If it is a string, parse
10514 it as a time string and apply `float-time' to it. If S is nil, just return 0."
10515 (cond
10516 ((numberp s) s)
10517 ((stringp s)
10518 (condition-case nil
10519 (float-time (apply 'encode-time (org-parse-time-string s)))
10520 (error 0.)))
10521 (t 0.)))
10523 (defun org-time-today ()
10524 "Time in seconds today at 0:00.
10525 Returns the float number of seconds since the beginning of the
10526 epoch to the beginning of today (00:00)."
10527 (float-time (apply 'encode-time
10528 (append '(0 0 0) (nthcdr 3 (decode-time))))))
10530 (defun org-matcher-time (s)
10531 "Interpret a time comparison value."
10532 (save-match-data
10533 (cond
10534 ((string= s "<now>") (float-time))
10535 ((string= s "<today>") (org-time-today))
10536 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
10537 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
10538 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
10539 (+ (org-time-today)
10540 (* (string-to-number (match-string 1 s))
10541 (cdr (assoc (match-string 2 s)
10542 '(("d" . 86400.0) ("w" . 604800.0)
10543 ("m" . 2678400.0) ("y" . 31557600.0)))))))
10544 (t (org-2ft s)))))
10546 (defun org-match-any-p (re list)
10547 "Does re match any element of list?"
10548 (setq list (mapcar (lambda (x) (string-match re x)) list))
10549 (delq nil list))
10551 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
10552 (defvar org-tags-overlay (org-make-overlay 1 1))
10553 (org-detach-overlay org-tags-overlay)
10555 (defun org-get-local-tags-at (&optional pos)
10556 "Get a list of tags defined in the current headline."
10557 (org-get-tags-at pos 'local))
10559 (defun org-get-local-tags ()
10560 "Get a list of tags defined in the current headline."
10561 (org-get-tags-at nil 'local))
10563 (defun org-get-tags-at (&optional pos local)
10564 "Get a list of all headline tags applicable at POS.
10565 POS defaults to point. If tags are inherited, the list contains
10566 the targets in the same sequence as the headlines appear, i.e.
10567 the tags of the current headline come last.
10568 When LOCAL is non-nil, only return tags from the current headline,
10569 ignore inherited ones."
10570 (interactive)
10571 (if (and org-trust-scanner-tags
10572 (or (not pos) (equal pos (point)))
10573 (not local))
10574 org-scanner-tags
10575 (let (tags ltags lastpos parent)
10576 (save-excursion
10577 (save-restriction
10578 (widen)
10579 (goto-char (or pos (point)))
10580 (save-match-data
10581 (catch 'done
10582 (condition-case nil
10583 (progn
10584 (org-back-to-heading t)
10585 (while (not (equal lastpos (point)))
10586 (setq lastpos (point))
10587 (when (looking-at
10588 (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
10589 (setq ltags (org-split-string
10590 (org-match-string-no-properties 1) ":"))
10591 (when parent
10592 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
10593 (setq tags (append
10594 (if parent
10595 (org-remove-uniherited-tags ltags)
10596 ltags)
10597 tags)))
10598 (or org-use-tag-inheritance (throw 'done t))
10599 (if local (throw 'done t))
10600 (or (org-up-heading-safe) (error nil))
10601 (setq parent t)))
10602 (error nil)))))
10603 (append (org-remove-uniherited-tags org-file-tags) tags)))))
10605 (defun org-add-prop-inherited (s)
10606 (add-text-properties 0 (length s) '(inherited t) s)
10609 (defun org-toggle-tag (tag &optional onoff)
10610 "Toggle the tag TAG for the current line.
10611 If ONOFF is `on' or `off', don't toggle but set to this state."
10612 (let (res current)
10613 (save-excursion
10614 (org-back-to-heading t)
10615 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
10616 (point-at-eol) t)
10617 (progn
10618 (setq current (match-string 1))
10619 (replace-match ""))
10620 (setq current ""))
10621 (setq current (nreverse (org-split-string current ":")))
10622 (cond
10623 ((eq onoff 'on)
10624 (setq res t)
10625 (or (member tag current) (push tag current)))
10626 ((eq onoff 'off)
10627 (or (not (member tag current)) (setq current (delete tag current))))
10628 (t (if (member tag current)
10629 (setq current (delete tag current))
10630 (setq res t)
10631 (push tag current))))
10632 (end-of-line 1)
10633 (if current
10634 (progn
10635 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
10636 (org-set-tags nil t))
10637 (delete-horizontal-space))
10638 (run-hooks 'org-after-tags-change-hook))
10639 res))
10641 (defun org-align-tags-here (to-col)
10642 ;; Assumes that this is a headline
10643 (let ((pos (point)) (col (current-column)) ncol tags-l p)
10644 (beginning-of-line 1)
10645 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10646 (< pos (match-beginning 2)))
10647 (progn
10648 (setq tags-l (- (match-end 2) (match-beginning 2)))
10649 (goto-char (match-beginning 1))
10650 (insert " ")
10651 (delete-region (point) (1+ (match-beginning 2)))
10652 (setq ncol (max (1+ (current-column))
10653 (1+ col)
10654 (if (> to-col 0)
10655 to-col
10656 (- (abs to-col) tags-l))))
10657 (setq p (point))
10658 (insert (make-string (- ncol (current-column)) ?\ ))
10659 (setq ncol (current-column))
10660 (when indent-tabs-mode (tabify p (point-at-eol)))
10661 (org-move-to-column (min ncol col) t))
10662 (goto-char pos))))
10664 (defun org-set-tags-command (&optional arg just-align)
10665 "Call the set-tags command for the current entry."
10666 (interactive "P")
10667 (if (org-on-heading-p)
10668 (org-set-tags arg just-align)
10669 (save-excursion
10670 (org-back-to-heading t)
10671 (org-set-tags arg just-align))))
10673 (defun org-set-tags (&optional arg just-align)
10674 "Set the tags for the current headline.
10675 With prefix ARG, realign all tags in headings in the current buffer."
10676 (interactive "P")
10677 (let* ((re (concat "^" outline-regexp))
10678 (current (org-get-tags-string))
10679 (col (current-column))
10680 (org-setting-tags t)
10681 table current-tags inherited-tags ; computed below when needed
10682 tags p0 c0 c1 rpl)
10683 (if arg
10684 (save-excursion
10685 (goto-char (point-min))
10686 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
10687 (while (re-search-forward re nil t)
10688 (org-set-tags nil t)
10689 (end-of-line 1)))
10690 (message "All tags realigned to column %d" org-tags-column))
10691 (if just-align
10692 (setq tags current)
10693 ;; Get a new set of tags from the user
10694 (save-excursion
10695 (setq table (append org-tag-persistent-alist
10696 (or org-tag-alist (org-get-buffer-tags)))
10697 org-last-tags-completion-table table
10698 current-tags (org-split-string current ":")
10699 inherited-tags (nreverse
10700 (nthcdr (length current-tags)
10701 (nreverse (org-get-tags-at))))
10702 tags
10703 (if (or (eq t org-use-fast-tag-selection)
10704 (and org-use-fast-tag-selection
10705 (delq nil (mapcar 'cdr table))))
10706 (org-fast-tag-selection
10707 current-tags inherited-tags table
10708 (if org-fast-tag-selection-include-todo org-todo-key-alist))
10709 (let ((org-add-colon-after-tag-completion t))
10710 (org-trim
10711 (org-without-partial-completion
10712 (org-ido-completing-read "Tags: " 'org-tags-completion-function
10713 nil nil current 'org-tags-history)))))))
10714 (while (string-match "[-+&]+" tags)
10715 ;; No boolean logic, just a list
10716 (setq tags (replace-match ":" t t tags))))
10718 (if (string-match "\\`[\t ]*\\'" tags)
10719 (setq tags "")
10720 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
10721 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
10723 ;; Insert new tags at the correct column
10724 (beginning-of-line 1)
10725 (cond
10726 ((and (equal current "") (equal tags "")))
10727 ((re-search-forward
10728 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
10729 (point-at-eol) t)
10730 (if (equal tags "")
10731 (setq rpl "")
10732 (goto-char (match-beginning 0))
10733 (setq c0 (current-column) p0 (point)
10734 c1 (max (1+ c0) (if (> org-tags-column 0)
10735 org-tags-column
10736 (- (- org-tags-column) (length tags))))
10737 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
10738 (replace-match rpl t t)
10739 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
10740 tags)
10741 (t (error "Tags alignment failed")))
10742 (org-move-to-column col)
10743 (unless just-align
10744 (run-hooks 'org-after-tags-change-hook)))))
10746 (defun org-change-tag-in-region (beg end tag off)
10747 "Add or remove TAG for each entry in the region.
10748 This works in the agenda, and also in an org-mode buffer."
10749 (interactive
10750 (list (region-beginning) (region-end)
10751 (let ((org-last-tags-completion-table
10752 (if (org-mode-p)
10753 (org-get-buffer-tags)
10754 (org-global-tags-completion-table))))
10755 (org-ido-completing-read
10756 "Tag: " 'org-tags-completion-function nil nil nil
10757 'org-tags-history))
10758 (progn
10759 (message "[s]et or [r]emove? ")
10760 (equal (read-char-exclusive) ?r))))
10761 (if (fboundp 'deactivate-mark) (deactivate-mark))
10762 (let ((agendap (equal major-mode 'org-agenda-mode))
10763 l1 l2 m buf pos newhead (cnt 0))
10764 (goto-char end)
10765 (setq l2 (1- (org-current-line)))
10766 (goto-char beg)
10767 (setq l1 (org-current-line))
10768 (loop for l from l1 to l2 do
10769 (goto-line l)
10770 (setq m (get-text-property (point) 'org-hd-marker))
10771 (when (or (and (org-mode-p) (org-on-heading-p))
10772 (and agendap m))
10773 (setq buf (if agendap (marker-buffer m) (current-buffer))
10774 pos (if agendap m (point)))
10775 (with-current-buffer buf
10776 (save-excursion
10777 (save-restriction
10778 (goto-char pos)
10779 (setq cnt (1+ cnt))
10780 (org-toggle-tag tag (if off 'off 'on))
10781 (setq newhead (org-get-heading)))))
10782 (and agendap (org-agenda-change-all-lines newhead m))))
10783 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
10785 (defun org-tags-completion-function (string predicate &optional flag)
10786 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
10787 (confirm (lambda (x) (stringp (car x)))))
10788 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
10789 (setq s1 (match-string 1 string)
10790 s2 (match-string 2 string))
10791 (setq s1 "" s2 string))
10792 (cond
10793 ((eq flag nil)
10794 ;; try completion
10795 (setq rtn (try-completion s2 ctable confirm))
10796 (if (stringp rtn)
10797 (setq rtn
10798 (concat s1 s2 (substring rtn (length s2))
10799 (if (and org-add-colon-after-tag-completion
10800 (assoc rtn ctable))
10801 ":" ""))))
10802 rtn)
10803 ((eq flag t)
10804 ;; all-completions
10805 (all-completions s2 ctable confirm)
10807 ((eq flag 'lambda)
10808 ;; exact match?
10809 (assoc s2 ctable)))
10812 (defun org-fast-tag-insert (kwd tags face &optional end)
10813 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
10814 (insert (format "%-12s" (concat kwd ":"))
10815 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
10816 (or end "")))
10818 (defun org-fast-tag-show-exit (flag)
10819 (save-excursion
10820 (goto-line 3)
10821 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
10822 (replace-match ""))
10823 (when flag
10824 (end-of-line 1)
10825 (org-move-to-column (- (window-width) 19) t)
10826 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
10828 (defun org-set-current-tags-overlay (current prefix)
10829 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
10830 (if (featurep 'xemacs)
10831 (org-overlay-display org-tags-overlay (concat prefix s)
10832 'secondary-selection)
10833 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
10834 (org-overlay-display org-tags-overlay (concat prefix s)))))
10836 (defun org-fast-tag-selection (current inherited table &optional todo-table)
10837 "Fast tag selection with single keys.
10838 CURRENT is the current list of tags in the headline, INHERITED is the
10839 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
10840 possibly with grouping information. TODO-TABLE is a similar table with
10841 TODO keywords, should these have keys assigned to them.
10842 If the keys are nil, a-z are automatically assigned.
10843 Returns the new tags string, or nil to not change the current settings."
10844 (let* ((fulltable (append table todo-table))
10845 (maxlen (apply 'max (mapcar
10846 (lambda (x)
10847 (if (stringp (car x)) (string-width (car x)) 0))
10848 fulltable)))
10849 (buf (current-buffer))
10850 (expert (eq org-fast-tag-selection-single-key 'expert))
10851 (buffer-tags nil)
10852 (fwidth (+ maxlen 3 1 3))
10853 (ncol (/ (- (window-width) 4) fwidth))
10854 (i-face 'org-done)
10855 (c-face 'org-todo)
10856 tg cnt e c char c1 c2 ntable tbl rtn
10857 ov-start ov-end ov-prefix
10858 (exit-after-next org-fast-tag-selection-single-key)
10859 (done-keywords org-done-keywords)
10860 groups ingroup)
10861 (save-excursion
10862 (beginning-of-line 1)
10863 (if (looking-at
10864 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10865 (setq ov-start (match-beginning 1)
10866 ov-end (match-end 1)
10867 ov-prefix "")
10868 (setq ov-start (1- (point-at-eol))
10869 ov-end (1+ ov-start))
10870 (skip-chars-forward "^\n\r")
10871 (setq ov-prefix
10872 (concat
10873 (buffer-substring (1- (point)) (point))
10874 (if (> (current-column) org-tags-column)
10876 (make-string (- org-tags-column (current-column)) ?\ ))))))
10877 (org-move-overlay org-tags-overlay ov-start ov-end)
10878 (save-window-excursion
10879 (if expert
10880 (set-buffer (get-buffer-create " *Org tags*"))
10881 (delete-other-windows)
10882 (split-window-vertically)
10883 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
10884 (erase-buffer)
10885 (org-set-local 'org-done-keywords done-keywords)
10886 (org-fast-tag-insert "Inherited" inherited i-face "\n")
10887 (org-fast-tag-insert "Current" current c-face "\n\n")
10888 (org-fast-tag-show-exit exit-after-next)
10889 (org-set-current-tags-overlay current ov-prefix)
10890 (setq tbl fulltable char ?a cnt 0)
10891 (while (setq e (pop tbl))
10892 (cond
10893 ((equal e '(:startgroup))
10894 (push '() groups) (setq ingroup t)
10895 (when (not (= cnt 0))
10896 (setq cnt 0)
10897 (insert "\n"))
10898 (insert "{ "))
10899 ((equal e '(:endgroup))
10900 (setq ingroup nil cnt 0)
10901 (insert "}\n"))
10902 ((equal e '(:newline))
10903 (when (not (= cnt 0))
10904 (setq cnt 0)
10905 (insert "\n")
10906 (setq e (car tbl))
10907 (while (equal (car tbl) '(:newline))
10908 (insert "\n")
10909 (setq tbl (cdr tbl)))))
10911 (setq tg (car e) c2 nil)
10912 (if (cdr e)
10913 (setq c (cdr e))
10914 ;; automatically assign a character.
10915 (setq c1 (string-to-char
10916 (downcase (substring
10917 tg (if (= (string-to-char tg) ?@) 1 0)))))
10918 (if (or (rassoc c1 ntable) (rassoc c1 table))
10919 (while (or (rassoc char ntable) (rassoc char table))
10920 (setq char (1+ char)))
10921 (setq c2 c1))
10922 (setq c (or c2 char)))
10923 (if ingroup (push tg (car groups)))
10924 (setq tg (org-add-props tg nil 'face
10925 (cond
10926 ((not (assoc tg table))
10927 (org-get-todo-face tg))
10928 ((member tg current) c-face)
10929 ((member tg inherited) i-face)
10930 (t nil))))
10931 (if (and (= cnt 0) (not ingroup)) (insert " "))
10932 (insert "[" c "] " tg (make-string
10933 (- fwidth 4 (length tg)) ?\ ))
10934 (push (cons tg c) ntable)
10935 (when (= (setq cnt (1+ cnt)) ncol)
10936 (insert "\n")
10937 (if ingroup (insert " "))
10938 (setq cnt 0)))))
10939 (setq ntable (nreverse ntable))
10940 (insert "\n")
10941 (goto-char (point-min))
10942 (if (not expert) (org-fit-window-to-buffer))
10943 (setq rtn
10944 (catch 'exit
10945 (while t
10946 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
10947 (if groups " [!] no groups" " [!]groups")
10948 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
10949 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
10950 (cond
10951 ((= c ?\r) (throw 'exit t))
10952 ((= c ?!)
10953 (setq groups (not groups))
10954 (goto-char (point-min))
10955 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
10956 ((= c ?\C-c)
10957 (if (not expert)
10958 (org-fast-tag-show-exit
10959 (setq exit-after-next (not exit-after-next)))
10960 (setq expert nil)
10961 (delete-other-windows)
10962 (split-window-vertically)
10963 (org-switch-to-buffer-other-window " *Org tags*")
10964 (org-fit-window-to-buffer)))
10965 ((or (= c ?\C-g)
10966 (and (= c ?q) (not (rassoc c ntable))))
10967 (org-detach-overlay org-tags-overlay)
10968 (setq quit-flag t))
10969 ((= c ?\ )
10970 (setq current nil)
10971 (if exit-after-next (setq exit-after-next 'now)))
10972 ((= c ?\t)
10973 (condition-case nil
10974 (setq tg (org-ido-completing-read
10975 "Tag: "
10976 (or buffer-tags
10977 (with-current-buffer buf
10978 (org-get-buffer-tags)))))
10979 (quit (setq tg "")))
10980 (when (string-match "\\S-" tg)
10981 (add-to-list 'buffer-tags (list tg))
10982 (if (member tg current)
10983 (setq current (delete tg current))
10984 (push tg current)))
10985 (if exit-after-next (setq exit-after-next 'now)))
10986 ((setq e (rassoc c todo-table) tg (car e))
10987 (with-current-buffer buf
10988 (save-excursion (org-todo tg)))
10989 (if exit-after-next (setq exit-after-next 'now)))
10990 ((setq e (rassoc c ntable) tg (car e))
10991 (if (member tg current)
10992 (setq current (delete tg current))
10993 (loop for g in groups do
10994 (if (member tg g)
10995 (mapc (lambda (x)
10996 (setq current (delete x current)))
10997 g)))
10998 (push tg current))
10999 (if exit-after-next (setq exit-after-next 'now))))
11001 ;; Create a sorted list
11002 (setq current
11003 (sort current
11004 (lambda (a b)
11005 (assoc b (cdr (memq (assoc a ntable) ntable))))))
11006 (if (eq exit-after-next 'now) (throw 'exit t))
11007 (goto-char (point-min))
11008 (beginning-of-line 2)
11009 (delete-region (point) (point-at-eol))
11010 (org-fast-tag-insert "Current" current c-face)
11011 (org-set-current-tags-overlay current ov-prefix)
11012 (while (re-search-forward
11013 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
11014 (setq tg (match-string 1))
11015 (add-text-properties
11016 (match-beginning 1) (match-end 1)
11017 (list 'face
11018 (cond
11019 ((member tg current) c-face)
11020 ((member tg inherited) i-face)
11021 (t (get-text-property (match-beginning 1) 'face))))))
11022 (goto-char (point-min)))))
11023 (org-detach-overlay org-tags-overlay)
11024 (if rtn
11025 (mapconcat 'identity current ":")
11026 nil))))
11028 (defun org-get-tags-string ()
11029 "Get the TAGS string in the current headline."
11030 (unless (org-on-heading-p t)
11031 (error "Not on a heading"))
11032 (save-excursion
11033 (beginning-of-line 1)
11034 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11035 (org-match-string-no-properties 1)
11036 "")))
11038 (defun org-get-tags ()
11039 "Get the list of tags specified in the current headline."
11040 (org-split-string (org-get-tags-string) ":"))
11042 (defun org-get-buffer-tags ()
11043 "Get a table of all tags used in the buffer, for completion."
11044 (let (tags)
11045 (save-excursion
11046 (goto-char (point-min))
11047 (while (re-search-forward
11048 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
11049 (when (equal (char-after (point-at-bol 0)) ?*)
11050 (mapc (lambda (x) (add-to-list 'tags x))
11051 (org-split-string (org-match-string-no-properties 1) ":")))))
11052 (mapcar 'list tags)))
11054 ;;;; The mapping API
11056 ;;;###autoload
11057 (defun org-map-entries (func &optional match scope &rest skip)
11058 "Call FUNC at each headline selected by MATCH in SCOPE.
11060 FUNC is a function or a lisp form. The function will be called without
11061 arguments, with the cursor positioned at the beginning of the headline.
11062 The return values of all calls to the function will be collected and
11063 returned as a list.
11065 The call to FUNC will be wrapped into a save-excursion form, so FUNC
11066 does not need to preserve point. After evaluaton, the cursor will be
11067 moved to the end of the line (presumably of the headline of the
11068 processed entry) and search continues from there. Under some
11069 circumstances, this may not produce the wanted results. For example,
11070 if you have removed (e.g. archived) the current (sub)tree it could
11071 mean that the next entry will be skipped entirely. In such cases, you
11072 can specify the position from where search should continue by making
11073 FUNC set the variable `org-map-continue-from' to the desired buffer
11074 position.
11076 MATCH is a tags/property/todo match as it is used in the agenda tags view.
11077 Only headlines that are matched by this query will be considered during
11078 the iteration. When MATCH is nil or t, all headlines will be
11079 visited by the iteration.
11081 SCOPE determines the scope of this command. It can be any of:
11083 nil The current buffer, respecting the restriction if any
11084 tree The subtree started with the entry at point
11085 file The current buffer, without restriction
11086 file-with-archives
11087 The current buffer, and any archives associated with it
11088 agenda All agenda files
11089 agenda-with-archives
11090 All agenda files with any archive files associated with them
11091 \(file1 file2 ...)
11092 If this is a list, all files in the list will be scanned
11094 The remaining args are treated as settings for the skipping facilities of
11095 the scanner. The following items can be given here:
11097 archive skip trees with the archive tag.
11098 comment skip trees with the COMMENT keyword
11099 function or Emacs Lisp form:
11100 will be used as value for `org-agenda-skip-function', so whenever
11101 the the function returns t, FUNC will not be called for that
11102 entry and search will continue from the point where the
11103 function leaves it.
11105 If your function needs to retrieve the tags including inherited tags
11106 at the *current* entry, you can use the value of the variable
11107 `org-scanner-tags' which will be much faster than getting the value
11108 with `org-get-tags-at'. If your function gets properties with
11109 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
11110 to t around the call to `org-entry-properties' to get the same speedup.
11111 Note that if your function moves around to retrieve tags and properties at
11112 a *different* entry, you cannot use these techniques."
11113 (let* ((org-agenda-archives-mode nil) ; just to make sure
11114 (org-agenda-skip-archived-trees (memq 'archive skip))
11115 (org-agenda-skip-comment-trees (memq 'comment skip))
11116 (org-agenda-skip-function
11117 (car (org-delete-all '(comment archive) skip)))
11118 (org-tags-match-list-sublevels t)
11119 matcher file res
11120 org-todo-keywords-for-agenda
11121 org-done-keywords-for-agenda
11122 org-todo-keyword-alist-for-agenda
11123 org-tag-alist-for-agenda)
11125 (cond
11126 ((eq match t) (setq matcher t))
11127 ((eq match nil) (setq matcher t))
11128 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
11130 (save-excursion
11131 (save-restriction
11132 (when (eq scope 'tree)
11133 (org-back-to-heading t)
11134 (org-narrow-to-subtree)
11135 (setq scope nil))
11137 (if (not scope)
11138 (progn
11139 (org-prepare-agenda-buffers
11140 (list (buffer-file-name (current-buffer))))
11141 (setq res (org-scan-tags func matcher)))
11142 ;; Get the right scope
11143 (cond
11144 ((and scope (listp scope) (symbolp (car scope)))
11145 (setq scope (eval scope)))
11146 ((eq scope 'agenda)
11147 (setq scope (org-agenda-files t)))
11148 ((eq scope 'agenda-with-archives)
11149 (setq scope (org-agenda-files t))
11150 (setq scope (org-add-archive-files scope)))
11151 ((eq scope 'file)
11152 (setq scope (list (buffer-file-name))))
11153 ((eq scope 'file-with-archives)
11154 (setq scope (org-add-archive-files (list (buffer-file-name))))))
11155 (org-prepare-agenda-buffers scope)
11156 (while (setq file (pop scope))
11157 (with-current-buffer (org-find-base-buffer-visiting file)
11158 (save-excursion
11159 (save-restriction
11160 (widen)
11161 (goto-char (point-min))
11162 (setq res (append res (org-scan-tags func matcher))))))))))
11163 res))
11165 ;;;; Properties
11167 ;;; Setting and retrieving properties
11169 (defconst org-special-properties
11170 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
11171 "TIMESTAMP" "TIMESTAMP_IA")
11172 "The special properties valid in Org-mode.
11174 These are properties that are not defined in the property drawer,
11175 but in some other way.")
11177 (defconst org-default-properties
11178 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
11179 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
11180 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
11181 "EXPORT_FILE_NAME" "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
11182 "ORDERED" "NOBLOCKING" "COOKIE_DATA")
11183 "Some properties that are used by Org-mode for various purposes.
11184 Being in this list makes sure that they are offered for completion.")
11186 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
11187 "Regular expression matching the first line of a property drawer.")
11189 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
11190 "Regular expression matching the first line of a property drawer.")
11192 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
11193 "Regular expression matching the first line of a property drawer.")
11195 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
11196 "Regular expression matching the first line of a property drawer.")
11198 (defconst org-property-drawer-re
11199 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
11200 org-property-end-re "\\)\n?")
11201 "Matches an entire property drawer.")
11203 (defconst org-clock-drawer-re
11204 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
11205 org-property-end-re "\\)\n?")
11206 "Matches an entire clock drawer.")
11208 (defun org-property-action ()
11209 "Do an action on properties."
11210 (interactive)
11211 (let (c)
11212 (org-at-property-p)
11213 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
11214 (setq c (read-char-exclusive))
11215 (cond
11216 ((equal c ?s)
11217 (call-interactively 'org-set-property))
11218 ((equal c ?d)
11219 (call-interactively 'org-delete-property))
11220 ((equal c ?D)
11221 (call-interactively 'org-delete-property-globally))
11222 ((equal c ?c)
11223 (call-interactively 'org-compute-property-at-point))
11224 (t (error "No such property action %c" c)))))
11226 (defun org-at-property-p ()
11227 "Is the cursor in a property line?"
11228 ;; FIXME: Does not check if we are actually in the drawer.
11229 ;; FIXME: also returns true on any drawers.....
11230 ;; This is used by C-c C-c for property action.
11231 (save-excursion
11232 (beginning-of-line 1)
11233 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
11235 (defun org-get-property-block (&optional beg end force)
11236 "Return the (beg . end) range of the body of the property drawer.
11237 BEG and END can be beginning and end of subtree, if not given
11238 they will be found.
11239 If the drawer does not exist and FORCE is non-nil, create the drawer."
11240 (catch 'exit
11241 (save-excursion
11242 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
11243 (end (or end (progn (outline-next-heading) (point)))))
11244 (goto-char beg)
11245 (if (re-search-forward org-property-start-re end t)
11246 (setq beg (1+ (match-end 0)))
11247 (if force
11248 (save-excursion
11249 (org-insert-property-drawer)
11250 (setq end (progn (outline-next-heading) (point))))
11251 (throw 'exit nil))
11252 (goto-char beg)
11253 (if (re-search-forward org-property-start-re end t)
11254 (setq beg (1+ (match-end 0)))))
11255 (if (re-search-forward org-property-end-re end t)
11256 (setq end (match-beginning 0))
11257 (or force (throw 'exit nil))
11258 (goto-char beg)
11259 (setq end beg)
11260 (org-indent-line-function)
11261 (insert ":END:\n"))
11262 (cons beg end)))))
11264 (defun org-entry-properties (&optional pom which)
11265 "Get all properties of the entry at point-or-marker POM.
11266 This includes the TODO keyword, the tags, time strings for deadline,
11267 scheduled, and clocking, and any additional properties defined in the
11268 entry. The return value is an alist, keys may occur multiple times
11269 if the property key was used several times.
11270 POM may also be nil, in which case the current entry is used.
11271 If WHICH is nil or `all', get all properties. If WHICH is
11272 `special' or `standard', only get that subclass."
11273 (setq which (or which 'all))
11274 (org-with-point-at pom
11275 (let ((clockstr (substring org-clock-string 0 -1))
11276 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
11277 beg end range props sum-props key value string clocksum)
11278 (save-excursion
11279 (when (condition-case nil
11280 (and (org-mode-p) (org-back-to-heading t))
11281 (error nil))
11282 (setq beg (point))
11283 (setq sum-props (get-text-property (point) 'org-summaries))
11284 (setq clocksum (get-text-property (point) :org-clock-minutes))
11285 (outline-next-heading)
11286 (setq end (point))
11287 (when (memq which '(all special))
11288 ;; Get the special properties, like TODO and tags
11289 (goto-char beg)
11290 (when (and (looking-at org-todo-line-regexp) (match-end 2))
11291 (push (cons "TODO" (org-match-string-no-properties 2)) props))
11292 (when (looking-at org-priority-regexp)
11293 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
11294 (when (and (setq value (org-get-tags-string))
11295 (string-match "\\S-" value))
11296 (push (cons "TAGS" value) props))
11297 (when (setq value (org-get-tags-at))
11298 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
11299 props))
11300 (while (re-search-forward org-maybe-keyword-time-regexp end t)
11301 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
11302 string (if (equal key clockstr)
11303 (org-no-properties
11304 (org-trim
11305 (buffer-substring
11306 (match-beginning 3) (goto-char (point-at-eol)))))
11307 (substring (org-match-string-no-properties 3) 1 -1)))
11308 (unless key
11309 (if (= (char-after (match-beginning 3)) ?\[)
11310 (setq key "TIMESTAMP_IA")
11311 (setq key "TIMESTAMP")))
11312 (when (or (equal key clockstr) (not (assoc key props)))
11313 (push (cons key string) props)))
11317 (when (memq which '(all standard))
11318 ;; Get the standard properties, like :PROP: ...
11319 (setq range (org-get-property-block beg end))
11320 (when range
11321 (goto-char (car range))
11322 (while (re-search-forward
11323 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
11324 (cdr range) t)
11325 (setq key (org-match-string-no-properties 1)
11326 value (org-trim (or (org-match-string-no-properties 2) "")))
11327 (unless (member key excluded)
11328 (push (cons key (or value "")) props)))))
11329 (if clocksum
11330 (push (cons "CLOCKSUM"
11331 (org-columns-number-to-string (/ (float clocksum) 60.)
11332 'add_times))
11333 props))
11334 (unless (assoc "CATEGORY" props)
11335 (setq value (or (org-get-category)
11336 (progn (org-refresh-category-properties)
11337 (org-get-category))))
11338 (push (cons "CATEGORY" value) props))
11339 (append sum-props (nreverse props)))))))
11341 (defun org-entry-get (pom property &optional inherit)
11342 "Get value of PROPERTY for entry at point-or-marker POM.
11343 If INHERIT is non-nil and the entry does not have the property,
11344 then also check higher levels of the hierarchy.
11345 If INHERIT is the symbol `selective', use inheritance only if the setting
11346 in `org-use-property-inheritance' selects PROPERTY for inheritance.
11347 If the property is present but empty, the return value is the empty string.
11348 If the property is not present at all, nil is returned."
11349 (org-with-point-at pom
11350 (if (and inherit (if (eq inherit 'selective)
11351 (org-property-inherit-p property)
11353 (org-entry-get-with-inheritance property)
11354 (if (member property org-special-properties)
11355 ;; We need a special property. Use brute force, get all properties.
11356 (cdr (assoc property (org-entry-properties nil 'special)))
11357 (let ((range (org-get-property-block)))
11358 (if (and range
11359 (goto-char (car range))
11360 (re-search-forward
11361 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
11362 (cdr range) t))
11363 ;; Found the property, return it.
11364 (if (match-end 1)
11365 (org-match-string-no-properties 1)
11366 "")))))))
11368 (defun org-property-or-variable-value (var &optional inherit)
11369 "Check if there is a property fixing the value of VAR.
11370 If yes, return this value. If not, return the current value of the variable."
11371 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
11372 (if (and prop (stringp prop) (string-match "\\S-" prop))
11373 (read prop)
11374 (symbol-value var))))
11376 (defun org-entry-delete (pom property)
11377 "Delete the property PROPERTY from entry at point-or-marker POM."
11378 (org-with-point-at pom
11379 (if (member property org-special-properties)
11380 nil ; cannot delete these properties.
11381 (let ((range (org-get-property-block)))
11382 (if (and range
11383 (goto-char (car range))
11384 (re-search-forward
11385 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
11386 (cdr range) t))
11387 (progn
11388 (delete-region (match-beginning 0) (1+ (point-at-eol)))
11390 nil)))))
11392 ;; Multi-values properties are properties that contain multiple values
11393 ;; These values are assumed to be single words, separated by whitespace.
11394 (defun org-entry-add-to-multivalued-property (pom property value)
11395 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
11396 (let* ((old (org-entry-get pom property))
11397 (values (and old (org-split-string old "[ \t]"))))
11398 (setq value (org-entry-protect-space value))
11399 (unless (member value values)
11400 (setq values (cons value values))
11401 (org-entry-put pom property
11402 (mapconcat 'identity values " ")))))
11404 (defun org-entry-remove-from-multivalued-property (pom property value)
11405 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
11406 (let* ((old (org-entry-get pom property))
11407 (values (and old (org-split-string old "[ \t]"))))
11408 (setq value (org-entry-protect-space value))
11409 (when (member value values)
11410 (setq values (delete value values))
11411 (org-entry-put pom property
11412 (mapconcat 'identity values " ")))))
11414 (defun org-entry-member-in-multivalued-property (pom property value)
11415 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
11416 (let* ((old (org-entry-get pom property))
11417 (values (and old (org-split-string old "[ \t]"))))
11418 (setq value (org-entry-protect-space value))
11419 (member value values)))
11421 (defun org-entry-get-multivalued-property (pom property)
11422 "Return a list of values in a multivalued property."
11423 (let* ((value (org-entry-get pom property))
11424 (values (and value (org-split-string value "[ \t]"))))
11425 (mapcar 'org-entry-restore-space values)))
11427 (defun org-entry-put-multivalued-property (pom property &rest values)
11428 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
11429 VALUES should be a list of strings. Spaces will be protected."
11430 (org-entry-put pom property
11431 (mapconcat 'org-entry-protect-space values " "))
11432 (let* ((value (org-entry-get pom property))
11433 (values (and value (org-split-string value "[ \t]"))))
11434 (mapcar 'org-entry-restore-space values)))
11436 (defun org-entry-protect-space (s)
11437 "Protect spaces and newline in string S."
11438 (while (string-match " " s)
11439 (setq s (replace-match "%20" t t s)))
11440 (while (string-match "\n" s)
11441 (setq s (replace-match "%0A" t t s)))
11444 (defun org-entry-restore-space (s)
11445 "Restore spaces and newline in string S."
11446 (while (string-match "%20" s)
11447 (setq s (replace-match " " t t s)))
11448 (while (string-match "%0A" s)
11449 (setq s (replace-match "\n" t t s)))
11452 (defvar org-entry-property-inherited-from (make-marker)
11453 "Marker pointing to the entry from where a property was inherited.
11454 Each call to `org-entry-get-with-inheritance' will set this marker to the
11455 location of the entry where the inheritance search matched. If there was
11456 no match, the marker will point nowhere.
11457 Note that also `org-entry-get' calls this function, if the INHERIT flag
11458 is set.")
11460 (defun org-entry-get-with-inheritance (property)
11461 "Get entry property, and search higher levels if not present."
11462 (move-marker org-entry-property-inherited-from nil)
11463 (let (tmp)
11464 (save-excursion
11465 (save-restriction
11466 (widen)
11467 (catch 'ex
11468 (while t
11469 (when (setq tmp (org-entry-get nil property))
11470 (org-back-to-heading t)
11471 (move-marker org-entry-property-inherited-from (point))
11472 (throw 'ex tmp))
11473 (or (org-up-heading-safe) (throw 'ex nil)))))
11474 (or tmp
11475 (cdr (assoc property org-file-properties))
11476 (cdr (assoc property org-global-properties))
11477 (cdr (assoc property org-global-properties-fixed))))))
11479 (defun org-entry-put (pom property value)
11480 "Set PROPERTY to VALUE for entry at point-or-marker POM."
11481 (org-with-point-at pom
11482 (org-back-to-heading t)
11483 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
11484 range)
11485 (cond
11486 ((equal property "TODO")
11487 (when (and (stringp value) (string-match "\\S-" value)
11488 (not (member value org-todo-keywords-1)))
11489 (error "\"%s\" is not a valid TODO state" value))
11490 (if (or (not value)
11491 (not (string-match "\\S-" value)))
11492 (setq value 'none))
11493 (org-todo value)
11494 (org-set-tags nil 'align))
11495 ((equal property "PRIORITY")
11496 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
11497 (string-to-char value) ?\ ))
11498 (org-set-tags nil 'align))
11499 ((equal property "SCHEDULED")
11500 (if (re-search-forward org-scheduled-time-regexp end t)
11501 (cond
11502 ((eq value 'earlier) (org-timestamp-change -1 'day))
11503 ((eq value 'later) (org-timestamp-change 1 'day))
11504 (t (call-interactively 'org-schedule)))
11505 (call-interactively 'org-schedule)))
11506 ((equal property "DEADLINE")
11507 (if (re-search-forward org-deadline-time-regexp end t)
11508 (cond
11509 ((eq value 'earlier) (org-timestamp-change -1 'day))
11510 ((eq value 'later) (org-timestamp-change 1 'day))
11511 (t (call-interactively 'org-deadline)))
11512 (call-interactively 'org-deadline)))
11513 ((member property org-special-properties)
11514 (error "The %s property can not yet be set with `org-entry-put'"
11515 property))
11516 (t ; a non-special property
11517 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
11518 (setq range (org-get-property-block beg end 'force))
11519 (goto-char (car range))
11520 (if (re-search-forward
11521 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
11522 (progn
11523 (delete-region (match-beginning 1) (match-end 1))
11524 (goto-char (match-beginning 1)))
11525 (goto-char (cdr range))
11526 (insert "\n")
11527 (backward-char 1)
11528 (org-indent-line-function)
11529 (insert ":" property ":"))
11530 (and value (insert " " value))
11531 (org-indent-line-function)))))))
11533 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
11534 "Get all property keys in the current buffer.
11535 With INCLUDE-SPECIALS, also list the special properties that reflect things
11536 like tags and TODO state.
11537 With INCLUDE-DEFAULTS, also include properties that has special meaning
11538 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
11539 With INCLUDE-COLUMNS, also include property names given in COLUMN
11540 formats in the current buffer."
11541 (let (rtn range cfmt s p)
11542 (save-excursion
11543 (save-restriction
11544 (widen)
11545 (goto-char (point-min))
11546 (while (re-search-forward org-property-start-re nil t)
11547 (setq range (org-get-property-block))
11548 (goto-char (car range))
11549 (while (re-search-forward
11550 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
11551 (cdr range) t)
11552 (add-to-list 'rtn (org-match-string-no-properties 1)))
11553 (outline-next-heading))))
11555 (when include-specials
11556 (setq rtn (append org-special-properties rtn)))
11558 (when include-defaults
11559 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
11561 (when include-columns
11562 (save-excursion
11563 (save-restriction
11564 (widen)
11565 (goto-char (point-min))
11566 (while (re-search-forward
11567 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
11568 nil t)
11569 (setq cfmt (match-string 2) s 0)
11570 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
11571 cfmt s)
11572 (setq s (match-end 0)
11573 p (match-string 1 cfmt))
11574 (unless (or (equal p "ITEM")
11575 (member p org-special-properties))
11576 (add-to-list 'rtn (match-string 1 cfmt))))))))
11578 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
11580 (defun org-property-values (key)
11581 "Return a list of all values of property KEY."
11582 (save-excursion
11583 (save-restriction
11584 (widen)
11585 (goto-char (point-min))
11586 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
11587 values)
11588 (while (re-search-forward re nil t)
11589 (add-to-list 'values (org-trim (match-string 1))))
11590 (delete "" values)))))
11592 (defun org-insert-property-drawer ()
11593 "Insert a property drawer into the current entry."
11594 (interactive)
11595 (org-back-to-heading t)
11596 (looking-at outline-regexp)
11597 (let ((indent (- (match-end 0)(match-beginning 0)))
11598 (beg (point))
11599 (re (concat "^[ \t]*" org-keyword-time-regexp))
11600 end hiddenp)
11601 (outline-next-heading)
11602 (setq end (point))
11603 (goto-char beg)
11604 (while (re-search-forward re end t))
11605 (setq hiddenp (org-invisible-p))
11606 (end-of-line 1)
11607 (and (equal (char-after) ?\n) (forward-char 1))
11608 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
11609 (if (member (match-string 1) '("CLOCK:" ":END:"))
11610 ;; just skip this line
11611 (beginning-of-line 2)
11612 ;; Drawer start, find the end
11613 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
11614 (beginning-of-line 1)))
11615 (org-skip-over-state-notes)
11616 (skip-chars-backward " \t\n\r")
11617 (if (eq (char-before) ?*) (forward-char 1))
11618 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
11619 (beginning-of-line 0)
11620 (org-indent-to-column indent)
11621 (beginning-of-line 2)
11622 (org-indent-to-column indent)
11623 (beginning-of-line 0)
11624 (if hiddenp
11625 (save-excursion
11626 (org-back-to-heading t)
11627 (hide-entry))
11628 (org-flag-drawer t))))
11630 (defun org-set-property (property value)
11631 "In the current entry, set PROPERTY to VALUE.
11632 When called interactively, this will prompt for a property name, offering
11633 completion on existing and default properties. And then it will prompt
11634 for a value, offering completion either on allowed values (via an inherited
11635 xxx_ALL property) or on existing values in other instances of this property
11636 in the current file."
11637 (interactive
11638 (let* ((completion-ignore-case t)
11639 (keys (org-buffer-property-keys nil t t))
11640 (prop0 (org-ido-completing-read "Property: " (mapcar 'list keys)))
11641 (prop (if (member prop0 keys)
11642 prop0
11643 (or (cdr (assoc (downcase prop0)
11644 (mapcar (lambda (x) (cons (downcase x) x))
11645 keys)))
11646 prop0)))
11647 (cur (org-entry-get nil prop))
11648 (allowed (org-property-get-allowed-values nil prop 'table))
11649 (existing (mapcar 'list (org-property-values prop)))
11650 (val (if allowed
11651 (org-completing-read "Value: " allowed nil 'req-match)
11652 (let (org-completion-use-ido)
11653 (org-completing-read
11654 (concat "Value" (if (and cur (string-match "\\S-" cur))
11655 (concat "[" cur "]") "")
11656 ": ")
11657 existing nil nil "" nil cur)))))
11658 (list prop (if (equal val "") cur val))))
11659 (unless (equal (org-entry-get nil property) value)
11660 (org-entry-put nil property value)))
11662 (defun org-delete-property (property)
11663 "In the current entry, delete PROPERTY."
11664 (interactive
11665 (let* ((completion-ignore-case t)
11666 (prop (org-ido-completing-read
11667 "Property: " (org-entry-properties nil 'standard))))
11668 (list prop)))
11669 (message "Property %s %s" property
11670 (if (org-entry-delete nil property)
11671 "deleted"
11672 "was not present in the entry")))
11674 (defun org-delete-property-globally (property)
11675 "Remove PROPERTY globally, from all entries."
11676 (interactive
11677 (let* ((completion-ignore-case t)
11678 (prop (org-ido-completing-read
11679 "Globally remove property: "
11680 (mapcar 'list (org-buffer-property-keys)))))
11681 (list prop)))
11682 (save-excursion
11683 (save-restriction
11684 (widen)
11685 (goto-char (point-min))
11686 (let ((cnt 0))
11687 (while (re-search-forward
11688 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
11689 nil t)
11690 (setq cnt (1+ cnt))
11691 (replace-match ""))
11692 (message "Property \"%s\" removed from %d entries" property cnt)))))
11694 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
11696 (defun org-compute-property-at-point ()
11697 "Compute the property at point.
11698 This looks for an enclosing column format, extracts the operator and
11699 then applies it to the property in the column format's scope."
11700 (interactive)
11701 (unless (org-at-property-p)
11702 (error "Not at a property"))
11703 (let ((prop (org-match-string-no-properties 2)))
11704 (org-columns-get-format-and-top-level)
11705 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
11706 (error "No operator defined for property %s" prop))
11707 (org-columns-compute prop)))
11709 (defun org-property-get-allowed-values (pom property &optional table)
11710 "Get allowed values for the property PROPERTY.
11711 When TABLE is non-nil, return an alist that can directly be used for
11712 completion."
11713 (let (vals)
11714 (cond
11715 ((equal property "TODO")
11716 (setq vals (org-with-point-at pom
11717 (append org-todo-keywords-1 '("")))))
11718 ((equal property "PRIORITY")
11719 (let ((n org-lowest-priority))
11720 (while (>= n org-highest-priority)
11721 (push (char-to-string n) vals)
11722 (setq n (1- n)))))
11723 ((member property org-special-properties))
11725 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
11727 (when (and vals (string-match "\\S-" vals))
11728 (setq vals (car (read-from-string (concat "(" vals ")"))))
11729 (setq vals (mapcar (lambda (x)
11730 (cond ((stringp x) x)
11731 ((numberp x) (number-to-string x))
11732 ((symbolp x) (symbol-name x))
11733 (t "???")))
11734 vals)))))
11735 (if table (mapcar 'list vals) vals)))
11737 (defun org-property-previous-allowed-value (&optional previous)
11738 "Switch to the next allowed value for this property."
11739 (interactive)
11740 (org-property-next-allowed-value t))
11742 (defun org-property-next-allowed-value (&optional previous)
11743 "Switch to the next allowed value for this property."
11744 (interactive)
11745 (unless (org-at-property-p)
11746 (error "Not at a property"))
11747 (let* ((key (match-string 2))
11748 (value (match-string 3))
11749 (allowed (or (org-property-get-allowed-values (point) key)
11750 (and (member value '("[ ]" "[-]" "[X]"))
11751 '("[ ]" "[X]"))))
11752 nval)
11753 (unless allowed
11754 (error "Allowed values for this property have not been defined"))
11755 (if previous (setq allowed (reverse allowed)))
11756 (if (member value allowed)
11757 (setq nval (car (cdr (member value allowed)))))
11758 (setq nval (or nval (car allowed)))
11759 (if (equal nval value)
11760 (error "Only one allowed value for this property"))
11761 (org-at-property-p)
11762 (replace-match (concat " :" key ": " nval) t t)
11763 (org-indent-line-function)
11764 (beginning-of-line 1)
11765 (skip-chars-forward " \t")))
11767 (defun org-find-entry-with-id (ident)
11768 "Locate the entry that contains the ID property with exact value IDENT.
11769 IDENT can be a string, a symbol or a number, this function will search for
11770 the string representation of it.
11771 Return the position where this entry starts, or nil if there is no such entry."
11772 (interactive "sID: ")
11773 (let ((id (cond
11774 ((stringp ident) ident)
11775 ((symbol-name ident) (symbol-name ident))
11776 ((numberp ident) (number-to-string ident))
11777 (t (error "IDENT %s must be a string, symbol or number" ident))))
11778 (case-fold-search nil))
11779 (save-excursion
11780 (save-restriction
11781 (widen)
11782 (goto-char (point-min))
11783 (when (re-search-forward
11784 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
11785 nil t)
11786 (org-back-to-heading)
11787 (point))))))
11789 ;;;; Timestamps
11791 (defvar org-last-changed-timestamp nil)
11792 (defvar org-last-inserted-timestamp nil
11793 "The last time stamp inserted with `org-insert-time-stamp'.")
11794 (defvar org-time-was-given) ; dynamically scoped parameter
11795 (defvar org-end-time-was-given) ; dynamically scoped parameter
11796 (defvar org-ts-what) ; dynamically scoped parameter
11798 (defun org-time-stamp (arg &optional inactive)
11799 "Prompt for a date/time and insert a time stamp.
11800 If the user specifies a time like HH:MM, or if this command is called
11801 with a prefix argument, the time stamp will contain date and time.
11802 Otherwise, only the date will be included. All parts of a date not
11803 specified by the user will be filled in from the current date/time.
11804 So if you press just return without typing anything, the time stamp
11805 will represent the current date/time. If there is already a timestamp
11806 at the cursor, it will be modified."
11807 (interactive "P")
11808 (let* ((ts nil)
11809 (default-time
11810 ;; Default time is either today, or, when entering a range,
11811 ;; the range start.
11812 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
11813 (save-excursion
11814 (re-search-backward
11815 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
11816 (- (point) 20) t)))
11817 (apply 'encode-time (org-parse-time-string (match-string 1)))
11818 (current-time)))
11819 (default-input (and ts (org-get-compact-tod ts)))
11820 org-time-was-given org-end-time-was-given time)
11821 (cond
11822 ((and (org-at-timestamp-p t)
11823 (memq last-command '(org-time-stamp org-time-stamp-inactive))
11824 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
11825 (insert "--")
11826 (setq time (let ((this-command this-command))
11827 (org-read-date arg 'totime nil nil
11828 default-time default-input)))
11829 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
11830 ((org-at-timestamp-p t)
11831 (setq time (let ((this-command this-command))
11832 (org-read-date arg 'totime nil nil default-time default-input)))
11833 (when (org-at-timestamp-p t) ; just to get the match data
11834 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
11835 (replace-match "")
11836 (setq org-last-changed-timestamp
11837 (org-insert-time-stamp
11838 time (or org-time-was-given arg)
11839 inactive nil nil (list org-end-time-was-given))))
11840 (message "Timestamp updated"))
11842 (setq time (let ((this-command this-command))
11843 (org-read-date arg 'totime nil nil default-time default-input)))
11844 (org-insert-time-stamp time (or org-time-was-given arg) inactive
11845 nil nil (list org-end-time-was-given))))))
11847 ;; FIXME: can we use this for something else, like computing time differences?
11848 (defun org-get-compact-tod (s)
11849 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
11850 (let* ((t1 (match-string 1 s))
11851 (h1 (string-to-number (match-string 2 s)))
11852 (m1 (string-to-number (match-string 3 s)))
11853 (t2 (and (match-end 4) (match-string 5 s)))
11854 (h2 (and t2 (string-to-number (match-string 6 s))))
11855 (m2 (and t2 (string-to-number (match-string 7 s))))
11856 dh dm)
11857 (if (not t2)
11859 (setq dh (- h2 h1) dm (- m2 m1))
11860 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
11861 (concat t1 "+" (number-to-string dh)
11862 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
11864 (defun org-time-stamp-inactive (&optional arg)
11865 "Insert an inactive time stamp.
11866 An inactive time stamp is enclosed in square brackets instead of angle
11867 brackets. It is inactive in the sense that it does not trigger agenda entries,
11868 does not link to the calendar and cannot be changed with the S-cursor keys.
11869 So these are more for recording a certain time/date."
11870 (interactive "P")
11871 (org-time-stamp arg 'inactive))
11873 (defvar org-date-ovl (org-make-overlay 1 1))
11874 (org-overlay-put org-date-ovl 'face 'org-warning)
11875 (org-detach-overlay org-date-ovl)
11877 (defvar org-ans1) ; dynamically scoped parameter
11878 (defvar org-ans2) ; dynamically scoped parameter
11880 (defvar org-plain-time-of-day-regexp) ; defined below
11882 (defvar org-overriding-default-time nil) ; dynamically scoped
11883 (defvar org-read-date-overlay nil)
11884 (defvar org-dcst nil) ; dynamically scoped
11885 (defvar org-read-date-history nil)
11887 (defun org-read-date (&optional with-time to-time from-string prompt
11888 default-time default-input)
11889 "Read a date, possibly a time, and make things smooth for the user.
11890 The prompt will suggest to enter an ISO date, but you can also enter anything
11891 which will at least partially be understood by `parse-time-string'.
11892 Unrecognized parts of the date will default to the current day, month, year,
11893 hour and minute. If this command is called to replace a timestamp at point,
11894 of to enter the second timestamp of a range, the default time is taken from the
11895 existing stamp. For example,
11896 3-2-5 --> 2003-02-05
11897 feb 15 --> currentyear-02-15
11898 sep 12 9 --> 2009-09-12
11899 12:45 --> today 12:45
11900 22 sept 0:34 --> currentyear-09-22 0:34
11901 12 --> currentyear-currentmonth-12
11902 Fri --> nearest Friday (today or later)
11903 etc.
11905 Furthermore you can specify a relative date by giving, as the *first* thing
11906 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
11907 change in days weeks, months, years.
11908 With a single plus or minus, the date is relative to today. With a double
11909 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
11910 +4d --> four days from today
11911 +4 --> same as above
11912 +2w --> two weeks from today
11913 ++5 --> five days from default date
11915 The function understands only English month and weekday abbreviations,
11916 but this can be configured with the variables `parse-time-months' and
11917 `parse-time-weekdays'.
11919 While prompting, a calendar is popped up - you can also select the
11920 date with the mouse (button 1). The calendar shows a period of three
11921 months. To scroll it to other months, use the keys `>' and `<'.
11922 If you don't like the calendar, turn it off with
11923 \(setq org-read-date-popup-calendar nil)
11925 With optional argument TO-TIME, the date will immediately be converted
11926 to an internal time.
11927 With an optional argument WITH-TIME, the prompt will suggest to also
11928 insert a time. Note that when WITH-TIME is not set, you can still
11929 enter a time, and this function will inform the calling routine about
11930 this change. The calling routine may then choose to change the format
11931 used to insert the time stamp into the buffer to include the time.
11932 With optional argument FROM-STRING, read from this string instead from
11933 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
11934 the time/date that is used for everything that is not specified by the
11935 user."
11936 (require 'parse-time)
11937 (let* ((org-time-stamp-rounding-minutes
11938 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
11939 (org-dcst org-display-custom-times)
11940 (ct (org-current-time))
11941 (def (or org-overriding-default-time default-time ct))
11942 (defdecode (decode-time def))
11943 (dummy (progn
11944 (when (< (nth 2 defdecode) org-extend-today-until)
11945 (setcar (nthcdr 2 defdecode) -1)
11946 (setcar (nthcdr 1 defdecode) 59)
11947 (setq def (apply 'encode-time defdecode)
11948 defdecode (decode-time def)))))
11949 (calendar-move-hook nil)
11950 (calendar-view-diary-initially-flag nil)
11951 (view-diary-entries-initially nil)
11952 (calendar-view-holidays-initially-flag nil)
11953 (view-calendar-holidays-initially nil)
11954 (timestr (format-time-string
11955 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
11956 (prompt (concat (if prompt (concat prompt " ") "")
11957 (format "Date+time [%s]: " timestr)))
11958 ans (org-ans0 "") org-ans1 org-ans2 final)
11960 (cond
11961 (from-string (setq ans from-string))
11962 (org-read-date-popup-calendar
11963 (save-excursion
11964 (save-window-excursion
11965 (calendar)
11966 (calendar-forward-day (- (time-to-days def)
11967 (calendar-absolute-from-gregorian
11968 (calendar-current-date))))
11969 (org-eval-in-calendar nil t)
11970 (let* ((old-map (current-local-map))
11971 (map (copy-keymap calendar-mode-map))
11972 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
11973 (org-defkey map (kbd "RET") 'org-calendar-select)
11974 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
11975 'org-calendar-select-mouse)
11976 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
11977 'org-calendar-select-mouse)
11978 (org-defkey minibuffer-local-map [(meta shift left)]
11979 (lambda () (interactive)
11980 (org-eval-in-calendar '(calendar-backward-month 1))))
11981 (org-defkey minibuffer-local-map [(meta shift right)]
11982 (lambda () (interactive)
11983 (org-eval-in-calendar '(calendar-forward-month 1))))
11984 (org-defkey minibuffer-local-map [(meta shift up)]
11985 (lambda () (interactive)
11986 (org-eval-in-calendar '(calendar-backward-year 1))))
11987 (org-defkey minibuffer-local-map [(meta shift down)]
11988 (lambda () (interactive)
11989 (org-eval-in-calendar '(calendar-forward-year 1))))
11990 (org-defkey minibuffer-local-map [(shift up)]
11991 (lambda () (interactive)
11992 (org-eval-in-calendar '(calendar-backward-week 1))))
11993 (org-defkey minibuffer-local-map [(shift down)]
11994 (lambda () (interactive)
11995 (org-eval-in-calendar '(calendar-forward-week 1))))
11996 (org-defkey minibuffer-local-map [(shift left)]
11997 (lambda () (interactive)
11998 (org-eval-in-calendar '(calendar-backward-day 1))))
11999 (org-defkey minibuffer-local-map [(shift right)]
12000 (lambda () (interactive)
12001 (org-eval-in-calendar '(calendar-forward-day 1))))
12002 (org-defkey minibuffer-local-map ">"
12003 (lambda () (interactive)
12004 (org-eval-in-calendar '(scroll-calendar-left 1))))
12005 (org-defkey minibuffer-local-map "<"
12006 (lambda () (interactive)
12007 (org-eval-in-calendar '(scroll-calendar-right 1))))
12008 (run-hooks 'org-read-date-minibuffer-setup-hook)
12009 (unwind-protect
12010 (progn
12011 (use-local-map map)
12012 (add-hook 'post-command-hook 'org-read-date-display)
12013 (setq org-ans0 (read-string prompt default-input
12014 'org-read-date-history nil))
12015 ;; org-ans0: from prompt
12016 ;; org-ans1: from mouse click
12017 ;; org-ans2: from calendar motion
12018 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
12019 (remove-hook 'post-command-hook 'org-read-date-display)
12020 (use-local-map old-map)
12021 (when org-read-date-overlay
12022 (org-delete-overlay org-read-date-overlay)
12023 (setq org-read-date-overlay nil)))))))
12025 (t ; Naked prompt only
12026 (unwind-protect
12027 (setq ans (read-string prompt default-input
12028 'org-read-date-history timestr))
12029 (when org-read-date-overlay
12030 (org-delete-overlay org-read-date-overlay)
12031 (setq org-read-date-overlay nil)))))
12033 (setq final (org-read-date-analyze ans def defdecode))
12035 (if to-time
12036 (apply 'encode-time final)
12037 (if (and (boundp 'org-time-was-given) org-time-was-given)
12038 (format "%04d-%02d-%02d %02d:%02d"
12039 (nth 5 final) (nth 4 final) (nth 3 final)
12040 (nth 2 final) (nth 1 final))
12041 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
12042 (defvar def)
12043 (defvar defdecode)
12044 (defvar with-time)
12045 (defun org-read-date-display ()
12046 "Display the current date prompt interpretation in the minibuffer."
12047 (when org-read-date-display-live
12048 (when org-read-date-overlay
12049 (org-delete-overlay org-read-date-overlay))
12050 (let ((p (point)))
12051 (end-of-line 1)
12052 (while (not (equal (buffer-substring
12053 (max (point-min) (- (point) 4)) (point))
12054 " "))
12055 (insert " "))
12056 (goto-char p))
12057 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
12058 " " (or org-ans1 org-ans2)))
12059 (org-end-time-was-given nil)
12060 (f (org-read-date-analyze ans def defdecode))
12061 (fmts (if org-dcst
12062 org-time-stamp-custom-formats
12063 org-time-stamp-formats))
12064 (fmt (if (or with-time
12065 (and (boundp 'org-time-was-given) org-time-was-given))
12066 (cdr fmts)
12067 (car fmts)))
12068 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
12069 (when (and org-end-time-was-given
12070 (string-match org-plain-time-of-day-regexp txt))
12071 (setq txt (concat (substring txt 0 (match-end 0)) "-"
12072 org-end-time-was-given
12073 (substring txt (match-end 0)))))
12074 (setq org-read-date-overlay
12075 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
12076 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
12078 (defun org-read-date-analyze (ans def defdecode)
12079 "Analyse the combined answer of the date prompt."
12080 ;; FIXME: cleanup and comment
12081 (let (delta deltan deltaw deltadef year month day
12082 hour minute second wday pm h2 m2 tl wday1
12083 iso-year iso-weekday iso-week iso-year iso-date)
12085 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
12086 (setq ans "+0"))
12088 (when (setq delta (org-read-date-get-relative ans (current-time) def))
12089 (setq ans (replace-match "" t t ans)
12090 deltan (car delta)
12091 deltaw (nth 1 delta)
12092 deltadef (nth 2 delta)))
12094 ;; Check if there is an iso week date in there
12095 ;; If yes, sore the info and postpone interpreting it until the rest
12096 ;; of the parsing is done
12097 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
12098 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
12099 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
12100 iso-week (string-to-number (match-string 2 ans)))
12101 (setq ans (replace-match "" t t ans)))
12103 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
12104 (when (string-match
12105 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
12106 (setq year (if (match-end 2)
12107 (string-to-number (match-string 2 ans))
12108 (string-to-number (format-time-string "%Y")))
12109 month (string-to-number (match-string 3 ans))
12110 day (string-to-number (match-string 4 ans)))
12111 (if (< year 100) (setq year (+ 2000 year)))
12112 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
12113 t nil ans)))
12114 ;; Help matching am/pm times, because `parse-time-string' does not do that.
12115 ;; If there is a time with am/pm, and *no* time without it, we convert
12116 ;; so that matching will be successful.
12117 (loop for i from 1 to 2 do ; twice, for end time as well
12118 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
12119 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
12120 (setq hour (string-to-number (match-string 1 ans))
12121 minute (if (match-end 3)
12122 (string-to-number (match-string 3 ans))
12124 pm (equal ?p
12125 (string-to-char (downcase (match-string 4 ans)))))
12126 (if (and (= hour 12) (not pm))
12127 (setq hour 0)
12128 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
12129 (setq ans (replace-match (format "%02d:%02d" hour minute)
12130 t t ans))))
12132 ;; Check if a time range is given as a duration
12133 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
12134 (setq hour (string-to-number (match-string 1 ans))
12135 h2 (+ hour (string-to-number (match-string 3 ans)))
12136 minute (string-to-number (match-string 2 ans))
12137 m2 (+ minute (if (match-end 5) (string-to-number
12138 (match-string 5 ans))0)))
12139 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
12140 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
12141 t t ans)))
12143 ;; Check if there is a time range
12144 (when (boundp 'org-end-time-was-given)
12145 (setq org-time-was-given nil)
12146 (when (and (string-match org-plain-time-of-day-regexp ans)
12147 (match-end 8))
12148 (setq org-end-time-was-given (match-string 8 ans))
12149 (setq ans (concat (substring ans 0 (match-beginning 7))
12150 (substring ans (match-end 7))))))
12152 (setq tl (parse-time-string ans)
12153 day (or (nth 3 tl) (nth 3 defdecode))
12154 month (or (nth 4 tl)
12155 (if (and org-read-date-prefer-future
12156 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
12157 (1+ (nth 4 defdecode))
12158 (nth 4 defdecode)))
12159 year (or (nth 5 tl)
12160 (if (and org-read-date-prefer-future
12161 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
12162 (1+ (nth 5 defdecode))
12163 (nth 5 defdecode)))
12164 hour (or (nth 2 tl) (nth 2 defdecode))
12165 minute (or (nth 1 tl) (nth 1 defdecode))
12166 second (or (nth 0 tl) 0)
12167 wday (nth 6 tl))
12169 ;; Special date definitions below
12170 (cond
12171 (iso-week
12172 ;; There was an iso week
12173 (setq year (or iso-year year)
12174 day (or iso-weekday wday 1)
12175 wday nil ; to make sure that the trigger below does not match
12176 iso-date (calendar-gregorian-from-absolute
12177 (calendar-absolute-from-iso
12178 (list iso-week day year))))
12179 ; FIXME: Should we also push ISO weeks into the future?
12180 ; (when (and org-read-date-prefer-future
12181 ; (not iso-year)
12182 ; (< (calendar-absolute-from-gregorian iso-date)
12183 ; (time-to-days (current-time))))
12184 ; (setq year (1+ year)
12185 ; iso-date (calendar-gregorian-from-absolute
12186 ; (calendar-absolute-from-iso
12187 ; (list iso-week day year)))))
12188 (setq month (car iso-date)
12189 year (nth 2 iso-date)
12190 day (nth 1 iso-date)))
12191 (deltan
12192 (unless deltadef
12193 (let ((now (decode-time (current-time))))
12194 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
12195 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
12196 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
12197 ((equal deltaw "m") (setq month (+ month deltan)))
12198 ((equal deltaw "y") (setq year (+ year deltan)))))
12199 ((and wday (not (nth 3 tl)))
12200 ;; Weekday was given, but no day, so pick that day in the week
12201 ;; on or after the derived date.
12202 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
12203 (unless (equal wday wday1)
12204 (setq day (+ day (% (- wday wday1 -7) 7))))))
12205 (if (and (boundp 'org-time-was-given)
12206 (nth 2 tl))
12207 (setq org-time-was-given t))
12208 (if (< year 100) (setq year (+ 2000 year)))
12209 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
12210 (list second minute hour day month year)))
12212 (defvar parse-time-weekdays)
12214 (defun org-read-date-get-relative (s today default)
12215 "Check string S for special relative date string.
12216 TODAY and DEFAULT are internal times, for today and for a default.
12217 Return shift list (N what def-flag)
12218 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
12219 N is the number of WHATs to shift.
12220 DEF-FLAG is t when a double ++ or -- indicates shift relative to
12221 the DEFAULT date rather than TODAY."
12222 (when (and
12223 (string-match
12224 (concat
12225 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
12226 "\\([0-9]+\\)?"
12227 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
12228 "\\([ \t]\\|$\\)") s)
12229 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
12230 (let* ((dir (if (> (match-end 1) (match-beginning 1))
12231 (string-to-char (substring (match-string 1 s) -1))
12232 ?+))
12233 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
12234 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
12235 (what (if (match-end 3) (match-string 3 s) "d"))
12236 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
12237 (date (if rel default today))
12238 (wday (nth 6 (decode-time date)))
12239 delta)
12240 (if wday1
12241 (progn
12242 (setq delta (mod (+ 7 (- wday1 wday)) 7))
12243 (if (= dir ?-) (setq delta (- delta 7)))
12244 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
12245 (list delta "d" rel))
12246 (list (* n (if (= dir ?-) -1 1)) what rel)))))
12248 (defun org-eval-in-calendar (form &optional keepdate)
12249 "Eval FORM in the calendar window and return to current window.
12250 Also, store the cursor date in variable org-ans2."
12251 (let ((sw (selected-window)))
12252 (select-window (get-buffer-window "*Calendar*"))
12253 (eval form)
12254 (when (and (not keepdate) (calendar-cursor-to-date))
12255 (let* ((date (calendar-cursor-to-date))
12256 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12257 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
12258 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
12259 (select-window sw)))
12261 (defun org-calendar-select ()
12262 "Return to `org-read-date' with the date currently selected.
12263 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
12264 (interactive)
12265 (when (calendar-cursor-to-date)
12266 (let* ((date (calendar-cursor-to-date))
12267 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12268 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
12269 (if (active-minibuffer-window) (exit-minibuffer))))
12271 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
12272 "Insert a date stamp for the date given by the internal TIME.
12273 WITH-HM means, use the stamp format that includes the time of the day.
12274 INACTIVE means use square brackets instead of angular ones, so that the
12275 stamp will not contribute to the agenda.
12276 PRE and POST are optional strings to be inserted before and after the
12277 stamp.
12278 The command returns the inserted time stamp."
12279 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
12280 stamp)
12281 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
12282 (insert-before-markers (or pre ""))
12283 (insert-before-markers (setq stamp (format-time-string fmt time)))
12284 (when (listp extra)
12285 (setq extra (car extra))
12286 (if (and (stringp extra)
12287 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
12288 (setq extra (format "-%02d:%02d"
12289 (string-to-number (match-string 1 extra))
12290 (string-to-number (match-string 2 extra))))
12291 (setq extra nil)))
12292 (when extra
12293 (backward-char 1)
12294 (insert-before-markers extra)
12295 (forward-char 1))
12296 (insert-before-markers (or post ""))
12297 (setq org-last-inserted-timestamp stamp)))
12299 (defun org-toggle-time-stamp-overlays ()
12300 "Toggle the use of custom time stamp formats."
12301 (interactive)
12302 (setq org-display-custom-times (not org-display-custom-times))
12303 (unless org-display-custom-times
12304 (let ((p (point-min)) (bmp (buffer-modified-p)))
12305 (while (setq p (next-single-property-change p 'display))
12306 (if (and (get-text-property p 'display)
12307 (eq (get-text-property p 'face) 'org-date))
12308 (remove-text-properties
12309 p (setq p (next-single-property-change p 'display))
12310 '(display t))))
12311 (set-buffer-modified-p bmp)))
12312 (if (featurep 'xemacs)
12313 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
12314 (org-restart-font-lock)
12315 (setq org-table-may-need-update t)
12316 (if org-display-custom-times
12317 (message "Time stamps are overlayed with custom format")
12318 (message "Time stamp overlays removed")))
12320 (defun org-display-custom-time (beg end)
12321 "Overlay modified time stamp format over timestamp between BEG and END."
12322 (let* ((ts (buffer-substring beg end))
12323 t1 w1 with-hm tf time str w2 (off 0))
12324 (save-match-data
12325 (setq t1 (org-parse-time-string ts t))
12326 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
12327 (setq off (- (match-end 0) (match-beginning 0)))))
12328 (setq end (- end off))
12329 (setq w1 (- end beg)
12330 with-hm (and (nth 1 t1) (nth 2 t1))
12331 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
12332 time (org-fix-decoded-time t1)
12333 str (org-add-props
12334 (format-time-string
12335 (substring tf 1 -1) (apply 'encode-time time))
12336 nil 'mouse-face 'highlight)
12337 w2 (length str))
12338 (if (not (= w2 w1))
12339 (add-text-properties (1+ beg) (+ 2 beg)
12340 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
12341 (if (featurep 'xemacs)
12342 (progn
12343 (put-text-property beg end 'invisible t)
12344 (put-text-property beg end 'end-glyph (make-glyph str)))
12345 (put-text-property beg end 'display str))))
12347 (defun org-translate-time (string)
12348 "Translate all timestamps in STRING to custom format.
12349 But do this only if the variable `org-display-custom-times' is set."
12350 (when org-display-custom-times
12351 (save-match-data
12352 (let* ((start 0)
12353 (re org-ts-regexp-both)
12354 t1 with-hm inactive tf time str beg end)
12355 (while (setq start (string-match re string start))
12356 (setq beg (match-beginning 0)
12357 end (match-end 0)
12358 t1 (save-match-data
12359 (org-parse-time-string (substring string beg end) t))
12360 with-hm (and (nth 1 t1) (nth 2 t1))
12361 inactive (equal (substring string beg (1+ beg)) "[")
12362 tf (funcall (if with-hm 'cdr 'car)
12363 org-time-stamp-custom-formats)
12364 time (org-fix-decoded-time t1)
12365 str (format-time-string
12366 (concat
12367 (if inactive "[" "<") (substring tf 1 -1)
12368 (if inactive "]" ">"))
12369 (apply 'encode-time time))
12370 string (replace-match str t t string)
12371 start (+ start (length str)))))))
12372 string)
12374 (defun org-fix-decoded-time (time)
12375 "Set 0 instead of nil for the first 6 elements of time.
12376 Don't touch the rest."
12377 (let ((n 0))
12378 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
12380 (defun org-days-to-time (timestamp-string)
12381 "Difference between TIMESTAMP-STRING and now in days."
12382 (- (time-to-days (org-time-string-to-time timestamp-string))
12383 (time-to-days (current-time))))
12385 (defun org-deadline-close (timestamp-string &optional ndays)
12386 "Is the time in TIMESTAMP-STRING close to the current date?"
12387 (setq ndays (or ndays (org-get-wdays timestamp-string)))
12388 (and (< (org-days-to-time timestamp-string) ndays)
12389 (not (org-entry-is-done-p))))
12391 (defun org-get-wdays (ts)
12392 "Get the deadline lead time appropriate for timestring TS."
12393 (cond
12394 ((<= org-deadline-warning-days 0)
12395 ;; 0 or negative, enforce this value no matter what
12396 (- org-deadline-warning-days))
12397 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
12398 ;; lead time is specified.
12399 (floor (* (string-to-number (match-string 1 ts))
12400 (cdr (assoc (match-string 2 ts)
12401 '(("d" . 1) ("w" . 7)
12402 ("m" . 30.4) ("y" . 365.25)))))))
12403 ;; go for the default.
12404 (t org-deadline-warning-days)))
12406 (defun org-calendar-select-mouse (ev)
12407 "Return to `org-read-date' with the date currently selected.
12408 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
12409 (interactive "e")
12410 (mouse-set-point ev)
12411 (when (calendar-cursor-to-date)
12412 (let* ((date (calendar-cursor-to-date))
12413 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12414 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
12415 (if (active-minibuffer-window) (exit-minibuffer))))
12417 (defun org-check-deadlines (ndays)
12418 "Check if there are any deadlines due or past due.
12419 A deadline is considered due if it happens within `org-deadline-warning-days'
12420 days from today's date. If the deadline appears in an entry marked DONE,
12421 it is not shown. The prefix arg NDAYS can be used to test that many
12422 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
12423 (interactive "P")
12424 (let* ((org-warn-days
12425 (cond
12426 ((equal ndays '(4)) 100000)
12427 (ndays (prefix-numeric-value ndays))
12428 (t (abs org-deadline-warning-days))))
12429 (case-fold-search nil)
12430 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
12431 (callback
12432 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
12434 (message "%d deadlines past-due or due within %d days"
12435 (org-occur regexp nil callback)
12436 org-warn-days)))
12438 (defun org-check-before-date (date)
12439 "Check if there are deadlines or scheduled entries before DATE."
12440 (interactive (list (org-read-date)))
12441 (let ((case-fold-search nil)
12442 (regexp (concat "\\<\\(" org-deadline-string
12443 "\\|" org-scheduled-string
12444 "\\) *<\\([^>]+\\)>"))
12445 (callback
12446 (lambda () (time-less-p
12447 (org-time-string-to-time (match-string 2))
12448 (org-time-string-to-time date)))))
12449 (message "%d entries before %s"
12450 (org-occur regexp nil callback) date)))
12452 (defun org-check-after-date (date)
12453 "Check if there are deadlines or scheduled entries after DATE."
12454 (interactive (list (org-read-date)))
12455 (let ((case-fold-search nil)
12456 (regexp (concat "\\<\\(" org-deadline-string
12457 "\\|" org-scheduled-string
12458 "\\) *<\\([^>]+\\)>"))
12459 (callback
12460 (lambda () (not
12461 (time-less-p
12462 (org-time-string-to-time (match-string 2))
12463 (org-time-string-to-time date))))))
12464 (message "%d entries after %s"
12465 (org-occur regexp nil callback) date)))
12467 (defun org-evaluate-time-range (&optional to-buffer)
12468 "Evaluate a time range by computing the difference between start and end.
12469 Normally the result is just printed in the echo area, but with prefix arg
12470 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
12471 If the time range is actually in a table, the result is inserted into the
12472 next column.
12473 For time difference computation, a year is assumed to be exactly 365
12474 days in order to avoid rounding problems."
12475 (interactive "P")
12477 (org-clock-update-time-maybe)
12478 (save-excursion
12479 (unless (org-at-date-range-p t)
12480 (goto-char (point-at-bol))
12481 (re-search-forward org-tr-regexp-both (point-at-eol) t))
12482 (if (not (org-at-date-range-p t))
12483 (error "Not at a time-stamp range, and none found in current line")))
12484 (let* ((ts1 (match-string 1))
12485 (ts2 (match-string 2))
12486 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
12487 (match-end (match-end 0))
12488 (time1 (org-time-string-to-time ts1))
12489 (time2 (org-time-string-to-time ts2))
12490 (t1 (time-to-seconds time1))
12491 (t2 (time-to-seconds time2))
12492 (diff (abs (- t2 t1)))
12493 (negative (< (- t2 t1) 0))
12494 ;; (ys (floor (* 365 24 60 60)))
12495 (ds (* 24 60 60))
12496 (hs (* 60 60))
12497 (fy "%dy %dd %02d:%02d")
12498 (fy1 "%dy %dd")
12499 (fd "%dd %02d:%02d")
12500 (fd1 "%dd")
12501 (fh "%02d:%02d")
12502 y d h m align)
12503 (if havetime
12504 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
12506 d (floor (/ diff ds)) diff (mod diff ds)
12507 h (floor (/ diff hs)) diff (mod diff hs)
12508 m (floor (/ diff 60)))
12509 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
12511 d (floor (+ (/ diff ds) 0.5))
12512 h 0 m 0))
12513 (if (not to-buffer)
12514 (message "%s" (org-make-tdiff-string y d h m))
12515 (if (org-at-table-p)
12516 (progn
12517 (goto-char match-end)
12518 (setq align t)
12519 (and (looking-at " *|") (goto-char (match-end 0))))
12520 (goto-char match-end))
12521 (if (looking-at
12522 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
12523 (replace-match ""))
12524 (if negative (insert " -"))
12525 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
12526 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
12527 (insert " " (format fh h m))))
12528 (if align (org-table-align))
12529 (message "Time difference inserted")))))
12531 (defun org-make-tdiff-string (y d h m)
12532 (let ((fmt "")
12533 (l nil))
12534 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
12535 l (push y l)))
12536 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
12537 l (push d l)))
12538 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
12539 l (push h l)))
12540 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
12541 l (push m l)))
12542 (apply 'format fmt (nreverse l))))
12544 (defun org-time-string-to-time (s)
12545 (apply 'encode-time (org-parse-time-string s)))
12547 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
12548 "Convert a time stamp to an absolute day number.
12549 If there is a specifyer for a cyclic time stamp, get the closest date to
12550 DAYNR.
12551 PREFER and SHOW-ALL are passed through to `org-closest-date'."
12552 (cond
12553 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
12554 (if (org-diary-sexp-entry (match-string 1 s) "" date)
12555 daynr
12556 (+ daynr 1000)))
12557 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
12558 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
12559 (time-to-days (current-time))) (match-string 0 s)
12560 prefer show-all))
12561 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
12563 (defun org-days-to-iso-week (days)
12564 "Return the iso week number."
12565 (require 'cal-iso)
12566 (car (calendar-iso-from-absolute days)))
12568 (defun org-small-year-to-year (year)
12569 "Convert 2-digit years into 4-digit years.
12570 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
12571 The year 2000 cannot be abbreviated. Any year larger than 99
12572 is returned unchanged."
12573 (if (< year 38)
12574 (setq year (+ 2000 year))
12575 (if (< year 100)
12576 (setq year (+ 1900 year))))
12577 year)
12579 (defun org-time-from-absolute (d)
12580 "Return the time corresponding to date D.
12581 D may be an absolute day number, or a calendar-type list (month day year)."
12582 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
12583 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
12585 (defun org-calendar-holiday ()
12586 "List of holidays, for Diary display in Org-mode."
12587 (require 'holidays)
12588 (let ((hl (funcall
12589 (if (fboundp 'calendar-check-holidays)
12590 'calendar-check-holidays 'check-calendar-holidays) date)))
12591 (if hl (mapconcat 'identity hl "; "))))
12593 (defun org-diary-sexp-entry (sexp entry date)
12594 "Process a SEXP diary ENTRY for DATE."
12595 (require 'diary-lib)
12596 (let ((result (if calendar-debug-sexp
12597 (let ((stack-trace-on-error t))
12598 (eval (car (read-from-string sexp))))
12599 (condition-case nil
12600 (eval (car (read-from-string sexp)))
12601 (error
12602 (beep)
12603 (message "Bad sexp at line %d in %s: %s"
12604 (org-current-line)
12605 (buffer-file-name) sexp)
12606 (sleep-for 2))))))
12607 (cond ((stringp result) result)
12608 ((and (consp result)
12609 (stringp (cdr result))) (cdr result))
12610 (result entry)
12611 (t nil))))
12613 (defun org-diary-to-ical-string (frombuf)
12614 "Get iCalendar entries from diary entries in buffer FROMBUF.
12615 This uses the icalendar.el library."
12616 (let* ((tmpdir (if (featurep 'xemacs)
12617 (temp-directory)
12618 temporary-file-directory))
12619 (tmpfile (make-temp-name
12620 (expand-file-name "orgics" tmpdir)))
12621 buf rtn b e)
12622 (save-excursion
12623 (set-buffer frombuf)
12624 (icalendar-export-region (point-min) (point-max) tmpfile)
12625 (setq buf (find-buffer-visiting tmpfile))
12626 (set-buffer buf)
12627 (goto-char (point-min))
12628 (if (re-search-forward "^BEGIN:VEVENT" nil t)
12629 (setq b (match-beginning 0)))
12630 (goto-char (point-max))
12631 (if (re-search-backward "^END:VEVENT" nil t)
12632 (setq e (match-end 0)))
12633 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
12634 (kill-buffer buf)
12635 (delete-file tmpfile)
12636 rtn))
12638 (defun org-closest-date (start current change prefer show-all)
12639 "Find the date closest to CURRENT that is consistent with START and CHANGE.
12640 When PREFER is `past' return a date that is either CURRENT or past.
12641 When PREFER is `future', return a date that is either CURRENT or future.
12642 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
12643 ;; Make the proper lists from the dates
12644 (catch 'exit
12645 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
12646 dn dw sday cday n1 n2 n0
12647 d m y y1 y2 date1 date2 nmonths nm ny m2)
12649 (setq start (org-date-to-gregorian start)
12650 current (org-date-to-gregorian
12651 (if show-all
12652 current
12653 (time-to-days (current-time))))
12654 sday (calendar-absolute-from-gregorian start)
12655 cday (calendar-absolute-from-gregorian current))
12657 (if (<= cday sday) (throw 'exit sday))
12659 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
12660 (setq dn (string-to-number (match-string 1 change))
12661 dw (cdr (assoc (match-string 2 change) a1)))
12662 (error "Invalid change specifyer: %s" change))
12663 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
12664 (cond
12665 ((eq dw 'day)
12666 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
12667 n2 (+ n1 dn)))
12668 ((eq dw 'year)
12669 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
12670 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
12671 (setq date1 (list m d y1)
12672 n1 (calendar-absolute-from-gregorian date1)
12673 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
12674 n2 (calendar-absolute-from-gregorian date2)))
12675 ((eq dw 'month)
12676 ;; approx number of month between the two dates
12677 (setq nmonths (floor (/ (- cday sday) 30.436875)))
12678 ;; How often does dn fit in there?
12679 (setq d (nth 1 start) m (car start) y (nth 2 start)
12680 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
12681 m (+ m nm)
12682 ny (floor (/ m 12))
12683 y (+ y ny)
12684 m (- m (* ny 12)))
12685 (while (> m 12) (setq m (- m 12) y (1+ y)))
12686 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
12687 (setq m2 (+ m dn) y2 y)
12688 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
12689 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
12690 (while (<= n2 cday)
12691 (setq n1 n2 m m2 y y2)
12692 (setq m2 (+ m dn) y2 y)
12693 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
12694 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
12695 ;; Make sure n1 is the earlier date
12696 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
12697 (if show-all
12698 (cond
12699 ((eq prefer 'past) n1)
12700 ((eq prefer 'future) (if (= cday n1) n1 n2))
12701 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
12702 (cond
12703 ((eq prefer 'past) n1)
12704 ((eq prefer 'future) (if (= cday n1) n1 n2))
12705 (t (if (= cday n1) n1 n2)))))))
12707 (defun org-date-to-gregorian (date)
12708 "Turn any specification of DATE into a gregorian date for the calendar."
12709 (cond ((integerp date) (calendar-gregorian-from-absolute date))
12710 ((and (listp date) (= (length date) 3)) date)
12711 ((stringp date)
12712 (setq date (org-parse-time-string date))
12713 (list (nth 4 date) (nth 3 date) (nth 5 date)))
12714 ((listp date)
12715 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
12717 (defun org-parse-time-string (s &optional nodefault)
12718 "Parse the standard Org-mode time string.
12719 This should be a lot faster than the normal `parse-time-string'.
12720 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
12721 hour and minute fields will be nil if not given."
12722 (if (string-match org-ts-regexp0 s)
12723 (list 0
12724 (if (or (match-beginning 8) (not nodefault))
12725 (string-to-number (or (match-string 8 s) "0")))
12726 (if (or (match-beginning 7) (not nodefault))
12727 (string-to-number (or (match-string 7 s) "0")))
12728 (string-to-number (match-string 4 s))
12729 (string-to-number (match-string 3 s))
12730 (string-to-number (match-string 2 s))
12731 nil nil nil)
12732 (make-list 9 0)))
12734 (defun org-timestamp-up (&optional arg)
12735 "Increase the date item at the cursor by one.
12736 If the cursor is on the year, change the year. If it is on the month or
12737 the day, change that.
12738 With prefix ARG, change by that many units."
12739 (interactive "p")
12740 (org-timestamp-change (prefix-numeric-value arg)))
12742 (defun org-timestamp-down (&optional arg)
12743 "Decrease the date item at the cursor by one.
12744 If the cursor is on the year, change the year. If it is on the month or
12745 the day, change that.
12746 With prefix ARG, change by that many units."
12747 (interactive "p")
12748 (org-timestamp-change (- (prefix-numeric-value arg))))
12750 (defun org-timestamp-up-day (&optional arg)
12751 "Increase the date in the time stamp by one day.
12752 With prefix ARG, change that many days."
12753 (interactive "p")
12754 (if (and (not (org-at-timestamp-p t))
12755 (org-on-heading-p))
12756 (org-todo 'up)
12757 (org-timestamp-change (prefix-numeric-value arg) 'day)))
12759 (defun org-timestamp-down-day (&optional arg)
12760 "Decrease the date in the time stamp by one day.
12761 With prefix ARG, change that many days."
12762 (interactive "p")
12763 (if (and (not (org-at-timestamp-p t))
12764 (org-on-heading-p))
12765 (org-todo 'down)
12766 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
12768 (defun org-at-timestamp-p (&optional inactive-ok)
12769 "Determine if the cursor is in or at a timestamp."
12770 (interactive)
12771 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
12772 (pos (point))
12773 (ans (or (looking-at tsr)
12774 (save-excursion
12775 (skip-chars-backward "^[<\n\r\t")
12776 (if (> (point) (point-min)) (backward-char 1))
12777 (and (looking-at tsr)
12778 (> (- (match-end 0) pos) -1))))))
12779 (and ans
12780 (boundp 'org-ts-what)
12781 (setq org-ts-what
12782 (cond
12783 ((= pos (match-beginning 0)) 'bracket)
12784 ((= pos (1- (match-end 0))) 'bracket)
12785 ((org-pos-in-match-range pos 2) 'year)
12786 ((org-pos-in-match-range pos 3) 'month)
12787 ((org-pos-in-match-range pos 7) 'hour)
12788 ((org-pos-in-match-range pos 8) 'minute)
12789 ((or (org-pos-in-match-range pos 4)
12790 (org-pos-in-match-range pos 5)) 'day)
12791 ((and (> pos (or (match-end 8) (match-end 5)))
12792 (< pos (match-end 0)))
12793 (- pos (or (match-end 8) (match-end 5))))
12794 (t 'day))))
12795 ans))
12797 (defun org-toggle-timestamp-type ()
12798 "Toggle the type (<active> or [inactive]) of a time stamp."
12799 (interactive)
12800 (when (org-at-timestamp-p t)
12801 (let ((beg (match-beginning 0)) (end (match-end 0))
12802 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
12803 (save-excursion
12804 (goto-char beg)
12805 (while (re-search-forward "[][<>]" end t)
12806 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
12807 t t)))
12808 (message "Timestamp is now %sactive"
12809 (if (equal (char-after beg) ?<) "" "in")))))
12811 (defun org-timestamp-change (n &optional what)
12812 "Change the date in the time stamp at point.
12813 The date will be changed by N times WHAT. WHAT can be `day', `month',
12814 `year', `minute', `second'. If WHAT is not given, the cursor position
12815 in the timestamp determines what will be changed."
12816 (let ((pos (point))
12817 with-hm inactive
12818 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
12819 org-ts-what
12820 extra rem
12821 ts time time0)
12822 (if (not (org-at-timestamp-p t))
12823 (error "Not at a timestamp"))
12824 (if (and (not what) (eq org-ts-what 'bracket))
12825 (org-toggle-timestamp-type)
12826 (if (and (not what) (not (eq org-ts-what 'day))
12827 org-display-custom-times
12828 (get-text-property (point) 'display)
12829 (not (get-text-property (1- (point)) 'display)))
12830 (setq org-ts-what 'day))
12831 (setq org-ts-what (or what org-ts-what)
12832 inactive (= (char-after (match-beginning 0)) ?\[)
12833 ts (match-string 0))
12834 (replace-match "")
12835 (if (string-match
12836 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
12838 (setq extra (match-string 1 ts)))
12839 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
12840 (setq with-hm t))
12841 (setq time0 (org-parse-time-string ts))
12842 (when (and (eq org-ts-what 'minute)
12843 (eq current-prefix-arg nil))
12844 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
12845 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
12846 (setcar (cdr time0) (+ (nth 1 time0)
12847 (if (> n 0) (- rem) (- dm rem))))))
12848 (setq time
12849 (encode-time (or (car time0) 0)
12850 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
12851 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
12852 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
12853 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
12854 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
12855 (nthcdr 6 time0)))
12856 (when (and (member org-ts-what '(hour minute))
12857 extra
12858 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
12859 (setq extra (org-modify-ts-extra
12860 extra
12861 (if (eq org-ts-what 'hour) 2 5)
12862 n dm)))
12863 (when (integerp org-ts-what)
12864 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
12865 (if (eq what 'calendar)
12866 (let ((cal-date (org-get-date-from-calendar)))
12867 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
12868 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
12869 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
12870 (setcar time0 (or (car time0) 0))
12871 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
12872 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
12873 (setq time (apply 'encode-time time0))))
12874 (setq org-last-changed-timestamp
12875 (org-insert-time-stamp time with-hm inactive nil nil extra))
12876 (org-clock-update-time-maybe)
12877 (goto-char pos)
12878 ;; Try to recenter the calendar window, if any
12879 (if (and org-calendar-follow-timestamp-change
12880 (get-buffer-window "*Calendar*" t)
12881 (memq org-ts-what '(day month year)))
12882 (org-recenter-calendar (time-to-days time))))))
12884 (defun org-modify-ts-extra (s pos n dm)
12885 "Change the different parts of the lead-time and repeat fields in timestamp."
12886 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
12887 ng h m new rem)
12888 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
12889 (cond
12890 ((or (org-pos-in-match-range pos 2)
12891 (org-pos-in-match-range pos 3))
12892 (setq m (string-to-number (match-string 3 s))
12893 h (string-to-number (match-string 2 s)))
12894 (if (org-pos-in-match-range pos 2)
12895 (setq h (+ h n))
12896 (setq n (* dm (org-no-warnings (signum n))))
12897 (when (not (= 0 (setq rem (% m dm))))
12898 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
12899 (setq m (+ m n)))
12900 (if (< m 0) (setq m (+ m 60) h (1- h)))
12901 (if (> m 59) (setq m (- m 60) h (1+ h)))
12902 (setq h (min 24 (max 0 h)))
12903 (setq ng 1 new (format "-%02d:%02d" h m)))
12904 ((org-pos-in-match-range pos 6)
12905 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
12906 ((org-pos-in-match-range pos 5)
12907 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
12909 ((org-pos-in-match-range pos 9)
12910 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
12911 ((org-pos-in-match-range pos 8)
12912 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
12914 (when ng
12915 (setq s (concat
12916 (substring s 0 (match-beginning ng))
12918 (substring s (match-end ng))))))
12921 (defun org-recenter-calendar (date)
12922 "If the calendar is visible, recenter it to DATE."
12923 (let* ((win (selected-window))
12924 (cwin (get-buffer-window "*Calendar*" t))
12925 (calendar-move-hook nil))
12926 (when cwin
12927 (select-window cwin)
12928 (calendar-goto-date (if (listp date) date
12929 (calendar-gregorian-from-absolute date)))
12930 (select-window win))))
12932 (defun org-goto-calendar (&optional arg)
12933 "Go to the Emacs calendar at the current date.
12934 If there is a time stamp in the current line, go to that date.
12935 A prefix ARG can be used to force the current date."
12936 (interactive "P")
12937 (let ((tsr org-ts-regexp) diff
12938 (calendar-move-hook nil)
12939 (calendar-view-holidays-initially-flag nil)
12940 (view-calendar-holidays-initially nil)
12941 (calendar-view-diary-initially-flag nil)
12942 (view-diary-entries-initially nil))
12943 (if (or (org-at-timestamp-p)
12944 (save-excursion
12945 (beginning-of-line 1)
12946 (looking-at (concat ".*" tsr))))
12947 (let ((d1 (time-to-days (current-time)))
12948 (d2 (time-to-days
12949 (org-time-string-to-time (match-string 1)))))
12950 (setq diff (- d2 d1))))
12951 (calendar)
12952 (calendar-goto-today)
12953 (if (and diff (not arg)) (calendar-forward-day diff))))
12955 (defun org-get-date-from-calendar ()
12956 "Return a list (month day year) of date at point in calendar."
12957 (with-current-buffer "*Calendar*"
12958 (save-match-data
12959 (calendar-cursor-to-date))))
12961 (defun org-date-from-calendar ()
12962 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
12963 If there is already a time stamp at the cursor position, update it."
12964 (interactive)
12965 (if (org-at-timestamp-p t)
12966 (org-timestamp-change 0 'calendar)
12967 (let ((cal-date (org-get-date-from-calendar)))
12968 (org-insert-time-stamp
12969 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
12971 (defun org-minutes-to-hh:mm-string (m)
12972 "Compute H:MM from a number of minutes."
12973 (let ((h (/ m 60)))
12974 (setq m (- m (* 60 h)))
12975 (format org-time-clocksum-format h m)))
12977 (defun org-hh:mm-string-to-minutes (s)
12978 "Convert a string H:MM to a number of minutes."
12979 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
12980 (+ (* (string-to-number (match-string 1 s)) 60)
12981 (string-to-number (match-string 2 s)))
12984 ;;;; Files
12986 (defun org-save-all-org-buffers ()
12987 "Save all Org-mode buffers without user confirmation."
12988 (interactive)
12989 (message "Saving all Org-mode buffers...")
12990 (save-some-buffers t 'org-mode-p)
12991 (when (featurep 'org-id) (org-id-locations-save))
12992 (message "Saving all Org-mode buffers... done"))
12994 (defun org-revert-all-org-buffers ()
12995 "Revert all Org-mode buffers.
12996 Prompt for confirmation when there are unsaved changes.
12997 Be sure you know what you are doing before letting this function
12998 overwrite your changes.
13000 This function is useful in a setup where one tracks org files
13001 with a version control system, to revert on one machine after pulling
13002 changes from another. I believe the procedure must be like this:
13004 1. M-x org-save-all-org-buffers
13005 2. Pull changes from the other machine, resolve conflicts
13006 3. M-x org-revert-all-org-buffers"
13007 (interactive)
13008 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
13009 (error "Abort"))
13010 (save-excursion
13011 (save-window-excursion
13012 (mapc
13013 (lambda (b)
13014 (when (and (with-current-buffer b (org-mode-p))
13015 (with-current-buffer b buffer-file-name))
13016 (switch-to-buffer b)
13017 (revert-buffer t 'no-confirm)))
13018 (buffer-list))
13019 (when (and (featurep 'org-id) org-id-track-globally)
13020 (org-id-locations-load)))))
13022 ;;;; Agenda files
13024 ;;;###autoload
13025 (defun org-iswitchb (&optional arg)
13026 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
13027 With a prefix argument, restrict available to files.
13028 With two prefix arguments, restrict available buffers to agenda files.
13030 Due to some yet unresolved reason, the global function
13031 `iswitchb-mode' needs to be active for this function to work."
13032 (interactive "P")
13033 (require 'iswitchb)
13034 (let ((enabled iswitchb-mode) blist)
13035 (or enabled (iswitchb-mode 1))
13036 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
13037 ((equal arg '(16)) (org-buffer-list 'agenda))
13038 (t (org-buffer-list))))
13039 (unwind-protect
13040 (let ((iswitchb-make-buflist-hook
13041 (lambda ()
13042 (setq iswitchb-temp-buflist
13043 (mapcar 'buffer-name blist)))))
13044 (switch-to-buffer
13045 (iswitchb-read-buffer
13046 "Switch-to: " nil t))
13047 (or enabled (iswitchb-mode -1))))))
13049 ;;;###autoload
13050 (defun org-ido-switchb (&optional arg)
13051 "Use `org-ido-completing-read' to prompt for an Org buffer to switch to.
13052 With a prefix argument, restrict available to files.
13053 With two prefix arguments, restrict available buffers to agenda files."
13054 (interactive "P")
13055 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
13056 ((equal arg '(16)) (org-buffer-list 'agenda))
13057 (t (org-buffer-list)))))
13058 (switch-to-buffer
13059 (org-ido-completing-read "Org buffer: "
13060 (mapcar 'list (mapcar 'buffer-name blist))
13061 nil t))))
13063 (defun org-buffer-list (&optional predicate exclude-tmp)
13064 "Return a list of Org buffers.
13065 PREDICATE can be `export', `files' or `agenda'.
13067 export restrict the list to Export buffers.
13068 files restrict the list to buffers visiting Org files.
13069 agenda restrict the list to buffers visiting agenda files.
13071 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
13072 (let* ((bfn nil)
13073 (agenda-files (and (eq predicate 'agenda)
13074 (mapcar 'file-truename (org-agenda-files t))))
13075 (filter
13076 (cond
13077 ((eq predicate 'files)
13078 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
13079 ((eq predicate 'export)
13080 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
13081 ((eq predicate 'agenda)
13082 (lambda (b)
13083 (with-current-buffer b
13084 (and (eq major-mode 'org-mode)
13085 (setq bfn (buffer-file-name b))
13086 (member (file-truename bfn) agenda-files)))))
13087 (t (lambda (b) (with-current-buffer b
13088 (or (eq major-mode 'org-mode)
13089 (string-match "\*Org .*Export"
13090 (buffer-name b)))))))))
13091 (delq nil
13092 (mapcar
13093 (lambda(b)
13094 (if (and (funcall filter b)
13095 (or (not exclude-tmp)
13096 (not (string-match "tmp" (buffer-name b)))))
13098 nil))
13099 (buffer-list)))))
13101 (defun org-agenda-files (&optional unrestricted archives)
13102 "Get the list of agenda files.
13103 Optional UNRESTRICTED means return the full list even if a restriction
13104 is currently in place.
13105 When ARCHIVES is t, include all archive files hat are really being
13106 used by the agenda files. If ARCHIVE is `ifmode', do this only if
13107 `org-agenda-archives-mode' is t."
13108 (let ((files
13109 (cond
13110 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
13111 ((stringp org-agenda-files) (org-read-agenda-file-list))
13112 ((listp org-agenda-files) org-agenda-files)
13113 (t (error "Invalid value of `org-agenda-files'")))))
13114 (setq files (apply 'append
13115 (mapcar (lambda (f)
13116 (if (file-directory-p f)
13117 (directory-files
13118 f t org-agenda-file-regexp)
13119 (list f)))
13120 files)))
13121 (when org-agenda-skip-unavailable-files
13122 (setq files (delq nil
13123 (mapcar (function
13124 (lambda (file)
13125 (and (file-readable-p file) file)))
13126 files))))
13127 (when (or (eq archives t)
13128 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
13129 (setq files (org-add-archive-files files)))
13130 files))
13132 (defun org-edit-agenda-file-list ()
13133 "Edit the list of agenda files.
13134 Depending on setup, this either uses customize to edit the variable
13135 `org-agenda-files', or it visits the file that is holding the list. In the
13136 latter case, the buffer is set up in a way that saving it automatically kills
13137 the buffer and restores the previous window configuration."
13138 (interactive)
13139 (if (stringp org-agenda-files)
13140 (let ((cw (current-window-configuration)))
13141 (find-file org-agenda-files)
13142 (org-set-local 'org-window-configuration cw)
13143 (org-add-hook 'after-save-hook
13144 (lambda ()
13145 (set-window-configuration
13146 (prog1 org-window-configuration
13147 (kill-buffer (current-buffer))))
13148 (org-install-agenda-files-menu)
13149 (message "New agenda file list installed"))
13150 nil 'local)
13151 (message "%s" (substitute-command-keys
13152 "Edit list and finish with \\[save-buffer]")))
13153 (customize-variable 'org-agenda-files)))
13155 (defun org-store-new-agenda-file-list (list)
13156 "Set new value for the agenda file list and save it correctly."
13157 (if (stringp org-agenda-files)
13158 (let ((f org-agenda-files) b)
13159 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
13160 (with-temp-file f
13161 (insert (mapconcat 'identity list "\n") "\n")))
13162 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
13163 (setq org-agenda-files list)
13164 (customize-save-variable 'org-agenda-files org-agenda-files))))
13166 (defun org-read-agenda-file-list ()
13167 "Read the list of agenda files from a file."
13168 (when (file-directory-p org-agenda-files)
13169 (error "`org-agenda-files' cannot be a single directory"))
13170 (when (stringp org-agenda-files)
13171 (with-temp-buffer
13172 (insert-file-contents org-agenda-files)
13173 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
13176 ;;;###autoload
13177 (defun org-cycle-agenda-files ()
13178 "Cycle through the files in `org-agenda-files'.
13179 If the current buffer visits an agenda file, find the next one in the list.
13180 If the current buffer does not, find the first agenda file."
13181 (interactive)
13182 (let* ((fs (org-agenda-files t))
13183 (files (append fs (list (car fs))))
13184 (tcf (if buffer-file-name (file-truename buffer-file-name)))
13185 file)
13186 (unless files (error "No agenda files"))
13187 (catch 'exit
13188 (while (setq file (pop files))
13189 (if (equal (file-truename file) tcf)
13190 (when (car files)
13191 (find-file (car files))
13192 (throw 'exit t))))
13193 (find-file (car fs)))
13194 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
13196 (defun org-agenda-file-to-front (&optional to-end)
13197 "Move/add the current file to the top of the agenda file list.
13198 If the file is not present in the list, it is added to the front. If it is
13199 present, it is moved there. With optional argument TO-END, add/move to the
13200 end of the list."
13201 (interactive "P")
13202 (let ((org-agenda-skip-unavailable-files nil)
13203 (file-alist (mapcar (lambda (x)
13204 (cons (file-truename x) x))
13205 (org-agenda-files t)))
13206 (ctf (file-truename buffer-file-name))
13207 x had)
13208 (setq x (assoc ctf file-alist) had x)
13210 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
13211 (if to-end
13212 (setq file-alist (append (delq x file-alist) (list x)))
13213 (setq file-alist (cons x (delq x file-alist))))
13214 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
13215 (org-install-agenda-files-menu)
13216 (message "File %s to %s of agenda file list"
13217 (if had "moved" "added") (if to-end "end" "front"))))
13219 (defun org-remove-file (&optional file)
13220 "Remove current file from the list of files in variable `org-agenda-files'.
13221 These are the files which are being checked for agenda entries.
13222 Optional argument FILE means, use this file instead of the current."
13223 (interactive)
13224 (let* ((org-agenda-skip-unavailable-files nil)
13225 (file (or file buffer-file-name))
13226 (true-file (file-truename file))
13227 (afile (abbreviate-file-name file))
13228 (files (delq nil (mapcar
13229 (lambda (x)
13230 (if (equal true-file
13231 (file-truename x))
13232 nil x))
13233 (org-agenda-files t)))))
13234 (if (not (= (length files) (length (org-agenda-files t))))
13235 (progn
13236 (org-store-new-agenda-file-list files)
13237 (org-install-agenda-files-menu)
13238 (message "Removed file: %s" afile))
13239 (message "File was not in list: %s (not removed)" afile))))
13241 (defun org-file-menu-entry (file)
13242 (vector file (list 'find-file file) t))
13244 (defun org-check-agenda-file (file)
13245 "Make sure FILE exists. If not, ask user what to do."
13246 (when (not (file-exists-p file))
13247 (message "non-existent file %s. [R]emove from list or [A]bort?"
13248 (abbreviate-file-name file))
13249 (let ((r (downcase (read-char-exclusive))))
13250 (cond
13251 ((equal r ?r)
13252 (org-remove-file file)
13253 (throw 'nextfile t))
13254 (t (error "Abort"))))))
13256 (defun org-get-agenda-file-buffer (file)
13257 "Get a buffer visiting FILE. If the buffer needs to be created, add
13258 it to the list of buffers which might be released later."
13259 (let ((buf (org-find-base-buffer-visiting file)))
13260 (if buf
13261 buf ; just return it
13262 ;; Make a new buffer and remember it
13263 (setq buf (find-file-noselect file))
13264 (if buf (push buf org-agenda-new-buffers))
13265 buf)))
13267 (defun org-release-buffers (blist)
13268 "Release all buffers in list, asking the user for confirmation when needed.
13269 When a buffer is unmodified, it is just killed. When modified, it is saved
13270 \(if the user agrees) and then killed."
13271 (let (buf file)
13272 (while (setq buf (pop blist))
13273 (setq file (buffer-file-name buf))
13274 (when (and (buffer-modified-p buf)
13275 file
13276 (y-or-n-p (format "Save file %s? " file)))
13277 (with-current-buffer buf (save-buffer)))
13278 (kill-buffer buf))))
13280 (defun org-prepare-agenda-buffers (files)
13281 "Create buffers for all agenda files, protect archived trees and comments."
13282 (interactive)
13283 (let ((pa '(:org-archived t))
13284 (pc '(:org-comment t))
13285 (pall '(:org-archived t :org-comment t))
13286 (inhibit-read-only t)
13287 (rea (concat ":" org-archive-tag ":"))
13288 bmp file re)
13289 (save-excursion
13290 (save-restriction
13291 (while (setq file (pop files))
13292 (catch 'nextfile
13293 (if (bufferp file)
13294 (set-buffer file)
13295 (org-check-agenda-file file)
13296 (set-buffer (org-get-agenda-file-buffer file)))
13297 (widen)
13298 (setq bmp (buffer-modified-p))
13299 (org-refresh-category-properties)
13300 (setq org-todo-keywords-for-agenda
13301 (append org-todo-keywords-for-agenda org-todo-keywords-1))
13302 (setq org-done-keywords-for-agenda
13303 (append org-done-keywords-for-agenda org-done-keywords))
13304 (setq org-todo-keyword-alist-for-agenda
13305 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
13306 (setq org-tag-alist-for-agenda
13307 (append org-tag-alist-for-agenda org-tag-alist))
13309 (save-excursion
13310 (remove-text-properties (point-min) (point-max) pall)
13311 (when org-agenda-skip-archived-trees
13312 (goto-char (point-min))
13313 (while (re-search-forward rea nil t)
13314 (if (org-on-heading-p t)
13315 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
13316 (goto-char (point-min))
13317 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
13318 (while (re-search-forward re nil t)
13319 (add-text-properties
13320 (match-beginning 0) (org-end-of-subtree t) pc)))
13321 (set-buffer-modified-p bmp)))))
13322 (setq org-todo-keyword-alist-for-agenda
13323 (org-uniquify org-todo-keyword-alist-for-agenda)
13324 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
13326 ;;;; Embedded LaTeX
13328 (defvar org-cdlatex-mode-map (make-sparse-keymap)
13329 "Keymap for the minor `org-cdlatex-mode'.")
13331 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
13332 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
13333 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
13334 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
13335 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
13337 (defvar org-cdlatex-texmathp-advice-is-done nil
13338 "Flag remembering if we have applied the advice to texmathp already.")
13340 (define-minor-mode org-cdlatex-mode
13341 "Toggle the minor `org-cdlatex-mode'.
13342 This mode supports entering LaTeX environment and math in LaTeX fragments
13343 in Org-mode.
13344 \\{org-cdlatex-mode-map}"
13345 nil " OCDL" nil
13346 (when org-cdlatex-mode (require 'cdlatex))
13347 (unless org-cdlatex-texmathp-advice-is-done
13348 (setq org-cdlatex-texmathp-advice-is-done t)
13349 (defadvice texmathp (around org-math-always-on activate)
13350 "Always return t in org-mode buffers.
13351 This is because we want to insert math symbols without dollars even outside
13352 the LaTeX math segments. If Orgmode thinks that point is actually inside
13353 an embedded LaTeX fragment, let texmathp do its job.
13354 \\[org-cdlatex-mode-map]"
13355 (interactive)
13356 (let (p)
13357 (cond
13358 ((not (org-mode-p)) ad-do-it)
13359 ((eq this-command 'cdlatex-math-symbol)
13360 (setq ad-return-value t
13361 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
13363 (let ((p (org-inside-LaTeX-fragment-p)))
13364 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
13365 (setq ad-return-value t
13366 texmathp-why '("Org-mode embedded math" . 0))
13367 (if p ad-do-it)))))))))
13369 (defun turn-on-org-cdlatex ()
13370 "Unconditionally turn on `org-cdlatex-mode'."
13371 (org-cdlatex-mode 1))
13373 (defun org-inside-LaTeX-fragment-p ()
13374 "Test if point is inside a LaTeX fragment.
13375 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
13376 sequence appearing also before point.
13377 Even though the matchers for math are configurable, this function assumes
13378 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
13379 delimiters are skipped when they have been removed by customization.
13380 The return value is nil, or a cons cell with the delimiter and
13381 and the position of this delimiter.
13383 This function does a reasonably good job, but can locally be fooled by
13384 for example currency specifications. For example it will assume being in
13385 inline math after \"$22.34\". The LaTeX fragment formatter will only format
13386 fragments that are properly closed, but during editing, we have to live
13387 with the uncertainty caused by missing closing delimiters. This function
13388 looks only before point, not after."
13389 (catch 'exit
13390 (let ((pos (point))
13391 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
13392 (lim (progn
13393 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
13394 (point)))
13395 dd-on str (start 0) m re)
13396 (goto-char pos)
13397 (when dodollar
13398 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
13399 re (nth 1 (assoc "$" org-latex-regexps)))
13400 (while (string-match re str start)
13401 (cond
13402 ((= (match-end 0) (length str))
13403 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
13404 ((= (match-end 0) (- (length str) 5))
13405 (throw 'exit nil))
13406 (t (setq start (match-end 0))))))
13407 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
13408 (goto-char pos)
13409 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
13410 (and (match-beginning 2) (throw 'exit nil))
13411 ;; count $$
13412 (while (re-search-backward "\\$\\$" lim t)
13413 (setq dd-on (not dd-on)))
13414 (goto-char pos)
13415 (if dd-on (cons "$$" m))))))
13418 (defun org-try-cdlatex-tab ()
13419 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
13420 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
13421 - inside a LaTeX fragment, or
13422 - after the first word in a line, where an abbreviation expansion could
13423 insert a LaTeX environment."
13424 (when org-cdlatex-mode
13425 (cond
13426 ((save-excursion
13427 (skip-chars-backward "a-zA-Z0-9*")
13428 (skip-chars-backward " \t")
13429 (bolp))
13430 (cdlatex-tab) t)
13431 ((org-inside-LaTeX-fragment-p)
13432 (cdlatex-tab) t)
13433 (t nil))))
13435 (defun org-cdlatex-underscore-caret (&optional arg)
13436 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
13437 Revert to the normal definition outside of these fragments."
13438 (interactive "P")
13439 (if (org-inside-LaTeX-fragment-p)
13440 (call-interactively 'cdlatex-sub-superscript)
13441 (let (org-cdlatex-mode)
13442 (call-interactively (key-binding (vector last-input-event))))))
13444 (defun org-cdlatex-math-modify (&optional arg)
13445 "Execute `cdlatex-math-modify' in LaTeX fragments.
13446 Revert to the normal definition outside of these fragments."
13447 (interactive "P")
13448 (if (org-inside-LaTeX-fragment-p)
13449 (call-interactively 'cdlatex-math-modify)
13450 (let (org-cdlatex-mode)
13451 (call-interactively (key-binding (vector last-input-event))))))
13453 (defvar org-latex-fragment-image-overlays nil
13454 "List of overlays carrying the images of latex fragments.")
13455 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
13457 (defun org-remove-latex-fragment-image-overlays ()
13458 "Remove all overlays with LaTeX fragment images in current buffer."
13459 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
13460 (setq org-latex-fragment-image-overlays nil))
13462 (defun org-preview-latex-fragment (&optional subtree)
13463 "Preview the LaTeX fragment at point, or all locally or globally.
13464 If the cursor is in a LaTeX fragment, create the image and overlay
13465 it over the source code. If there is no fragment at point, display
13466 all fragments in the current text, from one headline to the next. With
13467 prefix SUBTREE, display all fragments in the current subtree. With a
13468 double prefix `C-u C-u', or when the cursor is before the first headline,
13469 display all fragments in the buffer.
13470 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
13471 (interactive "P")
13472 (org-remove-latex-fragment-image-overlays)
13473 (save-excursion
13474 (save-restriction
13475 (let (beg end at msg)
13476 (cond
13477 ((or (equal subtree '(16))
13478 (not (save-excursion
13479 (re-search-backward (concat "^" outline-regexp) nil t))))
13480 (setq beg (point-min) end (point-max)
13481 msg "Creating images for buffer...%s"))
13482 ((equal subtree '(4))
13483 (org-back-to-heading)
13484 (setq beg (point) end (org-end-of-subtree t)
13485 msg "Creating images for subtree...%s"))
13487 (if (setq at (org-inside-LaTeX-fragment-p))
13488 (goto-char (max (point-min) (- (cdr at) 2)))
13489 (org-back-to-heading))
13490 (setq beg (point) end (progn (outline-next-heading) (point))
13491 msg (if at "Creating image...%s"
13492 "Creating images for entry...%s"))))
13493 (message msg "")
13494 (narrow-to-region beg end)
13495 (goto-char beg)
13496 (org-format-latex
13497 (concat "ltxpng/" (file-name-sans-extension
13498 (file-name-nondirectory
13499 buffer-file-name)))
13500 default-directory 'overlays msg at 'forbuffer)
13501 (message msg "done. Use `C-c C-c' to remove images.")))))
13503 (defvar org-latex-regexps
13504 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
13505 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
13506 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
13507 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
13508 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
13509 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
13510 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
13511 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
13512 "Regular expressions for matching embedded LaTeX.")
13514 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
13515 "Replace LaTeX fragments with links to an image, and produce images."
13516 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
13517 (let* ((prefixnodir (file-name-nondirectory prefix))
13518 (absprefix (expand-file-name prefix dir))
13519 (todir (file-name-directory absprefix))
13520 (opt org-format-latex-options)
13521 (matchers (plist-get opt :matchers))
13522 (re-list org-latex-regexps)
13523 (cnt 0) txt link beg end re e checkdir
13524 m n block linkfile movefile ov)
13525 ;; Check if there are old images files with this prefix, and remove them
13526 (when (file-directory-p todir)
13527 (mapc 'delete-file
13528 (directory-files
13529 todir 'full
13530 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
13531 ;; Check the different regular expressions
13532 (while (setq e (pop re-list))
13533 (setq m (car e) re (nth 1 e) n (nth 2 e)
13534 block (if (nth 3 e) "\n\n" ""))
13535 (when (member m matchers)
13536 (goto-char (point-min))
13537 (while (re-search-forward re nil t)
13538 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
13539 (not (get-text-property (match-beginning n)
13540 'org-protected)))
13541 (setq txt (match-string n)
13542 beg (match-beginning n) end (match-end n)
13543 cnt (1+ cnt)
13544 linkfile (format "%s_%04d.png" prefix cnt)
13545 movefile (format "%s_%04d.png" absprefix cnt)
13546 link (concat block "[[file:" linkfile "]]" block))
13547 (if msg (message msg cnt))
13548 (goto-char beg)
13549 (unless checkdir ; make sure the directory exists
13550 (setq checkdir t)
13551 (or (file-directory-p todir) (make-directory todir)))
13552 (org-create-formula-image
13553 txt movefile opt forbuffer)
13554 (if overlays
13555 (progn
13556 (setq ov (org-make-overlay beg end))
13557 (if (featurep 'xemacs)
13558 (progn
13559 (org-overlay-put ov 'invisible t)
13560 (org-overlay-put
13561 ov 'end-glyph
13562 (make-glyph (vector 'png :file movefile))))
13563 (org-overlay-put
13564 ov 'display
13565 (list 'image :type 'png :file movefile :ascent 'center)))
13566 (push ov org-latex-fragment-image-overlays)
13567 (goto-char end))
13568 (delete-region beg end)
13569 (insert link))))))))
13571 ;; This function borrows from Ganesh Swami's latex2png.el
13572 (defun org-create-formula-image (string tofile options buffer)
13573 (let* ((tmpdir (if (featurep 'xemacs)
13574 (temp-directory)
13575 temporary-file-directory))
13576 (texfilebase (make-temp-name
13577 (expand-file-name "orgtex" tmpdir)))
13578 (texfile (concat texfilebase ".tex"))
13579 (dvifile (concat texfilebase ".dvi"))
13580 (pngfile (concat texfilebase ".png"))
13581 (fnh (if (featurep 'xemacs)
13582 (font-height (get-face-font 'default))
13583 (face-attribute 'default :height nil)))
13584 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
13585 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
13586 (fg (or (plist-get options (if buffer :foreground :html-foreground))
13587 "Black"))
13588 (bg (or (plist-get options (if buffer :background :html-background))
13589 "Transparent")))
13590 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
13591 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
13592 (with-temp-file texfile
13593 (insert org-format-latex-header
13594 "\n\\begin{document}\n" string "\n\\end{document}\n"))
13595 (let ((dir default-directory))
13596 (condition-case nil
13597 (progn
13598 (cd tmpdir)
13599 (call-process "latex" nil nil nil texfile))
13600 (error nil))
13601 (cd dir))
13602 (if (not (file-exists-p dvifile))
13603 (progn (message "Failed to create dvi file from %s" texfile) nil)
13604 (condition-case nil
13605 (call-process "dvipng" nil nil nil
13606 "-E" "-fg" fg "-bg" bg
13607 "-D" dpi
13608 ;;"-x" scale "-y" scale
13609 "-T" "tight"
13610 "-o" pngfile
13611 dvifile)
13612 (error nil))
13613 (if (not (file-exists-p pngfile))
13614 (progn (message "Failed to create png file from %s" texfile) nil)
13615 ;; Use the requested file name and clean up
13616 (copy-file pngfile tofile 'replace)
13617 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
13618 (delete-file (concat texfilebase e)))
13619 pngfile))))
13621 (defun org-dvipng-color (attr)
13622 "Return an rgb color specification for dvipng."
13623 (apply 'format "rgb %s %s %s"
13624 (mapcar 'org-normalize-color
13625 (color-values (face-attribute 'default attr nil)))))
13627 (defun org-normalize-color (value)
13628 "Return string to be used as color value for an RGB component."
13629 (format "%g" (/ value 65535.0)))
13631 ;;;; Key bindings
13633 ;; Make `C-c C-x' a prefix key
13634 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
13636 ;; TAB key with modifiers
13637 (org-defkey org-mode-map "\C-i" 'org-cycle)
13638 (org-defkey org-mode-map [(tab)] 'org-cycle)
13639 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
13640 (org-defkey org-mode-map [(meta tab)] 'org-complete)
13641 (org-defkey org-mode-map "\M-\t" 'org-complete)
13642 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
13643 ;; The following line is necessary under Suse GNU/Linux
13644 (unless (featurep 'xemacs)
13645 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
13646 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
13647 (define-key org-mode-map [backtab] 'org-shifttab)
13649 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
13650 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
13651 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
13653 ;; Cursor keys with modifiers
13654 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
13655 (org-defkey org-mode-map [(meta right)] 'org-metaright)
13656 (org-defkey org-mode-map [(meta up)] 'org-metaup)
13657 (org-defkey org-mode-map [(meta down)] 'org-metadown)
13659 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
13660 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
13661 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
13662 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
13664 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
13665 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
13666 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
13667 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
13669 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
13670 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
13672 ;;; Extra keys for tty access.
13673 ;; We only set them when really needed because otherwise the
13674 ;; menus don't show the simple keys
13676 (when (or org-use-extra-keys
13677 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
13678 (not window-system))
13679 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
13680 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
13681 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
13682 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
13683 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
13684 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
13685 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
13686 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
13687 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
13688 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
13689 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
13690 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
13691 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
13692 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
13693 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
13694 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
13695 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
13696 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
13697 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
13698 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
13699 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
13700 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
13702 ;; All the other keys
13704 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
13705 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
13706 (if (boundp 'narrow-map)
13707 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
13708 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
13709 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
13710 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
13711 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
13712 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
13713 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
13714 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
13715 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
13716 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
13717 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
13718 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
13719 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
13720 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
13721 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
13722 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
13723 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
13724 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
13725 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
13726 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
13727 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
13728 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
13729 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
13730 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
13731 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
13732 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
13733 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
13734 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
13735 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
13736 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
13737 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
13738 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
13739 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
13740 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
13741 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
13742 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
13743 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
13744 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
13745 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
13746 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
13747 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
13748 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
13749 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
13750 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
13751 (org-defkey org-mode-map "\C-c^" 'org-sort)
13752 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
13753 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
13754 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
13755 (org-defkey org-mode-map "\C-m" 'org-return)
13756 (org-defkey org-mode-map "\C-j" 'org-return-indent)
13757 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
13758 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
13759 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
13760 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
13761 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
13762 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
13763 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
13764 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
13765 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
13766 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
13767 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
13768 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
13769 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
13770 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
13771 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
13772 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
13774 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
13775 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
13776 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
13777 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
13779 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
13780 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
13781 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
13782 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
13783 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
13784 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
13785 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
13786 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
13787 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
13788 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
13789 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
13790 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
13791 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
13793 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
13794 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
13795 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
13796 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
13798 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
13800 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
13802 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
13803 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
13805 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
13808 (when (featurep 'xemacs)
13809 (org-defkey org-mode-map 'button3 'popup-mode-menu))
13812 (defvar org-self-insert-command-undo-counter 0)
13814 (defvar org-table-auto-blank-field) ; defined in org-table.el
13815 (defun org-self-insert-command (N)
13816 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
13817 If the cursor is in a table looking at whitespace, the whitespace is
13818 overwritten, and the table is not marked as requiring realignment."
13819 (interactive "p")
13820 (if (and
13821 (org-table-p)
13822 (progn
13823 ;; check if we blank the field, and if that triggers align
13824 (and (featurep 'org-table) org-table-auto-blank-field
13825 (member last-command
13826 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
13827 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
13828 ;; got extra space, this field does not determine column width
13829 (let (org-table-may-need-update) (org-table-blank-field))
13830 ;; no extra space, this field may determine column width
13831 (org-table-blank-field)))
13833 (eq N 1)
13834 (looking-at "[^|\n]* |"))
13835 (let (org-table-may-need-update)
13836 (goto-char (1- (match-end 0)))
13837 (delete-backward-char 1)
13838 (goto-char (match-beginning 0))
13839 (self-insert-command N))
13840 (setq org-table-may-need-update t)
13841 (self-insert-command N)
13842 (org-fix-tags-on-the-fly)
13843 (if org-self-insert-cluster-for-undo
13844 (if (not (eq last-command 'org-self-insert-command))
13845 (setq org-self-insert-command-undo-counter 1)
13846 (if (>= org-self-insert-command-undo-counter 20)
13847 (setq org-self-insert-command-undo-counter 1)
13848 (and (> org-self-insert-command-undo-counter 0)
13849 buffer-undo-list
13850 (not (cadr buffer-undo-list)) ; remove nil entry
13851 (setcdr buffer-undo-list (cddr buffer-undo-list)))
13852 (setq org-self-insert-command-undo-counter
13853 (1+ org-self-insert-command-undo-counter)))))))
13855 (defun org-fix-tags-on-the-fly ()
13856 (when (and (equal (char-after (point-at-bol)) ?*)
13857 (org-on-heading-p))
13858 (org-align-tags-here org-tags-column)))
13860 (defun org-delete-backward-char (N)
13861 "Like `delete-backward-char', insert whitespace at field end in tables.
13862 When deleting backwards, in tables this function will insert whitespace in
13863 front of the next \"|\" separator, to keep the table aligned. The table will
13864 still be marked for re-alignment if the field did fill the entire column,
13865 because, in this case the deletion might narrow the column."
13866 (interactive "p")
13867 (if (and (org-table-p)
13868 (eq N 1)
13869 (string-match "|" (buffer-substring (point-at-bol) (point)))
13870 (looking-at ".*?|"))
13871 (let ((pos (point))
13872 (noalign (looking-at "[^|\n\r]* |"))
13873 (c org-table-may-need-update))
13874 (backward-delete-char N)
13875 (skip-chars-forward "^|")
13876 (insert " ")
13877 (goto-char (1- pos))
13878 ;; noalign: if there were two spaces at the end, this field
13879 ;; does not determine the width of the column.
13880 (if noalign (setq org-table-may-need-update c)))
13881 (backward-delete-char N)
13882 (org-fix-tags-on-the-fly)))
13884 (defun org-delete-char (N)
13885 "Like `delete-char', but insert whitespace at field end in tables.
13886 When deleting characters, in tables this function will insert whitespace in
13887 front of the next \"|\" separator, to keep the table aligned. The table will
13888 still be marked for re-alignment if the field did fill the entire column,
13889 because, in this case the deletion might narrow the column."
13890 (interactive "p")
13891 (if (and (org-table-p)
13892 (not (bolp))
13893 (not (= (char-after) ?|))
13894 (eq N 1))
13895 (if (looking-at ".*?|")
13896 (let ((pos (point))
13897 (noalign (looking-at "[^|\n\r]* |"))
13898 (c org-table-may-need-update))
13899 (replace-match (concat
13900 (substring (match-string 0) 1 -1)
13901 " |"))
13902 (goto-char pos)
13903 ;; noalign: if there were two spaces at the end, this field
13904 ;; does not determine the width of the column.
13905 (if noalign (setq org-table-may-need-update c)))
13906 (delete-char N))
13907 (delete-char N)
13908 (org-fix-tags-on-the-fly)))
13910 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
13911 (put 'org-self-insert-command 'delete-selection t)
13912 (put 'orgtbl-self-insert-command 'delete-selection t)
13913 (put 'org-delete-char 'delete-selection 'supersede)
13914 (put 'org-delete-backward-char 'delete-selection 'supersede)
13915 (put 'org-yank 'delete-selection 'yank)
13917 ;; Make `flyspell-mode' delay after some commands
13918 (put 'org-self-insert-command 'flyspell-delayed t)
13919 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
13920 (put 'org-delete-char 'flyspell-delayed t)
13921 (put 'org-delete-backward-char 'flyspell-delayed t)
13923 ;; Make pabbrev-mode expand after org-mode commands
13924 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
13925 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
13927 ;; How to do this: Measure non-white length of current string
13928 ;; If equal to column width, we should realign.
13930 (defun org-remap (map &rest commands)
13931 "In MAP, remap the functions given in COMMANDS.
13932 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
13933 (let (new old)
13934 (while commands
13935 (setq old (pop commands) new (pop commands))
13936 (if (fboundp 'command-remapping)
13937 (org-defkey map (vector 'remap old) new)
13938 (substitute-key-definition old new map global-map)))))
13940 (when (eq org-enable-table-editor 'optimized)
13941 ;; If the user wants maximum table support, we need to hijack
13942 ;; some standard editing functions
13943 (org-remap org-mode-map
13944 'self-insert-command 'org-self-insert-command
13945 'delete-char 'org-delete-char
13946 'delete-backward-char 'org-delete-backward-char)
13947 (org-defkey org-mode-map "|" 'org-force-self-insert))
13949 (defvar org-ctrl-c-ctrl-c-hook nil
13950 "Hook for functions attaching themselves to `C-c C-c'.
13951 This can be used to add additional functionality to the C-c C-c key which
13952 executes context-dependent commands.
13953 Each function will be called with no arguments. The function must check
13954 if the context is appropriate for it to act. If yes, it should do its
13955 thing and then return a non-nil value. If the context is wrong,
13956 just do nothing and return nil.")
13958 (defvar org-tab-first-hook nil
13959 "Hook for functions to attach themselves to TAB.
13960 See `org-ctrl-c-ctrl-c-hook' for more information.
13961 This hook runs as the first action when TAB is pressed, even before
13962 `org-cycle' messes around with the `outline-regexp' to cater for
13963 inline tasks and plain list item folding.
13964 If any function in this hook returns t, not other actions like table
13965 field motion visibility cycling will be done.")
13967 (defvar org-tab-after-check-for-table-hook nil
13968 "Hook for functions to attach themselves to TAB.
13969 See `org-ctrl-c-ctrl-c-hook' for more information.
13970 This hook runs after it has been established that the cursor is not in a
13971 table, but before checking if the cursor is in a headline or if global cycling
13972 should be done.
13973 If any function in this hook returns t, not other actions like visibility
13974 cycling will be done.")
13976 (defvar org-tab-after-check-for-cycling-hook nil
13977 "Hook for functions to attach themselves to TAB.
13978 See `org-ctrl-c-ctrl-c-hook' for more information.
13979 This hook runs after it has been established that not table field motion and
13980 not visibility should be done because of current context. This is probably
13981 the place where a package like yasnippets can hook in.")
13983 (defvar org-metaleft-hook nil
13984 "Hook for functions attaching themselves to `M-left'.
13985 See `org-ctrl-c-ctrl-c-hook' for more information.")
13986 (defvar org-metaright-hook nil
13987 "Hook for functions attaching themselves to `M-right'.
13988 See `org-ctrl-c-ctrl-c-hook' for more information.")
13989 (defvar org-metaup-hook nil
13990 "Hook for functions attaching themselves to `M-up'.
13991 See `org-ctrl-c-ctrl-c-hook' for more information.")
13992 (defvar org-metadown-hook nil
13993 "Hook for functions attaching themselves to `M-down'.
13994 See `org-ctrl-c-ctrl-c-hook' for more information.")
13995 (defvar org-shiftmetaleft-hook nil
13996 "Hook for functions attaching themselves to `M-S-left'.
13997 See `org-ctrl-c-ctrl-c-hook' for more information.")
13998 (defvar org-shiftmetaright-hook nil
13999 "Hook for functions attaching themselves to `M-S-right'.
14000 See `org-ctrl-c-ctrl-c-hook' for more information.")
14001 (defvar org-shiftmetaup-hook nil
14002 "Hook for functions attaching themselves to `M-S-up'.
14003 See `org-ctrl-c-ctrl-c-hook' for more information.")
14004 (defvar org-shiftmetadown-hook nil
14005 "Hook for functions attaching themselves to `M-S-down'.
14006 See `org-ctrl-c-ctrl-c-hook' for more information.")
14007 (defvar org-metareturn-hook nil
14008 "Hook for functions attaching themselves to `M-RET'.
14009 See `org-ctrl-c-ctrl-c-hook' for more information.")
14011 (defun org-modifier-cursor-error ()
14012 "Throw an error, a modified cursor command was applied in wrong context."
14013 (error "This command is active in special context like tables, headlines or items"))
14015 (defun org-shiftselect-error ()
14016 "Throw an error because Shift-Cursor command was applied in wrong context."
14017 (if (and (boundp 'shift-select-mode) shift-select-mode)
14018 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'.")
14019 (error "This command works only in special context like headlines or timestamps.")))
14021 (defun org-call-for-shift-select (cmd)
14022 (let ((this-command-keys-shift-translated t))
14023 (call-interactively cmd)))
14025 (defun org-shifttab (&optional arg)
14026 "Global visibility cycling or move to previous table field.
14027 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
14028 on context.
14029 See the individual commands for more information."
14030 (interactive "P")
14031 (cond
14032 ((org-at-table-p) (call-interactively 'org-table-previous-field))
14033 ((integerp arg)
14034 (message "Content view to level: %d" arg)
14035 (org-content (prefix-numeric-value arg))
14036 (setq org-cycle-global-status 'overview))
14037 (t (call-interactively 'org-global-cycle))))
14039 (defun org-shiftmetaleft ()
14040 "Promote subtree or delete table column.
14041 Calls `org-promote-subtree', `org-outdent-item',
14042 or `org-table-delete-column', depending on context.
14043 See the individual commands for more information."
14044 (interactive)
14045 (cond
14046 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
14047 ((org-at-table-p) (call-interactively 'org-table-delete-column))
14048 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
14049 ((org-at-item-p) (call-interactively 'org-outdent-item))
14050 (t (org-modifier-cursor-error))))
14052 (defun org-shiftmetaright ()
14053 "Demote subtree or insert table column.
14054 Calls `org-demote-subtree', `org-indent-item',
14055 or `org-table-insert-column', depending on context.
14056 See the individual commands for more information."
14057 (interactive)
14058 (cond
14059 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
14060 ((org-at-table-p) (call-interactively 'org-table-insert-column))
14061 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
14062 ((org-at-item-p) (call-interactively 'org-indent-item))
14063 (t (org-modifier-cursor-error))))
14065 (defun org-shiftmetaup (&optional arg)
14066 "Move subtree up or kill table row.
14067 Calls `org-move-subtree-up' or `org-table-kill-row' or
14068 `org-move-item-up' depending on context. See the individual commands
14069 for more information."
14070 (interactive "P")
14071 (cond
14072 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
14073 ((org-at-table-p) (call-interactively 'org-table-kill-row))
14074 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
14075 ((org-at-item-p) (call-interactively 'org-move-item-up))
14076 (t (org-modifier-cursor-error))))
14078 (defun org-shiftmetadown (&optional arg)
14079 "Move subtree down or insert table row.
14080 Calls `org-move-subtree-down' or `org-table-insert-row' or
14081 `org-move-item-down', depending on context. See the individual
14082 commands for more information."
14083 (interactive "P")
14084 (cond
14085 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
14086 ((org-at-table-p) (call-interactively 'org-table-insert-row))
14087 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
14088 ((org-at-item-p) (call-interactively 'org-move-item-down))
14089 (t (org-modifier-cursor-error))))
14091 (defun org-metaleft (&optional arg)
14092 "Promote heading or move table column to left.
14093 Calls `org-do-promote' or `org-table-move-column', depending on context.
14094 With no specific context, calls the Emacs default `backward-word'.
14095 See the individual commands for more information."
14096 (interactive "P")
14097 (cond
14098 ((run-hook-with-args-until-success 'org-metaleft-hook))
14099 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
14100 ((or (org-on-heading-p)
14101 (and (org-region-active-p)
14102 (save-excursion
14103 (goto-char (region-beginning))
14104 (org-on-heading-p))))
14105 (call-interactively 'org-do-promote))
14106 ((or (org-at-item-p)
14107 (and (org-region-active-p)
14108 (save-excursion
14109 (goto-char (region-beginning))
14110 (org-at-item-p))))
14111 (call-interactively 'org-outdent-item))
14112 (t (call-interactively 'backward-word))))
14114 (defun org-metaright (&optional arg)
14115 "Demote subtree or move table column to right.
14116 Calls `org-do-demote' or `org-table-move-column', depending on context.
14117 With no specific context, calls the Emacs default `forward-word'.
14118 See the individual commands for more information."
14119 (interactive "P")
14120 (cond
14121 ((run-hook-with-args-until-success 'org-metaright-hook))
14122 ((org-at-table-p) (call-interactively 'org-table-move-column))
14123 ((or (org-on-heading-p)
14124 (and (org-region-active-p)
14125 (save-excursion
14126 (goto-char (region-beginning))
14127 (org-on-heading-p))))
14128 (call-interactively 'org-do-demote))
14129 ((or (org-at-item-p)
14130 (and (org-region-active-p)
14131 (save-excursion
14132 (goto-char (region-beginning))
14133 (org-at-item-p))))
14134 (call-interactively 'org-indent-item))
14135 (t (call-interactively 'forward-word))))
14137 (defun org-metaup (&optional arg)
14138 "Move subtree up or move table row up.
14139 Calls `org-move-subtree-up' or `org-table-move-row' or
14140 `org-move-item-up', depending on context. See the individual commands
14141 for more information."
14142 (interactive "P")
14143 (cond
14144 ((run-hook-with-args-until-success 'org-metaup-hook))
14145 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
14146 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
14147 ((org-at-item-p) (call-interactively 'org-move-item-up))
14148 (t (transpose-lines 1) (beginning-of-line -1))))
14150 (defun org-metadown (&optional arg)
14151 "Move subtree down or move table row down.
14152 Calls `org-move-subtree-down' or `org-table-move-row' or
14153 `org-move-item-down', depending on context. See the individual
14154 commands for more information."
14155 (interactive "P")
14156 (cond
14157 ((run-hook-with-args-until-success 'org-metadown-hook))
14158 ((org-at-table-p) (call-interactively 'org-table-move-row))
14159 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
14160 ((org-at-item-p) (call-interactively 'org-move-item-down))
14161 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
14163 (defun org-shiftup (&optional arg)
14164 "Increase item in timestamp or increase priority of current headline.
14165 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
14166 depending on context. See the individual commands for more information."
14167 (interactive "P")
14168 (cond
14169 ((and org-support-shift-select (org-region-active-p))
14170 (org-call-for-shift-select 'previous-line))
14171 ((org-at-timestamp-p t)
14172 (call-interactively (if org-edit-timestamp-down-means-later
14173 'org-timestamp-down 'org-timestamp-up)))
14174 ((and (not (eq org-support-shift-select 'always))
14175 (org-on-heading-p))
14176 (call-interactively 'org-priority-up))
14177 ((and (not org-support-shift-select) (org-at-item-p))
14178 (call-interactively 'org-previous-item))
14179 ((org-clocktable-try-shift 'up arg))
14180 (org-support-shift-select
14181 (org-call-for-shift-select 'previous-line))
14182 (t (org-shiftselect-error))))
14184 (defun org-shiftdown (&optional arg)
14185 "Decrease item in timestamp or decrease priority of current headline.
14186 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
14187 depending on context. See the individual commands for more information."
14188 (interactive "P")
14189 (cond
14190 ((and org-support-shift-select (org-region-active-p))
14191 (org-call-for-shift-select 'next-line))
14192 ((org-at-timestamp-p t)
14193 (call-interactively (if org-edit-timestamp-down-means-later
14194 'org-timestamp-up 'org-timestamp-down)))
14195 ((and (not (eq org-support-shift-select 'always))
14196 (org-on-heading-p))
14197 (call-interactively 'org-priority-down))
14198 ((and (not org-support-shift-select) (org-at-item-p))
14199 (call-interactively 'org-next-item))
14200 ((org-clocktable-try-shift 'down arg))
14201 (org-support-shift-select
14202 (org-call-for-shift-select 'next-line))
14203 (t (org-shiftselect-error))))
14205 (defun org-shiftright (&optional arg)
14206 "Cycle the thing at point or in the current line, depending on context.
14207 Depending on context, this does one of the following:
14209 - switch a timestamp at point one day into the future
14210 - on a headline, switch to the next TODO keyword.
14211 - on an item, switch entire list to the next bullet type
14212 - on a property line, switch to the next allowed value
14213 - on a clocktable definition line, move time block into the future"
14214 (interactive "P")
14215 (cond
14216 ((and org-support-shift-select (org-region-active-p))
14217 (org-call-for-shift-select 'forward-char))
14218 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
14219 ((and (not (eq org-support-shift-select 'always))
14220 (org-on-heading-p))
14221 (org-call-with-arg 'org-todo 'right))
14222 ((or (and org-support-shift-select
14223 (not (eq org-support-shift-select 'always))
14224 (org-at-item-bullet-p))
14225 (and (not org-support-shift-select) (org-at-item-p)))
14226 (org-call-with-arg 'org-cycle-list-bullet nil))
14227 ((and (not (eq org-support-shift-select 'always))
14228 (org-at-property-p))
14229 (call-interactively 'org-property-next-allowed-value))
14230 ((org-clocktable-try-shift 'right arg))
14231 (org-support-shift-select
14232 (org-call-for-shift-select 'forward-char))
14233 (t (org-shiftselect-error))))
14235 (defun org-shiftleft (&optional arg)
14236 "Cycle the thing at point or in the current line, depending on context.
14237 Depending on context, this does one of the following:
14239 - switch a timestamp at point one day into the past
14240 - on a headline, switch to the previous TODO keyword.
14241 - on an item, switch entire list to the previous bullet type
14242 - on a property line, switch to the previous allowed value
14243 - on a clocktable definition line, move time block into the past"
14244 (interactive "P")
14245 (cond
14246 ((and org-support-shift-select (org-region-active-p))
14247 (org-call-for-shift-select 'backward-char))
14248 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
14249 ((and (not (eq org-support-shift-select 'always))
14250 (org-on-heading-p))
14251 (org-call-with-arg 'org-todo 'left))
14252 ((or (and org-support-shift-select
14253 (not (eq org-support-shift-select 'always))
14254 (org-at-item-bullet-p))
14255 (and (not org-support-shift-select) (org-at-item-p)))
14256 (org-call-with-arg 'org-cycle-list-bullet 'previous))
14257 ((and (not (eq org-support-shift-select 'always))
14258 (org-at-property-p))
14259 (call-interactively 'org-property-previous-allowed-value))
14260 ((org-clocktable-try-shift 'left arg))
14261 (org-support-shift-select
14262 (org-call-for-shift-select 'backward-char))
14263 (t (org-shiftselect-error))))
14265 (defun org-shiftcontrolright ()
14266 "Switch to next TODO set."
14267 (interactive)
14268 (cond
14269 ((and org-support-shift-select (org-region-active-p))
14270 (org-call-for-shift-select 'forward-word))
14271 ((and (not (eq org-support-shift-select 'always))
14272 (org-on-heading-p))
14273 (org-call-with-arg 'org-todo 'nextset))
14274 (org-support-shift-select
14275 (org-call-for-shift-select 'forward-word))
14276 (t (org-shiftselect-error))))
14278 (defun org-shiftcontrolleft ()
14279 "Switch to previous TODO set."
14280 (interactive)
14281 (cond
14282 ((and org-support-shift-select (org-region-active-p))
14283 (org-call-for-shift-select 'backward-word))
14284 ((and (not (eq org-support-shift-select 'always))
14285 (org-on-heading-p))
14286 (org-call-with-arg 'org-todo 'previousset))
14287 (org-support-shift-select
14288 (org-call-for-shift-select 'backward-word))
14289 (t (org-shiftselect-error))))
14291 (defun org-ctrl-c-ret ()
14292 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
14293 (interactive)
14294 (cond
14295 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
14296 (t (call-interactively 'org-insert-heading))))
14298 (defun org-copy-special ()
14299 "Copy region in table or copy current subtree.
14300 Calls `org-table-copy' or `org-copy-subtree', depending on context.
14301 See the individual commands for more information."
14302 (interactive)
14303 (call-interactively
14304 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
14306 (defun org-cut-special ()
14307 "Cut region in table or cut current subtree.
14308 Calls `org-table-copy' or `org-cut-subtree', depending on context.
14309 See the individual commands for more information."
14310 (interactive)
14311 (call-interactively
14312 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
14314 (defun org-paste-special (arg)
14315 "Paste rectangular region into table, or past subtree relative to level.
14316 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
14317 See the individual commands for more information."
14318 (interactive "P")
14319 (if (org-at-table-p)
14320 (org-table-paste-rectangle)
14321 (org-paste-subtree arg)))
14323 (defun org-edit-special ()
14324 "Call a special editor for the stuff at point.
14325 When at a table, call the formula editor with `org-table-edit-formulas'.
14326 When at the first line of an src example, call `org-edit-src-code'.
14327 When in an #+include line, visit the include file. Otherwise call
14328 `ffap' to visit the file at point."
14329 (interactive)
14330 (cond
14331 ((org-at-table-p)
14332 (call-interactively 'org-table-edit-formulas))
14333 ((save-excursion
14334 (beginning-of-line 1)
14335 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
14336 (find-file (org-trim (match-string 1))))
14337 ((org-edit-src-code))
14338 ((org-edit-fixed-width-region))
14339 (t (call-interactively 'ffap))))
14342 (defun org-ctrl-c-ctrl-c (&optional arg)
14343 "Set tags in headline, or update according to changed information at point.
14345 This command does many different things, depending on context:
14347 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
14348 this is what we do.
14350 - If the cursor is in a headline, prompt for tags and insert them
14351 into the current line, aligned to `org-tags-column'. When called
14352 with prefix arg, realign all tags in the current buffer.
14354 - If the cursor is in one of the special #+KEYWORD lines, this
14355 triggers scanning the buffer for these lines and updating the
14356 information.
14358 - If the cursor is inside a table, realign the table. This command
14359 works even if the automatic table editor has been turned off.
14361 - If the cursor is on a #+TBLFM line, re-apply the formulas to
14362 the entire table.
14364 - If the cursor is at a footnote reference or definition, jump to
14365 the corresponding definition or references, respectively.
14367 - If the cursor is a the beginning of a dynamic block, update it.
14369 - If the cursor is inside a table created by the table.el package,
14370 activate that table.
14372 - If the current buffer is a remember buffer, close note and file
14373 it. A prefix argument of 1 files to the default location
14374 without further interaction. A prefix argument of 2 files to
14375 the currently clocking task.
14377 - If the cursor is on a <<<target>>>, update radio targets and corresponding
14378 links in this buffer.
14380 - If the cursor is on a numbered item in a plain list, renumber the
14381 ordered list.
14383 - If the cursor is on a checkbox, toggle it."
14384 (interactive "P")
14385 (let ((org-enable-table-editor t))
14386 (cond
14387 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
14388 org-occur-highlights
14389 org-latex-fragment-image-overlays)
14390 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
14391 (org-remove-occur-highlights)
14392 (org-remove-latex-fragment-image-overlays)
14393 (message "Temporary highlights/overlays removed from current buffer"))
14394 ((and (local-variable-p 'org-finish-function (current-buffer))
14395 (fboundp org-finish-function))
14396 (funcall org-finish-function))
14397 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
14398 ((org-at-property-p)
14399 (call-interactively 'org-property-action))
14400 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
14401 ((org-on-heading-p) (call-interactively 'org-set-tags))
14402 ((org-at-table.el-p)
14403 (require 'table)
14404 (beginning-of-line 1)
14405 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
14406 (call-interactively 'table-recognize-table))
14407 ((org-at-table-p)
14408 (org-table-maybe-eval-formula)
14409 (if arg
14410 (call-interactively 'org-table-recalculate)
14411 (org-table-maybe-recalculate-line))
14412 (call-interactively 'org-table-align))
14413 ((or (org-footnote-at-reference-p)
14414 (org-footnote-at-definition-p))
14415 (call-interactively 'org-footnote-action))
14416 ((org-at-item-checkbox-p)
14417 (call-interactively 'org-toggle-checkbox))
14418 ((org-at-item-p)
14419 (if arg
14420 (call-interactively 'org-toggle-checkbox)
14421 (call-interactively 'org-maybe-renumber-ordered-list)))
14422 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
14423 ;; Dynamic block
14424 (beginning-of-line 1)
14425 (save-excursion (org-update-dblock)))
14426 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
14427 (cond
14428 ((equal (match-string 1) "TBLFM")
14429 ;; Recalculate the table before this line
14430 (save-excursion
14431 (beginning-of-line 1)
14432 (skip-chars-backward " \r\n\t")
14433 (if (org-at-table-p)
14434 (org-call-with-arg 'org-table-recalculate t))))
14436 ; (org-set-regexps-and-options)
14437 ; (org-restart-font-lock)
14438 (let ((org-inhibit-startup t)) (org-mode-restart))
14439 (message "Local setup has been refreshed"))))
14440 (t (error "C-c C-c can do nothing useful at this location.")))))
14442 (defun org-mode-restart ()
14443 "Restart Org-mode, to scan again for special lines.
14444 Also updates the keyword regular expressions."
14445 (interactive)
14446 (org-mode)
14447 (message "Org-mode restarted"))
14449 (defun org-kill-note-or-show-branches ()
14450 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
14451 (interactive)
14452 (if (not org-finish-function)
14453 (call-interactively 'show-branches)
14454 (let ((org-note-abort t))
14455 (funcall org-finish-function))))
14457 (defun org-return (&optional indent)
14458 "Goto next table row or insert a newline.
14459 Calls `org-table-next-row' or `newline', depending on context.
14460 See the individual commands for more information."
14461 (interactive)
14462 (cond
14463 ((bobp) (if indent (newline-and-indent) (newline)))
14464 ((org-at-table-p)
14465 (org-table-justify-field-maybe)
14466 (call-interactively 'org-table-next-row))
14467 ((and org-return-follows-link
14468 (eq (get-text-property (point) 'face) 'org-link))
14469 (call-interactively 'org-open-at-point))
14470 ((and (org-at-heading-p)
14471 (looking-at
14472 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
14473 (org-show-entry)
14474 (end-of-line 1)
14475 (newline))
14476 (t (if indent (newline-and-indent) (newline)))))
14478 (defun org-return-indent ()
14479 "Goto next table row or insert a newline and indent.
14480 Calls `org-table-next-row' or `newline-and-indent', depending on
14481 context. See the individual commands for more information."
14482 (interactive)
14483 (org-return t))
14485 (defun org-ctrl-c-star ()
14486 "Compute table, or change heading status of lines.
14487 Calls `org-table-recalculate' or `org-toggle-heading',
14488 depending on context."
14489 (interactive)
14490 (cond
14491 ((org-at-table-p)
14492 (call-interactively 'org-table-recalculate))
14494 ;; Convert all lines in region to list items
14495 (call-interactively 'org-toggle-heading))))
14497 (defun org-ctrl-c-minus ()
14498 "Insert separator line in table or modify bullet status of line.
14499 Also turns a plain line or a region of lines into list items.
14500 Calls `org-table-insert-hline', `org-toggle-item', or
14501 `org-cycle-list-bullet', depending on context."
14502 (interactive)
14503 (cond
14504 ((org-at-table-p)
14505 (call-interactively 'org-table-insert-hline))
14506 ((org-region-active-p)
14507 (call-interactively 'org-toggle-item))
14508 ((org-in-item-p)
14509 (call-interactively 'org-cycle-list-bullet))
14511 (call-interactively 'org-toggle-item))))
14513 (defun org-toggle-item ()
14514 "Convert headings or normal lines to items, items to normal lines.
14515 If there is no active region, only the current line is considered.
14517 If the first line in the region is a headline, convert all headlines to items.
14519 If the first line in the region is an item, convert all items to normal lines.
14521 If the first line is normal text, add an item bullet to each line."
14522 (interactive)
14523 (let (l2 l beg end)
14524 (if (org-region-active-p)
14525 (setq beg (region-beginning) end (region-end))
14526 (setq beg (point-at-bol)
14527 end (min (1+ (point-at-eol)) (point-max))))
14528 (save-excursion
14529 (goto-char end)
14530 (setq l2 (org-current-line))
14531 (goto-char beg)
14532 (beginning-of-line 1)
14533 (setq l (1- (org-current-line)))
14534 (if (org-at-item-p)
14535 ;; We already have items, de-itemize
14536 (while (< (setq l (1+ l)) l2)
14537 (when (org-at-item-p)
14538 (goto-char (match-beginning 2))
14539 (delete-region (match-beginning 2) (match-end 2))
14540 (and (looking-at "[ \t]+") (replace-match "")))
14541 (beginning-of-line 2))
14542 (if (org-on-heading-p)
14543 ;; Headings, convert to items
14544 (while (< (setq l (1+ l)) l2)
14545 (if (looking-at org-outline-regexp)
14546 (replace-match "- " t t))
14547 (beginning-of-line 2))
14548 ;; normal lines, turn them into items
14549 (while (< (setq l (1+ l)) l2)
14550 (unless (org-at-item-p)
14551 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
14552 (replace-match "\\1- \\2")))
14553 (beginning-of-line 2)))))))
14555 (defun org-toggle-heading (&optional nstars)
14556 "Convert headings to normal text, or items or text to headings.
14557 If there is no active region, only the current line is considered.
14559 If the first line is a heading, remove the stars from all headlines
14560 in the region.
14562 If the first line is a plain list item, turn all plain list items into
14563 headings.
14565 If the first line is a normal line, turn each and every line in the region
14566 into a heading.
14568 When converting a line into a heading, the number of stars is chosen
14569 such that the lines become children of the current entry. However, when
14570 a prefix argument is given, its value determines the number of stars to add."
14571 (interactive "P")
14572 (let (l2 l itemp beg end)
14573 (if (org-region-active-p)
14574 (setq beg (region-beginning) end (region-end))
14575 (setq beg (point-at-bol)
14576 end (min (1+ (point-at-eol)) (point-max))))
14577 (save-excursion
14578 (goto-char end)
14579 (setq l2 (org-current-line))
14580 (goto-char beg)
14581 (beginning-of-line 1)
14582 (setq l (1- (org-current-line)))
14583 (if (org-on-heading-p)
14584 ;; We already have headlines, de-star them
14585 (while (< (setq l (1+ l)) l2)
14586 (when (org-on-heading-p t)
14587 (and (looking-at outline-regexp) (replace-match "")))
14588 (beginning-of-line 2))
14589 (setq itemp (org-at-item-p))
14590 (let* ((stars
14591 (if nstars
14592 (make-string (prefix-numeric-value current-prefix-arg)
14594 (save-excursion
14595 (re-search-backward org-complex-heading-regexp nil t)
14596 (or (match-string 1) ""))))
14597 (add-stars (cond (nstars "")
14598 ((equal stars "") "*")
14599 (org-odd-levels-only "**")
14600 (t "*")))
14601 (rpl (concat stars add-stars " ")))
14602 (while (< (setq l (1+ l)) l2)
14603 (if itemp
14604 (and (org-at-item-p) (replace-match rpl t t))
14605 (unless (org-on-heading-p)
14606 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
14607 (replace-match (concat rpl (match-string 2))))))
14608 (beginning-of-line 2)))))))
14610 (defun org-meta-return (&optional arg)
14611 "Insert a new heading or wrap a region in a table.
14612 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
14613 See the individual commands for more information."
14614 (interactive "P")
14615 (cond
14616 ((run-hook-with-args-until-success 'org-metareturn-hook))
14617 ((org-at-table-p)
14618 (call-interactively 'org-table-wrap-region))
14619 (t (call-interactively 'org-insert-heading))))
14621 ;;; Menu entries
14623 ;; Define the Org-mode menus
14624 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
14625 '("Tbl"
14626 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
14627 ["Next Field" org-cycle (org-at-table-p)]
14628 ["Previous Field" org-shifttab (org-at-table-p)]
14629 ["Next Row" org-return (org-at-table-p)]
14630 "--"
14631 ["Blank Field" org-table-blank-field (org-at-table-p)]
14632 ["Edit Field" org-table-edit-field (org-at-table-p)]
14633 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
14634 "--"
14635 ("Column"
14636 ["Move Column Left" org-metaleft (org-at-table-p)]
14637 ["Move Column Right" org-metaright (org-at-table-p)]
14638 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
14639 ["Insert Column" org-shiftmetaright (org-at-table-p)])
14640 ("Row"
14641 ["Move Row Up" org-metaup (org-at-table-p)]
14642 ["Move Row Down" org-metadown (org-at-table-p)]
14643 ["Delete Row" org-shiftmetaup (org-at-table-p)]
14644 ["Insert Row" org-shiftmetadown (org-at-table-p)]
14645 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
14646 "--"
14647 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
14648 ("Rectangle"
14649 ["Copy Rectangle" org-copy-special (org-at-table-p)]
14650 ["Cut Rectangle" org-cut-special (org-at-table-p)]
14651 ["Paste Rectangle" org-paste-special (org-at-table-p)]
14652 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
14653 "--"
14654 ("Calculate"
14655 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
14656 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
14657 ["Edit Formulas" org-edit-special (org-at-table-p)]
14658 "--"
14659 ["Recalculate line" org-table-recalculate (org-at-table-p)]
14660 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
14661 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
14662 "--"
14663 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
14664 "--"
14665 ["Sum Column/Rectangle" org-table-sum
14666 (or (org-at-table-p) (org-region-active-p))]
14667 ["Which Column?" org-table-current-column (org-at-table-p)])
14668 ["Debug Formulas"
14669 org-table-toggle-formula-debugger
14670 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
14671 ["Show Col/Row Numbers"
14672 org-table-toggle-coordinate-overlays
14673 :style toggle
14674 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
14675 "--"
14676 ["Create" org-table-create (and (not (org-at-table-p))
14677 org-enable-table-editor)]
14678 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
14679 ["Import from File" org-table-import (not (org-at-table-p))]
14680 ["Export to File" org-table-export (org-at-table-p)]
14681 "--"
14682 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
14684 (easy-menu-define org-org-menu org-mode-map "Org menu"
14685 '("Org"
14686 ("Show/Hide"
14687 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
14688 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
14689 ["Sparse Tree..." org-sparse-tree t]
14690 ["Reveal Context" org-reveal t]
14691 ["Show All" show-all t]
14692 "--"
14693 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
14694 "--"
14695 ["New Heading" org-insert-heading t]
14696 ("Navigate Headings"
14697 ["Up" outline-up-heading t]
14698 ["Next" outline-next-visible-heading t]
14699 ["Previous" outline-previous-visible-heading t]
14700 ["Next Same Level" outline-forward-same-level t]
14701 ["Previous Same Level" outline-backward-same-level t]
14702 "--"
14703 ["Jump" org-goto t])
14704 ("Edit Structure"
14705 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
14706 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
14707 "--"
14708 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
14709 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
14710 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
14711 "--"
14712 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
14713 "--"
14714 ["Promote Heading" org-metaleft (not (org-at-table-p))]
14715 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
14716 ["Demote Heading" org-metaright (not (org-at-table-p))]
14717 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
14718 "--"
14719 ["Sort Region/Children" org-sort (not (org-at-table-p))]
14720 "--"
14721 ["Convert to odd levels" org-convert-to-odd-levels t]
14722 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
14723 ("Editing"
14724 ["Emphasis..." org-emphasize t]
14725 ["Edit Source Example" org-edit-special t]
14726 "--"
14727 ["Footnote new/jump" org-footnote-action t]
14728 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
14729 ("Archive"
14730 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
14731 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
14732 ; :active t :keys "C-u C-c C-x C-a"]
14733 ["Sparse trees open ARCHIVE trees"
14734 (setq org-sparse-tree-open-archived-trees
14735 (not org-sparse-tree-open-archived-trees))
14736 :style toggle :selected org-sparse-tree-open-archived-trees]
14737 ["Cycling opens ARCHIVE trees"
14738 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
14739 :style toggle :selected org-cycle-open-archived-trees]
14740 "--"
14741 ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
14742 ["Move Subtree to Archive" org-advertized-archive-subtree t]
14743 ; ["Check and Move Children" (org-archive-subtree '(4))
14744 ; :active t :keys "C-u C-c C-x C-s"]
14746 "--"
14747 ("Hyperlinks"
14748 ["Store Link (Global)" org-store-link t]
14749 ["Insert Link" org-insert-link t]
14750 ["Follow Link" org-open-at-point t]
14751 "--"
14752 ["Next link" org-next-link t]
14753 ["Previous link" org-previous-link t]
14754 "--"
14755 ["Descriptive Links"
14756 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
14757 :style radio
14758 :selected (member '(org-link) buffer-invisibility-spec)]
14759 ["Literal Links"
14760 (progn
14761 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
14762 :style radio
14763 :selected (not (member '(org-link) buffer-invisibility-spec))])
14764 "--"
14765 ("TODO Lists"
14766 ["TODO/DONE/-" org-todo t]
14767 ("Select keyword"
14768 ["Next keyword" org-shiftright (org-on-heading-p)]
14769 ["Previous keyword" org-shiftleft (org-on-heading-p)]
14770 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
14771 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
14772 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
14773 ["Show TODO Tree" org-show-todo-tree t]
14774 ["Global TODO list" org-todo-list t]
14775 "--"
14776 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
14777 :selected org-enforce-todo-dependencies :style toggle :active t]
14778 "Settings for tree at point"
14779 ["Do Children sequentially" org-toggle-ordered-property :style radio
14780 :selected (ignore-errors (org-entry-get nil "ORDERED"))
14781 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
14782 ["Do Children parallel" org-toggle-ordered-property :style radio
14783 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
14784 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
14785 "--"
14786 ["Set Priority" org-priority t]
14787 ["Priority Up" org-shiftup t]
14788 ["Priority Down" org-shiftdown t]
14789 "--"
14790 ["Get news from all feeds" org-feed-update-all t]
14791 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
14792 ["Customize feeds" (customize-variable 'org-feed-alist) t])
14793 ("TAGS and Properties"
14794 ["Set Tags" org-set-tags-command t]
14795 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
14796 "--"
14797 ["Set property" org-set-property t]
14798 ["Column view of properties" org-columns t]
14799 ["Insert Column View DBlock" org-insert-columns-dblock t])
14800 ("Dates and Scheduling"
14801 ["Timestamp" org-time-stamp t]
14802 ["Timestamp (inactive)" org-time-stamp-inactive t]
14803 ("Change Date"
14804 ["1 Day Later" org-shiftright t]
14805 ["1 Day Earlier" org-shiftleft t]
14806 ["1 ... Later" org-shiftup t]
14807 ["1 ... Earlier" org-shiftdown t])
14808 ["Compute Time Range" org-evaluate-time-range t]
14809 ["Schedule Item" org-schedule t]
14810 ["Deadline" org-deadline t]
14811 "--"
14812 ["Custom time format" org-toggle-time-stamp-overlays
14813 :style radio :selected org-display-custom-times]
14814 "--"
14815 ["Goto Calendar" org-goto-calendar t]
14816 ["Date from Calendar" org-date-from-calendar t]
14817 "--"
14818 ["Start/Restart Timer" org-timer-start t]
14819 ["Pause/Continue Timer" org-timer-pause-or-continue t]
14820 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
14821 ["Insert Timer String" org-timer t]
14822 ["Insert Timer Item" org-timer-item t])
14823 ("Logging work"
14824 ["Clock in" org-clock-in t]
14825 ["Clock out" org-clock-out t]
14826 ["Clock cancel" org-clock-cancel t]
14827 ["Goto running clock" org-clock-goto t]
14828 ["Display times" org-clock-display t]
14829 ["Create clock table" org-clock-report t]
14830 "--"
14831 ["Record DONE time"
14832 (progn (setq org-log-done (not org-log-done))
14833 (message "Switching to %s will %s record a timestamp"
14834 (car org-done-keywords)
14835 (if org-log-done "automatically" "not")))
14836 :style toggle :selected org-log-done])
14837 "--"
14838 ["Agenda Command..." org-agenda t]
14839 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
14840 ("File List for Agenda")
14841 ("Special views current file"
14842 ["TODO Tree" org-show-todo-tree t]
14843 ["Check Deadlines" org-check-deadlines t]
14844 ["Timeline" org-timeline t]
14845 ["Tags/Property tree" org-match-sparse-tree t])
14846 "--"
14847 ["Export/Publish..." org-export t]
14848 ("LaTeX"
14849 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
14850 :selected org-cdlatex-mode]
14851 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
14852 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
14853 ["Modify math symbol" org-cdlatex-math-modify
14854 (org-inside-LaTeX-fragment-p)]
14855 ["Insert citation" org-reftex-citation t]
14856 "--"
14857 ["Export LaTeX fragments as images"
14858 (if (featurep 'org-exp)
14859 (setq org-export-with-LaTeX-fragments
14860 (not org-export-with-LaTeX-fragments))
14861 (require 'org-exp))
14862 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
14863 org-export-with-LaTeX-fragments)])
14864 "--"
14865 ("Documentation"
14866 ["Show Version" org-version t]
14867 ["Info Documentation" org-info t])
14868 ("Customize"
14869 ["Browse Org Group" org-customize t]
14870 "--"
14871 ["Expand This Menu" org-create-customize-menu
14872 (fboundp 'customize-menu-create)])
14873 "--"
14874 ("Refresh/Reload"
14875 ["Refresh setup current buffer" org-mode-restart t]
14876 ["Reload Org (after update)" org-reload t]
14877 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
14880 (defun org-info (&optional node)
14881 "Read documentation for Org-mode in the info system.
14882 With optional NODE, go directly to that node."
14883 (interactive)
14884 (info (format "(org)%s" (or node ""))))
14886 (defun org-install-agenda-files-menu ()
14887 (let ((bl (buffer-list)))
14888 (save-excursion
14889 (while bl
14890 (set-buffer (pop bl))
14891 (if (org-mode-p) (setq bl nil)))
14892 (when (org-mode-p)
14893 (easy-menu-change
14894 '("Org") "File List for Agenda"
14895 (append
14896 (list
14897 ["Edit File List" (org-edit-agenda-file-list) t]
14898 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
14899 ["Remove Current File from List" org-remove-file t]
14900 ["Cycle through agenda files" org-cycle-agenda-files t]
14901 ["Occur in all agenda files" org-occur-in-agenda-files t]
14902 "--")
14903 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
14905 ;;;; Documentation
14907 ;;;###autoload
14908 (defun org-require-autoloaded-modules ()
14909 (interactive)
14910 (mapc 'require
14911 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
14912 org-docbook org-exp org-html org-icalendar
14913 org-id org-latex
14914 org-publish org-remember org-table
14915 org-timer org-xoxo)))
14917 ;;;###autoload
14918 (defun org-reload (&optional uncompiled)
14919 "Reload all org lisp files.
14920 With prefix arg UNCOMPILED, load the uncompiled versions."
14921 (interactive "P")
14922 (require 'find-func)
14923 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
14924 (dir-org (file-name-directory (org-find-library-name "org")))
14925 (dir-org-contrib (ignore-errors
14926 (file-name-directory
14927 (org-find-library-name "org-contribdir"))))
14928 (files
14929 (append (directory-files dir-org t file-re)
14930 (and dir-org-contrib
14931 (directory-files dir-org-contrib t file-re))))
14932 (remove-re (concat (if (featurep 'xemacs)
14933 "org-colview" "org-colview-xemacs")
14934 "\\'")))
14935 (setq files (mapcar 'file-name-sans-extension files))
14936 (setq files (mapcar
14937 (lambda (x) (if (string-match remove-re x) nil x))
14938 files))
14939 (setq files (delq nil files))
14940 (mapc
14941 (lambda (f)
14942 (when (featurep (intern (file-name-nondirectory f)))
14943 (if (and (not uncompiled)
14944 (file-exists-p (concat f ".elc")))
14945 (load (concat f ".elc") nil nil t)
14946 (load (concat f ".el") nil nil t))))
14947 files))
14948 (org-version))
14950 ;;;###autoload
14951 (defun org-customize ()
14952 "Call the customize function with org as argument."
14953 (interactive)
14954 (org-load-modules-maybe)
14955 (org-require-autoloaded-modules)
14956 (customize-browse 'org))
14958 (defun org-create-customize-menu ()
14959 "Create a full customization menu for Org-mode, insert it into the menu."
14960 (interactive)
14961 (org-load-modules-maybe)
14962 (org-require-autoloaded-modules)
14963 (if (fboundp 'customize-menu-create)
14964 (progn
14965 (easy-menu-change
14966 '("Org") "Customize"
14967 `(["Browse Org group" org-customize t]
14968 "--"
14969 ,(customize-menu-create 'org)
14970 ["Set" Custom-set t]
14971 ["Save" Custom-save t]
14972 ["Reset to Current" Custom-reset-current t]
14973 ["Reset to Saved" Custom-reset-saved t]
14974 ["Reset to Standard Settings" Custom-reset-standard t]))
14975 (message "\"Org\"-menu now contains full customization menu"))
14976 (error "Cannot expand menu (outdated version of cus-edit.el)")))
14978 ;;;; Miscellaneous stuff
14980 ;;; Generally useful functions
14982 (defun org-find-text-property-in-string (prop s)
14983 "Return the first non-nil value of property PROP in string S."
14984 (or (get-text-property 0 prop s)
14985 (get-text-property (or (next-single-property-change 0 prop s) 0)
14986 prop s)))
14988 (defun org-display-warning (message) ;; Copied from Emacs-Muse
14989 "Display the given MESSAGE as a warning."
14990 (if (fboundp 'display-warning)
14991 (display-warning 'org message
14992 (if (featurep 'xemacs)
14993 'warning
14994 :warning))
14995 (let ((buf (get-buffer-create "*Org warnings*")))
14996 (with-current-buffer buf
14997 (goto-char (point-max))
14998 (insert "Warning (Org): " message)
14999 (unless (bolp)
15000 (newline)))
15001 (display-buffer buf)
15002 (sit-for 0))))
15004 (defun org-goto-marker-or-bmk (marker &optional bookmark)
15005 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
15006 (if (and marker (marker-buffer marker)
15007 (buffer-live-p (marker-buffer marker)))
15008 (progn
15009 (switch-to-buffer (marker-buffer marker))
15010 (if (or (> marker (point-max)) (< marker (point-min)))
15011 (widen))
15012 (goto-char marker)
15013 (org-show-context 'org-goto))
15014 (if bookmark
15015 (bookmark-jump bookmark)
15016 (error "Cannot find location"))))
15018 (defun org-quote-csv-field (s)
15019 "Quote field for inclusion in CSV material."
15020 (if (string-match "[\",]" s)
15021 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
15024 (defun org-plist-delete (plist property)
15025 "Delete PROPERTY from PLIST.
15026 This is in contrast to merely setting it to 0."
15027 (let (p)
15028 (while plist
15029 (if (not (eq property (car plist)))
15030 (setq p (plist-put p (car plist) (nth 1 plist))))
15031 (setq plist (cddr plist)))
15034 (defun org-force-self-insert (N)
15035 "Needed to enforce self-insert under remapping."
15036 (interactive "p")
15037 (self-insert-command N))
15039 (defun org-string-width (s)
15040 "Compute width of string, ignoring invisible characters.
15041 This ignores character with invisibility property `org-link', and also
15042 characters with property `org-cwidth', because these will become invisible
15043 upon the next fontification round."
15044 (let (b l)
15045 (when (or (eq t buffer-invisibility-spec)
15046 (assq 'org-link buffer-invisibility-spec))
15047 (while (setq b (text-property-any 0 (length s)
15048 'invisible 'org-link s))
15049 (setq s (concat (substring s 0 b)
15050 (substring s (or (next-single-property-change
15051 b 'invisible s) (length s)))))))
15052 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
15053 (setq s (concat (substring s 0 b)
15054 (substring s (or (next-single-property-change
15055 b 'org-cwidth s) (length s))))))
15056 (setq l (string-width s) b -1)
15057 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
15058 (setq l (- l (get-text-property b 'org-dwidth-n s))))
15061 (defun org-get-indentation (&optional line)
15062 "Get the indentation of the current line, interpreting tabs.
15063 When LINE is given, assume it represents a line and compute its indentation."
15064 (if line
15065 (if (string-match "^ *" (org-remove-tabs line))
15066 (match-end 0))
15067 (save-excursion
15068 (beginning-of-line 1)
15069 (skip-chars-forward " \t")
15070 (current-column))))
15072 (defun org-remove-tabs (s &optional width)
15073 "Replace tabulators in S with spaces.
15074 Assumes that s is a single line, starting in column 0."
15075 (setq width (or width tab-width))
15076 (while (string-match "\t" s)
15077 (setq s (replace-match
15078 (make-string
15079 (- (* width (/ (+ (match-beginning 0) width) width))
15080 (match-beginning 0)) ?\ )
15081 t t s)))
15084 (defun org-fix-indentation (line ind)
15085 "Fix indentation in LINE.
15086 IND is a cons cell with target and minimum indentation.
15087 If the current indentation in LINE is smaller than the minimum,
15088 leave it alone. If it is larger than ind, set it to the target."
15089 (let* ((l (org-remove-tabs line))
15090 (i (org-get-indentation l))
15091 (i1 (car ind)) (i2 (cdr ind)))
15092 (if (>= i i2) (setq l (substring line i2)))
15093 (if (> i1 0)
15094 (concat (make-string i1 ?\ ) l)
15095 l)))
15097 (defun org-base-buffer (buffer)
15098 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
15099 (if (not buffer)
15100 buffer
15101 (or (buffer-base-buffer buffer)
15102 buffer)))
15104 (defun org-trim (s)
15105 "Remove whitespace at beginning and end of string."
15106 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
15107 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
15110 (defun org-wrap (string &optional width lines)
15111 "Wrap string to either a number of lines, or a width in characters.
15112 If WIDTH is non-nil, the string is wrapped to that width, however many lines
15113 that costs. If there is a word longer than WIDTH, the text is actually
15114 wrapped to the length of that word.
15115 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
15116 many lines, whatever width that takes.
15117 The return value is a list of lines, without newlines at the end."
15118 (let* ((words (org-split-string string "[ \t\n]+"))
15119 (maxword (apply 'max (mapcar 'org-string-width words)))
15120 w ll)
15121 (cond (width
15122 (org-do-wrap words (max maxword width)))
15123 (lines
15124 (setq w maxword)
15125 (setq ll (org-do-wrap words maxword))
15126 (if (<= (length ll) lines)
15128 (setq ll words)
15129 (while (> (length ll) lines)
15130 (setq w (1+ w))
15131 (setq ll (org-do-wrap words w)))
15132 ll))
15133 (t (error "Cannot wrap this")))))
15135 (defun org-do-wrap (words width)
15136 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
15137 (let (lines line)
15138 (while words
15139 (setq line (pop words))
15140 (while (and words (< (+ (length line) (length (car words))) width))
15141 (setq line (concat line " " (pop words))))
15142 (setq lines (push line lines)))
15143 (nreverse lines)))
15145 (defun org-split-string (string &optional separators)
15146 "Splits STRING into substrings at SEPARATORS.
15147 No empty strings are returned if there are matches at the beginning
15148 and end of string."
15149 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
15150 (start 0)
15151 notfirst
15152 (list nil))
15153 (while (and (string-match rexp string
15154 (if (and notfirst
15155 (= start (match-beginning 0))
15156 (< start (length string)))
15157 (1+ start) start))
15158 (< (match-beginning 0) (length string)))
15159 (setq notfirst t)
15160 (or (eq (match-beginning 0) 0)
15161 (and (eq (match-beginning 0) (match-end 0))
15162 (eq (match-beginning 0) start))
15163 (setq list
15164 (cons (substring string start (match-beginning 0))
15165 list)))
15166 (setq start (match-end 0)))
15167 (or (eq start (length string))
15168 (setq list
15169 (cons (substring string start)
15170 list)))
15171 (nreverse list)))
15173 (defun org-uuidgen-p (s)
15174 "Is S an ID created by UUIDGEN?"
15175 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
15177 (defun org-context ()
15178 "Return a list of contexts of the current cursor position.
15179 If several contexts apply, all are returned.
15180 Each context entry is a list with a symbol naming the context, and
15181 two positions indicating start and end of the context. Possible
15182 contexts are:
15184 :headline anywhere in a headline
15185 :headline-stars on the leading stars in a headline
15186 :todo-keyword on a TODO keyword (including DONE) in a headline
15187 :tags on the TAGS in a headline
15188 :priority on the priority cookie in a headline
15189 :item on the first line of a plain list item
15190 :item-bullet on the bullet/number of a plain list item
15191 :checkbox on the checkbox in a plain list item
15192 :table in an org-mode table
15193 :table-special on a special filed in a table
15194 :table-table in a table.el table
15195 :link on a hyperlink
15196 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
15197 :target on a <<target>>
15198 :radio-target on a <<<radio-target>>>
15199 :latex-fragment on a LaTeX fragment
15200 :latex-preview on a LaTeX fragment with overlayed preview image
15202 This function expects the position to be visible because it uses font-lock
15203 faces as a help to recognize the following contexts: :table-special, :link,
15204 and :keyword."
15205 (let* ((f (get-text-property (point) 'face))
15206 (faces (if (listp f) f (list f)))
15207 (p (point)) clist o)
15208 ;; First the large context
15209 (cond
15210 ((org-on-heading-p t)
15211 (push (list :headline (point-at-bol) (point-at-eol)) clist)
15212 (when (progn
15213 (beginning-of-line 1)
15214 (looking-at org-todo-line-tags-regexp))
15215 (push (org-point-in-group p 1 :headline-stars) clist)
15216 (push (org-point-in-group p 2 :todo-keyword) clist)
15217 (push (org-point-in-group p 4 :tags) clist))
15218 (goto-char p)
15219 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
15220 (if (looking-at "\\[#[A-Z0-9]\\]")
15221 (push (org-point-in-group p 0 :priority) clist)))
15223 ((org-at-item-p)
15224 (push (org-point-in-group p 2 :item-bullet) clist)
15225 (push (list :item (point-at-bol)
15226 (save-excursion (org-end-of-item) (point)))
15227 clist)
15228 (and (org-at-item-checkbox-p)
15229 (push (org-point-in-group p 0 :checkbox) clist)))
15231 ((org-at-table-p)
15232 (push (list :table (org-table-begin) (org-table-end)) clist)
15233 (if (memq 'org-formula faces)
15234 (push (list :table-special
15235 (previous-single-property-change p 'face)
15236 (next-single-property-change p 'face)) clist)))
15237 ((org-at-table-p 'any)
15238 (push (list :table-table) clist)))
15239 (goto-char p)
15241 ;; Now the small context
15242 (cond
15243 ((org-at-timestamp-p)
15244 (push (org-point-in-group p 0 :timestamp) clist))
15245 ((memq 'org-link faces)
15246 (push (list :link
15247 (previous-single-property-change p 'face)
15248 (next-single-property-change p 'face)) clist))
15249 ((memq 'org-special-keyword faces)
15250 (push (list :keyword
15251 (previous-single-property-change p 'face)
15252 (next-single-property-change p 'face)) clist))
15253 ((org-on-target-p)
15254 (push (org-point-in-group p 0 :target) clist)
15255 (goto-char (1- (match-beginning 0)))
15256 (if (looking-at org-radio-target-regexp)
15257 (push (org-point-in-group p 0 :radio-target) clist))
15258 (goto-char p))
15259 ((setq o (car (delq nil
15260 (mapcar
15261 (lambda (x)
15262 (if (memq x org-latex-fragment-image-overlays) x))
15263 (org-overlays-at (point))))))
15264 (push (list :latex-fragment
15265 (org-overlay-start o) (org-overlay-end o)) clist)
15266 (push (list :latex-preview
15267 (org-overlay-start o) (org-overlay-end o)) clist))
15268 ((org-inside-LaTeX-fragment-p)
15269 ;; FIXME: positions wrong.
15270 (push (list :latex-fragment (point) (point)) clist)))
15272 (setq clist (nreverse (delq nil clist)))
15273 clist))
15275 ;; FIXME: Compare with at-regexp-p Do we need both?
15276 (defun org-in-regexp (re &optional nlines visually)
15277 "Check if point is inside a match of regexp.
15278 Normally only the current line is checked, but you can include NLINES extra
15279 lines both before and after point into the search.
15280 If VISUALLY is set, require that the cursor is not after the match but
15281 really on, so that the block visually is on the match."
15282 (catch 'exit
15283 (let ((pos (point))
15284 (eol (point-at-eol (+ 1 (or nlines 0))))
15285 (inc (if visually 1 0)))
15286 (save-excursion
15287 (beginning-of-line (- 1 (or nlines 0)))
15288 (while (re-search-forward re eol t)
15289 (if (and (<= (match-beginning 0) pos)
15290 (>= (+ inc (match-end 0)) pos))
15291 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
15293 (defun org-at-regexp-p (regexp)
15294 "Is point inside a match of REGEXP in the current line?"
15295 (catch 'exit
15296 (save-excursion
15297 (let ((pos (point)) (end (point-at-eol)))
15298 (beginning-of-line 1)
15299 (while (re-search-forward regexp end t)
15300 (if (and (<= (match-beginning 0) pos)
15301 (>= (match-end 0) pos))
15302 (throw 'exit t)))
15303 nil))))
15305 (defun org-occur-in-agenda-files (regexp &optional nlines)
15306 "Call `multi-occur' with buffers for all agenda files."
15307 (interactive "sOrg-files matching: \np")
15308 (let* ((files (org-agenda-files))
15309 (tnames (mapcar 'file-truename files))
15310 (extra org-agenda-text-search-extra-files)
15312 (when (eq (car extra) 'agenda-archives)
15313 (setq extra (cdr extra))
15314 (setq files (org-add-archive-files files)))
15315 (while (setq f (pop extra))
15316 (unless (member (file-truename f) tnames)
15317 (add-to-list 'files f 'append)
15318 (add-to-list 'tnames (file-truename f) 'append)))
15319 (multi-occur
15320 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
15321 regexp)))
15323 (if (boundp 'occur-mode-find-occurrence-hook)
15324 ;; Emacs 23
15325 (add-hook 'occur-mode-find-occurrence-hook
15326 (lambda ()
15327 (when (org-mode-p)
15328 (org-reveal))))
15329 ;; Emacs 22
15330 (defadvice occur-mode-goto-occurrence
15331 (after org-occur-reveal activate)
15332 (and (org-mode-p) (org-reveal)))
15333 (defadvice occur-mode-goto-occurrence-other-window
15334 (after org-occur-reveal activate)
15335 (and (org-mode-p) (org-reveal)))
15336 (defadvice occur-mode-display-occurrence
15337 (after org-occur-reveal activate)
15338 (when (org-mode-p)
15339 (let ((pos (occur-mode-find-occurrence)))
15340 (with-current-buffer (marker-buffer pos)
15341 (save-excursion
15342 (goto-char pos)
15343 (org-reveal)))))))
15345 (defun org-uniquify (list)
15346 "Remove duplicate elements from LIST."
15347 (let (res)
15348 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
15349 res))
15351 (defun org-delete-all (elts list)
15352 "Remove all elements in ELTS from LIST."
15353 (while elts
15354 (setq list (delete (pop elts) list)))
15355 list)
15357 (defun org-back-over-empty-lines ()
15358 "Move backwards over whitespace, to the beginning of the first empty line.
15359 Returns the number of empty lines passed."
15360 (let ((pos (point)))
15361 (skip-chars-backward " \t\n\r")
15362 (beginning-of-line 2)
15363 (goto-char (min (point) pos))
15364 (count-lines (point) pos)))
15366 (defun org-skip-whitespace ()
15367 (skip-chars-forward " \t\n\r"))
15369 (defun org-point-in-group (point group &optional context)
15370 "Check if POINT is in match-group GROUP.
15371 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
15372 match. If the match group does ot exist or point is not inside it,
15373 return nil."
15374 (and (match-beginning group)
15375 (>= point (match-beginning group))
15376 (<= point (match-end group))
15377 (if context
15378 (list context (match-beginning group) (match-end group))
15379 t)))
15381 (defun org-switch-to-buffer-other-window (&rest args)
15382 "Switch to buffer in a second window on the current frame.
15383 In particular, do not allow pop-up frames."
15384 (let (pop-up-frames special-display-buffer-names special-display-regexps
15385 special-display-function)
15386 (apply 'switch-to-buffer-other-window args)))
15388 (defun org-combine-plists (&rest plists)
15389 "Create a single property list from all plists in PLISTS.
15390 The process starts by copying the first list, and then setting properties
15391 from the other lists. Settings in the last list are the most significant
15392 ones and overrule settings in the other lists."
15393 (let ((rtn (copy-sequence (pop plists)))
15394 p v ls)
15395 (while plists
15396 (setq ls (pop plists))
15397 (while ls
15398 (setq p (pop ls) v (pop ls))
15399 (setq rtn (plist-put rtn p v))))
15400 rtn))
15402 (defun org-move-line-down (arg)
15403 "Move the current line down. With prefix argument, move it past ARG lines."
15404 (interactive "p")
15405 (let ((col (current-column))
15406 beg end pos)
15407 (beginning-of-line 1) (setq beg (point))
15408 (beginning-of-line 2) (setq end (point))
15409 (beginning-of-line (+ 1 arg))
15410 (setq pos (move-marker (make-marker) (point)))
15411 (insert (delete-and-extract-region beg end))
15412 (goto-char pos)
15413 (org-move-to-column col)))
15415 (defun org-move-line-up (arg)
15416 "Move the current line up. With prefix argument, move it past ARG lines."
15417 (interactive "p")
15418 (let ((col (current-column))
15419 beg end pos)
15420 (beginning-of-line 1) (setq beg (point))
15421 (beginning-of-line 2) (setq end (point))
15422 (beginning-of-line (- arg))
15423 (setq pos (move-marker (make-marker) (point)))
15424 (insert (delete-and-extract-region beg end))
15425 (goto-char pos)
15426 (org-move-to-column col)))
15428 (defun org-replace-escapes (string table)
15429 "Replace %-escapes in STRING with values in TABLE.
15430 TABLE is an association list with keys like \"%a\" and string values.
15431 The sequences in STRING may contain normal field width and padding information,
15432 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
15433 so values can contain further %-escapes if they are define later in TABLE."
15434 (let ((case-fold-search nil)
15435 e re rpl)
15436 (while (setq e (pop table))
15437 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
15438 (while (string-match re string)
15439 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
15440 (cdr e)))
15441 (setq string (replace-match rpl t t string))))
15442 string))
15445 (defun org-sublist (list start end)
15446 "Return a section of LIST, from START to END.
15447 Counting starts at 1."
15448 (let (rtn (c start))
15449 (setq list (nthcdr (1- start) list))
15450 (while (and list (<= c end))
15451 (push (pop list) rtn)
15452 (setq c (1+ c)))
15453 (nreverse rtn)))
15455 (defun org-find-base-buffer-visiting (file)
15456 "Like `find-buffer-visiting' but always return the base buffer and
15457 not an indirect buffer."
15458 (let ((buf (or (get-file-buffer file)
15459 (find-buffer-visiting file))))
15460 (if buf
15461 (or (buffer-base-buffer buf) buf)
15462 nil)))
15464 (defun org-image-file-name-regexp (&optional extensions)
15465 "Return regexp matching the file names of images.
15466 If EXTENSIONS is given, only match these."
15467 (if (and (not extensions) (fboundp 'image-file-name-regexp))
15468 (image-file-name-regexp)
15469 (let ((image-file-name-extensions
15470 (or extensions
15471 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
15472 "xbm" "xpm" "pbm" "pgm" "ppm"))))
15473 (concat "\\."
15474 (regexp-opt (nconc (mapcar 'upcase
15475 image-file-name-extensions)
15476 image-file-name-extensions)
15478 "\\'"))))
15480 (defun org-file-image-p (file &optional extensions)
15481 "Return non-nil if FILE is an image."
15482 (save-match-data
15483 (string-match (org-image-file-name-regexp extensions) file)))
15485 (defun org-get-cursor-date ()
15486 "Return the date at cursor in as a time.
15487 This works in the calendar and in the agenda, anywhere else it just
15488 returns the current time."
15489 (let (date day defd)
15490 (cond
15491 ((eq major-mode 'calendar-mode)
15492 (setq date (calendar-cursor-to-date)
15493 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15494 ((eq major-mode 'org-agenda-mode)
15495 (setq day (get-text-property (point) 'day))
15496 (if day
15497 (setq date (calendar-gregorian-from-absolute day)
15498 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
15499 (nth 2 date))))))
15500 (or defd (current-time))))
15502 (defvar org-agenda-action-marker (make-marker)
15503 "Marker pointing to the entry for the next agenda action.")
15505 (defun org-mark-entry-for-agenda-action ()
15506 "Mark the current entry as target of an agenda action.
15507 Agenda actions are actions executed from the agenda with the key `k',
15508 which make use of the date at the cursor."
15509 (interactive)
15510 (move-marker org-agenda-action-marker
15511 (save-excursion (org-back-to-heading t) (point))
15512 (current-buffer))
15513 (message
15514 "Entry marked for action; press `k' at desired date in agenda or calendar"))
15516 ;;; Paragraph filling stuff.
15517 ;; We want this to be just right, so use the full arsenal.
15519 (defun org-indent-line-function ()
15520 "Indent line like previous, but further if previous was headline or item."
15521 (interactive)
15522 (let* ((pos (point))
15523 (itemp (org-at-item-p))
15524 (org-drawer-regexp (or org-drawer-regexp "\000"))
15525 column bpos bcol tpos tcol bullet btype bullet-type)
15526 ;; Find the previous relevant line
15527 (beginning-of-line 1)
15528 (cond
15529 ((looking-at "#") (setq column 0))
15530 ((looking-at "\\*+ ") (setq column 0))
15531 ((and (looking-at "[ \t]*:END:")
15532 (save-excursion (re-search-backward org-drawer-regexp nil t)))
15533 (save-excursion
15534 (goto-char (1- (match-beginning 1)))
15535 (setq column (current-column))))
15537 (beginning-of-line 0)
15538 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]")
15539 (not (looking-at "[ \t]*:END:"))
15540 (not (looking-at org-drawer-regexp)))
15541 (beginning-of-line 0))
15542 (cond
15543 ((looking-at "\\*+[ \t]+")
15544 (if (not org-adapt-indentation)
15545 (setq column 0)
15546 (goto-char (match-end 0))
15547 (setq column (current-column))))
15548 ((looking-at org-drawer-regexp)
15549 (goto-char (1- (match-beginning 1)))
15550 (setq column (current-column)))
15551 ((looking-at "\\([ \t]*\\):END:")
15552 (goto-char (match-end 1))
15553 (setq column (current-column)))
15554 ((org-in-item-p)
15555 (org-beginning-of-item)
15556 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
15557 (setq bpos (match-beginning 1) tpos (match-end 0)
15558 bcol (progn (goto-char bpos) (current-column))
15559 tcol (progn (goto-char tpos) (current-column))
15560 bullet (match-string 1)
15561 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
15562 (if (> tcol (+ bcol org-description-max-indent))
15563 (setq tcol (+ bcol 5)))
15564 (if (not itemp)
15565 (setq column tcol)
15566 (goto-char pos)
15567 (beginning-of-line 1)
15568 (if (looking-at "\\S-")
15569 (progn
15570 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
15571 (setq bullet (match-string 1)
15572 btype (if (string-match "[0-9]" bullet) "n" bullet))
15573 (setq column (if (equal btype bullet-type) bcol tcol)))
15574 (setq column (org-get-indentation)))))
15575 (t (setq column (org-get-indentation))))))
15576 (goto-char pos)
15577 (if (<= (current-column) (current-indentation))
15578 (org-indent-line-to column)
15579 (save-excursion (org-indent-line-to column)))
15580 (setq column (current-column))
15581 (beginning-of-line 1)
15582 (if (looking-at
15583 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
15584 (replace-match (concat "\\1" (format org-property-format
15585 (match-string 2) (match-string 3)))
15586 t nil))
15587 (org-move-to-column column)))
15589 (defun org-set-autofill-regexps ()
15590 (interactive)
15591 ;; In the paragraph separator we include headlines, because filling
15592 ;; text in a line directly attached to a headline would otherwise
15593 ;; fill the headline as well.
15594 (org-set-local 'comment-start-skip "^#+[ \t]*")
15595 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
15596 ;; The paragraph starter includes hand-formatted lists.
15597 (org-set-local 'paragraph-start
15598 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
15599 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
15600 ;; But only if the user has not turned off tables or fixed-width regions
15601 (org-set-local
15602 'auto-fill-inhibit-regexp
15603 (concat "\\*+ \\|#\\+"
15604 "\\|[ \t]*" org-keyword-time-regexp
15605 (if (or org-enable-table-editor org-enable-fixed-width-editor)
15606 (concat
15607 "\\|[ \t]*["
15608 (if org-enable-table-editor "|" "")
15609 (if org-enable-fixed-width-editor ":" "")
15610 "]"))))
15611 ;; We use our own fill-paragraph function, to make sure that tables
15612 ;; and fixed-width regions are not wrapped. That function will pass
15613 ;; through to `fill-paragraph' when appropriate.
15614 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
15615 ; Adaptive filling: To get full control, first make sure that
15616 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
15617 (org-set-local 'adaptive-fill-regexp "\000")
15618 (org-set-local 'adaptive-fill-function
15619 'org-adaptive-fill-function)
15620 (org-set-local
15621 'align-mode-rules-list
15622 '((org-in-buffer-settings
15623 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
15624 (modes . '(org-mode))))))
15626 (defun org-fill-paragraph (&optional justify)
15627 "Re-align a table, pass through to fill-paragraph if no table."
15628 (let ((table-p (org-at-table-p))
15629 (table.el-p (org-at-table.el-p)))
15630 (cond ((and (equal (char-after (point-at-bol)) ?*)
15631 (save-excursion (goto-char (point-at-bol))
15632 (looking-at outline-regexp)))
15633 t) ; skip headlines
15634 (table.el-p t) ; skip table.el tables
15635 (table-p (org-table-align) t) ; align org-mode tables
15636 (t nil)))) ; call paragraph-fill
15638 ;; For reference, this is the default value of adaptive-fill-regexp
15639 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
15641 (defun org-adaptive-fill-function ()
15642 "Return a fill prefix for org-mode files.
15643 In particular, this makes sure hanging paragraphs for hand-formatted lists
15644 work correctly."
15645 (cond ((looking-at "#[ \t]+")
15646 (match-string 0))
15647 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
15648 (save-excursion
15649 (if (> (match-end 1) (+ (match-beginning 1)
15650 org-description-max-indent))
15651 (goto-char (+ (match-beginning 1) 5))
15652 (goto-char (match-end 0)))
15653 (make-string (current-column) ?\ )))
15654 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
15655 (save-excursion
15656 (goto-char (match-end 0))
15657 (make-string (current-column) ?\ )))
15658 (t nil)))
15660 ;;; Other stuff.
15662 (defun org-toggle-fixed-width-section (arg)
15663 "Toggle the fixed-width export.
15664 If there is no active region, the QUOTE keyword at the current headline is
15665 inserted or removed. When present, it causes the text between this headline
15666 and the next to be exported as fixed-width text, and unmodified.
15667 If there is an active region, this command adds or removes a colon as the
15668 first character of this line. If the first character of a line is a colon,
15669 this line is also exported in fixed-width font."
15670 (interactive "P")
15671 (let* ((cc 0)
15672 (regionp (org-region-active-p))
15673 (beg (if regionp (region-beginning) (point)))
15674 (end (if regionp (region-end)))
15675 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
15676 (case-fold-search nil)
15677 (re "[ \t]*\\(: \\)")
15678 off)
15679 (if regionp
15680 (save-excursion
15681 (goto-char beg)
15682 (setq cc (current-column))
15683 (beginning-of-line 1)
15684 (setq off (looking-at re))
15685 (while (> nlines 0)
15686 (setq nlines (1- nlines))
15687 (beginning-of-line 1)
15688 (cond
15689 (arg
15690 (org-move-to-column cc t)
15691 (insert ": \n")
15692 (forward-line -1))
15693 ((and off (looking-at re))
15694 (replace-match "" t t nil 1))
15695 ((not off) (org-move-to-column cc t) (insert ": ")))
15696 (forward-line 1)))
15697 (save-excursion
15698 (org-back-to-heading)
15699 (if (looking-at (concat outline-regexp
15700 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
15701 (replace-match "" t t nil 1)
15702 (if (looking-at outline-regexp)
15703 (progn
15704 (goto-char (match-end 0))
15705 (insert org-quote-string " "))))))))
15707 (defun org-reftex-citation ()
15708 "Use reftex-citation to insert a citation into the buffer.
15709 This looks for a line like
15711 #+BIBLIOGRAPHY: foo plain option:-d
15713 and derives from it that foo.bib is the bbliography file relevant
15714 for this document. It then installs the necessary environment for RefTeX
15715 to work in this buffer and calls `reftex-citation' to insert a citation
15716 into the buffer.
15718 Export of such citations to both LaTeX and HTML is handled by the contributed
15719 package org-exp-bibtex by Taru Karttunen."
15720 (interactive)
15721 (let ((reftex-docstruct-symbol 'rds)
15722 (reftex-cite-format "\\cite{%l}")
15723 rds bib)
15724 (save-excursion
15725 (save-restriction
15726 (widen)
15727 (let ((case-fold-search t)
15728 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
15729 (if (not (save-excursion
15730 (or (re-search-forward re nil t)
15731 (re-search-backward re nil t))))
15732 (error "No bibliography defined in file")
15733 (setq bib (concat (match-string 1) ".bib")
15734 rds (list (list 'bib bib)))))))
15735 (call-interactively 'reftex-citation)))
15737 ;;;; Functions extending outline functionality
15739 (defun org-beginning-of-line (&optional arg)
15740 "Go to the beginning of the current line. If that is invisible, continue
15741 to a visible line beginning. This makes the function of C-a more intuitive.
15742 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
15743 first attempt, and only move to after the tags when the cursor is already
15744 beyond the end of the headline."
15745 (interactive "P")
15746 (let ((pos (point))
15747 (special (if (consp org-special-ctrl-a/e)
15748 (car org-special-ctrl-a/e)
15749 org-special-ctrl-a/e))
15750 refpos)
15751 (beginning-of-line 1)
15752 (if (and arg (fboundp 'move-beginning-of-line))
15753 (call-interactively 'move-beginning-of-line)
15754 (if (bobp)
15756 (backward-char 1)
15757 (if (org-invisible-p)
15758 (while (and (not (bobp)) (org-invisible-p))
15759 (backward-char 1)
15760 (beginning-of-line 1))
15761 (forward-char 1))))
15762 (when special
15763 (cond
15764 ((and (looking-at org-complex-heading-regexp)
15765 (= (char-after (match-end 1)) ?\ ))
15766 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
15767 (point-at-eol)))
15768 (goto-char
15769 (if (eq special t)
15770 (cond ((> pos refpos) refpos)
15771 ((= pos (point)) refpos)
15772 (t (point)))
15773 (cond ((> pos (point)) (point))
15774 ((not (eq last-command this-command)) (point))
15775 (t refpos)))))
15776 ((org-at-item-p)
15777 (goto-char
15778 (if (eq special t)
15779 (cond ((> pos (match-end 4)) (match-end 4))
15780 ((= pos (point)) (match-end 4))
15781 (t (point)))
15782 (cond ((> pos (point)) (point))
15783 ((not (eq last-command this-command)) (point))
15784 (t (match-end 4))))))))
15785 (org-no-warnings
15786 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
15788 (defun org-end-of-line (&optional arg)
15789 "Go to the end of the line.
15790 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
15791 first attempt, and only move to after the tags when the cursor is already
15792 beyond the end of the headline."
15793 (interactive "P")
15794 (let ((special (if (consp org-special-ctrl-a/e)
15795 (cdr org-special-ctrl-a/e)
15796 org-special-ctrl-a/e)))
15797 (if (or (not special)
15798 (not (org-on-heading-p))
15799 arg)
15800 (call-interactively (if (fboundp 'move-end-of-line)
15801 'move-end-of-line
15802 'end-of-line))
15803 (let ((pos (point)))
15804 (beginning-of-line 1)
15805 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
15806 (if (eq special t)
15807 (if (or (< pos (match-beginning 1))
15808 (= pos (match-end 0)))
15809 (goto-char (match-beginning 1))
15810 (goto-char (match-end 0)))
15811 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
15812 (goto-char (match-end 0))
15813 (goto-char (match-beginning 1))))
15814 (call-interactively (if (fboundp 'move-end-of-line)
15815 'move-end-of-line
15816 'end-of-line)))))
15817 (org-no-warnings
15818 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
15820 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
15821 (define-key org-mode-map "\C-e" 'org-end-of-line)
15823 (defun org-backward-sentence (&optional arg)
15824 "Go to beginning of sentence, or beginning of table field.
15825 This will call `backward-sentence' or `org-table-beginning-of-field',
15826 depending on context."
15827 (interactive "P")
15828 (cond
15829 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
15830 (t (call-interactively 'backward-sentence))))
15832 (defun org-forward-sentence (&optional arg)
15833 "Go to end of sentence, or end of table field.
15834 This will call `forward-sentence' or `org-table-end-of-field',
15835 depending on context."
15836 (interactive "P")
15837 (cond
15838 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
15839 (t (call-interactively 'forward-sentence))))
15841 (define-key org-mode-map "\M-a" 'org-backward-sentence)
15842 (define-key org-mode-map "\M-e" 'org-forward-sentence)
15844 (defun org-kill-line (&optional arg)
15845 "Kill line, to tags or end of line."
15846 (interactive "P")
15847 (cond
15848 ((or (not org-special-ctrl-k)
15849 (bolp)
15850 (not (org-on-heading-p)))
15851 (call-interactively 'kill-line))
15852 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
15853 (kill-region (point) (match-beginning 1))
15854 (org-set-tags nil t))
15855 (t (kill-region (point) (point-at-eol)))))
15857 (define-key org-mode-map "\C-k" 'org-kill-line)
15859 (defun org-yank (&optional arg)
15860 "Yank. If the kill is a subtree, treat it specially.
15861 This command will look at the current kill and check if is a single
15862 subtree, or a series of subtrees[1]. If it passes the test, and if the
15863 cursor is at the beginning of a line or after the stars of a currently
15864 empty headline, then the yank is handled specially. How exactly depends
15865 on the value of the following variables, both set by default.
15867 org-yank-folded-subtrees
15868 When set, the subtree(s) will be folded after insertion, but only
15869 if doing so would now swallow text after the yanked text.
15871 org-yank-adjusted-subtrees
15872 When set, the subtree will be promoted or demoted in order to
15873 fit into the local outline tree structure, which means that the level
15874 will be adjusted so that it becomes the smaller one of the two
15875 *visible* surrounding headings.
15877 Any prefix to this command will cause `yank' to be called directly with
15878 no special treatment. In particular, a simple `C-u' prefix will just
15879 plainly yank the text as it is.
15881 \[1] Basically, the test checks if the first non-white line is a heading
15882 and if there are no other headings with fewer stars."
15883 (interactive "P")
15884 (setq this-command 'yank)
15885 (if arg
15886 (call-interactively 'yank)
15887 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
15888 (and (org-kill-is-subtree-p)
15889 (or (bolp)
15890 (and (looking-at "[ \t]*$")
15891 (string-match
15892 "\\`\\*+\\'"
15893 (buffer-substring (point-at-bol) (point)))))))
15894 swallowp)
15895 (cond
15896 ((and subtreep org-yank-folded-subtrees)
15897 (let ((beg (point))
15898 end)
15899 (if (and subtreep org-yank-adjusted-subtrees)
15900 (org-paste-subtree nil nil 'for-yank)
15901 (call-interactively 'yank))
15902 (setq end (point))
15903 (goto-char beg)
15904 (when (and (bolp) subtreep
15905 (not (setq swallowp
15906 (org-yank-folding-would-swallow-text beg end))))
15907 (or (looking-at outline-regexp)
15908 (re-search-forward (concat "^" outline-regexp) end t))
15909 (while (and (< (point) end) (looking-at outline-regexp))
15910 (hide-subtree)
15911 (org-cycle-show-empty-lines 'folded)
15912 (condition-case nil
15913 (outline-forward-same-level 1)
15914 (error (goto-char end)))))
15915 (when swallowp
15916 (message
15917 "Yanked text not folded because that would swallow text"))
15918 (goto-char end)
15919 (skip-chars-forward " \t\n\r")
15920 (beginning-of-line 1)
15921 (push-mark beg 'nomsg)))
15922 ((and subtreep org-yank-adjusted-subtrees)
15923 (let ((beg (point-at-bol)))
15924 (org-paste-subtree nil nil 'for-yank)
15925 (push-mark beg 'nomsg)))
15927 (call-interactively 'yank))))))
15929 (defun org-yank-folding-would-swallow-text (beg end)
15930 "Would hide-subtree at BEG swallow any text after END?"
15931 (let (level)
15932 (save-excursion
15933 (goto-char beg)
15934 (when (or (looking-at outline-regexp)
15935 (re-search-forward (concat "^" outline-regexp) end t))
15936 (setq level (org-outline-level)))
15937 (goto-char end)
15938 (skip-chars-forward " \t\r\n\v\f")
15939 (if (or (eobp)
15940 (and (bolp) (looking-at org-outline-regexp)
15941 (<= (org-outline-level) level)))
15942 nil ; Nothing would be swallowed
15943 t)))) ; something would swallow
15945 (define-key org-mode-map "\C-y" 'org-yank)
15947 (defun org-invisible-p ()
15948 "Check if point is at a character currently not visible."
15949 ;; Early versions of noutline don't have `outline-invisible-p'.
15950 (if (fboundp 'outline-invisible-p)
15951 (outline-invisible-p)
15952 (get-char-property (point) 'invisible)))
15954 (defun org-invisible-p2 ()
15955 "Check if point is at a character currently not visible."
15956 (save-excursion
15957 (if (and (eolp) (not (bobp))) (backward-char 1))
15958 ;; Early versions of noutline don't have `outline-invisible-p'.
15959 (if (fboundp 'outline-invisible-p)
15960 (outline-invisible-p)
15961 (get-char-property (point) 'invisible))))
15963 (defun org-back-to-heading (&optional invisible-ok)
15964 "Call `outline-back-to-heading', but provide a better error message."
15965 (condition-case nil
15966 (outline-back-to-heading invisible-ok)
15967 (error (error "Before first headline at position %d in buffer %s"
15968 (point) (current-buffer)))))
15970 (defun org-before-first-heading-p ()
15971 "Before first heading?"
15972 (save-excursion
15973 (null (re-search-backward "^\\*+ " nil t))))
15975 (defalias 'org-on-heading-p 'outline-on-heading-p)
15976 (defalias 'org-at-heading-p 'outline-on-heading-p)
15977 (defun org-at-heading-or-item-p ()
15978 (or (org-on-heading-p) (org-at-item-p)))
15980 (defun org-on-target-p ()
15981 (or (org-in-regexp org-radio-target-regexp)
15982 (org-in-regexp org-target-regexp)))
15984 (defun org-up-heading-all (arg)
15985 "Move to the heading line of which the present line is a subheading.
15986 This function considers both visible and invisible heading lines.
15987 With argument, move up ARG levels."
15988 (if (fboundp 'outline-up-heading-all)
15989 (outline-up-heading-all arg) ; emacs 21 version of outline.el
15990 (outline-up-heading arg t))) ; emacs 22 version of outline.el
15992 (defun org-up-heading-safe ()
15993 "Move to the heading line of which the present line is a subheading.
15994 This version will not throw an error. It will return the level of the
15995 headline found, or nil if no higher level is found.
15997 Also, this function will be a lot faster than `outline-up-heading',
15998 because it relies on stars being the outline starters. This can really
15999 make a significant difference in outlines with very many siblings."
16000 (let (start-level re)
16001 (org-back-to-heading t)
16002 (setq start-level (funcall outline-level))
16003 (if (equal start-level 1)
16005 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
16006 (if (re-search-backward re nil t)
16007 (funcall outline-level)))))
16009 (defun org-first-sibling-p ()
16010 "Is this heading the first child of its parents?"
16011 (interactive)
16012 (let ((re (concat "^" outline-regexp))
16013 level l)
16014 (unless (org-at-heading-p t)
16015 (error "Not at a heading"))
16016 (setq level (funcall outline-level))
16017 (save-excursion
16018 (if (not (re-search-backward re nil t))
16020 (setq l (funcall outline-level))
16021 (< l level)))))
16023 (defun org-goto-sibling (&optional previous)
16024 "Goto the next sibling, even if it is invisible.
16025 When PREVIOUS is set, go to the previous sibling instead. Returns t
16026 when a sibling was found. When none is found, return nil and don't
16027 move point."
16028 (let ((fun (if previous 're-search-backward 're-search-forward))
16029 (pos (point))
16030 (re (concat "^" outline-regexp))
16031 level l)
16032 (when (condition-case nil (org-back-to-heading t) (error nil))
16033 (setq level (funcall outline-level))
16034 (catch 'exit
16035 (or previous (forward-char 1))
16036 (while (funcall fun re nil t)
16037 (setq l (funcall outline-level))
16038 (when (< l level) (goto-char pos) (throw 'exit nil))
16039 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
16040 (goto-char pos)
16041 nil))))
16043 (defun org-show-siblings ()
16044 "Show all siblings of the current headline."
16045 (save-excursion
16046 (while (org-goto-sibling) (org-flag-heading nil)))
16047 (save-excursion
16048 (while (org-goto-sibling 'previous)
16049 (org-flag-heading nil))))
16051 (defun org-show-hidden-entry ()
16052 "Show an entry where even the heading is hidden."
16053 (save-excursion
16054 (org-show-entry)))
16056 (defun org-flag-heading (flag &optional entry)
16057 "Flag the current heading. FLAG non-nil means make invisible.
16058 When ENTRY is non-nil, show the entire entry."
16059 (save-excursion
16060 (org-back-to-heading t)
16061 ;; Check if we should show the entire entry
16062 (if entry
16063 (progn
16064 (org-show-entry)
16065 (save-excursion
16066 (and (outline-next-heading)
16067 (org-flag-heading nil))))
16068 (outline-flag-region (max (point-min) (1- (point)))
16069 (save-excursion (outline-end-of-heading) (point))
16070 flag))))
16072 (defun org-forward-same-level (arg)
16073 "Move forward to the ARG'th subheading at same level as this one.
16074 Stop at the first and last subheadings of a superior heading.
16075 This is like outline-forward-same-level, but invisible headings are ok."
16076 (interactive "p")
16077 (org-back-to-heading t)
16078 (while (> arg 0)
16079 (let ((point-to-move-to (save-excursion
16080 (org-get-next-sibling))))
16081 (if point-to-move-to
16082 (progn
16083 (goto-char point-to-move-to)
16084 (setq arg (1- arg)))
16085 (progn
16086 (setq arg 0)
16087 (error "No following same-level heading"))))))
16089 (defun org-get-next-sibling ()
16090 "Move to next heading of the same level, and return point.
16091 If there is no such heading, return nil.
16092 This is like outline-next-sibling, but invisible headings are ok."
16093 (let ((level (funcall outline-level)))
16094 (outline-next-heading)
16095 (while (and (not (eobp)) (> (funcall outline-level) level))
16096 (outline-next-heading))
16097 (if (or (eobp) (< (funcall outline-level) level))
16099 (point))))
16101 (defun org-end-of-subtree (&optional invisible-OK to-heading)
16102 ;; This is an exact copy of the original function, but it uses
16103 ;; `org-back-to-heading', to make it work also in invisible
16104 ;; trees. And is uses an invisible-OK argument.
16105 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
16106 (org-back-to-heading invisible-OK)
16107 (let ((first t)
16108 (level (funcall outline-level)))
16109 (while (and (not (eobp))
16110 (or first (> (funcall outline-level) level)))
16111 (setq first nil)
16112 (outline-next-heading))
16113 (unless to-heading
16114 (if (memq (preceding-char) '(?\n ?\^M))
16115 (progn
16116 ;; Go to end of line before heading
16117 (forward-char -1)
16118 (if (memq (preceding-char) '(?\n ?\^M))
16119 ;; leave blank line before heading
16120 (forward-char -1))))))
16121 (point))
16123 (defun org-end-of-subtree (&optional invisible-OK to-heading)
16124 ;; This contains an exact copy of the original function, but it uses
16125 ;; `org-back-to-heading', to make it work also in invisible
16126 ;; trees. And is uses an invisible-OK argument.
16127 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
16128 ;; Furthermore, when used inside Org, finding the end of a large subtree
16129 ;; with many children and grandchildren etc, this can be much faster
16130 ;; than the outline version.
16131 (org-back-to-heading invisible-OK)
16132 (let ((first t)
16133 (level (funcall outline-level)))
16134 (if (and (org-mode-p) (< level 1000))
16135 ;; A true heading (not a plain list item), in Org-mode
16136 ;; This means we can easily find the end by looking
16137 ;; only for the right number of stars. Using a regexp to do
16138 ;; this is so much faster than using a Lisp loop.
16139 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
16140 (forward-char 1)
16141 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
16142 ;; something else, do it the slow way
16143 (while (and (not (eobp))
16144 (or first (> (funcall outline-level) level)))
16145 (setq first nil)
16146 (outline-next-heading)))
16147 (unless to-heading
16148 (if (memq (preceding-char) '(?\n ?\^M))
16149 (progn
16150 ;; Go to end of line before heading
16151 (forward-char -1)
16152 (if (memq (preceding-char) '(?\n ?\^M))
16153 ;; leave blank line before heading
16154 (forward-char -1))))))
16155 (point))
16157 (defun org-show-subtree ()
16158 "Show everything after this heading at deeper levels."
16159 (outline-flag-region
16160 (point)
16161 (save-excursion
16162 (outline-end-of-subtree) (outline-next-heading) (point))
16163 nil))
16165 (defun org-show-entry ()
16166 "Show the body directly following this heading.
16167 Show the heading too, if it is currently invisible."
16168 (interactive)
16169 (save-excursion
16170 (condition-case nil
16171 (progn
16172 (org-back-to-heading t)
16173 (outline-flag-region
16174 (max (point-min) (1- (point)))
16175 (save-excursion
16176 (if (re-search-forward
16177 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
16178 (match-beginning 1)
16179 (point-max)))
16180 nil))
16181 (error nil))))
16183 (defun org-make-options-regexp (kwds &optional extra)
16184 "Make a regular expression for keyword lines."
16185 (concat
16187 "#?[ \t]*\\+\\("
16188 (mapconcat 'regexp-quote kwds "\\|")
16189 (if extra (concat "\\|" extra))
16190 "\\):[ \t]*"
16191 "\\(.+\\)"))
16193 ;; Make isearch reveal the necessary context
16194 (defun org-isearch-end ()
16195 "Reveal context after isearch exits."
16196 (when isearch-success ; only if search was successful
16197 (if (featurep 'xemacs)
16198 ;; Under XEmacs, the hook is run in the correct place,
16199 ;; we directly show the context.
16200 (org-show-context 'isearch)
16201 ;; In Emacs the hook runs *before* restoring the overlays.
16202 ;; So we have to use a one-time post-command-hook to do this.
16203 ;; (Emacs 22 has a special variable, see function `org-mode')
16204 (unless (and (boundp 'isearch-mode-end-hook-quit)
16205 isearch-mode-end-hook-quit)
16206 ;; Only when the isearch was not quitted.
16207 (org-add-hook 'post-command-hook 'org-isearch-post-command
16208 'append 'local)))))
16210 (defun org-isearch-post-command ()
16211 "Remove self from hook, and show context."
16212 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
16213 (org-show-context 'isearch))
16216 ;;;; Integration with and fixes for other packages
16218 ;;; Imenu support
16220 (defvar org-imenu-markers nil
16221 "All markers currently used by Imenu.")
16222 (make-variable-buffer-local 'org-imenu-markers)
16224 (defun org-imenu-new-marker (&optional pos)
16225 "Return a new marker for use by Imenu, and remember the marker."
16226 (let ((m (make-marker)))
16227 (move-marker m (or pos (point)))
16228 (push m org-imenu-markers)
16231 (defun org-imenu-get-tree ()
16232 "Produce the index for Imenu."
16233 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
16234 (setq org-imenu-markers nil)
16235 (let* ((n org-imenu-depth)
16236 (re (concat "^" outline-regexp))
16237 (subs (make-vector (1+ n) nil))
16238 (last-level 0)
16239 m level head)
16240 (save-excursion
16241 (save-restriction
16242 (widen)
16243 (goto-char (point-max))
16244 (while (re-search-backward re nil t)
16245 (setq level (org-reduced-level (funcall outline-level)))
16246 (when (<= level n)
16247 (looking-at org-complex-heading-regexp)
16248 (setq head (org-link-display-format
16249 (org-match-string-no-properties 4))
16250 m (org-imenu-new-marker))
16251 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
16252 (if (>= level last-level)
16253 (push (cons head m) (aref subs level))
16254 (push (cons head (aref subs (1+ level))) (aref subs level))
16255 (loop for i from (1+ level) to n do (aset subs i nil)))
16256 (setq last-level level)))))
16257 (aref subs 1)))
16259 (eval-after-load "imenu"
16260 '(progn
16261 (add-hook 'imenu-after-jump-hook
16262 (lambda ()
16263 (if (eq major-mode 'org-mode)
16264 (org-show-context 'org-goto))))))
16266 (defun org-link-display-format (link)
16267 "Replace a link with either the description, or the link target
16268 if no description is present"
16269 (save-match-data
16270 (if (string-match org-bracket-link-analytic-regexp link)
16271 (replace-match (or (match-string 5 link)
16272 (concat (match-string 1 link)
16273 (match-string 3 link)))
16274 nil nil link)
16275 link)))
16277 ;; Speedbar support
16279 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
16280 "Overlay marking the agenda restriction line in speedbar.")
16281 (org-overlay-put org-speedbar-restriction-lock-overlay
16282 'face 'org-agenda-restriction-lock)
16283 (org-overlay-put org-speedbar-restriction-lock-overlay
16284 'help-echo "Agendas are currently limited to this item.")
16285 (org-detach-overlay org-speedbar-restriction-lock-overlay)
16287 (defun org-speedbar-set-agenda-restriction ()
16288 "Restrict future agenda commands to the location at point in speedbar.
16289 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
16290 (interactive)
16291 (require 'org-agenda)
16292 (let (p m tp np dir txt)
16293 (cond
16294 ((setq p (text-property-any (point-at-bol) (point-at-eol)
16295 'org-imenu t))
16296 (setq m (get-text-property p 'org-imenu-marker))
16297 (save-excursion
16298 (save-restriction
16299 (set-buffer (marker-buffer m))
16300 (goto-char m)
16301 (org-agenda-set-restriction-lock 'subtree))))
16302 ((setq p (text-property-any (point-at-bol) (point-at-eol)
16303 'speedbar-function 'speedbar-find-file))
16304 (setq tp (previous-single-property-change
16305 (1+ p) 'speedbar-function)
16306 np (next-single-property-change
16307 tp 'speedbar-function)
16308 dir (speedbar-line-directory)
16309 txt (buffer-substring-no-properties (or tp (point-min))
16310 (or np (point-max))))
16311 (save-excursion
16312 (save-restriction
16313 (set-buffer (find-file-noselect
16314 (let ((default-directory dir))
16315 (expand-file-name txt))))
16316 (unless (org-mode-p)
16317 (error "Cannot restrict to non-Org-mode file"))
16318 (org-agenda-set-restriction-lock 'file))))
16319 (t (error "Don't know how to restrict Org-mode's agenda")))
16320 (org-move-overlay org-speedbar-restriction-lock-overlay
16321 (point-at-bol) (point-at-eol))
16322 (setq current-prefix-arg nil)
16323 (org-agenda-maybe-redo)))
16325 (eval-after-load "speedbar"
16326 '(progn
16327 (speedbar-add-supported-extension ".org")
16328 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
16329 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
16330 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
16331 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
16332 (add-hook 'speedbar-visiting-tag-hook
16333 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
16336 ;;; Fixes and Hacks for problems with other packages
16338 ;; Make flyspell not check words in links, to not mess up our keymap
16339 (defun org-mode-flyspell-verify ()
16340 "Don't let flyspell put overlays at active buttons."
16341 (not (get-text-property (point) 'keymap)))
16343 ;; Make `bookmark-jump' show the jump location if it was hidden.
16344 (eval-after-load "bookmark"
16345 '(if (boundp 'bookmark-after-jump-hook)
16346 ;; We can use the hook
16347 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
16348 ;; Hook not available, use advice
16349 (defadvice bookmark-jump (after org-make-visible activate)
16350 "Make the position visible."
16351 (org-bookmark-jump-unhide))))
16353 ;; Make sure saveplace show the location if it was hidden
16354 (eval-after-load "saveplace"
16355 '(defadvice save-place-find-file-hook (after org-make-visible activate)
16356 "Make the position visible."
16357 (org-bookmark-jump-unhide)))
16359 (defun org-bookmark-jump-unhide ()
16360 "Unhide the current position, to show the bookmark location."
16361 (and (org-mode-p)
16362 (or (org-invisible-p)
16363 (save-excursion (goto-char (max (point-min) (1- (point))))
16364 (org-invisible-p)))
16365 (org-show-context 'bookmark-jump)))
16367 ;; Make session.el ignore our circular variable
16368 (eval-after-load "session"
16369 '(add-to-list 'session-globals-exclude 'org-mark-ring))
16371 ;;;; Experimental code
16373 (defun org-closed-in-range ()
16374 "Sparse tree of items closed in a certain time range.
16375 Still experimental, may disappear in the future."
16376 (interactive)
16377 ;; Get the time interval from the user.
16378 (let* ((time1 (time-to-seconds
16379 (org-read-date nil 'to-time nil "Starting date: ")))
16380 (time2 (time-to-seconds
16381 (org-read-date nil 'to-time nil "End date:")))
16382 ;; callback function
16383 (callback (lambda ()
16384 (let ((time
16385 (time-to-seconds
16386 (apply 'encode-time
16387 (org-parse-time-string
16388 (match-string 1))))))
16389 ;; check if time in interval
16390 (and (>= time time1) (<= time time2))))))
16391 ;; make tree, check each match with the callback
16392 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
16394 ;;;; Finish up
16396 (provide 'org)
16398 (run-hooks 'org-load-hook)
16400 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
16402 ;;; org.el ends here